My son is having summer vacation and he wanted to learn animation and create games. He had learnt Flash and ActionScript a couple of years back. So he started developing a game in Flash. However he ran into few issues and sought my help. Since I don’t know Flash, I could not help him much. But I suggested that if he develops his game in HTML5, I could help him. So while teaching him HTML5 and animation, I ended up creating a very simple game, which I want to share here.
In this game, when you press the ‘Start’ button, a square starts moving inside a bigger square and the goal is to prevent the smaller square hitting the outer square, by controlling its motion using arrow keys. You don’t need to keep the keys pressed, just press and release any arrow key to change direction. The square moves on its own and accelerates as the game progresses. Give it a try –
The animation loop in this game is created using window.setInterval() function, initially in the startGame() function and then later when the square needs to be accelerated, in accelerate() function. Before creating a new interval in the accelerate(), old loop is cancelled by calling window.clearInterval(). The square is drawn in animateFunc(), which is called by setInterval() method at fixed interval. See the code listing at the end of this post.
Acceleration is controlled by three variables; xStep, yStep and interval. xStep and yStep determine how much the square should move along X and Y axis respectively. interval determines how frequently animateFunc() is called. The interval at which acceleration is changed is controlled by changeAccelerationInterval variable. The game can be made as simple or difficult as you want by tweaking values of these variables.
Key down event (for all arrow keys) is handled by handleKeyDown() and up event is handled by handleKeyUp(). The score is calculated by dividing number of seconds played by two.
Note that I haven’t used animation optimizations techniques I had discussed in my earlier posts in this game because there is not much to redraw on the Canvas and performance is quite good.
Though the game is very simple, I had fun developing it.