Friday, March 21, 2014

Polygon Slicing With Corona SDK

As we all know by now, Corona SDK includes the fantastic 2D physics engine Box2D. Play with this for long enough and knowing how to manipulate polygons becomes very useful indeed. I've wanted to implement everything from Angry Birds to iSlash, so it was awesome to see Corona Labs include the new display.newOutline() function in a recent build.

This cool function basically takes a PNG with web transparency and returns a table of x,y coordinates for the circumference polygon of the visible pixels in the PNG. That polygon can then be plugged into a new constructor parameter of the physics.addBody() function to actually create a physics body against an image for that image's outline.

I wanted to take that further, ala iSlash, and decided to produce a library which would take the outline polygon and the end points of a line and separate the polygon into sliced parts. I won't go into the painful details of trying to dig up the code from the internet but suffice to say that code I found was either unintelligable enough to use or simply a mass of maths that I couldn't fathom.

Fast forward a few days and having tried at least 3 different methods I finally hit upon a winner. Here's the proof, running on Mac Corona simulator...



[View full size video]

As you can see, the intersection code works both for a single line cutting straight through the object at any any angle and even re-entering the polygon multiple times. It also handles a hand-drawn curve which, likewise, can start anywhere and enter/exit the shape as often as required. This allows quite a powerful set of options ranging from effects seen in iSlash to cutting shapes into unordered pieces.

I won't be posting the code this time as I fully intend to use this in my own productions. If you would like to implement this in your own production please get in touch via the Corona forums or on twitter: @horacebury

No comments:

Post a Comment