物体沿着它的旋转方向移动

我有一个不断旋转并发射子弹的物体。我想让子弹根据它们的方向向前移动。

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

它们不会根据自己的方向向前移动,似乎朝向它们的右侧移动。我的计算出了什么问题?

点赞
用户1504668
用户1504668

你可以交换 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)
2016-09-02 23:45:30