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")
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:
- Event is emitted when the we press down the mouse button.
- 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!")
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")
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")
At this point of my learning, I'm not really sure what is the difference between
event.pressed == true and
I'll write an entry about it when I find out the differences between the two.
Thanks for reading!