2016-09-02 23 views
2

私はオブジェクトが連続的に回転しており、弾丸を発射します。弾丸がその方向に沿って前進するようにしたい。オブジェクトを回転方向に移動

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 

彼らは方向に応じて前進しませんが、右に向かって移動しているようです。私の計算に何が問題なのですか?

答えて

3

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) 
+1

どうもありがとうございました。 – Abdou023

関連する問題