Monday, August 14, 2017

java - Breakout Collision: Detecting the side of collision


I am writing a breakout clone (my first game) and am totally stuck as to how I figure out which side of the brick was hit.


I have a collision detection method that looks like this:


DetectCollision(Object a, Object b)

x = distance(a.x, b.x);
y = distance(a.y, b.y);

if (x is smaller than the combined width & y is smaller is than combined height {

return true;
}
return false;

This works totally fine, but I need to know the side of the collision, and location relative to the center in order to respond properly.


I've spent the past few days snooping around but am lost.



Answer



This can all be gleaned from the position of the ball relative to the position of the brick it collided with.


Once you have detected a collision:


if(ballPosition.y <= brickPosition.y - (brickHeight/2))

//Hit was from below the brick

if(ballPosition.y >= brickPosition.y + (brickHeight/2))
//Hit was from above the brick

if(ballPostion.x < brickPosition.x)
//Hit was on left

if(ballPostion.x > brickPosition.x)
//Hit was on right


The first two check to see if the ball is above or below the brick. If neither than it must be next to the brick, so check which side it's on. This will need to be tweeked to fit where you're taking the location from, i.e. brickPosition is the center of the brick or brickPosition is the top left corner.


No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...