[SOLVED] Using onPress with specific mouse button

I try to use this.entity.element.on(‘mousedown’, this.onPress, this); with for example the left mouse button. I already tried the two ways below, but without success…

// Select item from inventory
Inventory.prototype.onPress = function (event) {

// event is the item

    if (this.app.mouse.wasPressed(pc.MOUSEBUTTON_LEFT)) {

    }
    
    else if (this.app.mouse.wasPressed(pc.MOUSEBUTTON_RIGHT)) {

    }
};
// update code called every frame
Inventory.prototype.update = function(dt) {
    if (this.app.mouse.isPressed(pc.MOUSEBUTTON_LEFT)) {
        this.leftClick = true;
        this.rightClick = false;
    }
    
    if (this.app.mouse.isPressed(pc.MOUSEBUTTON_RIGHT)) {
        this.rightClick = true;
        this.leftClick = false;
    }
};

// Select item from inventory
Inventory.prototype.onPress = function (event) {

// event is the item

    if (this.leftClick === true) {

    }
    
    else if (this.rightClick === true) {

    }
};

Hi @Albertos,

Here is how you setup an event handler for mouse input on element, and how you check which mouse button was pressed:

Inventory.prototype.initialize = function() {
   this.entity.element.on('mousedown', this.onPress, this);
};

Inventory.prototype.onPress = function (event) {
    if (event.button === pc.MOUSEBUTTON_LEFT) {
       console.log('Left click down!');
    }
};

Hay @Leonidas! Can the event store more then one things together? Sinds the event is already the item where is pressed on…

The event is fired as a response to input on the element you attached your callback to.

The best way to reuse the same code on multiple elements is to create a single script and attach it to multiple entity elements. Like the following tutorials does, check how the same script functions on all 3 buttons:

https://developer.playcanvas.com/en/tutorials/ui-elements-buttons/

Hmm okay, I was thinking about doing that, but I thought it was an exaggeration to do that on that way. I will give it a try. Thanks!

1 Like

I only had to change this:

// Select item from inventory
Inventory.prototype.onPress = function (event) {
// event is the item
    if (this.app.mouse.wasPressed(pc.MOUSEBUTTON_LEFT)) {

    }
};

In to this:

// Select item from inventory
Inventory.prototype.onPress = function (event) {
// event is the item
    if (event.button === pc.MOUSEBUTTON_LEFT)) {

    }
};

The event is still the inventory item where is pressed on and event.button is wich button.

Great, that should work!