How to Add Drift Effects to Your HTML5 Game - dummies

How to Add Drift Effects to Your HTML5 Game

By Andy Harris

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:

<html lang="en-US">
 <meta charset="UTF-8">
 <script type = "text/javascript"
   src = "simpleGame.js"></script>
 <script type="text/javascript">
 var game;
 var boat;
 function Boat(){
  tBoat = new Sprite(game, "boat.png", 100, 50);
  tBoat.checkKeys = function(){
   if (keysDown[K_LEFT]){
   if (keysDown[K_RIGHT]){
   if (keysDown[K_UP]){
    this.addVector(this.getImgAngle(), 2);
   this.addVector(this.getImgAngle(), (this.speed / 20));
  } // end checkKeys
  tBoat.checkDrag = function(){
   speed = this.getSpeed();
   speed *= .95;
  return tBoat;
 function init(){
  game = new Scene();
  boat = new Boat();
 } // end init
 function update(){
<body onload = "init()">

How to add drift to your game’s sprites

It’s a very simple procedure.

  1. Build a standard vehicle model.

    Consider making a boat, just for variation.

  2. 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.

  3. 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.