- Home /
How to do Linear Translation between two Game object smoothly.
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);
}
} },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);
}
} }
Answer by Legend_Bacon · Mar 21, 2018 at 07:30 AM
Hello there,
You do want to use lerp here, but not that way. The third value you pass in should be "t", a value that increases from 0 to 1, where 0 is the start value and 1 is the target. You can read more about the proper use of Lerps (and all you can do with them) on this page.
Here is an example of basic a implementation in Update that should work for you:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class test : MonoBehaviour
{
private float t = 0.0f;
private float speed = 0.1f;
[SerializeField] private GameObject go_cube1 = null, go_cube2 = null;
private void Update()
{
if (Input.GetKey(KeyCode.RightArrow))
t += speed * Time.deltaTime;
else if (Input.GetKey(KeyCode.LeftArrow))
t -= speed * Time.deltaTime;
Mathf.Clamp(t, 0.0f, 1.0f);
transform.position = Vector3.Lerp(go_cube1.transform.position, go_cube2.transform.position, t);
}
}
Hope that helps!
Cheers,
~LegendBacon