Making a WebApp for a portfolio in JavaScript. The avatar is not moving

The code came from a course, I didn’t write it myself, but I understand what it means and is supposed to do.

My dimensions for ship are 75px by 75px. At full size it moves.
My dimensions for the moon are 50px by 35px. At full size, it moves, but WITH the rocket ship.

The goal of the app is for the user to use the arrow keys to move the ship to the moon, upon collision, the moon moves to a random location. There is no score to keep, that’s all.

But like I said nothing is moving.

Any help is appreciated. I think the problem lies either in my Javascript or image sizes.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie-edge">
    <title>Lunar Landing</title>
    <link rel="stylesheet" href="app.css">
</head>
<body>
    <img src="img/ship.png" id="ship">
    <img src="img/moon.png" id="moon">
    <script src="app.js"></script>
</body>
</html>


function isTouching(a, b) {
const aRect = a.getBoundingClientRect();
const bRect = b.getBoundingClientRect();

return !(
    aRect.top + aRect.height < bRect.top ||
    aRect.top > bRect.top + bRect.height ||
    aRect.left + aRect.width < bRect.left ||
    aRect.left > bRect.left + bRect.width
);
}

const init = () => {
const avatar = document.querySelector('#ship');
const coin = document.querySelector('#moon');
moveCoin();
window.addEventListener('keyup', function(e) {
    if (e.key === 'ArrowDown' || e.key === 'Down') {
        moveVertical(avatar, 50);
    }
    else if (e.key === 'ArrowUp' || e.key === 'Up') {
        moveVertical(avatar, -50);
    }
    else if (e.key === 'ArrowRight' || e.key === 'Right') {
        moveHorizontal(avatar, 50);
        avatar.style.transform = 'scale(1,1)';
    }
    else if (e.key === 'ArrowLeft' || e.key === 'Left') {
        moveHorizontal(avatar, -50);
        avatar.style.transform = 'scale(-1,1)';
    }
    if (isTouching(avatar, coin)) moveCoin();
});
};

const moveVertical = (element, amount) => {
const currTop = extractPos(element.style.top);
element.style.top = `${currTop + amount}px`;
};
const moveHorizontal = (element, amount) => {
const currLeft = extractPos(element.style.left);
element.style.left = `${currLeft + amount}px`;
};

const extractPos = (pos) => {
if (!pos) return 100;
return parseInt(pos.slice(0, -2));
};

const moveCoin = () => {
const x = Math.floor(Math.random() * window.innerWidth);
const y = Math.floor(Math.random() * window.innerHeight);
coin.style.top = `${y}px`;
coin.style.left = `${x}px`;
};

init();

24 thoughts on “Making a WebApp for a portfolio in JavaScript. The avatar is not moving”

Leave a Comment