Skip to content
The Chat Archive
o1-mini-2024-09-12· OpenAI WildChat-4.8M (AI2)

// PlayerMovement using System; using UnityEngine; public class PlayerMovement :…

  1. User

    // PlayerMovement using System; using UnityEngine;

    public class PlayerMovement : MonoBehaviour {
    [Header("Assignables")] //Assignables public Transform playerCam; public Transform orientation; private Collider playerCollider; public Rigidbody rb;

    [Space(10)]
    
    public LayerMask whatIsGround;
    public LayerMask whatIsWallrunnable;
    
    [Header("MovementSettings")]
    //Movement Settings 
    public float sensitivity = 50f;
    public float moveSpeed = 4500f;
    public float walkSpeed = 20f;
    public float runSpeed = 10f;
    public bool grounded;
    public bool onWall;
    
    //Private Floats
    private float wallRunGravity = 1f;
    private float maxSlopeAngle = 35f;
    private float wallRunRotation;
    private float slideSlowdown = 0.2f;
    private float actualWallRotation;
    private float wallRotationVel;
    private float desiredX;
    private float xRotation;
    private float sensMultiplier = 1f;
    private float jumpCooldown = 0.25f;
    private float jumpForce = 550f;
    private float x;
    private float y;
    private float vel;
    
    //Private bools
    private bool readyToJump;
    private bool jumping;
    private bool sprinting;
    private bool crouching;
    private bool wallRunning;
    private bool cancelling;
    private bool readyToWallrun = true;
    private bool airborne;
    private bool onGround;
    private bool surfing;
    private bool cancellingGrounded;
    private bool cancellingWall;
    private bool cancellingSurf;
    
    //Private Vector3's
    private Vector3 grapplePoint;
    private Vector3 normalVector;
    private Vector3 wallNormalVector;
    private Vector3 wallRunPos;
    private Vector3 previousLookdir;
    
    //Private int
    private int nw;
    
    //Instance
    public static PlayerMovement Instance { get; private set; }
    
    private void Awake()
    {
    	Instance = this;
    	rb = GetComponent<Rigidbody>();
    }
    
    private void Start()
    {
    	playerCollider = GetComponent<Collider>();
    	Cursor.lockState = CursorLockMode.Locked;
    	Cursor.visible = false;
    	readyToJump = true;
    	wallNormalVector = Vector3.up;
    }
    
    private void LateUpdate()
    {
        //For wallrunning
        WallRunning();
    }
    
    private void FixedUpdate()
    {
        //For moving
    	Movement();
    }
    
    private void Update()
    {
        //Input
    	MyInput();
        //Looking around
    	Look();
    }
    
    //Player input
    private void MyInput()
    {
    	x = Input.GetAxisRaw("Horizontal");
    	y = Input.GetAxisRaw("Vertical");
    	jumping = Input.GetButton("Jump");
    	crouching = Input.GetKey(KeyCode.LeftShift);
    	if (Input.GetKeyDown(KeyCode.LeftShift))
    	{
    		StartCrouch();
    	}
    	if (Input.GetKeyUp(KeyCode.LeftShift))
    	{
    		StopCrouch();
    	}
    }
    
    //Scale player down
    private void StartCrouch()
    {
    	float num = 400f;
    	base.transform.localScale = new Vector3(1f, 0.5f, 1f);
    	base.transform.position = new Vector3(base.transform.position.x, base.transform.position.y - 0.5f, base.transform.position.z);
    	if (rb.velocity.magnitude > 0.1f && grounded)
    	{
    		rb.AddForce(orientation.transform.forward * num);
    	}
    }
    
    //Scale player to original size
    private void StopCrouch()
    {
    	base.transform.localScale = new Vector3(1f, 1.5f, 1f);
    	base.transform.position = new Vector3(base.transform.position.x, base.transform.position.y + 0.5f, base.transform.position.z);
    }
    
    //Moving around with WASD
    private void Movement()
    {
    	rb.AddForce(Vector3.down * Time.deltaTime * 10f);
    	Vector2 mag = FindVelRelativeToLook();
    	float num = mag.x;
    	float num2 = mag.y;
    	CounterMovement(x, y, mag);
    	if (readyToJump && jumping)
    	{
    		Jump();
    	}
    	float num3 = walkSpeed;
    	if (sprinting)
    	{
    		num3 = runSpeed;
    	}
    	if (crouching && grounded && readyToJump)
    	{
    		rb.AddForce(Vector3.down * Time.deltaTime * 3000f);
    		return;
    	}
    	if (x > 0f && num > num3)
    	{
    		x = 0f;
    	}
    	if (x < 0f && num < 0f - num3)
    	{
    		x = 0f;
    	}
    	if (y > 0f && num2 > num3)
    	{
    		y = 0f;
    	}
    	if (y < 0f && num2 < 0f - num3)
    	{
    		y = 0f;
    	}
    	float num4 = 1f;
    	float num5 = 1f;
    	if (!grounded)
    	{
    		num4 = 0.5f;
    		num5 = 0.5f;
    	}
    	if (grounded && crouching)
    	{
    		num5 = 0f;
    	}
    	if (wallRunning)
    	{
    		num5 = 0.3f;
    		num4 = 0.3f;
    	}
    	if (surfing)
    	{
    		num4 = 0.7f;
    		num5 = 0.3f;
    	}
    	rb.AddForce(orientation.transform.forward * y * moveSpeed * Time.deltaTime * num4 * num5);
    	rb.AddForce(orientation.transform.right * x * moveSpeed * Time.deltaTime * num4);
    }
    
    //Ready to jump again
    private void ResetJump()
    {
    	readyToJump = true;
    }
    
    //Player go fly
    private void Jump()
    {
        if ((grounded || wallRunning || surfing) && readyToJump)
    	{
    	    MonoBehaviour.print("jumping");
    	    Vector3 velocity = rb.velocity;
    	    readyToJump = false;
    	    rb.AddForce(Vector2.up * jumpForce * 1.5f);
    	    rb.AddForce(normalVector * jumpForce * 0.5f);
    	    if (rb.velocity.y < 0.5f)
    	    {
    		    rb.velocity = new Vector3(velocity.x, 0f, velocity.z);
    	    }
    	    else if (rb.velocity.y > 0f)
    	    {
    		    rb.velocity = new Vector3(velocity.x, velocity.y / 2f, velocity.z);
    	    }
    	    if (wallRunning)
    	    {
    		    rb.AddForce(wallNormalVector * jumpForce * 3f);
    	    }
    	    Invoke("ResetJump", jumpCooldown);
    	    if (wallRunning)
    	    {
    		    wallRunning = false;
    	    }
        }
    }
    
    //Looking around by using your mouse
    private void Look()
    {
    	float num = Input.GetAxis("Mouse X") * sensitivity * Time.fixedDeltaTime * sensMultiplier;
    	float num2 = Input.GetAxis("Mouse Y") * sensitivity * Time.fixedDeltaTime * sensMultiplier;
    	desiredX = playerCam.transform.localRotation.eulerAngles.y + num;
    	xRotation -= num2;
    	xRotation = Mathf.Clamp(xRotation, -90f, 90f);
    	FindWallRunRotation();
    	actualWallRotation = Mathf.SmoothDamp(actualWallRotation, wallRunRotation, ref wallRotationVel, 0.2f);
    	playerCam.transform.localRotation = Quaternion.Euler(xRotation, desiredX, actualWallRotation);
    	orientation.transform.localRotation = Quaternion.Euler(0f, desiredX, 0f);
    }
    
    //Make the player movement feel good 
    private void CounterMovement(float x, float y, Vector2 mag)
    {
    	if (!grounded || jumping)
    	{
    		return;
    	}
    	float num = 0.16f;
    	float num2 = 0.01f;
    	if (crouching)
    	{
    		rb.AddForce(moveSpeed * Time.deltaTime * -rb.velocity.normalized * slideSlowdown);
    		return;
    	}
    	if ((Math.Abs(mag.x) > num2 && Math.Abs(x) < 0.05f) || (mag.x < 0f - num2 && x > 0f) || (mag.x > num2 && x < 0f))
    	{
    		rb.AddForce(moveSpeed * orientation.transform.right * Time.deltaTime * (0f - mag.x) * num);
    	}
    	if ((Math.Abs(mag.y) > num2 && Math.Abs(y) < 0.05f) || (mag.y < 0f - num2 && y > 0f) || (mag.y > num2 && y < 0f))
    	{
    		rb.AddForce(moveSpeed * orientation.transform.forward * Time.deltaTime * (0f - mag.y) * num);
    	}
    	if (Mathf.Sqrt(Mathf.Pow(rb.velocity.x, 2f) + Mathf.Pow(rb.velocity.z, 2f)) > walkSpeed)
    	{
    		float num3 = rb.velocity.y;
    		Vector3 vector = rb.velocity.normalized * walkSpeed;
    		rb.velocity = new Vector3(vector.x, num3, vector.z);
    	}
    }
    
    public Vector2 FindVelRelativeToLook()
    {
    	float current = orientation.transform.eulerAngles.y;
    	float target = Mathf.Atan2(rb.velocity.x, rb.velocity.z) * 57.29578f;
    	float num = Mathf.DeltaAngle(current, target);
    	float num2 = 90f - num;
    	float magnitude = rb.velocity.magnitude;
    	return new Vector2(y: magnitude * Mathf.Cos(num * ((float)Math.PI / 180f)), x: magnitude * Mathf.Cos(num2 * ((float)Math.PI / 180f)));
    }
    
    private void FindWallRunRotation()
    {
    	if (!wallRunning)
    	{
    		wallRunRotation = 0f;
    		return;
    	}
    	_ = new Vector3(0f, playerCam.transform.rotation.y, 0f).normalized;
    	new Vector3(0f, 0f, 1f);
    	float num = 0f;
    	float current = playerCam.transform.rotation.eulerAngles.y;
    	if (Math.Abs(wallNormalVector.x - 1f) < 0.1f)
    	{
    		num = 90f;
    	}
    	else if (Math.Abs(wallNormalVector.x - -1f) < 0.1f)
    	{
    		num = 270f;
    	}
    	else if (Math.Abs(wallNormalVector.z - 1f) < 0.1f)
    	{
    		num = 0f;
    	}
    	else if (Math.Abs(wallNormalVector.z - -1f) < 0.1f)
    	{
    		num = 180f;
    	}
    	num = Vector3.SignedAngle(new Vector3(0f, 0f, 1f), wallNormalVector, Vector3.up);
    	float num2 = Mathf.DeltaAngle(current, num);
    	wallRunRotation = (0f - num2 / 90f) * 15f;
    	if (!readyToWallrun)
    	{
    		return;
    	}
    	if ((Mathf.Abs(wallRunRotation) < 4f && y > 0f && Math.Abs(x) < 0.1f) || (Mathf.Abs(wallRunRotation) > 22f && y < 0f && Math.Abs(x) < 0.1f))
    	{
    		if (!cancelling)
    		{
    			cancelling = true;
    			CancelInvoke("CancelWallrun");
    			Invoke("CancelWallrun", 0.2f);
    		}
    	}
    	else
    	{
    		cancelling = false;
    		CancelInvoke("CancelWallrun");
    	}
    }
    
    private void CancelWallrun()
    {
    	MonoBehaviour.print("cancelled");
    	Invoke("GetReadyToWallrun", 0.1f);
    	rb.AddForce(wallNormalVector * 600f);
    	readyToWallrun = false;
    }
    
    private void GetReadyToWallrun()
    {
    	readyToWallrun = true;
    }
    
    private void WallRunning()
    {
    	if (wallRunning)
    	{
    		rb.AddForce(-wallNormalVector * Time.deltaTime * moveSpeed);
    		rb.AddForce(Vector3.up * Time.deltaTime * rb.mass * 100f * wallRunGravity);
    	}
    }
    
    private bool IsFloor(Vector3 v)
    {
    	return Vector3.Angle(Vector3.up, v) < maxSlopeAngle;
    }
    
    private bool IsSurf(Vector3 v)
    {
    	float num = Vector3.Angle(Vector3.up, v);
    	if (num < 89f)
    	{
    		return num > maxSlopeAngle;
    	}
    	return false;
    }
    
    private bool IsWall(Vector3 v)
    {
    	return Math.Abs(90f - Vector3.Angle(Vector3.up, v)) < 0.1f;
    }
    
    private bool IsRoof(Vector3 v)
    {
    	return v.y == -1f;
    }
    
    private void StartWallRun(Vector3 normal)
    {
    	if (!grounded && readyToWallrun)
    	{
    		wallNormalVector = normal;
    		float num = 20f;
    		if (!wallRunning)
    		{
    			rb.velocity = new Vector3(rb.velocity.x, 0f, rb.velocity.z);
    			rb.AddForce(Vector3.up * num, ForceMode.Impulse);
    		}
    		wallRunning = true;
    	}
    }
    
    private void OnCollisionStay(Collision other)
    {
    	int layer = other.gameObject.layer;
    	if ((int)whatIsGround != ((int)whatIsGround | (1 << layer)))
    	{
    		return;
    	}
    	for (int i = 0; i < other.contactCount; i++)
    	{
    		Vector3 normal = other.contacts[i].normal;
    		if (IsFloor(normal))
    		{
    			if (wallRunning)
    			{
    				wallRunning = false;
    			}
    			grounded = true;
    			normalVector = normal;
    			cancellingGrounded = false;
    			CancelInvoke("StopGrounded");
    		}
    		if (IsWall(normal) && layer == LayerMask.NameToLayer("Ground"))
    		{
    			StartWallRun(normal);
    			onWall = true;
    			cancellingWall = false;
    			CancelInvoke("StopWall");
    		}
    		if (IsSurf(normal))
    		{
    			surfing = true;
    			cancellingSurf = false;
    			CancelInvoke("StopSurf");
    		}
    		IsRoof(normal);
    	}
    	float num = 3f;
    	if (!cancellingGrounded)
    	{
    		cancellingGrounded = true;
    		Invoke("StopGrounded", Time.deltaTime * num);
    	}
    	if (!cancellingWall)
    	{
    		cancellingWall = true;
    		Invoke("StopWall", Time.deltaTime * num);
    	}
    	if (!cancellingSurf)
    	{
    		cancellingSurf = true;
    		Invoke("StopSurf", Time.deltaTime * num);
    	}
    }
    
    private void StopGrounded()
    {
    	grounded = false;
    }
    
    private void StopWall()
    {
    	onWall = false;
    	wallRunning = false;
    }
    
    private void StopSurf()
    {
    	surfing = false;
    }
    
    public Vector3 GetVelocity()
    {
    	return rb.velocity;
    }
    
    public float GetFallSpeed()
    {
    	return rb.velocity.y;
    }
    
    public Collider GetPlayerCollider()
    {
    	return playerCollider;
    }
    
    public Transform GetPlayerCamTransform()
    {
    	return playerCam.transform;
    }
    
    public bool IsCrouching()
    {
    	return crouching;
    }
    
    public Rigidbody GetRb()
    {
    	return rb;
    }
    

    }

    Take the wall running sliding and put it into this script:

    // PlayerMovement using System; using UnityEngine;

    public class PlayerMovement : MonoBehaviour {
    [Header("Assignables")] //Assignables public Transform playerCam; public Transform orientation; private Collider playerCollider; public Rigidbody rb;

    [Space(10)]
    
    public LayerMask whatIsGround;
    public LayerMask whatIsWallrunnable;
    
    [Header("MovementSettings")]
    //Movement Settings 
    public float sensitivity = 50f;
    public float moveSpeed = 4500f;
    public float walkSpeed = 20f;
    public float runSpeed = 10f;
    public bool grounded;
    public bool onWall;
    
    //Private Floats
    private float wallRunGravity = 1f;
    private float maxSlopeAngle = 35f;
    private float wallRunRotation;
    private float slideSlowdown = 0.2f;
    private float actualWallRotation;
    private float wallRotationVel;
    private float desiredX;
    private float xRotation;
    private float sensMultiplier = 1f;
    private float jumpCooldown = 0.25f;
    private float jumpForce = 550f;
    private float x;
    private float y;
    private float vel;
    
    //Private bools
    private bool readyToJump;
    private bool jumping;
    private bool sprinting;
    private bool crouching;
    private bool wallRunning;
    private bool cancelling;
    private bool readyToWallrun = true;
    private bool airborne;
    private bool onGround;
    private bool surfing;
    private bool cancellingGrounded;
    private bool cancellingWall;
    private bool cancellingSurf;
    
    //Private Vector3's
    private Vector3 grapplePoint;
    private Vector3 normalVector;
    private Vector3 wallNormalVector;
    private Vector3 wallRunPos;
    private Vector3 previousLookdir;
    
    //Private int
    private int nw;
    
    //Instance
    public static PlayerMovement Instance { get; private set; }
    
    private void Awake()
    {
    	Instance = this;
    	rb = GetComponent<Rigidbody>();
    }
    
    private void Start()
    {
    	playerCollider = GetComponent<Collider>();
    	Cursor.lockState = CursorLockMode.Locked;
    	Cursor.visible = false;
    	readyToJump = true;
    	wallNormalVector = Vector3.up;
    }
    
    private void LateUpdate()
    {
        //For wallrunning
        WallRunning();
    }
    
    private void FixedUpdate()
    {
        //For moving
    	Movement();
    }
    
    private void Update()
    {
        //Input
    	MyInput();
        //Looking around
    	Look();
    }
    
    //Player input
    private void MyInput()
    {
    	x = Input.GetAxisRaw("Horizontal");
    	y = Input.GetAxisRaw("Vertical");
    	jumping = Input.GetButton("Jump");
    	crouching = Input.GetKey(KeyCode.LeftShift);
    	if (Input.GetKeyDown(KeyCode.LeftShift))
    	{
    		StartCrouch();
    	}
    	if (Input.GetKeyUp(KeyCode.LeftShift))
    	{
    		StopCrouch();
    	}
    }
    
    //Scale player down
    private void StartCrouch()
    {
    	float num = 400f;
    	base.transform.localScale = new Vector3(1f, 0.5f, 1f);
    	base.transform.position = new Vector3(base.transform.position.x, base.transform.position.y - 0.5f, base.transform.position.z);
    	if (rb.velocity.magnitude > 0.1f && grounded)
    	{
    		rb.AddForce(orientation.transform.forward * num);
    	}
    }
    
    //Scale player to original size
    private void StopCrouch()
    {
    	base.transform.localScale = new Vector3(1f, 1.5f, 1f);
    	base.transform.position = new Vector3(base.transform.position.x, base.transform.position.y + 0.5f, base.transform.position.z);
    }
    
    //Moving around with WASD
    private void Movement()
    {
    	rb.AddForce(Vector3.down * Time.deltaTime * 10f);
    	Vector2 mag = FindVelRelativeToLook();
    	float num = mag.x;
    	float num2 = mag.y;
    	CounterMovement(x, y, mag);
    	if (readyToJump && jumping)
    	{
    		Jump();
    	}
    	float num3 = walkSpeed;
    	if (sprinting)
    	{
    		num3 = runSpeed;
    	}
    	if (crouching && grounded && readyToJump)
    	{
    		rb.AddForce(Vector3.down * Time.deltaTime * 3000f);
    		return;
    	}
    	if (x > 0f && num > num3)
    	{
    		x = 0f;
    	}
    	if (x < 0f && num < 0f - num3)
    	{
    		x = 0f;
    	}
    	if (y > 0f && num2 > num3)
    	{
    		y = 0f;
    	}
    	if (y < 0f && num2 < 0f - num3)
    	{
    		y = 0f;
    	}
    	float num4 = 1f;
    	float num5 = 1f;
    	if (!grounded)
    	{
    		num4 = 0.5f;
    		num5 = 0.5f;
    	}
    	if (grounded && crouching)
    	{
    		num5 = 0f;
    	}
    	if (wallRunning)
    	{
    		num5 = 0.3f;
    		num4 = 0.3f;
    	}
    	if (surfing)
    	{
    		num4 = 0.7f;
    		num5 = 0.3f;
    	}
    	rb.AddForce(orientation.transform.forward * y * moveSpeed * Time.deltaTime * num4 * num5);
    	rb.AddForce(orientation.transform.right * x * moveSpeed * Time.deltaTime * num4);
    }
    
    //Ready to jump again
    private void ResetJump()
    {
    	readyToJump = true;
    }
    
    //Player go fly
    private void Jump()
    {
        if ((grounded || wallRunning || surfing) && readyToJump)
    	{
    	    MonoBehaviour.print("jumping");
    	    Vector3 velocity = rb.velocity;
    	    readyToJump = false;
    	    rb.AddForce(Vector2.up * jumpForce * 1.5f);
    	    rb.AddForce(normalVector * jumpForce * 0.5f);
    	    if (rb.velocity.y < 0.5f)
    	    {
    		    rb.velocity = new Vector3(velocity.x, 0f, velocity.z);
    	    }
    	    else if (rb.velocity.y > 0f)
    	    {
    		    rb.velocity = new Vector3(velocity.x, velocity.y / 2f, velocity.z);
    	    }
    	    if (wallRunning)
    	    {
    		    rb.AddForce(wallNormalVector * jumpForce * 3f);
    	    }
    	    Invoke("ResetJump", jumpCooldown);
    	    if (wallRunning)
    	    {
    		    wallRunning = false;
    	    }
        }
    }
    
    //Looking around by using your mouse
    private void Look()
    {
    	float num = Input.GetAxis("Mouse X") * sensitivity * Time.fixedDeltaTime * sensMultiplier;
    	float num2 = Input.GetAxis("Mouse Y") * sensitivity * Time.fixedDeltaTime * sensMultiplier;
    	desiredX = playerCam.transform.localRotation.eulerAngles.y + num;
    	xRotation -= num2;
    	xRotation = Mathf.Clamp(xRotation, -90f, 90f);
    	FindWallRunRotation();
    	actualWallRotation = Mathf.SmoothDamp(actualWallRotation, wallRunRotation, ref wallRotationVel, 0.2f);
    	playerCam.transform.localRotation = Quaternion.Euler(xRotation, desiredX, actualWallRotation);
    	orientation.transform.localRotation = Quaternion.Euler(0f, desiredX, 0f);
    }
    
    //Make the player movement feel good 
    private void CounterMovement(float x, float y, Vector2 mag)
    {
    	if (!grounded || jumping)
    	{
    		return;
    	}
    	float num = 0.16f;
    	float num2 = 0.01f;
    	if (crouching)
    	{
    		rb.AddForce(moveSpeed * Time.deltaTime * -rb.velocity.normalized * slideSlowdown);
    		return;
    	}
    	if ((Math.Abs(mag.x) > num2 && Math.Abs(x) < 0.05f) || (mag.x < 0f - num2 && x > 0f) || (mag.x > num2 && x < 0f))
    	{
    		rb.AddForce(moveSpeed * orientation.transform.right * Time.deltaTime * (0f - mag.x) * num);
    	}
    	if ((Math.Abs(mag.y) > num2 && Math.Abs(y) < 0.05f) || (mag.y < 0f - num2 && y > 0f) || (mag.y > num2 && y < 0f))
    	{
    		rb.AddForce(moveSpeed * orientation.transform.forward * Time.deltaTime * (0f - mag.y) * num);
    	}
    	if (Mathf.Sqrt(Mathf.Pow(rb.velocity.x, 2f) + Mathf.Pow(rb.velocity.z, 2f)) > walkSpeed)
    	{
    		float num3 = rb.velocity.y;
    		Vector3 vector = rb.velocity.normalized * walkSpeed;
    		rb.velocity = new Vector3(vector.x, num3, vector.z);
    	}
    }
    
    public Vector2 FindVelRelativeToLook()
    {
    	float current = orientation.transform.eulerAngles.y;
    	float target = Mathf.Atan2(rb.velocity.x, rb.velocity.z) * 57.29578f;
    	float num = Mathf.DeltaAngle(current, target);
    	float num2 = 90f - num;
    	float magnitude = rb.velocity.magnitude;
    	return new Vector2(y: magnitude * Mathf.Cos(num * ((float)Math.PI / 180f)), x: magnitude * Mathf.Cos(num2 * ((float)Math.PI / 180f)));
    }
    
    private void FindWallRunRotation()
    {
    	if (!wallRunning)
    	{
    		wallRunRotation = 0f;
    		return;
    	}
    	_ = new Vector3(0f, playerCam.transform.rotation.y, 0f).normalized;
    	new Vector3(0f, 0f, 1f);
    	float num = 0f;
    	float current = playerCam.transform.rotation.eulerAngles.y;
    	if (Math.Abs(wallNormalVector.x - 1f) < 0.1f)
    	{
    		num = 90f;
    	}
    	else if (Math.Abs(wallNormalVector.x - -1f) < 0.1f)
    	{
    		num = 270f;
    	}
    	else if (Math.Abs(wallNormalVector.z - 1f) < 0.1f)
    	{
    		num = 0f;
    	}
    	else if (Math.Abs(wallNormalVector.z - -1f) < 0.1f)
    	{
    		num = 180f;
    	}
    	num = Vector3.SignedAngle(new Vector3(0f, 0f, 1f), wallNormalVector, Vector3.up);
    	float num2 = Mathf.DeltaAngle(current, num);
    	wallRunRotation = (0f - num2 / 90f) * 15f;
    	if (!readyToWallrun)
    	{
    		return;
    	}
    	if ((Mathf.Abs(wallRunRotation) < 4f && y > 0f && Math.Abs(x) < 0.1f) || (Mathf.Abs(wallRunRotation) > 22f && y < 0f && Math.Abs(x) < 0.1f))
    	{
    		if (!cancelling)
    		{
    			cancelling = true;
    			CancelInvoke("CancelWallrun");
    			Invoke("CancelWallrun", 0.2f);
    		}
    	}
    	else
    	{
    		cancelling = false;
    		CancelInvoke("CancelWallrun");
    	}
    }
    
    private void CancelWallrun()
    {
    	MonoBehaviour.print("cancelled");
    	Invoke("GetReadyToWallrun", 0.1f);
    	rb.AddForce(wallNormalVector * 600f);
    	readyToWallrun = false;
    }
    
    private void GetReadyToWallrun()
    {
    	readyToWallrun = true;
    }
    
    private void WallRunning()
    {
    	if (wallRunning)
    	{
    		rb.AddForce(-wallNormalVector * Time.deltaTime * moveSpeed);
    		rb.AddForce(Vector3.up * Time.deltaTime * rb.mass * 100f * wallRunGravity);
    	}
    }
    
    private bool IsFloor(Vector3 v)
    {
    	return Vector3.Angle(Vector3.up, v) < maxSlopeAngle;
    }
    
    private bool IsSurf(Vector3 v)
    {
    	float num = Vector3.Angle(Vector3.up, v);
    	if (num < 89f)
    	{
    		return num > maxSlopeAngle;
    	}
    	return false;
    }
    
    private bool IsWall(Vector3 v)
    {
    	return Math.Abs(90f - Vector3.Angle(Vector3.up, v)) < 0.1f;
    }
    
    private bool IsRoof(Vector3 v)
    {
    	return v.y == -1f;
    }
    
    private void StartWallRun(Vector3 normal)
    {
    	if (!grounded && readyToWallrun)
    	{
    		wallNormalVector = normal;
    		float num = 20f;
    		if (!wallRunning)
    		{
    			rb.velocity = new Vector3(rb.velocity.x, 0f, rb.velocity.z);
    			rb.AddForce(Vector3.up * num, ForceMode.Impulse);
    		}
    		wallRunning = true;
    	}
    }
    
    private void OnCollisionStay(Collision other)
    {
    	int layer = other.gameObject.layer;
    	if ((int)whatIsGround != ((int)whatIsGround | (1 << layer)))
    	{
    		return;
    	}
    	for (int i = 0; i < other.contactCount; i++)
    	{
    		Vector3 normal = other.contacts[i].normal;
    		if (IsFloor(normal))
    		{
    			if (wallRunning)
    			{
    				wallRunning = false;
    			}
    			grounded = true;
    			normalVector = normal;
    			cancellingGrounded = false;
    			CancelInvoke("StopGrounded");
    		}
    		if (IsWall(normal) && layer == LayerMask.NameToLayer("Ground"))
    		{
    			StartWallRun(normal);
    			onWall = true;
    			cancellingWall = false;
    			CancelInvoke("StopWall");
    		}
    		if (IsSurf(normal))
    		{
    			surfing = true;
    			cancellingSurf = false;
    			CancelInvoke("StopSurf");
    		}
    		IsRoof(normal);
    	}
    	float num = 3f;
    	if (!cancellingGrounded)
    	{
    		cancellingGrounded = true;
    		Invoke("StopGrounded", Time.deltaTime * num);
    	}
    	if (!cancellingWall)
    	{
    		cancellingWall = true;
    		Invoke("StopWall", Time.deltaTime * num);
    	}
    	if (!cancellingSurf)
    	{
    		cancellingSurf = true;
    		Invoke("StopSurf", Time.deltaTime * num);
    	}
    }
    
    private void StopGrounded()
    {
    	grounded = false;
    }
    
    private void StopWall()
    {
    	onWall = false;
    	wallRunning = false;
    }
    
    private void StopSurf()
    {
    	surfing = false;
    }
    
    public Vector3 GetVelocity()
    {
    	return rb.velocity;
    }
    
    public float GetFallSpeed()
    {
    	return rb.velocity.y;
    }
    
    public Collider GetPlayerCollider()
    {
    	return playerCollider;
    }
    
    public Transform GetPlayerCamTransform()
    {
    	return playerCam.transform;
    }
    
    public bool IsCrouching()
    {
    	return crouching;
    }
    
    public Rigidbody GetRb()
    {
    	return rb;
    }
    

    }

  2. Assistant

    Certainly! To integrate both wall running and sliding functionalities into your existing PlayerMovement script, we'll enhance the current implementation by adding sliding mechanics alongside the existing wall running features. Below is the updated script with detailed explanations of the changes made to incorporate sliding seamlessly.

    Updated PlayerMovement Script with Wall Running and Sliding

    // PlayerMovement
    using System;
    using UnityEngine;
    
    public class PlayerMovement : MonoBehaviour
    {   
        [Header("Assignables")]
        // Assignables
        public Transform playerCam;
        public Transform orientation;
        private Collider playerCollider;
        public Rigidbody rb;
    
        [Space(10)]
    
        public LayerMask whatIsGround;
        public LayerMask whatIsWallrunnable;
    
        [Header("MovementSettings")]
        // Movement Settings 
        public float sensitivity = 50f;
        public float moveSpeed = 4500f;
        public float walkSpeed = 20f;
        public float runSpeed = 10f;
        public bool grounded;
        public bool onWall;
    
        [Header("Sliding Settings")]
        public float slideForce = 600f;           // Force applied when sliding
        public float slideDuration = 1f;          // Duration of the slide
        public float slideCooldown = 1f;          // Cooldown before another slide can be initiated
        private bool isSliding = false;           // Indicates if the player is currently sliding
        private bool canSlide = true;             // Indicates if the player can initiate a slide
    
        // Private Floats
        private float wallRunGravity = 1f;
        private float maxSlopeAngle = 35f;
        private float wallRunRotation;
        private float slideSlowdown = 0.2f;
        private float actualWallRotation;
        private float wallRotationVel;
        private float desiredX;
        private float xRotation;
        private float sensMultiplier = 1f;
        private float jumpCooldown = 0.25f;
        private float jumpForce = 550f;
        private float x;
        private float y;
        private float vel;
    
        // Private Bools
        private bool readyToJump;
        private bool jumping;
        private bool sprinting;
        private bool crouching;
        private bool wallRunning;
        private bool cancelling;
        private bool readyToWallrun = true;
        private bool airborne;
        private bool onGround;
        private bool surfing;
        private bool cancellingGrounded;
        private bool cancellingWall;
        private bool cancellingSurf;
    
        // Private Vector3's
        private Vector3 grapplePoint;
        private Vector3 normalVector;
        private Vector3 wallNormalVector;
        private Vector3 wallRunPos;
        private Vector3 previousLookdir;
    
        // Private int
        private int nw;
    
        // Instance
        public static PlayerMovement Instance { get; private set; }
    
        private void Awake()
        {
            Instance = this;
            rb = GetComponent<Rigidbody>();
        }
    
        private void Start()
        {
            playerCollider = GetComponent<Collider>();
            Cursor.lockState = CursorLockMode.Locked;
            Cursor.visible = false;
            readyToJump = true;
            wallNormalVector = Vector3.up;
        }
    
        private void LateUpdate()
        {
            // For wall running
            WallRunning();
        }
    
        private void FixedUpdate()
        {
            // For moving
            Movement();
        }
    
        private void Update()
        {
            // Input
            MyInput();
            // Looking around
            Look();
        }
    
        // Player input
        private void MyInput()
        {
            x = Input.GetAxisRaw("Horizontal");
            y = Input.GetAxisRaw("Vertical");
            jumping = Input.GetButton("Jump");
            bool wasCrouching = crouching;
            crouching = Input.GetKey(KeyCode.LeftShift);
    
            if (Input.GetKeyDown(KeyCode.LeftShift))
            {
                if (grounded && rb.velocity.magnitude > 0.1f && canSlide)
                {
                    StartSlide();
                }
                else
                {
                    StartCrouch();
                }
            }
            if (Input.GetKeyUp(KeyCode.LeftShift))
            {
                if (isSliding)
                {
                    StopSlide();
                }
                else
                {
                    StopCrouch();
                }
            }
        }
    
        // Scale player down for crouching
        private void StartCrouch()
        {
            Vector3 originalScale = transform.localScale;
            transform.localScale = new Vector3(originalScale.x, 0.5f, originalScale.z);
            transform.position = new Vector3(transform.position.x, transform.position.y - 0.5f, transform.position.z);
        }
    
        // Scale player to original size
        private void StopCrouch()
        {
            Vector3 originalScale = transform.localScale;
            transform.localScale = new Vector3(originalScale.x, 1.5f, originalScale.z);
            transform.position = new Vector3(transform.position.x, transform.position.y + 0.5f, transform.position.z);
        }
    
        // Initiate sliding
        private void StartSlide()
        {
            isSliding = true;
            canSlide = false;
    
            // Reduce player height for sliding (if different from crouching)
            Vector3 originalScale = transform.localScale;
            transform.localScale = new Vector3(originalScale.x, 1f, originalScale.z);
            transform.position = new Vector3(transform.position.x, transform.position.y - 0.5f, transform.position.z);
    
            // Apply forward force
            Vector3 slideDirection = orientation.transform.forward;
            rb.AddForce(slideDirection * slideForce, ForceMode.Impulse);
    
            // Invoke to stop sliding after duration
            Invoke(nameof(StopSlide), slideDuration);
            // Invoke to reset sliding ability after cooldown
            Invoke(nameof(ResetSlide), slideCooldown);
        }
    
        // Stop sliding
        private void StopSlide()
        {
            isSliding = false;
            // Reset player scale after sliding
            Vector3 originalScale = transform.localScale;
            transform.localScale = new Vector3(originalScale.x, 1.5f, originalScale.z);
            transform.position = new Vector3(transform.position.x, transform.position.y + 0.5f, transform.position.z);
        }
    
        // Reset sliding ability
        private void ResetSlide()
        {
            canSlide = true;
        }
    
        // Moving around with WASD and sliding
        private void Movement()
        {
            rb.AddForce(Vector3.down * Time.deltaTime * 10f);
            Vector2 mag = FindVelRelativeToLook();
            float currentX = mag.x;
            float currentY = mag.y;
            CounterMovement(x, y, mag);
    
            if (readyToJump && jumping)
            {
                Jump();
            }
    
            float targetSpeed = walkSpeed;
            if (sprinting)
            {
                targetSpeed = runSpeed;
            }
    
            if (crouching && grounded && !isSliding && readyToJump)
            {
                rb.AddForce(Vector3.down * Time.deltaTime * 3000f);
                return;
            }
    
            if (x > 0f && currentX > targetSpeed)
            {
                x = 0f;
            }
            if (x < 0f && currentX < -targetSpeed)
            {
                x = 0f;
            }
            if (y > 0f && currentY > targetSpeed)
            {
                y = 0f;
            }
            if (y < 0f && currentY < -targetSpeed)
            {
                y = 0f;
            }
    
            float multiplierX = 1f;
            float multiplierY = 1f;
    
            if (!grounded)
            {
                multiplierX = 0.5f;
                multiplierY = 0.5f;
            }
    
            if (grounded && crouching && !isSliding)
            {
                multiplierY = 0f;
            }
    
            if (wallRunning)
            {
                multiplierY = 0.3f;
                multiplierX = 0.3f;
            }
    
            if (surfing)
            {
                multiplierX = 0.7f;
                multiplierY = 0.3f;
            }
    
            // Apply movement forces
            rb.AddForce(orientation.transform.forward * y * moveSpeed * Time.deltaTime * multiplierY * (isSliding ? 1.5f : 1f));
            rb.AddForce(orientation.transform.right * x * moveSpeed * Time.deltaTime * multiplierX);
        }
    
        // Ready to jump again
        private void ResetJump()
        {
            readyToJump = true;
        }
    
        // Player jump
        private void Jump()
        {
            if ((grounded || wallRunning || surfing) && readyToJump)
            {
                Debug.Log("Jumping");
                Vector3 velocity = rb.velocity;
                readyToJump = false;
                rb.AddForce(Vector2.up * jumpForce * 1.5f);
                rb.AddForce(normalVector * jumpForce * 0.5f);
                if (rb.velocity.y < 0.5f)
                {
                    rb.velocity = new Vector3(velocity.x, 0f, velocity.z);
                }
                else if (rb.velocity.y > 0f)
                {
                    rb.velocity = new Vector3(velocity.x, rb.velocity.y / 2f, velocity.z);
                }
                if (wallRunning)
                {
                    rb.AddForce(wallNormalVector * jumpForce * 3f);
                }
                Invoke(nameof(ResetJump), jumpCooldown);
                if (wallRunning)
                {
                    wallRunning = false;
                }
            }
        }
    
        // Looking around by using your mouse
        private void Look()
        {
            float mouseX = Input.GetAxis("Mouse X") * sensitivity * Time.fixedDeltaTime * sensMultiplier;
            float mouseY = Input.GetAxis("Mouse Y") * sensitivity * Time.fixedDeltaTime * sensMultiplier;
    
            desiredX = playerCam.transform.localRotation.eulerAngles.y + mouseX;
            xRotation -= mouseY;
            xRotation = Mathf.Clamp(xRotation, -90f, 90f);
    
            FindWallRunRotation();
            actualWallRotation = Mathf.SmoothDamp(actualWallRotation, wallRunRotation, ref wallRotationVel, 0.2f);
    
            playerCam.transform.localRotation = Quaternion.Euler(xRotation, desiredX, actualWallRotation);
            orientation.transform.localRotation = Quaternion.Euler(0f, desiredX, 0f);
        }
    
        // Make the player movement feel good 
        private void CounterMovement(float x, float y, Vector2 mag)
        {
            if (!grounded || jumping)
            {
                return;
            }
    
            float counterForce = 0.16f;
            float minVelocity = 0.01f;
    
            if (crouching && !isSliding)
            {
                rb.AddForce(moveSpeed * Time.deltaTime * -rb.velocity.normalized * slideSlowdown);
                return;
            }
    
            // Counter movement on X axis
            if ((Math.Abs(mag.x) > minVelocity && Math.Abs(x) < 0.05f) ||
                (mag.x < 0f - minVelocity && x > 0f) ||
                (mag.x > minVelocity && x < 0f))
            {
                rb.AddForce(orientation.transform.right * Time.deltaTime * -mag.x * counterForce * moveSpeed);
            }
    
            // Counter movement on Y axis
            if ((Math.Abs(mag.y) > minVelocity && Math.Abs(y) < 0.05f) ||
                (mag.y < 0f - minVelocity && y > 0f) ||
                (mag.y > minVelocity && y < 0f))
            {
                rb.AddForce(orientation.transform.forward * Time.deltaTime * -mag.y * counterForce * moveSpeed);
            }
    
            // Limit maximum speed
            float horizontalSpeed = new Vector3(rb.velocity.x, 0, rb.velocity.z).magnitude;
            if (horizontalSpeed > walkSpeed)
            {
                Vector3 limitedVelocity = rb.velocity.normalized * walkSpeed;
                rb.velocity = new Vector3(limitedVelocity.x, rb.velocity.y, limitedVelocity.z);
            }
        }
    
        // Find velocity relative to where the player is looking
        public Vector2 FindVelRelativeToLook()
        {
            float lookAngle = orientation.transform.eulerAngles.y;
            float moveAngle = Mathf.Atan2(rb.velocity.x, rb.velocity.z) * Mathf.Rad2Deg;
            float angle = Mathf.DeltaAngle(lookAngle, moveAngle);
            float adjustedAngle = 90f - angle;
            float magnitude = rb.velocity.magnitude;
    
            return new Vector2(Mathf.Cos(Mathf.Deg2Rad * angle) * magnitude, Mathf.Cos(Mathf.Deg2Rad * adjustedAngle) * magnitude);
        }
    
        // Calculate rotation during wall run
        private void FindWallRunRotation()
        {
            if (!wallRunning)
            {
                wallRunRotation = 0f;
                return;
            }
    
            float desiredAngle = Vector3.SignedAngle(Vector3.forward, wallNormalVector, Vector3.up);
            float currentAngle = playerCam.transform.rotation.eulerAngles.y;
            float deltaAngle = Mathf.DeltaAngle(currentAngle, desiredAngle);
            wallRunRotation = (-deltaAngle / 90f) * 15f;
    
            if (!readyToWallrun)
            {
                return;
            }
    
            // Determine if wall run should be cancelled based on camera rotation and player input
            if ((Mathf.Abs(wallRunRotation) < 4f && y > 0f && Math.Abs(x) < 0.1f) || 
                (Mathf.Abs(wallRunRotation) > 22f && y < 0f && Math.Abs(x) < 0.1f))
            {
                if (!cancelling)
                {
                    cancelling = true;
                    CancelInvoke(nameof(CancelWallrun));
                    Invoke(nameof(CancelWallrun), 0.2f);
                }
            }
            else
            {
                cancelling = false;
                CancelInvoke(nameof(CancelWallrun));
            }
        }
    
        // Cancel wall running
        private void CancelWallrun()
        {
            Debug.Log("Wall run cancelled");
            Invoke(nameof(GetReadyToWallrun), 0.1f);
            rb.AddForce(wallNormalVector * 600f);
            readyToWallrun = false;
        }
    
        // Prepare to wall run again
        private void GetReadyToWallrun()
        {
            readyToWallrun = true;
        }
    
        // Handle wall running forces
        private void WallRunning()
        {
            if (wallRunning)
            {
                rb.AddForce(-wallNormalVector * Time.deltaTime * moveSpeed);
                rb.AddForce(Vector3.up * Time.deltaTime * rb.mass * 100f * wallRunGravity);
            }
        }
    
        // Helper methods to identify surface types based on normal vectors
        private bool IsFloor(Vector3 normal)
        {
            return Vector3.Angle(Vector3.up, normal) < maxSlopeAngle;
        }
    
        private bool IsSurf(Vector3 normal)
        {
            float angle = Vector3.Angle(Vector3.up, normal);
            return angle > maxSlopeAngle && angle < 89f;
        }
    
        private bool IsWall(Vector3 normal)
        {
            return Math.Abs(90f - Vector3.Angle(Vector3.up, normal)) < 0.1f;
        }
    
        private bool IsRoof(Vector3 normal)
        {
            return normal.y == -1f;
        }
    
        // Initiate wall run
        private void StartWallRun(Vector3 normal)
        {
            if (!grounded && readyToWallrun)
            {
                wallNormalVector = normal;
                float upwardForce = 20f;
                if (!wallRunning)
                {
                    rb.velocity = new Vector3(rb.velocity.x, 0f, rb.velocity.z);
                    rb.AddForce(Vector3.up * upwardForce, ForceMode.Impulse);
                }
                wallRunning = true;
            }
        }
    
        // Handle collisions to detect surfaces for sliding and wall running
        private void OnCollisionStay(Collision other)
        {
            int layer = other.gameObject.layer;
            if ((whatIsGround.value & (1 << layer)) == 0)
            {
                return;
            }
    
            for (int i = 0; i < other.contactCount; i++)
            {
                Vector3 normal = other.contacts[i].normal;
                if (IsFloor(normal))
                {
                    if (wallRunning)
                    {
                        wallRunning = false;
                    }
                    grounded = true;
                    normalVector = normal;
                    cancellingGrounded = false;
                    CancelInvoke(nameof(StopGrounded));
                }
                if (IsWall(normal) && layer == LayerMask.NameToLayer("Ground"))
                {
                    StartWallRun(normal);
                    onWall = true;
                    cancellingWall = false;
                    CancelInvoke(nameof(StopWall));
                }
                if (IsSurf(normal))
                {
                    surfing = true;
                    cancellingSurf = false;
                    CancelInvoke(nameof(StopSurf));
                }
                // You can handle roof detection here if needed
                // IsRoof(normal);
            }
    
            float delay = 3f;
            if (!cancellingGrounded)
            {
                cancellingGrounded = true;
                Invoke(nameof(StopGrounded), Time.deltaTime * delay);
            }
            if (!cancellingWall)
            {
                cancellingWall = true;
                Invoke(nameof(StopWall), Time.deltaTime * delay);
            }
            if (!cancellingSurf)
            {
                cancellingSurf = true;
                Invoke(nameof(StopSurf), Time.deltaTime * delay);
            }
        }
    
        private void StopGrounded()
        {
            grounded = false;
        }
    
        private void StopWall()
        {
            onWall = false;
            wallRunning = false;
        }
    
        private void StopSurf()
        {
            surfing = false;
        }
    
        // Public getters for other scripts (if needed)
        public Vector3 GetVelocity()
        {
            return rb.velocity;
        }
    
        public float GetFallSpeed()
        {
            return rb.velocity.y;
        }
    
        public Collider GetPlayerCollider()
        {
            return playerCollider;
        }
    
        public Transform GetPlayerCamTransform()
        {
            return playerCam.transform;
        }
    
        public bool IsCrouching()
        {
            return crouching;
        }
    
        public Rigidbody GetRb()
        {
            return rb;
        }
    }
    

    Key Enhancements and Additions

    1. Sliding Mechanics:

      • Variables Added:
        • slideForce: Determines the force applied forward when sliding.
        • slideDuration: How long the slide lasts.
        • slideCooldown: Time before the player can slide again.
        • isSliding and canSlide: To manage sliding state and cooldown.
      • Sliding Implementation:
        • Input Handling: Modified the MyInput() method to detect if the player is moving while initiating a crouch. If the player is moving and can slide, it triggers the slide instead of just crouching.
        • StartSlide(): Adjusts the player's scale (height) for sliding, applies a forward impulse, and sets up timers to stop sliding and reset the ability to slide.
        • StopSlide(): Resets the player's scale and sliding state.
        • ResetSlide(): Allows the player to slide again after the cooldown.
    2. Enhanced Crouching:

      • Crouching now differentiates between simply lowering the player's height and initiating a slide. When sliding, additional forward force is applied, and the player's collider is adjusted appropriately.
    3. Movement Adjustments During Slide:

      • In the Movement() method, when isSliding is true, an increased multiplier is applied to movement forces to make sliding feel more impactful and distinct from regular movement.
    4. Counter Movement Tweaks:

      • The CounterMovement() method has conditions to reduce or negate movement forces when the player is sliding, ensuring smooth transitions and maintaining control.
    5. Wall Running Integration:

      • The existing wall running logic remains intact, allowing the player to perform wall runs seamlessly alongside sliding.
      • Adjustments ensure that sliding doesn't interfere with wall running and vice versa.
    6. Code Clean-Up and Optimization:

      • Debugging: Replaced MonoBehaviour.print with Debug.Log for better logging practices.
      • Method Naming: Used nameof() for method references in Invoke and CancelInvoke to prevent errors due to typos.
      • Layer Mask Checks: Optimized layer mask comparisons for better performance and readability.

    Usage Instructions

    1. Assign Layer Masks:

      • Ensure that your ground and wall objects are assigned to the layers specified in whatIsGround and whatIsWallrunnable respectively.
    2. Configure Sliding Parameters:

      • Adjust the slideForce, slideDuration, and slideCooldown in the Inspector to fit the desired sliding behavior.
    3. Player Collider and Rigidbody:

      • Make sure your player GameObject has both a Collider (preferably a CapsuleCollider) and a Rigidbody component attached. The Rigidbody should have Freeze Rotation checked on all axes to prevent unwanted rotation.
    4. Input Mapping:

      • The script uses the LeftShift key for both crouching and sliding. When the player is moving and presses LeftShift, the character will slide. If the player is stationary, pressing LeftShift will initiate a crouch.
    5. Camera Setup:

      • Assign the playerCam and orientation transforms in the Inspector. The orientation should typically be a child object that determines the direction the player is facing.
    6. Testing:

      • Play the scene and test the sliding by moving forward and pressing LeftShift. The player should smoothly transition into a slide, maintain forward momentum, and then return to normal movement after the slide duration and cooldown.

    Additional Recommendations

    • Animations: For a more polished experience, consider adding sliding animations that correspond with the sliding mechanics.
    • Sound Effects: Incorporate sliding sound effects to enhance the feel of the movement.
    • Visual Effects: Add particle effects or camera shakes during slides to provide visual feedback.
    • Advanced Mechanics: Implement slide decay or multiple slide stages for increased depth and responsiveness.

    By integrating these sliding mechanics alongside your existing wall running features, your PlayerMovement script will offer a more dynamic and responsive control scheme, enhancing the overall gameplay experience.