How to detect click inside StaticBody2D in Godot Game Engine?


A 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.

A simple approach I discovered is two steps.


How to Set and Restrict the Camera 2d Boundary in Godot Game engine


I have been learning and practicing Godot game engine by watching free high quality video series from HeartBeast. I really want you to go and watch this RPG tutorial series to learn practical fundamentals of Godot engine. In part-20 of the series we learned about setting up camera and make camera follow the player around the level. It is very easy in Godot.

Above tutorial video lets you learn to easily setup player Camera2D. One thing was missing and I took a challenge exercise where camera stops following the player when player is near the edge or boundary of the level. Currently camera moves with player and vast empty space is visible when player is near boundary of the level.

My solution is based on existing type of game world I am working with.


Recommended posts