lua - 如何使用 Corona SDK 有效处理对象的对象移除

标签 lua sdk coronasdk

刚刚开始使用很棒的 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() 函数;相同的结果。

最佳答案

我遇到了同样的问题......并得到了解决方案:

您正在使用 for 循环删除对象: 如果你删除 for 循环中的对象说:你删除了索引 1 处的对象,然后对象 2 移动到对象 1...所以当它循环到对象时它不会检查对象 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

希望有用

关于lua - 如何使用 Corona SDK 有效处理对象的对象移除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7705439/

相关文章:

lua - 如何设置和使用lua squish?

function - Lua十进制符号?

function - Corona SDK - 我们如何将外部函数连接到 main.lua?

lua - 使用Corona SDK时如何具有多个Lua文件?

android - '不支持的模板依赖 : Upgrade your Android Eclipse plugin' with SDK Tools v22

lua - Corona SDK 或 Lua 是否有可用的 'eval' 函数?

Android:无法将我的 ADT 版本更新到 17+

android - 无法更新 build.gradle 以使用支持库 23.0.1

coronasdk - 不同场景下的 Corona SDK 变量

ios - 如何解决上传应用程序错误 : 10. 1(不支持的 : Local iOS SDK is 10. 2 不匹配)的问题?