Started to move box laterally
This commit is contained in:
parent
e85691a8c1
commit
1bccdaa9f4
56
src/box.js
56
src/box.js
|
@ -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;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
|
|
@ -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);
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
|
|
19
src/scene.js
19
src/scene.js
|
@ -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();
|
||||
}
|
||||
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue