Corona SDK physics - apply force in particular direction?
I'm new to Corona and as a learning exercise I'm creating a simple game of "keepie uppie" (http://en.wikipedia.org/wiki/Keepie_uppie) using the Corona SDK physics engine.
I have all aspects working correctly, except the ball motion on "kick". I'm using the touch event "began" phase to apply a kick, via the applyLenearImpulse method.
My issue is that the ball is generally behaving as if force is being applied from above, causing it to shoot towards the game environment's floor. This is despite the force being applied at the point of contact on the ball.
I have come up with the following workaround:
function ball:touch( event )
-- only allow taps in bottom half of ball
if ( event.y > ball.y and event.phase == "began" ) then
-- temporarily move floor to just below ball
floor.y = ball.y + ballSize
local flipx = 0
if(event.x > ball.x) then
flipx = event.x - ballSize
elseif(event.x < ball.x) then
flipx = event.x + ballSize
else
flipx = event.x
end
ball:applyLinearImpulse( 0, kickForce, flipx, event.y)
end
end
The above works by temporarily movin开发者_如何转开发g the floor position to just under the ball before the force is applied (the floor is then moved back to the correct position via an enterFrame event listener).
I also found that with this solution I had to flip the x position of the event touch, or it would otherwise bounce horizontally opposite to the expected direction.
The above is clearly not ideal. Should I be stopping the ball motion before applying the force and, if so, how? Or am I taking the wrong approach completely?
applyLinearImpulse is the command you want to use for this, but in all your workarounds you didn't mention the first adjustment I would try: reversing the direction of the force applied. The code you posted doesn't tell us the value of "kickForce"; have you tried negating that?
physics = require( "physics" )
physics.start()
physics.setGravity( 0, 9.8 )
ball = display.newCircle(400,100,100,100)
physics.addBody(ball)
function ballf(event)
if event.phase == "ended" then
vx, vy = ball:getLinearVelocity()
ball:setLinearVelocity( -vx, -vy )
end
end
ball:addEventListener("touch", ballf)
is a simple way to "bounce" a ball on click.
what it does:
function ballf(event)
if event.phase == "ended" then
vx, vy = ball:getLinearVelocity()
ball:setLinearVelocity( -vx, -vy )
end
end
if the click event has ended, it takes the current balls linear velocity and inverses it.
I dunno what your code was doing (couldn't see how to run it.) so I made that in a minute :)
been loving corona for less than a week <3
精彩评论