Created
September 26, 2022 13:05
-
-
Save Cobertos/c2a0906704021536331700c878dd698f to your computer and use it in GitHub Desktop.
RigidbodyFPSWalker - Retrieved from Wayback Machine as it looks like Unity took down their wiki. http://web.archive.org/web/20200130173118/http://wiki.unity3d.com/index.php?title=RigidbodyFPSWalker
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
using System.Collections; | |
[RequireComponent (typeof (Rigidbody))] | |
[RequireComponent (typeof (CapsuleCollider))] | |
public class CharacterControls : MonoBehaviour { | |
public float speed = 10.0f; | |
public float gravity = 10.0f; | |
public float maxVelocityChange = 10.0f; | |
public bool canJump = true; | |
public float jumpHeight = 2.0f; | |
private bool grounded = false; | |
void Awake () { | |
rigidbody.freezeRotation = true; | |
rigidbody.useGravity = false; | |
} | |
void FixedUpdate () { | |
if (grounded) { | |
// Calculate how fast we should be moving | |
Vector3 targetVelocity = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical")); | |
targetVelocity = transform.TransformDirection(targetVelocity); | |
targetVelocity *= speed; | |
// Apply a force that attempts to reach our target velocity | |
Vector3 velocity = rigidbody.velocity; | |
Vector3 velocityChange = (targetVelocity - velocity); | |
velocityChange.x = Mathf.Clamp(velocityChange.x, -maxVelocityChange, maxVelocityChange); | |
velocityChange.z = Mathf.Clamp(velocityChange.z, -maxVelocityChange, maxVelocityChange); | |
velocityChange.y = 0; | |
rigidbody.AddForce(velocityChange, ForceMode.VelocityChange); | |
// Jump | |
if (canJump && Input.GetButton("Jump")) { | |
rigidbody.velocity = new Vector3(velocity.x, CalculateJumpVerticalSpeed(), velocity.z); | |
} | |
} | |
// We apply gravity manually for more tuning control | |
rigidbody.AddForce(new Vector3 (0, -gravity * rigidbody.mass, 0)); | |
grounded = false; | |
} | |
void OnCollisionStay () { | |
grounded = true; | |
} | |
float CalculateJumpVerticalSpeed () { | |
// From the jump height and gravity we deduce the upwards speed | |
// for the character to reach at the apex. | |
return Mathf.Sqrt(2 * jumpHeight * gravity); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment