Automatically triggering standard spaceship controls to stop its motion

Posted by Garan on Game Development See other posts from Game Development or by Garan
Published on 2012-12-30T23:36:50Z Indexed on 2013/07/02 23:19 UTC
Read the original article Hit count: 224

Filed under:
|

I have been working on a 2D top-down space strategy/shooting game. Right now it is only in the prototyping stage (I have gotten basic movement) but now I am trying to write a function that will stop the ship based on it's velocity. This is being written in Lua, using the Love2D engine.

My code is as follows (note- object.dx is the x-velocity, object.dy is the y-velocity, object.acc is the acceleration, and object.r is the rotation in radians):

function stopMoving(object, dt)
    local targetr = math.atan2(object.dy, object.dx)
    if targetr == object.r + math.pi then
        local currentspeed = math.sqrt(object.dx*object.dx+object.dy*object.dy)
        if currentspeed ~= 0 then
            object.dx = object.dx + object.acc*dt*math.cos(object.r)
            object.dy = object.dy + object.acc*dt*math.sin(object.r)
        end
    else
        if (targetr - object.r) >= math.pi then
            object.r = object.r - object.turnspeed*dt
        else
            object.r = object.r + object.turnspeed*dt
        end
    end
end

It is implemented in the update function as:

if love.keyboard.isDown("backspace") then
    stopMoving(player, dt)
end

The problem is that when I am holding down backspace, it spins the player clockwise (though I am trying to have it go the direction that would be the most efficient at getting to the angle it would have to be) and then it never starts to accelerate the player in the direction opposite to it's velocity.

What should I change in this code to get that to work?

EDIT :

I'm not trying to just stop the player in place, I'm trying to get it to use it's normal commands to neutralize it's existing velocity.

I also changed math.atan to math.atan2, apparently it's better. I noticed no difference when running it, though.

© Game Development or respective owner

Related posts about lua

Related posts about love2d