Make it Move

One of the first goals you will have when making a game is to have some kind of animation. Animation will be responsible for automatic movement and smooth visual effects. Animation functions can also check for certain conditions and control decision making inside your game. The way it works is you use:

window.requestAnimationFrame(animate);

This command tells the window (browser) to call the function you specify before the browser refreshes again. Usually, you will have the window.requestAnimationFrame() command inside the function that is specified. That way, the function will be called over and over indefinitely. Lets take a look at a simple bouncing square.

<!DOCTYPE HTML>
<html>
<head>
<title>Animation</title>
</head>
<body onload="animate()">
<canvas id="canvas" width="200" height="200"></canvas>
<script>

var can = document.getElementById("canvas");
var ctx = can.getContext('2d');

var x=100;
var y=30;
var xDirection = 1;
var yDirection = 1;

function animate() {
  window.requestAnimationFrame(animate);
  
  ctx.fillStyle = "black";
  ctx.fillRect(0, 0, 200, 200);
  
  ctx.fillStyle = "white";
  ctx.fillRect(x-10, y-10, 20, 20);

  x += xDirection;
  y += yDirection;

  if (x<10 || x> 190) xDirection *= -1;
  if (y<10 || y> 190) yDirection *= -1;
}

</script>
</body>
</html>


  • Line 6 We added onload="animate()" to the body tag, this tells the page to call the animate() function once the body loads
  • Line 13 Our box will start with a x position of 100
  • Line 14 Our box will start with a y position of 30
  • Line 15 We use xDirection to keep track if x is increasing or not. You could increase this number to speed up the animation
  • Line 16 Same as above, but this time for y
  • Line 18 This is our animate() function. A function is just a group of code. Everything inside the curly brackets is included (and indented) in the function
  • Line 19 is our animation command that will cause the animate() function to get called over and over
  • Line 25 We are drawing the square here, x and y are the coordinates for the center, so we start drawing at x-10 and y-10 and use a width and height of 20
  • Line 27 Adds the xDirection to the x coordinate, this creates the side to side movement
  • Line 28 Adds the yDirection to the y coordinate, this creates the up and down movement
  • Line 30 Checks if x is about to leave the canvas, if so the direction must be reversed by multiplying xDirection by -1. If you change xDirection to a different number, like 2, this will still work fine
  • Line 31 Same as line 30 except for the yDirection. The if statement is checking both the minimum and maximum allowed values using an or (the "||") statement.

In the example, the JavaScript runs through all the variable declarations in lines 10-16. After that, nothing happens until the page is done loading and the body's onload will kick off the animate() function. The animate() function will then get called over and over until the page is closed.

JavaScript Objects

Objects are sort of like a variable that is a box that you can put all kinds of stuff into. There are a lot of great tutorials out there that explain objects. You can create an object that describes something, like our box. Then instead of having 4 variables (x, y, xDirection, yDirection), we can have one. We can then access the inner variables, or proprieties with the dot symbol. This makes it easy to manage lots of variables. Lets say I want to have a large number of boxes, it would be a nightmare trying to manage all the variables. The solution is to put the box objects into an array. That way it is easy to loop through them, or add and delete them. We will look at arrays in more detail in the Keyboard section. Lets take a look at an object:


var car = {make:"Lexus", model:"RX 350", color:"blue", horsepower:295}

Each propriety of the object is declared in key:value pairs inside curly brackets. Then you can access the value using the key, such as car.make or car.color. You can also add or reassign proprieties using the dot.



<!DOCTYPE HTML>
<html>
<head>
<title>Animation</title>
</head>
<body onload="animate()">
<canvas id="canvas" width="200" height="200"></canvas>
<script>

var can = document.getElementById("canvas");
var ctx = can.getContext('2d');

var boxes = []
for (var i=0; i<3; i++) {
  boxes.push( {x:100, y:100, xD:1, yD:1, color:"red"} );
}

boxes[0].x = 10;
boxes[1].y = 85;
boxes[1].color = "blue";
boxes[2].xD = -2;
boxes[2].color = "lime";

function animate() {
  window.requestAnimationFrame(animate);
  
  ctx.fillStyle = "black";
  ctx.fillRect(0, 0, 200, 200);
 
  for (var i=0; i<3; i++) { 
    ctx.fillStyle = boxes[i].color;
    ctx.fillRect(boxes[i].x-10, boxes[i].y-10, 20, 20);

    boxes[i].x += boxes[i].xD;
    boxes[i].y += boxes[i].yD;

    if (boxes[i].x<10 || boxes[i].x> 190) boxes[i].xD *= -1;
    if (boxes[i].y<10 || boxes[i].y> 190) boxes[i].yD *= -1;
  }
}


</script>
</body>
</html>

In this example we created an array called boxes. We used a for-loop to push 3 box objects into the array. Each object has x and y coordinates, x and y directions, and a color. Then we change some of the properties so that they each move and look different. If we built the box objects with Math.Random() it would be easy to create any amount of boxes that have random properties. The animate loop is basically the same as it was before except that we see "boxes[i]" to refer to the box object that is currently being processed.