bpy ray_cast doesn't find intersection from camera position to object position I am currently trying to discover if any background object is in front of my foreground object (obj.name = 'Mhx2test') with blenderpython. To do this, I use the ray_cast method. So what I do is sending a ray from the camera directed to the foreground model what should return a position I can compare with the position of the foreground model to determine if the first intersection was with the foreground model or any other background model. I built a very basic scene with a Cube being between the camera and the foreground object:



So the camera view shows that blue cube in front ob the foreground model. Sending a ray towards the foreground model should thus return the nearest intersection point with the cube. However when I run the following code it doesn't discover any intersection, i.e. the result is 'False'.

def detect_nearest_intersection():
    scene = bpy.context.scene
    me_tmp = bpy.data.meshes.new(name="~temp~")
    obj_tmp = bpy.data.objects.new(name=me_tmp.name, object_data=me_tmp)
    scene.objects.link(obj_tmp)
    scene.update()
    ray_cast = obj_tmp.ray_cast
    camera = bpy.context.scene.camera
    mod = bpy.data.objects['Mhx2test']
    direction = mod.location - camera.location;
    direction.normalize()
    result, location, normal, index = ray_cast(camera.location,direction)
    print("Raycast from %s to %s" % (camera.location, mod.location))
    print("Result: %s, location: %s, normal: %s, index: %s" % (result,location,normal,index))


Here is the output of the result: 

Result: False, location: &lt;Vector (0.0000, 0.0000, 0.0000)&gt;, normal: &lt;Vector (0.0000, 0.0000, 0.0000)&gt;, index: -1


The ray_cast documentation from here:


  ray_cast(origin, direction, distance=1.70141e+38) Cast a ray onto in
  object space Parameters:   distance (float in [0, inf], (optional)) –
  Maximum distance Return (result, location, normal, index): result,
  boolean location, The hit location of this ray cast, float array of 3
  items in [-inf, inf] normal, The face normal at the ray cast hit
  location, float array of 3 items in [-inf, inf] index, The face index,
  -1 when original data isn’t available, int in [-inf, inf]


I am using blender v2.78 (former versions implemented the ray_cast as ray_cast(start,end), v2.78 seems to use ray_cast(start,direction))
Transforming the world coordinates to local coordinates fixed it.