2

Actually i new in unity trying to learn Linear Translation smoothly.I use two cubes and trying to translate linear smoothly each other.

public class LinearTrasnformation : MonoBehaviour {

    public GameObject cube1, cube2;

    // Use this for initialization
    void Start () {
        //cube1.transform.position = new Vector3 (cube1.transform.position.x,cube1.transform.position.y,cube1.transform.position.z);
    }

    // Update is called once per frame
    void Update () { 
        if(Input.GetKey(KeyCode.UpArrow)){
            cube1.transform.position = Vector3.Lerp (cube2.transform.position,cube1.transform.position,0.5f*Time.deltaTime);
        }
    }
}
derHugo
  • 83,094
  • 9
  • 75
  • 115
Mohit Gandhi
  • 175
  • 1
  • 1
  • 6

1 Answers1

2

The last component of the Lerp can be thought of as the fraction of completion of the lerp (from 0 to 1). You will also need to store the original position of cube 1, otherwise the lerp will continously be updated using the new position of the cube. You should instead do...

float t = 0;
Vector2 origpos;

void Start() {

}
void Update () {
    if(Input.GetKeyDown(KeyCode.UpArrow))
          origpos = cube1.transform.position; //store position on keydown      
    if(Input.GetKey(KeyCode.UpArrow)){
        t += Time.deltaTime;
        cube1.transform.position = Vector3.Lerp(origpos, cube2.transform.position, t/2f); // where 2f is the amount of time you want the transition to take
    }
    else if (Input.GetKeyUp(KeyCode.UpArrow) 
        t = 0; // reset timer on key up
}
ryeMoss
  • 4,303
  • 1
  • 15
  • 34