When Im moving diagonally, my character goes faster, and I’d like to stop it.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Movement : MonoBehaviour
{
public float speed;
public float runSpeed;
public float baseSpeed;
public float jumpForce;
public bool isRunning = false;
private float multiplier;
public float turnSmoothTime = 0.1f;
float turnSmoothVelocity;
[Space]
public Vector3 checkDistance;
public Transform groundCheck;
public LayerMask groundMask;
[Space]
public bool isGrounded;
public bool canMove;
public bool isMoving;
[Space]
[SerializeField] private Rigidbody rb;
public Animator anim;
public Transform cam;
void FixedUpdate()
{
//Cursor.lockState = CursorLockMode.Locked;
float horizontalInput = Input.GetAxis("Horizontal");
float verticalInput = Input.GetAxis("Vertical");
if (Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.S) || Input.GetKey(KeyCode.D)
|| Input.GetKey(KeyCode.UpArrow) || Input.GetKey(KeyCode.LeftArrow) || Input.GetKey(KeyCode.DownArrow) || Input.GetKey(KeyCode.RightArrow))
isMoving = true;
else
isMoving = false;
Vector3 forward = Camera.main.transform.forward;
Vector3 right = Camera.main.transform.right;
multiplier = 1f;
forward.y = 0;
right.y = 0;
forward.Normalize();
right.Normalize();
Vector3 rotateDirection = new Vector3(horizontalInput, 0f, verticalInput).normalized;
Vector3 moveDirection = forward * verticalInput + right * horizontalInput;
rb.velocity = new Vector3(moveDirection.x * (speed) * multiplier, rb.velocity.y, moveDirection.z * (speed) * multiplier);
//transform.rotation = new Quaternion(0, camFace.transform.rotation.y, 0, camFace.transform.rotation.w);
if (moveDirection != new Vector3(0, 0, 0))
{
float targetAngle = Mathf.Atan2(rotateDirection.x, rotateDirection.z) * Mathf.Rad2Deg + cam.eulerAngles.y;
float angle = Mathf.SmoothDampAngle(transform.eulerAngles.y, targetAngle, ref turnSmoothVelocity, turnSmoothTime);
transform.rotation = Quaternion.Euler(0, angle, 0f);
}
else
{
StartCoroutine(StopRun());
}
anim.SetBool("isMoving", isMoving);
anim.SetBool("isGrounded", isGrounded);
}
void Update()
{
isGrounded = Physics.CheckBox(groundCheck.position, checkDistance, Quaternion.identity, groundMask);
if (isGrounded && Input.GetKey(KeyCode.Space))
{
rb.velocity = Vector3.up * jumpForce;
}
if (Input.GetKeyDown(KeyCode.LeftShift))
{
if (isRunning == false)
{
StartCoroutine(Run());
}
else
{
speed = baseSpeed;
isRunning = false;
}
}
if (!isRunning)
speed = baseSpeed;
}
private void OnDrawGizmosSelected()
{
Gizmos.color = Color.yellow;
Gizmos.DrawWireCube(groundCheck.transform.position, checkDistance);
}
IEnumerator Run()
{
yield return new WaitForSeconds(0.01f);
speed = runSpeed;
isRunning = true;
}
IEnumerator StopRun()
{
yield return new WaitForSeconds(0.05f);
if(!isMoving)
isRunning = false;
}
}