Hello, everyone, this is my second time asking a question here. So what I’m trying to do is when the character slides, he only slides in one direction. I want to do this so that you can’t move backward when sliding. Here’s the movement code I’m using. (This is a first person game using the Character Controller for moving if that’s important)
- using UnityEngine;
using System.Collections;
public class Movement : MonoBehaviour
{
public float moveSpeed;
public float runSpeed;
public float jumpPower;
float gravity = -9.81f;
float verticalVel = 0;
CharacterController controller;
float horizontalRotation;
float verticalRotation;
public float upDownRange;
public float mouseSensX;
public float mouseSensY;
float distToCeiling;
private bool crouchCollision = false;
public bool isRunning;
public bool isSliding;
public float slideSpeed = 10.0f;
private float slideTimer = 0.0f;
public float slideTimerMax = 1.5f;
void Start()
{
controller = GetComponent<CharacterController> ();
Cursor.visible = false;
Cursor.lockState = CursorLockMode.Locked;
distToCeiling = GetComponent<CapsuleCollider> ().bounds.extents.y;
}
void Update()
{
//Rotation
horizontalRotation = Input.GetAxis ("Mouse X") * mouseSensX;
transform.Rotate (0, horizontalRotation, 0);
verticalRotation -= Input.GetAxis ("Mouse Y") * mouseSensY;
verticalRotation = Mathf.Clamp (verticalRotation, -upDownRange, upDownRange);
Camera.main.transform.localRotation = Quaternion.Euler (verticalRotation, 0, 0);
//Movement
float forwardSpeed = Input.GetAxis ("Vertical") * moveSpeed;
float sideSpeed = Input.GetAxis ("Horizontal") * moveSpeed;
if (controller.isGrounded)
{
verticalVel = 0;
}
if (Input.GetKeyDown (KeyCode.Space) && controller.isGrounded)
{
verticalVel = jumpPower;
}
verticalVel += gravity * Time.deltaTime;
Vector3 speed = new Vector3 (sideSpeed, verticalVel, forwardSpeed);
speed = transform.rotation * speed;
controller.Move (speed * Time.deltaTime);
//Other Stuff
if (Input.GetKey (KeyCode.LeftShift))
{
moveSpeed = runSpeed;
isRunning = true;
}
else
{
moveSpeed = 5f;
isRunning = false;
}
if (Physics.Raycast (transform.position, transform.up, 1.5f))
{
crouchCollision = true;
}
else
{
crouchCollision = false;
}
if (!isSliding && crouchCollision) {
Crouch ();
} else if (isSliding && crouchCollision) {
Crouch ();
} else {
UnCrouch ();
}
if (Input.GetKeyDown (KeyCode.F) && !isSliding && isRunning)
{
slideTimer = 0.0f;
isSliding = true;
}
if (isSliding) {
Slide ();
}
}
void Slide()
{
Crouch ();
moveSpeed = slideSpeed;
slideTimer += Time.deltaTime;
if (slideTimer > slideTimerMax) {
isSliding = false;
slideTimer = 0.0f;
}
}
void Crouch()
{
controller.height = 1.0f;
jumpPower = 0f;
}
void UnCrouch()
{
controller.height = 2.0f;
jumpPower = 6f;
}
void FixedUpdate()
{
Vector3 up = transform.TransformDirection (Vector3.up);
if (Physics.Raycast (transform.position, up, distToCeiling + 0.1f))
{
verticalVel = 0;
}
}
}