GETTING THE DISTANCE BETWEEN RAYCAST AND COLLIDING OBJECT

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

so i want to get the distance btw the raycast and colliding objects as i want to perform some calculations with that value just cant get the right method from raycast to get the job done

:bust_in_silhouette: Reply From: kidscancode

It’s a little bit unclear from your question, but I think you’re asking for the length of the ray when it collides.

First, to get the position where the RayCast collided, you use get_collision_point(). Then you find the distance from that point to the raycast’s origin. Keep in mind that the function returns the collision point in global coordinates.

if $RayCast.is_colliding():
    var origin = $RayCast.global_transform.origin
    var collision_point = $RayCast.get_collision_point()
    var distance = origin.distance_to(collision_point)

thanks for the reply was straightforward and giving wat i want thanks

pro | 2020-04-08 08:21

:bust_in_silhouette: Reply From: njamster

Put these lines into a script attached to your RayCast2D/3D-node:

var origin = global_position
var collision_point = get_collision_point()
var distance = origin.distance_to(collision_point)

thanks for the answer

pro | 2020-04-08 08:20

its correct, although “global_position” is related to 2D only

comanche | 2021-03-20 15:32