7 Replies - 1862 Views - Last Post: 11 September 2012 - 08:27 AM

#1 Flor1N  Icon User is offline

  • New D.I.C Head

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

Problem with Rectangle and Vector2 Intersects

Posted 10 September 2012 - 03:50 PM

Hi everybody.
Recently I started learning XNA without knowing C# (just structured used in C++ also like statements,loops etc) from youtube.Here is the link.
I want to make a simple 2D game with scrolling objects and background.
Using the tutorials, I made a scrolling backgrounds and objects, Jump ( I tried double jumps but they don't work very well), HealthBar,Moving the player.
I don't understand pretty well the classes.
The guy who made the tutorials, was using Texture2D and Rectangle for declaring a image.
After several lesson,he went to classes and instead of using Rectangle in classes for declaring images, he was using new Vector2.
But, I think you can't intersect a Rectangle with a Vector2 and this is what I need.
When my player rectangle instersects enemy rectangle (but is a vector), the health will decrease.
As you can see in the posted code,I changed Vector2 to Rectangle at player, but at enemy I couldn't because there is a list.

My 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 ScrollingBackground
{
    /// <summary>
    /// This is the main type for your game
    /// </summary>
    public class Game1 : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;

        //Adversari
        List<Enemies> enemies = new List<Enemies>();
        public Random random = new Random();
        public float spawn = 0;

        //Background cu clasa
        Scrolling scrolling1;
        Scrolling scrolling2;
        Scrolling scrolling3;
        Scrolling scrolling4;

        //Player
        Character player;
        Rectangle playerrectangle;

        //Health Bar
        Texture2D healthTexture;
        Rectangle healthRectangle;





        //Platforme
        //List<Platform> platforms = new List<Platform>();

        //Screen settings
        int ScreenWidth;
        int ScreenHeight;


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

        /// <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

            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);
            
            //Jucator
            player = new Character(Content.Load<Texture2D>("Jucator/jucator_redimensionat"),new Rectangle(50,50,200,200),200);
            healthTexture = Content.Load<Texture2D>("Jucator/viata");
            //Background
            scrolling1 = new Scrolling(Content.Load<Texture2D>("Background/copaci1"),new Rectangle(0, 0, 800,500));
            scrolling2 = new Scrolling(Content.Load<Texture2D>("Background/copaci2"), new Rectangle(800, 0, 800, 500));
            scrolling3 = new Scrolling(Content.Load<Texture2D>("Background/drum1"), new Rectangle(0, 420, 800, 70));
            scrolling4 = new Scrolling(Content.Load<Texture2D>("Background/drum2"), new Rectangle(800, 420, 800, 70));
            LoadEnemies();

            //Limitarea screen-ului
            ScreenWidth = GraphicsDevice.Viewport.Width;
            ScreenHeight = GraphicsDevice.Viewport.Height;

            //graphics.IsFullScreen = true;
            graphics.ApplyChanges();
            
            //platforms.Add(new Platform(Content.Load<Texture2D>("Platforme/Platform"), new Vector2(30, 400)));
            //platforms.Add(new Platform(Content.Load<Texture2D>("Platforme/Platform"), new Vector2(350, 300)));
            //platforms.Add(new Platform(Content.Load<Texture2D>("Platforme/Platform"), new Vector2(700, 350)));
        }
        

        /// <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 (Keyboard.GetState().IsKeyDown(Keys.Escape))
                this.Exit();
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                this.Exit();



            player.Update(gameTime);



           
            

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

            //Platforme
            //foreach(Platform platform in platforms)
                //if (player.playerrectangle.isOnTopOf(platform.platformrectangle))
                //{
                    //player.velocity.Y = 0f;
                    //player.hasJumped = false;
                //}


            // Scrolling Backgrounds
            if (scrolling1.rectangle.X + scrolling1.texture.Width <= 0)
                scrolling1.rectangle.X = scrolling2.rectangle.X + scrolling1.texture.Width;
            if (scrolling2.rectangle.X + scrolling2.texture.Width <= 0)
                scrolling2.rectangle.X = scrolling1.rectangle.X + scrolling2.texture.Width;
            if (scrolling3.rectangle.X + scrolling3.texture.Width <= 0)
                scrolling3.rectangle.X = scrolling4.rectangle.X + scrolling3.texture.Width;
            if (scrolling4.rectangle.X + scrolling4.texture.Width <= 0)
                scrolling4.rectangle.X = scrolling3.rectangle.X + scrolling4.texture.Width;

            //Miscarea jucatorului nu mai este necesara pentru ca e facuta in clasa


            //Blocarea jucatorului sa iasa din decor ! NU FUNCTIONEAZA
            if (player.playerrectangle.X < 0)
                player.playerrectangle.X = 0;
            if (player.playerrectangle.Y < 0)
                player.playerrectangle.Y = 0;
            if (player.playerrectangle.X + player.playertexture.Width > ScreenWidth)
                player.playerrectangle.X = ScreenWidth - player.playertexture.Width;
            if (player.playerrectangle.X + player.playertexture.Width > ScreenWidth)
                player.playerrectangle.X = ScreenWidth - player.playertexture.Width;



            scrolling1.Update();
            scrolling2.Update();
            scrolling3.Update();
            scrolling4.Update();

            {
                int randY = random.Next(100, 300);
                if (spawn >= 1)
                {
                    spawn = 0;
                    if (enemies.Count() < 3 )
                    {
                        
                        enemies.Add(new Enemies(Content.Load<Texture2D>("Adversari/enemy"), new Vector2(1300, randY)));
                    }
                }
                for (int i = 0; i < enemies.Count; i++)
                    if (!enemies[i].isVisible)
                    {
                        enemies.RemoveAt(i);
                        i--;
                    }
            }

  
            if (scrolling1.rectangle.X + scrolling1.texture.Width <= 0)
                scrolling1.rectangle.X = scrolling2.rectangle.X + scrolling1.texture.Width;
            if (scrolling2.rectangle.X + scrolling2.texture.Width <= 0)
                scrolling2.rectangle.X = scrolling1.rectangle.X + scrolling2.texture.Width;
            if (scrolling3.rectangle.X + scrolling3.texture.Width <= 0)
                scrolling3.rectangle.X = scrolling4.rectangle.X + scrolling3.texture.Width;
            if (scrolling4.rectangle.X + scrolling4.texture.Width <= 0)
                scrolling4.rectangle.X = scrolling3.rectangle.X + scrolling4.texture.Width;

            spawn += (float)gameTime.ElapsedGameTime.TotalSeconds;
            foreach (Enemies enemy in enemies)
                enemy.Update(graphics.GraphicsDevice);
            base.Update(gameTime);
            
        }

        public void LoadEnemies()
        {
            int randY = random.Next(100, 300);
            if(spawn >= 1 )
            {
                spawn = 0 ;
                if (enemies.Count() < 3 )
                
                    enemies.Add(new Enemies(Content.Load<Texture2D>("Adversari/enemy"), new Vector2(300, randY)));
                    
                
                    
            }
            for(int i = 0;i< enemies.Count;i++)
                if (!enemies[i].isVisible)
                {
                    enemies.RemoveAt(i);
                    i--;
                }
        }



        /// <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);

            // TODO: Add your drawing code here
            spriteBatch.Begin();
            scrolling1.Draw(spriteBatch);
            scrolling2.Draw(spriteBatch);
           // foreach (Platform platform in platforms)
             //   platform.Draw(spriteBatch);
            player.Draw(spriteBatch);
            spriteBatch.Draw(healthTexture, healthRectangle, Color.White);
            foreach (Enemies enemy in enemies)
                enemy.Draw(spriteBatch);
            scrolling3.Draw(spriteBatch);
            scrolling4.Draw(spriteBatch);
            spriteBatch.End();


            base.Draw(gameTime);
        }
    }
}

//static class RectangleHelper
//{
  //  const int penetrationMargin = 5;
    //public static bool isOnTopOf(this Rectangle r1, Rectangle r2)
    //{
      //  return (r1.Bottom >= r2.Top - penetrationMargin &&
        //    r1.Bottom <= r2.Top && r1.Right >= r2.Left + 5 &&
          //  r1.Left <= r2.Right - 5);
   // }
//}

Enemies code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace ScrollingBackground
{
    class Enemies
    {
        public Texture2D enemytexture;
        public Vector2 enemyposition;
        public Vector2 enemyvelocity;

        public bool isVisible = true;

        public Random random = new Random();
        int randX, randY;

        public Enemies(Texture2D newTexture, Vector2 newPosition)
        {
            enemytexture = newTexture;
            enemyposition = newPosition;

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

            enemyvelocity = new Vector2(randX, randY);

        }
        public void Update(GraphicsDevice graphics)
        {
            enemyposition += enemyvelocity;
            if (enemyposition.Y <= 0 || enemyposition.Y >= graphics.Viewport.Height - enemytexture.Height)
                enemyvelocity.Y = -enemyvelocity.Y;
            if (enemyposition.X < 0 - enemytexture.Width)
                isVisible = false;
        }
        public void Draw(SpriteBatch spriteBatch)
        {
            spriteBatch.Draw(enemytexture, enemyposition, Color.White);
        }


    }
}


Character code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Audio;

namespace ScrollingBackground
{
    class Character
    {
        public Texture2D playertexture;
        Vector2 playerposition;
        public Vector2 velocity;
        public Rectangle playerrectangle;
        public bool hasJumped; // are valoare true , verifica daca jucatorul a sarit
        public KeyboardState presentKey;
        public KeyboardState pastKey;
        public int health;


        public Character(Texture2D newTexture, Rectangle newRectangle,int newHealth)
        {
            playertexture = newTexture;
            playerrectangle = newRectangle ;
            hasJumped = true;
            health = newHealth;
        }

        public void Update(GameTime gameTime)
        {
            playerposition += velocity;  //Pozitia ia valoarea velocity
            playerrectangle = new Rectangle((int)playerposition.X, (int)playerposition.Y, playertexture.Width, playertexture.Height);

            presentKey = Keyboard.GetState();
            if (presentKey.IsKeyDown(Keys.Right) && pastKey.IsKeyDown(Keys.Right))
                velocity.X = 3f;
            else if (presentKey.IsKeyDown(Keys.Left) && pastKey.IsKeyDown(Keys.Left))
                velocity.X = -3f;
            else
                velocity.X = 0f;

            if(presentKey.IsKeyDown(Keys.Up) && pastKey.IsKeyDown(Keys.Up) && hasJumped == false)
            {
                playerposition.Y -= 10f;
                velocity.Y = -5f;
                hasJumped = true;
                
            }
            if (hasJumped == true)
            {
                float i = 1;
                velocity.Y += 0.15f * i;
                if (Keyboard.GetState().IsKeyDown(Keys.Up)) //Double Jump
                {
                    playerposition.Y -= 10f;
                    velocity.Y = -5f;
                    hasJumped = true;

                }
            }
            if (playerposition.Y + playertexture.Height >= 417)
                hasJumped = false;
            if (hasJumped == false)
                velocity.Y = 0f;

            pastKey = presentKey;
    
            
        }
        public void Draw(SpriteBatch spriteBatch)  //Desenarea texturii (jucatorului)
        {
            if(health > 0)
            spriteBatch.Draw(playertexture, playerposition, Color.White);
        }



    }
}



Background code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework;

namespace ScrollingBackground
{
    class Background
    {
        public Texture2D texture;
        public Rectangle rectangle;
        public void Draw(SpriteBatch spriteBatch)
        {
            spriteBatch.Draw(texture, rectangle, Color.White);
        }
    }
    class Scrolling : Background
    {
        public Scrolling(Texture2D newTexture, Rectangle newRectangle)
        {
            texture = newTexture;
            rectangle = newRectangle;
        }
        public void Update()
        {
            rectangle.X -= 2;
        }
    }
}


and another issues. I want the double jump option. It works but if I keep pressing the key, the player goes up exiting the screen. If I keep pressing Up, it will exit the window.
Also, I can't set the screen settings. The player can go over the borders.
Thank you and sorry for my bad code and English.

Is This A Good Question/Topic? 0
  • +

Replies To: Problem with Rectangle and Vector2 Intersects

#2 Flor1N  Icon User is offline

  • New D.I.C Head

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

Re: Problem with Rectangle and Vector2 Intersects

Posted 11 September 2012 - 01:00 AM

Sorry for double post:
How can I make that enemies spawn at every 2 seconds (a wait function in Draw())?
Was This Post Helpful? 0
  • +
  • -

#3 Kilorn  Icon User is offline

  • XNArchitect
  • member icon



Reputation: 1356
  • View blog
  • Posts: 3,528
  • Joined: 03-May 10

Re: Problem with Rectangle and Vector2 Intersects

Posted 11 September 2012 - 05:54 AM

You could make a rectangle based off of the Vector2 for that enemy object. Inside your foreach loop that checks for collision, just add something like:
Rectangle enemyRect = new Rectangle((int)enemy.Position.X, (int)enemy.Position.Y, enemy.Width, enemy.Height);



You'll have to cast the X and Y positions into integers because a Vector2 is just 2 floats while a rectangle requires integers.

This will give you a rectangle for the current enemy object in the foreach loop, and you can easily do:
if (player.Intersects(enemyRect))
{
   // Do something...
}


This post has been edited by Kilorn: 11 September 2012 - 05:55 AM

Was This Post Helpful? 0
  • +
  • -

#4 Flor1N  Icon User is offline

  • New D.I.C Head

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

Re: Problem with Rectangle and Vector2 Intersects

Posted 11 September 2012 - 07:40 AM

I added
Rectangle enemyRect = new Rectangle((int)enemy.enemyposition.X, (int)enemy.enemyposition.Y, enemy.enemytexture.Width, enemy.enemytexture.Height);
in foreach loop and then I made the if statement like this:
if(playerrectangle.Intersects(enemies[1].enemyRect));
            {
                player.health -= 10;
            }

But the debugged says that:
Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index

I know it's something wrong with the [1] but I don't know how to resolve this.
I must put the index in the code.
Thanks.
Was This Post Helpful? 0
  • +
  • -

#5 Kilorn  Icon User is offline

  • XNArchitect
  • member icon



Reputation: 1356
  • View blog
  • Posts: 3,528
  • Joined: 03-May 10

Re: Problem with Rectangle and Vector2 Intersects

Posted 11 September 2012 - 07:51 AM

You're trying to access the second element, since they are zero-based, this will cause an error most likely because you've only got one object in the list. We're also creating the enemyRect in the foreach loop instead of it being a property of the enemy class, so you don't want to use enemy.enemyRect. Change that line to if (playerrectangle.Intersects(enemyRect)) You also want to remove the semicolon from the end of the if check, because it will cause the compiler to think that is the end of the if check and not view the code inside the brackets to follow as being part of the same chunk.

I'd also recommend doing a little research on naming conventions for programming languages, specifically C#. We generally use that is commonly referred to as "Camel Case" where the name of fields that are not public static begin with a lowercase letter, and if there are multiple words pushed together as a single word, you capitalize the first letter of each word beyond the first, for instance playerRectangle. Properties and methods are a different story, you want to capitalize the first letter of each word. Naming conventions are all a matter of personal preference, but the majority of us prefer to use camel case because it makes the code easier to read through, and helps tremendously when working with a team of developers.
Was This Post Helpful? 0
  • +
  • -

#6 Flor1N  Icon User is offline

  • New D.I.C Head

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

Re: Problem with Rectangle and Vector2 Intersects

Posted 11 September 2012 - 08:06 AM

I did what you told me but it gives me this error.
The name 'enemyRect' does not exist in the current context.


Here is my game code after the changes:
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 ScrollingBackground
{
    /// <summary>
    /// This is the main type for your game
    /// </summary>
    public class Game1 : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;

        //Adversari
        List<Enemies> enemies = new List<Enemies>();
        public Random random = new Random();
        public float spawn = 0;

        //Background cu clasa
        Scrolling scrolling1;
        Scrolling scrolling2;
        Scrolling scrolling3;
        Scrolling scrolling4;



        //Player
        Character player;
        Rectangle playerrectangle;

        //Health Bar
        Texture2D healthTexture;
        Rectangle healthRectangle;





        //Platforme
        //List<Platform> platforms = new List<Platform>();

        //Screen settings
        int ScreenWidth;
        int ScreenHeight;

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

        /// <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

            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);
            
            //Jucator
            player = new Character(Content.Load<Texture2D>("Jucator/jucator_redimensionat"),new Rectangle(50,50,200,200),200);
            healthTexture = Content.Load<Texture2D>("Jucator/viata");
            //Background
            scrolling1 = new Scrolling(Content.Load<Texture2D>("Background/copaci1"),new Rectangle(0, 0, 800,500));
            scrolling2 = new Scrolling(Content.Load<Texture2D>("Background/copaci2"), new Rectangle(800, 0, 800, 500));
            scrolling3 = new Scrolling(Content.Load<Texture2D>("Background/drum1"), new Rectangle(0, 420, 800, 70));
            scrolling4 = new Scrolling(Content.Load<Texture2D>("Background/drum2"), new Rectangle(800, 420, 800, 70));
            LoadEnemies();

            //Limitarea screen-ului
            ScreenWidth = GraphicsDevice.Viewport.Width;
            ScreenHeight = GraphicsDevice.Viewport.Height;
            //graphics.IsFullScreen = true;
            graphics.ApplyChanges();
            
            //platforms.Add(new Platform(Content.Load<Texture2D>("Platforme/Platform"), new Vector2(30, 400)));
            //platforms.Add(new Platform(Content.Load<Texture2D>("Platforme/Platform"), new Vector2(350, 300)));
            //platforms.Add(new Platform(Content.Load<Texture2D>("Platforme/Platform"), new Vector2(700, 350)));
        }
        

        /// <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 (Keyboard.GetState().IsKeyDown(Keys.Escape))
                this.Exit();
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                this.Exit();



            player.Update(gameTime);



           
            

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

            //Platforme
            //foreach(Platform platform in platforms)
                //if (player.playerrectangle.isOnTopOf(platform.platformrectangle))
                //{
                    //player.velocity.Y = 0f;
                    //player.hasJumped = false;
                //}


            // Scrolling Backgrounds
            if (scrolling1.rectangle.X + scrolling1.texture.Width <= 0)
                scrolling1.rectangle.X = scrolling2.rectangle.X + scrolling1.texture.Width;
            if (scrolling2.rectangle.X + scrolling2.texture.Width <= 0)
                scrolling2.rectangle.X = scrolling1.rectangle.X + scrolling2.texture.Width;
            if (scrolling3.rectangle.X + scrolling3.texture.Width <= 0)
                scrolling3.rectangle.X = scrolling4.rectangle.X + scrolling3.texture.Width;
            if (scrolling4.rectangle.X + scrolling4.texture.Width <= 0)
                scrolling4.rectangle.X = scrolling3.rectangle.X + scrolling4.texture.Width;

            //Miscarea jucatorului nu mai este necesara pentru ca e facuta in clasa


            //Blocarea jucatorului sa iasa din decor ! NU FUNCTIONEAZA
            if (playerrectangle.X < 0) 
                playerrectangle.X = 0;
            if (playerrectangle.Y < 0)
                playerrectangle.Y = 0;
            if (playerrectangle.X + player.playertexture.Width > ScreenWidth)
                playerrectangle.X = ScreenWidth - player.playertexture.Width;
            if (playerrectangle.X + player.playertexture.Width > ScreenWidth)
                playerrectangle.X = ScreenWidth - player.playertexture.Width;



            scrolling1.Update();
            scrolling2.Update();
            scrolling3.Update();
            scrolling4.Update();

            {
                int randY = random.Next(100, 300);
                if (spawn >= 1)
                {
                    spawn = 0;
                    if (enemies.Count() < 3 )
                    {
                        
                        enemies.Add(new Enemies(Content.Load<Texture2D>("Adversari/enemy"), new Vector2(1300, randY)));
                    }
                }
                for (int i = 0; i < enemies.Count; i++)
                    if (!enemies[i].isVisible)
                    {
                        enemies.RemoveAt(i);
                        i--;
                    }
            }

  
            if (scrolling1.rectangle.X + scrolling1.texture.Width <= 0)
                scrolling1.rectangle.X = scrolling2.rectangle.X + scrolling1.texture.Width;
            if (scrolling2.rectangle.X + scrolling2.texture.Width <= 0)
                scrolling2.rectangle.X = scrolling1.rectangle.X + scrolling2.texture.Width;
            if (scrolling3.rectangle.X + scrolling3.texture.Width <= 0)
                scrolling3.rectangle.X = scrolling4.rectangle.X + scrolling3.texture.Width;
            if (scrolling4.rectangle.X + scrolling4.texture.Width <= 0)
                scrolling4.rectangle.X = scrolling3.rectangle.X + scrolling4.texture.Width;

            spawn += (float)gameTime.ElapsedGameTime.TotalSeconds;
            foreach (Enemies enemy in enemies)
            {
                enemy.Update(graphics.GraphicsDevice);
                Rectangle enemyRect = new Rectangle((int)enemy.enemyposition.X, (int)enemy.enemyposition.Y, enemy.enemytexture.Width, enemy.enemytexture.Height);
            }
            base.Update(gameTime);

            if (playerrectangle.Intersects(enemyRect)) 
            {
                player.health -= 10;
            }
        }
        public void LoadEnemies()
        {
            int randY = random.Next(100, 300);
            if(spawn >= 1 )
            {
                spawn = 0 ;
                if (enemies.Count() < 3 )
                
                    enemies.Add(new Enemies(Content.Load<Texture2D>("Adversari/enemy"), new Vector2(300, randY)));
                    
                
                    
            }
            for(int i = 0;i< enemies.Count;i++)
                if (!enemies[i].isVisible)
                {
                    enemies.RemoveAt(i);
                    i--;
                }
        }



        /// <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);

            // TODO: Add your drawing code here
            spriteBatch.Begin();
            scrolling1.Draw(spriteBatch);
            scrolling2.Draw(spriteBatch);
           // foreach (Platform platform in platforms)
             //   platform.Draw(spriteBatch);
            player.Draw(spriteBatch);
            spriteBatch.Draw(healthTexture, healthRectangle, Color.White);
            foreach (Enemies enemy in enemies)
            {
                Rectangle enemyRect = new Rectangle((int)enemy.enemyposition.X, (int)enemy.enemyposition.Y, enemy.enemytexture.Width, enemy.enemytexture.Height);
                enemy.Draw(spriteBatch);
            }
            scrolling3.Draw(spriteBatch);
            scrolling4.Draw(spriteBatch);
            spriteBatch.End();

           
            base.Draw(gameTime);
        }
    }
}

//static class RectangleHelper
//{
  //  const int penetrationMargin = 5;
    //public static bool isOnTopOf(this Rectangle r1, Rectangle r2)
    //{
      //  return (r1.Bottom >= r2.Top - penetrationMargin &&
        //    r1.Bottom <= r2.Top && r1.Right >= r2.Left + 5 &&
          //  r1.Left <= r2.Right - 5);
   // }
//}

Was This Post Helpful? 0
  • +
  • -

#7 Kilorn  Icon User is offline

  • XNArchitect
  • member icon



Reputation: 1356
  • View blog
  • Posts: 3,528
  • Joined: 03-May 10

Re: Problem with Rectangle and Vector2 Intersects

Posted 11 September 2012 - 08:14 AM

You're creating the Rectangle inside the foreach loop, and then performing the logic for collisions outside of that foreach loop, where the Rectangle no longer exists. A simple way of fixing it is to add the collision code inside the foreach loop:
foreach (Enemies enemy in enemies)
{
    enemy.Update(graphics.GraphicsDevice);
    Rectangle enemyRect = new Rectangle((int)enemy.enemyposition.X, (int)enemy.enemyposition.Y, enemy.enemytexture.Width, enemy.enemytexture.Height);

    if (playerrectangle.Intersects(enemyRect)) 
    {
        player.health -= 10;
    }
}


Was This Post Helpful? 1
  • +
  • -

#8 Flor1N  Icon User is offline

  • New D.I.C Head

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

Re: Problem with Rectangle and Vector2 Intersects

Posted 11 September 2012 - 08:27 AM

Thank you Kilorn! I understand now.
Unfortunately, the Collision isn't working but I will try my best to solve this.
If someone can help me with the rest of the problems, I will be very grateful.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1