# Box2D: Asteroids-Like Spaceship Physics

I'm new to Box2D (JavaScript) (and the world of physics/mathematics) so I'm having a hard time working out the methods I need to use to make a spaceship act like it does in the classic arcade game Asteroids. I've tried varying methods and nothing works quite right (as I obviously don't understand what I'm doing).

For example, in Asteroids you can rotate the ship but it turns at a constant rate and won't continue to spin after you let go of the key, unlike the rest of the ship's physics. So I tried SetPositionAndAngle(position, angle-0.1) as an example to make the ship turn without having it rotate after key up, however when I then press the up key to make the ship go forward, it turns left as well as going forwards (via ApplyForce).

Can anybody give some tips on how I should be dealing with Asteroids-type spaceship physics?

Box2D is massive overkill for Asteroids.

Without Box2D, assuming you're forcing yourself to use that for some reason, you just need some basic Newtonian physics.

Velocity is your speed in a particular direction. Acceleration is your change in velocity in some particular direction.

You can take your heading (rotation), generate from that a unit vector (cos(theta), sin(theta)) and then set your acceleration to that vector +/- a particular amount depending on whether up or down is pressed.

You can then integrate your new position and velocity each frame with simple Euler integration:

velocity += dt * acceleration
position += dt * velocity


For rotating, just modify your heading angle when you press left or right directly.

You now have the same 'physics' Asteroids has. Now you just need to add in collision detection so asteroids kill your ship and your bullets kill asteroids. Simple circle-circle collision can work just fine here.

check_collision(center1, radius1, center2, radius2):
distance = square_root(center1.x * center2.x + center1.y * center2.y)
collide
else
no collide


And there you have it. Add random Asteroids spawning, lives, and bullets, and you have reimplemented Astroids exactly.

Even if you want to keep using Box2D, to use it well you need to understand Newtonian dynamics, impulses and forces, what constraints are in theory, linear and rotational dynamics, etc. It's not hard to learn it all, but you will need to take some time reading up on it (it's not really feasible to fit it all in a single SE answer). Having had introductory high school or college physics will come in extremely handy.