Hello.
I'm trying to create a good way to handle all possible collisions between two objects. Typically one will be moving and hitting the other, and should then "bounce" away.
What I've done so far (I'm creating a typical game where you have a board and bounce a ball at bricks) is to check if the rectangles intersect and if they do, invert the Y-velocity.
This is a really ugly and temporary solution that won't work in the long haul and since this is kind of processing is very common in games I'd really like to find a great way of doing this for future projects aswell. Any links or helpful info is appreciated.
Below is what my collision-handling function looks like right now.
protected void collision()
{
#region Boundaries
if (bal.position.X + bal.velocity.X >= viewportRect.Width ||
bal.position.X + bal.velocity.X <= 0)
{
bal.velocity.X *= -1;
}
if (bal.position.Y + bal.velocity.Y <= 0)
{
bal.velocity.Y *= -1;
}
#endregion
bal.rect = new Rectangle((int)bal.position.X+(int)bal.velocity.X-bal.sprite.Width/2, (int)bal.position.Y-bal.sprite.Height/2+(int)bal.velocity.Y, bal.sprite.Width, bal.sprite.Height);
player.rect = new Rectangle((int)player.position.X-player.sprite.Width/2, (int)player.position.Y-player.sprite.Height/2, player.sprite.Width, player.sprite.Height);
if (bal.rect.Intersects(player.rect))
{
bal.position.Y = player.position.Y - player.sprite.Height / 2 - bal.sprite.Height / 2;
if (player.position.X != player.prevPos.X)
{
bal.velocity.X -= (player.prevPos.X - player.position.X) / 2;
}
bal.velocity.Y *= -1;
}
foreach (Brick b in brickArray.list)
{
b.rect.X = Convert.ToInt32(b.position.X-b.sprite.Width/2);
b.rect.Y = Convert.ToInt32(b.position.Y-b.sprite.Height/2);
if (bal.rect.Intersects(b.rect))
{
b.recieveHit();
bal.velocity.Y *= -1;
}
}
brickArray.removeDead();
}