Advertisement
ZeronSix

Old charmove

Jul 18th, 2013
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.72 KB | None | 0 0
  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. /// <summary>
  5. /// Character motor for fps player.
  6. /// </summary>
  7. [AddComponentMenu("FPS Stuff/Player Movement")]
  8. public class PlayerMovement : MonoBehaviour
  9. {
  10.     public float movementSpeed = 10;
  11.     public float speedMultiplier = 1;
  12.     public float maxVelocityChange = 10;
  13.     public float jumpHeight = 2;
  14.     public bool canJump = true;
  15.     public bool grounded = false;
  16.  
  17.     void FixedUpdate()
  18.     {
  19.         if (grounded)
  20.         {
  21.             float h = Input.GetAxis("Horizontal") * movementSpeed * speedMultiplier * 0.7f;
  22.             float v = Input.GetAxis("Vertical") * movementSpeed * speedMultiplier;
  23.             Vector3 targetVelocity = transform.TransformDirection(new Vector3(h, 0, v));
  24.  
  25.             Vector3 velocityChange = (targetVelocity - rigidbody.velocity);
  26.             velocityChange.x = Mathf.Clamp(velocityChange.x, -maxVelocityChange, maxVelocityChange);
  27.             velocityChange.z = Mathf.Clamp(velocityChange.z, -maxVelocityChange, maxVelocityChange);
  28.             velocityChange.y = 0;
  29.             rigidbody.AddForce(velocityChange, ForceMode.VelocityChange);
  30.  
  31.             // Jump
  32.             if (canJump && Input.GetButton("Jump"))
  33.             {
  34.                 rigidbody.velocity = new Vector3(rigidbody.velocity.x, CalculateJumpVerticalSpeed(), rigidbody.velocity.z);
  35.             }
  36.         }
  37.  
  38.         grounded = false;
  39.     }
  40.  
  41.     void OnCollisionStay()
  42.     {
  43.         grounded = true;
  44.     }
  45.  
  46.     float CalculateJumpVerticalSpeed()
  47.     {
  48.         // From the jump height and gravity we deduce the upwards speed
  49.         // for the character to reach at the apex.
  50.         return Mathf.Sqrt(2 * jumpHeight * -Physics.gravity.y);
  51.     }
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement