I'm trying to get the velocity of my character to be zero when it collides with another sprite. It does this, however the distance between the textures increases when it collides if I choose a higher value for speed, the higher the value the further the distance between the textures when collision occurs.
At a speed of 1f the collision seems to work fine (both textures touching) but 1f is too slow for my game and I can't figure out how to increase it without increasing the distance of collision.
I believe this is because I use: rectangle.Right + Velocity.X in my Collision region but I'm not sure how to alter this to fix my problem. Help would be appreciated.
//In Sprite class
#region Collision
protected bool IsTouchingLeft(Sprite sprite)
{
return rectangle.Right + Velocity.X > sprite.rectangle.Left &&
rectangle.Left < sprite.rectangle.Left &&
rectangle.Bottom > sprite.rectangle.Top &&
rectangle.Top < sprite.rectangle.Bottom;
}
protected bool IsTouchingRight(Sprite sprite)
{
return rectangle.Left + Velocity.X < sprite.rectangle.Right &&
rectangle.Right > sprite.rectangle.Right &&
rectangle.Bottom > sprite.rectangle.Top &&
rectangle.Top < sprite.rectangle.Bottom;
}
protected bool IsTouchingTop(Sprite sprite)
{
return rectangle.Bottom + Velocity.Y > sprite.rectangle.Top &
rectangle.Top < sprite.rectangle.Top &&
rectangle.Right > sprite.rectangle.Left &&
rectangle.Left < sprite.rectangle.Right;
}
protected bool IsTouchingBottom(Sprite sprite)
{
return rectangle.Top + Velocity.Y < sprite.rectangle.Bottom &
rectangle.Bottom > sprite.rectangle.Bottom &&
rectangle.Right > sprite.rectangle.Left &&
rectangle.Left < sprite.rectangle.Right;
}
#endregion
//In MainChar class
foreach (var sprite in sprites)
{
if (sprite == this)
{
continue;
}
if (Velocity.X > 0 && IsTouchingLeft(sprite) || Velocity.X < 0 && IsTouchingRight(sprite))
{
Velocity.X = 0;
}
if (Velocity.Y > 0 && IsTouchingTop(sprite) || Velocity.Y < 0 && IsTouchingBottom(sprite))
{
Velocity.Y = 0;
}
if (sprite.rectangle.Intersects(rectangle))
{
hasDied = true;
}
}
IsTouching*methods really should be namedWillBeTouching*because you're adding velocity to current position. Two things come to mind. Reduce velocity to have them collide perfectly, or set position to where the collision would happen. - Zer0