It looks like you're new here. If you want to get involved, click one of these buttons!
--include box2d library require "box2d" game = gideros.class(Sprite) --on game initialization function game:init() self.world= b2.World.new(0,10,true) --run world self:addEventListener(Event.ENTER_FRAME, self.onEnterFrame, self) --remove event on exiting game self:addEventListener("exitBegin", self.onExitBegin, self) local debugDraw = b2.DebugDraw.new() self.debugDraw=debugDraw self.world:setDebugDraw(debugDraw) self:addChild(debugDraw) self.layer=Sprite.new() self:addChild(self.layer) local bbody = self.world:createBody{type = b2.DYNAMIC_BODY,position ={x=200, y=10}} local shotball = Bitmap.new(Texture.new("images/ball.png")) local bradius = shotball:getWidth()/2 local bcircle = b2.CircleShape.new(0, 0, bradius) local bfixture = bbody:createFixture{shape = bcircle,density = 0.7, restitution = 0.6, friction = 0.2, filter = {categoryBits = 2, maskBits = 1}} shotball:setAnchorPoint(0.5,0.5) bbody:setAngle(shotball:getRotation() * math.pi/180) shotball.body = bbody shotball.body.type = "ball" shotball:setPosition(400,100) self.layer:addChild(shotball) end function game:onEnterFrame(event) self.world:step(1/60, 10,8 ) for i = 1, self:getNumChildren() do --get specific sprite local sprite = self:getChildAt(i) print(i) -- check if sprite HAS a body (ie, physical object reference we added) if sprite.body then --update position to match box2d world object's position --get physical body reference local body = sprite.body --get body coordinates local bodyX, bodyY = body:getPosition() --apply coordinates to sprite sprite:setPosition(bodyX, bodyY) --apply rotation to sprite sprite:setRotation(body:getAngle() * 180 / math.pi) end end end --removing event on exiting game --just in case you're using gameManager function game:onExitBegin() self:removeEventListener(Event.ENTER_FRAME, self.onEnterFrame, self) end |
Comments
local shotball = Bitmap.new(Texture.new("images/ball.png"))
should be:
self.shotball = Bitmap.new(Texture.new("images/ball.png"))
You need to expose the body also with: self.body=bbody in "Init" function
and then in "onEnterFrame" handler:
you need self.shotball:setPosition(self.body:getPosition())
self.shotball:setRotation(self.body:getRotation())
The problem is that you assign bbody to shotball object and thus both have local scope inside "Init" function and are not exposed as subobjects of the class "game"
Easiest fix would be (provided that you add all physics bodies to the layer) is to change one line in you onEnterFrame method: