Last active 9 months ago
If you notice in the tutorial, the movement gets faster as you hold the key down. This is because keyDown events continue to be generated, with each one adding to the move distance.
I made some modifications to my code to ignore any additional keyDown events, until a corresponding keyUp event has happened.
It also avoids unexpected keyboard behaviour by allowing for multiple keys to be held down at once, and cancel each other out if they're for opposite directions, until one of them is released (although there may be a limit to how many simultaneous key presses are registered, due to the keyboard hardware. On one keyboard I can't hold W,S,A and D down and have the object be stationary, but on my gaming keyboard with full rollover , I can).
local move_x, move_z = 0,0 local wDown, sDown, aDown, dDown = false, false, false, false local moveDistance = 1 function onKeyDown(keyCode) if keyCode == KEY_w and not wDown then move_z = move_z - moveDistance wDown = true elseif keyCode == KEY_s and not sDown then move_z = move_z + moveDistance sDown = true elseif keyCode == KEY_a and not aDown then move_x = move_x - moveDistance aDown = true elseif keyCode == KEY_d and not dDown then move_x = move_x + moveDistance dDown = true end end function onKeyUp(keyCode) if keyCode == KEY_w then move_z = move_z + moveDistance wDown = false elseif keyCode == KEY_s then move_z = move_z - moveDistance sDown = false elseif keyCode == KEY_a then move_x = move_x + moveDistance aDown = false elseif keyCode == KEY_d then move_x = move_x - moveDistance dDown = false end end function Update(elapsed) if wDown or sDown or aDown or dDown then sphere:setPosition(sphere:getPosition().x + (move_x * elapsed), sphere:getPosition().y, sphere:getPosition().z + (move_z * elapsed)) end end