Files
2026-03-04 10:03:45 +08:00

121 lines
2.6 KiB
C#

using UnityEngine;
namespace Artngame.SKYMASTER
{
[RequireComponent(typeof(CharacterController))]
public class FirstPersonController : MonoBehaviour
{
public float speed;
public float upDownRange;
public float jumpSpeed;
private float verticalRotation;
private CharacterController cc;
private bool rotate;
private float currentSpeed;
private bool flying;
private float verticalVelocity;
private void Start()
{
cc = GetComponent<CharacterController>();
rotate = true;
SetCursorState(CursorLockMode.Locked);
}
private void SetCursorState(CursorLockMode wantedMode)
{
Cursor.lockState = wantedMode;
Cursor.visible = CursorLockMode.Locked != wantedMode;
}
private void OnControllerColliderHit(ControllerColliderHit hit)
{
float num = currentSpeed * 0.5f;
Rigidbody attachedRigidbody = hit.collider.attachedRigidbody;
if (!(attachedRigidbody == null) && !attachedRigidbody.isKinematic && !(hit.moveDirection.y < -0.3f))
{
Vector3 vector = new Vector3(hit.moveDirection.x, 0f, hit.moveDirection.z);
attachedRigidbody.velocity = vector * num;
}
}
private void Update()
{
float axis = Input.GetAxis("Vertical");
float axis2 = Input.GetAxis("Horizontal");
currentSpeed = speed;
if (rotate)
{
float axis3 = Input.GetAxis("Mouse X");
verticalRotation -= Input.GetAxis("Mouse Y");
verticalRotation = Mathf.Clamp(verticalRotation, 0f - upDownRange, upDownRange);
Camera.main.transform.localRotation = Quaternion.Euler(verticalRotation, 0f, 0f);
base.transform.Rotate(0f, axis3, 0f);
}
if (!flying)
{
if (cc.isGrounded)
{
verticalVelocity = 0f;
if (Input.GetButton("Jump"))
{
verticalVelocity = jumpSpeed;
}
}
else
{
verticalVelocity += Physics.gravity.y * Time.deltaTime;
}
}
else
{
currentSpeed = speed * 300f;
if (Input.GetKey("e"))
{
verticalVelocity = 1f;
}
else if (Input.GetKey("q"))
{
verticalVelocity = -1f;
}
else
{
verticalVelocity = 0f;
}
}
if (Input.GetKey(KeyCode.LeftControl))
{
cc.height = 0.2f;
currentSpeed *= 0.25f;
}
else
{
cc.height = 2f;
}
if (Input.GetKey(KeyCode.LeftShift))
{
currentSpeed *= 2.2f;
}
if (Input.GetKeyDown("f"))
{
flying = !flying;
}
Vector3 vector = base.transform.rotation * new Vector3(axis2, verticalVelocity, axis);
cc.Move(vector * currentSpeed * Time.deltaTime);
if (Input.GetKeyDown(KeyCode.Escape))
{
rotate = !rotate;
SetCursorState(rotate ? CursorLockMode.Locked : CursorLockMode.None);
}
}
}
}