JSFiddle - React, Tailwind, and code Playground
by Nathan Piper
HTML
<canvas id="background" width="300" height="300"></canvas>
<canvas id="background2" width="300" height="300"></canvas>
<canvas id="Player" width="300" height="300"></canvas>
CSS
canvas {
padding-left: 0;
padding-right: 0;
margin-left: auto;
margin-right: auto;
display: block;
width: 500px;
position: absolute;
top: 0;
left: 0;
}
JavaScript
var FPS = 60;
var height = 300;
var width = 300;
var posX = 0;
var posX2 = 0;
var walls = [];
var pathway = [];
var posY = 0;
var runOnce = 0;
var rand = 0;
var randomLength = 0;
var x = 0;
var posY2 = 0;
var gamestate = "play";
var temp = 0;
function canvas(id){
return document.getElementById(id).getContext('2d');
}
var bG = canvas("background");
var bG2 = canvas("background2");
var pG = canvas("Player");
function collision(obj1, obj2){
return (
obj1.x < obj2.x + obj2.width &&
obj1.x + obj1.width > obj2.x &&
obj1.y < obj2.y + obj2.height &&
obj1.y + obj1.height > obj2.y
);
}
var Player = {
x: 0,
y: 0,
width: 20,
height: 20,
speed: 3,
render: function(){
pG.fillStyle = 'black'
pG.fillRect(this.x, this.y, this.width, this.height);
},
update: function(){
if (Key.up && this.y > 0) this.y -= this.speed;
if (Key.down && this.y < height-20 ) this.y += this.speed;
if (Key.left && this.x > 0) this.x -= this.speed;
if (Key.right && this.x < width-20 ) this.x += this.speed;
}
}
function Path (x,y) {
this.x = x;
this.y = y;
this.width = 30;
this.height = 30;
this.render = function(){
bG2.fillStyle = 'aqua'
bG2.fillRect(this.x, this.y, this.width, this.height);
}
this.update = function() {
}
};
function Wall(x,y) {
this.x = x;
this.y = y;
this.width = 30;
this.height = 30;
this.render = function() {
bG.fillStyle = 'grey';
bG.fillRect(this.x, this.y, this.width, this.height);
}
this.update = function() {
if(collision(this, Player)){
gamestate = "gameover";
console.log("yay");
}
}
}
function buildWalls(){
walls.push(new Wall(posX2, posY2));
}
function buildPath(){
pathway.push(new Path(posX, posY));
}
var Map =...