Preferred Slick2D Collision Detection

Started by
2 comments, last by Kobo 12 years, 8 months ago
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:

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 */
}
}


That was far from ideal though. What collision detection methods do you prefer to use?
Advertisement
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.
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

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++)
{


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?
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.
int i = 0; int j = 0

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




This topic is closed to new replies.

Advertisement