Advertisement
Guest User

Untitled

a guest
Feb 19th, 2018
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.05 KB | None | 0 0
  1. using UnityEngine;
  2.  
  3. [RequireComponent(typeof (Rigidbody))]
  4.  
  5. public class RigidbodyPlayer : MonoBehaviour {
  6.  
  7.     public float speed = 10.0f;
  8.     public float gravity = 10.0f;
  9.     public float maxVelocityChange = 10.0f;
  10.     public bool canJump = true;
  11.     public float jumpHeight = 2.0f;
  12.     private bool grounded = false;
  13.  
  14.     Rigidbody phisicBody;
  15.  
  16.  
  17.  
  18.     void Awake()
  19.     {
  20.         phisicBody = GetComponent<Rigidbody>();
  21.  
  22.         phisicBody.freezeRotation = true;
  23.         phisicBody.useGravity = false;
  24.     }
  25.  
  26.     void FixedUpdate()
  27.     {
  28.         if (grounded)
  29.         {
  30.             // Calculate how fast we should be moving
  31.             Vector3 targetVelocity = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
  32.             targetVelocity = transform.TransformDirection(targetVelocity);
  33.             targetVelocity *= speed;
  34.  
  35.             // Apply a force that attempts to reach our target velocity
  36.             Vector3 velocity = phisicBody.velocity;
  37.             Vector3 velocityChange = (targetVelocity - velocity);
  38.             velocityChange.x = Mathf.Clamp(velocityChange.x, -maxVelocityChange, maxVelocityChange);
  39.             velocityChange.z = Mathf.Clamp(velocityChange.z, -maxVelocityChange, maxVelocityChange);
  40.             velocityChange.y = 0;
  41.             phisicBody.AddForce(velocityChange, ForceMode.VelocityChange);
  42.  
  43.             // Jump
  44.             if (canJump && Input.GetButton("Jump"))
  45.             {
  46.                 phisicBody.velocity = new Vector3(velocity.x, CalculateJumpVerticalSpeed(), velocity.z);
  47.             }
  48.         }
  49.  
  50.         // We apply gravity manually for more tuning control
  51.         phisicBody.AddForce(new Vector3(0, -gravity * phisicBody.mass, 0));
  52.  
  53.         grounded = false;
  54.     }
  55.  
  56.     void OnCollisionStay()
  57.     {
  58.         grounded = true;
  59.     }
  60.  
  61.     float CalculateJumpVerticalSpeed()
  62.     {
  63.         // From the jump height and gravity we deduce the upwards speed
  64.         // for the character to reach at the apex.
  65.         return Mathf.Sqrt(2 * jumpHeight * gravity);
  66.     }
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement