Friday 24 May 2013

Pixel Perfect Hit Testing.

One of the fun things I have been messing with this month is CoffeeScript and the HTML5 canvas element. I regularly return to these two topics.

I took a bit of a look around at some of the gaming/rendering libraries but then realized the urge I had was to actually knock one together. Perhaps using some open source for things like tweening.

Anyway I was quite impressed with easelJS part of the createJS collection of tools for interactive graphics. If I was not just messing with code and had something I wanted to achieve I would use it.

However I have been looking through the code just to learn some of the ideas they use and one fun one stands out.

It is for pixel perfect hit testing they use for shapes they are going to render. The idea is to test whether the mouse pointer is over a shape or not.

It works for both bitmap shapes and vector based images. I like they way they solved the problem mostly because it is really simple.

The create an internal canvas that is 1 pixel by 1 pixel. Then if you want to hit test at position x,y then simply draw the graphic to this canvas but with a translation set to -x,-y in the context. Finally read single pixel on the canvas. If that pixel has color then the position x,y overlaps the shape otherwise it does not.

You need to be clear about using world or local co-ordinates and remember to clear out the pixel when you are done.

Obviously is does not handle collision between arbitrary shapes bit it is such a simple idea and not one I had thought of doing myself. I really like reading code that lets me learn new idea even if they are really obvious once you have come across them.

No comments:

Post a Comment