簡體   English   中英

測量產生的物體之間的距離

[英]measure distance between spawned objects

如何測量產生的物體之間的距離? 我使用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 )

要獲得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

要檢查“ a”和“ b”之間的距離小於200,可以執行以下操作:

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

***請注意,距離不是以像素為單位,而是相對於您為電暈設置選擇的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不變,因為它們是一個單獨的實例(彼此獨立)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM