2014-04-04 51 views
1

我如何測量產卵物體之間的距離? 即時通訊使用timer.performWithDelay時間對象,但如果你重新啓動遊戲幾次它混亂了。所以我怎麼能說如果對象之間有200px產生一個新的。測量產卵物體之間的距離

如果我嘗試刪除對象「onComplete」它刪除新對象是否有一個簡單的修復?

holl:removeSelf() 
holl = nil 

產卵代碼:

function hollspawn() 
screenGroup = self.view  
holl = display.newRect(0, 0, math.random(10, 500), 53) 
holl.y = display.contentHeight - holl.contentHeight/2 
holl.x =display.contentWidth + holl.contentWidth/2 
holl:setFillColor(1, 0, 0) 
holl.name = "hollgameover" 
physics.addBody(holl, "static", {density=.1, bounce=0.5, friction=.2,filter=playerCollisionFilter })  
screenGroup:insert(holl) 
trans55 = transition.to(holl,{time=2000, x=display.contentWidth - display.contentWidth - holl.contentWidth/2 - 20, onComplete=pluspoint, transition=easing.OutExpo }) --onComplete=jetReady 
end 
timereholl = timer.performWithDelay( 1500 , hollspawn, 0) 
+0

這取決於您如何訪問對象,您的帖子沒有足夠的信息。還有它不清楚你正在做什麼:你試圖讓hollspawn產生一個對象,只有當其他兩個特定對象的距離超過200像素,或者*你的所有對象中的任意兩個對象比這個更遠? – Schollii

回答

1

拿到2個物體之間的距離可以使用畢達哥拉斯定理

function getDistance(objA, objB) 
    -- Get the length for each of the components x and y 
    local xDist = objB.x - objA.x 
    local yDist = objB.y - objA.y 

    return math.sqrt((xDist^2) + (yDist^2)) 
end 

要與 「一」 和「檢查的距離小於200 b「你可以這樣做:

if (getDistance(a,b) < 200) then 
    --Your code here 
end 

***請注意,距離不是以像素爲單位,而是與您爲Corona設置選擇的contentWidth和contentHeight相關的度量。

您的spawn函數可能會有一些問題,因爲它每次調用時都不會創建新的實例,可能會一遍又一遍地重複使用相同的對象。嘗試這樣的事情作爲一個工廠模式:

function spawnNewObject() 
    local newInstance = display.newRect(0, 0, math.random(10, 500), 53) 

    -- Do things to newInstance here 
    newInstance.y = display.contentHeight - (newInstance.contentHeight * 0.5) 
    newInstance.x = display.contentWidth + (newInstance.contentWidth * 0.5) 
    newInstance:setFillColor(1, 0, 0) 
    newInstance.name = "hollgameover" 

    -- Return a new instanced object 
    return newInstance 
end 

使用方法如下:

local newThing01 = spawnNewObject() 
group:insert(newThing01) 

local newThing02 = spawnNewObject() 
group:insert(newThing02) 

這樣,如果你刪除newThing01,它應該保持newThing02不變,因爲他們是一個單獨的實例(獨立於各其他)