file.javascript 2.46 KB
Newer Older
1 2
define(function(require, exports, module) {
  module.exports = Player;
3

4 5
  var Key = require("./key")
    , Direction = require("./direction");
6

7 8
  function Player(game) {
    this.game = game;
9

10 11
    this.image = new Image("./assets/fighter.png");
    this.game.resources.add(this.image);
12

13 14
    this.x = 0;
    this.y = 0;
15

16 17
    this.pixelX = 10;
    this.pixelY = 10;
18

19
    this.animationStep = 0;
20 21
  }

22 23 24 25
  Player.prototype.update = function() {
    if (!this.isWalking()) {
      this.handleInput();
    }
26

27 28 29
    if (this.isWalking()) {
      // Increase the animation step.
      this.animationStep = ++this.animationStep % 60;
30

31 32 33 34 35
      if (this.x * 32 > this.pixelX) {
        this.pixelX++;
      } else if (this.x * 32 < this.pixelX) {
        this.pixelX--;
      }
36

37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
      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;
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
    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;
    }
105

106 107 108
    context.drawImage(this.image.data, offsetX, offsetY, 32, 48, this.pixelX, this.pixelY, 32, 48);
  };
});