5
\$\begingroup\$

I would like to figure out whether a collider is in a physics layer by the name (string) I set in project settings:

func _physics_process(delta):
    var collision = move_and_collide(direction * delta * speed)
    if collision and (collision.collider.collision_layer & get_collision_layer("Walls")) != 0:
        direction = direction.bounce(Vector2.LEFT)
    # more behaviors based on other layer tests

Walls is the name of the physics layer and I am trying to find get_collision_layer.

I am using Godot 3.2.1. self is a KinematicBody2D & colliders are StaticBody2D's & also KinematicBody2D's.

I have figured out the collision id (as an int) but still think it would be cleaner to use layer names, preferably using a built-in function.

\$\endgroup\$

2 Answers 2

4
\$\begingroup\$

Getting layer via name is not possible as of Godot v3.2.1.

However, you can use groups and the logic will be the same. Add the wall collision objects to a "Walls" group and then check if it's in the group instead of checking the collision layer. For example:

    if collision and collision.collider.is_in_group("Walls"):
        direction = direction.bounce(Vector2.LEFT)
\$\endgroup\$
1
  • 1
    \$\begingroup\$ Groups are OK for some usages, but you often need layer bitmasks when using Godot APIs. \$\endgroup\$ Commented Jul 22, 2021 at 17:47
5
\$\begingroup\$

Just a demo in an empty node - range starts with 1 up to the number of layers It creates a dictionary where you can access with layer name and get the number as 2 to the power of layer number - run only once in a parent node

func _ready():
    var layers = {}
    for i in range(0, 5, 1):
        var layer = ProjectSettings.get_setting("layer_names/2d_physics/layer_" + str(i + 1))
        layers[layer] = pow(2, i)
    print(layers)
    print(layers['Coins'])

{Bumpers:16, Coins:4, Enemies:2, Player:1, World:8}

4

and a working version

var is_stomping = false
var _layers := {}

func _ready():
    for i in range(0, 5, 1):
        var layer = ProjectSettings.get_setting("layer_names/2d_physics/layer_" + str(i + 1))
        _layers[layer] = pow(2, i)


func _on_StompDetector_area_entered(area: Area2D) -> void:
    is_stomping = area.collision_layer == _layers['Bumpers']
\$\endgroup\$
2
  • \$\begingroup\$ Neat. I went with @hola's suggestion of using groups though. At the time I had asked the question I wasn't aware of groups. \$\endgroup\$
    – muhuk
    Commented Sep 25, 2020 at 6:21
  • 4
    \$\begingroup\$ I know it was ages ago-but I had the same problem and it was said in few places that its impossible in current godot so I made it possible. \$\endgroup\$ Commented Sep 26, 2020 at 7:21

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .