Detecting collision between ball (circle) and brick(rectangle)?
Posted
by
James Harrison
on Game Development
See other posts from Game Development
or by James Harrison
Published on 2013-03-17T21:13:05Z
Indexed on
2013/11/12
22:05 UTC
Read the original article
Hit count: 310
Ok so this is for a small uni project. My lecturer provided me with a framework for a simple brickbreaker game. I am currently trying to overcome to problem of detecting a collision between the two game objects. One object is always the ball and the other objects can either be the bricks or the bat.
public Collision hitBy( GameObject obj )
{
//obj is the bat or the bricks
//the current object is the ball
// if ball hits top of object
if(topX + width >= obj.topX && topX <= obj.topX + obj.width &&
topY + height >= obj.topY - 2 && topY + height <= obj.topY){
return Collision.HITY;
}
//if ball hits left hand side
else if(topY + height >= obj.topY && topY <= obj.topY + obj.height &&
topX + width >= obj.topX -2 && topX + width <= obj.topX){
return Collision.HITX;
}
else return Collision.NO_HIT;
}
So far I have a method that is used to detect this collision. The the current obj is a ball and the obj passed into the method is the the bricks. At the moment I have only added statement to check for left and top collisions but do not want to continue as I have a few problems.
The ball reacts perfectly if it hits the top of the bricks or bat but when it hits the ball often does not change directing. It seems that it is happening toward the top of the left hand edge but I cannot figure out why.
I would like to know if there is another way of approaching this or if people know where I'm going wrong.
Lastly the collision.HITX calls another method later on the changes the x direction likewise with y.
© Game Development or respective owner