Solved

How to create solid object in my game.

Posted on 2009-04-12
20
571 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 11
  • 8
20 Comments
 
LVL 4

Expert Comment

by:Xcone
ID: 24133088
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
ID: 24133767
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
ID: 24137499
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
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 1

Author Comment

by:KG1973
ID: 24137515
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
ID: 24141291
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
ID: 24143775
what is your email address?
0
 
LVL 4

Expert Comment

by:Xcone
ID: 24145184
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
ID: 24147408
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
ID: 24149057
I agree to that. I think it will be fine without the .sln file.
0
 
LVL 1

Author Comment

by:KG1973
ID: 24152925
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
ID: 24153040
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
ID: 24155592
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
ID: 24155634
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
ID: 24160439
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
ID: 24162364
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
ID: 24168436
Xcone, if you could helpme on the last one. please...
0
 
LVL 4

Expert Comment

by:Xcone
ID: 24168713
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
ID: 24210848
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
ID: 24212192
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

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Author Cited: Konstantinos Dimopoulos URL Cited From: Article from Indie Games: http://indiegames.com/2012/07/browser_game_pick_the_grid.html The Grid (http://codeelf.com/games/grid/) is the sort of game I haven't played in over 10 years. It is …
Programming  of  forecasting lottery numbers for self use  on Turbo C++ is done by use of random number generator code by a program algorithm logic. Random numbers usually generates numbers between definite interval. Therefore, when entering the c…
A short tutorial showing how to set up an email signature in Outlook on the Web (previously known as OWA). For free email signatures designs, visit https://www.mail-signatures.com/articles/signature-templates/?sts=6651 If you want to manage em…
I've attached the XLSM Excel spreadsheet I used in the video and also text files containing the macros used below. https://filedb.experts-exchange.com/incoming/2017/03_w12/1151775/Permutations.txt https://filedb.experts-exchange.com/incoming/201…

739 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