Search Unity

  1. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Question I created this code based on a video and I don t know why the player cannot always jump

Discussion in 'Physics' started by bettercallmedad, Nov 29, 2020.

  1. bettercallmedad

    bettercallmedad

    Joined:
    Nov 29, 2020
    Posts:
    3
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class playermouvement : MonoBehaviour
    6. {
    7.       public CharacterController controller;
    8.     //gravity
    9.       public float speed = 12f;
    10.       public float  gravity = -9.81f;
    11.       public float  JumpHeight = 3f;
    12.      //ground check
    13.       public Transform groundCheck;
    14.       public float groundDisdance = 0.4f;
    15.       public LayerMask groundMask;
    16.    
    17.       Vector3 velocity;
    18.       bool isGrounded;
    19.  
    20.     // Update is called once per frame
    21.     void Update()
    22.     {
    23.     isGrounded = Physics.CheckSphere(groundCheck.position, groundDisdance, groundMask);
    24.  
    25.          if(isGrounded && velocity.y < 0)
    26.         {
    27.              velocity.y = -2f;
    28.         }    
    29.  
    30.       float x = Input.GetAxis("Horizontal");
    31.       float z = Input.GetAxis("Vertical");
    32.       Vector3 move = transform.right * x + transform.forward * z;
    33.       controller.Move(move * speed * Time.deltaTime);
    34.    
    35.       if(Input.GetButtonDown("Jump")&& isGrounded)
    36.       {
    37.           velocity.y = Mathf.Sqrt(JumpHeight * -2f * gravity);
    38.       }  
    39.        velocity.y += gravity * Time.deltaTime;
    40.        controller.Move(velocity * Time.deltaTime);
    41.  
    42.     }
    43. }
    44.  
     
  2. AlTheSlacker

    AlTheSlacker

    Joined:
    Jun 12, 2017
    Posts:
    326
    Put some debug lines in your code and see what is happening, e.g.

    Debug.Log("Just before check, velocity: " + velocity.y + " isGrounded: " + isGrounded);

    I would guess you have some noise in velocity.y that is preventing it firing or that your ground check distance is too small, but you don't give much information. Use the debug lines to understand what your code is doing.

    If you want better help here, generate a simple reproducer of your problem with a 1x1x1 cube on a flat surface, or whatever type of surface you need (you don't say) to cause the problem. Give a good description of when the problem occurs and what you have tried already.
     
    Last edited: Nov 30, 2020
  3. bettercallmedad

    bettercallmedad

    Joined:
    Nov 29, 2020
    Posts:
    3
    thanks I actually resolved the problem