-
Notifications
You must be signed in to change notification settings - Fork 2
Description
const gravity = 0.5;
let player = {
x: 50,
y: 300,
width: 30,
height: 30,
dx: 0,
dy: 0,
onGround: false
};
let keys = {};
const platforms = [
{x: 0, y: 350, width: 200, height: 50},
{x: 250, y: 300, width: 150, height: 20},
{x: 450, y: 250, width: 150, height: 20},
{x: 650, y: 200, width: 100, height: 20},
];
const spikes = [
{x: 220, y: 330, width: 30, height: 20},
{x: 600, y: 180, width: 50, height: 20},
];
const finish = {x: 700, y: 150, width: 50, height: 50};
function drawRect(obj, color){
ctx.fillStyle = color;
ctx.fillRect(obj.x, obj.y, obj.width, obj.height);
}
function checkCollision(a, b){
return a.x < b.x + b.width &&
a.x + a.width > b.x &&
a.y < b.y + b.height &&
a.y + a.height > b.y;
}
function resetPlayer(){
player.x = 50;
player.y = 300;
player.dx = 0;
player.dy = 0;
}
function update(){
// Movement
if(keys['ArrowLeft']) player.dx = -5;
else if(keys['ArrowRight']) player.dx = 5;
else player.dx = 0;
// Jump
if(keys['Space'] && player.onGround){
player.dy = -10;
player.onGround = false;
}
// Apply gravity
player.dy += gravity;
player.x += player.dx;
player.y += player.dy;
// Collision with platforms
player.onGround = false;
for(let plat of platforms){
if(checkCollision(player, plat) && player.dy >= 0){
player.y = plat.y - player.height;
player.dy = 0;
player.onGround = true;
}
}
// Collision with spikes
for(let spike of spikes){
if(checkCollision(player, spike)){
resetPlayer();
}
}
// Collision with finish
if(checkCollision(player, finish)){
alert("You Win!");
resetPlayer();
}
}
function draw(){
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Draw platforms
for(let plat of platforms) drawRect(plat, 'brown');
// Draw spikes
for(let spike of spikes) drawRect(spike, 'red');
// Draw finish
drawRect(finish, 'green');
// Draw player
drawRect(player, 'blue');
}
function gameLoop(){
update();
draw();
requestAnimationFrame(gameLoop);
}
document.addEventListener('keydown', e => { keys[e.code] = true; });
document.addEventListener('keyup', e => { keys[e.code] = false; });
gameLoop();
</script>