출처: https://forum.unity.com/threads/get-simple-rectangle-shaped-mesh-face-direction.264826/
정답 답변
Mesh vertices use local positions, need to convert it to world position to calculate center rectangle.
I used a Quad as rectangle in this example. Spawned object must look at to forward axis.
Code (CSharp):
using UnityEngine;
using System.Collections;
[RequireComponent
(typeof(MeshFilter
))] public class temp : MonoBehaviour {
public GameObject prefab;
GameObject instancePrefab;
Mesh meshQuad;
void Start(){
meshQuad = GetComponent<MeshFilter>().mesh;
instancePrefab = (GameObject)Instantiate(prefab);
}
void prefabLookAt(){
Matrix4x4 localToWorld = transform.localToWorldMatrix;
Vector3 v0 = localToWorld.MultiplyPoint3x4(meshQuad.vertices[meshQuad.triangles[0]]);
Vector3 v1 = localToWorld.MultiplyPoint3x4(meshQuad.vertices[meshQuad.triangles[1]]);
Vector3 v2 = localToWorld.MultiplyPoint3x4(meshQuad.vertices[meshQuad.triangles[2]]);
Vector3 normal = Vector3.Cross(v1-v0,v2-v0);
Vector3 center = Vector3.zero;
int i;
for(i=0;i<meshQuad.vertices.Length;i++)
center += localToWorld.MultiplyPoint3x4(meshQuad.vertices[i]);
center /= (float)i;
instancePrefab.transform.position = center;
instancePrefab.transform.rotation = Quaternion.LookRotation(normal);
}
void Update(){
prefabLookAt();
}
}
댓글 영역