Reputation: 259
I'm trying to build a game. Very similar to space invaders but without shooting and instead it will be avoiding the moving invaders. I named them corona virus : ) The viruses should move gradually so that the hero can try to avoid hitting them but the viruses are moving instantly to a random position. How can I make it move gradually to a random point?
Here is my JS code
var henryLocation = {
top: 700,
left: 700
}
var coronaLocation = [
{
top: 0,
left: 100
},
{
top: 0,
left: 300
},
{
top: 0,
left: 500
}
]
document.onkeydown = function (evt) {
console.log(evt)
if (evt.keyCode === 38 && henryLocation.top > 10) {
henryLocation.top = henryLocation.top - 10
} else if (evt.keyCode === 40 && henryLocation.top < 700) {
henryLocation.top = henryLocation.top + 10
} else if (evt.keyCode === 37 && henryLocation.left > 10) {
henryLocation.left = henryLocation.left - 10
} else if (evt.keyCode === 39 && henryLocation.left < 1360) {
henryLocation.left = henryLocation.left + 10
}
moveHenry()
}
function moveHenry () {
document.getElementById('henry').style.top = henryLocation.top + 'px'
document.getElementById('henry').style.left = henryLocation.left + 'px'
}
function locateCorona () {
document.getElementById('corona').innerHTML = ""
for (let i = 0; i < coronaLocation.length; i ++) {
document.getElementById('corona').innerHTML += `<div class="corona1" style='top:${coronaLocation[i].top}px; left:${coronaLocation[i].left}px'}}></div>`
}
}
const startBtn = document.getElementById('btn-start')
startBtn.addEventListener("click", startMoveCorona)
function startMoveCorona () {
setInterval(movingCorona, 1000)
function movingCorona () {
const randomTop = Math.floor(Math.random()*600)
const randomLeft = Math.floor(Math.random()*1300)
for (let i = 0; i < coronaLocation.length; i++) {
if (coronaLocation[i].top < 700 && coronaLocation[i].left < 1360) {
coronaLocation[i].top = randomTop
coronaLocation[i].left = randomLeft
} else if (coronaLocation[i].top > 10 && coronaLocation[i].left > 10) {
coronaLocation[i].top--
coronaLocation[i].left--
}
}
}
}
function gameLoop () {
setTimeout(gameLoop, 1000)
moveHenry()
locateCorona()
}
gameLoop()
Upvotes: 2
Views: 682
Reputation: 138
Your best bet would be to use CSS transitions. For example:
transition: top .5s ease, left .5s ease;
See the demo below:
// Prepare vars
var $object = document.getElementById('object');
var $btn = document.getElementById('btn');
var w = window.innerWidth, h = window.innerHeight;
// Attach a click handler to the button
$btn.addEventListener('click', function (event) {
// Modify the object's position to a random one within the window
$object.style.top = Math.floor(Math.random() * h) + 'px';
$object.style.left = Math.floor(Math.random() * w) + 'px';
}, false);
#object {
position: absolute;
top: 50px;
left: 30px;
width: 20px;
height: 20px;
background: red;
transition: top .5s ease, left .5s ease;
}
<div id="object"></div>
<button id="btn">Move randomly</button>
Upvotes: 1