How to Get CollisionShape2D below player(KinematicBody2D)

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

Hello,

When the character in the game dies, I would like it to fall to the floor and then play the die animation. Quite often the player in the game is jumping from platform(StaticBody2D) to platform(StaticBody2D).

My player is a KinematicBody2D. Can someone tell me how to get the area(s) directly below the player in the _physics_process so that I can move my player down to the [floor] after dying?

Thank you.

Do you want to achieve something like Mario Bros death but instead of fall off screen hit the floor?

Or you want that when your player dies get the position of the first plataform below him?

fershopls | 2020-03-01 03:41

When my player dies, I want to get the position of the top-most platform below it.

bribat123 | 2020-03-01 04:08

:bust_in_silhouette: Reply From: Eric Ellingson

One thing you could do is add a RayCast2D node to your KinematicBody2D player node that is pointing down, and extends a reasonably long distance as to ensure it will always reach to the bottom of the screen.

Then, let’s say you call a _die() function when you want to move your player:

func _die():
    var closest_platform = $RayCast2D.get_collider() # could be null
    if closest_platform:
        # use `closest_platform.position` to move
        # your player where you want it

You want to be sure to enable the RayCast2D node, and under the “collisions” option, make sure “Areas” is checked. You may also want to uncheck “Bodies”, so that if there are other entities that are bodies (enemies, etc), it doesn’t return those instead, especially if all your platforms are definitely Area2D’s.

enter image description here

Thanks for this suggestion. However it doesn’t seem to be working with sloped platforms. Is there a different method required for detecting raycadt collisions with slopes?

bribat123 | 2020-03-02 02:58

It doesn’t detect them at all? Or it doesn’t give you the position of the point where the RayCast2D is colliding on the slope?

Also, is there a reason you’re not using StaticBody2D’s for the platforms? You could then just move the KineticBody2D down until it collided with the platform, and it would stop automatically.

Eric Ellingson | 2020-03-02 03:53

I figured out why the sloped platform below the player was not being found by the RayCast and fixed it. The platforms are StaticBody2D nodes. The problem is that the player is already in a collision state with an enemy area so physics updating has been halted so my player freezes at the collision location.

bribat123 | 2020-03-03 17:01