I’m making a game where you can press “q” to slide when you’re at a certain speed. If you’re too slow, or when you eventually slow down from the slide, you start “crawling” (moving slow). I can make the CharacterController crawl, but I can’t make it slide (it seems to just reverse your controls while crawling).
This is my code.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UIElements;
public class PlayerMovement : MonoBehaviour
{
public CharacterController controller;
public float speed = 12f;
public float crawlSpeed = 0f;
public float gravity = -9.81f;
public float jumpHeight = 3f;
public float crouchHeight = 0.5f;
public float slideDuration = 1f;
public Transform groundCheck;
public float groundDistance = 0.4f;
public LayerMask groundMask;
private float slideMinus;
private float pSpeed;
private float speedBackup;
private Vector3 scaleBackup;
private Vector3 move2;
Vector3 velocity;
bool isGrounded;
private void Start()
{
print(transform.right);
print(transform.forward);
pSpeed = speed;
speedBackup = speed;
scaleBackup = transform.localScale;
}
// Update is called once per frame
void Update()
{
if(Input.GetKey("q") == false)
{
transform.localScale = scaleBackup;
}
pSpeed = speedBackup;
isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);
if(isGrounded && velocity.y < 0)
{
velocity.y = -5f;
}
float x = Input.GetAxis("Horizontal");
float z = Input.GetAxis("Vertical");
Vector3 move = transform.right * x + transform.forward * z;
move2 = move;
if(Input.GetKey("q"))
{
StartCoroutine("Slide");
pSpeed = crawlSpeed;
Crouch();
}
controller.Move(move * pSpeed * Time.deltaTime);
if (Input.GetButtonDown("Jump") && isGrounded)
{
velocity.y = Mathf.Sqrt(jumpHeight * -5f * gravity);
}
velocity.y += gravity * Time.deltaTime;
controller.Move(velocity * Time.deltaTime);
}
void Crouch()
{
transform.localScale = new Vector3(transform.localScale.x, crouchHeight, transform.localScale.z);
}
IEnumerator Slide()
{
Vector3 moveLocked = move2 * pSpeed * Time.deltaTime;
controller.Move(new Vector3(moveLocked.x * -0.5f, moveLocked.y, moveLocked.z * -0.5f));
yield return new WaitForSeconds(1);
}
}
Any idea how to fix this?
NOTE: I’m a beginner to Unity.