我想创建 fps 游戏,玩家可以在其中移动 w a s d 并使用空格键跳跃,但也可以将鼠标放在游戏中心,我可以在移动相机时旋转相机还需要我检查冻结旋转 *所有游戏都是3d
使用UnityEngine; 使用 System.Collections;
[RequireComponent(typeof(Rigidbody))]
public class PlayerController : MonoBehaviour
{
public float speed = 1.5f;
public Transform head;
public float sensitivity = 5f;
public float headMinY = -40f;
public float headMaxY = 40f;
public KeyCode jumpButton = KeyCode.Space;
public float jumpForce = 10;
public float jumpDistance = 1.2f;
private Vector3 direction;
private float h, v;
private int layerMask;
private Rigidbody body;
private float rotationY;
void Start()
{
body = GetComponent<Rigidbody>();
body.freezeRotation = true;
layerMask = 1 << gameObject.layer | 1 << 2;
layerMask = ~layerMask;
}
void FixedUpdate()
{
body.AddForce(direction * speed, ForceMode.VelocityChange);
// Ограничение скорости, иначе объект будет постоянно ускоряться
if (Mathf.Abs(body.velocity.x) > speed)
{
body.velocity = new Vector3(Mathf.Sign(body.velocity.x) * speed, body.velocity.y, body.velocity.z);
}
if (Mathf.Abs(body.velocity.z) > speed)
{
body.velocity = new Vector3(body.velocity.x, body.velocity.y, Mathf.Sign(body.velocity.z) * speed);
}
}
bool GetJump()
{
RaycastHit hit;
Ray ray = new Ray(transform.position, Vector3.down);
if (Physics.Raycast(ray, out hit, jumpDistance, layerMask))
{
return true;
}
return false;
}
void Update()
{
h = Input.GetAxis("Horizontal");
v = Input.GetAxis("Vertical");
float rotationX = head.localEulerAngles.y + Input.GetAxis("Mouse X") * sensitivity;
rotationY += Input.GetAxis("Mouse Y") * sensitivity;
rotationY = Mathf.Clamp(rotationY, headMinY, headMaxY);
head.localEulerAngles = new Vector3(-rotationY, rotationX, 0);
direction = new Vector3(h, 0, v);
direction = head.TransformDirection(direction);
direction = new Vector3(direction.x, 0, direction.z);
if (Input.GetKeyDown(jumpButton) && GetJump())
{
body.velocity = new Vector2(0, jumpForce);
}
}
void OnDrawGizmosSelected()
{
Gizmos.color = Color.red;
Gizmos.DrawRay(transform.position, Vector3.down * jumpDistance);
}
}
您的代码似乎大部分是正确的。但是,您需要将
fixUpdate
替换为 update
以便自更新以来更流畅的输入处理,因为它每帧调用一次并执行。
其次,您需要将 GetJump() 方法中的 body.velocity
赋值更改为 body.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
看看是否可行