冠状病毒+碰撞失效。

我正在学习 Corona 并尝试使用碰撞事件。以下程序的目标是:rock 使用 transition.to 向 car 移动,并打印一行来报告碰撞的位置。

然而,它不起作用。此外,我甚至不能接收消息 "enterenter",为什么程序甚至不能进入 enter 函数呢?

我的代码如下。先谢谢您。

点赞
用户2524586
用户2524586

使用本地和全局(运行时)侦听器的工作代码:

local widget = require "widget"
local composer = require( "composer" )
local scene = composer.newScene()

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

local function onGlobalCollision( event )
        local target = event.object1
        local other = event.object2

        if ( event.phase == "began" ) then
            print( "GLOBAL: " .. target.name .. ": collision began with " .. other.name )
        elseif ( event.phase == "ended" ) then
            print( "GLOBAL: " .. target.name .. ": collision ended  with " .. other.name )
        end
    end

local function onLocalCollision( event )
    local target = event.target
    local other = event.other

    if ( event.phase == "began" ) then
        print( "LOCAL: " .. other.name .. ": collision began with " .. target.name )
    elseif ( event.phase == "ended" ) then
        print( "LOCAL: " .. other.name .. ": collision ended  with " .. target.name )
    end
end

function scene:create( event )
    print("scene:create")

    local sceneGroup = self.view

    local car = display.newRect( 100, 100, 100, 100 )
    car.name = "car"
    physics.addBody( car )

    local rock = display.newRect( 250, 250, 100, 100 )
    rock.name = "rock"
    rock:setFillColor( 0.5, 0.5, 0.5 )
    physics.addBody( rock )
    rock:addEventListener( "collision", onLocalCollision )

    sceneGroup:insert(car)
    sceneGroup:insert(rock)

    transition.to(rock,{time=4000, x = -40, y = -100})

    Runtime:addEventListener( "collision", onGlobalCollision )
end

function scene:show( event )
    if ( event.phase == "will" ) then
        print("scene:show")
    elseif ( event.phase == "did" ) then
        print("scene:show did")
    end
end

scene:addEventListener( "create", scene )
scene:addEventListener( "show", scene )

return scene

您的代码问题是两个物体都是静态的,两个静态物体无法彼此碰撞,而且在composer中没有叫做scene:enter的东西(因此它不会被调用,因此也不会有onLocalListener)。

某些物体类型会-或不会-与其他物体类型发生碰撞。在两个物理对象之间的碰撞中,至少有一个对象必须是动态的,因为这是唯一与任何其他类型发生碰撞的物体类型。有关物体类型的详细信息,请参见物理主体指南。

https://docs.coronalabs.com/daily/guide/physics/collisionDetection/index.html

这里是有关Composer API的一些信息,您将发现您应该使用scene:show

https://coronalabs.com/blog/2014/01/21/introducing-the-composer-api-plus-tutorial/

2015-09-25 22:02:09