How to calculate the distance between my player and another object?

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

So i’m using a kinematic body 3D nd i’m changing its movement direction using mouse rotation, by getting the mouse’s basis.x nd basis.z, however when i try to calculate the distance between my player (kinematic body 3d) nd a softbody it doesn’t work well, i’ve applied the formula sqrt(pow(x2-x1,2)+pow(y2-y1,2)+pow(z2-z1,2)) but it doesnt work well

it only works when iam in certain side, if i move to the other side it doesnt work

this my code for calculating the distance:

extends Spatial

func _physics_process(delta):
var x=$KinematicBody.translation.x-$SoftBody.translation.x
var z=$KinematicBody.translation.z-$SoftBody.translation.z
var y=$KinematicBody.translation.y-$SoftBody.translation.y
if (sqrt(pow(x,2)+pow(z,2)+pow(y,2))<2):
$Control.visible=true
if Input.is_action_just_pressed(“ui_accept”):
$ItemList.add_item(“tool”,load(“res://b65186fd210e34e35d0763332262993c.jpg”))
else:
$Control.visible=false

EDIT:
i want to let u guys know that i’ve found the reason of why the distance isnt calculated well, the reason is that both player nd softbody doesnt start at the same point, they both start with 0 coordinates but not at the same point, so now i just hav to find a way to get pass that

i want to let u guys know that i’ve found the reason of why the distance isnt calculated well, the reason is that both player nd softbody doesnt start at the same point, they both start with 0 coordinates but not at the same point, so now i just hav to find a way to get pass that

Mazen | 2023-01-20 11:45

:bust_in_silhouette: Reply From: magicalogic

Using global_position to calculate distances is much simpler.
In your case:

var distance = abs($KinematicBody.global_position - $SoftBody.global_position)

The abs() function makes sure you don’t get negative values as distances can not be negative.
Also am not sure you need that complicated looking formula just to calculate the distance between two objects.

i’ve tried using position as i saw in the docs, it tells me that position doesnt exist in 3d, nd i tried global_position as u suggested nd its the same thing

Mazen | 2023-01-19 15:18

:bust_in_silhouette: Reply From: Wakatta

Vectors already have that function

var distance = global_transform.origin.distance_to($SoftBody.global_transform.origin)

Oh and are you from the future? Godot version 5.3.1?

@wakatta sorry i meant to 3.5.1 i’ll edit that, i’ve tried the distance function btw, i’ve dived very deep in the docs before posting here, don’t think i’ve tried it with global_transform tho, i’ll try again nd see if it works, edit:
i’ve tried it nd it didn’t work, when i print the difference between the player nd the object its bigger than 2 even if the actual distance is equal or less than 2

Mazen | 2023-01-19 14:56