1
$\begingroup$

I do a ray_cast from the camera along its direction to get the hit face:

def find_hit_face(camera, direction):
    _, _, _, hit_face_index, hit_object, _ = (
        scene.ray_cast(
            depsgraph=context.view_layer.depsgraph,
            origin=camera.location,
            direction=direction,
            distance=camera.data.clip_end,
        )
    )
    polygons = hit_object.data.polygons()
    return polygons[hit_face_index]

But I got the error IndexError: bpy_prop_collection[index]: index 5544 out of range, size 2224.

How can I get the hit face from the hit face index?

$\endgroup$
2
  • 1
    $\begingroup$ Hello ! I think you need to use the evaluated object. I assume the object has generative modifiers that modify it's number of polygons ? $\endgroup$
    – Gorgious
    Apr 11 at 13:40
  • $\begingroup$ Thank you for the suggestion. This is exactly the problem. I've used updated_object = hit_object.evaluated_get(context.view_layer.depsgraph) instead of hit_object and it works. $\endgroup$ Apr 12 at 5:07

1 Answer 1

1
$\begingroup$

You need to query the evaluated object. By default raycasting acts on the evaluated scene so you want to query the evaluated object's polygons.

import bpy

def find_hit_face(camera, direction):
    _, _, _, hit_face_index, hit_object, _ = (
        scene.ray_cast(
            depsgraph=context.view_layer.depsgraph,
            origin=camera.location,
            direction=direction,
            distance=camera.data.clip_end,
        )
    )
    polygons = hit_object.evaluated_get(bpy.context.view_layer.depsgraph).data.polygons
    return polygons[hit_face_index]

Link to bpy.types.ID.evaluated_get docs

$\endgroup$

You must log in to answer this question.

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