75 lines
1.7 KiB
JavaScript
75 lines
1.7 KiB
JavaScript
class Player {
|
|
constructor(x, y, direction) {
|
|
this.canvasX = x
|
|
this.canvasY = y
|
|
|
|
this.direction = direction
|
|
|
|
this.spriteWidth = spriteSize
|
|
this.spriteHeight = spriteSize * 2
|
|
|
|
this.animationCycle = [0, 1, 0, 2]
|
|
this.animationCycleIndex = 0
|
|
this.spriteMapXAnimationOffset = 0
|
|
|
|
this.directionSpriteYMap = {
|
|
'down': 2,
|
|
'right': 4,
|
|
'up': 6,
|
|
'left': 8,
|
|
}
|
|
}
|
|
|
|
move(direction) {
|
|
this.direction = direction
|
|
var nextPosition
|
|
if (direction === 'left' && this.canvasX - 1 >= 0) {
|
|
nextPosition = [this.canvasX - 1, this.canvasY]
|
|
if (!this.isBoundary(nextPosition)) {
|
|
this.canvasX -= 1;
|
|
}
|
|
}
|
|
|
|
if (direction === 'right' && this.canvasX + 1 < canvas.width/spriteSize) {
|
|
nextPosition = [this.canvasX + 1, this.canvasY]
|
|
if (!this.isBoundary(nextPosition)) {
|
|
this.canvasX += 1;
|
|
}
|
|
}
|
|
|
|
if (direction === 'up' && this.canvasY - 1 >= 0) {
|
|
nextPosition = [this.canvasX, this.canvasY - 1]
|
|
if (!this.isBoundary(nextPosition)) {
|
|
this.canvasY -= 1;
|
|
}
|
|
}
|
|
|
|
if (direction === 'down' && this.canvasY + 2 < canvas.height/spriteSize){
|
|
nextPosition = [this.canvasX, this.canvasY + 1]
|
|
if (!this.isBoundary(nextPosition)) {
|
|
this.canvasY += 1
|
|
}
|
|
}
|
|
}
|
|
|
|
isBoundary(nextPosition) {
|
|
return boundaries.some(a => nextPosition.every((v, i) => v === a[i]));
|
|
}
|
|
|
|
render() {
|
|
this.spriteMapX = this.spriteWidth * 5
|
|
this.spriteMapY = this.directionSpriteYMap[this.direction] * spriteSize
|
|
|
|
ctx.drawImage(
|
|
spriteMap,
|
|
this.spriteMapX + this.spriteMapXAnimationOffset,
|
|
this.spriteMapY,
|
|
this.spriteWidth,
|
|
this.spriteHeight,
|
|
spriteSize * this.canvasX,
|
|
spriteSize * this.canvasY,
|
|
this.spriteWidth,
|
|
this.spriteHeight,
|
|
)
|
|
}
|
|
}
|