How to detect click inside StaticBody2D in Godot Game Engine?
byA simple approach to detect mouse click in our game is to intercept input event in in-built _input method. Let’s intercept the input.
extends StaticBody2D
func _input(event):
if event is InputEventMouseButton:
if event.button_index == BUTTON_LEFT and event.pressed:
print(“A click!”)
The problem is that input detection is registered all over the viewport. Let me explain. I have a Sprite child node inside StaticBody2D node. My intention is to detect mouse input over the visible sprite only. In our 2D game we may want to select an object in our world with mouse and do some interaction with it. In this case mouse input is been registered outside the Sprite node.Note that our script is attached to StaticBody2D. As a result this node has to have a shape, so the example has a collision shape as a child. We are trying to keep Sprite node loosely coupled from the logic. Documentation clearly says that StaticBody2D is not intended to move. This makes perfect for objects like trees in the game.
Let’s come back to our problem. My assumption for the behaviour would be that StaticBody2D is shapeless. Yes, we did add a collision shape so it mouse input should be triggered only over defined collision shape. However, StaticBody2D is behaving shapeless and mouse input is registered all over the screen.