School Assignment? Project Due Tomorrow? Chat LIVE With A Programming Expert!

Welcome to Dream.In.Code
Become an Expert!

Join 307,127 Programmers for FREE! Get instant access to thousands of experts, tutorials, code snippets, and more! There are 2,050 people online right now. Registration is fast and FREE... Join Now!




XNA how return false in collision detection

 

XNA how return false in collision detection

Hellbroth

2 Nov, 2009 - 01:22 AM
Post #1

D.I.C Head
**

Joined: 15 Aug, 2009
Posts: 53



Thanked: 1 times
My Contributions
I am making a 2D scroller game like metal Slug but with punches biggrin.gif and "Super Punches".
So enemys are comming all the time from the left and right position of the screen.

CODE

private bool Collide()
        {
            Rectangle characterRect = new Rectangle(
            (int)pos1.X + characterOffset,
            (int)pos1.Y + characterOffset,
            frameSize.X - (characterOffset * 2),
            frameSize.Y - (characterOffset * 2));
            Rectangle enemyRect = new Rectangle(
            (int)pos2.X + enemyOffset,
            (int)pos2.Y + enemyOffset,
            frameSize2.X - (enemyOffset * 2),
            frameSize2.Y - (enemyOffset * 2));
            return characterRect.Intersects(enemyRect);
        }


Ok this is my collision detection everything work fine for my game the collision detection is perfect for what i am doing.But i have a small problem.

I have this bool

bool dead = false;

When the enemys are dead and the bool dead is becomming true i want the enemys to don't have anymore collision.

The tutorial i was reading uses this to examine if the method works.
if(Collides))

but i want to return false to it so i don't have any collision anymore.

Example :

CODE


if(dead == true)
{
  // return false to collide  

}

i tried many things but nothing works :S like

Any help if i don't fix this i can't continue my game and i am almost finished with the boss character.

Mod Edit:
Fixed code tags.

User is offlineProfile CardPM
+Quote Post


SixOfEleven

RE: XNA How Return False In Collision Detection

2 Nov, 2009 - 04:41 AM
Post #2

lives.ToCode();
Group Icon

Joined: 18 Oct, 2008
Posts: 3,066



Thanked: 171 times
Dream Kudos: 775
Expert In: C, C#, XNA, Game Programming, Programming Concepts

My Contributions
Are you using classes for the player and the enemies? Where are you calling the Collide method? If you could show where you are calling the Collide method from that would be really helpful.

The reason I say that is from the snippet you posted I can't tell what the game objects look like. It is also hard to see where the variables pos1 and pos2 are coming from. They just seem to appear from no where.
User is offlineProfile CardPM
+Quote Post

stayscrisp

RE: XNA How Return False In Collision Detection

2 Nov, 2009 - 05:05 AM
Post #3

Mouth->Insert(Foot);
Group Icon

Joined: 14 Feb, 2008
Posts: 1,404



Thanked: 53 times
Dream Kudos: 300
My Contributions
CODE

private bool Collide()
        {
            
            if(!Enemy.Dead)
            {
            Rectangle characterRect = new Rectangle(
            (int)pos1.X + characterOffset,
            (int)pos1.Y + characterOffset,
            frameSize.X - (characterOffset * 2),
            frameSize.Y - (characterOffset * 2));
            Rectangle enemyRect = new Rectangle(
            (int)pos2.X + enemyOffset,
            (int)pos2.Y + enemyOffset,
            frameSize2.X - (enemyOffset * 2),
            frameSize2.Y - (enemyOffset * 2));
            return characterRect.Intersects(enemyRect);
            }
        }


That's a quick and shoddy fix smile.gif . Like SixOfEleven said though it would be nice to see the rest of your code.

User is offlineProfile CardPM
+Quote Post

Hellbroth

RE: XNA How Return False In Collision Detection

2 Nov, 2009 - 07:47 AM
Post #4

D.I.C Head
**

Joined: 15 Aug, 2009
Posts: 53



Thanked: 1 times
My Contributions
CODE

using System;
using System.Collections.Generic;
using System.Linq;
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;

namespace WindowsGame8
{
    /// <summary>
    /// This is the main type for your game
    /// </summary>
    public class Game1 : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;
        Sprite mBackground1;

        Texture2D character;
        Point frameSize = new Point(48, 48);
        Point currentFrame = new Point(0, 0);
        Point sheetSize = new Point(3, 11);
        Vector2 pos1 = new Vector2(140, 150);
        float speed1 = 4f;
        int hits = 0;

        Texture2D enemy;
        Point frameSize2 = new Point(48, 48);
        Point currentFrame2 = new Point(0, 0);
        Point sheetSize2 = new Point(3, 11);
        Vector2 pos2 = new Vector2(300, 150);
        float speed2 = 4f;

        Texture2D dragon;
        Vector2 pos3 = new Vector2(200, 0);

        Texture2D hand1;
        Vector2 pos4 = new Vector2(260,0);
        Texture2D hand2;
        Vector2 pos5 = new Vector2(170, 0);

        SoundEffect soundEffect;
        SoundEffect soundEffect2;
        
        string soundName = "song";
        string soundName2 = "punch2";

        bool dead = false;

        int timeSinceLastFrame = 0;
        int millisecondsPerFrame = 20;

        int characterOffset = 10;
        int enemyOffset = 15;
        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
            TargetElapsedTime = new TimeSpan(0, 0, 0, 0, 100);
        }
        private bool Collide()
        {
            
                Rectangle ringsRect = new Rectangle(
                (int)pos1.X + characterOffset,
                (int)pos1.Y + characterOffset,
                frameSize.X - (characterOffset * 2),
                frameSize.Y - (characterOffset * 2));
                Rectangle skullRect = new Rectangle(
                (int)pos2.X + enemyOffset,
                (int)pos2.Y + enemyOffset,
                frameSize2.X - (enemyOffset * 2),
                frameSize2.Y - (enemyOffset * 2));
                return ringsRect.Intersects(skullRect);
            
        }
        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            // TODO: Add your initialization logic here
            graphics.PreferredBackBufferWidth = 420;
            graphics.PreferredBackBufferHeight = 216;
            graphics.IsFullScreen = false;
            graphics.ApplyChanges();
            Window.Title = "Break the shit out of them";

            mBackground1 = new Sprite();
            character = Content.Load<Texture2D>("a2");
            enemy = Content.Load<Texture2D>("enemy");
          
            

            

            base.Initialize();
        }

        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);
            mBackground1.LoadContent(this.Content, "assss");
            dragon = Content.Load<Texture2D>("dragonh");
            hand1 = Content.Load<Texture2D>("hand1");
            hand2 = Content.Load<Texture2D>("hand2");
            mBackground1.Position = new Vector2(0, 0);
            mBackground1.Position2 = new Vector2(-1320, 0);
            

            ContentManager contentManager = new ContentManager(this.Services, @"Content\");
            soundEffect = contentManager.Load<SoundEffect>(soundName);
            soundEffect2 = contentManager.Load<SoundEffect>(soundName2);
            SoundEffectInstance instance = soundEffect.CreateInstance();
            //instance.IsLooped = true;
            //instance.Play();

            

            // TODO: use this.Content to load your game content here
        }

        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// all content.
        /// </summary>
        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
        }

        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {
            // Allows the game to exit
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                this.Exit();
            Vector2 aDirection = new Vector2(-1, 0);

            Vector2 aSpeed = new Vector2(100, 0);
          
            
            currentFrame.Y = 1;
            ++currentFrame.X;
            if (currentFrame.X >= sheetSize.X)
            {
                currentFrame.X = 0;

            }
          

            KeyboardState keyboardState = Keyboard.GetState();
            if (keyboardState.IsKeyDown(Keys.A))
            {
                
                pos1.X += speed1;
                currentFrame.Y = 9;
                timeSinceLastFrame += gameTime.ElapsedGameTime.Milliseconds;
                if (timeSinceLastFrame > millisecondsPerFrame)
                {
                    timeSinceLastFrame -= millisecondsPerFrame;
                    if (currentFrame.Y >= sheetSize.Y)
                        currentFrame.Y = 0;
                    {
                        ++currentFrame.X;
                        if (currentFrame.X >= sheetSize.X)
                        {
                            currentFrame.X = 0;

                        }
                        
                    }
                  
                }
                if (Collide())
                {
                                
                     hits += 1;
                     soundEffect2.Play();
                     pos1.X -= speed1;
                     speed2 = 0;
                    
                    currentFrame2.Y = 2;
                    ++currentFrame2.X;
                    if (currentFrame2.X >= sheetSize2.X)
                    {

                        currentFrame2.X = 0;

                    }
                }
                

            }

            else if (keyboardState.IsKeyDown(Keys.S))
            {
                pos1.X += speed1;
                currentFrame.Y = 8;
                timeSinceLastFrame += gameTime.ElapsedGameTime.Milliseconds;
                if (timeSinceLastFrame > millisecondsPerFrame)
                {
                    timeSinceLastFrame -= millisecondsPerFrame;
                    if (currentFrame.Y >= sheetSize.Y)
                        currentFrame.Y = 0;
                    {
                        ++currentFrame.X;
                        if (currentFrame.X >= sheetSize.X)
                        {
                            currentFrame.X = 0;

                        }
                    }
                }
                if (dead == false)
                {
                    if (Collide())
                    {
                        hits += 1;
                        soundEffect2.Play();
                        pos1.X -= speed1;
                        speed2 = 0;
                        currentFrame2.Y = 2;
                        ++currentFrame2.X;
                        if (currentFrame2.X >= sheetSize2.X)
                        {

                            currentFrame2.X = 0;

                        }
                    }
                }

            }

            else if (keyboardState.IsKeyDown(Keys.Right))
            {
                pos1.X += speed1;
                currentFrame.Y = 6;
                timeSinceLastFrame += gameTime.ElapsedGameTime.Milliseconds;
                if (timeSinceLastFrame > millisecondsPerFrame)
                {
                    timeSinceLastFrame -= millisecondsPerFrame;
                    if (currentFrame.Y >= sheetSize.Y)
                        currentFrame.Y = 0;
                    {
                        ++currentFrame.X;
                        if (currentFrame.X >= sheetSize.X)
                        {
                            currentFrame.X = 0;

                        }
                    }
                }
                if (pos1.X >= Window.ClientBounds.X /2)
                {
                    mBackground1.Position += aDirection * aSpeed * (float)gameTime.ElapsedGameTime.TotalSeconds;;
                    if (mBackground1.Position.X < mBackground1.Position2.X)
                    {
                        mBackground1.Position -= aDirection * aSpeed * (float)gameTime.ElapsedGameTime.TotalSeconds;;
                    }
                }
                
            }
            else if (keyboardState.IsKeyDown(Keys.Left))
            {
                pos1.X -= speed1;
              
                currentFrame.Y = 7;
                timeSinceLastFrame += gameTime.ElapsedGameTime.Milliseconds;
                if (timeSinceLastFrame > millisecondsPerFrame)
                {
                    timeSinceLastFrame -= millisecondsPerFrame;
                    if (currentFrame.Y >= sheetSize.Y)
                        currentFrame.Y = 0;
                    {
                        ++currentFrame.X;
                        if (currentFrame.X >= sheetSize.X)
                        {
                            currentFrame.X = 0;

                        }
                    }
                }
                if (pos1.X <= Window.ClientBounds.X / 2)
                {
                    mBackground1.Position -= aDirection * aSpeed * (float)gameTime.ElapsedGameTime.TotalSeconds;
                    if (mBackground1.Position.X > mBackground1.Position3.X)
                    {
                        mBackground1.Position += aDirection * aSpeed * (float)gameTime.ElapsedGameTime.TotalSeconds;
                    }
                }

            }

            
                        
          
           if (pos1.X < 0)
               pos1.X = 0;
           if (pos1.X > Window.ClientBounds.Width - frameSize.X)
               pos1.X = Window.ClientBounds.Width - frameSize.X;

           currentFrame2.Y = 6;
           pos2.X -= speed2;
           ++currentFrame2.X;
           if (currentFrame2.X >= sheetSize2.X)
           {
               currentFrame2.X = 0;
           }
           if (pos2.X <= pos1.X +25)
           {
               //speed2 =0;
               currentFrame2.Y = 8;
               ++currentFrame2.X;
               if (currentFrame2.X >= sheetSize2.X)
               {
                   currentFrame2.X = 0;
               }
               if (Collide())
               {
                   speed2 = 0;
                   soundEffect2.Play();                                                      
                   currentFrame.Y = 2;
                   ++currentFrame.X;
                   if (currentFrame.X >= sheetSize.X)
                   {

                       currentFrame.X = 0;

                   }
               }

           }

          


              
  

          
          
           if (hits >= 2)
           {
               currentFrame2 = new Point(2, 3);
               pos2.Y = 160;
               dead = true;
           }
          
          

            

            base.Update(gameTime);
        }

        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.CornflowerBlue);

            spriteBatch.Begin();
            mBackground1.Draw(this.spriteBatch);
            spriteBatch.Draw(enemy, pos2,
                new Rectangle(currentFrame2.X * frameSize2.X,
                    currentFrame2.Y * frameSize2.Y,
                    frameSize2.X,
                    frameSize2.Y),
                    Color.White, 0, Vector2.Zero, 1, SpriteEffects.None, 0);
            spriteBatch.Draw(character, pos1,
                new Rectangle(currentFrame.X * frameSize.X,
                    currentFrame.Y * frameSize.Y,
                    frameSize.X,
                    frameSize.Y),
                    Color.White
                    , 0, Vector2.Zero, 1, SpriteEffects.FlipHorizontally, 0);
            spriteBatch.Draw(dragon, pos3, Color.White);
            spriteBatch.Draw(hand1, pos5, Color.White);
            spriteBatch.Draw(hand2, pos4, Color.White);

            
            spriteBatch.End();

            base.Draw(gameTime);
        }
    }
}





There is a sprite class also which i use it for the background image but you don't need that.
What i want to do is when the enemy get's two hits i change the frame so it look's like he is dead.
I check for collision only when you press key A or key S which is when the character is punching.
So when the enemy has get two hits or more i consider he is dead so i want then to make the collision false so if
my character is above and punching it won't collide and play the sound of a puch.


Sorry if it's a bit crappy i just try first to learn things by creating simply things and when i am able to do everything i will start creating classes and move to more object orient programming.
User is offlineProfile CardPM
+Quote Post

lesPaul456

RE: XNA How Return False In Collision Detection

2 Nov, 2009 - 08:59 AM
Post #5

D.I.C Regular
Group Icon

Joined: 16 Apr, 2009
Posts: 258



Thanked: 35 times
Dream Kudos: 175
My Contributions
It looks like staycrisp's code should work. However, you need make a slight change:


CODE

private bool Collide()
{
       if(!Enemy.Dead)
       {
            Rectangle characterRect = new Rectangle(
            (int)pos1.X + characterOffset,
            (int)pos1.Y + characterOffset,
            frameSize.X - (characterOffset * 2),
            frameSize.Y - (characterOffset * 2));
            Rectangle enemyRect = new Rectangle(
            (int)pos2.X + enemyOffset,
            (int)pos2.Y + enemyOffset,
            frameSize2.X - (enemyOffset * 2),
            frameSize2.Y - (enemyOffset * 2));
            return characterRect.Intersects(enemyRect);
       }
       return false; // for the code to compile you need to add this line.
}

User is offlineProfile CardPM
+Quote Post

stayscrisp

RE: XNA How Return False In Collision Detection

2 Nov, 2009 - 10:49 AM
Post #6

Mouth->Insert(Foot);
Group Icon

Joined: 14 Feb, 2008
Posts: 1,404



Thanked: 53 times
Dream Kudos: 300
My Contributions
Yeah I was giving more of a pseudo code answer, but yeah it should work.
User is offlineProfile CardPM
+Quote Post

Hellbroth

RE: XNA How Return False In Collision Detection

2 Nov, 2009 - 09:23 PM
Post #7

D.I.C Head
**

Joined: 15 Aug, 2009
Posts: 53



Thanked: 1 times
My Contributions
QUOTE(stayscrisp @ 2 Nov, 2009 - 10:49 AM) *

Yeah I was giving more of a pseudo code answer, but yeah it should work.


Thanx Statyscrisp you realy helped me like always biggrin.gif
even though i had to use the code in a different place cause i was getting an error there you still gave me the idea.

CODE


currentFrame2.Y = 6;
           pos2.X -= speed2;
           ++currentFrame2.X;
           if (currentFrame2.X >= sheetSize2.X)
           {
               currentFrame2.X = 0;
           }
           if (pos2.X <= pos1.X +25)
           {
               //speed2 =0;
               currentFrame2.Y = 8;
               ++currentFrame2.X;
               if (currentFrame2.X >= sheetSize2.X)
               {
                   currentFrame2.X = 0;
               }
               if (dead == false)
               {
                   if (Collide())
                   {
                       speed2 = 0;
                       soundEffect2.Play();
                       currentFrame.Y = 2;
                       ++currentFrame.X;
                       if (currentFrame.X >= sheetSize.X)
                       {

                           currentFrame.X = 0;

                       }
                   }
               }
           }


This how it should be smile.gif it's about the ai of the enemy.
This is how it looks like till now.

IPB Image


The dragon on the top is the boss but i will put him in the end of the stage with hands moving towards to you
and they fall down if they don't hit you you could punch them and so the boss will loose life silly little thoughts but they work for me smile.gif

User is offlineProfile CardPM
+Quote Post

Fast ReplyReply to this topicStart new topic

Time is now: 11/21/09 02:29PM

Live Help!

Be Social

Dream.In.Code RSS Feed Dream.In.Code LinkedIn Group Follow Us On Twitter Fan Us On Facebook

Tutorials

Programming

Web Development

Reference Sheets

Code Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month