Advertisement
Guest User

Dani's modified RB controller

a guest
Mar 30th, 2020
586
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 9.04 KB | None | 0 0
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using System;
  4. using UnityEngine;
  5.  
  6. public class PlayerMovement : MonoBehaviour {
  7.  
  8.     //Assingables
  9.     public Transform playerCam;
  10.     public Transform orientation;
  11.  
  12.     //Other
  13.     private Rigidbody rb;
  14.  
  15.     //Rotation and look
  16.     private float xRotation;
  17.     private float sensitivity = 50f;
  18.     private float sensMultiplier = 1f;
  19.  
  20.     //Movement
  21.     public float moveSpeed = 4500;
  22.     public float maxSpeed = 20;
  23.     public bool grounded;
  24.     public LayerMask whatIsGround;
  25.  
  26.     public float counterMovement = 0.175f;
  27.     private float threshold = 0.01f;
  28.     public float maxSlopeAngle = 35f;
  29.  
  30.     //Crouch & Slide
  31.     private Vector3 crouchScale = new Vector3( 1, 0.5f, 1 );
  32.     private Vector3 playerScale;
  33.     public float slideForce = 400;
  34.     public float slideCounterMovement = 0.2f;
  35.  
  36.     //Jumping
  37.     private bool readyToJump = true;
  38.     private float jumpCooldown = 0.25f;
  39.     public float jumpForce = 550f;
  40.  
  41.     //Input
  42.     float x, y;
  43.     bool jumping, sprinting, crouching;
  44.  
  45.     //Sliding
  46.     private Vector3 normalVector = Vector3.up;
  47.     private Vector3 wallNormalVector;
  48.  
  49.     void Awake() {
  50.         rb = GetComponent<Rigidbody>();
  51.     }
  52.  
  53.     void Start() {
  54.         playerScale = transform.localScale;
  55.         Cursor.lockState = CursorLockMode.Locked;
  56.         Cursor.visible = false;
  57.     }
  58.  
  59.  
  60.     private void FixedUpdate() {
  61.         Movement();
  62.     }
  63.  
  64.     private void Update() {
  65.         MyInput();
  66.         Look();
  67.     }
  68.  
  69.     /// <summary>
  70.     /// Find user input. Should put this in its own class but im lazy
  71.     /// </summary>
  72.     private void MyInput() {
  73.         x = Input.GetAxisRaw( "Horizontal" );
  74.         y = Input.GetAxisRaw( "Vertical" );
  75.         jumping = Input.GetButton( "Jump" );
  76.         crouching = Input.GetKey( KeyCode.LeftControl );
  77.  
  78.         //Crouching
  79.         if ( Input.GetKeyDown( KeyCode.LeftControl ) )
  80.             StartCrouch();
  81.         if ( Input.GetKeyUp( KeyCode.LeftControl ) )
  82.             StopCrouch();
  83.     }
  84.  
  85.     private void StartCrouch() {
  86.         transform.localScale = crouchScale;
  87.         transform.position = new Vector3( transform.position.x, transform.position.y - 0.5f, transform.position.z );
  88.         if ( rb.velocity.magnitude > 0.5f ) {
  89.             if ( grounded ) {
  90.                 rb.AddForce( orientation.transform.forward * slideForce );
  91.             }
  92.         }
  93.     }
  94.  
  95.     private void StopCrouch() {
  96.         transform.localScale = playerScale;
  97.         transform.position = new Vector3( transform.position.x, transform.position.y + 0.5f, transform.position.z );
  98.     }
  99.  
  100.     private void Movement() {
  101.         //Extra gravity
  102.         rb.AddForce( Vector3.down * Time.deltaTime * 10 );
  103.  
  104.         //Find actual velocity relative to where player is looking
  105.         Vector2 mag = FindVelRelativeToLook();
  106.         float xMag = mag.x, yMag = mag.y;
  107.  
  108.         //Counteract sliding and sloppy movement
  109.         CounterMovement( x, y, mag );
  110.  
  111.         //If holding jump && ready to jump, then jump
  112.         if ( readyToJump && jumping ) Jump();
  113.  
  114.         //Set max speed
  115.         float maxSpeed = this.maxSpeed;
  116.  
  117.         //If sliding down a ramp, add force down so player stays grounded and also builds speed
  118.         if ( crouching && grounded && readyToJump ) {
  119.             rb.AddForce( Vector3.down * Time.deltaTime * 3000 );
  120.             return;
  121.         }
  122.  
  123.         //If speed is larger than maxspeed, cancel out the input so you don't go over max speed
  124.         if ( x > 0 && xMag > maxSpeed ) x = 0;
  125.         if ( x < 0 && xMag < -maxSpeed ) x = 0;
  126.         if ( y > 0 && yMag > maxSpeed ) y = 0;
  127.         if ( y < 0 && yMag < -maxSpeed ) y = 0;
  128.  
  129.         //Some multipliers
  130.         float multiplier = 1f, multiplierV = 1f;
  131.  
  132.         // Movement in air
  133.         if ( !grounded ) {
  134.             multiplier = 0.8f;
  135.             multiplierV = 0.8f;
  136.         }
  137.  
  138.         // Movement while sliding
  139.         if ( grounded && crouching ) multiplierV = 0f;
  140.  
  141.         //Apply forces to move player
  142.         rb.AddForce( orientation.transform.forward * y * moveSpeed * Time.deltaTime * multiplier * multiplierV );
  143.         rb.AddForce( orientation.transform.right * x * moveSpeed * Time.deltaTime * multiplier );
  144.     }
  145.  
  146.     private void Jump() {
  147.         if ( grounded && readyToJump ) {
  148.             readyToJump = false;
  149.  
  150.             //Add jump forces
  151.             rb.AddForce( Vector2.up * jumpForce * 1.5f );
  152.             rb.AddForce( normalVector * jumpForce * 0.5f );
  153.  
  154.             //If jumping while falling, reset y velocity.
  155.             Vector3 vel = rb.velocity;
  156.             if ( rb.velocity.y < 0.5f )
  157.                 rb.velocity = new Vector3( vel.x, 0, vel.z );
  158.             else if ( rb.velocity.y > 0 )
  159.                 rb.velocity = new Vector3( vel.x, vel.y / 2, vel.z );
  160.  
  161.             Invoke( nameof( ResetJump ), jumpCooldown );
  162.         }
  163.     }
  164.  
  165.     private void ResetJump() {
  166.         readyToJump = true;
  167.     }
  168.  
  169.     private float desiredX;
  170.     private void Look() {
  171.         float mouseX = Input.GetAxis( "Mouse X" ) * sensitivity * Time.fixedDeltaTime * sensMultiplier;
  172.         float mouseY = Input.GetAxis( "Mouse Y" ) * sensitivity * Time.fixedDeltaTime * sensMultiplier;
  173.  
  174.         //Find current look rotation
  175.         Vector3 rot = playerCam.transform.localRotation.eulerAngles;
  176.         desiredX = rot.y + mouseX;
  177.  
  178.         //Rotate, and also make sure we dont over- or under-rotate.
  179.         xRotation -= mouseY;
  180.         xRotation = Mathf.Clamp( xRotation, -90f, 90f );
  181.  
  182.         //Perform the rotations
  183.         playerCam.transform.localRotation = Quaternion.Euler( xRotation, desiredX, 0 );
  184.         orientation.transform.localRotation = Quaternion.Euler( 0, desiredX, 0 );
  185.     }
  186.  
  187.     private void CounterMovement( float x, float y, Vector2 mag ) {
  188.         if ( !grounded || jumping ) return;
  189.  
  190.         //Slow down sliding
  191.         if ( crouching ) {
  192.             rb.AddForce( moveSpeed * Time.deltaTime * -rb.velocity.normalized * slideCounterMovement );
  193.             return;
  194.         }
  195.  
  196.         //Counter movement
  197.         if ( Math.Abs( mag.x ) > threshold && Math.Abs( x ) < 0.05f || ( mag.x < -threshold && x > 0 ) || ( mag.x > threshold && x < 0 ) ) {
  198.             rb.AddForce( moveSpeed * orientation.transform.right * Time.deltaTime * -mag.x * counterMovement );
  199.         }
  200.         if ( Math.Abs( mag.y ) > threshold && Math.Abs( y ) < 0.05f || ( mag.y < -threshold && y > 0 ) || ( mag.y > threshold && y < 0 ) ) {
  201.             rb.AddForce( moveSpeed * orientation.transform.forward * Time.deltaTime * -mag.y * counterMovement );
  202.         }
  203.  
  204.         //Limit diagonal running. This will also cause a full stop if sliding fast and un-crouching, so not optimal.
  205.         if ( Mathf.Sqrt( ( Mathf.Pow( rb.velocity.x, 2 ) + Mathf.Pow( rb.velocity.z, 2 ) ) ) > maxSpeed ) {
  206.             float fallspeed = rb.velocity.y;
  207.             Vector3 n = rb.velocity.normalized * maxSpeed;
  208.             rb.velocity = new Vector3( n.x, fallspeed, n.z );
  209.         }
  210.     }
  211.  
  212.     /// <summary>
  213.     /// Find the velocity relative to where the player is looking
  214.     /// Useful for vectors calculations regarding movement and limiting movement
  215.     /// </summary>
  216.     /// <returns></returns>
  217.     public Vector2 FindVelRelativeToLook() {
  218.         float lookAngle = orientation.transform.eulerAngles.y;
  219.         float moveAngle = Mathf.Atan2( rb.velocity.x, rb.velocity.z ) * Mathf.Rad2Deg;
  220.  
  221.         float u = Mathf.DeltaAngle( lookAngle, moveAngle );
  222.         float v = 90 - u;
  223.  
  224.         float thing = new Vector3( rb.velocity.x, 0, rb.velocity.z ).magnitude;
  225.         float magnitue = rb.velocity.magnitude;
  226.         float yMag = thing * Mathf.Cos( u * Mathf.Deg2Rad );
  227.         float xMag = thing * Mathf.Cos( v * Mathf.Deg2Rad );
  228.  
  229.         return new Vector2( xMag, yMag );
  230.     }
  231.  
  232.     private bool IsFloor( Vector3 v ) {
  233.         float angle = Vector3.Angle( Vector3.up, v );
  234.         return angle < maxSlopeAngle;
  235.     }
  236.  
  237.     private bool cancellingGrounded;
  238.  
  239.     /// <summary>
  240.     /// Handle ground detection
  241.     /// </summary>
  242.     private void OnCollisionStay( Collision other ) {
  243.         //Make sure we are only checking for walkable layers
  244.         int layer = other.gameObject.layer;
  245.         if ( whatIsGround != ( whatIsGround | ( 1 << layer ) ) ) return;
  246.  
  247.         //Iterate through every collision in a physics update
  248.         for ( int i = 0; i < other.contactCount; i++ ) {
  249.             Vector3 normal = other.contacts[ i ].normal;
  250.             //FLOOR
  251.             if ( IsFloor( normal ) ) {
  252.                 grounded = true;
  253.                 cancellingGrounded = false;
  254.                 normalVector = normal;
  255.                 CancelInvoke( nameof( StopGrounded ) );
  256.             }
  257.         }
  258.  
  259.         //Invoke ground/wall cancel, since we can't check normals with CollisionExit
  260.         float delay = 3f;
  261.         if ( !cancellingGrounded ) {
  262.             cancellingGrounded = true;
  263.             Invoke( nameof( StopGrounded ), Time.deltaTime * delay );
  264.         }
  265.     }
  266.  
  267.     private void StopGrounded() {
  268.         grounded = false;
  269.     }
  270.  
  271. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement