如何为多个虚拟相机添加相对运动?
How to add relative movement to multiple virtual cameras?
我正在使用 Cinemachine 状态驱动程序在围绕我的播放器运行的 8 个定向摄像机之间进行转换。现在我的播放器脚本设置为基本的等距角色控制器:
Player.cs
public float speed = 5f;
Vector3 forward;
Vector3 right;
// Start is called before the first frame update
void Start()
{
forward = Camera.main.transform.forward;
forward.y = 0;
forward = Vector3.Normalize(forward);
right = Quaternion.Euler(new Vector3(0, 90, 0)) * forward;
}
// Update is called once per frame
void Update()
{
if (Input.anyKey)
{
Move();
}
}
void Move ()
{
Vector3 direction = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
Vector3 rightMovement = right * speed * Time.deltaTime * Input.GetAxis("Horizontal");
Vector3 upMovement = forward * speed * Time.deltaTime * Input.GetAxis("Vertical");
Vector3 heading = Vector3.Normalize(rightMovement + upMovement);
transform.forward += heading;
transform.position += rightMovement;
transform.position += upMovement;
}
我想让玩家的移动方向反映摄像机的方向。例如,使用 W(来自 WASD)将始终使玩家向上移动。我可以编辑脚本以获取我的每个虚拟摄像机的方向并将其添加到我的播放器控制器还是有更好的方法?
要解决这个问题,你必须根据相机的角度改变按键的移动。这是通过 transform.TransformDirection
完成的。当移动与相机方向同步时,它会导致 W 键将角色压向地面,因为相机前方的角度在地面内。为了解决这个问题,我们将 y 设置为零,然后对轴进行归一化。
public float speed = 10f;
void Update()
{
var moveInput = new Vector3(Input.GetAxis("Horizontal"), 0f , Input.GetAxis("Vertical"));
moveInput = Camera.main.transform.TransformDirection(moveInput);
moveInput.y = 0;
moveInput = moveInput.normalized;
transform.position += moveInput * Time.deltaTime * speed;
}
我正在使用 Cinemachine 状态驱动程序在围绕我的播放器运行的 8 个定向摄像机之间进行转换。现在我的播放器脚本设置为基本的等距角色控制器:
Player.cs
public float speed = 5f;
Vector3 forward;
Vector3 right;
// Start is called before the first frame update
void Start()
{
forward = Camera.main.transform.forward;
forward.y = 0;
forward = Vector3.Normalize(forward);
right = Quaternion.Euler(new Vector3(0, 90, 0)) * forward;
}
// Update is called once per frame
void Update()
{
if (Input.anyKey)
{
Move();
}
}
void Move ()
{
Vector3 direction = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
Vector3 rightMovement = right * speed * Time.deltaTime * Input.GetAxis("Horizontal");
Vector3 upMovement = forward * speed * Time.deltaTime * Input.GetAxis("Vertical");
Vector3 heading = Vector3.Normalize(rightMovement + upMovement);
transform.forward += heading;
transform.position += rightMovement;
transform.position += upMovement;
}
要解决这个问题,你必须根据相机的角度改变按键的移动。这是通过 transform.TransformDirection
完成的。当移动与相机方向同步时,它会导致 W 键将角色压向地面,因为相机前方的角度在地面内。为了解决这个问题,我们将 y 设置为零,然后对轴进行归一化。
public float speed = 10f;
void Update()
{
var moveInput = new Vector3(Input.GetAxis("Horizontal"), 0f , Input.GetAxis("Vertical"));
moveInput = Camera.main.transform.TransformDirection(moveInput);
moveInput.y = 0;
moveInput = moveInput.normalized;
transform.position += moveInput * Time.deltaTime * speed;
}