Automating the Creation of CollisionShape2d Based on Patterns in Scenes

Godot Version

4.3.1

Question

I am working on a 2d top-down game. Many scenes have a consistent pattern: green is grass, blue is water. I want to make CollisionShape2d nodes to slow the player movement down in grass and prevent them from walking over water. I also want to be able to change my scenes without needing to re-draw all of these objects. I’m wondering whether there is a way to write a script to automate the creation of CollisionShape2d nodes based my scenes. E.g, make slow-down areas over big patches of green and movement fences around big patches of blue.

Instead of using CollisionShape2D, you could have your player check what they’re standing on, and then depending on what they’re standing on, slow down or prevent movement. This could eliminate all need for CollisionShape2Ds. A script for it (in your player’s code) would look something like this:

var speed = 1
func _process(_delta: float) -> void:
    # take movement inputs and figure out where you're going to go.
    var move_delta : Vector2 = get_move_delta()  * speed
    var next_position : Vector2 = move_delta + self.position
    
    # get the type of ground that you're going to be on
    var next_pos_ground_type = get_ground_type(next_position)
    if next_pos_ground_type == "normal":
        speed = 1
    elif next_pos_ground_type == "grass":
        speed = 0.5
    elif next_pos_ground_type == "water":
        return # to prevent movement
    
    position = next_position

get_ground_type() is probably going to be the hardest function to implement. Could you send a photo of your game’s world and sprite tree? The function will depend on how your world is set up (with Sprite2D or TileMapLayer).

Hope this helps!

You can assign custom data to a tile in a TileSet and have the player check the data of the tile it’s currently on.