
|
Downloads
Demo: geexlab-demopack-gl21/d56-box2d/03/
|
Box2D is a nice little physics engine and it’s fun to code physics simulation with it because it’s easy to use and it has some cool features such as polygon and chain shapes.
A polygon shape is a physics actor based on a convex polygon. Just add some vertices, build the polygon and you’re ready to play with your polygon shaped actor.
Let’s see an example with a simple polygon: the triangle. Here is a Lua code snippet (from the demo) that builds a triangle:
b2_triangle = gh_box2d.world_create_actor(b2_world, -3, 10, "dynamic")
gh_box2d.actor_add_vertices(b2_triangle, -1,-1)
gh_box2d.actor_add_vertices(b2_triangle, 0, 1)
gh_box2d.actor_add_vertices(b2_triangle, 1,-1)
gh_box2d.actor_polygon_build(b2_triangle)
Now let’s see the second interesting feature: chain shapes.
A chain shape is simply a list of segments (or edges) connected together. A chain is an handy object to build static obstacles. Depending on the winding order of vertices, the edge normal will point outwards (counter-clockwise winding or CCW) or inwards (clockwise winding or CW).
Here is the code to create a chain in CCW:
chain_vertices = {
{x=10.0, y=-0.5},
{x=7.0, y=-1.2},
{x=6.0, y=-1.0},
{x=5.0, y=-1.75},
{x=4.0, y=-2.0},
{x=3.0, y=-2.5},
{x=2.0, y=-2.8},
{x=1.0, y=-2.8},
{x=0.0, y=-2.8},
{x=-0.5, y=-2.0},
{x=-1, y=-0.5},
{x=-3, y=0},
{x=-5, y=1},
{x=-6, y=2},
}
b2_chain = gh_box2d.world_create_actor(b2_world, 0, 1, "static")
local numverts = #chain_vertices
for i=1, numverts do
local vertex = chain_vertices[i]
gh_box2d.actor_add_vertices(b2_chain, vertex.x, vertex.y)
end
gh_box2d.actor_chain_build(b2_chain)
A demo that shows polygon and chain shapes in action is available in the OpenGL 2.1 demopack (geexlab-demopack-gl-21/d56-box2d/03/). This demo requires GeeXLab 0.37.0.
The d56-box2d/03/ demo is available in two versions: gl21 and gl32. The OpenGL 3.2 version can draw polygon shapes with more than four vertices. A helper library in Lua (polygon.lua) does all the dirty job.