Help with keyboard input.

  1. 2 years ago
    Edited 2 years ago by Platinum Frog

    I can't quite grasp how input works. I've been reading the learn section on this website, and with the knowledge, trying to make a function where you put in the key's name and it checks and returns wether it is pressed. Here is what I've got:

    Services.Input:addEventListener(nil, onKeyDownEvent, InputEvent.EVENT_KEYDOWN)
    Services.Input:addEventListener(nil, onKeyUpEvent, InputEvent.EVENT_KEYUP)
    	local inputEvent = InputEvent
    	if inputEvent:keyCode() == key then
    		print("A key was pressed")
                    return true
                    return false

    Could you tell me what I should do? / Did wrong?
    PS. I'm using Lua.

  2. fodinabor

    2 Jun 2016 Administrator

    maybe have a look at this very cool new video:

  3. Thank you! That was so helpful!

  4. last year
    Edited last year by polarity

    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
    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
    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))

or Sign Up to reply!