I'm confused - are you wanting to detect the circle hitting the cube, the other way around, or detect the circle hitting itself? It would have been great to clarify that as well as a picture from the file:

Instead of waiting for feedback, I'll assume the first option is what you want based on your file naming convention. But first, regarding your main question of why it's returning zero, remember that the hit location given to you is in that object's local space. You don't need to convert it to local (as you did in your file). Second, self-intersections are possible, so it's best to add some epsilon to your origin (if part of the mesh is on that origin) so the ray cast doesn't accidentally hit itself at your origin.
In short, an object's ray_cast()
is only aware of itself, and therefore can only hit its own mesh. You can use the context.scene.ray_cast()
which is nice since you don't have to worry about coordinate conversion between spaces, but that means it can intersect any object.
If you want to use the object raycast, simply do the ray_cast()
function on the obstacle instead. Here's the final result (some slight refactoring for readability for other users):
import bpy
import mathutils
context = bpy.context
originObj = context.active_object
obstacle = context.scene.objects['Obstacle']
def globalToLocal(objectForLocal, vectorOrTupleToConv):
vectorified = mathutils.Vector(vectorOrTupleToConv)
return objectForLocal.matrix_world.inverted() @ vectorified
def localToGlobal(obj, vectorOrTupleToConv):
vectorified = mathutils.Vector(vectorOrTupleToConv)
return obj.matrix_world @ vectorified
#Actual ray_cast code
origin = globalToLocal(obstacle, originObj.location)
obstacle_origin = mathutils.Vector((0,0,0))
direction = obstacle_origin - origin
is_hit, location, _, _ = obstacle.ray_cast(origin, direction)
if is_hit:
'''moving some vertices to visualize the locations'''
world_loc = localToGlobal(obstacle, location)
#Ray visualized. Origin
originObj.data.vertices[0].co = (0,0,0)
print(originObj.location)
#Raycast hit location
originObj.data.vertices[1].co = globalToLocal(originObj, world_loc)