Intersect ray from bottom center of collider

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

I have a KinematicBody2D with a collision shape (rectangular) and an animated sprite.

I would like to get the distance to the ground from the bottom center of the collider shape.

This is what I tried so far:

    var p = self.get_global_position()
	var bottom_right = p + collider_extent * (Vector2(1, 1))
	var bottom_left = p + collider_extent * (Vector2(-1, 1))
	var bottom_middle = (bottom_left + bottom_right) / 2

	var result = space_state.intersect_ray(bottom_middle, Vector2(bottom_middle.x, 500), [self])
	if result:
		distance_to_floor = result.position.distance_to(self.position)
	print (distance_to_floor)

It works but the distance seems to be calculated from the middle center coordinates instead of the bottom because when the player hits the ground the distance is always half of the size of the node, instead of 0.


:bust_in_silhouette: Reply From: c-o-d-e

You’re complicating things a bit here. Assuming that collider_extents is the extents of the collision shape, all you need should be this:

var p = self.get_global_position()
var bottom_middle = p + Vector2(0, collider_extent.y)

var result = space_state.intersect_ray(bottom_middle, bottom_middle + Vector2(0, 500), [self])
if result:
	distance_to_floor = result.position.distance_to(bottom_middle)

To answer your question, calculate the distance to bottom_middle instead of the position (centre).

If your result is not quite 0, that’s because of the collision safe margin.