AndyMack
New Coder
I made a code, trying to make a little character run around my screen, but I cannot figure out where I went wrong. HELP!
When I ran the code, the GIFs all went in different directions, but i cannot make them stay together. I cannot figure out how to make the GIFs only work when that individual button is pressed.
When I ran the code, the GIFs all went in different directions, but i cannot make them stay together. I cannot figure out how to make the GIFs only work when that individual button is pressed.
HTML:
<!doctype html>
<html lang="en">
<head>
<title>The Forest of Forgotten Souls</title>
<script type="text/javascript" src="script.js"></script>
<link rel="stylesheet" href="style.css" />
</head>
<body onkeydown="getKeyAndMove(event)">
<div id="game"></div>
<img id="image1" src="walkforward.gif"/>
<img id="image2" src="walkleft.gif"/>
<img id="image3" src="walkright.gif"/>
<img id="image4" src="walkbackward.gif"/>
</body>
</html>
JavaScript:
var image1 = null;
var image2 = null;
var image3 = null;
var image4 = null;
function init() {
image1 = document.getElementById("image1");
image1.style.position = "absolute";
image1.style.left = "250px";
image1.style.top = "250px";
image2 = document.getElementById("image2");
image2.style.position = "absolute";
image2.style.left = "250px";
image2.style.top = "250px";
image3 = document.getElementById("image3");
image3.style.position = "absolute";
image3.style.left = "250px";
image3.style.top = "250px";
image4 = document.getElementById("image4");
image4.style.position = "absolute";
image4.style.left = "250px";
image4.style.top = "250px";
}
function getKeyAndMove(e) {
var key_code = e.which || e.keyCode;
switch (key_code) {
case 37: //left arrow key
moveLeft();
break;
case 38: //Up arrow key
moveUp();
break;
case 39: //right arrow key
moveRight();
break;
case 40: //down arrow key
moveDown();
break;
}
}
function moveLeft() {
image2.style.left = parseInt(image2.style.left) - 5 + "px";
}
function moveUp() {
image1.style.top = parseInt(image1.style.top) - 5 + "px";
}
function moveRight() {
image3.style.left = parseInt(image3.style.left) + 5 + "px";
}
function moveDown() {
image4.style.top = parseInt(image4.style.top) + 5 + "px";
}
window.onload = init;
Last edited: