class Scene { init(elem, opts){ this.elem = elem; this.gravity = opts && opts.gravity ? opts.gravity : 1.5; this.sel = document.querySelector(this.elem); this.canvas = document.createElement("canvas"); this.canvas.style.background = "lightblue"; this.context = this.canvas.getContext("2d"); this.sel.appendChild(this.canvas); this.resize(); } addPlayer(player){ this.player = player; } movePlayer(dirs){ if (!this.player) { console.error("You need to add a player with scene.addPlayer(player) before trying to move it."); return null; } if (dirs.right){ this.player.x += Math.min(this.player.agility, this.width - (this.player.x + this.player.width)); } if (dirs.left){ this.player.x -= Math.min(this.player.agility, this.player.x); } if (dirs.up && !this.player.jumping){ this.player.jumping = true; this.player.vy = this.player.jumpPower; } if (this.player.jumping){ this.player.vy -= this.gravity; this.player.y -= this.player.vy; if (this.player.y - this.player.height < 0){ this.player.y = this.player.height; this.player.vy = 0; } if (this.player.y >= this.height){ this.player.y = this.height; this.player.vy = 0; this.player.jumping = false; } } } resize(){ this.width = innerWidth; this.height = innerHeight; } draw(){ this.resize(); this.canvas.width = this.width; this.canvas.height = this.height; this.context.clearRect(0, 0, this.width, this.height) if (this.player){ this.context.fillStyle = "steelblue"; this.context.fillRect(this.player.x, this.player.y - this.player.height, this.player.width, this.player.height); } } }