Collision detection in J2ME
Posted by Jim on November 20th, 2008 filed in j2me, java codeI am going to show a basic exclusion collision algorithm for J2ME. Whilst the Sprite class has collision detection methods, they are not very flexible and are useless when checking how objects collide. For example, in a bat and ball game you probably will want to know which edge the ball collides with in order to bet the ball to bounce correctly.
Exclusion collision detection is done by checking where certain parts of the two items are in correspondence to each other. Basically if the highest point of item A is lower than the lowest part of item B, it is not possible for the items to collide.
In addition, you can order your method based on which direction you are expecting collisions to usually occur from. This will then be more efficient than even the box detection method offered by the Sprite class.
public boolean collisionBetween(Sprite a, Sprite b)
{
if (a.getY() > (b.getY() + b.getHeight()))
{
//Not collided b is above a
return false;
}
else
{
if ((a.getY() + a.getHeight()) < b.getY())
{
//Not collided b is below a
return false;
}
else
{
if (a.getX() > (b.getY() + b.getWidth()))
{
//Not collided b is to the left of a
return false;
}
else
{
if ((a.getX() + a.getWidth()) < b.getX())
{
//Not collided b is to the right of a
return false;
}
}
}
}
//There is a collision
return true;
}
There might be a parenthesis error in here, as I did this in notepad at work. So I couldn’t check the syntax! From the formatting — which Wordpress kindly destroyed — it looks fine though.
Bad Behavior has blocked 121 access attempts in the last 7 days.
