+ 1
Moving an image
So I am doing a new project, and this project will be a game, tennis. I am trying to create a 2-player game, but I am currently stuck on moving an image. I have managed to move the image by holding down the "WASD", or arrow keys, but they move across the screen unexpectedly. How do I fix this? You can see my code here and try to move the characters: https://code.sololearn.com/WJRPNb50TQue/#js
1 Réponse
+ 3
Your way of speed += 2 and then left/top = - speed is wrong! Your player will jump like crazy between different quadrants with respect to the page origin 0, 0
You need to separate position variables and speed variable:
var playerLeft, playerTop;
// and then initialize them with value of your start position
const speed = 2; // constant
//move left
playerLeft += speed;
.style.left = playerLeft + "px" ; //use your own dom name
//move right
playerLeft -= speed; /* you see? Update Current position by minus speed. */
.style.right = player Left + "px" ; // use your own dom name
Same idea for moving up and down, I leave it to yourself as homework.
And oh, because you have two players
For players positions you need two pairs:
player1_left
player1_top
player2_left
player2_top