How can I move by the distance of a Vector3 variable rather than position? Vector3.Lerp only takes Vector3 positions and I don’t know of any way to lerp by distance.
I see there is a Vector3.Distance but it only returns a float, and you can’t lerp by a float alone, unless I’m misunderstanding the purpose of Vector3.Distance.
What I’m trying to do is if someone enters 0,0,-2 in the inspector, they move a distance of -2 on the Z, not to position -2 on z in world or local space.
Is there a simple way to lerp by distance taking x,y,z inputs from the inspector?
I wrote an example that I hope will help you out. If you attach it to a GameObject and enter some values in the inspector fields you should be able to see how it works.
using UnityEngine;
using System.Collections;
public class MoveTest : MonoBehaviour
{
// How much to move this object.
public Vector3 moveBy;
// How long the movement should take, in seconds.
public float transitionTime;
private Vector3 targetPosition;
private Vector3 startPosition;
private float moveTime;
void Start()
{
// Record our starting position so that we can
// lerp to the target position smoothly.
startPosition = transform.position;
// Add how much we want to move by to the start position.
// This is where we want to end up.
targetPosition = startPosition + moveBy;
// This tracks how long we've been moving for, in seconds.
moveTime = 0.0f;
}
void Update()
{
// Check if we're close enough to the target.
// Replace Mathf.Epsilon with something else if you want to have a different
// closeness threshold.
if (Vector3.Distance(targetPosition, transform.position) > Mathf.Epsilon)
{
moveTime += Time.deltaTime;
// Lerp from start to target position.
// Note that "moveTime / transitionTime" will equal 1 when we reach the target, which
// is exactly what we want.
transform.position = Vector3.Lerp(startPosition, targetPosition, moveTime / transitionTime);
}
}
}
Typically, ‘Distance’ with vectors is used to mean ‘length’, which is a scalar value, rather than a vector value, as you’re seeing. What you want is the difference between two vectors: (vectorA - vectorB). You can throw a Mathf.Abs() around it if you don’t care about direction of the resulting vector, otherwise (vectorA - vectorB) and (vectorB - vectorA) will result in equal vectors pointing in opposite directions.
Lerp is just is a shortcut for the equation to move between, as you note, two positions. To go 20% from A to B, the math is: A+(B-A)*0.2. That’s all Lerp is. Note how (B-A) is the distance you have to go. Since you already have that distance, may as well use it: