开发者

.NET screen objects touch detection

How would one go about detecting if two images on 开发者_StackOverflowthe 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?


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.


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.


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... :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜