Search Unity

Ceiling Check for 2D Player

Discussion in 'Editor & General Support' started by Squiddu, Dec 5, 2021.

  1. Squiddu

    Squiddu

    Joined:
    Jan 10, 2020
    Posts:
    5
    Hello, I'm a beginner trying to make a platformer base for my game. Currently moving left/right and jumping works, however if I'm below a ground block and hit it during a jump, I'm able to jump a second time before falling down.
    How do I make sure the player square only regains their jump when the bottom of them hits the ground?
    Here's my current movement code (with only a ground check):
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class Movement : MonoBehaviour
    6. {
    7.     Rigidbody2D rb;
    8.     public float speed;
    9.     public bool isGrounded;
    10.  
    11.  
    12.     // Start is called before the first frame update
    13.     void Start()
    14.     {
    15.         rb = GetComponent<Rigidbody2D>();
    16.     }
    17.  
    18.     // Update is called once per frame
    19.     void FixedUpdate()
    20.     {
    21.         Move();
    22.     }
    23.  
    24.     void Move()
    25.     {
    26.         rb.velocity = new Vector2(Input.GetAxis("Horizontal") * speed, rb.velocity.y);
    27.  
    28.         if(Input.GetKey("space") && isGrounded)
    29.         {
    30.             rb.velocity = new Vector2(rb.velocity.x, speed);
    31.             isGrounded = false;
    32.         }
    33.     }
    34.  
    35.     void OnCollisionEnter2D(Collision2D collider)
    36.     {
    37.         if (collider.gameObject.tag == "Ground")
    38.         {
    39.             isGrounded = true;
    40.         }
    41.     }
    42. }
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,689
    I assume this is because your ceiling is actually the underside of the ground above it, and it is tagged as "Ground" ?

    If this is the case, one approach is to split the platform into two vertically-thinner colliders, one top, one bottom.

    Then you would mark the top one as "Ground" that you stand on, and then the lower one would be ceiling, such that colliding with it does not reset the isGrounded value.

    Another way is to put a separate Collider down low on your player and ONLY consider yourself grounded if that lower collider hits. You can check the collider from within the trigger service function.