简体   繁体   中英

Unity Tag and Collider problem while player is jumping

This is my player's jump code:

void Update()
{
    float oldmoveHorizontal = moveHorizontal;
    moveHorizontal = Joystick.Horizontal;
    moveVertical = Joystick.Vertical;    

    if (isJumping == false && moveVertical >= .7f)
    {
        moveVertical = Speed * 70;
        isJumping = true;
    }

    ball_move = new Vector2(moveHorizontal, moveVertical);         
    ball_rigid.AddForce(ball_move);

    void OnCollisionEnter2D(Collision2D col)
    {
        if (col.gameObject.tag == "Ground")
         {
             isJumping = false;
         }        
    }
}

When ball touches under of the collider it can jump again. How can i block this situation ? 这是图像

if you cant download: https://ibb.co/yVgXmrM

One solution is to check the position of the collision points of the collision and see any of them is "low enough" from the center of your player to be a jumpable collision:

private Collider2D playerCollider; 
private float playerJumpableOffset = 0.001;

void Start() { playerCollider = GetComponent<Collider2D>(); }

void OnCollisionEnter2D(Collision2D col)
{
    float jumpableWorldHeight = transform.position.y - playerJumpableOffset;

    for (int i = 0 ; i < col.contactCount && isJumping; i++)  
    {
        Vector2 contactPoint = col.GetContact(i).point; 
        if (contactPoint.y <= jumpableWorldHeight) 
        {
            isJumping = false;
        }
    }
}
void OnCollisionEnter2D(Collision2D col)
{
    if (col.gameObject.tag == "Ground")
    {
        foreach (ContactPoint2D item in col.contacts)
        {
            Debug.Log("Normal:" + item.normal);
            if (item.normal.y > 0 && col.gameObject.tag == "Ground")
            {
                isJumping = false;
                Debug.Log("Top of Collider");
            }
        }
    }}

I found my solution with checking top side of collider. With this code way, if player touchs top side of collider , it's going to activate jump again.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM