3
$\begingroup$

In a Blender script I'm trying to cast a ray against my object and see what face it hits. However, ray_cast doesn't work in any way.

You can see in my example I try casting a ray from every angle to the center of the scene. I'm using the default cube that comes with Blender's startup scene. You can easily test this script by opening Blender and deleting everything except the startup cube.

ops = bpy.ops
scene = bpy.context.scene
current_mesh = scene.objects[ 0 ]
scene.objects.active = current_mesh
ops.object.mode_set( mode = 'OBJECT' )

print( current_mesh.ray_cast( ( 0, 0, 10 ), ( 0, 0, 0 ) )[ 0 ] )
print( current_mesh.ray_cast( ( 0, 0, -10 ), ( 0, 0, 0 ) )[ 0 ] )
print( current_mesh.ray_cast( ( 0, 10, 0 ), ( 0, 0, 0 ) )[ 0 ] )
print( current_mesh.ray_cast( ( 0, -10, 0 ), ( 0, 0, 0 ) )[ 0 ] )
print( current_mesh.ray_cast( ( 10, 0, 0 ), ( 0, 0, 0 ) )[ 0 ] )
print( current_mesh.ray_cast( ( -10, 0, 0 ), ( 0, 0, 0 ) )[ 0 ] )

You can see the result of the above script in the screenshot. Every ray cast comes up False:

raycast completely broken

I also get the same empty, incorrect results if I replace current_mesh.ray_cast with scene.ray_cast.

Why is ray casting completely broken? Since my object is at (0, 0, 0) I don't think I need to translate any of my ray origins, but either way I'm casting from every cardinal direction and nothing comes back.

I'm using Blender 2.77.

$\endgroup$
4
$\begingroup$

It turns out ray_cast takes start, direction, not start, end, as parameters.

Given a start and end, you can find the direction with something like:

direction = end - start;
direction.normalize()

Assuming that start and end are Vectors, as in start = Vector( ( 0, 10, 0 ) )

Don't trust any Google results about the Blender API docs, because the newest documentation doesn't appear in Google search results. Here's the correct documentation which won't show up when searching.

| improve this answer | |
$\endgroup$
  • 1
    $\begingroup$ Or even better - we can now use blender_python_api_current in the URL instead of a specific version that gets outdated. $\endgroup$ – sambler Jul 10 '16 at 6:48

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.