tilegame/src/player.js

74 lines
1.4 KiB
JavaScript

import { ctx } from './canvas'
import Input from './input'
class Player {
constructor (x, y, w, h) {
this.x = x
this.y = y
this.width = w
this.height = h
this.mX = 0
this.mY = 0
this.grounded = false
this.speed = 8
this.gravity = 1
this.jumpPower = 20
}
moveAndSlide (collider) {
// y collision
let oldY = this.y
this.y += this.mY
if (oldY !== this.y && collider.collide(this)) {
if (this.y > oldY) this.grounded = true
this.y = oldY
this.mY = 0
} else {
this.grounded = false
}
// x collision
let oldX = this.x
this.x += this.mX
if (oldX !== this.x && collider.collide(this)) {
this.mX = this.mX < 0 ? -1 : 1
this.x = oldX + this.mX
if (collider.collide(this)) {
this.x = oldX
this.mX = 0
}
}
}
update (dt, vp, world) {
this.mY += this.gravity
if (Input.isDown('a')) {
this.mX = -this.speed
} else if (Input.isDown('d')) {
this.mX = this.speed
} else {
this.mX = 0
}
if (this.grounded && (Input.isDown('w') || Input.isDown('space'))) {
this.mY = -this.jumpPower
}
this.moveAndSlide(world)
vp.x = parseInt(this.x - vp.width / 2)
vp.y = parseInt(this.y - vp.height / 2)
}
draw (vp) {
ctx.fillStyle = '#f00'
ctx.fillRect(this.x - vp.x, this.y - vp.y, this.width, this.height)
}
}
export default Player