406 Not Acceptable

Tag: j2me code

Collision detection in J2ME

by Jim on Nov.20, 2008, under Java, j2me, java code

I 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.

Leave a Comment :, , more...

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Visit our friends!

A few highly recommended friends...