1
This commit is contained in:
53
Src/Unity/Scripts/Physics/GetClosestPointFromMesh.cs
Normal file
53
Src/Unity/Scripts/Physics/GetClosestPointFromMesh.cs
Normal file
@@ -0,0 +1,53 @@
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using UnityEditor;
|
||||
using UnityEngine;
|
||||
|
||||
namespace BITKit.Physics
|
||||
{
|
||||
public readonly struct GetClosestPointFromMesh:IClosePointProvider
|
||||
{
|
||||
private readonly Vector3 _position;
|
||||
private readonly Mesh _mesh;
|
||||
|
||||
public GetClosestPointFromMesh(Mesh mesh, Vector3 position)
|
||||
{
|
||||
_mesh = mesh;
|
||||
_position = position;
|
||||
}
|
||||
|
||||
public bool TryGetValue(out Vector3 position, out Collider collider)
|
||||
{
|
||||
position = default;
|
||||
collider = default;
|
||||
|
||||
if (_mesh.isReadable is false) return false;
|
||||
|
||||
|
||||
var vertices = _mesh.vertices;
|
||||
|
||||
if (vertices.Length > 2048) return false;
|
||||
|
||||
var minPos = new Vector3(64, 64, 64);
|
||||
|
||||
for (var index = 0; index < _mesh.triangles.Length; index+=3)
|
||||
{
|
||||
var x = vertices[_mesh.triangles[index]];
|
||||
var y = vertices[_mesh.triangles[index + 1]];
|
||||
var z = vertices[_mesh.triangles[index + 2]];
|
||||
|
||||
var pos = GeometryUtils.GetPosInTriangle(x, y, z, _position);
|
||||
|
||||
if (Vector3.Distance(pos, _position) < Vector3.Distance(minPos, _position))
|
||||
{
|
||||
minPos = pos;
|
||||
}
|
||||
}
|
||||
|
||||
position = minPos;
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user