Hello,
I'm playing around with collision detection and my current situation is this: I have a ball which is controlled by WASD, and I have a wall object. The ball is 16x16 px, the wall is 32x32. I have gotten to the point where I can successfully detect a collision and thus stop movement. However, since the ball moves a variant amount of pixels each frame, the distance it stops from the wall object varies, and it almost never stops perfectly side by side. What I want is to make it so that the ball stops right at the wall.
I can't come up with a good solution how to get this done. I get the collision and I get the overlap, but I don't understand how I can calculate a new position for the ball based on this overlap. Here's my current code which obviously doesn't work as intended (sorry for the C# code, but I'm sure you can all understand it, it's not all that important to my question anyway):
FloatRect overlap;
if (CheckCollision(ball.sprite.GetGlobalBounds(), wall.sprite.GetGlobalBounds(), out overlap))
{
new_pos.X = new_pos.X + overlap.Width;
new_pos.Y = new_pos.Y + overlap.Height;
ball.sprite.Position = new_pos;
}
The CheckCollision function is simply doing a normal FloatRect intersect call. The problem here, of course, is that what I want to do to new_pos depends on where the intersection happened. If the ball hits the wall from the left, I want to subtract the overlap width, but if I hit it from the right, I want to add the width. In both cases, I don't want to mess with the Y value. However, if I hit the wall from the top, I obviously want to subtract the height of the overlap.
I'm just really confused since it seems like I would need quite a few of conditionals to find out what collision it is before I can calculate the new position, it seems like there must be a smarter way to do it.
If you want to put code in your answer, feel free to use C++ if you prefer, I have no problem translating it for my needs.