Search code examples
cocos2d-iphonebox2dchipmunklove2dlibgosu

Pushing a spaceship around


I have a spaceship with two thrusters on it's base, one on the left and one on the right.

When the right thruster is on it should push the space ship in a parabolic curve towards the left as it is accelerating. and the reverse for the left thruster.

How do I implement this?

I've found something called "radian impulse" on box2d, would this do the job?

I would also like the physics the reverse the right thrust for a little bit (a bit like one of those cheap RC cars with just the one button) but only if the other thruster was used within a certain amount of time prior.

A working example (or something pointing in the right direction) with any library would suffice.


Solution

  • When you have rockets off center and only one fires, you are giving your ship torque. To simulate this you would need to split your rocket's thrust into two components. First one pushes your ship forward (in direction in which it is facing), second increases your rate of rotation. Example:

    pos_x,pos_y - position
    vel_x,vel_y - velocity
    angle - angle where ship is facing in deg
    angle_vel - speed of rotation in deg/s
    thrust - how much to add to speed
    torque - how much to add to angle
    thruster_left, thruster_right - boolean, true if left or right truster is firing
    
    function love.update(dt)
        if thruster_left then
            angle_vel=angle_vel+dt*torque
        end
        if thruster_right then
            angle_vel=angle_vel-dt*torque
        end
        angle=angle+angle_vel
        vel_x=vel_x+thrust*math.sin(math.rad(angle))*dt
        vel_y=vel_y-thrust*math.cos(math.rad(angle))*dt
        pos_x=pos_x+vel_x*dt
        pos_y=pos_y+vel_y*dt
    end