I’m trying to teach myself JavaScript and making a little game. The game consists of where you use your arrow keys and move around a closed area on a html document with an image (lets call it main) that will move in the direction you want. The object randomly appears one time on the screen and when the main image is on top of it, the object disappears.
I’ve been using apendChild to make the image appears randomly with Math.Random. The object moves, but what is missing is how to get rid of the image after moving on top of the image. How would you do this? Another Remove Child, or something else?
The code is over 150 lines. This is a snap of where I have put the appendChild and the removeChild, but not sure if this is the right way. I have also called up a location called toPlay() that will set the Interval and docReady.
var imgC = document.createElement("img");
imgC.src = “image.jpg”;
imgC.id = "food";
function man() {
var food1 = document.getElementById("food");
var man1 = document.getElementById("man");
var blue = Math.floor(Math.random()*3);
if(blue === 0) {
var box1 = document.getElementById("box").appendChild(imgC);
var manTop = (Math.floor(Math.random() * 20) *25);
var manLeft = (Math.floor(Math.random() * 20) * 25);
food.style.position = 'absolute';
food.style.top = manTop + "px";
food.style.left = manLeft + "px";
}
else {
var box = document.removeChild(box1);
}
}
function toPlay() {
setInterval(man, 5000);
}
function docReady() {
window.addEventListener('keydown', moveSelection);
}
toPlay();
removeChild()