Code der Vorlseung
INDEX.HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Mein erstes Spiel!</title>
<style>
canvas {
background-color: black;
}
</style>
</head>
<body onload="startGame()">
<canvas id="canvas" width="720" height="480"></canvas>
<script src="game.js"></script>
</body>
</html>
GAME.JS:
let KEY_SPACE = false;
let KEY_UP = false;
let KEY_DOWN = false;
let backgroundImage = new Image;
let canvas;
let ctx;
let rocket = {
x: 50,
y: 250,
width: 95,
heigth: 60,
src: "rocket.png"
};
let ufo = {
x: 600,
y: 120,
width: 120,
heigth: 40,
src: "ufo.png"
};
document.onkeydown = function(e) {
if (e.key == " ") {
KEY_SPACE = true;
}
if (e.key == "ArrowUp") {
KEY_UP = true;
}
if (e.key == "ArrowDown") {
KEY_DOWN = true;
}
}
document.onkeyup = function(e) {
if (e.key == " ") {
KEY_SPACE = false;
}
if (e.key == "ArrowUp") {
KEY_UP = false;
}
if (e.key == "ArrowDown") {
KEY_DOWN = false;
}
}
function startGame() {
loadImages();
canvas = document.getElementById("canvas");
ctx = canvas.getContext("2d");
setInterval(update, 1000 / 25);
draw();
}
function draw() {
ctx.drawImage(backgroundImage, 0, 0, 720, 480);
ctx.drawImage(rocket.img, rocket.x, rocket.y, rocket.width, rocket.heigth);
requestAnimationFrame(draw);
}
function loadImages() {
backgroundImage.src = "space.png"
rocket.img = new Image;
rocket.img.src = rocket.src;
ufo.img = new Image;
ufo.img.src = ufo.src;
}
function update() {
if(KEY_UP) {
rocket.y = rocket.y - 4;
}
}
Zuletzt geändert: Montag, 17. April 2023, 17:25