Added sprite and animation

This commit is contained in:
Thomas Forgione 2018-08-21 16:20:23 +02:00
parent 15b32fe710
commit 40950633f7
No known key found for this signature in database
GPG Key ID: 203DAEA747F48F41
2 changed files with 34 additions and 10 deletions

View File

@ -2,9 +2,17 @@ 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.1;
this.size = 0.2;
// Animate can be -1, 0, or 1
this.animate = 0;
this.frameNumber = 0;
this.reset();
}
@ -20,6 +28,17 @@ class Box {
}
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;
@ -41,6 +60,11 @@ class Box {
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;
@ -49,3 +73,5 @@ class Box {
}
}
Box.texture = img;

View File

@ -36,7 +36,7 @@ class Scene extends Screen {
}
drawBackground() {
this.context.fillStyle = 'rgb(255, 0, 0)';
this.context.fillStyle = 'rgb(10, 0, 0)';
this.context.beginPath();
this.context.rect(0, 0, this.width(), this.height());
this.context.fill();
@ -91,8 +91,8 @@ class Scene extends Screen {
};
if (previous.y >= p.y && next.y < p.y) {
if (next.x >= p.x - p.width / 2 - next.size / 2) {
if (next.x <= p.x + p.width / 2 + next.size / 2) {
if (next.x >= p.x - p.width / 2 - next.size / 4) {
if (next.x <= p.x + p.width / 2 + next.size / 4) {
// Collision detected
this.player.collide(p.y - next.size/2);
}
@ -131,15 +131,13 @@ class Scene extends Screen {
let size = object.size * this.width();
this.context.fillStyle = 'rgb(0, 0, 0)';
this.context.beginPath();
this.context.rect(
this.context.drawImage(
Box.texture,
0, 64 * this.player.frameNumber, 64, 64,
(object.x - object.size / 2) * this.width(),
(1 - object.y - object.size / 2 + this.cameraHeight) * this.height(),
size,
size,
size, size
);
this.context.fill();
}
drawPlatform(object) {