Skip to main content

How to Draw Cars Like a Pro TUTORIAL

I come across this sort of matter far too often:

          transform.position = Vector3.Lerp(startPos, endPos, Time.deltaTime);                  

The person posting it is usually convinced that Vector3.Lerp is "cleaved", but the real trouble is that they're not using it correctly.

Lerp, brusque for "linear interpolation" does one very simple thing: given two values, x and y, it returns a value that is t percentage between them. If y'all look the output to change, the arguments you lot pass in need to reflect that!

In the example higher up, information technology doesn't brand sense to but pass in Time.deltaTime, because that'southward only the time that passed during the about recent frame. If your game is running at a constant 50fps, that's always going to be 0.02.

Nosotros'll get better results if we let that timer accumulate over multiple frames.

Something like this should get the betoken across:

          public form LerpExample : MonoBehaviour {         float lerpTime = 1f;         float currentLerpTime;          float moveDistance = 10f;          Vector3 startPos;         Vector3 endPos;          protected void Offset() {             startPos = transform.position;             endPos = transform.position + transform.upwardly * moveDistance;         }          protected void Update() {             //reset when we press spacebar             if (Input.GetKeyDown(KeyCode.Space)) {                 currentLerpTime = 0f;             }              //increase timer once per frame             currentLerpTime += Time.deltaTime;             if (currentLerpTime > lerpTime) {                 currentLerpTime = lerpTime;             }              //lerp!             bladder perc = currentLerpTime / lerpTime;             transform.position = Vector3.Lerp(startPos, endPos, perc);         }     }        

You could create an empty scene, drop in a cube, attach this script, and see it in activeness.

The variable perc is used where Time.deltaTime used to exist. What is perc? It's a number betwixt 0 and i, representing our progress through the Lerp.

If you're curious, check the result if y'all change lerpTime or moveDistance.

Lerp everything

Unity provides helper functions for interpolating many different values.

  • Mathf.Lerp
  • Vector3.Lerp
  • Color.Lerp

At the finish of the twenty-four hour period, though, Mathf.Lerp is all you demand; the others are just convenience methods on top of that. It's easy enough to write your own Lerp function for any class or data you might need to interpolate.

In the specific example of quaternions, which Unity uses to represent rotation, there'south fifty-fifty a Slerp or "Spherical Lerp".

Any time you have two values, and you'd like to smoothly transition between them? Interpolation is your friend!

Beyond Lerp

What if we passed Lerp a t that wasn't but a straight percentage? What if, instead of a straight line graphed between two points, nosotros wanted some sort of curve? Our input must remain between 0 and one, but there are many functions that accomplish that.

For example, nosotros could "ease out" with sinerp:

          float t = currentLerpTime / lerpTime; t = Mathf.Sin(t * Mathf.PI * 0.5f);                  

interp-sinerp

Or we could "ease in" with coserp:

          t = 1f - Mathf.Cos(t * Mathf.PI * 0.5f)                  

interp-coserp

We could even create exponential movement:

          t = t*t                  

interp-quad

Multiplying t by itself has an interesting quirk: and so long as t is between 0 and i, multiplying t by itself any number of times volition always produce a number that is also between 0 and one.

Smoothstep

The multiplication property mentioned higher up is the cadre concept backside some interpolation methods which ease in and ease out, such equally the famous "smoothstep" formula:

          t = t*t * (3f - 2f*t)                  

interp-smooth

Or my personal favorite, "smootherstep":

          t = t*t*t * (t * (6f*t - 15f) + 10f)                  

interp-smoother

So smooth! (Couldn't resist.)

Many of these extra formulas I've mentioned aren't included with Unity, but that just gives you the liberty to utilise whatsoever function you tin notice or create.

Brand information technology breathe

What about a Lerp that never ends?

Robert Yang in one case said, "Sometimes I wish I could animate every single thing in my game with a sine wave."

Some games introduce a slight "head bob" while the player is running. Other games need a gentle bob for the primary menu camera. I've seen lights that "snore", fading in and out. Whatever the case, I just want to point out how fantastically useful moving ridge functions tin can be — their input domain is space, so they never have to end, and their output range is both narrow and constant, so they're easy to control.

For example, this script makes an object slowly move upward and down, according to a sine moving ridge:

          public class BreatheSimple : MonoBehaviour {         Vector3 startPos;          protected void Start() {             startPos = transform.position;         }          protected void Update() {             bladder distance = Mathf.Sin(Time.timeSinceLevelLoad);             transform.position = startPos + Vector3.upwards * distance;         }     }        

Adjusting the sine wave gives us more command:

          public class Breathe : MonoBehaviour {         Vector3 startPos;          public float aamplitude = 10f;         public float period = 5f;          protected void Start() {             startPos = transform.position;         }          protected void Update() {             float theta = Fourth dimension.timeSinceLevelLoad / flow;             bladder distance = amplitude * Mathf.Sin(theta);             transform.position = startPos + Vector3.up * distance;         }     }        

Amplitude controls how far the object moves; catamenia controls how quickly it does so.

interp-sineparams

A player's head bob might call for modest amplitude and a short menstruation. A menu camera's tiresome breathing might phone call for an extremely long period, or motion on multiple axes at varying rates.

Every bit long as you tin can sort out the math, you lot can get whatsoever behavior you want.

What happens if y'all take merely the accented value of the sine wave? Upward-only bouncing.

What happens in you clench the sine wave'due south output between 0 and i? Upwards-simply bouncing with a pause between bounces. Can y'all see why? Draw the clamped bend yourself and it should go clear.

What if you lot clamped that wave's output between 0.6 and one? Would yous get a sort of "throb" motion? Could that exist useful to scale an alert in your UI?

If you want to get actually fancy, you could even use an animation bend to manage your Lerp params.

I've written some pretty esoteric bend and wave functions. Don't be afraid to mix it up.

In closing

Lerp is an like shooting fish in a barrel and powerful function with many applications.

One of the first plugins I ever wrote was a camera director that interpolates between various zooms and positions. I've likewise used interpolation to manage material parameters, UI animation, physical forces, audio volume, simple cutscenes, and more.

This is 1 of those hammers that turns upwards more and more than oft, once you lot know how to apply it.

If yous don't want to write a lot of code, or want a head start, plugins like iTween, GoKit, or Hotween add lots of extra interpolation back up to Unity.

DOWNLOAD HERE

How to Draw Cars Like a Pro TUTORIAL

Posted by: joeofteeking.blogspot.com

Comments