2
votes

I have an object that is rotating continuously, and it fires bullets. I want the bullets to travel forward according to their direction.

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

So far so good, the bullets appear with the exact rotation of the player.

    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

They don't move forward according to their direction, they seem to be moving towards their right. What's wrong with my calculation?

1

1 Answers

3
votes

You can flip sin/cos for x/y and use -velocity on y.

Here is a useful refactoring:

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

...and you can replace:

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)

with:

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