**
# It took two days to realize the ladder's function, and there were few references on the Internet; / / Maybe because it was too low-end, the big guys didn't send it, Xiaobai's pain.
**
## It took two days to figure out how to do it.
First, let's talk about the design idea: change the ladder collision mode to trigger, turn off the gravity simulation of the protagonist when the protagonist enters it, so that only the direction key controls the protagonist's upper and lower displacement; / / Remember to restore him when he leaves.
**
using System.Collections; using System.Collections.Generic; using UnityEngine; public class LadderClimb : MonoBehaviour { public float climbSpeed = 0.02f; //Speed of climbing ladders public Collider2D jiaoca; //Object rigid body private void OnTriggerStay2D(Collider2D collision) //When entering the ladder { if (collision.gameObject .tag == "Player") //Enter the label of the ladder protagonist!!! { if(Input .GetKey (KeyCode.UpArrow)) //Judgement key { collision.gameObject.GetComponent<Rigidbody2D>().velocity = new Vector2(0, climbSpeed); //The protagonist gives a force in the Y-axis direction after touching the ladder. collision.gameObject.GetComponent<Rigidbody2D>().gravityScale = 0; //Gravity returns to zero after the protagonist touches the ladder Physics2D.IgnoreCollision(collision.GetComponent<Collider2D>(), jiaoca, true); //Ladder contact floor and protagonist collision closure } if (Input.GetKey(KeyCode.DownArrow)) { collision.gameObject.GetComponent<Rigidbody2D>().velocity = new Vector2(0, -climbSpeed); collision.gameObject.GetComponent<Rigidbody2D>().gravityScale = 0; Physics2D.IgnoreCollision(collision.GetComponent<Collider2D>(), jiaoca,true); } else { collision.gameObject.GetComponent<Rigidbody2D>().velocity = new Vector2(0,0); } } } private void OnTriggerExit2D(Collider2D collision) //When leaving the ladder { collision.gameObject.GetComponent<Rigidbody2D>().gravityScale = 1; //// Ladder contact floor and protagonist collision closure Physics2D.IgnoreCollision(collision.GetComponent<Collider2D>(), jiaoca, false );//Ladder contact floor and protagonist collision opening } }
[Insert picture description here]( https://img-blog.csdnimg.cn/20190410163822793.png
Drag the code into the ladder, and then drag the code into the ladder.
Contact ground
Pull it into the public box ** so that the ladder can be set up.