[英]Inserting spawned objects into a group and removing the scene
基于下面的代码块,我有两个主要问题:
(1)在这两个生成函数中,即使我已经命名了sceneGroup并将生成的对象插入到新的组中,sceneGroup:insert()方法仍返回nil。 为什么返回nil值?
(2)由于玩家死亡而进入下一个场景时,如何销毁当前场景? 我尝试获取当前场景并以这种方式将其删除,但是它没有用。
local function spawnObjects()
local bananas = display.newGroup()
sceneGroup:insert(bananas)
bananas = display.newImageRect("object_bananas.png", 30, 20);
physics.addBody(bananas, "dynamic", {bounce = 0.3, radius = 9.5});
bananas.x = math.random(0, 320);
bananas.y = -40;
transition.to( bananas, {time = math.random(6000, 10000), x = math.random(10, 310)+1 , y = 600, });
-- function to handle the collision on the bananas
function bananas:collision(e)
-- only perform logic when the bananas are colliding with monkey
if (e.other.class == "monkey") then
updateScore()
-- cannot remove objects during a collision, so wait a short moment for it to end
timer.performWithDelay(100, function()
-- remove the bananas
display.remove(self)
end, 1)
end
-- always return true because we have handled the collision
return true
end
-- attach a collision listener to the bananas
bananas:addEventListener("collision",bananas)
return bananas
end
local total_bananas = 15
tmr = timer.performWithDelay(2000, spawnObjects, total_bananas);
local function spawnObjects()
local coconut = display.newGroup()
sceneGroup:insert(coconut)
coconut = display.newImageRect("coconut.png", 30, 35)
physics.addBody(coconut, "dynamic", {bounce = 0.5, radius = 11.5});
coconut.x = math.random(0, 320);
coconut.y = -40;
transition.to( coconut, {time = math.random(6000, 10000), x = math.random(10, 310) , y = 600, });
-- function to handle the collision on the bananas
function coconut:collision(e)
-- only perform logic when the coconut is colliding with monkey
if (e.other.class == "monkey") then
-- cannot remove objects during a collision, so wait a short moment for it to end
timer.performWithDelay(1, function()
-- remove the coconut
display.remove(self)
end, 1)
composer.gotoScene("scene_gameOver")
end
-- always return true because we have handled the collision
return true
end
-- attach a collision listener to the bananas
coconut:addEventListener("collision", coconut)
return coconut
end
local total_coconut = 15
tmr = timer.performWithDelay(2000, spawnObjects, total_coconut);
暂时忘掉SceneGroup。 场景是一个对象,其中具有display.newGroup()作为对象的一部分。 它是被称为“视图”的成员。 也就是说,“ scene.view”是该组。
因为您可以使用Composer做一些高级的事情,例如在一个组中有多个场景(并非我会推荐这样做),所以场景的事件函数(例如scene:create())以面向对象的方式处理。 通过在场景和创建之间使用冒号运算符(:),您将传递一个称为“ self”的隐式参数,该参数是触发事件的场景对象。 在大多数情况下,自我和场景是同一回事。
为了方便开发人员,我们在事件函数中局部引用了scene.view(self.view),以使其易于使用。 如果您需要在这些事件功能之一之外访问场景的视图组,只需执行以下操作:
scene.view:insert( displayObjectOfYourChoice )
或者您可以本地化自己的sceneGroup变量:
local sceneGroup = scene.view
并像您喜欢的那样继续使用sceneGroup。
抢
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.