Home > Software engineering >  Problems with OnCollisionEnter2D & OnCollisionExit2D
Problems with OnCollisionEnter2D & OnCollisionExit2D

Time:11-18

I'm trying to make the Player not jump continuously so I use isOnGrounded variable to check if the player is on the ground or not. Here is my code:

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

public class PlayerController : MonoBehaviour
{
    //REFERENCES
    private Rigidbody2D rb2D;
    //VARIABLES
    [SerializeField] float moveSpeed = 0;
    private float moveX;

    [SerializeField] bool isOnGrounded = true;
    [SerializeField] float jumpY;
    // Start is called before the first frame update
    void Start()
    {
        rb2D = GetComponent<Rigidbody2D>();
    }
    // Update is called once per frame
    void Update()
    {
        moveX = Input.GetAxis("Horizontal");
        PlayerJump();
    }
    private void FixedUpdate()
    {
        PlayerMove();

    }
    void PlayerMove()
    {
        rb2D.velocity = new Vector2(moveX * moveSpeed * Time.fixedDeltaTime, rb2D.velocity.y);

    }
    void PlayerJump()
    {
        if (Input.GetKeyDown(KeyCode.Space) && isOnGrounded == true)
        {
            rb2D.AddForce(new Vector2(rb2D.velocity.x, jumpY));
        }
    }
    private void OnCollisionEnter2D(Collision2D other)
    {
        if (other.gameObject.CompareTag("Ground"))
        {
            isOnGrounded = true;
        }
    }
    private void OnCollisionExit2D(Collision2D other)
    {
        if (other.gameObject.CompareTag("Ground"))
        {
            isOnGrounded = false;
        }
    }
}

enter image description here The problem is when the Player is standing on Platform01 so obviously isOnGrounded = true and when the Player moves out of Platform01 isOnGrounded = false, I suppose when move in Platform02 it will automatically check the Ground and isOnGrounded = true but it still false and everything just messing up.

CodePudding user response:

This is because OnCollisionEnter2D(Platform02) is triggered before OnCollisionExit2D(Platform01).

You can remember the last hit collider and compare with it when leave a platform.

public class PlayerController : MonoBehaviour
{
    private Collision2D ground;
    public bool IsGround => (bool)ground;

    private void OnCollisionEnter2D(Collision2D other)
    {
        if (other.gameObject.CompareTag("Ground"))
        {
            ground = other;
        }
    }
    private void OnCollisionExit2D(Collision2D other)
    {
        if (other.gameObject.CompareTag("Ground") && other == ground)
        {
            ground = null;
        }
    }
}
  • Related