Unity3d 用鼠标拾取模型顶点 三
Unity3d 用鼠标拾取模型顶点 三
我们接着第二篇,描绘点的方式,就用自带的Sphere,然后做成预制件(Prefab),然后在顶点的位置,绘制Sphere,效果还可以!上一节说了,找到鼠标发出的射线与模型的碰撞面三角形(Triangle),我的做法是,判断鼠标Input.mousePosition与三角形的三个顶点哪个顶点最近,这个就是鼠标选择顶点!
代码如下:
using UnityEngine; using System.Collections; public class DrawBox : MonoBehaviour { public GameObject sphere1; // Update is called once per frame void Update () { RaycastHit hit; Ray ray = Camera.mainCamera.ScreenPointToRay(Input.mousePosition); if (Physics.Raycast(ray, out hit, 100)) { Debug.Log(hit.collider.gameObject.name); MeshCollider collider = hit.collider as MeshCollider; if (collider == null||collider.sharedMesh==null) return; Mesh mesh0 = collider.sharedMesh; Vector3[] vertices = mesh0.vertices; int[] triangles = mesh0.triangles; Vector3 p0 = hit.transform.TransformPoint(vertices[triangles[hit.triangleIndex * 3]]); Vector3 p1 = hit.transform.TransformPoint(vertices[triangles[hit.triangleIndex * 3+1]]); Vector3 p2 = hit.transform.TransformPoint(vertices[triangles[hit.triangleIndex * 3+2]]); sphere1.transform.position = MinDistanceMouse(p0, p1, p2); } } Vector3 MinDistanceMouse(Vector3 v1, Vector3 v2, Vector3 v3) { Vector3 mouseposition = Input.mousePosition; float distance1 = Vector3.Distance(v1, mouseposition); float distance2 = Vector3.Distance(v2, mouseposition); float distance3= Vector3.Distance(v3, mouseposition); if (distance1 < distance2 && distance1 < distance3) return v1; if (distance2 < distance1 && distance2 < distance3) return v2; if (distance3 < distance1 && distance3 < distance2) return v3; return Vector3.zero; } }
其中MinDistanceMouse方法就是选择哪个是离鼠标最近的点!
这一章节说到这儿,下一节开始编辑顶点,呵呵!