Adding balls to the game framework

Let’s augment the game framework

This time, we will extract the source code used to create the balls, and include it in our game framework. We will also use time-based animation. The distance that the player and each ball should move is computed and may vary between animation frames, depending  on the time-delta since the previous frame.

Online example at JSBin.

Try to move the monster with arrow keys and use the mouse button while moving to change the monster’s speed. Look at the source code and change the parameters controlling the creation of the balls: number, speed, radius, etc. Also, try changing the monster’s default speed. See the results.

Monster + balls in the game framework. On the screen we see the monster + a bunch of balls

For this version, we copied and pasted some code from the previous example and we also modified the mainLoop to make it more readable. In a next lesson, we will split the game engine into different files and clean the code-base to make it more manageable. But for the moment, jsbin.com is a good playground to try-out and test things…

The new mainLoop :

  1. var mainLoop = function(time){
  2.   //main function, called each frame
  3.   measureFPS(time);
  4.   // number of ms since last frame draw
  5.   delta = timer(time);
  6.   // Clear the canvas
  7.   clearCanvas();
  8.   // Draw the monster
  9.   drawMyMonster(monster.x, monster.y);
  10.   // Check inputs and move the monster
  11.   updateMonsterPosition(delta);
  12.   // Update and draw balls
  13.   updateBalls(delta);
  14.   // Call the animation loop every 1/60th of second
  15.   requestAnimationFrame(mainLoop);
  16. };

As you can see, we draw the player/monster, we update its position; and we call an updateBalls function to do the same  for the balls: draw and update their position.

  1. function updateMonsterPosition(delta) {
  2.   monster.speedX = monster.speedY = 0;
  3.   // check inputStates
  4.   if (inputStates.left) {
  5.     monster.speedX = monster.speed;
  6.   }
  7.   if (inputStates.up) {
  8.     monster.speedY = monster.speed;
  9.   }
  10.   
  11.   // Compute the incX and incY in pixels depending
  12.   // on the time elapsed since last redraw
  13.   monster.x += calcDistanceToMove(delta, monster.speedX);
  14.   monster.y += calcDistanceToMove(delta, monster.speedY);
  15. }
  16. function updateBalls(delta) {
  17.   // for each ball in the array
  18.   for(var i=0; i < ballArray.length; i++) {
  19.    var ball = ballArray[i];
  20.    // 1) move the ball
  21.    ball.move();
  22.    // 2) test if the ball collides with a wall
  23.    testCollisionWithWalls(ball);
  24.    // 3) draw the ball
  25.    ball.draw();
  26. }
  27. }

Now, in order to turn this into a game, we need to create some interactions between the player (the monster) and the obstacles/enemies (balls, walls)… It’s time to take a look at collision detection.

Leave a comment