Jump to content

Javascript movement


Mollynater
 Share

Recommended Posts

I'm trying to get this red square moving but I can't get it to work. (I checked the code in a code error finder and it said that there were no errors).

here's the code

var player = null;
 
function restart(player) {
  player = document.getElementById("player");
  player.style.top = '0px';
  player.style.left = '0px';
}
 
var x = [0,'px'];
var y = [0,'px'];
 
function moveDown() {
  x[0] + 100;
 
  player.style.top = x[0] + x[1];
}
 
function moveUp() {
  x[0] - 100;
 
  player.style.top = x[0] + x[1];
}
 
function moveRight() {
  y[0] + 100;
 
  player.style.left = y[0] + y[1];
}
 
function moveleft() {
  y[0] - 100;
 
  player.style.left = y[0] + y[1];
}
 
function move(p) {
  var key = p.which || p.keyCode;
 
  switch (key) {
    case (87😞
      moveUp();
    break;
    case (83😞
      moveDown();
    break;
    case (68😞
      moveRight();
    break;
    case (65😞
      moveLeft();
    break;
  }
} 
 
window.onLoad = restart;

The id "player" is the red square.

 

the key codes in order stand for:

  • w
  • a
  • s
  • d

Can anyone help. :)

Skärmavbild 2021-01-28 kl. 22.12.43.png

Link to comment
Share on other sites

You will need to use the assignment operator if you want to change the value of a variable. It should be   x[0] = x[0] + 100; or x[0] += 100;

There's also the issue that there is no key event listener in your code that I can see.  You will need to add an event listener to listen for key presses.

Your X and Y coordinates are mixed up according to convention. X should be the distance from the left, Y should be the distance from the top.

 

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...