0 votes

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?

in Engine by (37 points)

1 Answer

+3 votes
Best answer

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

by (1,517 points)
selected by

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.


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"
Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.