MouseState Component

Handles valid mouse related events and button states for the entity.

Note: This is an internally used component, automatically included in the MouseSystem.

Events

MouseDown [Data = {MouseEvent}]
when a mouse button is pressed
MouseMove [Data = {MouseEvent}]
when the mouse moves
MouseUp [Data = {MouseEvent}]
when a mouse button is released

The standard Crafty MouseEvent object:

// event name of mouse event
e.eventName

// Normalized mouse button according to Crafty.mouseButtons:
// Crafty.mouseButtons.LEFT, Crafty.mouseButtons.RIGHT or Crafty.mouseButtons.MIDDLE
e.mouseButton

// the closest (visible & Mouse-enhanced) entity to the source of the event (if available), otherwise null
e.target

// (x,y) coordinates of mouse event in world (default viewport) space
e.realX
e.realY

// Original mouse event, containing additional native properties
e.originalEvent

In addition to binding to these events, the current state (pressed/released) of a mouse button can also be queried using the .isButtonDown method.

Properties

Methods

Back to top

.lastMouseEvent

Check which read-only mouse event occured most recently (useful for determining mouse position in every frame).

Back to top

.isButtonDown()

public Boolean .isButtonDown(String mouseButtonName)
mouseButtonName

Name of the button to check. See Crafty.mouseButtons.

[Returns]

The pressed state of the button

public Boolean .isButtonDown(Number buttonId)
buttonId

ButtonId in Crafty.mouseButtons.

[Returns]

The pressed state of the button

Determine if a certain mouse button is currently down.

Example

ent.bind('UpdateFrame', function() {
  if (Crafty.s('Mouse').isButtonDown('LEFT'))
    this.y--;
});
Back to top

.resetButtonDown()

public this .resetButtonDown()

Reset all currently pressed buttons. Triggers appropriate "MouseUp" events.

This method is called internally, but may be useful when running Crafty in headless mode.

Back to top

.triggerMouse()

public this triggerMouse(String eventName, Object eventData)
eventName

Name of the mouse event to trigger ("MouseDown", "MouseUp", "MouseMove", ...)

eventData

The mouse event to trigger

Try to trigger a mouse event on this entity and persist the button state. This method prevents inconsistent button state. e.g. If this entity didn't receive a "MouseDown" previously, it won't fire a "MouseUp" event.

This method is called internally, but may be useful when running Crafty in headless mode.

Example

var wasTriggered = false;

ent.requires('MouseState')
   .bind('MouseUp', function(evt) {
      wasTriggered = true;
   })
   .triggerMouse('MouseUp', { mouseButton: Crafty.mouseButtons.LEFT });

Crafty.log(wasTriggered); // prints false