Search Unity

my character keeps jumping infinitely, i want it to be a single jump, please can anyone help

Discussion in 'Scripting' started by PhatCatDev11, Jul 25, 2021.

  1. PhatCatDev11

    PhatCatDev11

    Joined:
    Apr 10, 2021
    Posts:
    16
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class PlayerCtrl : MonoBehaviour
    6. {
    7.     public bool canjump = false;
    8.     public Animator animtor;
    9.     public float waittime = 0.5f;
    10.     private float jumpvel = 10;
    11. public int MovementSpeed;
    12. public Rigidbody2D rb;
    13. float mx;
    14.  
    15. private void Update()
    16. {
    17.      if (Input.GetKeyDown(KeyCode.P))
    18.      {
    19.  
    20.      }
    21.      if (Input.GetKeyDown(KeyCode.Space))
    22.      {
    23.          if (canjump == true)
    24.          {
    25.          animtor.SetBool("IsSpacePressed", true);
    26.          rb.velocity = Vector2.up * jumpvel;
    27.          }
    28.      }
    29.      mx = Input.GetAxisRaw("Horizontal");
    30. }
    31. private void FixedUpdate()
    32. {
    33.      Vector2 movement = new Vector2(mx * MovementSpeed, rb.velocity.y);
    34.  
    35.      rb.velocity = movement;
    36. }
    37. private void OnTriggerEnter2D(Collider2D col)
    38. {
    39. if (col.gameObject.CompareTag("Map"))
    40. {
    41.     if (rb.velocity.y < 0)
    42.     {
    43. canjump = true;
    44.     animtor.SetBool("IsSpacePressed", false);
    45.     }
    46.     else
    47.     {
    48.         canjump = false;
    49.     }
    50. }
    51. }
    52. }
    53.  
     
  2. gorbit99

    gorbit99

    Joined:
    Jul 14, 2015
    Posts:
    1,350
    You don't set the bool to false, also, this is not the best idea, as you can hit a wall and be able to jump and it's god awful to test if the player ran off the edge without jumping.
    Instead I'd suggest creating a small trigger at the foot of the player and have that check if it's being collided with the ground.