刚刚开始使用令人惊叹的corona sdk。
我开始创建一个简单的射击游戏。
我有以下代码:
-- Global Variables
local shot = audio.loadSound('shot.mp3')
local bg = display.newImage('bg.png')
local shoot = {}
local Main = {}
local Init = {}
local bullets = display.newGroup()
function update()
if(bullets.numChildren ~= 0) then
for i = 1, bullets.numChildren do
bullets[i].y = bullets[i].y - 8
-- Destroy Offstage Bullets
if(bullets[i].y < (-bullets[i].height-5)) then
-- bullets[i]:removeSelf()
bullets:remove(bullets[i])
display.remove(bullets[i])
return
end
end
end
end
-- Initialisation functions
function Init ()
display.setStatusBar(display.HiddenStatusBar)
local movieclip = require('movieclip')
local physics = require('physics')
physics.start()
physics.setGravity(0, 0)
end
function shoot:tap(e)
for i = 1, 15 do
local bullet = display.newImage('bullet.png')
bullet.x = 150
bullet.y = 470
bullet.name = 'bullet'
physics.addBody(bullet)
bullets.insert(bullets, bullet)
end
audio.play(shot)
end
-- Main routine
function Main ()
Init()
bg:addEventListener('tap', shoot)
Runtime:addEventListener('enterFrame', update)
end
Main()现在它“起作用了”;但是当子弹从屏幕上射出时,整个“游戏”就慢了下来,我可以清楚地看到每一个子弹都被移走了,这就减慢了游戏的速度。
也许我做得不对;我也尝试了:removeSelf()函数;同样的结果。
发布于 2011-12-05 22:08:17
我面对的是同样的problem...And得到的解决方案:
你正在使用for循环移除对象:如果你在for循环中移除对象,比如:你删除了索引1处的对象,那么当对象2循环到对象时,对象2就会移动到对象1...so,而不会检查对象2(因为它移动到了对象1的位置,而你正在检查对象3)
for j = 1, buttonGroup.numChildren do
buttonGroup[1]:removeSelf(); --this removes all childrens
end
for j = 1, buttonGroup.numChildren do
buttonGroup[j]:removeSelf(); --this removes alternative childrens
end我希望它是有用的
发布于 2013-12-22 02:04:19
我为我的游戏争取了很长很长一段时间,因为我的游戏使用了很多标签视图。我找到的解决方案是在所有需要删除的对象上使用"= nil",":removeSelf()“和".alpha = 0”。如果它们都被添加到同一个组中,并且没有其他内容,那么也可以使用它,但由于各种原因,比如组是如何在幕后建立的,这并不总是有效。
看起来你所做的是删除“bullet”的内容,但这只是一个参考,所以你说的每个bullet被删除的地方,它实际上只是从数组中删除-对象本身仍然存在,需要被置零,以防止内存泄漏和应用程序的减慢(您可能已经发现每个bullet都会使应用程序变慢,对吧?)
在删除后添加此条件,您应该设置:
if(not(bullet == nil)) then
bullet.alpha = 0;
bullet:removeSelf();
bullet = nil;
end发布于 2013-12-27 00:19:40
简单地创建一个这样的表会更容易
local bulletCache = {}然后在你的项目符号创建代码中添加
table.insert(bulletCache, myBulletObject)然后在你的退出代码和/或销毁代码中
for i = 1, #bulletCache do
--[[
--Below is not needed but just to keep your code consitant
pcall(function()
bullet.alpha = 0
end)
--]]
pcall(function()
bullet:removeSelf()
end)
pcall(function()
bullet = nil
end)
endhttps://stackoverflow.com/questions/7705439
复制相似问题