I'am trying to develop a plugin that raycasts an animated mesh to produce pointcloud streams, which then are used as computer vision related training data with known ground truth poses. Everything works fine except of the raycasting when using the ray_cast function on the mesh to be sampled. Below I posted a picture depicting the problem.

left to right ray_cast works only on undeformed mesh

On the left, the mesh is undeformed, the ray used is drawn in white and a sphere is created at the hit point result from ray_cast, everything as expected. Middle and right meshs are deformed and the hit points are obviously off the surface.

The code used for raytracing:

def raytrace(obj, ray):
    drawRay([ray[0], ray[1]])
    valid, pos, _, _ = obj.ray_cast(ray[0], ray[1])
    if valid:
         bpy.ops.mesh.primitive_uv_sphere_add(segments=15, ring_count=7, radius=0.01, location=pos)

Any help is appreciated, I'am really struggling with this problem and couldn't find any workaround so far. Many thanks in advance.


1 Answer 1


Use the depsgraph

To hit the evaluated mesh use the depsgraph. (Assuming 2.8+)

Example, raycasts from global (0, 0, 10) in a negative global z direction. The object raycast uses the object space of the mesh, so convert the rays to object space and the result to global.

import bpy
from mathutils import Vector

context = bpy.context

ray_co = (0, 0, 10) 
ray_dir = (0, 0, -1)

ob = context.object
mw = ob.matrix_world
mwi = mw.inverted()

hit, loc, _, _ = ob.ray_cast(
    mwi @ Vector(ray_co),
    mwi @ Vector(ray_dir),
if hit:
        location=mw @ loc)
  • $\begingroup$ Wow, great! Thank you so much, this helped me a lot. $\endgroup$
    – patrice079
    Jun 9, 2020 at 8:45

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.