我正在使用Unity 3D开发一款FPS射击游戏。我对Unity还比较陌生,我的玩家移动脚本有点问题。单独操作时看起来都很正常,可以自由旋转和移动玩家,但是当我同时进行这两个操作时,玩家好像会卡住,无法旋转。
有时跳跃或者在地形上移动到高处似乎可以解决这个问题,但是我已经禁用了重力、碰撞器,并将玩家移动到远离地面的位置进行了几次检查,所以问题应该出在脚本上。我也进行了一些调试,Rotate()代码确实运行了,只是旋转量似乎没有改变。
以下是玩家移动脚本:
有时跳跃或者在地形上移动到高处似乎可以解决这个问题,但是我已经禁用了重力、碰撞器,并将玩家移动到远离地面的位置进行了几次检查,所以问题应该出在脚本上。我也进行了一些调试,Rotate()代码确实运行了,只是旋转量似乎没有改变。
以下是玩家移动脚本:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(Rigidbody))]
public class PlayerMov : MonoBehaviour
{
[SerializeField]
private Camera cam;
[SerializeField]
private float speed = 5f;
[SerializeField]
private float looksensitivity = 4f;
[Header("Camera View Lock:")]
[SerializeField] //min and max amount for looking up and down (degrees)
private float lowlock = 70f;
[SerializeField]
private float highlock = 85f;
private Rigidbody rb;
private float currentrotx; //used later for calculating relative rotation
public Vector3 velocity;
public Vector3 rotation; // rotates the player from side to side
public float camrotation; // rotates the camera up and down
public float jmpspe = 2000f;
void Start()
{
rb = GetComponent<Rigidbody>();
}
// Update is called once per frame
void Update()
{
CalcMovement();
CalcRotation();
Rotate();
}
void FixedUpdate()
{
Move();
}
private void CalcRotation()
{
float yrot = Input.GetAxisRaw("Mouse X"); //around x axis
rotation = new Vector3(0f, yrot, 0f) * looksensitivity;
float xrot = Input.GetAxisRaw("Mouse Y"); //around y axis
camrotation = xrot * looksensitivity;
}
private void CalcMovement()
{
float xmov = Input.GetAxisRaw("Horizontal");
float zmov = Input.GetAxisRaw("Vertical");
Vector3 movhor = transform.right * xmov;
Vector3 movver = transform.forward * zmov;
velocity = (movhor + movver).normalized * speed;
}
void Move()
{
//move
if (velocity != Vector3.zero)
{
rb.MovePosition(rb.position + velocity * Time.fixedDeltaTime);
}
//jump
if (Input.GetKeyDown(KeyCode.Space))
{
//add double jump limit later!
rb.AddForce(0, jmpspe * Time.deltaTime, 0, ForceMode.Impulse);
}
}
void Rotate()
{
//looking side to side
rb.MoveRotation(rb.rotation * Quaternion.Euler(rotation));
// camera looking up and down
currentrotx -= camrotation;
currentrotx = Mathf.Clamp(currentrotx, -lowlock, highlock);
cam.transform.localEulerAngles = new Vector3(currentrotx, 0, 0);
}
}
以下是连接到我的播放器的相关组件:
(播放器还连接了一些其他组件,但我已经在没有它们的情况下运行测试,问题仍然存在)
就像我说的,我有点 Unity 初学者,所以我肯定错过了一些小细节,但就是找不到问题所在,我已经卡在这上面一段时间了,所以非常感谢任何帮助。