witchday/Person.js

80 lines
1.8 KiB
JavaScript
Raw Normal View History

class Person extends GameObject {
constructor(config) {
super(config);
this.movementProgressRemaining = 0;
this.isPlayerControlled = config.isPlayerControlled || false;
this.directionUpdate = {
"up": ["y", -1],
"down": ["y", 1],
"left": ["x", -1],
"right": ["x", 1],
}
}
update(state) {
if (this.movementProgressRemaining > 0) {
this.updatePosition();
} else {
// more cases for starting to walk come here
// case: keyboard ready and arrow pressed
if (state.map.isCutscenePlaying == false && this.isPlayerControlled && state.arrow) {
this.startBehavior(state, {
type: "walk",
direction: state.arrow
})
}
this.updateSprite(state);
}
}
startBehavior(state, behavior) {
// set character direction to behavior
this.direction = behavior.direction;
if (behavior.type === "walk") {
// stop if space is not free
if (state.map.isSpaceTaken(this.x, this.y, this.direction)) {
behavior.retry && setTimeout(() => {
this.startBehavior(state, behavior);
}, 10);
return;
}
// ready to walk
state.map.moveWall(this.x, this.y, this.direction);
this.movementProgressRemaining = 16;
this.updateSprite(state);
}
if (behavior.type = "stand") {
setTimeout(() => {
utils.emitEvent("PersonStandComplete", {
whoId: this.id
})
}, behavior.time);
}
}
updatePosition() {
const [property, change] = this.directionUpdate[this.direction];
this[property] += change;
this.movementProgressRemaining -= 1;
if (this.movementProgressRemaining === 0) {
utils.emitEvent("PersonWalkingComplete", {
whoId: this.id
})
}
}
updateSprite() {
if (this.movementProgressRemaining > 0) {
this.sprite.setAnimation("walk-" + this.direction);
return;
}
this.sprite.setAnimation("idle-" + this.direction);
}
}