Home > OS >  Why can I not jump with my tutorial First-Person Controller in Unity?
Why can I not jump with my tutorial First-Person Controller in Unity?

Time:01-09

I followed Brackey's Unity 1st person controller tutorial and am unable to jump.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerMovementScript : MonoBehaviour
{

    public CharacterController controller;

    public float speed = 12f;
    public float gravity = -9.81f;
    
   [Header("Keybinds")]
    public KeyCode jumpKey = KeyCode.Space;


    public float JumpHeight = 3f;

    public Transform groundCheck;
    public float groundDistance = 0.4f;
    public LayerMask groundMask;

    Vector3 velocity;
    bool isGrounded;

    // Update is called once per frame
    void Update()
    {

        isGrounded = Physics.Raycast(transform.position, Vector3.down, 1   0.3f, groundMask);

        if (isGrounded && velocity.y < 0)
        {
            velocity.y = -2f;
        }



        float x = Input.GetAxis("Horizontal");
        float z = Input.GetAxis("Vertical");

        Vector3 move = transform.right * x   transform.forward * z;

        controller.Move(move * speed * Time.deltaTime);



        if (Input.GetKeyDown(jumpKey) && isGrounded)
        {
            velocity.y = Mathf.Sqrt(JumpHeight * -2f * gravity);
        }


        velocity.y  = gravity * Time.deltaTime;

        controller.Move(velocity * Time.deltaTime);
    }
}

I discovered that if I remove isGrounded from the if statement for jumping, then I can jump, but infinitely. If isGrounded is in the code, then I can not jump at all.

I tried removing isGrounded from the if statement, which gave me the ability to jump, but I could jump forever without touching the ground.

I tried removing the line velocity.y = gravity * Time.deltaTime; which I wasn't able to jump there.

I tried removing isGrounded, all references to it, and things involving the ground, which lead to jumping once and then continuing to float up.

I've tried changing isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);to Physics.Raycast(transform.position, Vector3.down, 1 0.3f, groundMask); and that resulted in no change.

I double checked that the ground layer has been applied to the ground and that the GroundCheck has been linked and mask selected.

I am completely stumped as to why this is not working. Any and all help would be greatly appreciated, thanks!

CodePudding user response:

You need to assign the ground mask in the inspector!!! you need to assign everything my player is doing fine after applying the ground mask

CodePudding user response:

Check your ground if it has the ground tag/layer selected in the inspector

  • Related