测量生成对象之间的距离。

如何测量生成对象之间的距离? 我正在使用 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 )
点赞
用户1078537
用户1078537

使用勾股定理可以得到两个物体之间的距离

function getDistance(objA, objB)
    -- 获取x轴和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
  --在这里添加代码
end

***请注意,距离不是以像素为单位的,而是相对于您为Corona设置选择的contentWidth和contentHeight的度量。

您的生成函数可能会遇到一些麻烦,因为它不会每次调用时创建新实例,可能会一遍又一遍地重用相同的对象。尝试像这样使用工厂模式:

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

    -- 在这里对新实例进行处理
    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 newInstance
end

像这样使用它:

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

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

这样如果您删除newThing01,它应该不会影响newThing02,因为它们是独立的实例。

2014-04-07 21:58:15