I’m trying to get my player to run when I press the left shift down, but no matter how I try and modify the code, it only ever moves according to walkSpeed and never to sprintSpeed even though I know that the velocity is being set to sprintSpeed when I press left shift down. Any help would be appreciated.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CharacterController : MonoBehaviour
{
//8 direction character controller
//https://www.youtube.com/watch?v=cVy-NTjqZR8
float velocity = 5;
public float turnSpeed;
public float walkSpeed;
public float sprintSpeed;
public bool isSprinting;
Animator anim;
Vector2 playerInput;
float angle; //to know how to rotate player
Quaternion targetRotation; //quaternion used to represent rotations
Transform cam; // to keep track of camera angles
// Start is called before the first frame update
void Start()
{
cam = Camera.main.transform; //this accesses the main camera
anim = GetComponent<Animator>();
}
// Update is called once per frame
void Update()
{
GetInput();//get input every frame, so the thing stops when
if (Mathf.Abs(playerInput.x) < 1 && Mathf.Abs(playerInput.y) < 1)
{ //this stops the character from moving when no input
anim.SetInteger("condition", 0);
return;
}
else
{
anim.SetInteger("condition", 1);
}
CalculateDirection();
Rotate();
if (Input.GetKeyDown(KeyCode.LeftShift))
{
isSprinting = true;
}
else
{
isSprinting = false;
}
Move();
}
void GetInput()
{
playerInput.x = Input.GetAxisRaw("Horizontal");
playerInput.y = Input.GetAxisRaw("Vertical");
}
void CalculateDirection()
{
angle = Mathf.Atan2(playerInput.x, playerInput.y); //give us radians, tangent between up and horizontal
angle = Mathf.Rad2Deg * angle; // to convert to degrees
angle += cam.eulerAngles.y;
}
void Rotate()
{
targetRotation = Quaternion.Euler(0, angle, 0); // convert euler angles to quaternions
transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, turnSpeed * Time.deltaTime);
}
void Move()
{
if(isSprinting == true)
{
velocity = sprintSpeed;
Debug.Log("debug: " + sprintSpeed + "velocity: " + velocity);
}
else
{
velocity = walkSpeed;
}
Debug.Log("debug velocity: " + velocity);
anim.SetFloat("velocity", velocity / 10);
transform.position += transform.forward * walkSpeed * Time.deltaTime;
}
}