function spawnRBird( x,y )
print("\n entered into spawnred");
rBird = display.newSprite (sheet, seqData);
rBird.x = x;
rBird.y = y;
rBird:setSequence("rBird")
rBird.anchorX = 0;
rBird.anchorY = 1;
physics.addBody(rBird, "dynamic", {density=1, bounce=0.5, friction=0.5})
rBird:play();
rBird:addEventListener( "collision", birdCollision );
I am getting:
attempt to call method 'applyForce' (a nil value)
when I click on the screen after spawning red bird rBird
object inside rBirdJump
is becoming nil please explain in corona lua
function rBirdJump( event )
if (event.phase == "began") then
rBird:applyForce(0, -50, redBird.x, redBird.y)
rBird:setLinearVelocity( 0, -10 )
rBird.isFixedRotation = true;
end
end
Runtime:addEventListener("touch", rBirdJump);
--timer.performWithDelay( 1000, function Runtime:addEventListener("touch", rBirdJump) end, 1 )
end
Do you know for a fact that spawnRBird
is being called before you touch the screen? Also the message indicates that rBird
is not nil but that applyForce
is not a method on rBird
. This implies that rBird has been removed from physics after being spawned, or removed as a display object (which does not make it nil, just removes certain methods from it).
If this doesn't help you find the problem you will have to post the file as you have it instead of just portions.
The error occurs because rBird is not a physics object when the function is called.
In your spawnBird function, you are initializing rBird and adding it to physics. You are declaring rBird to be a global variable. This is generally a bad programming practice and should not be adapted because it might lead to major memory leaks.
-- forward reference to your created redBird. Initialize as nil to make sure the variable is assigned a value after its added in physics. local redBird = nil function spawnRBird( x,y ) print("\\n entered into spawnred"); local rBird = display.newSprite (sheet, seqData); rBird.x = x; rBird.y = y; rBird:setSequence("rBird") rBird.anchorX = 0; rBird.anchorY = 1; physics.addBody(rBird, "dynamic", {density=1, bounce=0.5, friction=0.5}) redBird = rBird rBird:play(); rBird:addEventListener( "collision", birdCollision );
By using the variable redBird in the later code, you can make sure that you are using a phusics object as you are assigning it a value after it is added in physics.
function rBirdJump( event ) if (event.phase == "began" and redBird ~= nil) then redBird:applyForce(0, -50, redBird.x, redBird.y) redBird:setLinearVelocity( 0, -10 ) redBird.isFixedRotation = true; end end Runtime:addEventListener("touch", rBirdJump); --timer.performWithDelay( 1000, function Runtime:addEventListener("touch", rBirdJump) end, 1 )
确保您已开始物理:
physics.start();
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.