Search Unity

Question Problem with Crouching

Discussion in 'Scripting' started by AerionXI, Apr 21, 2021.

  1. AerionXI

    AerionXI

    Joined:
    Jul 20, 2020
    Posts:
    482
    So when I go to crouch, for some reason it's pushing my player forward a little bit. How do I stop that from happening based on my below code?

    Code (CSharp):
    1.  
    2.     using System;
    3.     using UnityEngine;
    4.  
    5.     public class PlayerMoving : MonoBehaviour {
    6.  
    7.         // Assingables
    8.         public Transform playerCam;
    9.         public Transform orientation;
    10.    
    11.         // Other
    12.         private Rigidbody rb;
    13.  
    14.         // Rotation and look
    15.         private float xRotation;
    16.  
    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.         public float jumpCooldown = 1.0f;
    39.         public float jumpForce = 100.0f;
    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.position = new Vector3(transform.position.x, transform.position.y - 0.5f, transform.position.z);
    87.             // transform.position = new Vector3(transform.position.x, transform.position.y, transform.position.z);
    88.             transform.localScale = crouchScale;
    89.             if (rb.velocity.magnitude > 0.5f) {
    90.                 if (grounded) {
    91.                     rb.AddForce(orientation.transform.forward * slideForce);
    92.                 }
    93.             }
    94.         }
    95.  
    96.         private void StopCrouch() {
    97.             // transform.position = new Vector3(transform.position.x, transform.position.y + 0.5f, transform.position.z);
    98.             // transform.localScale = playerScale;
    99.             Vector3 orgPos = transform.position;
    100.             transform.localScale = playerScale;
    101.             orgPos.x = transform.position.x;
    102.             orgPos.y = transform.position.y + 0.5f;
    103.             transform.position = orgPos;
    104.         }
    105.  
    106.         private void Movement() {
    107.             // Extra gravity
    108.             rb.AddForce(Vector3.down * Time.deltaTime * 10);
    109.        
    110.             // Find actual velocity relative to where player is looking
    111.             Vector2 mag = FindVelRelativeToLook();
    112.             float xMag = mag.x, yMag = mag.y;
    113.  
    114.             // Counteract sliding & sloppy movement
    115.             CounterMovement(x, y, mag);
    116.  
    117.             // If holding jump && ready to jump, then jump
    118.             if (readyToJump && jumping) Jump();
    119.  
    120.             // Set max speed
    121.             float maxSpeed = this.maxSpeed;
    122.  
    123.             // If sliding down a ramp, add force down so player stays grounded and also builds speed
    124.             if (crouching && grounded && readyToJump) {
    125.                 rb.AddForce(Vector3.down * Time.deltaTime * 3000);
    126.                 return;
    127.             }
    128.        
    129.             // If speed is larger than maxspeed, cancel out the input so you don't go over max speed
    130.             if (x > 0 && xMag > maxSpeed) x = 0;
    131.             if (x < 0 && xMag < -maxSpeed) x = 0;
    132.             if (y > 0 && yMag > maxSpeed) y = 0;
    133.             if (y < 0 && yMag < -maxSpeed) y = 0;
    134.  
    135.             // Some multipliers
    136.             float multiplier = 1f, multiplierV = 1f;
    137.        
    138.             // Movement in air
    139.             if (!grounded) {
    140.                 multiplier = 0.5f;
    141.                 multiplierV = 0.5f;
    142.             }
    143.        
    144.             // Movement while sliding
    145.             if (grounded && crouching) multiplierV = 0f;
    146.  
    147.             // Apply forces to move player
    148.             rb.AddForce(orientation.transform.forward * y * moveSpeed * Time.deltaTime * multiplier * multiplierV);
    149.             rb.AddForce(orientation.transform.right * x * moveSpeed * Time.deltaTime * multiplier);
    150.         }
    151.  
    152.         private void Jump() {
    153.             if (grounded && readyToJump) {
    154.                 readyToJump = false;
    155.  
    156.                 // Add jump forces
    157.                 rb.AddForce(Vector2.up * jumpForce * 1.5f);
    158.                 rb.AddForce(normalVector * jumpForce * 0.5f);
    159.            
    160.                 // If jumping while falling, reset y velocity.
    161.                 Vector3 vel = rb.velocity;
    162.                 if (rb.velocity.y < 0.5f)
    163.                     rb.velocity = new Vector3(vel.x, 0, vel.z);
    164.                 else if (rb.velocity.y > 0)
    165.                     rb.velocity = new Vector3(vel.x, vel.y / 2, vel.z);
    166.            
    167.                 Invoke(nameof(ResetJump), jumpCooldown);
    168.             }
    169.         }
    170.    
    171.         private void ResetJump() {
    172.             readyToJump = true;
    173.         }
    174.    
    175.         private void CounterMovement(float x, float y, Vector2 mag) {
    176.  
    177.             if (!grounded || jumping) return;
    178.  
    179.             // Slow down sliding
    180.             if (crouching) {
    181.                 rb.AddForce(moveSpeed * Time.deltaTime * -rb.velocity.normalized * slideCounterMovement);
    182.                 return;
    183.             }
    184.  
    185.             // Counter movement
    186.             if (Math.Abs(mag.x) > threshold && Math.Abs(x) < 0.05f || (mag.x < -threshold && x > 0) || (mag.x > threshold && x < 0)) {
    187.                 rb.AddForce(moveSpeed * orientation.transform.right * Time.deltaTime * -mag.x * counterMovement);
    188.             }
    189.             if (Math.Abs(mag.y) > threshold && Math.Abs(y) < 0.05f || (mag.y < -threshold && y > 0) || (mag.y > threshold && y < 0)) {
    190.                 rb.AddForce(moveSpeed * orientation.transform.forward * Time.deltaTime * -mag.y * counterMovement);
    191.             }
    192.        
    193.             // Limit diagonal running. This will also cause a full stop if sliding fast and un-crouching, so not optimal.
    194.             if (Mathf.Sqrt((Mathf.Pow(rb.velocity.x, 2) + Mathf.Pow(rb.velocity.z, 2))) > maxSpeed) {
    195.                 float fallspeed = rb.velocity.y;
    196.                 Vector3 n = rb.velocity.normalized * maxSpeed;
    197.                 rb.velocity = new Vector3(n.x, fallspeed, n.z);
    198.             }
    199.         }
    200.  
    201.         // / <summary>
    202.         // / Find the velocity relative to where the player is looking
    203.         // / Useful for vectors calculations regarding movement and limiting movement
    204.         // / </summary>
    205.         // / <returns></returns>
    206.         public Vector2 FindVelRelativeToLook() {
    207.             float lookAngle = orientation.transform.eulerAngles.y;
    208.             float moveAngle = Mathf.Atan2(rb.velocity.x, rb.velocity.z) * Mathf.Rad2Deg;
    209.  
    210.             float u = Mathf.DeltaAngle(lookAngle, moveAngle);
    211.             float v = 90 - u;
    212.  
    213.             float magnitue = rb.velocity.magnitude;
    214.             float yMag = magnitue * Mathf.Cos(u * Mathf.Deg2Rad);
    215.             float xMag = magnitue * Mathf.Cos(v * Mathf.Deg2Rad);
    216.        
    217.             return new Vector2(xMag, yMag);
    218.         }
    219.  
    220.         private bool IsFloor(Vector3 v) {
    221.             float angle = Vector3.Angle(Vector3.up, v);
    222.             return angle < maxSlopeAngle;
    223.         }
    224.  
    225.         private bool cancellingGrounded;
    226.    
    227.         // / <summary>
    228.         // / Handle ground detection
    229.         // / </summary>
    230.         private void OnCollisionStay(Collision other) {
    231.             // Make sure we are only checking for walkable layers
    232.             int layer = other.gameObject.layer;
    233.             if (whatIsGround != (whatIsGround | (1 << layer))) return;
    234.  
    235.             // Iterate through every collision in a physics update
    236.             for (int i = 0; i < other.contactCount; i++) {
    237.                 Vector3 normal = other.contacts[I].normal;
    238.                 // FLOOR
    239.                 if (IsFloor(normal)) {
    240.                     grounded = true;
    241.                     cancellingGrounded = false;
    242.                     normalVector = normal;
    243.                     CancelInvoke(nameof(StopGrounded));
    244.                 }
    245.             }
    246.  
    247.             // Invoke ground/wall cancel, since we can't check normals with CollisionExit
    248.             float delay = 3f;
    249.             if (!cancellingGrounded) {
    250.                 cancellingGrounded = true;
    251.                 Invoke(nameof(StopGrounded), Time.deltaTime * delay);
    252.             }
    253.         }
    254.  
    255.         private void StopGrounded() {
    256.             grounded = false;
    257.         }
    258.      
    259.     }
    260.  
    Any help is above & beyond appreciated!

    Thank you!
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,735
    If you use the Transform do anything to a GameObject with a Rigidbody, you are effectively bypassing the physics system. This will cause things to creep, glitch, jerk, etc. because you are startling the physics system and it has to suddenly recover.

    I see you doing this on at least Lines 86 and 103 above (setting the .position directly).

    For moving you must always use .MovePosition() and .MoveRotation() methods on the Rigidbody instance. This gives the physics solver a chance to sort things out reasonably, if at all possible.

    As far as changing Scale, I'm not sure there is an equivalent for Rigidbody use. You might have better stability if you use TWO colliders, one for bottom that you never turn off, one for the top half that you turn off.

    I also see you adding forces AND setting velocities. That might be causing issues too, but at least the setting position directly will certainly be causing issues.