- Home /
Lerp between two Vectors
I'm testing some 3D transformations, and while I can change transform.position to instantly change location of a game object I can't seem to get the slower Lerp method to work.
using UnityEngine;
using System.Collections;
public class MoveTest : MonoBehaviour {
Vector3 start;
Vector3 des;
void Start () {
start = new Vector3(transform.position.x, transform.position.y, transform.position.z);
des = new Vector3(transform.position.x, 10.0F, transform.position.z);
}
void Update(){
transform.position = Vector3.Lerp(start, des, 1.10F * Time.deltaTime);
}
I'm a little embarrassed for asking such a simply question.
We would need something more than 'I can't seem to get the slower Lerp method to work'.
What is the issue that you are facing with your lerp method?
basically the game objects don't move at all. I was expecting them to slowly move to the destination.
Answer by MikeNewall · Jun 19, 2014 at 03:01 PM
The lerp method gives you a point that is a fraction of the way along a line between the start and end point. The fraction is supplied as the third parameter. If the fraction is 0 then the position is at the start of the line between the twho points, and a fraction of 1 would be at the end of the line. In your case it's always the same so the position never changes. You need to increase the fraction over time.
public float speed = .5f;
private Vector3 start;
private Vector3 des;
private float fraction = 0;
void Start () {
start = new Vector3(transform.position.x, transform.position.y, transform.position.z);
des = new Vector3(transform.position.x, 10f, transform.position.z);
}
void Update(){
if (fraction < 1) {
fraction += Time.deltaTime * speed;
transform.position = Vector3.Lerp(start, des, fraction);
}
}
Thank you. The answer and the explanation was what I was looking for.
Answer by robertbu · Jun 19, 2014 at 03:23 PM
@MikeNewall's solution is the traditional way to use Lerp(). Here is a common non-traditional use of Lerp() that produces an eased movement:
Vector3 des;
void Start () {
des = new Vector3(transform.position.x, 10.0F, transform.position.z);
}
void Update() {
transform.position = Vector3.Lerp(transform.position, des, speed * Time.deltaTime);
}
And here is a movement by speed that does not use a timer:
Vector3 des;
void Start () {
des = new Vector3(transform.position.x, 10.0F, transform.position.z);
}
void Update() {
transform.position = Vector3.MoveTowards(transform.position, des, speed * Time.deltaTime);
}
Your answer
Follow this Question
Related Questions
How to move an object from point A to point B with one key press 3 Answers
Grid Movement - Lerp that ends with precise values 6 Answers
Lerping textures 3 Answers
Animate buttons on click. 2 Answers
Move Transform to Target in X seconds 3 Answers