Corona SDK 的碰撞检测不起作用。

我有一个(能正常工作的)函数用于生成子弹:

local function shootBullets( event ) -- 它通过计时器调用
    local bullet = display.newImageRect( "images/Bullet.png", 12, 12 ) -- 创建一个子弹

    local convertedGunRotation = tankGun.rotation*( math.pi / 180 ) -- 不用担心,这只是用来计算子弹射出方向的一些数学
    local orientation = math.pi

    bullet.x = tankBody.x
    bullet.y = tankBody.y

    physics.addBody( bullet, "kinematic", { bounce = 0 } ) -- 将子弹变成一个物体,这样我就可以使用 setLinearVelocity 函数给它一个速度
    bullets:insert( bullet ) -- 将它添加到我的子弹组中

    bullet.name = "bullet" -- 用于后面的碰撞检测
    bullet.collision = onCollision -- 这两行代码用于处理碰撞,但并没有起作用。
    bullet:addEventListener( "collision", bullet )

    -- 这是我移动子弹的方式
    bullet:setLinearVelocity( 0 * math.cos( convertedGunRotation + orientation ) - 100 * math.sin( convertedGunRotation + orientation ), 0 * math.sin( convertedGunRotation + orientation ) + 100 * math.cos( convertedGunRotation + orientation ) )
end

我有四个围绕屏幕的矩形:

local leftWall = display.newRect( 0, 0, 10, _H ) -- 创建矩形
leftWall.strokeWidth = 3 -- 边框的宽度
leftWall:setFillColor( 192, 255, 255 ) -- 填充颜色以使其可见
leftWall:setStrokeColor( 192, 255, 255 )
leftWall.name = "wall" -- 给它一个名称用于碰撞检测的参考
physics.addBody( leftWall, "static" ) -- 确保它不能移动并使其成为一个物体。

-- 相同的规则适用于其他 3 个墙壁,它们围绕玩家,因此您可以使用子弹时不会错过其中任何一面。
local rightWall = display.newRect( _W - 10, 0, 10, _H )
rightWall.strokeWidth = 3
rightWall:setFillColor( 192, 255, 255 )
rightWall:setStrokeColor( 192, 255, 255 )
rightWall.name = "wall"
physics.addBody( rightWall, "static" )

local bottomWall = display.newRect( 0, _H - 10, _W, 10 )
bottomWall.strokeWidth = 3
bottomWall:setFillColor( 192, 255, 255 )
bottomWall:setStrokeColor( 192, 255, 255 )
bottomWall.name = "wall"
physics.addBody( bottomWall, "static" )

local topWall = display.newRect( 0, 0, _W, 10 )
topWall.strokeWidth = 3
topWall:setFillColor( 192, 255, 255 )
topWall:setStrokeColor( 192, 255, 255 )
topWall.name = "wall"
physics.addBody( topWall, "static" )

还有一个碰撞检测函数:

local function onCollision( event )
    print( "Here" ) -- 从未进入此处。
    -- 子弹击中了某些东西
    if event.object1.name == "bullet" then
        if event.object2.name == "enemy" then -- 我稍后再处理敌人
            -- 我稍后会做一些事情
        elseif event.object2.name == "wall" then -- 它应该撞到了一面墙
            -- 待办事项
        end
    end
end

但是,当我在 Corona 终端中运行它时,onCollision 函数中的 print("Here") 函数甚至没有被调用过。任何帮助将不胜感激。

原文链接 https://stackoverflow.com/questions/7055103

点赞
stackoverflow用户893601
stackoverflow用户893601

请查看:

http://developer.anscamobile.com/reference/index/physicsaddbody

在备注中,他们说:

注意:不应在Collision事件处理程序中使用此API。

祝你好运 =)

2011-08-14 05:07:16
stackoverflow用户667648
stackoverflow用户667648

嗯,最终我使用了以下解决办法(请注意,这只适用于你的游戏没有任何重力的情况):当我将子弹的物理体添加到物理引擎中时,我将其设为“dynamic”,并将其 isSensor 属性设置为 true。对我来说,这种方式奏效了,但我仍会保持开放,直到有人找到更好的答案(一种适用于子弹具有“运动学”属性的良好解决方案)。 (虽然对我来说是有效的...)

2011-08-14 23:34:32