Hi,
i'm new to gideros and not the best in programming. I have some trouble to add physics to a class object. "scene3" gets called in main.lua by sceneManager. In Scene3:init() i want to add a "Puck" with physics behavior. But it does not work... Can someone help? Here is the code:
-- scene3.lua: ---------------------------------------
function Scene3:init(t)
self.world = b2.World.new(0, 10, true)
self:addChild(Puck.new(100,100))
self:addEventListener("enterBegin", self.onTransitionInBegin, self)
self:addEventListener("enterEnd", self.onTransitionInEnd, self)
self:addEventListener("exitBegin", self.onTransitionOutBegin, self)
self:addEventListener("exitEnd", self.onTransitionOutEnd, self)
self:addEventListener(Event.ENTER_FRAME, self.onEnterFrame, self)
end
function Scene3:onEnterFrame()
self.world:step(1/60, 8, 3)
for i = 1, self:getNumChildren() do
local sprite = self:getChildAt(i)
if sprite.body then
local body = sprite.body
local bodyX, bodyY = body:getPosition()
sprite:setPosition(bodyX, bodyY)
sprite:setRotation(body:getAngle() * 180 / math.pi)
end
end
end
-- puck.lua: -------------------------------------------
Puck = Core.class(Sprite)
function Puck:init(xp, yp)
local puckArrow = Bitmap.new(Texture.new("puckArrow.png"))
local puckHalo = Bitmap.new(Texture.new("puckHalo.png"))
local puckBody = Bitmap.new(Texture.new("puck.png"))
puckArrow:setAnchorPoint(0.5, 1)
puckArrow:setVisible(false)
self:addChild(puckArrow)
self:addChild(puckBody)
self:addChild(puckHalo)
puckBody:setPosition(-50,-50)
puckHalo:setPosition(-100,-100)
self:setPosition(xp,yp)
local body = self.world:createBody{type = b2.DYNAMIC_BODY}
body:setPosition(xp, yp)
body:setAngle(self:getRotation() * math.pi/180)
local circle = b2.CircleShape.new(0, 0, 50)
local fixture = body:createFixture{shape = circle, density = 1.0, friction = 0, restitution = 0.2}
self.body = body
self.body.type = "Puck"
end
The Error Message is:
puck.lua:20: attempt to index field 'world' (a nil value)
Makes sense 'cause world is a local in scene3:init. But i dont know how to do it right...
Comments
Also, when posting code to the forums, you can wrap it with a tag to make it more readable, see: http://www.giderosmobile.com/DevCenter/index.php/Forum_FAQ#How_can_I_highlight_my_Lua_code_in_the_forum_post.3F
Well in this case world is the property of Scene3 class, and it would make sense to pass that instance to Puck class (because you may want to get some other properties form scene class, not only world). So here's what we can do:
P.S ninjajed by @zvardin just don't tell anyone
@ ar2rsawseen: just seen your comment. Thx a for help!
These answers came really fast
It's because puckArrow is a local in Puck:init() right?? Maybe i do hard to understand this. But puckArrow is a child of Puck. Why does it not work. I tried to make puckArrow global:
your event handler should like something like this: