Character controller only checks if grounded when moving.
I'm following brackey's tutorial on player movement and since the ground check he made wasn't working for me I followed some person In the comments advice to use the character controller ground check. It worked when trying to stop velocity accumulation but when I tried to add a jump feature it wasn't working, or only working when moving. I wrote some code to print whenever I'm grounded, whenever I jump and whenever I do both. From what I see it only checks for grounded when moving despite it being in void Update which should check every frame. Sorry if anything is unclear, I'm completely new to game developing and don't have a clue what I'm doing.
A lot of people come here from Brackey's tutorials XD. I'm actually helping another person on the same tutorial. Here is the code Brackey uses:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player$$anonymous$$ovement : $$anonymous$$onoBehaviour
{
public CharacterController controller;
public float speed = 12f;
public float gravity = -9.81f;
public float jumpHeight = 3f;
public Transform groundCheck;
public float groundDistance = 0.01f;
public Layer$$anonymous$$ask ground$$anonymous$$ask;
Vector3 velocity;
bool isGrounded;
// Update is called once per frame
void Update()
{
isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, ground$$anonymous$$ask);
if(isGrounded && velocity.y < 0)
{
velocity.y = -6f;
}
float x = Input.GetAxis("Horizontal");
float z = Input.GetAxis("Vertical");
Vector3 move = transform.right * x + transform.forward * z;
controller.$$anonymous$$ove(move * speed * Time.deltaTime);
if(Input.GetButtonDown("Jump") && isGrounded)
{
velocity.y = $$anonymous$$athf.Sqrt(jumpHeight * -2f * gravity);
}
velocity.y += gravity * Time.deltaTime;
controller.$$anonymous$$ove(velocity * Time.deltaTime);
}
}
Thanks! I actually made some Frankenstein code to fix my problem but the help is appreciated.