2D对象的旋转
public Transform from; public Transform to; public Transform fromTop; public Transform toTop; float speed = 1f; private void Update() { //方法是求两向量之间的夹角 Vector3 fromScreenPosition = RectTransformUtility.WorldToScreenPoint(Camera.main, from.position); Vector3 toScreenPosition = RectTransformUtility.WorldToScreenPoint(Camera.main, to.position); Vector3 fromTopScreenPosition = RectTransformUtility.WorldToScreenPoint(Camera.main, fromTop.position); Vector3 toTopScreenPosition = RectTransformUtility.WorldToScreenPoint(Camera.main, toTop.position); //Input.mousePosition; //第一条向量 Vector3 fromVector = fromTopScreenPosition - fromScreenPosition; //第二条向量 Vector3 toVector = toTopScreenPosition - toScreenPosition; print("两向量之间的夹角 = " + Vector3.Angle(fromVector, toVector)); Quaternion quaternion = Quaternion.FromToRotation(fromVector, toVector); from.Rotate(quaternion.eulerAngles * speed); }
在计算2D对象的屏幕坐标时,无论是使用RectTransformUtility.WorldToScreenPoint(Camera.main , from.position)还是使用Camera.main.WorldToScreenPoint(from.position)
Canvas的Render Camera是必须赋值摄像机的,不能为空!不然计算的屏幕坐标是不正确的!!!
同理,3D的旋转也可以计算两向量之间的夹角
//top.position为人物正方向点(z轴)的位置//transform.position为人物所在位置//targertPosition为目标点的位置Vector3 form = top.position - transform.position;Vector3 to = targetPosition - transform.position;float allangle = Vector3.Angle(form, to);
2D计算夹角是要保证向量的Z轴是一样的,最好为0,即为同一个水平面
3D计算夹角是要保证y轴是一样的,即为同一个水平面,上面的3D计算夹角中是要保证top、transform、targetPosition这三个对象的坐标的Y值是一样的!不然计算的夹角是有问题的,因为不在同一个水平面!