【问题标题】:Move object in the direction of it's rotation沿旋转方向移动对象
【发布时间】:2017-01-11 02:06:20
【问题描述】:

我有一个持续旋转的物体,它会发射子弹。我希望子弹按照它们的方向前进。

physics.setGravity( 0, 0 )

fireBullets = function (  )
    local bullet = display.newRect( sceneGroup,0,0, 40, 40 )
    bullet:setFillColor( 0, 1, 0 )

    local h = player.height
    local posX = h * math.sin( math.rad( player.rotation ))
    local posY = h * math.cos( math.rad(player.rotation ))
    bullet.x = player.x + posX
    bullet.y = player.y - posY
    bullet.rotation = player.rotation

到目前为止一切都很好,子弹会随着玩家的精确旋转而出现。

    local angle = math.rad( bullet.rotation )
    local xDir = math.cos( angle )
    local yDir = math.sin( angle )

    physics.addBody( bullet, "dynamic" )
    bullet:setLinearVelocity( xDir * 100, yDir * 100)
end

他们没有按照自己的方向前进,他们似乎在向右移动。我的计算出了什么问题?

【问题讨论】:

    标签: lua rotation coronasdk


    【解决方案1】:

    您可以为 x/y 翻转 sin/cos 并在 y 上使用 -velocity。

    这是一个有用的重构:

    local function getLinearVelocity(rotation, velocity)
      local angle = math.rad(rotation)
      return {
        xVelocity = math.sin(angle) * velocity,
        yVelocity = math.cos(angle) * -velocity
      }
    end
    

    ...你可以替换:

    local angle = math.rad( bullet.rotation )
    local xDir = math.cos( angle )
    local yDir = math.sin( angle )
    
    physics.addBody( bullet, "dynamic" )
    bullet:setLinearVelocity( xDir * 100, yDir * 100)
    

    与:

    physics.addBody( bullet, "dynamic" )
    local bulletLinearVelocity = getLinearVelocity(bullet.rotation, 100)
    bullet:setLinearVelocity(bulletLinearVelocity.xVelocity, bulletLinearVelocity.yVelocity)
    

    【讨论】:

      猜你喜欢
      • 2013-01-04
      • 1970-01-01
      • 2023-04-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-09
      • 1970-01-01
      相关资源
      最近更新 更多