Search code examples
unity-game-engine2dlerp

unity 2D how to move object between two positions


I have two possitions posA and posB i want to move my player between this two position on button click.using Vetor3.Lerp player move only one time but it didnt work second move.can any one help.

    using UnityEngine;
using System.Collections;

public class PlayerTurn : MonoBehaviour {

    public Transform leftPos;
    public Transform rightPos;

    public float speed = 5;

    // Use this for initialization
    void Start () {
    }

    // Update is called once per frame
    void Update () {
    }

    public void functionForButton(){
            transform.position = Vector3.Lerp (leftPos.position, rightPos.position, speed);
    }
}

screen


Solution

  • You are messing some things up, Vector.lerp is used in Update, since it's a function that should work for every frame until it's done.
    It works from 'Source' to 'Destination', so as you click again, it will still run from the source to the destination, if you want to change it, you need to design your code in a way it will swap places. like setting a flag or creating another function. This is a good tutorial from the Unity developers on how to use Lerp.

    Vector3 Lerp Video
    Vector3 Lerp Scripting Reference