Adventures in TypeScript 02

Today’s part of the adventure, we will be going over in creating the ball that terrorizes the bricks in the game. From the last adventure (Adventures in TypeScript 01), we created a basic HTML page that houses the canvas, and started the main guts of the game with a nice little game loop.

Game.ts – Adding more guts

Before we want to add the nice little ball, let’s think about how we want to implement it. Each entity in the game will need to be updated, draw, and have a position. So why not create an interface that houses all the basics that each object will need to implement? That sounds like a marvelous idea.

I went ahead and added velocity as well, because most will want to move on the screen. You can name this whatever you like, but I usually like to start off my interface with an ‘i’, and then later on for classes, I like to start them off with a ‘c’. With this interface, we are saying any class that implements this will have a draw function, update function, x and y position, as well as x and y velocity.

Now let’s start working on the actual implementation for the ball class. Since we know it will implement the iEntity interface, we can start off by creating a base shell of the class.

Nice and sweet. Now if you think about it, the ball should have more properties, like the radius and color. Let’s go ahead and add that to the class, as well as create a nice constructor to set everything up.

If you compile and run it, you should see a nice little white ball in the canvas. It isn’t moving yet because we haven’t given it a velocity and we haven’t filled out the update function. Let’s go ahead and make this ball move!

We are adding the velocity for x and y to the position to move the ball. Next we want to make sure we keep it in bounds of the canvas, else it will just fly off the canvas and never return. So we check to see if the position of the ball is within bounds of the canvas (+- the radius of the ball so it doesn’t go partially off screen before bouncing back). Now if you run this you should still see the ball on the canvas, yet it still isn’t moving. To get the ball to move, we need to set the velocity x and y properties. Inside the window.onload event, before we make the call to the gameLoop, let’s set the velocity of the ball.

ball.velX = 3;
ball.velY = 3;

Now if you compile and run, you should see the ball bounce around and around. Here is what game.ts should look like so far.