2
\$\begingroup\$

So I've made my collision boxes visual (Draw method) and I saw that there were some problems with the boxes and I fixed them (x, y, length, width). They are now big enough.

This is the collision box inside my constructor for my TileSprite class:

public TileSprite(Texture2D collisionImage, Texture2D textureImage, Vector2 position, Point frameSize, Point currentFrame)
    : base (collisionImage, textureImage, position, frameSize, currentFrame)
{
    // Collision box (Rectangle)
    bCollisionRect = new Rectangle((int)position.X, (int)position.Y, frameSize.X * 2, frameSize.Y * 2);
}

And this is the collision box for my PlayerMovement class. This collision box is written in the update method so it updates when the player moves:

collisionRect = new Rectangle((int)position.X + 4, (int)position.Y + 14, frameSize.X + 10, frameSize.Y + 20);

TileSprite and PlayerMovement have an abstract class in common, named Sprite.I have all my virtual methods for the sprites in Sprite and this is my Collision method:

public virtual void Collision (GameTime gameTime)
{
    // collisionRect is from PlayerMovement and bCollisionRect from TileSprite
    if(collisionRect.Intersects(bCollisionRect))
    {
        Console.WriteLine("collision");
    }
}

But my problem is, that there is no console output when the two collision boxes intersect. (Yes, I call the collision method.)

\$\endgroup\$

1 Answer 1

3
\$\begingroup\$

Instead of updating your object's Rectangle variable each frame, you should instead create a read-only Property for it:

public Rectangle Rectangle
{
    get { 
        return new Rectangle((int)position.X, (int)position.Y, frameSize.X * 2, frameSize.Y * 2); 
    }
}

Your player update method should look like:

public void Update(TileSprite[] TilesToCheck)
{
    //Move player
    ...

    //Check for collision
    Collision(TilesToCheck);
}

And then your Player's Collision function:

public virtual void Collision (TileSprite[] TilesToCheck)
{
    for (int i = 0; i < TilesToCheck.Length; i++)
    {
        if(Rectangle.Intersects(TilesToCheck[i].Rectangle))
        {
            Console.WriteLine("collision");
        }
    }
}
\$\endgroup\$
2
  • \$\begingroup\$ Thanks Jon! I will try this as soon as possible and will give you the feedback. One question though: my GraphicsDevice is still returning null (in my previous question). I updated the question a bit, could you maybe look at it again? \$\endgroup\$
    – Jelle
    Commented Nov 8, 2015 at 14:47
  • \$\begingroup\$ I managed to do this by changing one line of code but I will update my code with your code! (and I will delete the DrawableGameComponent) \$\endgroup\$
    – Jelle
    Commented Nov 8, 2015 at 22:09

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .