C# XNA Collision detection with random falling sprite

486 views Asked by At

i am new in XNA .i am trying to build a small 2D game where enemy(ball) are falling from the top of the screen randomly.the player can move inside the screen. what i want to do is when the player(spaceShip) collide with the ball the ball will remove from the screen.And i don't know how to do that. can anyone help me with this? here's 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 RandomSprite
{

    public class Game1 : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;
        TimeSpan timeSpan = TimeSpan.FromMilliseconds(2000);
        Sprite spaceShip;
        Texture2D ballTexture;
        Texture2D backgroundtexture;
        Vector2 ballPos = new Vector2(100f, 100f);

        List<Sprite> ballList = new List<Sprite>();

        float timer = 0f;
        float dropInterval = .50f;
        float speed = 4f;

        Random random;



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

        protected override void Initialize()
        {
            // TODO: Add your initialization logic here
            random = new Random();

            base.Initialize();
        }
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            backgroundtexture = Content.Load<Texture2D>("dungeon600x400");

            spriteBatch = new SpriteBatch(GraphicsDevice);
            ballTexture = Content.Load<Texture2D>("ball");

            spaceShip = new Sprite();
            spaceShip.Texture = Content.Load<Texture2D>("gugu");

            // retrieve the height of the screen
            int screenHeight = GraphicsDevice.Viewport.Height;
            // find the center point of the screen along the x-axis
            int screenCenterX = GraphicsDevice.Viewport.Width / 2;
            spaceShip.Position = new Vector2(
                screenCenterX - (spaceShip.Texture.Width / 2),
                screenHeight - spaceShip.Texture.Height - 20);
        }
       private void HandleInput()
        {
            // Retrieve the current state of the keyboard
            KeyboardState keyboardState = Keyboard.GetState();

            Vector2 playerVelocity = Vector2.Zero;

            // Check if the Left arrow key is pressed and change the velocity of the character accordingly
            if (keyboardState.IsKeyDown(Keys.Left))
            {
                playerVelocity += new Vector2(-speed, 0);

            }

            // Check if the Right arrow key is pressed and change the velocity of the character accordingly
            if (keyboardState.IsKeyDown(Keys.Right))
            {
                playerVelocity += new Vector2(speed, 0);
            }
            if (keyboardState.IsKeyDown(Keys.Up))
            {
                playerVelocity += new Vector2(0, -speed);
            }
            if (keyboardState.IsKeyDown(Keys.Down))
            {
                playerVelocity += new Vector2(0, speed);
            }
            // Apply the velocity to the character's position
            spaceShip.Position += playerVelocity;
        }
        public void HandleFallingCake()
        {
            List<Sprite> toRemove = new List<Sprite>();



            foreach (Sprite ball in ballList)
            {
                if (ball.Position.Y > (GraphicsDevice.Viewport.Height - 100))
                    toRemove.Add(ball);
                else
                    ball.Position += new Vector2(0, speed);
            }


            if (toRemove.Count==1 )
            {
                foreach (Sprite cake in toRemove)
                {
                    ballList.Remove(cake);




                }
            }

        }


        protected override void Update(GameTime gameTime)
        {
            // Allows the game to exit
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                this.Exit();

            // TODO: Add your update logic here
            timer += (float)gameTime.ElapsedGameTime.TotalSeconds;


            if (timer >= dropInterval)
            {

                int xPos = random.Next(GraphicsDevice.Viewport.Width-50);
                ballList.Add(new Sprite(ballTexture, new Vector2(xPos, -100)));
                timer = 0f;
            }
            HandleFallingCake();
            HandleInput();

            timeSpan -= gameTime.ElapsedGameTime;


            if (timeSpan <= TimeSpan.Zero)
            {

                timeSpan = TimeSpan.FromMilliseconds(2000);
            }


            base.Update(gameTime);
        }

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

            // TODO: Add your drawing code here
            spriteBatch.Begin();
            //spriteBatch.Draw(backgroundtexture, new Rectangle(0,0,GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height), Color.White);
            spaceShip.Draw(spriteBatch);
            foreach (Sprite ball in ballList)
            {
                ball.Draw(spriteBatch);
            }
            spriteBatch.End();
            base.Draw(gameTime);
        }
    }
}

and i have a subclass sprite.cs

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

namespace RandomSprite
{
    class Sprite
    {
        public Texture2D Texture;
        public Vector2 Position ;

        public Sprite() { }

        public Sprite(Texture2D texture, Vector2 position)
        {
            Texture = texture;
            Position = position;
        }

        public void Draw(SpriteBatch spriteBatch)
        {
            if (Texture != null)
                spriteBatch.Draw(Texture, Position, Color.White);
        }


    }
}
1

There are 1 answers

0
AudioBubble On BEST ANSWER

You describe the goal, but not ask questions.

If you want to know how to check the intersection of two objects, then you need to define for them bounds (class Rectangle) and check their intersection method Rectangle.Intersect. Anyway better adjust your question.