Reputation: 9
Why does the Image multiply and not change the position by pressing up or down? The ufo also just multiply why? The rocket schould only move up and down. The Ufos schould move vom right to left and spawn every second. I only change the coordinates. So the ufo and rocket schould not multiply.
"use strict";
let keySpace = false;
let keyUp = false;
let keyDown = false;
let canvas;
let drawer;
let ufos = [];
let rocket = {
x: 10,
y: 180,
width: 100,
height: 100,
src: "rocket.png",
};
document.onkeydown = function(e) { //Keypressed
if (e.keyCode == 32) {
keySpace = true;
}
if (e.keyCode == 38) {
keyUp = true;
}
if (e.keyCode == 40) {
keyDown = true;
}
};
document.onkeyup = function(e) { //KeyUp
if (e.keyCode == 32) {
keySpace = false;
}
if (e.keyCode == 38) {
keyUp = false;
}
if (e.keyCode == 40) {
keyDown = false;
}
};
function start() {
canvas = document.getElementById("ID");
drawer = canvas.getContext("2d");
load();
setInterval(update, 1000 / 25);
setInterval(createUfo, 1000);
draw();
}
function createUfo() {
let ufo = {
x: 650,
y: Math.random() * 450,
width: 50,
height: 50,
src: "ufo.png",
img: new Image(),
};
ufo.img.src = ufo.src;
ufos.push(ufo);
}
function update() {
if (keyUp) {
rocket.y -= 3;
}
if (keyDown) {
rocket.y += 3;
}
ufos.forEach(function(ufo) {
ufo.x -= 3;
});
}
function load() {
rocket.img = new Image();
rocket.img.src = rocket.src;
}
function draw() {
drawer.drawImage(rocket.img, rocket.x, rocket.y, rocket.width, rocket.height);
ufos.forEach(function(ufo) {
drawer.drawImage(ufo.img, ufo.x, ufo.y, ufo.width, ufo.height);
});
requestAnimationFrame(draw);
}
canvas {
background-color: gray;
}
<body onload="start()">
<canvas id="ID" width="720" height="480"></canvas>
</body>
Upvotes: 1
Views: 78
Reputation: 957
I briefly refactor your code and prepared a pen: https://codepen.io/Zaaburin/pen/BaxVxMb
function draw() {
update();
drawer.clearRect(0,0,720,480);
drawer.drawImage(rocket.img, rocket.x, rocket.y, rocket.width, rocket.height);
ufos.forEach(function (ufo) {
drawer.drawImage(ufo.img, ufo.x, ufo.y, ufo.width, ufo.height);
});
requestAnimationFrame(draw);
}
start()
Upvotes: 1