Question by
MaxTheMinerBoy · Apr 30, 2021 at 12:28 PM ·
movementcharacter controllerrunning
Character Controller run not working
I followed a Brackeys tutorial to make fps player movement. It works fine but when I try to add an option to run then it won't let me run. Anyone know how I can fix this?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
// Movement variables
public CharacterController controller;
public float speed;
public float walkSpeed = 12f;
public float runSpeed = 20f;
// Gravity variables
Vector3 velocity;
public float gravity = -9.81f;
public Transform groundCheck;
public float groundDistance = 0.4f;
public LayerMask groundMask;
bool onGround;
public float jumpHeight = 3f;
// Every frame
void Update()
{
// Check if we are on the ground
onGround = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);
if (onGround == true && velocity.y < 0)
{
// Reset velocity
velocity.y = -2f;
}
// Get player input
float x = Input.GetAxis("Horizontal");
float z = Input.GetAxis("Vertical");
// Check if we want to run
speed = walkSpeed;
if (Input.GetKeyDown(KeyCode.LeftControl) || Input.GetKeyDown(KeyCode.LeftShift))
{
speed = runSpeed;
}
// Turn it into the movement then move the player
Vector3 move = transform.right * x + transform.forward * z;
controller.Move(move * speed * Time.deltaTime);
// Check if we want to jump
if (Input.GetButtonDown("Jump") && onGround == true)
{
velocity.y = Mathf.Sqrt(jumpHeight * -2 * gravity);
}
// Increase the players velocity and then add it to the player
velocity.y += gravity * Time.deltaTime;
controller.Move(velocity * Time.deltaTime);
}
}
Comment
Your answer
Follow this Question
Related Questions
how do I make my character jump while running without losing all your speed 1 Answer
How can I make character accelerate and deccelerate using GetAxis? 0 Answers
Have an issue with looking and moving Unity3D 1 Answer
Controller script active on both characters. 1 Answer
"Is Walking" is constantly on and I can't turn it off. Help? 0 Answers