Wednesday, July 6, 2011

Your Polygons are Hitting Each Other

While working on HTML5 games, I sometimes need something in JavaScript that I'm not able to find. On one such occasion I found myself in need of a JavaScript polygon object that would support collision detection with other polygons. This algorithm, using the Separating Axis Theorem, is well-known and had many implementations in other languages. It wasn't too difficult to convert it to JavaScript. While I was at it, I added methods to support determining if the polygon contains a given point (to detect if I was clicking on it) and rotating the polygon.

You can see what I came up with here, and I have a test page for it here.

As you can see by viewing the source of the test page, it is fairly easy to use. It is designed to combine with the HTML5 canvas element.

To create a polygon centered at a given point and using center-relative coordinates for the vertices, you do something like this:
var poly = new Polygon( { x: 50, y: 50 }, "#00FF00");
poly.addPoint( { x: -20, y: -20 } );
poly.addPoint( { x: -20, y: 20 } );
poly.addPoint( { x: 20, y: 20 } );
If you want to use all absolute coordinates for the vertices, you can do that too:
var poly = new Polygon( { x: 50, y: 50 }, "#00FF00");
poly.addAbsolutePoint( { x: 130, y: 130 } );
poly.addAbsolutePoint( { x: 130, y: 170 } );
poly.addAbsolutePoint( { x: 170, y: 170 } );
To rotate, just call the rotate method with the number of radians you want to rotate. Remember, to convert degrees to radians, multiply by Pi/180.
poly.rotate(0.78539); // 45 degrees
So now you have no excuse for not making a fun HTML5 canvas game. I'd like to see a game about cheese-making. I think that would be awesome.