유니티3d mesh의 normal, face direction 관련된 내용

프로그래밍2019. 3. 20. 22:35

출처: https://forum.unity.com/threads/get-simple-rectangle-shaped-mesh-face-direction.264826/


정답 답변


IsGreen

IsGreen

Joined:
Jan 17, 2014
Posts:
206
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):
  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. [RequireComponent(typeof(MeshFilter))]
  5. public class temp : MonoBehaviour {
  6.  
  7.     public GameObject prefab;
  8.  
  9.     GameObject instancePrefab;
  10.     Mesh meshQuad;
  11.  
  12.     void Start(){
  13.  
  14.         meshQuad = GetComponent<MeshFilter>().mesh;
  15.         instancePrefab = (GameObject)Instantiate(prefab);
  16.  
  17.     }
  18.  
  19.     void prefabLookAt(){
  20.  
  21.         Matrix4x4 localToWorld = transform.localToWorldMatrix;
  22.  
  23.         Vector3 v0 = localToWorld.MultiplyPoint3x4(meshQuad.vertices[meshQuad.triangles[0]]);
  24.         Vector3 v1 = localToWorld.MultiplyPoint3x4(meshQuad.vertices[meshQuad.triangles[1]]);
  25.         Vector3 v2 = localToWorld.MultiplyPoint3x4(meshQuad.vertices[meshQuad.triangles[2]]);
  26.  
  27.         Vector3 normal = Vector3.Cross(v1-v0,v2-v0);
  28.      
  29.         Vector3 center = Vector3.zero;
  30.      
  31.         int i;
  32.         for(i=0;i<meshQuad.vertices.Length;i++)
  33.             center += localToWorld.MultiplyPoint3x4(meshQuad.vertices[i]);
  34.      
  35.         center /= (float)i;
  36.  
  37.         instancePrefab.transform.position = center;
  38.         instancePrefab.transform.rotation = Quaternion.LookRotation(normal);
  39.  
  40.     }
  41.  
  42.     void Update(){
  43.  
  44.         prefabLookAt();
  45.  
  46.     }
  47.  
  48. }


작성자

Posted by 드리머즈

관련 글

댓글 영역