gpt4 book ai didi

c# - 无法让我的相机正确限制其旋转

转载 作者:太空宇宙 更新时间:2023-11-03 12:11:05 25 4
gpt4 key购买 nike

在我的游戏中,我想夹住玩家的相机,使其无法进行前空翻或后空翻。我想将 x 轴固定在 -75 到 50 之间,但它不起作用。

每次我添加一个夹子(例如我的代码中的那个)时,相机不想将它的旋转从 0,0,0 移动到比 Input.GetAxisRaw 表示鼠标正在移动的更远的位置。

我也尝试过将 if 语句用作手动钳位,但如果我切换极性,它要么一直保持在 0,0,0,要么一直保持在 -75,0,0。

我已经尝试更换摄像头,以防它与其设置相关但没有任何变化。

我不想发布这个,因为它不应该这么难,但我已经花了好几天时间,但我别无选择;非常感谢任何和所有想法。

我使用 Visual Studio 作为我的编辑器。

using UnityEngine;

public class PlayerMove : MonoBehaviour {

Rigidbody rb;

public Camera cam;
public Transform camTrans;

Vector3 movement;
Vector3 rotation;

public float sensitivityX;
public float sensitivityY;
public float playerSpeed;
public float jumpForce;
float forward;
float sideways;

void Start()
{
rb = GetComponent<Rigidbody>();
}

void FixedUpdate ()
{
forward = Input.GetAxisRaw("Vertical");
sideways = Input.GetAxisRaw("Horizontal");
movement = new Vector3 (forward, 0, -sideways).normalized;

float _xRot = Input.GetAxisRaw("Mouse Y");
float _yRot = Input.GetAxisRaw("Mouse X");

rotation = new Vector3(0f, _yRot, 0f) * sensitivityX;

float _jump = Input.GetAxisRaw("Jump");

if (movement != Vector3.zero)
{
MovePlayer();
}
if (rotation != Vector3.zero && Input.GetAxisRaw("Fire2") != 0 || _xRot != 0 && Input.GetAxisRaw("Fire2") != 0)
{
Rotate(-_xRot);
}
if (_jump != 0f)
{
Jump();
}
}

void MovePlayer()
{
float _playerSpeed;
_playerSpeed = playerSpeed * 0.1f;
transform.Translate(movement * _playerSpeed * Time.fixedDeltaTime, Space.Self);
}

void Jump()
{
if (IsGrounded())
{
rb.AddForce(new Vector3(0, 1 * jumpForce, 0), ForceMode.Impulse);
}
}

void Rotate(float _camRot)
{
camTrans.Rotate(new Vector3(_camRot * sensitivityY, 0, 0));
float _camPosX = camTrans.rotation.x;
Mathf.Clamp(_camPosX, -75, 50);
camTrans.rotation = Quaternion.Euler(new Vector3(_camPosX, 0, 0));
rb.MoveRotation(rb.rotation * Quaternion.Euler(rotation * sensitivityX));
}

bool IsGrounded()
{
RaycastHit hit;
return Physics.Raycast(transform.position, Vector3.down, out hit, 1.001f);
}
}

最佳答案

Input.GetAxisRaw("Mouse Y"); 返回鼠标移动的单位数(参见 Unity Documentation - Input.GetAxisRaw)。

当您移动鼠标时,脚本会运行,但是因为 void Rotate()Update() 函数中调用了每一帧,在某些帧 输入之后。 GetAxisRaw("鼠标 Y");返回 0,然后 _camRot = 0

所以,camTrans.rotation = Quaternion.Euler(new Vector3(0, 0, 0)); 并且因为 Update() 每秒调用多次,我们认为相机始终保持在 0,0,0。

要限制旋转,您可以将代码更改为:

public class PlayerMove : MonoBehaviour 
{
...

private float rotationX;

...

void Rotate(float _camRot)
{
rotationX += _camRot * sensitivityY;
rotationX = Mathf.Clamp(rotationX, -75, 50);
camTrans.localEulerAngles = new Vector3(rotationX, camTrans.localEulerAngles.y, camTrans.localEulerAngles.z);

rb.MoveRotation(rb.rotation * Quaternion.Euler(rotation * sensitivityX));
}
}

希望对你有帮助。

关于c# - 无法让我的相机正确限制其旋转,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52286966/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com