旋转相机向量以查看玩家Unity

时间:2019-08-25 19:00:51

标签: unity3d vector camera

我创建了一个游戏,例如迷你高尔夫/泳池。我想要一台跟随玩家的相机。

位置通常没问题,我得到了球的方向,然后弯腰。 旋转几乎可以。目前,可以通过Y轴旋转,但相机会向前看,并且不要向下看播放器: enter image description here

enter image description here

我已经尝试了很多事情,四元数angleToaxis,四分之一像素外观...但是看起来并不好,相机会移开视线... 这是我的代码

namespace CameraManagerNameSpace
{
    public class CameraManager : MonoBehaviour 
    {
        public float cameraHeight=13f;
        public PlayerNameSpace.Player playerToFollow; 
        public float followSpeed = 3f;
        public float rotationSpeed = 1f;

        float distance;
        Vector3 position;
        Vector3 newPos;
        Quaternion rotation;
        Quaternion newRot;
        Vector3 playerPrevPos, playerMoveDir;
        bool firstMoveDone=false;

        void Start() 
        {
            playerPrevPos = playerToFollow.player_transform.position;
            distance = Vector3.Distance(transform.position,playerToFollow.player_transform.position);
        }

        void FixedUpdate() 
        {
            if(Vector3.Distance(playerToFollow.player_transform.position ,playerPrevPos)>0.5f || firstMoveDone)
            {
                playerMoveDir = playerToFollow.player_transform.position - playerPrevPos;
                firstMoveDone = true;
            }
            else 
            {
                playerMoveDir = new Vector3(0,0,0);
            }

            if (playerMoveDir != Vector3.zero)
            {
                playerMoveDir.Normalize();

                newPos = playerToFollow.player_transform.position - playerMoveDir * distance;
                newRot =Quaternion.LookRotation(playerMoveDir,Vector3.up);

                position = Vector3.Lerp(transform.position, new Vector3(newPos.x,newPos.y+cameraHeight,newPos.z), followSpeed * Time.deltaTime);
                rotation = Quaternion.Lerp(transform.rotation, newRot, rotationSpeed * Time.deltaTime);

                transform.position = position;
                transform.rotation = rotation;

                playerPrevPos = playerToFollow.player_transform.position;
            }
        }
    }
}

我也不知道为什么,但是当球停下来之后,相机会继续做一些非常生涩,颠簸,停止的运动。

1 个答案:

答案 0 :(得分:2)

进场

newRot = Quaternion.LookRotation(playerMoveDir,Vector3.up);

您说的是照相机的视线应与播放器的移动方向相同...而不是视线。如果您不给相机在Y轴上的额外位置偏移,这将起作用。


您可能想尝试

// vector pointing from the camera towards the player
var targetDirection = playerToFollow.player_transform.position - transform.position;
newRot = Quaternion.LookRotation(targetDirection, Vector3.up);

您还应该使用Update,因为FixedUpdate仅用于与物理相关的事物(另请参见Update & FixedUpdate