Started to move box laterally

This commit is contained in:
Thomas Forgione 2018-08-21 09:48:31 +02:00
parent e85691a8c1
commit 1bccdaa9f4
No known key found for this signature in database
GPG Key ID: 203DAEA747F48F41
3 changed files with 51 additions and 29 deletions

View File

@ -4,45 +4,47 @@ const G = 500;
class Box {
constructor() {
this.position = 0;
this.speed = 0;
this.size = 100;
// All these values are in percentage of the screen
this.x = 0.5;
this.y = 0;
this.speedX = 0;
this.speedY = 0;
this.size = 0.1;
this.jumpCounter = MAX_JUMP;
}
drawOn(canvas) {
let ctx = canvas.getContext('2d');
ctx.fillStyle = 'rgb(0, 0, 0)';
ctx.beginPath();
ctx.rect(
canvas.width / 2.0 - this.size / 2.0,
canvas.height - this.size - this.position,
this.size,
this.size
);
ctx.fill();
}
update(time = 0.002) {
this.speed -= G * time;
this.speed = Math.max(this.speed, -MAX_SPEED);
this.position += this.speed;
this.speedX *= 0.95;
if (this.position <= 0) {
this.position = 0;
this.speed = 0;
this.speedY -= G * time;
this.speedY = Math.max(this.speedY, -MAX_SPEED);
this.x += this.speedX * time;
this.y += this.speedY * time;
if (this.y <= 0) {
this.y = 0;
this.speedY = 0;
this.jumpCounter = MAX_JUMP;
}
this.x = Math.max(0, Math.min(1, this.x));
}
jump() {
jump(_x, _y) {
// Put x between -1 and 1
let x = (_x - 0.5) * 2;
let y = _y;
if (this.jumpCounter > 0) {
this.jumpCounter--;
this.speed = MAX_SPEED;
this.speedX = MAX_SPEED * x;
this.speedY = MAX_SPEED;
}
}
}

View File

@ -13,7 +13,10 @@ function init() {
// Initialize listeners
window.addEventListener('resize', () => scene.autoResize());
document.addEventListener('touchstart', () => box.jump());
document.addEventListener('touchstart', (event) => {
let e = event.changedTouches[0];
box.jump(e.clientX / window.innerWidth, e.clientY / window.innerHeight);
});
}

View File

@ -49,7 +49,24 @@ class Scene {
this.drawBackground();
for (let object of this.objects) {
object.drawOn(this.canvas);
this.draw(object);
// object.drawOn(this.canvas);
}
}
draw(object) {
let size = object.size * this.width();
this.context.fillStyle = 'rgb(0, 0, 0)';
this.context.beginPath();
this.context.rect(
object.x * this.width(),
(1 - object.y) * this.height() - size,
size,
size,
);
this.context.fill();
}
}