Moving an object slowly from on point to another

Hello

I want to move an object slowly from one point to another point when a button is pressed. In this case i use the right mouse button, but that dosen’t matter at this point.

I use this code:
using UnityEngine;
using System.Collections;

public class MoveFromTo : MonoBehaviour {
	
		//public Transform startMarker;
		public Transform endMarker;
		public float speed = 1.0F;
		private float startTime;
		private float journeyLength;
		
	void Start() {
	
	}


	void Update() {

		if (Input.GetMouseButtonDown(1))
		{
			startTime = Time.time;
			journeyLength = Vector3.Distance(this.transform.position, endMarker.position);
		}

		float distCovered = (Time.time - startTime) * speed;
		float fracJourney = distCovered / journeyLength;
		transform.position = Vector3.Lerp(this.transform.position, endMarker.position, fracJourney);
		
	}

}

But i get this error:

transform.position assign attempt for
‘Sphere’ is not valid. Input position
is { NaN, NaN, NaN }.

and the objet is at the endposition right at the first frame. why does that happens?

Regards from Germany
Asta

Hello,
Asta!

In the 1st frame fracJorney == Infinity, because journeyLength == 0. So you get an error.

You should restrict the running of next lines:

         float distCovered = (Time.time - startTime) * speed;
         float fracJourney = distCovered / journeyLength;
         transform.position = Vector3.Lerp(this.transform.position, endMarker.position, fracJourney);

before mouse click was detect.

I think that you code (with fast-fixing of this problem) can look like this:

public class MoveFromTo : MonoBehaviour {
     
         //public Transform startMarker;
         public Transform endMarker;
         public float speed = 1.0F;
         private float startTime;
         private float journeyLength;
         private bool _needMove = false;

     void Start() 
     {
     
     }
 
 
     void Update() 
     {
 
         if (Input.GetMouseButtonDown(1))
         {
             startTime = Time.time;
             journeyLength = Vector3.Distance(this.transform.position, endMarker.position);
             _needMove = true;
         }

         if (!_needMove) return;
         
         float distCovered = (Time.time - startTime) * speed;
         float fracJourney = distCovered / journeyLength;
         transform.position = Vector3.Lerp(this.transform.position, endMarker.position, fracJourney);
         
     }
 
 }