开发者

Collision detection by color

I'm currently implemen开发者_如何转开发ting a little game in java that allows for a player to drive a car around a track.

I want the car to slow if it deviates from the track. However, because the track is rounded, using rectangles doesn't seem to be the best idea.

One idea that popped into my head was somehow using the colors of the pixels the car is on. If all the pixels of the car happen to be where the map is green, as opposed to black for the track, then I slow the car down.

Is this a good approach? If so, how do I go about doing it? Searches have just yielded the same rectangle intersection approach to collision detection.


If your cars and track can be drawn using classes that implement the Shape interface, one of the assorted contains() methods may solve the problem. There's a scale and rotate example here and a more elaborate example here.


You could do collision detection sort of like bit-blit'ing. Make the 'mask' for the car with 1's for foreground and 0's for the transparent or outside pixels. 'AND'ing the mask with the background where the car is located results in the background pixels that the car is on. Of course this 'AND' operation isn't doesn't operate on bits but rather pixel values of the background. Searching for Raster-Ops or PixBlt might lead to some solutions.


These are all good answers. If you wanted to go more with your idea of color detection, check out the Robot class in the Java API; It has a lot of cool lower level functions like getting a color value of a point on the screen (px,px), moving the cursor independent of the user, etc..


I like trashgod's answer the best, but, if you're not using the Shape class, then you may have problems.

So, here is my answer.

Firstly, anything you can draw on the screen has some granularity, so take advantage of that. You have not provided many details on how you're blitting to the screen, but, this is what I would suggest.

Use Bezier Curves. Since they are mathematically defined (and very simple to plot), you can easily, pick, say 100 points on a Bezier curve and check if the edges of your car are inside the Bezier Curve. This is probably the most accurate solution.

If you don't like math for some reason, I would suggest keeping track of a variable that contains how close the nearest patch of dirt is, and when that goes to zero, you can slow down the car.

Or (the worst solution), you can compare two patches of what is being shown on the screen (the car and the dirt), and check if the car is on the dirt. This is what the Shape.contains() method does, but, it has been written by professionals and your version is probably going to be significantly slower.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜