Advertisement
Psykik

Movement Code

Mar 10th, 2020
281
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 8.59 KB | None | 0 0
  1. public class PlayerMovement: MonoBehaviourPun
  2. {
  3.     [Header("Movement Settings")]
  4.     public float maxVelocityGround = 15f;
  5.     public float maxVelocityAir = 10f;
  6.     public float groundAccelerate = 90f;
  7.     public float airAccelerate = 180f;
  8.     public float fallMultiplier = 1.2f;
  9.     public float lookSens = 8f;
  10.     public float slowDrag = 0;
  11.     public float thrusterForce = 7f;
  12.     public float friction = 10f;
  13.     private float _friction = 0f;
  14.  
  15.     [Header("Rotation")]
  16.     float xRot = 0F;
  17.     float yRot = 0F;
  18.     float minY = -90f;
  19.     float maxY = 90f;
  20.     Quaternion originalRotation;
  21.  
  22.     //More Movement Variables
  23.     private float distToGround;
  24.     private Vector3 _velocity;
  25.     private Vector2 xyVelocity;
  26.  
  27.  
  28.     [Header("References")]
  29.     //public Text grounded;
  30.     //public Text velocity;
  31.     public Camera cam;
  32.     private Move motor;
  33.     private Rigidbody rb;
  34.     private CapsuleCollider collidr;
  35.     private GameObject rayPoint;
  36.  
  37.  
  38.  
  39.     //private PlayerSetup playerSetup;
  40.  
  41.  
  42.     //Booleans
  43.     private bool jumpy = false;
  44.  
  45.  
  46.  
  47.  
  48.  
  49.  
  50.  
  51.  
  52.  
  53.     void Start()
  54.     {
  55.         _friction = friction;
  56.  
  57.         //Locks the cursor to the middle of the screen, and hides it from view
  58.         Cursor.lockState = CursorLockMode.Locked;
  59.         Cursor.visible = false;
  60.  
  61.         //These attatch the correct objectss to their references in the script, defined above
  62.         motor = GetComponent<Move>();
  63.         rb = GetComponent<Rigidbody>();
  64.         collidr = GetComponent<CapsuleCollider>();
  65.         rayPoint = GameObject.Find("point");
  66.         //playerSetup = GetComponent<PlayerSetup>();
  67.  
  68.         //Sets the distance to the ground from the center of the collider, used in determining whe nthe player is on the ground
  69.         distToGround = collidr.bounds.extents.y;
  70.  
  71.         if (GetComponent<Rigidbody>())
  72.             GetComponent<Rigidbody>().freezeRotation = true;
  73.         originalRotation = transform.localRotation;
  74.  
  75.     }
  76.  
  77.  
  78.  
  79.  
  80.     void FixedUpdate()
  81.     {
  82.         //Debug function that shows a visual representation of when the player is on the ground
  83.         //string a = isGrounded().ToString();
  84.         //grounded.GetComponent<Text>().text = a;
  85.  
  86.         //Finds the Velocity in the x plane. Also used in debug, as it shows it on screen
  87.         //xyVelocity = new Vector2(rb.velocity.x, rb.velocity.z);
  88.         //velocity.GetComponent<Text>().text = xyVelocity.magnitude.ToString("0.000");
  89.  
  90.  
  91.         //This statement checks if the player both is on the ground, and has requested to jump. If so it will jump
  92.         //while also not allowing multiple jumps while in the air. If the player holds it down, he will jump as soon
  93.         //as he touches the ground, avoiding friction and allowing the player to bunnyhop
  94.         if (Input.GetKey("space") && isGrounded())
  95.         {
  96.             rb.AddForce(Vector3.up * thrusterForce, ForceMode.Impulse);
  97.             jumpy = true;
  98.         }
  99.         //rb.AddForce(Jump(), ForceMode.Impulse);
  100.         //This makes you fall faster than you rise, and make jumping feel nicer overall.
  101.         if (rb.velocity.y < 0)
  102.         {
  103.             rb.velocity += Vector3.up * Physics.gravity.y * fallMultiplier * Time.deltaTime;
  104.         }
  105.  
  106.  
  107.         //Gets the input from the axis'
  108.         float input_y = Input.GetAxis("Vertical");
  109.         float input_x = Input.GetAxis("Horizontal");
  110.  
  111.         //Calculates the direction we want to move in, taking into account mouse movement to allow for strafing
  112.         Vector3 accelDir = (transform.forward * input_y + transform.right * input_x).normalized;
  113.  
  114.         //Checks if we are not pressing any inputs, and makes us decelerate faster, to make moving feel more snappy
  115.         decelerate(accelDir);
  116.  
  117.         //This code adjusts the vector to be projected onto the plane that we are currently moving on. Makes strafing better
  118.         RaycastHit hit;
  119.         Physics.Raycast(collidr.center, Vector3.down, out hit, 1000);
  120.         accelDir = Vector3.ProjectOnPlane(accelDir, hit.normal).normalized;
  121.  
  122.         //Finds the current velocity of our RIgidBody
  123.         Vector3 curVel = rb.velocity;
  124.         //Determines whether or not we want to use the air movement(ignore friction) or not.
  125.         //The boolean checks if we have just jumped, so while we are still on the ground, we don't want to calculate friciton
  126.         if (isGrounded() && jumpy == false)
  127.         {
  128.             _velocity = MoveGround(accelDir, curVel);
  129.         }
  130.         else
  131.         {
  132.             _velocity = MoveAir(accelDir, curVel);
  133.         }
  134.  
  135.         //Apply Movement
  136.         rb.velocity = _velocity;
  137.  
  138.  
  139.    
  140.  
  141.         //These call the rotation functions below, one rotates the camera in the y plane, the other the rigidbody in the x plane, which has the camera as a child
  142.         cameraRotate();
  143.         rbRotate();
  144.  
  145.         jumpy = false;
  146.  
  147.     }
  148.  
  149.     private Vector3 MoveGround(Vector3 accelDir, Vector3 prevVelocity)
  150.     {
  151.         // Apply Friction
  152.         float speed = prevVelocity.magnitude;
  153.         if (speed != 0) // To avoid divide by zero errors
  154.         {
  155.             float drop = speed * _friction * Time.fixedDeltaTime;
  156.             prevVelocity *= Mathf.Max(speed - drop, 0) / speed; // Scale the velocity based on friction.
  157.         }
  158.  
  159.         return Accelerate(accelDir, prevVelocity, groundAccelerate, maxVelocityGround);
  160.     }
  161.  
  162.     private Vector3 MoveAir(Vector3 accelDir, Vector3 prevVelocity)
  163.     {
  164.         return Accelerate(accelDir, prevVelocity, airAccelerate, maxVelocityAir);
  165.     }
  166.  
  167.     private Vector3 Accelerate(Vector3 accelDir, Vector3 prevVelocity, float accelerate, float max_velocity)
  168.     {
  169.         float projVel = Vector3.Dot(prevVelocity, accelDir); // Vector projection of Current velocity onto accelDir.
  170.         float accelVel = accelerate * Time.fixedDeltaTime; // Accelerated velocity in direction of movment
  171.  
  172.         // If necessary, truncate the accelerated velocity so the vector projection does not exceed max_velocity
  173.         if (projVel + accelVel > max_velocity)
  174.         {
  175.             accelVel = max_velocity - projVel;
  176.         };
  177.  
  178.         return prevVelocity + accelDir * accelVel;
  179.     }
  180.  
  181.  
  182.     //Function to check if we are on the ground
  183.     public bool isGrounded()
  184.     {
  185.         return Physics.Raycast(collidr.bounds.center, Vector3.down, distToGround);
  186.  
  187.         //Below is a capsule cast, it would be better to implement because it has a thickness
  188.         //return Physics.CheckCapsule(collider.bounds.center, new Vector3(collider.bounds.center.x, collider.bounds.min.y, collider.bounds.center.z), collider.radius * 0.9f);
  189.     }
  190.  
  191.     /// <summary>
  192.     /// decelerates us faster when not moving
  193.     /// </summary>
  194.     /// <param name="input"></param>
  195.     public void decelerate(Vector3 input)
  196.     {
  197.         if (input == Vector3.zero)
  198.         {
  199.             _friction = 10f * friction;
  200.         }
  201.         else
  202.         {
  203.             _friction = friction;
  204.         }
  205.     }
  206.     /// <summary>
  207.     /// This function is the camera rotation function
  208.     /// </summary>
  209.     public void cameraRotate()
  210.     {
  211.         //Get the input from the mouse and multiply it by sensitivity so it can be adjusted from ingame
  212.         yRot += Input.GetAxis("Mouse Y") * lookSens;
  213.         //Clamp it so that we cant just keep spinning in the Y direction
  214.         yRot = clamp(yRot, minY, maxY);
  215.         //Calculate the quaternion using the amount of rotation found before. We use the negative mouse input as the amount
  216.         //of rotation, and then specify that we want this rotation to be around the x axis. It seems counter intuitive, but this is the way to do it
  217.         Quaternion yRotAngle = Quaternion.AngleAxis(-yRot, Vector3.right);
  218.         //Apply this rotation to the cameras transform
  219.         cam.transform.localRotation = originalRotation * yRotAngle;
  220.     }
  221.     /// <summary>
  222.     /// Basically the same as above, but we dont need to clamp it because we want to be able to forever spin to the left and right
  223.     /// </summary>
  224.     public void rbRotate()
  225.     {
  226.         xRot += Input.GetAxis("Mouse X") * lookSens;
  227.         Quaternion xRotAngle = Quaternion.AngleAxis(xRot, Vector3.up);
  228.         rb.transform.localRotation = originalRotation * xRotAngle;
  229.     }
  230.     /// <summary>
  231.     /// just clamps the angle we input between the next 2 floats
  232.     /// </summary>
  233.     /// <param name="angle">the float representation of the angle</param>
  234.     /// <param name="min">the min that the angle can be</param>
  235.     /// <param name="max">you got it by now right?></param>
  236.     /// <returns></returns>
  237.     private float clamp(float angle, float min, float max)
  238.     {
  239.         return Mathf.Clamp(angle, min, max);
  240.     }
  241. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement