I would also like to improve my sprinting function, I followed a youtube tutorial just for the movement, but I had to wing it for the sprint. I want to be able to just hold down the left shift key to sprint, but if the player accidentally hits the left shift key, the moveSpeed is just doubled and when the left shift key is pressed again, the speed is quadrupled.
I also keep getting: Look rotation viewing vector is zero. I’ve researched everything I could I cannot seem to keep it from popping up, it states that there’s an issue with the line: transform.forward += heading;
Also note, that I am creating a 3D Isometric game, so the player movement is crucial to the gameplay.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CharController : MonoBehaviour
{
public Rigidbody rb;
public bool playerIsOnTheGround = true;
[SerializeField]
float moveSpeed = 5f;
float sprintSpeed = 2f;
Vector3 forward, right;
void Start()
{
forward = Camera.main.transform.forward;
forward.y = 0;
forward = Vector3.Normalize(forward);
right = Quaternion.Euler(new Vector3(0, 90, 0)) * forward;
rb = GetComponent<Rigidbody>();
}
void Update()
{
if (Input.anyKey)
Move();
}
void Move()
{
Vector3 direction = new Vector3(Input.GetAxis("HorizontalKey"), 0, Input.GetAxis("VerticalKey"));
Vector3 rightMovement = right * moveSpeed * Time.deltaTime * Input.GetAxis("HorizontalKey");
Vector3 upMovement = forward * moveSpeed * Time.deltaTime * Input.GetAxis("VerticalKey");
Vector3 heading = Vector3.Normalize(rightMovement + upMovement);
transform.forward += heading;
transform.position += rightMovement;
transform.position += upMovement;
if (Input.GetKeyDown(KeyCode.LeftShift))
{
moveSpeed = moveSpeed * sprintSpeed;
}
if (Input.GetKeyUp(KeyCode.LeftShift))
{
moveSpeed = 5f;
}
if (Input.GetButtonDown("Jump") && playerIsOnTheGround)
{
rb.AddForce(new Vector3(0, 5, 0), ForceMode.Impulse);
playerIsOnTheGround = false;
}
}
private void OnCollisionEnter(Collision collision)
{
if(collision.gameObject.tag == "Ground")
{
playerIsOnTheGround = true;
}
}
}