phriol
phriol

Reputation: 101

Square barely moves (Javascript)

I have this small HTML application:

var hoi = document.getElementById('hoi')
var square = document.getElementById('box')
var player = {
	top: 10,
    r: 10
}
setInterval(function(){
	square.style.top = player.top + 'px';
    square.style.right = player.r + 'px;
},3000);
window.addEventListener('keydown', function(e){
	if(e.keyCode===83){
    player.top += 10;
  } else if(e.keyCode===87){
  	player.top -= 10;
  } else if(e.keyCode===68){
  	player.r -= 10;
  } else if(e.keyCode===65){
  	player.r += 10;
  }
})
body {
  background-color: #f41fff;
}

#box {
  background-color: black;
  border: solid black 1px;
  width: 50px;
  height: 50px;
  position: relative;
}
<h1 id='hoi'>HOI</h1>
<div id='box' class='box'></div>

But when I ran it, the square moved with a lot of lag. It also wasn't able to move sideways. Later when I edited it, it just stopped moving all together. I've tried so many things like changing the timing for my setInterval function, etc. Help would be greatly appreciated.

Upvotes: 1

Views: 46

Answers (2)

Daniel Barral
Daniel Barral

Reputation: 4086

https://jsfiddle.net/dzzgd3qo/

var hoi = document.getElementById('hoi')
var square = document.getElementById('box')
var player = {
    top: 10,
    r: 10
}

window.addEventListener('keydown', function(e){
  if(e.keyCode===83){
    player.top += 10;
  } else if(e.keyCode===87){
    player.top -= 10;
  } else if(e.keyCode===68){
    player.r -= 10;
  } else if(e.keyCode===65){
    player.r += 10;
  }

  document.getElementById('box').style.top = player.top + 'px';
  document.getElementById('box').style.right = player.r + 'px';

})

Upvotes: -1

Asperger
Asperger

Reputation: 3222

First of all use requestAnimationFrame as it is much smoother than setInterval for animations.

As a convention use x and y as variables since you are working with the cartesian coordinate system. Also check your console since you are missing a closing quotation mark at your px string.

Here is a minimalistic version so you can learn what ive done and where your mistakes were.

https://jsfiddle.net/9tntp2qq/

var hoi = document.getElementById('hoi')
var square = document.getElementById('box')
var position = null;
var x = 0;

function animate() {
  if(position == 'right') {
    x += 1;
    square.style.left =  x + 'px';
  }

  requestAnimationFrame(animate)
}
animate();
window.addEventListener('keydown', function(e){
 if(e.keyCode) {
    position = 'right';
  }
})

Upvotes: 2

Related Questions