How does ray_cast() work?

I haven’t found any decent documentation. All example code I find is either in someone’s question about something not working, or is doing something way more sophisticated than I’m interested in. The documentation at docs.blender.org leaves a lot unsaid.

Just how does ray_cast() work?

What’s the difference between scene.ray_cast() and some_object.ray_cast()? (some_object is obtained by something like bpy.data.objects[‘FooBar’])

In what coordinate system to I set the components of the ray start point and direction?
I believe (but don’t know) that some_object.ray_cast works with given vectors in the object’s local coordinate system. scene.ray_cast() uses global coords. Is the result in the same coords as the given vectors?

What does ray_cast return? I see examples of a tuple of five things, but sometimes four things. I think I saw six things in a tuple once. What should it be?

I want to cast rays from certain locations near and relative to a camera. I tried using the_camera.ray_cast() but it failed with an exception, saying the camera doesn’t have a mesh. Why does some_object.ray_cast() need for some_object to have a mesh?

If I care about intersections with only certain target objects, is there a way to limit the search to those? In my case, I’m testing only a few rays in per frame in a simple animation and simple model, so this isn’t important, but good to know anyway.

Does ray_cast take any optional keyword args? Is there anything else one should know about ray_cast()?

scene cast uses current scene meshes for casting, from any point. So if you hide object from scene - ray_cast WILL NOT hit it. Uses global coords

Object cast uses mesh of the very object only. So you will not hit any other objects in scene when use object cast. Uses local coords

For other questions read docs, all blender ops are well documented (not always but good enough). i suggest you also read about BVHTree from mathutils.bvhtree. This also has ray_casts. It`s faster, managable and you can put different objects into same bvh (or use several), there is no other way to limit objects that should affect ray casts

2 Likes