From 40950633f7613f2084075f457d83581d4fdceac8 Mon Sep 17 00:00:00 2001 From: Thomas Forgione Date: Tue, 21 Aug 2018 16:20:23 +0200 Subject: [PATCH] Added sprite and animation --- src/box.js | 28 +++++++++++++++++++++++++++- src/scene.js | 16 +++++++--------- 2 files changed, 34 insertions(+), 10 deletions(-) diff --git a/src/box.js b/src/box.js index 44954c3..aaff216 100644 --- a/src/box.js +++ b/src/box.js @@ -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; diff --git a/src/scene.js b/src/scene.js index 83c4425..ecb660a 100644 --- a/src/scene.js +++ b/src/scene.js @@ -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) {