tags:

views:

62

answers:

3

How would one go about detecting if two images on the screen (form) were touching each other in C#?

I have a little game where I have to find out if two objects (images of objects) are touching each other.

Is there a simple way to implement this?

+1  A: 

The quickest way is to treat each object as a circle with a radius that is generally close to its perimeter, and an X,Y coordinate pair of its center. Then calculate the distance between the two objects centers, and compare that to the sum of their radii. If the sum of their radii is greater than the distance between their centers, they are touching.

jball
Just to add: You can speed up circular collision detection by comparing the square of the distance against the square of the sum of the radii - since you don't need to know the actual distance (only whether it's more or less than something), you can save a fair bit of time by omitting the costly square root.
Anon.
+2  A: 

The quick n' dirty way is to check the bounding rectangles:

if (a.left <= b.right && b.left <= a.right &&
    a.top <= b.bottom && b.top <= a.bottom)

If you want pixel-perfect detection on stuff involving transparancy, it gets a lot more complicated.

Anon.
Cool! Do you know where I can find stuff on the pixel detection you're talking about, just out of interest?
Tony
There's a quick example on CodeProject: http://www.codeproject.com/KB/game/collision3.aspx
Anon.
A: 

treating them as rectangles, you can consider getting the point coordinates of every point of each image. then check each point if one is greater than another one (point) from the other image.

something like:

/// each point represent the points in the images
Point ImageAUpperLeft; 
Point ImageAUpperRight; 
Point ImageALowerLeft; 
Point ImageALowerRight; 
Point ImageBUpperLeft; 
Point ImageBUpperRight; 
Point ImageBLowerLeft; 
Point ImageBLowerRight;
Point[] PtsList = new Point[] { ImageAUpperLeft, ImageAUpperRight, ImageALowerLeft, ImageALowerRight, ImageBUpperLeft, ImageBUpperRight, ImageBLowerLeft, ImageBLowerRight }; 

/// perform checking here, like:
if (ImageAUpperLeft coincides with ImageBUpperLeft) || (... so on so forth

I think you know the algorithm to continue this one, but if it still isnt clear you can still post your questions as comments here. would be glad to help... :)

trace