Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

My character can jump even if it is already in the air(it should not)

Discussion in 'Physics' started by LRodini, Aug 26, 2020.

  1. LRodini

    LRodini

    Joined:
    Aug 11, 2020
    Posts:
    6
    Hey! I'm making a small game, and I just made a character movement code, but he can jump even while already in the air (in the middle of a previous jump, for example), and I know why he can do that, which is because my jump code doesn't care wherever my char is, before it jumps, but i also have no idea how to fix it, considering that the terrain has no fixed Y coordinate (in that case it would be just making a condition that checks if the player is in the ground), here's the code, help me
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class Controlplayer : MonoBehaviour
    6. {
    7.  
    8.     [SerializeField]
    9.     float Speed;
    10.     [SerializeField]
    11.     float jumpspeed;
    12.     [SerializeField]
    13.     Rigidbody rb;
    14.     void Start()
    15.     {
    16.         rb = GetComponent<Rigidbody>();
    17.     }
    18.     void Update()
    19.     {
    20.         PlayerMovement();
    21.         if (Input.GetKeyDown("x"))
    22.         {
    23.             rb.AddForce(0, jumpspeed, 0, ForceMode.Impulse);
    24.         }
    25.     }
    26.     void PlayerMovement()
    27.     {
    28.         float hor = Input.GetAxis("Horizontal");
    29.         float ver = Input.GetAxis("Vertical");
    30.         Vector3 playerMov = new Vector3(hor, 0f, ver) * Speed * Time.deltaTime;
    31.         transform.Translate(playerMov, Space.Self);
    32.    
    33.     }
    34. }
    35.  
     
  2. alexeu

    alexeu

    Joined:
    Jan 24, 2016
    Posts:
    257