Search code examples
c#unity-game-enginelerp

Unity c#: Lerp causes positions to go crazy


I'm making a gunBob function in unity and I have a function called resetBob() that lerps the current position of the gun to the 0 position on the X and Y scale but not the Z, in order to not clash with another function. This is called in the main gunBob() functions as the first thing it does. However, whenever it lerps, the X and Y values doesn't go the 0 but it instead something like -9.584906e-06 and 2.820429e-06 respectively. The code can be seen below.

void gunBob()
    {
        resetBob();

        if (Input.GetAxisRaw("Horizontal") + Input.GetAxisRaw("Vertical") != 0)
        {
            float swayMultiplier = frequencyMultiplier();

            gunBobPos.x += Mathf.Cos(Time.time * (settings.frequency/2 * swayMultiplier)) * settings.amplitude/2;
            gunBobPos.y += Mathf.Sin(Time.time * (settings.frequency * swayMultiplier)) * settings.amplitude/2;
            gunBobPos.z = transform.localPosition.z;

            transform.localPosition = gunBobPos;
        }
    }

    void resetBob()
    {
        if (transform.localPosition != Vector3.zero)
        {
            transform.localPosition = Vector3.Lerp(transform.localPosition, new Vector3(0, 0, transform.localPosition.z), Time.deltaTime * 3f);
            gunBobPos = Vector3.zero;
        }
    }

I have no idea what causes this and have tried other methods like lerping to a value that stores the localPosition at a variable called at the start of the script but it all gives the exact same issue.


Solution

  • It depends on what you want to achieve as the result.

    In my mind, it seems that you do not understand how lerp works. Lerp(a, b, t) interpolates the value between a and b depending on the t value. the result will be a in case of t == 0 and b in case of t == 1.

    In your code, I see that you always use Time.deltaTime * 3 as t. In the case of 60 fps it will always be around 0.1666 * 3. So it will never be 1 and your object will never reach your b value ((0, 0, transform.localPosition.z) in your case). That's why you are getting those numbers.