Very odd physics error...

I used this code to try to make an object accelerate toward a touch:

[lua]physics=require “physics”
physics.start()

local rect=display.newRect(0, 0, 60, 60)
rect.x, rect.y=130, 638
physics.addBody(rect, {radius=75, density=0.1})

local function touchfunc(event)
local p=event.phase
local x=event.x
local y=event.y

if “ended”==p then
rect:applyForce((x/2-rect.x/2), (y/2-rect.y/2))
end
end
Runtime:addEventListener(“touch”, touchfunc)[/lua]

When I touch the screen, the rectangle will sometimes start spinning wildly. Sometimes I’ll do it, and it will stop dead. I don’t know what’s happening. It does the same thing if you use applyLinearImpulse instead of applyForce.

Any ideas? [import]uid: 147322 topic_id: 31577 reply_id: 331577[/import]

HI there,

Change [lua]rect:applyForce((x/2-rect.x/2), (y/2-rect.y/2))[/lua] to [lua]rect:applyForce((x/2-rect.x/2), (y/2-rect.y/2), rect.x, rect.y)[/lua]. The key is passing the rectangle’s center coordinates as the third and fourth paremeters. For both applyForce and applyLinearImpulse, you specify where on the object the force should be applied in the third and fourth parameters). By setting them at the center, it ensures the object won’t spin. Without those parameters, my guess is that the force is applied at the object’s local 0,0 coordinate, which would be a corner, resulting in spin.

Hope this helps.

  • Andrew [import]uid: 109711 topic_id: 31577 reply_id: 126170[/import]

HI there,

Change [lua]rect:applyForce((x/2-rect.x/2), (y/2-rect.y/2))[/lua] to [lua]rect:applyForce((x/2-rect.x/2), (y/2-rect.y/2), rect.x, rect.y)[/lua]. The key is passing the rectangle’s center coordinates as the third and fourth paremeters. For both applyForce and applyLinearImpulse, you specify where on the object the force should be applied in the third and fourth parameters). By setting them at the center, it ensures the object won’t spin. Without those parameters, my guess is that the force is applied at the object’s local 0,0 coordinate, which would be a corner, resulting in spin.

Hope this helps.

  • Andrew [import]uid: 109711 topic_id: 31577 reply_id: 126170[/import]

Thanks! That works!

quinc [import]uid: 147322 topic_id: 31577 reply_id: 126635[/import]

Thanks! That works!

quinc [import]uid: 147322 topic_id: 31577 reply_id: 126635[/import]