Public Group

# Preferred Slick2D Collision Detection

This topic is 2649 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## 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:

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?

##### 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 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

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?

##### 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. 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; } } } } } } 

1. 1
Rutin
42
2. 2
3. 3
4. 4
5. 5

• 9
• 27
• 20
• 14
• 14
• ### Forum Statistics

• Total Topics
633385
• Total Posts
3011600
• ### Who's Online (See full list)

There are no registered users currently online

×