Sign in to follow this  
David.M

Preferred Slick2D Collision Detection

Recommended Posts

I was thinking of ways to get collision detection out of slick. I made my very first game using swing and the 2D APIs included in Java. For its detection I cycled through my sprites (stored in an ArrayList) with a nested loop and compared rectangles. Something like this:

[code]for(int i = 0; i < sprites.size(); i++)
{
Sprite firstSprite = sprites.get(i);
Rectangle first = new Rectangle(firstSprite.getXPos(), firstSprite.getYPos(), firstSprite.getWidth(), firstSprite.getHeight());
for(int j = 0; j < i; j++)
{
Sprite secondSprite = sprites.get(j);
Rectangle second = new Rectangle(secondSprite.getXPos(), secondSprite.getYPos(), secondSprite.getWidth(), secondSprite.getHeight());
if(first.intersects(second))
/** Do stuff */
}
}[/code]

That was far from ideal though. What collision detection methods do you prefer to use?

Share this post


Link to post
Share on other sites
You are doing far too many comparisons. At the very least j should start from i on the inner compare instead of zero, since the first i th values have ready been evaluated against every other value in a previous pass.

Share this post


Link to post
Share on other sites
You're right. That's not actually what I was using. I was trying to remember what I did since I didn't have the source with me. I've got

[code]for(int i = 0 - 1; i < sprites.size(); i++)
{
myFirst = sprites.get(i); /** assign sprite to first */
firstRect = new Rectangle(myFirst.getXPos(), myFirst.getYPos(), myFirst.getWidth(), myFirst.getHeight());
for(int j = i + 1; j < sprites.size(); j++)
{[/code]

But the specific code didn't really have anything to do with the question. Would you recommend using rectangles and the intersect() method for collision?

Share this post


Link to post
Share on other sites
This is assuming 0, 0 is the top left. I think this is probably the fastest way to do it if you're working with rectangles. Using rectangles is really fast and if it is close enough for your application, it will probably be the best. If you need something more accurate you can use barycentric coordinates but I think that is a more expensive check.[code]
int i = 0; int j = 0

for(i = 0; i < num_objects ; i++){
for(j = i+1; j < num_objects; j++){
if(objects[i].leftedge < objects[j].rightedge){
if(objects[i].rightedge > objects[j].leftedge{
if(objects[i].topedge < objects[j].botedge){
if(objects[i].botedge > objects[j].topedge){
return true;
}
}
}
}
}
}



[/code]

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this