Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unity wall climbing 2D

Tags:

c#

unity3d

I made little code for detect climbing (script attached to the player object):

private float PlayerColHeight;
private float PlayerColWidth;
private bool Climb = false;


void Start () {
    PlayerCol = GetComponent<CapsuleCollider2D> ();
    PlayerColHeight = PlayerCol.bounds.size.y;
    PlayerColWidth = PlayerCol.bounds.size.x;
}
private void OnCollisionStay2D(Collision2D col){
    if (!IsGrounded() && (col.gameObject.tag == "Wall")) {
        Vector2 position = transform.position;
        Vector2 wallPos = col.transform.position;
        float wallColHeight = col.gameObject.GetComponent<BoxCollider2D> ().bounds.size.y;
        if ((position.y+PlayerColHeight/2)==(wallPos.y + wallColHeight/2)){
            Climb = true;               
        }
        Debug.Log (Climb);
    }
}    

This means when player in the air and colliding with wall, i need to check if player top point Y = wall top point Y and understand that it works. But this is not works... Console returns only False.
Image:

enter image description here

Why it doesn't works? If you know another way to make climbing, can you explain how?

like image 550
Fan4i Avatar asked Mar 07 '23 14:03

Fan4i


1 Answers

I think your condition statement is wrong

    if ((position.y+PlayerColHeight/2)==(wallPos.y + wallColHeight/2)){
    Climb = true;               
}

It should be

    if ((position.y+PlayerColHeight/2) <= (wallPos.y + wallColHeight/2)){
    Climb = true;               
}

Climb was true only when both values were equal but you are interested on climbing when the player position is smaller than the wall, right?

In any case you should check your values debugging the game or just writing logs with the values position.y+PlayerColHeight/2 and wallPos.y + wallColHeight/2 to understand what's going on.

Edit: It could happen that when you are close to get out of the "climbing zone" your player gets stucked as he will get Climb = false, the ideal should be enable climbing when you are in the wall, you don't care if jumping again will leave the player above the wall, what it's more you could be interested on that for reaching the top of the wall in same situations

like image 123
Chopi Avatar answered Mar 09 '23 06:03

Chopi