Forum begins after the advertisement:


[Part 7] Save Function

Viewing 3 posts - 1 through 3 (of 3 total)
  • Author
    Posts
  • #14062
    Liêm Trần
    Participant

    Hey guys i have some issues with the save function. I have to move and press the interact button many times while stay in the save’s box collider to get it interacted. Is there anyway to improve this?.

    #14065
    Terence
    Keymaster

    That’s a great question Liêm. In the video, the code listens to input using OnTriggerStay2D(). Ideally, this should be moved to Update(), because if you listen to input in OnTriggerStay2D(), the input gets dropped if it doesn’t happen at the time frame as Update().

    For example:

        // Update is called once per frame
        void Update()
        {
            
        }
        private void OnTriggerStay2D(Collider2D _collision)
        {
            if(_collision.CompareTag("Player") && Input.GetButtonDown("Interact"))
            {
                interacted = true;
            }
        }

    The logic should be reorganised so that the input is checked in Update() instead, like this:

        bool hasSeater = false;
        // Update is called once per frame
        void Update()
        {
            if(Input.GetButtonDown("Interact") && hasSeater) interacted = true;
        }
        private void OnTriggerStay2D(Collider2D _collision)
        {
            if(_collision.CompareTag("Player") && Input.GetButtonDown("Interact"))
            {
                interacted = true;
            }
        }
    
        void OnTriggerEnter2D(Collider2D _collision)
        {
            if(_collision.CompareTag("Player")) hasSeater = true;
        }
    
        void OnTriggerExit2D(Collider2D _collision)
        {
            if(_collision.CompareTag("Player")) hasSeater = false;
        }

    This happens because basically the physics-based OnTriggerStay2D() is fixed — it always happens at the same time regardless of frame rate, and Update() will change the number of times it runs depending on frame rate (and Input only gets read on Update().

    You can read this article if you are interested in learning more: https://blog.terresquall.com/2020/08/unity-rigidbodys-interpolate-property/

    #14127
    Liêm Trần
    Participant

    Havent try this but thanks a lot

Viewing 3 posts - 1 through 3 (of 3 total)
  • You must be logged in to reply to this topic.

Go to Login Page →


Advertisement below: