How to Add Drift Effects to Your HTML5 Game
You can use force vectors in an interesting way in your HTML5 game. Many racing games include skidding or drifting mechanisms. Getting this behavior exactly right requires very sophisticated mathematics, but you can make a reasonable approximation of this behavior without too much effort.
This image is not enough. You really need to see this as a working program because it’s really cool. As you move the boat around on the screen, the boat drifts and skids. It’s really fun to play with.
How to add drifting behavior to your game’s object
To get a simple drifting behavior, simply add a small force vector in the boat’s current direction regardless of whether the user is currently pressing the accelerator.
This technique is a compromise between the space-based motion (where the force vector is added only when the accelerator is pressed) and standard car behavior (where the direction of travel is always following the vehicle’s nose). Each frame has a little of each behavior.
Here’s the code:
How to add drift to your game’s sprites
It’s a very simple procedure.
Build a standard vehicle model.
Consider making a boat, just for variation.
Use a force vector for acceleration.
Again, you’re manually controlling the speed, so the addVector() mechanism gives you great power. The acceleration force vector (used in the up-arrow key press) can be a literal value, but it doesn’t need to be huge. Because you’re actually going to be adding a second force vector, you might want to tone down the acceleration vector.
Add a small force vector every frame.
The primary force vector happens only when you accelerate, but a secondary smaller vector is added every frame. This vector goes in the direction the boat is currently facing. This small motion vector will simulate momentum. It’s important that this force vector be a percentage of the speed rather than a literal value. If you always move forward one pixel, for example, the boat will never stop.