I am trying to make collision between rectangles in my game. The player can move with W, A, S, D and there are ‘blocks’ that the player is supposed to collide with. I’m able to make it so the player can collide normally along 1 axis, but whenever I combine the x and y axis it creates strange behaviour. I’ve tried making it so it checks which axis the player is closer to the center of the block on, but it only makes it worse.
if (pos.x + WIDTH / 2f > block.pos.x - block.width / 2f && pos.x - WIDTH / 2f < block.pos.x + block.width / 2f
&& pos.y + HEIGHT / 2f > block.pos.y - block.width / 2f && pos.y - HEIGHT / 2f < block.pos.y + block.height / 2f)
{
float dx = Application.dist(pos.x, 0, block.pos.x, 0);
float dy = Application.dist(0, pos.y, 0, block.pos.y);
if (dx < dy)
{
// left
if (pos.x + WIDTH / 2f > block.pos.x - block.width / 2f && pos.x < block.pos.x)
{
pos.x = block.pos.x - block.width / 2f - WIDTH / 2f;
}
}
else
{
// top
if (pos.y + HEIGHT / 2f > block.pos.y - block.height / 2f && pos.y < block.pos.y)
{
pos.y = block.pos.y - block.height / 2f - HEIGHT / 2f;
}
}
if (dx < dy)
{
// right
if (pos.x - WIDTH / 2f < block.pos.x + block.width / 2f && pos.x > block.pos.x)
{
pos.x = block.pos.x + block.width / 2f + WIDTH / 2f;
}
// bottom
if (pos.y - HEIGHT / 2f > block.pos.y + block.height / 2f && pos.y < block.pos.y)
{
pos.y = block.pos.y + block.height / 2f + HEIGHT / 2f;
}
}
}
I also know why it doesn’t work, though I don’t have a clue on how to fix it.