【问题标题】:Collision Detection with lua using Corona使用 Corona 的 lua 碰撞检测
【发布时间】:2015-02-09 16:13:51
【问题描述】:

我在为特定碰撞检测表中的所有对象时遇到问题。只有当桌子上的第一个物体被雪球击中时,我才能使分数增加。这是我用于对象创建和碰撞的代码。按下按钮后,我有一个 createSnowBall() 函数调用。这部分工作正常。

local physics = require("physics")
physics.start()
physics.setGravity( 0, 0 )

local snowBalls = {}
local ornaments = {}
local score = 0

local scoreText = display.newText( "Score: " .. score, 70, 25, native.systemBoldFont, 32 )

function createSnowBall()
    snowBall = display.newImageRect( "snowball.png", 20, 20)
    snowBall.x = gun.x
    snowBall.y = HEIGHT - 110
    physics.addBody( snowBall, { density = 1.0, friction = 1, bounce = 0, radius = 20 } )
    snowBall.isSnowBall = true
    snowBalls[#snowBalls+1] = snowBall
    moveSnowBall(snowBall)
    return snowBall
end

function createOrnament(num)
        if num == 1 then
            ornament = display.newImageRect( "blueO.png", 30, 40)
        elseif num == 2 then
            ornament = display.newImageRect( "redO.png", 30, 40)
        elseif num == 3 then
            ornament = display.newImageRect( "greenO.png", 30, 40)
        end
    ornament.isOrnament = true
    ornaments[#ornaments+1] = ornament
    ornament.x = math.random(50, 270)
    ornament.y = 3
    local radius = 15
    physics.addBody( ornament, { density = 1.0, friction = 1, bounce = 1, radius = radius } )
    ornament:applyForce(35, 70, ornament.x + 4, ornament.y + 4)
    return ornament
end
createOrnament(math.random(1, 3))

function snowBallCollision(event)
    if event.phase == "began" then
        local target = event.other 
            if target.isSnowBall then
                score = score + 5
                scoreText.text = "Score: " .. score
            end
    end
end

ornament:addEventListener( "collision", snowBallCollision )

【问题讨论】:

  • 我尝试过使用函数 decor:snowBallCollision(event) 和一个 snowBall:addEventListener("collision", ornament) 但我遇到的问题是按下按钮时会创建雪球因此事先为零。

标签: lua coronasdk collision-detection lua-table


【解决方案1】:

出现此问题的原因是:

ornament:addEventListener( "collision", snowBallCollision )

在这里,您只需向对象添加一次侦听器,然后将其分配给先前生成但尚未销毁的对象。

因此,只需从代码中删除该行,并且无论何时调用该行:

createOrnament(math.random(1, 3))

替换为:

local myOrnament = createOrnament(math.random(1, 3)) -- Since 'createOrnament' returns the object
myOrnament:addEventListener( "collision", snowBallCollision ) -- assign listener to the newly created object

这会将侦听器分配给您的所有“myOrnament”对象。

继续编码...... :)

【讨论】:

  • 是的,我在凌晨 2 点左右发现了这一点。我在 createOrnament 函数中包含了监听器。只是简单的逻辑,当所有其他装饰表字段在函数内工作时。现在,当任何物体发生碰撞时,我的分数就会更新。我想我只是习惯于将侦听器放在所有代码的底部。你摇滚克里希纳!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-08-24
  • 2021-12-13
  • 1970-01-01
  • 2014-06-22
  • 1970-01-01
  • 2014-03-14
  • 2015-12-29
相关资源
最近更新 更多