Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

lerp position with mouseclick on object?

Discussion in 'Scripting' started by woy, Jun 16, 2015.

  1. woy

    woy

    Joined:
    Jun 15, 2015
    Posts:
    5
    Hi guys i got this code from a tutorial video. But i want to click on a object and it moves in position B when i click again on the object it should move back to position A. I read that a bool is used for this but i dont understand it. Can someone ad a few lines code for this. Im pretty new to scripting.

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class lerp : MonoBehaviour
    5. {
    6.     private Vector3 newPosition;
    7.  
    8.     void Awake ()
    9.     {
    10.         newPosition = transform.position;
    11.     }
    12.  
    13.     void Update ()
    14.     {
    15.         PositionChanging ();
    16.     }
    17.  
    18.     void PositionChanging ()
    19.     {
    20.         Vector3 positionA = new Vector3(-15042,30,23148);
    21.         Vector3 positionB = new Vector3(-15042,40,23148);
    22.  
    23.         if (Input.GetKeyDown (KeyCode.Q))
    24.             newPosition = positionA;
    25.         if (Input.GetKeyDown (KeyCode.E))
    26.             newPosition = positionB;
    27.  
    28.         transform.position = Vector3.Lerp (transform.position, newPosition, Time.deltaTime);
    29.     }
    30.  
    31. }
     
  2. bogartrye

    bogartrye

    Joined:
    Jun 16, 2015
    Posts:
    1
    Here you go. If you want to have the object stationary until you click it the first time, you'll need to change the bool to an int and use different int values to represent which destination to move towards (ie. 0 = stationary, 1 = position A, 2 = position B). Good luck!
     

    Attached Files:

    • lerp.cs
      File size:
      1.4 KB
      Views:
      980
  3. woy

    woy

    Joined:
    Jun 15, 2015
    Posts:
    5
    This is awsome. Thank you very much. It worked perfect. Im really happy right now :D