With a basic game framework in place, we can start by developing an object that will handle the player and any behaviors they may have. This will involve expanding upon the game framework to handle the loading of a sprite, which will be used to represent the player within the game.
We must first begin by creating a new object called
Player
. Once created, insert the following code into ourplayer
object. This object is responsible for initializing and drawing the player on the canvas as well as stating the players position on the canvas.function Player() { this.InitPlayer = function() { this.InitDrawableObject(player_idle, 0, 0, 0); return this; } } Player.prototype = new DrawableObject;
With our
player
object completed, we then need to load the sprite texture into our application. In order to do this, we need to edit theMain.js
object we created previously, openMain.js
and before theOnload
function we will declare a new image object, which will be used to hold our sprite texture.var player_idle = new Image(); player_idle.src = "idle_left.png";
The final step is to initialize our player object by calling the
player
constructor and passing the player sprite to it.this.player = new Player().InitPlayer(player_idle);
If we were to open the application's HTML file in any modern browser we would see the player sprite drawn in the top-left corner of the canvas.
When creating a new game object, in this case the player
object, we must first create a new image object within the Main
object and then assign an external path to the object by setting the source property. In return this results in a texture being loaded into our application that is the player sprite texture. This texture is then passed to the player object and is assigned a position and draw order on the canvas; this is done by means of the drawable object script. In return, the constructor within Main
is passed the player sprite and initializes a new player object, which then draws the player sprite to the canvas.