Hello everyone! I had a question that i kept asking myself and could never figure a proper way to do this.
What i want to happen is something like this.
-User presses key once
– An object moves from one spot to another using Vector3.Lerp
Vector3.Lerp requires it to be repeated either in the update method or some other way.
I was wondering what the most efficient way i could make this happen with just one button press
and not have to hold down the button.
Thanks in advance to everyone! Happy developing!
@username
if you don’t want to move in update or not want to press the button to move,then there is a simple way of moving object.
- Make a thread to move object.
- Make Two points to move from one
point to other.
- Time For moving object to
destination.
class MyClass: MonoBehaviour
{
[SerializeField]private Vector3 _pointBVector3;
private void Start()
{
var pointAVector3 = this.transform.position;
StartCoroutine(MoveObject(this.transform,pointAVector3,_pointBVector3,Random.Range(2f,5f)));
}
/// <summary>
/// MoveObject
/// </summary>
/// <param name="_transform">Pass transform Which You Want To Move</param>
/// <param name="initialPos">Start Position Of Move Object</param>
/// <param name="endPos">PointB </param>
/// <param name="time">Random Time Like Random.Range(2f,5f)</param>
/// <returns></returns>
private IEnumerator MoveObject(Transform _transform,Vector3 initialPos,Vector3 endPos,float time)
{
var i = 0.0f;
float rate = 1.0f / time;
while (i < 1.0f)
{
i += Time.deltaTime * rate;
_transform.position = Vector3.Lerp(a: initialPos, b: endPos, t: i);
yield return null;
}
}
}