ray_cast() does not operate as expected


I’m using the ray_cast() function form the Object class from the bpy library (thus not the game engine).
But it seems it does not work as expected.

See the attached pictures (note: they do not show up in the order I attached them).
pict1 shows a Plane at the origin and a ray_cast() call casting a beam from above onto the middle of the pane.
This works fine and the hit point is at the origin, as you can see in the terminal window. A second ray misses the Plane and thus gives no hit.
pict2 shows the same ray casts but the Plane is now moved to a location where the second ray cast should hit. But it doesn’t. The first ray cast detects a hit at the origin. But there is no Plane there!
pict3 shows the same situation as pict2 but now the rotation and translate of the Plane are ‘Applied’ . Thus the current location becomes it origin. Now the first does not hit and the second cast hits the Plane!

I assume this is not how it is intended to work.
How can I work around this? I do not want to apply the translation and rotation etc because I need to update the position with the script repeatedly and then the position will not be correct anymore (I do not want to do that incrementally).


I think ray_cast() operates in object space and you’re assuming it’s in world space.


…or the other way around, dunno really?

Thanks Uncle Entity

I made this wrapper function to create a ray cast that works in world space:

def MyRayCast(obj, start, end):
localStart = obj.matrix_world.inverted() * start
localEnd = obj.matrix_world.inverted() * end
(loc, norm, index) = obj.ray_cast(localStart, localEnd)
location = obj.matrix_world * loc
normal = (obj.matrix_world * norm) - (obj.matrix_world * Vector((0.0, 0.0, 0.0)))
return (location,normal,index)

This is maybe not very efficient, but seems to work perfectly for me

can you elaborate on how it works

may be a more complete script using a UVsphere just to show how it works


Hello RickyBlender

It works the same as the ray_cast() form the object class.
But now in world coordinates in stead of local co-ordinates.

I convert the (world) parameters for the ray_cast() function to local coordinates and after the ray_cast() call I convert the result back to world coordinates. Thats all.

i have not realy use this raycast command before

so i was more interested in how this ray cast work from a vector point of view!

like is this raycast from a lamp or any object then being cast to any object in the scene ?

and what does this raycast provide is it like a vector from the lamp to the shortest distance to an object center or each object’s faces


It is a generic function. Not ment for something specific.
You give the ray_cast function a ray defined by a start and end point. Then it will give you the point at which it hits the object.

You may wanna use the Scene’s ray_cast() instead:bpy.types.Scene.ray_cast