1
$\begingroup$

I'm working on a project in Blender where I need to perform raycasting from all the vertices of a plane in the direction the plane is facing. The plane represents a surface, and I want to determine if any objects intersect with the rays cast from the vertices.

I'm looking for guidance on how to achieve this. Specifically, I need help with the following:

  1. What's the proper way to calculate the direction in which the plane is facing?
  2. How can I cast rays from each vertex in the direction of the plane's normal and detect intersections with other objects (suppose a cube) in the scene?
  3. What actions can I take when a ray hits an object? For example, I may want to print information about the intersection or perform other operations.

Any example code or step-by-step instructions would be greatly appreciated. Thank you for your assistance!

$\endgroup$

1 Answer 1

1
$\begingroup$

I hope this code helps you out. The plane and Suzanne objects are obtained from bpy.data. I used the plane's matrix_world to get the true direction of its normal vector. From there I simply loop through the vertices of the plane and ray cast them towards Suzanne using obj.ray_cast. The 0th index of the cast result is a boolean determining whether or not the cast intersected. The 1st index is the location of the hit. If there was no hit, it's (0, 0, 0). I then plot some some empty's at the hit locations, if there is a hit. Note: I applied the scale and location of Suzanne (using ctrl-A) for it to register properly.

import bpy

plane = bpy.data.objects["Plane"]

mtx = plane.matrix_world

verts = plane.data.vertices

polys = plane.data.polygons

normal = mtx @ polys[0].normal

obj = bpy.data.objects["Suzanne"]

for v in verts:
    # cast_result
    # input: (origin, direction, distance, depsgraph) <---excluding depsgraph
    # cast_result returns: (T/F, hit location, normal vector at intersection face, intersection face index)        
    cast_result = obj.ray_cast(v.co, normal, distance = 1000)
    
    T_or_F = cast_result[0]
    
    hit_location = cast_result[1]
    
    print(T_or_F)
    
    print(hit_location)
    
    if T_or_F:
        bpy.ops.object.empty_add(location=hit_location)

enter image description here

$\endgroup$
3
  • 1
    $\begingroup$ You could do if T_or_F: bpy.ops.object.empty_add(... to only add empties when a ray hits. $\endgroup$ Commented Oct 21, 2023 at 10:09
  • $\begingroup$ @MarkusvonBroady done thanks for that advice $\endgroup$ Commented Oct 21, 2023 at 20:27
  • 1
    $\begingroup$ thank you! that works! $\endgroup$ Commented Nov 8, 2023 at 20:13

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .