DEV Community

Abd Sani
Abd Sani

Posted on • Edited on

Godot One Mouse Click Two Events

This is worth sharing. I was implementing a mouse click event on my game in Godot. This is the GScript code that I used:

func _input(event):
    if event is InputEventMouseButton:
        print("Mouse click")
Enter fullscreen mode Exit fullscreen mode

I expected this to print once every time I click my mouse. But this code actually prints twice every time the mouse is clicked.

It turned out that there are 2 events that occur every time the mouse is clicked:

  1. Event is emitted when we press down the mouse button.
  2. Event is emitted when we lift our finger from the mouse button.

So, how should we alter the code to only get one event when the mouse button is clicked?

This is what I did:

func _input(event):
    if event is InputEventMouseButton:
        if event.pressed == true:
            print("Mouse clicked!")
Enter fullscreen mode Exit fullscreen mode

So with this function, we only get when the mouse button is pressed.

You probably could write it like this too:

func _input(event):
    if event is InputEventMouseButton && event.pressed == true:
        print("Pressed")
Enter fullscreen mode Exit fullscreen mode

Here we combined the if in a single line. I, however, prefer to have multiple ifs because I find it easier to understand it when I write multiple ifs. But hey, it's up to you and the team to decide which style you like.

I also found out that you can write it like this:

func _input(event):
    if event is InputEventMouseButton && event.is_pressed():
        print("Pressed")
Enter fullscreen mode Exit fullscreen mode

At this point of my learning, I'm not really sure what is the difference between event.pressed == true and event.is_pressed()

I'll write an entry about it when I find out the differences between the two.

Thanks for reading!

Top comments (0)