class Scene {
init(opts){
this.widthOverride = opts && opts.width ? opts.width : null;
this.heightOverride = opts && opts.height ? opts.height : null;
this.gravity = opts && opts.gravity ? opts.gravity : 1.5;
this.canvas = DOM.canvas();
this.canvas.style.background = "lightblue";
this.context = this.canvas.getContext("2d");
this.resize(opts);
}
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.vx += this.player.agility;
if (this.player.vx >= this.player.maxspeed) this.player.vx = this.player.maxspeed;
this.player.x += this.player.vx;
}
else if (dirs.left){
this.player.vx -= this.player.agility;
if (this.player.vx <= -this.player.maxspeed) this.player.vx = -this.player.maxspeed;
this.player.x += this.player.vx;
}
else {
if (this.player.vx > 0) {
this.player.vx -= this.player.agility;
if (this.player.vx <= 0) this.player.vx = 0;
this.player.x += this.player.vx;
}
else if (this.player.vx < 0) {
this.player.vx += this.player.agility;
if (this.player.vx >= 0) this.player.vx = 0;
this.player.x += this.player.vx;
}
}
// Hit the wall
if (this.player.x >= (this.width - this.player.width)) {
this.player.x = this.width - this.player.width;
this.player.vx = 0;
} else if (this.player.x <= 0) {
this.player.x = 0;
this.player.vx = 0;
}
// Break
if (dirs.down){
if (this.player.vx > 0) {
this.player.vx -= this.player.agility * 2;
if (this.player.vx <= 0) this.player.vx = 0;
this.player.x += this.player.vx;
}
else if (this.player.vx < 0) {
this.player.vx += this.player.agility * 2;
if (this.player.vx >= 0) this.player.vx = 0;
this.player.x += this.player.vx;
}
}
if (dirs.up && (flyingPower === "on" ? 1 : !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(opts){
this.width = opts && opts.width ? opts.width : this.widthOverride || innerWidth;
this.height = opts && opts.height ? opts.height : this.heightOverride || innerHeight;
}
draw(opts){
this.resize(opts);
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);
}
}
}