Game Development Reference
In-Depth Information
function onClick(down)
body:setLinearVelocity(0,0)
body:applyLinearImpulse(0,1)
end
MOAIInputMgr.device.mouseLeft:setCallback(onClick)
Now every time we click the left mouse button, we reset the velocity to 0 and then apply a linear
impulse of 0,1, which applies an impulse of 0 on the x-axis and 1 on the y-axis. This makes the
object jump upward.
Chipmunk Physics
We can also use Chipmunk physics in Moai. The principles for this are similar to those in Box2D. We
first we need to create the Chipmunk world space using the MOAICpSpace class:
space = MOAICpSpace.new()
space:setGravity(0,-2000)
space:setIterations(5)
space:start()
The iterations are the number of calculations performed to determine if bodies are in collision with
each other. A larger number of iterations will provide a much smoother and better physics simulation;
however, this will take up a lot of CPU time and processing. On the other hand, if we use a smaller
value for iterations, less CPU power is required, but the motion may seem too bouncy and unrealistic.
To create a physics body, we can use the MOAICpBody class, which returns a Chipmunk physics body.
We can then add a fixture as a polygon body to the physics body.
poly = {-32, 32, 32, 32, 32, -32, -32, -32}
mass = 1
moment = MOAICpShape.momentForPolygon (mass, poly)
body = MOAICpBody.new(1, moment)
space:insertPrim(body)
shape = body:addPolygon( poly )
shape:setElasticity( 0.8 )
shape:setFriction( 0.8 )
shape:setType( 1 )
space:insertPrim( shape )
When we run the code now, the object will fall right off the screen. Let's create a floor-type object so
that the physics body doesn't fall off the screen:
body = space:getStaticBody()
x1,y1,x2,y2 = -320, -240, 320, -240
shape = body:addSegment(x1,y1,x2,y2)
shape:setElasticity(1)
shape:setFriction(0.1)
shape:setType(2)
space:insertPrim(shape)
 
Search WWH ::




Custom Search