How to know which wall has collided when using KinematicBody2D with move_and_slide

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Levi Lindsey

I’m making a simple platformer.

I’m just wondering what would be the cleanest way to determine which wall was collided (i.e., the left one or the right one) when KinematicBody2D.is_on_wall() is true (I’m using move_and_slide with Vector(0,-1), so there is one floor, one ceiling, and two walls).

Right now, the best approach I’m thinking of is to keep track of the last non-zero x-velocity, and check whether it was positive or negative. But is there any simpler way?

:bust_in_silhouette: Reply From: omggomb

According to the docs you can use get_slide_collision(idx) to get the collision objects for each call to move_and_slide. You can then test the collision’s collider property for the type you need to identify the wall (special node, node name, position etc).
Relevant doc entry

Ah, thanks. It looks like in my case, the KinematicCollision2D.normal member is probably more useful, since I only really care about whether the player is colliding to the left or to the right. But using KinematicBody2D.get_slide_collision definitely seems like the way to go. I’ll also have to loop through each index, from 0 to KinematicBody2D.get_slide_count, and check the normal of each collision until I find one with a non-zero x component, but that should be easy enough.

Thanks!

Edit: For completion’s sake, here’s the helper function I came up with:

func get_which_wall_collided():
    for i in range(get_slide_count()):
        var collision = get_slide_collision(i)
        if collision.normal.x > 0:
            return "left"
        elif collision.normal.x < 0:
            return "right"
    return "none"

Levi Lindsey | 2019-02-15 02:42