This site is currently in read-only mode during migration to a new platform.
You cannot post questions, answers or comments, as they would be lost during the migration otherwise.
0 votes

How do you get the current face that an object or RayCast is colliding with?

Is this a job for the MeshDataTool?

Godot version 3.5.1
in Engine by (137 points)

1 Answer

0 votes

To anyone that finds this:

Use this function to get the face index of a mesh from a RayCast hit position (or any vector) and the current camera.

#Gets the face index player is activating
func get_hit_mesh_triangle_face_index(hitVector, currentCamera):
    var cubeMeshInstance = get_child(0)
    var cubeMesh = cubeMeshInstance.get_mesh()
    var vertices = cubeMesh.get_faces()
    var arrayMesh = ArrayMesh.new()
    var arrays = []
    arrays.resize(ArrayMesh.ARRAY_MAX)
    arrays[ArrayMesh.ARRAY_VERTEX] = vertices
    arrayMesh.add_surface_from_arrays(Mesh.PRIMITIVE_TRIANGLES, arrays)
    var meshDataTool = MeshDataTool.new()
    meshDataTool.create_from_surface(arrayMesh, 0)
    var camera_origin = currentCamera.global_transform.origin
    var purple_arrow = hitVector - camera_origin
    var i = 0
    while i < vertices.size():
        var face_index = i / 3
        var a = cubeMeshInstance.to_global(vertices[i])
        var b = cubeMeshInstance.to_global(vertices[i + 1])
        var c = cubeMeshInstance.to_global(vertices[i + 2])

        var intersects_triangle = Geometry.ray_intersects_triangle(camera_origin, purple_arrow, a, b, c)

        if intersects_triangle != null:
            var angle = rad2deg(purple_arrow.angle_to(meshDataTool.get_face_normal(face_index)))
            if angle > 90 and angle < 180:
                return face_index

        i += 3

    return -1
by (137 points)
Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.