I am trying to make a game for school, the game is simple. 1. player needs to eat cakes to score points 2. a fixed number of enemies spawn randomly and move randomly 3. enemies have to bounce off of walls and move to another random direction
My issue here is: I made a for-loop creating a few enemies, these enemies move and spawn randomly, but don't bounce off the walls. These enemies get their ID from the for-loop (#enemy + i) and I push them into an array.
I know I have to use setInterval in order to make it check each time if an enemy is at the border, but I can't seem to make it work.
In order to make the code easier to understand:
randomTopVijand = creates a random top position for each enemy
randomLeftVijand = creates a random left position for each enemy
randomRichting = decides in which direction the enemy will go
At first I tried to make the animation stop at the walls, but that didn't work out. Would highly appreciate if someone could help me making those guys bounce of the walls.
function maakVijand() {
for ( i = 0; i < 6; i++) {
randomTopVijand = Math.floor(Math.random() * 580);
randomLeftVijand = Math.floor(Math.random() * 780);
randomRichting = Math.floor(Math.random() * 7);
$("#terrain").append("<img src='IMG/knight_sprite.gif' id='enemy" + i + "' />");
arrayVijand.push("enemy" + i);
$("#enemy" + i).css({
position : "absolute",
top : randomTopVijand + "px",
left : randomLeftVijand + "px"
});
if (randomRichting == 0) {
$("#enemy" + i).animate({
'left' : '-=200',
'top' : '-=200'
}, 1750);
} else if (randomRichting == 1) {
$("#enemy" + i).animate({
'top' : '-=610'
}, 1750);
} else if (randomRichting == 2) {
$("#enemy" + i).animate({
'left' : '+=810',
'top' : '-=610'
}, 1750);
} else if (randomRichting == 3) {
$("#enemy" + i).animate({
'left' : '+=810'
}, 1750);
} else if (randomRichting == 4) {
$("#enemy" + i).animate({
'left' : '+=810',
'top' : '+=610'
}, 1750);
} else if (randomRichting == 5) {
$("#enemy" + i).animate({
'top' : '+=610'
}, 1750);
} else if (randomRichting == 6) {
$("#enemy" + i).animate({
left : '-=810',
top : '+=610'
}, 1750);
} else if (randomRichting == 7) {
$("#enemy" + i).animate({
left : '-=810'
}, 1750);
}
if ($("#enemy" + i).position.top <= positiescherm.left) {
$("#enemy" + i).stop(true, false);
}
if ($('#enemy' + i).position().left <= positiescherm.left) {
$('#enemy' + i).stop(true, false);
} else if ($("#enemy" + i).position().left + $("#enemy" + i).width() >= positiescherm.right) {
$("#enemy" + i).stop(true, false);
} else if ($("#enemy" + i).position().top <= positiescherm.top) {
$("#enemy" + i).stop(true, false);
} else if ($("#enemy" + i).position().top + $("#enemy" + i).height >= positiescherm.bottom) {
$("#enemy" + i).stop(true, false);
}
}
}
Aucun commentaire:
Enregistrer un commentaire