3 Replies - 1063 Views - Last Post: 15 September 2012 - 10:23 AM

#1 Flor1N  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 7
  • Joined: 10-September 12

Collision 2D problem (player with enemies)

Posted 14 September 2012 - 02:39 PM

Hi. I'm trying to make a 2D game but I have a problem with collision.
The game is like this:
The player can move only left and right.
Enemies are falling from the top of the window.
The player should avoid the enemies.
If the player intersects with any enemies, his health is lowered.
If the health == 0 , the player will not be drawn anymore on the screen.

My problem is:
I made the rectangle for player.
I made the rectangles for enemies (at least I tried to. I don't know if the rectangles are succefully build.)
I made a if statement for collision between the rectangles but the health stays the same.

Here is my source 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;

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

        Background background;
        Texture2D backgroundTexture;
        Vector2 backgroundPosition;

        Player player;
        Texture2D playerTexture;
        Rectangle playerRectangle;
        Texture2D healthTexture;
        Rectangle healthRectangle;
        Texture2D healthBarTexture;
        Rectangle healthBarRectangle;
        List<Enemy> enemyList = new List<Enemy>();
        Texture2D enemyTexturedreapta;
        Texture2D enemyTexturestanga;
        Rectangle enemyRectangledreapta;
        Rectangle enemyRectanglestanga;

        KeyboardState presentKey;
        KeyboardState pastKey;

        Random rnd = new Random();
        float totalTime = 0.0f;

        public enum EnemyType
        {
            dreapta,
            stanga
        }


        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
            
        }


        protected override void Initialize()
        {
            // TODO: Add your initialization logic here

            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()
        {
            backgroundPosition.X = 0;
            backgroundPosition.Y = -20;
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);
            backgroundTexture = Content.Load<Texture2D>("background");
            background = new Background(backgroundTexture,backgroundPosition );
            playerTexture = Content.Load<Texture2D>("player");
            player = new Player(playerTexture, new Vector2(400,420),232);
            healthTexture = Content.Load<Texture2D>("viata");
            healthBarTexture = Content.Load<Texture2D>("healthbar");
            healthBarRectangle = new Rectangle(8, 11, healthBarTexture.Width, healthBarTexture.Height);
            enemyTexturedreapta = Content.Load<Texture2D>("enemy1");
            enemyTexturestanga = Content.Load<Texture2D>("enemy2");



        }


        protected override void UnloadContent()
        {

        }


        protected override void Update(GameTime gameTime)
        {

            presentKey = Keyboard.GetState();

            float elapsed = (float)gameTime.ElapsedGameTime.TotalSeconds;
            totalTime += elapsed;


            Rectangle playerRectangle = new Rectangle((int)player.playerPosition.X, (int)player.playerPosition.Y, playerTexture.Width, playerTexture.Height);

            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                this.Exit();



            for (int i = 0; i < enemyList.Count; i++)
            {
                enemyList[i].Update(gameTime);
                
                if (enemyList[i].enemyPosition.Y > 900.0f)
                    enemyList.RemoveAt(i);
            }

            
                    

            healthRectangle = new Rectangle(20, 19, player.health, 16); 

            if(Keyboard.GetState().IsKeyDown(Keys.LeftAlt))
                player.health --;

            player.Update();
            CreateEnemyTime();

            pastKey = presentKey;
              base.Update(gameTime);
        }
        public void CreateEnemyTime()
        {
            if (totalTime > 1.0f && totalTime < 1.01f)
                CreateEnemy(EnemyType.stanga);
            if (totalTime > 1.5f && totalTime < 1.51f)
                for (int i = 0; i < 10; i++)
                
                    CreateEnemy(EnemyType.dreapta);
                
            if (totalTime > 2.0f && totalTime < 2.01f)
                for (int i = 0; i < 7; i++)
                {
                    CreateEnemy(EnemyType.stanga);
                    totalTime = 0.0f;
                }
                    
        }
        public void CreateEnemy(EnemyType enemyType)
        {
            Random r = new Random();
            int startX = r.Next(0,800);
            int start2X = r.Next(800);
            if (enemyType == EnemyType.dreapta)
            {
                Enemy enemy = new Enemy(enemyTexturedreapta, new
                Vector2(startX, -100), 180.0f);
                enemyRectangledreapta = new Rectangle((int)enemy.enemyPosition.X, (int)enemy.enemyPosition.Y, enemyTexturedreapta.Width, enemyTexturedreapta.Height);
                enemyList.Add(enemy);
                if (playerRectangle.Intersects(enemyRectangledreapta))
                    this.Exit();
                    
            }
            if (enemyType == EnemyType.stanga)
            {
                Enemy enemy = new Enemy(enemyTexturestanga, new Vector2(startX,-100), 150.0f);
                enemyRectanglestanga = new Rectangle((int)enemy.enemyPosition.X, (int)enemy.enemyPosition.Y, enemyTexturestanga.Width, enemyTexturestanga.Height);
                enemyList.Add(enemy);
                if (playerRectangle.Intersects(enemyRectanglestanga))
                    this.Exit();
            }
        }


        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.CornflowerBlue);



            spriteBatch.Begin();
            background.Draw(spriteBatch);
            player.Draw(spriteBatch);
            spriteBatch.Draw(healthTexture, healthRectangle, Color.White);
            spriteBatch.Draw(healthBarTexture, healthBarRectangle, Color.White);
            foreach (Enemy enem in enemyList)
                enem.Draw(spriteBatch);
            spriteBatch.End();
       }
    }
}



Player class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
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;

namespace BlockHeads
{
    class Player
    {
        Texture2D playerTexture;
        public Vector2 playerPosition;
        public int health = 200;


        public Player(Texture2D texture, Vector2 position, int newhealth )
        {
            playerTexture = texture;
            playerPosition = position;
            health = newhealth;  //Viata
        }


        public void Update()
        {
            if (Keyboard.GetState().IsKeyDown(Keys.Left))  //Miscare
                playerPosition.X -= 4;
            if (Keyboard.GetState().IsKeyDown(Keys.Right)) //Miscare
                playerPosition.X += 4;
        }

        public void Draw(SpriteBatch spriteBatch)
        {
            if(health>0)  //Daca viata < 0 , playerul nu va mai fi desenat
                spriteBatch.Draw(playerTexture, playerPosition, Color.White);
        }
    
    }
}



Enemy Class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
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;

namespace BlockHeads
{
    class Enemy
    {
        Texture2D enemyTexture;
        public Vector2 enemyPosition;

        
        float speed=150f;
        float randY;
        public Random random = new Random();


        public Enemy(Texture2D texture, Vector2 enemyPosition, float speed)
        {
            this.enemyTexture = texture;

            this.speed = speed;
            this.enemyPosition = enemyPosition;
        

            float randX= 0;
            randY = random.Next(-2, -1);
        }

        public void Update(GameTime gameTime)
        {
            float elapsed = (float)gameTime.ElapsedGameTime.TotalSeconds;
            enemyPosition.Y += (float)speed * (float)elapsed;
    
        }



        public void Draw(SpriteBatch spriteBatch)
        {
            spriteBatch.Draw(enemyTexture, enemyPosition, Color.White);
        }




    }
}


I think I know what I'm doing wrong. I should make a list of rectangles of enemies? If so, can you explain me how?
Thank you.

Unfortunately , I can't edit so I need to make this post.
Change the this.Exit() with player.health --; because I forgot to put the right code.

Is This A Good Question/Topic? 0
  • +

Replies To: Collision 2D problem (player with enemies)

#2 LiberLogic969  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 34
  • View blog
  • Posts: 85
  • Joined: 03-September 12

Re: Collision 2D problem (player with enemies)

Posted 15 September 2012 - 06:10 AM

It seems like you're only checking for a collision when an enemy is created and not every frame. Check for collisions in the for loop inside Update().


public overide void Update(GameTime gameTime)
{
  ......

  for (int i = 0; i < enemyList.Count; i++)
  {
      Enemy e = enemyList[i];      
      e.Update(gameTime);

      Rectangle enemyRect = new Rectangle(
      (int)e.enemyPosition.X, (int)e.enemyPosition.Y, e.Width, e.Height);

      if (e.enemyPosition.Y > 900.0f)  
          enemyList.RemoveAt(i); 
      else if (playerRectangle.Intersects(enemyRect))
          {
              player.Health--;
          }
  }
}



Was This Post Helpful? 1
  • +
  • -

#3 Flor1N  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 7
  • Joined: 10-September 12

Re: Collision 2D problem (player with enemies)

Posted 15 September 2012 - 08:24 AM

Thank you!!!
Was This Post Helpful? 0
  • +
  • -

#4 LiberLogic969  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 34
  • View blog
  • Posts: 85
  • Joined: 03-September 12

Re: Collision 2D problem (player with enemies)

Posted 15 September 2012 - 10:23 AM

You're welcome :)
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1