89 lines
2.3 KiB
C#
89 lines
2.3 KiB
C#
using UnityEngine;
|
|
using UnityStandardAssets.Characters.FirstPerson;
|
|
using UnityStandardAssets.CrossPlatformInput;
|
|
|
|
[RequireComponent(typeof(RigidbodyFirstPersonController))]
|
|
public class FlyingRigidbodyFirstPersonController : MonoBehaviour
|
|
{
|
|
private Rigidbody rigidbody;
|
|
|
|
private RigidbodyFirstPersonController rigidbodyFPC;
|
|
|
|
private HeadBob headBob;
|
|
|
|
public bool flying;
|
|
|
|
public float flyingDrag = 5f;
|
|
|
|
public float flightToggleTimeThreshold = 0.5f;
|
|
|
|
private float lastAscendKeyHit = float.MinValue;
|
|
|
|
private void Awake()
|
|
{
|
|
rigidbody = GetComponent<Rigidbody>();
|
|
rigidbodyFPC = GetComponent<RigidbodyFirstPersonController>();
|
|
headBob = GetComponentInChildren<HeadBob>();
|
|
}
|
|
|
|
private void Update()
|
|
{
|
|
if (AscendKeyDoubleHit())
|
|
{
|
|
flying = !flying;
|
|
rigidbody.useGravity = !flying;
|
|
rigidbodyFPC.enabled = !flying;
|
|
headBob.enabled = !flying;
|
|
if (flying)
|
|
{
|
|
rigidbody.drag = flyingDrag;
|
|
}
|
|
}
|
|
if (flying)
|
|
{
|
|
rigidbodyFPC.mouseLook.LookRotation(base.transform, rigidbodyFPC.cam.transform);
|
|
}
|
|
}
|
|
|
|
private void FixedUpdate()
|
|
{
|
|
if (!flying)
|
|
{
|
|
return;
|
|
}
|
|
Vector2 input = GetInput();
|
|
Vector3 vector = Vector3.up * (((!CrossPlatformInputManager.GetButton("Jump")) ? 0f : 1f) - ((!CrossPlatformInputManager.GetButton("Crouch")) ? 0f : 1f));
|
|
if (Mathf.Abs(input.x) > float.Epsilon || Mathf.Abs(input.y) > float.Epsilon || Mathf.Abs(vector.y) > float.Epsilon)
|
|
{
|
|
Vector3 vector2 = rigidbodyFPC.cam.transform.forward * input.y + rigidbodyFPC.cam.transform.right * input.x;
|
|
vector2 = (vector2 + vector).normalized * rigidbodyFPC.movementSettings.CurrentTargetSpeed;
|
|
if (rigidbodyFPC.Velocity.sqrMagnitude < rigidbodyFPC.movementSettings.CurrentTargetSpeed * rigidbodyFPC.movementSettings.CurrentTargetSpeed)
|
|
{
|
|
rigidbody.AddForce(vector2, ForceMode.Impulse);
|
|
}
|
|
}
|
|
}
|
|
|
|
private Vector2 GetInput()
|
|
{
|
|
Vector2 vector = new Vector2
|
|
{
|
|
x = CrossPlatformInputManager.GetAxis("Horizontal"),
|
|
y = CrossPlatformInputManager.GetAxis("Vertical")
|
|
};
|
|
rigidbodyFPC.movementSettings.UpdateDesiredTargetSpeed(vector);
|
|
return vector;
|
|
}
|
|
|
|
private bool AscendKeyDoubleHit()
|
|
{
|
|
bool result = false;
|
|
if (CrossPlatformInputManager.GetButtonDown("Jump"))
|
|
{
|
|
result = Time.time - lastAscendKeyHit < flightToggleTimeThreshold;
|
|
lastAscendKeyHit = Time.time;
|
|
}
|
|
return result;
|
|
}
|
|
}
|