Lerping issues (C #)

I’m attempting to move an object from one place to another, so I used a lerp but it isn’t working.

Here’s the function i created to run the lerp and also the instantiate:

attackObj = Instantiate (attackObj,attackingCity.transform.position,Quaternion.identity) as Transform;

attackObj.transform.position = Vector3.Lerp (attackingCity.transform.position,defendingCity.transform.position, Time.deltaTime);

Debug.Log (“Success!”);

I’m running this function from update in an if statement for when I press space. It definately runs because the log works. It also does spawn the object on the attacking city, but doesn’t move it at all. Any suggestions?

When you are using attackObj = Instantiate, You are creating an instance of an object and naming it attackObj. If you are doing that in Update function, it will create an instance every frame. So it constnatly creates new transforms and names them attackObj.

When you are telling it to lerp, you are telling the attackObj to lerp but next frame the attackObj is a different object. So you are starting the lerp on one object every frame but never continuing the lerp on one object over multiple frames. If you move the instanciate into start you will see it lerp.

Moving the t parameter in Vector3.Lerp from 0 to 1 over time will cause the object to move from the start position to the end over that same length of time.

Alternatively, you can pass in the position of attackObj as the start position, then use the t parameter as a damping value. So…

attackObj.transform.position = 
                10 * Time.deltaTime);

The value 10 here can be modified to control how fast the object moves. What this does is move the object from its current position to the target position by 10 * Time.deltaTime percent of the distance. As it gets closer it will move less of a distance. Increasing the multiplier will cause the object to move a greater percentage of the distance each frame, but it will stop much faster (i.e. not as smoothly) when it arrives.