简体   繁体   中英

Simple physics objects in Corona/Lua

Not having any luck in the Corona forums, so I thought I'd try here.

I'm simply trying to create an object with a pivot joint. Seems simple but it's just not working.

I just can't figure out how to add bodies to the physics system if those bodies are part of an object that is created in a separate file (class). Hope someone can help - been struggling for weeks on this.

Here is my code:

main.lua :

local JointedObj = require("JointedObj")

local physics = require("physics")
physics.start()

local o = JointedObj.new()
o.x = 50
o.y = 200

local wall = display.newRect( 350, 10, 50, 300 )
physics.addBody ( wall, "static", {density=1, friction=1, bounce=.5})

local floor = display.newRect( 0, 300, 400, 10 )
physics.addBody ( floor, "static", {density=1, friction=1, bounce=.5})

--toss the object against the wall
o:toss(120, -160, o.x, o.y)

JointedObj.lua :

module(..., package.seeall)

--constructor
function new()
local obj = display.newGroup()

local red = display.newImageRect( "images/red.png", 27, 18 )
local blue = display.newImageRect( "images/blue.png", 11, 9 )
blue.x = -16

obj:insert(red)
obj:insert(blue)

function obj:toss(xForce, yForce, xPos, yPos )

    --THIS WORKS, BUT OBVIOUSLY THE OBJECT HAS NO JOINTS
    --physics.addBody( obj, "dynamic", {density=1, friction=1, bounce=0.3} )
    --obj:applyForce( xForce, yForce, xPos, yPos )


    --THIS IS WHAT I WANT TO DO. AS-IS, THE OBJECT JUST FALLS THROUGH EVERYTHING
    physics.addBody( red, {density=1, friction=1, bounce=0.3} )
    physics.addBody( blue, {density=1, friction=1, bounce=0.3} )
    myJoint = physics.newJoint( "pivot", red, blue, 0,0 )
    myJoint.isLimitEnabled = true
    myJoint:setRotationLimits( -30, 30 )
    --obj:applyForce( xForce, yForce, xPos, yPos )  --THIS THROWS A NIL ERROR IF UNCOMMENTED


end


return obj;
end

Physics don't work between groups, only within a group. That's done on purpose to allow for moving cameras done using groups. Refer to the Egg Breaker demo to see what I mean. The entire scene is in a group that moves around, but objects within the group don't react to the group moving.

Incidentally, the reason that last line throws an error is because you can only use applyForce on a physics body and you haven't set a physics body on "obj", only on "red" and "blue".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM