escalator-web/src/box.js

78 lines
1.5 KiB
JavaScript

const MAX_SPEED = 20;
const MAX_JUMP = 2;
const G = 500;
const MAX_FRAME = 9;
let img = new Image();
img.src = "img/griezmann.png"
class Box {
constructor() {
this.size = 0.2;
// Animate can be -1, 0, or 1
this.animate = 0;
this.frameNumber = 0;
this.reset();
}
reset() {
// All these values are in percentage of the screen
this.x = 0.5;
this.y = 0;
this.speedX = 0;
this.speedY = 0;
this.jumpCounter = MAX_JUMP;
}
update(time = 0.002) {
if (this.animate !== 0) {
this.frameNumber += this.animate;
if (this.frameNumber === MAX_FRAME) {
this.animate = -1;
} else if (this.frameNumber === 0) {
this.animate = 0;
}
}
this.speedX *= 0.95;
this.speedY -= G * time;
this.speedY = Math.max(this.speedY, -MAX_SPEED);
this.x += this.speedX * time;
this.y += this.speedY * time;
}
collide(y) {
this.y = y;
this.speedX = 0;
this.speedY = 0;
this.jumpCounter = MAX_JUMP;
}
jump(_x, _y) {
// Put x between -1 and 1
let x = (_x - this.x) * 2;
let y = _y;
if (this.jumpCounter == MAX_JUMP) {
// Trigger animation
this.animate = 1;
}
if (this.jumpCounter > 0) {
this.jumpCounter--;
this.speedX = MAX_SPEED * x;
this.speedY = MAX_SPEED;
}
}
}
Box.texture = img;