首页 文章

相机在旋转时跟随物体

提问于
浏览
0

我正在尝试制作一款游戏,当相机移动时,相机跟随用户 . 我让相机成为玩家的孩子,在编辑器中,相机可以很好地围绕玩家旋转 . 当我玩游戏(在Unity中)并旋转播放器时,相机会旋转而不是围绕播放器旋转以保持相同的常规跟随距离 . 我使用transform.Rotate()来旋转播放器 .

综上所述:

  • 寻找在3D游戏中跟随玩家的相机,当玩家转动时看起来并不相同 .

  • 问题是摄像机出现在编辑器中以完美地围绕播放器旋转,但是在Unity运行期间在其上调用transform.Rotate()时却没有 .

所有帮助表示赞赏,请求帮助 .

1 回答

  • 3

    我让相机成为玩家和编辑的孩子

    这样做一切都失败了 . 如果您希望相机跟随播放器,则不要让相机成为孩子 .

    你所做的是在 Start() 函数中获取相机和播放器之间的距离 . 这也称为 offset . 在 LateUpdate() 功能中,连续将相机移动到播放器's position, then add that offset to the camera'的位置 . 它是如此简单 .

    public class CameraMover: MonoBehaviour
    {
        public Transform playerTransform;
        public Transform mainCameraTransform = null;
        private Vector3 cameraOffset = Vector3.zero;
    
        void Start()
        {
    
            mainCameraTransform = Camera.main.transform;
    
            //Get camera-player Transform Offset that will be used to move the camera 
            cameraOffset = mainCameraTransform.position - playerTransform.position;
        }
    
        void LateUpdate()
        {
            //Move the camera to the position of the playerTransform with the offset that was saved in the begining
            mainCameraTransform.position = playerTransform.position + cameraOffset;
        }
    }
    

相关问题