General programming question C# Unity

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!

for lerp you need to calculate the alpha. when you use MovePosition you just use the speed as last parameter, so that's easier. furthermore, just change the target position on press and just run MovePosition in Update. if target is the same position at the beginning as the object's, it won't move. as soon as target changes, it moves there. this makes it easy to just set different target positions.

–

1 Answer

1

@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.

  1. Make a thread to move object.
  2. Make Two points to move from one
    point to other.
  3. 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;
             }
         }
     }