3Dオブジェクトについて、頂点を画面上でタッチ&ドラッグした時に、その頂点がドラッグに追従して移動し、メッシュが変形する処理を作りたいです。
下記のコードを書いてみたのですが、mesh.verticesに入力した頂点座標と、実際の移動後の頂点座標が一致しません。
コードのどこでミスをしてしまっているのでしょうか?
public class NewBehaviourScript : MonoBehaviour { public MeshFilter MF;//変形対象である3DオブジェのMeshFilter private Vector3[] AllVertices;//MFのmesh.verticesと対応させる配列 public GameObject p;//目印としてマウスに追従するSphereオブジェクト private VerticesSet nearestVS;//タッチした点に最も近い頂点の情報を入れます public class VerticesSet//ある頂点の「座標」と「その頂点を成すvetice達の、AllVerticesにおけるインデックス番号」を保持するクラス { public Vector3 vec;//その頂点の座標 public List<int> nums;//AllVertices[nums]がvecと同値になる } private List<VerticesSet> VSList;//全頂点分のVerticesSetを保持 // Use this for initialization void Start () { AllVertices = MF.mesh.vertices; VSList = new List<VerticesSet>(); VSListSet(); } // Update is called once per frame void Update () { if (Input.GetMouseButtonDown(0)) { nearestVS= SelectNearestVertice(); } if (Input.GetMouseButton(0)) { Ray mouseRay = Camera.main.ScreenPointToRay(Input.mousePosition); RaycastHit hit = new RaycastHit(); if (Physics.Raycast(mouseRay,out hit)) { Vector3 hitPoint = hit.point;//バックの黒い壁とmouseRayの交点座標 nearestVS.vec = hitPoint; for (int x = 0; x < nearestVS.nums.Count; x++) { AllVertices[nearestVS.nums[x]] = hitPoint; } MF.mesh.vertices = AllVertices; p.transform.position=hitPoint; Debug.Log(hitPoint); Debug.Log(nearestVS.vec); Debug.Log(AllVertices[nearestVS.nums[0]]); } } } private void VSListSet()//全頂点分のVerticesSetを作り、VSListに格納。ここは問題なさそうです。 { List<int> counter = new List<int>(); for(int x = 0; x < AllVertices.Length; x++) { counter.Add(x); } for(int x = 0; 0 < counter.Count; x = counter[0]) { List<int> c = new List<int>(); var vs = new VerticesSet { vec=AllVertices[x],nums=new List<int>() }; for (int y = 0; y < counter.Count; y++) { if (AllVertices[x] == AllVertices[counter[y]]) { c.Add(counter[y]); vs.nums.Add(counter[y]); } } for (int z = 0; z < c.Count; z++) { counter.Remove(c[z]); } VSList.Add(vs); if (counter.Count == 0) { break; } } } private VerticesSet SelectNearestVertice()//タッチした座標と最も近い頂点についてのVerticesSetを出力。ここも問題なさそうです。 { Vector2 MousePos = new Vector2(Input.mousePosition.x, Input.mousePosition.y); Vector3 VecToWP = Camera.main.WorldToScreenPoint(VSList[0].vec); Vector2 v = new Vector2(VecToWP.x, VecToWP.y); float distance=(MousePos-v).sqrMagnitude; int whichVS = 0; for(int x =0; x < VSList.Count; x++) { Vector3 v3 = Camera.main.WorldToScreenPoint(VSList[x].vec); Vector2 v2 = new Vector2(v3.x, v3.y); var d = (MousePos-v2).sqrMagnitude; if (distance >= d) { distance = d; whichVS = x; } } return VSList[whichVS]; } }
回答1件
あなたの回答
tips
プレビュー