Untitled
unknown
plain_text
10 months ago
1.6 kB
4
Indexable
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
let player = {
x: canvas.width / 2,
y: canvas.height / 2,
width: 20,
height: 20,
speed: 5,
bullets: []
};
function drawPlayer() {
ctx.fillStyle = 'blue';
ctx.fillRect(player.x, player.y, player.width, player.height);
}
function drawBullets() {
ctx.fillStyle = 'red';
player.bullets.forEach(bullet => {
ctx.fillRect(bullet.x, bullet.y, bullet.width, bullet.height);
});
}
function updateBullets() {
player.bullets.forEach((bullet, index) => {
bullet.y -= bullet.speed;
if (bullet.y < 0) {
player.bullets.splice(index, 1);
}
});
}
function update() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawPlayer();
drawBullets();
updateBullets();
requestAnimationFrame(update);
}
function movePlayer(event) {
switch (event.key) {
case 'ArrowUp':
player.y -= player.speed;
break;
case 'ArrowDown':
player.y += player.speed;
break;
case 'ArrowLeft':
player.x -= player.speed;
break;
case 'ArrowRight':
player.x += player.speed;
break;
case ' ':
shootBullet();
break;
}
}
function shootBullet() {
const bullet = {
x: player.x + player.width / 2 - 2.5,
y: player.y,
width: 5,
height: 10,
speed: 7
};
player.bullets.push(bullet);
}
document.addEventListener('keydown', movePlayer);
update();Editor is loading...
Leave a Comment