HTML and CSS Reference
In-Depth Information
4.
Now that we have an enemy positioned within our level, we need to add that enemy
unit to the level. This is done through means of the
AddEnemy
function, which is
as follows:
var x, y;
this.AddEnemy = function(width, height) {
for(var i = 0; i < this.tiles.length; ++i) {
if(this.enemy[i]){
x = i * this.tileWidth + this.tileWidth / 2;
y = height - this.TerrainHeight(i);
if(this.enemy[i] == 'Enemy') {
new Enemy().InitEnemy(enemy_left, x - enemy_left.width / 2, y -
enemy_left.height, 7, 4, 4);
}
}
}
}
5. The inal part that is required is to load the enemy sprite sheet into the application
inside of the
Main
object.
var enemy_left = new Image();
enemy_left.src = "textures/enemy_left.png";
How it works...
The Enemy object creates a new enemy object that represents an animated object similar to
the player object. The
Enemy
object constructor takes in a texture parameter, as well as a 2D
position, depth position, frame count, and frame rate parameters. The texture is a 2D sprite
sheet, which is used to animate the enemy. The x, y, and z positions represent the position of
the enemy on the canvas as well as the position of the enemy texture within the list of layers
within the game. The frame count is used to determine how many frames make up the enemy
sprite sheet and inally the frame rate dictates how many frames the enemy texture should be
played each second.
The
update
function within the
Enemy
object is used to move an enemy object along the
x axis and towards the player. The
update
function is also used to check for any collisions
between the player and the enemy. If there is a collision then the enemy object that collided
with the player is removed from the game and the player has part of their health deducted.
Finally we use the prototype keyword to extend the functionality of the
AnimationManager
to the
Enemy
object.
This collision detection makes use of the
Rectangle
object, which checks whether or not
two rectangles are overlapping and if so whether a collision has occurred.