Skip to content

By xiopl #17

@hernandezrguezomar1989-art

Description

<title>2D Obby Game</title> <style> body { margin: 0; overflow: hidden; background: #87CEEB; } canvas { background: #87CEEB; display: block; margin: 0 auto; } </style> <script> const canvas = document.getElementById('gameCanvas'); const ctx = canvas.getContext('2d');

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>

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions