I'm writing a little game with vueJS as the frontend. I managed to create all the needed objects and now I want to make them move if a key is pressed.
My problem is I can only move them once when the key is pressed. I want to move it consistently while the key is pressed.
My Code for moving is:
let myCircle = document.querySelector('.ball');
var key_left = false;
window.addEventListener('load', () =>{
myCircle.style.position = 'absolute';
myCircle.style.left = 0 + 'px';
myCircle.style.top = 1200 + 'px';
});
window.addEventListener('keyup', (event) => {
if (event.key == 'ArrowLeft')
key_left = true;
if (key_left == true)
{
myCircle.style.left = parseInt(myCircle.style.left) - 5 + 'px';
}
When I tried to add a while loop it stopped moving at all.
Code:
let myCircle = document.querySelector('.ball');
var key_left = false;
window.addEventListener('load', () =>{
myCircle.style.position = 'absolute';
myCircle.style.left = 0 + 'px';
myCircle.style.top = 1200 + 'px';
});
window.addEventListener('keyup', (event) => {
if (event.key == 'ArrowLeft')
key_left = true;
while (key_left == true)
{
myCircle.style.left = parseInt(myCircle.style.left) - 5 + 'px';
}
});
Does someone have a hint for me?
Thanks!