Hash :
19fa9c0c
Author :
Date :
2014-07-14T22:20:02
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
define(function(require, exports, module) {
module.exports = Player;
var Key = require("./key")
, Direction = require("./direction");
function Player(game) {
this.game = game;
this.image = new Image("./assets/fighter.png");
this.game.resources.add(this.image);
this.x = 0;
this.y = 0;
this.pixelX = 10;
this.pixelY = 10;
this.animationStep = 0;
}
Player.prototype.update = function() {
if (!this.isWalking()) {
this.handleInput();
}
if (this.isWalking()) {
// Increase the animation step.
this.animationStep = ++this.animationStep % 60;
if (this.x * 32 > this.pixelX) {
this.pixelX++;
} else if (this.x * 32 < this.pixelX) {
this.pixelX--;
}
if (this.y * 32 > this.pixelY) {
this.pixelY++;
} else if (this.y * 32 < this.pixelY) {
this.pixelY--;
}
} else {
// Reset the animation step.
this.animationStep = 0;
}
};
Player.prototype.handleInput = function() {
var keyboard = this.game.keyboard, finalAction, action, inputs = {
'moveDown': keyboard.isDown(Key.DOWN),
'moveUp': keyboard.isDown(Key.UP),
'moveLeft': keyboard.isDown(Key.LEFT),
'moveRight': keyboard.isDown(Key.RIGHT)
};
for (action in inputs) {
if (inputs[action]) {
if (!finalAction || inputs[finalAction] < inputs[action]) {
finalAction = action;
}
}
}
this[finalAction] && this[finalAction]();
};
Player.prototype.isWalking = function() {
return this.x * 32 != this.pixelX || this.y * 32 != this.pixelY;
};
Player.prototype.moveDown = function() {
this.y += 1;
this.direction = Direction.DOWN;
};
Player.prototype.moveUp = function() {
this.y -= 1;
this.direction = Direction.UP;
};
Player.prototype.moveLeft = function() {
this.x -= 5;
this.direction = Direction.LEFT;
};
Player.prototype.moveRight = function() {
this.x += 1;
this.direction = Direction.RIGHT;
};
Player.prototype.draw = function(context) {
var offsetX = Math.floor(this.animationStep / 15) * 32, offsetY = 0;
switch(this.direction) {
case Direction.UP:
offsetY = 48 * 3;
break;
case Direction.RIGHT:
offsetY = 48 * 2;
break;
case Direction.LEFT:
offsetY = 48;
break;
}
context.drawImage(this.image.data, offsetX, offsetY, 32, 48, this.pixelX, this.pixelY, 32, 48);
};
});