【问题标题】:How to change the angle of an object after collision in corona sdk如何在电晕sdk中碰撞后改变物体的角度
【发布时间】:2013-08-16 01:14:28
【问题描述】:

在我的游戏中,两个物体相互碰撞,但我想改变物体的角度 与另一个物体碰撞后。我希望对象在碰撞后将其方向更改为 180 度,我已经使用物理进行碰撞,任何帮助或建议.. 谢谢

【问题讨论】:

    标签: lua coronasdk


    【解决方案1】:

    尝试使用以下方法获取身体线速度的 x,y 分量:

    vx, vy = myBody:getLinearVelocity()
    

    并将其重置为:

    myBody:setLinearVelocity(-vx,-vy ) 
    

    欲了解更多信息,请访问Corona - Physics Bodies

    示例:

    local physics = require( "physics" )
    physics.start()
    
    -- Create ground and bodies ---
    local ground = display.newImage( "ground.png" )
    ground.x = display.contentWidth / 2
    ground.y = 445
    ground.myName = "ground"
    
    local crate1 = display.newCircle(0,0,30,30)
    crate1.x = 180; crate1.y = 350
    crate1.myName = "first crate"
    
    local crate2 = display.newCircle(0,0,30,30)
    crate2.x = 220; crate2.y = -50
    crate2.myName = "second crate"
    
    -- physics.setDrawMode( "debug" ) -- Uncomment this line to see the physics shapes
    
    -- Adding physics --
    physics.addBody( ground, "static", { friction=0.5, bounce=0.3 } )
    physics.addBody( crate1, { density=3.0, friction=0.5, bounce=0.3,radius = 30} )
    physics.addBody( crate2, { density=3.0, friction=0.5, bounce=0.3,radius = 30} )
    
    crate1:setLinearVelocity( 0, -400 )
    
    -- Collision function --
    local function onGlobalCollision( event )
      if ( event.phase == "began" ) then
        print(event.object1.myName .. " & " .. event.object2.myName .. " collision began" )
        vx_1, vy_1 = crate2:getLinearVelocity()     -- get the velocities of crate2
        crate2:setLinearVelocity(-vx_1,-vy_1 )      -- reset the velocities of crate2
    
        vx_2, vy_2 = crate1:getLinearVelocity()     -- get the velocities of crate1
        crate1:setLinearVelocity(-vx_2,-vy_2 )      -- reset the velocities of crate1
      end   
    end
    Runtime:addEventListener( "collision", onGlobalCollision )
    

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

    【讨论】:

    • 这个解决方案对我不起作用,我试过了。您能否告诉我在哪里包含此代码或提供此类解决方案的链接。在我的例子中,两个物体都在碰撞,因为它们是物理物体,碰撞后另一个物体向任何方向移动,但我希望它移动到 180 度,它在哪个部分碰撞并不重要..
    • 感谢您的帮助.. 上面的代码对我有用,但我需要一些修改,在这个例子中,两个球都移动,但我想要一个静态的,另一个会移动并在碰撞后碰撞它会改变角度,如果我想让球移动到 90 度而不是 180 度的角度,我应该在这段代码中进行哪些更改...
    • 只需注释以下行:'crate1:setLinearVelocity( 0, -400 )' 将使一个球静止。
    • 碰撞后可以设置'crate1:setLinearVelocity(vx,vy),其中vx和vy分别是xVelocity和yVelocity。例如: crate1:setLinearVelocity(-90,0 )。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多