- Home /
Question by
AlienHook · Apr 30, 2014 at 04:28 AM ·
c#lerpanimationcurve
Transition between Vector3s using AnimationCurve
How would I move an object from one location to another, smoothly along an AnimationCurve in C#? I'm not sure if I would use a Vector3.Lerp or AnimationCurve.Evaluate.
Comment
Answer by robertbu · Apr 30, 2014 at 04:59 AM
There are a few different things you can mean by 'smoothly along an AnimationCurve'. One use of an AnimationCurve is to vary the speed of movement along...for example to ease the movement at the ends. Below is a test class. Put it on a cube and adjust the AnimationCurve in the inspector. As a first test, make sure your AnimationCurve starts at 0.0 and ends at 1.0.
using UnityEngine;
using System.Collections;
public class Bug25b : MonoBehaviour {
public AnimationCurve ac;
public Vector3 pos1 = new Vector3(-4.0f, 0.0f, 0.0f);
public Vector3 pos2 = new Vector3( 4.0f, 0.0f, 0.0f);
void Update() {
if (Input.GetKeyDown (KeyCode.Space)) {
StartCoroutine(Move(pos1, pos2, ac, 3.0f));
}
}
IEnumerator Move(Vector3 pos1, Vector3 pos2, AnimationCurve ac, float time) {
float timer = 0.0f;
while (timer <= time) {
transform.position = Vector3.Lerp (pos1, pos2, ac.Evaluate(timer/time));
timer += Time.deltaTime;
yield return null;
}
}
}
Didn't know we about this neat trick. It's great to have animation curves directly into the inspector ! Thank You.
Your answer
![](https://koobas.hobune.stream/wayback/20220613143918im_/https://answers.unity.com/themes/thub/images/avi.jpg)