测量衍生对象之间的距离

时间:2014-04-04 13:54:28

标签: lua corona

如何测量衍生物体之间的距离? 我使用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 )

1 个答案:

答案 0 :(得分: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

要检查“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不变,因为它们是一个单独的实例(彼此独立)