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:

My scene's camera view where the foreground model is hidden behind the blue cube

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)
    ray_cast = obj_tmp.ray_cast
    camera = bpy.context.scene.camera
    mod = bpy.data.objects['Mhx2test']
    direction = mod.location - camera.location;
    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: <Vector (0.0000, 0.0000, 0.0000)>, normal: <Vector (0.0000, 0.0000, 0.0000)>, 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))


1 Answer 1


Transforming the world coordinates to local coordinates fixed it.

  • 1
    $\begingroup$ I'm having a similar problem and this answer is very vague. I didn't downvote your answer but some elaboration would make it much more useful for people struggling with the same problem. $\endgroup$
    – andyV
    Sep 14, 2017 at 3:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.