Skip to content
SoJS coder edited this page Dec 26, 2023 · 4 revisions

Input Class

Anvil.js uses it's own proprietary input monitoring system for ease of use and customization. Input Monitors are created and monitor all input from the user... including mouse clicks.

Monitoring Keyboard Input

To create a monitor, create a new instance of the input class and pass the key code of the key you want to monitor.

const keyUp = new Input(“ArrowUp”,fireRate)

fireRate is the number of milliseconds in between each event “fire”.

Monitoring Mouse Input

const clickM = new Input("click") // fireRate is not needed here

Handling Keyboard Events

To handle the event, attach an “on” function to your monitor.

keyUp.on = (event)=>{
   console.log(“Key press”);
}

Handling Mouse Events

Handling mouse events uses the same syntax as keyboard events:

clickM.on = (object) =>{
}

The differences

  • instead of passing an event object, the GameObject that was clicked is passed.
  • Inside the function, to modify GameObjects in a way that allows them to return to their orignal state after the key is lifted, use GameObject.state()
  • When activating a mouse click monitor, pass the scene you want to activate it on as well (clickM.activate(scene))

For example:

clickM.on = (object)=>{
    object.state("backgroundColor","yellow");
}

This code will turn any clicked polygon yellow, as long as the user keeps the mouse press down. Once the mouse is lifted, the object will return to it's original state. You can also change attributes permanently but just setting them... for example object.backgroundColor = "yellow". This will not, however, return the object to its original state.

Finally, activate the monitor.

keyUp.activate()

You can also deactivate it using monitor.deactivate()

Note: to reactivate it, use monitor.reactivate() not monitor.activate()

Properties

  • clickMonitor (Boolean): true if the monitor looks for click events
  • key (String): JS key code of the key that the monitor monitors (if it is a clickMonitor, this is set to "click")
  • id (String): UID for the monitor
  • fireInterval (Interval): reference to interval that fires on function
  • firing (Boolean): True if the event is currently being fired, false otherwise

Methods

Assign an "on" method to the class before calling activate, otherwise it will not work and throw an error.

  • startFiring(event): force the event to start firing (even if no key was clicked. event will be passed to on if it is not a click monitor)
  • stopFiring(): force the event to stop firing (even if no key was lifted)
  • activate(): initializes the monitor (set Input.on before this)
  • deactivate(): temporarily deactivates the monitor
  • reactivate(): reactivates the monitor (use this instead of activate after deactivating)