Ray sensor: calculate distance to object

I want calculate the distance from object A to object B and assign a property(float) to the distance accordingly. Being new to python this is what I came up with:

import bge

controller = bge.logic.getCurrentController()
Ray = controller.sensors[0]

if (Ray.positive):
Distance = ray.hitPosition
propertyActuator = controller.actuators[0]
propertyActuator.value = str(Distance)
controller.activate(propertyActuator)

Why is it not working? Can I do it differently?

Thanks for anwsering

Peasant

you need the distance, you are just grabbing the position, also setting a property is easy enough with python

import bge

controller = bge.logic.getCurrentController()
own = controller.owner

Ray = controller.sensors[0]

if ray.positive and ray[0]:
    distance = own.getDistanceTo(ray[0])
    own['a'] = distance

Thanks for the anwser! Still not working though. What function has ray[0] in your script?

ray[0] is ray.hitObject

did you change the ray in script? i see you used capital R i use small r

I made sure that all are small r, still not working. Here is the blend:

distance to object.blend (418.3 KB)

Sorry i assumed that the ray sensor could also use [0] to call hitObject, seems it doesn’t do that (i don’t use sensors).

so 2 things i did, one of them is needed the other is just to make it easier for yourself.

import bge

controller = bge.logic.getCurrentController()
own = controller.owner

ray = controller.sensors['ray'] #using the name of the sensor instead of the sensors index (not needed just easier to work with)

if ray.positive and ray.hitObject: #changed ray[0] to ray.hitobject
    distance = own.getDistanceTo(ray.hitObject) #changed ray[0] to ray.hitobject
    own['a'] = distance

Have fun

Cotaks
Many thanks for helping me out! It works perfectly.