Untitled

mail@pastecode.io avatar
unknown
plain_text
8 days ago
1.6 kB
8
Indexable
Never
const canvas = document.getElementById("myCanvas");
const context = canvas.getContext("2d");

let playerX = canvas.width / 2;
let playerY = canvas.height - 25;

let enemyX = canvas.width / 2 - 400;
let enemyY = canvas.height - 25;
const borderRadius = 25;

function drawPlayer(){
    context.beginPath();
    context.arc(playerX , playerY , borderRadius , 0 , Math.PI * 2);
    context.fillStyle = "black";
    context.fill();
    context.closePath();
}

function drawEnemy(){
    context.beginPath();
    context.arc(enemyX , enemyY, borderRadius , 0 , Math.PI * 2);
    context.fillStyle = "red";
    context.fill();
    context.closePath();
}

function movePlayer(event){
    const stepSize = 10;
    const jumpSize = 30;
    if(event.key === "a"){
        playerX -= stepSize;
    } else if (event.key === "d"){
        playerX += stepSize;
    } else if (event.key === " "){
        playerY -= jumpSize;
    } else if (event.key === "s"){
        playerY += stepSize;
    }
    redraw();
}
function movePlayerStep(event) {
    if (event.key === 'd' && event.key === ' ') {
        playerX += stepSize;
        playerY -= jumpSize;
    } else if (event.key === 'a' || event.key === ' ') {
        playerX -= stepSize;
        playerY += jumpSize;
    }
}

function redraw(){
    context.clearRect(0, 0, canvas.width, canvas.height);
    drawPlayer();
    drawEnemy();
}

function startGame(){
    drawPlayer();
    drawEnemy();
}

document.addEventListener(`keydown`, movePlayer);
document.addEventListener(`keyup` , movePlayerStep );

startGame();
Leave a Comment