2013-11-27 46 views
1

我試圖隨機產生朝向可以在屏幕上拖動的球移動的對象。基本上我只想讓用戶嘗試避免這些對象。我正在嘗試使箭產生並移向球的位置,然後在一段時間後消失。這裏的代碼適用於第一個箭頭,但是當它試圖刪除第二個時,它會調用並且錯誤地說attempt to call method 'remove self' (a nil value)在corona lua中刪除數組中的特定對象

local function cleararray() 
    if (object[objectTag]) then 
     object[objectTag]:removeSelf() 
    end 
end 

local function spawnObject() 
    objectTag = objectTag + 1 
    local objIdx = mRandom(#objects) 
    local objName = objects[objIdx] 
    object[objectTag] = display.newImage("btn_arrow.png") 
    object[objectTag].x = mRandom(320) 
    object[objectTag].y = mRandom(480) 
    object[objectTag].name = objectTag 
    print(objectTag) 
    transition.to(object[objectTag], { time=2000, y=myObject.y, x=myObject.x }) 
    timer.performWithDelay(2000,cleararray,1) 
end 
+0

嘗試調用方法'remove self'?你確定你不是指'removeSelf'?它們是有區別的。 –

+0

您的'cleararray'函數正在使用全局objectTag,它始終是您創建的最後一個對象的ID。這不會正常工作。你需要在正在超時的對象的objectTag上運行'cleararray'。 –

回答

0

cleararray通過某種方式知道要刪除哪個對象。引用objectTag將不起作用,因爲這是全球性的,所以它總是擁有迄今爲止達到的最高價值,而不是您嘗試刪除的對象的價值。相反,您可以創建一個引用該對象的閉包,以便知道要在哪個對象上進行操作。

local function spawnObject() 
    objectTag = objectTag + 1 
    object[objectTag].name = objectTag 
    ... 
    local function cleararray() 
     object[object.name]:removeSelf() 
     object[object.name] = nil 
    end 
    timer.performWithDelay(2000,cleararray,1) 
end