Reputation: 1
I have followed a YouTube tutorial but the code to ground check (So the player cannot jump in the air leading to flying) is not working. The code is:
[SerializeField] private bool isCharacterGrounded = false;
private Vector3 velocity = Vector3.zero;
private void Update()
{
HandleIsGrounded();
HandleGravity();
HandleJumping();
}
private void HandleIsGrounded()
{
isCharacterGrounded = Physics.CheckSphere(transform.position, groundDistance);
}
private void HandleGravity()
{
if (isCharacterGrounded && velocity.y < 0)
{
velocity.y = -2f;
}
velocity.y += gravity * Time.deltaTime;
controller.Move(velocity * Time.deltaTime);
}
private void HandleJumping()
{
if (Input.GetKeyDown(KeyCode.Space) && isCharacterGrounded)
{
velocity.y += Mathf.Sqrt(jumpForce * -2f * gravity);
}
}
Upvotes: 0
Views: 2451
Reputation: 418
To do a ground check, either with a CheckSphere or a Raycast, you need a Layer Mask to identify what "layer" you want to check for. Otherwise your ground check will always return true because it will be hitting your player's own collider.
[SerializeField] private bool isCharacterGrounded = false;
// Assign in the inspector
public LayerMask GroundLayer;
private Vector3 velocity = Vector3.zero;
private void Update()
{
HandleIsGrounded();
HandleGravity();
HandleJumping();
}
private void HandleIsGrounded()
{
isCharacterGrounded = Physics.CheckSphere(transform.position, groundDistance, GroundLayer);
}
Next, make sure that your ground is assigned to the Ground layer in the inspector
And last, assign the Ground layer to the GroundLayer variable in the inspector
Upvotes: 1