Get Face of Colliding Mesh

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Blockmaster27

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

Is this a job for the MeshDataTool?

:bust_in_silhouette: Reply From: Blockmaster27

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 =
	var arrays = []
	arrays[ArrayMesh.ARRAY_VERTEX] = vertices
	arrayMesh.add_surface_from_arrays(Mesh.PRIMITIVE_TRIANGLES, arrays)
	var meshDataTool =
	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