Search code examples
unity-game-engineeventtriggerrigid-bodies

Unity3D: Create scripts to climb a ladder


I'm inexperienced and I'm trying to understand the mechanism for using a ladder with my character or climbing over small walls. To move I use a rigidbody not kinematic, but with AddForce. I tried to create an object to simulate a ladder to climb on. To get my character into contact with the ladder I inserted a collider trigger on the ladder and called the OnTriggerStay function. After working a bit, my character now with a bool when he's close enough, he can go up or down the ladder but I don't understand some things. First of all, the script is better to put it on the character or create one on the scale? The second thing is once you get to the top how to insert a function correctly and make my character complete the climb, making it arrive above the object where the staircase is located. Do I have to get to the top, destroy the game object and respawn at a point just above the ladder? ... what is the best way in these cases?

        private Rigidbody rb;
    public bool ladderClimb = false;
    void Start()
        {
         rb = GetComponent<Rigidbody>();
        }

     void Update()
        {
         if(ladderClimb){
    directionRot = new Vector3(0, 0, 0);  //direction of rotation
    movement = new Vector3(0, Input.GetAxisRaw("Vertical"), 0).normalized; //object movement
      rb.useGravity = false;}
       else rb.useGravity = true;
    }

        void OnTriggerStay(Collider collider){
         if(collider.gameObject.tag == "ladder"){
         if(Input.GetKeyUp(KeyCode.E)) ladderClimb = !ladderClimb;}}

    void OnTriggerExit(Collider collider){
       if(collider.gameObject.tag == "ladder") ladderClimb = false;}

Solution

  • You can add a trigger collider to the ladder and check if the player is touched to the collider then disable gravity and allow vertical movement. But in case the object detaches from the ladder the reenable the gravity and restrict the vertical movement.