C# XNA Collision Detection with list of objects

615 views Asked by At

I am currently learning C# and XNA and I am having some troubles with getting my collision detection to work properly. I wish for my player to disappear when the Enemy object intersects.

Below shows my code within the Obj class

class Obj
{
    public Vector2 position;
    public float rotation = 0.0f;
    public Texture2D spriteIndex;
    public string spriteName;
    public float speed = 0.0f;
    public float scale = 1.0f;
    public bool alive = true;
    public Rectangle area;
    public bool solid = false;


    public Obj(Vector2 pos)
    {
        position = pos;
    }

    private Obj()
    {

    }

    public virtual void Update()
    {
        if (!alive) return;

        UpdateArea();
        pushTo(speed, rotation);
    }

    public virtual void LoadContent(ContentManager content)
    {
        spriteIndex = content.Load<Texture2D>("sprites\\" + spriteName);
        area = new Rectangle(0, 0, spriteIndex.Width, spriteIndex.Height);
    }

    public virtual void Draw(SpriteBatch spriteBatch)
    {
        if (!alive) return;

        Rectangle Size;
        Vector2 center = new Vector2(spriteIndex.Width / 2, spriteIndex.Height / 2);

        spriteBatch.Draw(spriteIndex, position, null, Color.White, MathHelper.ToRadians(rotation), center, scale, SpriteEffects.None, 0);

    }

    public bool Collision(Vector2 pos, Obj obj)
    {
        Rectangle newArea = new Rectangle(area.X, area.Y, area.Width, area.Height);
        newArea.X += (int)pos.X;
        newArea.Y += (int)pos.Y;

        foreach (Obj o in Items.objList)
        {
            if (o.GetType() == obj.GetType() && o.solid)
                if (o.area.Intersects(newArea))
                    return true;
        }
        return false;
    }

    public Obj Collision(Obj obj)
    {
        foreach (Obj o in Items.objList)
        {
            if (o.GetType() == obj.GetType())
                if (o.area.Intersects(area))
                    return o;
        }
        return new Obj();
    }

    public void UpdateArea()
    {
        area.X = (int)position.X - (spriteIndex.Width / 2);
        area.Y = (int)position.Y - (spriteIndex.Height / 2);
    }

    public T CheckCollisionAgainst<T>() where T : Obj
    {
        // If collision detected, returns the colliding object; otherwise null.
        return Items.objList
            .OfType<T>()
            .FirstOrDefault(o => o.solid && o.area.Intersects(area));
    }

    public virtual void pushTo(float pix, float dir)
    {
        float newX = (float)Math.Cos(MathHelper.ToRadians(dir));
        float newY = (float)Math.Sin(MathHelper.ToRadians(dir));
        position.X += pix * (float)newX;
        position.Y += pix * (float)newY;
    }
}

I am cycling through each Item in my objList to see if they intersect with each other, in this case, I want my Player to disappear if the Enemy intersects with them but this is not happening.

This code is from my Player class

class Player : Obj
{
    KeyboardState keyboard;
    KeyboardState prevKeyboard;

    float spd;

    public static Player player;

    public Player(Vector2 pos) 
        : base(pos)
    {
        position = pos;
        spd = 4;
        spriteName = "WhiteBall";
        solid = false;
        player = this;
    }

    public override void Update()
    {
        player = this;
        //If the player is NOT alive, end.
        if (!alive) return;

        keyboard = Keyboard.GetState();

        //Keyboard controls for game
        if(keyboard.IsKeyDown(Keys.W) && !Collision(new Vector2(0, -spd), new Enemy(new Vector2(0, 0))))
        {
            position.Y -= spd;
        }
        if (keyboard.IsKeyDown(Keys.A) && !Collision(new Vector2(-spd, 0), new Enemy(new Vector2(0, 0))))
        {
            position.X -= spd;
        }

        if (keyboard.IsKeyDown(Keys.S) && !Collision(new Vector2(0, spd), new Enemy(new Vector2(0, 0))))
        {
            position.Y += spd;
        }

        if (keyboard.IsKeyDown(Keys.D) && !Collision(new Vector2(spd, 0), new Enemy(new Vector2(0, 0))))
        {
            position.X += spd;
        }
        prevKeyboard = keyboard;

        //Collision with enemy
        Enemy enemy = CheckCollisionAgainst<Enemy>();
        if (enemy != null)
        {
            alive = false;
        }

        base.Update();
    }


    public override void Draw(SpriteBatch spriteBatch)
    {
        spriteBatch.DrawString(Game1.font, "Pick Up The Crew", new      Vector2(350, 0), Color.White);

        base.Draw(spriteBatch);
    }
}

If it intersects with the Enemy, it should disappear but this doesnt seem to be happening.

1

There are 1 answers

17
Jaanus Varus On BEST ANSWER

Based on the comments you provided, I'm taking a shot here and providing a possible solution (ensure UpdateArea is called before calling this):

public T CheckCollisionAgainst<T>() where T : Obj
{      
    // If collision detected, returns the colliding object; otherwise null.
    return Items.objList
        .OfType<T>()
        .FirstOrDefault(o => o.area.Intersects(area));
}

Enemy enemy = CheckCollisionAgainst<Enemy>();
if (enemy != null)
{
    alive = false;
}