Mover
A script is now attached to your cube.
MoveCurve
Your class should look like this:
using UnityEngine;
public class Mover : MonoBehaviour
{
public AnimationCurve MoveCurve;
private void Start()
{
}
private void Update()
{
}
}
The Curve editor opens
using UnityEngine;
public class Mover : MonoBehaviour
{
public AnimationCurve MoveCurve;
private Vector3 _target;
private Vector3 _startPoint;
private float _animationTimePosition;
private void Start()
{
UpdatePath();
}
private void Update()
{
if (_target != transform.position)
{
_animationTimePosition += Time.deltaTime;
transform.position = Vector3.Lerp(_startPoint, _target, MoveCurve.Evaluate(_animationTimePosition));
}
else
{
UpdatePath();
_animationTimePosition = 0;
}
}
private void UpdatePath()
{
_startPoint = transform.position;
_target = Random.insideUnitSphere;
}
}
The Update method checks if the cube is at the target position. If it is not, the position will be calculated by the Lerp function.
The Lerp function takes a starting and target vector and a position between 0 and 1. The next graph shows a Vector2 Lerp function.
In the script above the Lerp position _animationTimePosition
starts at zero and is updated on each frame. When the cube is at its target position _animationTimePosition
is reset to zero and a random new target position is being calculated.