Discord
Login
Community
DARK THEME

Movement

I need help because I can't move my player with this code

if keyboard.UP then player.y += player.speed end

if keyboard.DOWN then player.y -= player.speed end

if keyboard.RIGHT then player.x += player.speed end

if keyboard.LEFT then player.x -= player.speed end

Thank you for the help. Alessandro

I can't see anything wrong with those lines, but it all depends on what else is going on in your code. One would have to see the whole thing to figure out what might have gone wrong.

Here a quick test:

init = function()
  player = object
    x = 0
    y = 0
    speed = 1
  end
end

update = function()
  if keyboard.UP then player.y += player.speed end
  if keyboard.DOWN then player.y -= player.speed end
  if keyboard.RIGHT then player.x += player.speed end
  if keyboard.LEFT then player.x -= player.speed end
end

Use the 'Watch' window in the console while you run it and open the player object in there. You will see that x and y update nicely.

Hope this helps
Live Long and Tinker

P.S.
Here is a sneaky way how you can replace the 4 'if' loops with 2 lines:

  player.y += (keyboard.UP-keyboard.DOWN)*player.speed
  player.x += (keyboard.RIGHT-keyboard.LEFT)*player.speed

It takes advantage that the keyboard.(key) command return '0' for nothing is pressed and '1' when the key is pressed.
So keyboard.UP-keyboard.DOWN would return the values -1 0 +1 depending on the key that is pressed. Then we multiply that by the speed and Voila, we are moving ;)

Hope it doesn't confuse :)

Post a reply

Progress

Status

Preview
Cancel
Post
Validate your e-mail address to participate in the community