为了账号安全,请及时绑定邮箱和手机立即绑定

如何在 Unity 中以第三人称视角让摄像机围绕玩家旋转?

如何在 Unity 中以第三人称视角让摄像机围绕玩家旋转?

C#
qq_遁去的一_1 2022-11-21 16:46:40
我正在尝试让摄像机围绕玩家旋转,以便玩家始终位于屏幕中间。我试过使用这个Slerp()功能。using UnityEngine;using System.Collections;public class rotate : MonoBehaviour{    public Transform target;    public float Speed = 1f;    public Camera cam;    public Vector3 offset;    void Update()    {        Vector3 direction = (target.position - cam.transform.position).normalized;        Quaternion lookrotation = target.rotation;        Quaternion playerrotation = target.rotation;        playerrotation.y = target.rotation.y;        playerrotation.x = 0f;        playerrotation.z = 0f;        lookrotation.x = transform.rotation.x;        lookrotation.z = transform.rotation.z;        //lookrotation.y = transform.rotation.y;        offset.x = -target.rotation.x * Mathf.PI;        transform.rotation = Quaternion.Slerp(transform.rotation, playerrotation, Time.deltaTime * Speed);        transform.position = Vector3.Slerp(transform.position, target.position + offset, Time.deltaTime * 10000);    }}它有效,但播放器不在屏幕中间。
查看完整描述

1 回答

?
慕哥9229398

TA贡献1877条经验 获得超6个赞

以下脚本将旋转它附加到的游戏对象,以便将游戏对象保持在Target屏幕的中心,并使相机看起来与目标的方向相同。


public Transform Target;

public float Speed = 1f;

public Vector3 Offset;

void LateUpdate()

{

    // Compute the position the object will reach

    Vector3 desiredPosition = Target.rotation * (Target.position + Offset);


    // Compute the direction the object will look at

    Vector3 desiredDirection = Vector3.Project( Target.forward, (Target.position - desiredPosition).normalized );


    // Rotate the object

    transform.rotation = Quaternion.Slerp( transform.rotation, Quaternion.LookRotation( desiredDirection ), Time.deltaTime * Speed );


    // Place the object to "compensate" the rotation

    transform.position = Target.position - transform.forward * Offset.magnitude;

}

注意:永远,永远,永远不要操纵四元数的组件,除非你真的知道你在做什么。四元数不存储您在检查器中看到的值。它们是用于表示旋转的复杂实体,具有 4 个值。


查看完整回答
反对 回复 2022-11-21
  • 1 回答
  • 0 关注
  • 165 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信