How to Add Realistic Motion to Your HTML5 Game
Take a look at space.html. This simple game provides a good example for applying realistic motion to your HTML5 game. It utilizes the control scheme made famous in the classic games Asteroids and Spacewar! (Though Asteroids is better-known, Spacewar! is by far the earlier and more influential game.)
Click here to get the full experience.
How to add a force vector to your game’s object
The ship is controlled by the arrow keys, but Newton’s effect is easier to see in space than on the ground (no pesky drag forces to get in the way). The left- and right-arrow keys rotate the ship, but they do not affect the ship’s motion. The up arrow fires a rocket, which adds a force vector in the direction the ship is currently facing.
Here’s the code:
How to simulate space in your game
Here’s the rundown:
Begin the example in the normal way.
Like most simpleGame demos, begin with a sprite and a scene. Because the ship will have a custom method, you make it a unique object.
Give the ship a checkKeys() method.
The checkKeys() method looks for key presses and changes the ship’s behavior accordingly.
Change the image angle.
A sprite actually has two distinct angles. It can have an angle that it’s pointing (called the imgAngle in simpleGame) and the angle it’s moving (called the moveAngle). When you change the angle, you’re changing both the movement and the image angles on the assumption that the object will simply travel in the direction it’s facing.
For simple examples this is fine, but many kinds of motion require decoupling the image and motion angles. The changeImgAngleBy() method allows you to change the direction the image is pointing without changing the motion angle. (There is a changeMotionAngle() method, too, but it isn’t used very often.)
Add a force vector to simulate thrust.
When the user presses the up arrow, the ship fires its main rockets. This adds a small force vector in the direction the ship is currently facing. Use the getImgAngle() method to determine the direction the ship is currently facing, and use this value to specify where the force should be added.
Because this code is happening in the animation loop and is amplified as the arrow key is held down, only a very small force is needed.