DE EN FR ES IT CZ

6. Reacting to keys and the mouse

Reacting to keys and the mouse

Pia presses a big button, the light bulb above her lights up

Some things should apply throughout the game, not just in one action. For this you register an event handler in a definition script: a function that Visionaire calls when a certain event happens.

A key for hints

On the scene, create an action give_hint with the execution type "Called by other action" that displays a hint. Then:

function keyHandler(eventType, character, keycode, modifiers)
  if eventType == eEvtKeyUp and character == "h" then
    startAction(Actions["give_hint"])
    return true    -- key handled
  end
  return false     -- Visionaire handles everything else as usual
end

registerEventHandler("keyEvent", "keyHandler")

The return value matters: true means the engine ignores this key. If you return true for every key, Escape, for example, stops working.

Simple key actions can also be created in the editor without Lua. The handler pays off when you want to handle keys depending on the game state.

The mouse wheel

function mouseHandler(eventType, position)
  if eventType == eEvtMouseWheelUp then
    print("Wheel up at " .. position.x .. ", " .. position.y)
  end
end

registerEventHandler("mouseEvent", "mouseHandler", {eEvtMouseWheelUp, eEvtMouseWheelDown})

Running something later

setDelay(2000, function()
  print("Two seconds later")
end)

Careful with the main loop

A handler for "mainLoop" runs about 60 times per second. Whatever is in there costs processing time on every frame. Only use it when there is really no other way, and keep it short.

Rule to remember
Event handlers belong in definition scripts and should only do what is necessary.

Your task
Rebuild the hint key. Then check whether Escape still works in the game.