Solved

How to create solid object in my game.

Posted on 2009-04-12
20
560 Views
Last Modified: 2016-08-29
Hi,
I am new with game development. Currently I am creating simple game (VS 2008 C++ and XML). The game should be simple. The following code actually contain :
1. Background (garden)
2. Tree
3. Boy character, walking around the garden.

The boy can walk around including passig through the Tree.

What I want to do is,
1. to create a new object/sprite called "Fence". And the boy can walk anywhere around the garden, but he should not be allowed to pass through the fence. I assumed that the fence is solid object. At this stage I don't border so much the location of the fence.

2. create another obeject, let say "Tunnel" or "Cave". When the boy go into the tunnel/Cave, then new screen will be displayed, as if new level of the game with new background but with the same character (Boy).

I'd marked the code //================= Help me here ============================, which I think where the changes should be, or state otherwise.

Thanks.
          
using Microsoft.Xna.Framework;

using Microsoft.Xna.Framework.Audio;

using Microsoft.Xna.Framework.Content;

using Microsoft.Xna.Framework.GamerServices;

using Microsoft.Xna.Framework.Graphics;

using Microsoft.Xna.Framework.Input;

using Microsoft.Xna.Framework.Media;

using Microsoft.Xna.Framework.Net;

using Microsoft.Xna.Framework.Storage;

using System.Xml;

using System.Xml.Serialization;

using System.IO;

using System;

using System.Collections.Generic;

using System.Linq;
 

namespace WindowsGame1

{

    public class Game1 : Microsoft.Xna.Framework.Game

    {

        GraphicsDeviceManager graphics;

        SpriteBatch spriteBatch;
 

        //Global Variable Declarations

        Texture2D backgroundTexture;

        Texture2D sprite; 

        Texture2D sprite1;

        Point frameCounter = new Point(0,0);  

        Point frameCounter1 = new Point(0, 0);

        Vector2 position = Vector2.Zero; 

        Vector2 speed = Vector2.Zero; 

        SpriteEffects se =SpriteEffects.FlipHorizontally; 
 

        

        double frameDelay = 0.1; 

        double frameDelay1 = 0.5;

        Level level; //xml level code that will be serialized into this object

        SpriteFont spriteFont;
 

        public Game1()

        {

            graphics = new GraphicsDeviceManager(this);

            Content.RootDirectory = "Content";

        }
 

        protected override void Initialize()

        {

            XmlSerializer s = new XmlSerializer(typeof(Level));

            TextReader r = new StreamReader("Content/Level.xml");
 

            level = (Level)s.Deserialize(r);
 

            r.Close();
 

            

            foreach (Level.character c in level.allCharacters)

            {

                c.sprite = Content.Load<Texture2D>(c.textureAsset);

                c.bound = new BoundingSphere(new Vector3(c.position , 0), 50);

            }
 

            base.Initialize();

        }
 

        protected override void LoadContent()

        {

            // Create a new SpriteBatch, which can be used to draw textures.

            spriteBatch = new SpriteBatch(GraphicsDevice);

            spriteFont = Content.Load<SpriteFont>("Arial");
 

            backgroundTexture = Content.Load<Texture2D>("Background");

            sprite = Content.Load<Texture2D>("Boy");

            sprite1 = Content.Load<Texture2D>("Tree");
 
 

	    //================= Help me here ============================

	    //

            //create new sprite here called Fence or wall

            //png file will be added into the content called Fence.png
 
 
 

        }
 

        protected override void UnloadContent()

        {

        }
 

        protected override void Update(GameTime gameTime)

        {
 

            KeyboardState kb = new KeyboardState();

            kb = Keyboard.GetState();   

            speed = Vector2.Zero;       

            bool moving = false;         
 

            if (kb.IsKeyDown(Keys.Right))

            {

                

                speed.X = 2;

                moving = true;

                

                se = SpriteEffects.FlipHorizontally;

                frameCounter.Y = 0;

            }

            if (kb.IsKeyDown(Keys.Up))

            {

                speed.Y = -2;

                moving = true;

                frameCounter.Y = sprite.Height * 2 / 3;

            }

            if (kb.IsKeyDown(Keys.Left))

            {

                speed.X = -2;

                moving = true;

                

                se = SpriteEffects.None;

                frameCounter.Y = 0;

            }

            if (kb.IsKeyDown(Keys.Down))

            {

                speed.Y = 2;

                moving = true;

                frameCounter.Y = sprite.Height / 3;

            }

            

            position += speed;
 

            if (moving)  

            {

                

                frameDelay -= gameTime.ElapsedGameTime.TotalSeconds;

                if (frameDelay < 0)

                {

                    

                    frameDelay = 0.1;

                    frameCounter.X += sprite.Width / 8; 

                    if (frameCounter.X >= sprite.Width) frameCounter.X = 0; 

                }

            }

            frameDelay1 -= gameTime.ElapsedGameTime.TotalSeconds;

            if (frameDelay1 < 0)

            {

                

                frameDelay1 = 0.5;

                frameCounter1.X += sprite1.Width / 5; 

                if (frameCounter1.X >= sprite1.Width) frameCounter1.X = 0; 

            }

            base.Update(gameTime);

        }
 

        protected override void Draw(GameTime gameTime)

        {

            GraphicsDevice.Clear(Color.Green);

            spriteBatch.Begin();
 

            //Draw Background (Background with trees, rock, garden etc...)

            spriteBatch.Draw(backgroundTexture, new Rectangle(0,0,Window.ClientBounds.Width, Window.ClientBounds.Height), null, Color.White, 0, Vector2.Zero, SpriteEffects.None, 0);

            

            //Draw Sprite1 (Tree)

            spriteBatch.Draw(sprite1, new Vector2(300, 500), new Rectangle(frameCounter1.X, frameCounter1.Y, sprite1.Width / 6, sprite1.Height), Color.White, 0, Vector2.Zero, 1, SpriteEffects.None, 0);

            

            //Draw Sprite (Boy character)

            spriteBatch.Draw(sprite, position, new Rectangle(frameCounter.X, frameCounter.Y, sprite.Width/8, sprite.Height/3), Color.White,0,Vector2.Zero,1,se,0);
 

	    
 

	    //================= Help me here ============================

	    //

            //Draw new sprite (Fence)

            //The boy cannot past through the fence
 
 

            //create a bounding sphere at the players current position

            BoundingSphere playerSphere = new BoundingSphere(new Vector3(position,0),1);

            

            //In this loop we draw each Male/Female character...

            foreach (Level.character c in level.allCharacters)

            {

                spriteBatch.Draw(c.sprite, c.position, new Rectangle(0, 0, c.sprite.Height, c.sprite.Height), Color.White, 0, Vector2.Zero,c.scale, SpriteEffects.None, 0);

                

                if (c.bound.Intersects(playerSphere))

                {

                    

                    spriteBatch.DrawString(spriteFont, c.greeting, (c.position + new Vector2(10, -10)), Color.White);

                }
 

            }

            spriteBatch.End();

            base.Draw(gameTime);

        }

    }

}

Open in new window

game-code-for-help.txt
0
Comment
Question by:KG1973
  • 11
  • 8
20 Comments
 
LVL 4

Expert Comment

by:Xcone
Comment Utility
Are you sure it's C++ with XML?. It looks like C# with XNA.

You're trying to test for movement in your draw method. This should actually be part of the Update method. To prevent movement, you should calculate the movement (which you do) and then test if that movement is allowed by the World you're in (which you don't). In your code  you simply execute: "position += speed" with no testing at all.

If your fence is square (the edges of the screen) testing is really simple, something like:
position += speed;
if (position.X > 1000)
  position.X = 1000;
if (position.X < 0)
  position.X = 0;
// Simular for Y

If you also have diagonal fences, or other complicated shapes, you really should advance to somesort of collision detection. Try these sites to find a good tutorial on the matter:
http://www.ziggyware.com
http://creators.xna.com

This link points to a simple tutorial that looks like you can use it:
http://www.ziggyware.com/readarticle.php?article_id=126

As for drawing of the fence, it looks like you can copy/paste it from Tree and Boy??
0
 
LVL 1

Author Comment

by:KG1973
Comment Utility
Xcone,
Yes you are right. It's C# not c++. Sorry for this.

I would do an object for the fence (rectangular shape, just for a simple test). But I don't know how to create do collision detection with simple object.
0
 
LVL 1

Author Comment

by:KG1973
Comment Utility
Xcone,
I had added the code as follow :
                position += speed;

                if (position.X > 100)
                    position.X = 100;
                if (position.X < 0)
                    position.X = 0;

                // Simular for Y
                if (position.X > 100)
                    position.X = 100;
                if (position.X < 0)
                    position.X = 0;

But the Boy character still able to walk entire screen.

Can you helpme on this ?
0
 
LVL 1

Author Comment

by:KG1973
Comment Utility
sorry, actually the code like ths :
   
             if (position.X > 100)
                    position.X = 100;
                if (position.X < 0)
                    position.X = 0;

                // Simular for Y
                if (position.Y > 100)
                    position.Y = 100;
                if (position.Y < 0)
                    position.Y = 0;

but still does not working.
0
 
LVL 4

Expert Comment

by:Xcone
Comment Utility
Could you please send me your project, so I'll be able to compile and run it here. I can help you better if I can see what happens.
0
 
LVL 1

Author Comment

by:KG1973
Comment Utility
what is your email address?
0
 
LVL 4

Expert Comment

by:Xcone
Comment Utility
I'm not sure if posting personal information (like an e-mail address) is allowed by Expert Exchange rules. I've asked the community support about this. Can't you attach the file as part of a comment, or maybe provide it as external link?
0
 
LVL 1

Author Comment

by:KG1973
Comment Utility
ok, I will try to attach my project file here (zip file).
But failed due to the file type .sln .

The extension of one or more files in the archive is not in the list of allowed extensions: XML Demo/WindowsGame1.sln

Strange, it says that it can accept zip file.
So I cannot post i here. I can rezip all files again but without 1 file (.sln) Will that ok for you, coz probably you may create new project and then copy & paste all my files.
But I will only post it if you agreed.

Thanks.
0
 
LVL 4

Expert Comment

by:Xcone
Comment Utility
I agree to that. I think it will be fine without the .sln file.
0
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 
LVL 1

Author Comment

by:KG1973
Comment Utility
Xcone,
It is not just shl file but there are some files still not allowed (.xna, .xml, .shl, .exe, .pbd, .spritefont , contentproj, .cache, .db).... i dont know how else..

modus operandi,

>>One thing you can do, if the file(s) get blocked by EE, is upload them to a related site,
>>www.ee-stuff.com, which allows darn near any file type, and then post a link to the uploaded file.

Can you helpme on this. I couldn't find anything at the site that you gave to upload my project files.


0
 
LVL 4

Expert Comment

by:Xcone
Comment Utility
At www.ee-stuff.com, login with the same username and password that you use on this page. If succesful, a new tab 'Expert Area' will appear, click it. There's a list of 5 items on that page. The 4th is 'File Upload/Storage' and contains a subitem with a link to upload files. Follow that link, then follow the instructions on the screen.
0
 
LVL 1

Author Comment

by:KG1973
Comment Utility
Xcone,
Finally I uploaded the flle.

Your file has successfully been uploaded!
To download the file, you must be logged into EE-Stuff. Here are two pages that will display your file,

View all files for Question ID: 24316113
https://filedb.experts-exchange.com/incoming/ee-stuff/7604-WindowsGame1.zip

Direct link to your file
https://filedb.experts-exchange.com/incoming/ee-stuff/7604-WindowsGame1.zip
0
 
LVL 1

Author Comment

by:KG1973
Comment Utility
Xcone,

In the program, Ive 2 sprites. Boy and other the Barn.
If the boy walk thru the Barn, it wll collide and display a message.
What I want is, asssuming the Barn is a fence, the Boy should not e able to walk through the Barn/fence.

Similarly if he walk through the end of the windows.

Simple logic that I want to implement, when we press , let say "Right" key, the moment it collide, thefunction key "Right" will be disabled until other key pressed. This would prevent us to press Right key, stop moving the boy further right direction.

I need the solution urgently.
Thanks a million.
0
 
LVL 4

Accepted Solution

by:
Xcone earned 500 total points
Comment Utility
Hi, I've worked it out for you. Replace you Update Method for the in the attached code, and eveything should work fine. Exept for some minor tweaking on your part.

The collision detection was working nicely the way you had it in the Draw Method, so I used the same way to detect them. In the MoveBoy function there's also Collision HANDLING.

Don't be suprised if the result is not completely to your desire. The topleft position of the sprites are drawn on the centerposition of your levelentities. Therefor it looks like it is wrong, but it actually isn't. But this is something you have to correct yourself.
protected override void Update(GameTime gameTime)

        {
 

            KeyboardState kb = new KeyboardState();

            kb = Keyboard.GetState();   //current state of the keyboard 

            speed = Vector2.Zero;       //Reset our speed value 

            bool moving = false;          
 

            if (kb.IsKeyDown(Keys.Right))

            {

                //set the speed value, the sprite is now moving

                speed.X = 2;

                moving = true;

                //make our spriteeffect flip the sprite to face right

                se = SpriteEffects.FlipHorizontally;

                frameCounter.Y = 0;

            }

            

            if (kb.IsKeyDown(Keys.Up))

            {

                speed.Y = -2;

                moving = true;

                frameCounter.Y = sprite.Height * 2 / 3;

            }
 

            if (kb.IsKeyDown(Keys.Left))

            {

                speed.X = -2;

                moving = true;

                //reset the spriteeffect 

                se = SpriteEffects.None;

                frameCounter.Y = 0;

            }

            if (kb.IsKeyDown(Keys.Down))

            {

                speed.Y = 2;

                moving = true;

                frameCounter.Y = sprite.Height / 3;

            }

            //add speed value 

            position = MoveBoy(position, speed);
 

            if (moving) //if the sprite has moved this update 

            {

                frameDelay -= gameTime.ElapsedGameTime.TotalSeconds;

                if (frameDelay < 0)

                {

                    //advce to the next frame

                    frameDelay = 0.1;

                    frameCounter.X += sprite.Width / 8; 

                    if (frameCounter.X >= sprite.Width) frameCounter.X = 0; 

                }

            }
 

            base.Update(gameTime);

        }
 

        private Vector2 MoveBoy(Vector2 position, Vector2 speed)

        {

            // Check edges of the playfield

            Vector2 topLeft = new Vector2(0, 0);

            Vector2 bottomRight = new Vector2(750, 550);

            speed = Vector2.Clamp(position + speed, topLeft, bottomRight) - position;
 

            // Check Collision on entities in the World

            BoundingSphere playerPositionSphere = new BoundingSphere(new Vector3(position, 0), 1);

            BoundingSphere playerPositionPlusMovementSphere = new BoundingSphere(new Vector3(position + speed, 0), 1);

            float overlap;

            Vector3 speedCorrection3D;

            foreach (Level.character c in level.allCharacters)

            {

                // Check of the movement causes an overlap.

                if (c.bound.Intersects(playerPositionPlusMovementSphere))

                {

                    // Yes, there's an overlap, how much?

                    overlap = (c.bound.Radius + playerPositionPlusMovementSphere.Radius) - (new Vector3(position, 0) - c.bound.Center).Length();
 

                    // Get the direction from the entity to the boy's position.

                    // Use the direction to correct the direction of speed with the ammount of overlap.

                    speedCorrection3D = (Vector3.Normalize(new Vector3(position, 0) - c.bound.Center) * overlap);
 

                    // Since our result is a Vector3, because the Bounding object from XNA are Vector3's, we need to manually get the XY value.

                    speed.X += speedCorrection3D.X;

                    speed.Y += speedCorrection3D.Y;
 

                    // Create a new sphere containing the new movenent. Required to check for other collisions

                    playerPositionPlusMovementSphere = new BoundingSphere(new Vector3(position + speed, 0), 1);

                }

            }
 

            // Return new position of the boy.

            return position + speed;

        }

Open in new window

0
 
LVL 1

Author Comment

by:KG1973
Comment Utility
Xcone,
That was GREAT !!!!!. We almost there. Now its seems that Bouncing Box or Rectangle is more
appropriate than Spehere one, since the barn/fence are normally either square or rectangle.

How can I change it to rectangle ? ( last one ). The point will be yours........
Thanks a million.


0
 
LVL 1

Author Comment

by:KG1973
Comment Utility
Xcone, if you could helpme on the last one. please...
0
 
LVL 4

Expert Comment

by:Xcone
Comment Utility
Your level.character object doesn't support bounding boxes. It uses bounding spheres. That's why I used bounding spheres in the collision handling as well.

If you want bounding boxes, you have to alter your level.character class to support bounding boxes, or maybe even multiple types of bounding shapes (which is even more advanced). Then you need to alter the MoveBoy method, to work with bounding boxes, which basicly requires a different type of collision handling.

Judging by you current knowledge of vector math (no offence), this is not a step you want to take right now. I suggest you keep it with bounding spheres for the moment. And focus your attention on other aspects of the game, or maybe take a crash course vector math using a few tutorials. Basic understanding of vector math is essential for collision detection and handling.

I won't be able to help you on this the next few days, due to some problems with my computer. I'm sorry for that. Please let me know if you need more help. I'll help you the best I can in a few days.
0
 
LVL 1

Author Comment

by:KG1973
Comment Utility
Xcone,

>>Judging by you current knowledge of vector math (no offence),
No problem at all. You are right. I am still newbie with this game development.

Now I realised that once it get work, one by one, its getting excited. Now I almost finish the 1s level of the game. The square bouncing box that I mention earlier, I can forget it for now coz with sphere one, I can manipulate it. I also managed to create an invisible object that I can use it as the wall or fence. These objects were placed on top of the backgorund. The user wont realised that the character are actually collided with invisible object.

Very interesting. Even sound also I managed to add easily. The solution that you gave me, really helpful++ :)  Now I want to do the ext level, with different storyline but I don't know how to create 2nd level in the same project. Can I create level2.xml for this ? Please advise so that I can open new question.

Thanks a miliion. You really save my life. :)
0
 
LVL 4

Expert Comment

by:Xcone
Comment Utility
That's the whole problem with development of a project. You build something, you add something, you realise something and then suddenly, you want something extra you didn't anticipate and it's gonna be a HARD time getting it to work neatly in the rest of the code. There's only one solution to this problem. Planning.

Before you create something, you sit down and think REAL hard on what you want it to accomplish. Then you create diagrams and start planning on the things you need to accomplish this. This is quite a common step in profesional development, but it's a step which is easily forgotten when doing devlopment as hobby. Hehe, I forget it all time as well.

Obviously, you're beyond this step now. You've created a big part of your game, and now you want something extra you didn't anticipate on. The steps you have to take now are these:
- Make sure you want what you want. (is this step really nessecary)
- Decide how you want it. (Level change, new games, multiplayer modes, different gametypes)
- Decide which additional support is required. (savegames perhaps?)
- Create a plan on how to create this. Ignoring the current state of your game.
- Use that plan to determine how well it's going to fit in your current game.
- The issues you get here, you've got to decide if you will change your plan, or if you change your game to support your plan.

Well, that's the theory. In practice you'd probably want to use the XMLserializer you allready have. That's the way your levels are loaded. So you need to create way to trigger a level change (collision?). Unload the current level, load the new level, position your boy character to the position which is expected after change of level and then you've got most of it to work.
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
Is an Indie RTS practical? 7 112
Domain policy 6 80
MS Solitaire Collection Gone 2 35
Can This PC Run OverWatch 7 65
Artificial Intelligence comes in many forms, and for game developers, Path-Finding is an important ability for making an NPC (Non-Playable Character) maneuver through terrain.  A* is a particularly easy way to approach it.  I’ll start with the algor…
As game developers, we quickly learn that Artificial Intelligence (AI) doesn’t need to be so tough.  To reference Space Ghost: “Moltar, I have a giant brain that is able to reduce any complex machine into a simple yes or no answer. (http://www.youtu…
Internet Business Fax to Email Made Easy - With eFax Corporate (http://www.enterprise.efax.com), you'll receive a dedicated online fax number, which is used the same way as a typical analog fax number. You'll receive secure faxes in your email, fr…
Polish reports in Access so they look terrific. Take yourself to another level. Equations, Back Color, Alternate Back Color. Write easy VBA Code. Tighten space to use less pages. Launch report from a menu, considering criteria only when it is filled…

744 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now