我试图旋转角色以面对鼠标位置,仅相对于“变形”有效:(0,0,0)

时间:2018-11-03 17:02:53

标签: unity3d rotation quaternions raycasting

字符旋转,仅当鼠标绕世界中心(0,0,0)旋转时发生-

MoveToMouse()可以完美运行,单击世界上的某个点,然后播放器移动,摄像机随之跟随。

但是当按住shift键将角色旋转到鼠标指向的位置时,它只会相对于世界中心指向。

transform.LookAt-效果很好,但我希望能够使旋转平滑。

using UnityEngine;
using UnityEngine.AI;


public class ClickToMove : MonoBehaviour
{
     NavMeshAgent player;
     public float rotSpeed = 10f;

     void Start()
     {
         player = GetComponent<NavMeshAgent>();
     }

     void Update()
     {
         MoveToMouse();
         LookAtMouse();
     }

     void MoveToMouse()
     {
         if (Input.GetMouseButtonDown(1))
         {
             RaycastHit hit;

             if (Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hit, 100))
             {
                 player.destination = hit.point;
             }
         }
     }

     void LookAtMouse()
     {
         if (Input.GetKey(KeyCode.LeftShift))
         {
             RaycastHit lookHit;

             Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out lookHit, 100);

            //transform.LookAt - works perfectly, but want to be able to smooth the rotation.
            //transform.LookAt(lookHit.point);

             transform.rotation = Quaternion.Slerp(transform.rotation, 
             Quaternion.LookRotation(lookHit.point), rotSpeed * Time.deltaTime);
         }
     }
}

1 个答案:

答案 0 :(得分:0)

Quaternion.LookRotation将方向向量作为参数而不是位置。