How can I detect a collision between 2 images? E.G if(Image1 collidesWith Image2){}

Recommended Answers

All 2 Replies

Simple geometry, really. Suppose the images are quadrilaterals. If any point of image1 is between the top and bottom of image2, and also between left and right of image2, then you have a collision. If image2 is a circle, it's still simple - if the pythagorean distance from any point in image1 is within distance r of image2's center point, collision. Gets a little tricky with more complicated shapes, of course.
Suppose you're dealing with a class MobileImageObject - you'd include a collidesWith(MobileImageObject) method which would include your collision logic and return a boolean. If you have multiple image shapes, and you want the collision to be realistic, you'd have to inherit from MobileImageObject and override the collidesWith method with logic for each shape.

If you want to detect collisions while the objects are moving, it's trickier. One very common error case is when image1 is moving so fast that it never actually registers a point within image2. For example, if you have a "wall" 100 units thick, and an object moving at 1000 units per tick, it's likely that it'll never register as a collision using this method.

You'd also have to determine which point or points you're going to test - obviously, you don't want to test all of the points of image1! You might do this by figuring that the leading edge or corner of an object is likely to be the best choice, so you'd have to have logic to figure out which is the leading edge.

There's a lot of thought that you could put into making this work, depending on your requirements. If you don't need to detect collisions in real time, for example if you just want to reject an attempt to drop image1 on top of image2, then obviously life's easier in a lot of ways.

Simple Geometry worked for me :) Thanks!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.