Home > Mobile >  How to set vCam orthographic size relative to velocity?
How to set vCam orthographic size relative to velocity?

Time:04-06

I'm trying to make it so that when my player velocity increases, the virtual follow cam orthographic size increases and when the player velocity decreases, the orthographic size decreases. When I try this though, it doesn't scale smoothly, it judders really badly.

My code looks something like this...

void Update()
{
    // Take the fastest velocity (x or y)
    if((Mathf.Abs(rb.velocity.x) > Mathf.Abs(rb.velocity.y))
    {
        velocity = Mathf.Abs(rb.velocity.x)
    }
    else
    {
        velocity = Mathf.Abs(rb.velocity.y)
    }
 
    //Set orthogrpahic camera size
    if(velocity > 0)
    {
        vCam.m_Lens.OrthographicSize = Mathf.Clamp(defaultCamSize   velocity, defaultCamSize, maxCamSize);
    }
    else
    {
        vCam.m_Lens.OrthographicSize = defaultCamSize;
    }
}

CodePudding user response:

You could use Mathf.Lerp(), documentation says that

Returns float The interpolated float result between the two float values.

Description
Linearly interpolates between a and b by t.
The parameter t is clamped to the range [0, 1].
When t = 0 returns a. When t = 1 return b. When t = 0.5 returns the midpoint of a and b.

You can write somthing like following to smoothly change the orthographicSize

private void Update() 
{
    velocity = Mathf.Max(Mathf.Abs(rb.velocity.x), Mathf.Abs(rb.velocity.y));
    float lerpSpeed = .05f;
    float newSize = Mathf.Clamp(defaultCamSize   velocity, defaultCamSize, maxCamSize);
    vCam.m_Lens.OrthographicSize = Mathf.Lerp(vCam.m_Lens.OrthographicSize, 
                                   velocity > 0 ? newSize : defaultCamSize,
                                   lerpSpeed);
}

CodePudding user response:

// Take the fastest velocity (x or y)

If you did this, the velocity swung widely when the player moved sidelong, you'd better use velocity = rb.velocity.magnitude / 2f instead.

  • Related