Moving an object to another position on click

I have some game objects that start in a certain position and are immobile. Upon clicking these objects I would like them to be moved from their current position to a set position and then act as their behavior dictates (move around, jump, etc). I know I can use lerp to accomplish going from the start position to then end position smoothly but I get stuck there (object keeps going back to this position whenever it tries to move away)

private bool started;

private Vector3 startPoint;

private Vector3 endPoint;

private float startTime;

void Start() {

     startPoint = transform.position;
     endPoint = new Vector3(15.0f, 3.0f, 0.0f);
     startTime = Time.time;
     started = false;

}

void Update() {

     if(started) {
       Vector3 endPoint = new Vector3(beginX, beginY, 0);
       transform.position = endPoint;
       transform.position = Vector3.Lerp(startPoint, endPoint, (Time.time - startTime));
     }
}

void OnMouseUp() {

     if(!started) {
       RaycastHit hitInfo1;
       Ray r1 = Camera.main.ScreenPointToRay(Input.mousePosition);
     if(Physics.Raycast(r1, out hitInfo1)) {
       if(hitInfo1.collider == GetComponent<BoxCollider>().collider) {
         started = true;
       }
     }
}

Thanks in advance

Firstly, if you want to move an object to another position with Vector3.Lerp, just use Time.deltaTime (and multiply it with a float to make it faster or slower, see here).

Secondly, you should only put the following in your if-statement

transform.position = Vector3.Lerp(startPoint, endPoint, (Time.deltaTime));

Thirdly, you should set start and end points only once (and not continuously within the Update function).

Put something like this in your OnMouseUp function:

startPoint = transform.position;
endPoint = new Vector3(beginX, beginY, 0);

Lastly, once your object reaches its destination, you might consider setting started to false again.

In your current script you basically told your object to flip back and forth because you always set the object’s position directly while concurrently using the Lerp. I can’t test any of the code right now, but give it a shot.

function OnMouseDown () {
var screenSpace = Camera.main.WorldToScreenPoint(transform.position);
var offset = transform.position - Camera.main.ScreenToWorldPoint(Vector3(Input.mousePosition.x, Input.mousePosition.y, screenSpace.z));
while (Input.GetMouseButton(0))
{
var curScreenSpace = Vector3(Input.mousePosition.x, Input.mousePosition.y, screenSpace.z);
var curPosition = Camera.main.ScreenToWorldPoint(curScreenSpace) + offset;
transform.position = curPosition;
yield;
}
}