Search Unity

Vector3.Lerp with OnMouseDown problems

Discussion in 'Scripting' started by luigis, Aug 24, 2016.

  1. luigis

    luigis

    Joined:
    Oct 30, 2013
    Posts:
    25
    Hi all!

    i come back after the first problem: Learn what is Lerp! :)
    Now that i understood I've got another problem.
    I need to start the lerp function when i click with my mouse
    I'm using this wrong code that clearly return always 0 :mad:
    But I need to say at the button that start my animation: When i click you start from 0 and add the passing time

    Thanks a lot!

    Code (CSharp):
    1. void Update (){
    2.        
    3.  
    4.         if (Input.GetMouseButtonDown (0)) {
    5.             startTime = Time.time;//avvia il conteggio del tempo
    6.             step = ((Time.time - startTime) * speed);
    7.             Debug.Log (step);
    8.             animCamera.transform.position = Vector3.Lerp (animCamera.transform.position, target.position, curve.Evaluate (step));
    9.             }
    10.            
     
  2. Brathnann

    Brathnann

    Joined:
    Aug 12, 2014
    Posts:
    7,187
    GetMouseButtonDown will only trigger once when you click, which means to trigger this over and over would require multiple clicks. This isn't going to start your animation since it's only going to trigger once on buttonDown. You need to trigger a coroutine to loop to move your piece. Or you could do a loop inside the update, but just be careful of triggering it multiple times if you do additional mouse clicks.

    startTime = Time.time
    Time.time - startTime...I would see what this is returning, it's very possible you're getting 0 back. Which means 0 * whatever is going to be 0.
     
  3. kru

    kru

    Joined:
    Jan 19, 2013
    Posts:
    452
    To add some extra clarity to the above:

    Input.GetMouseButton() will return true every frame that the mouse button is held down.
    Input.GetMouseButtonDown() will return true only on the first frame that the user presses the mouse button down.
    Input.GetMouseButtonUp(), similarly, will return true only on the first frame that the user releases the mouse button.

    Since GetMouseButtonDown() returns true for only one frame, you can't use it directly to do any type of continuous activity. Instead, use the frame where GetMouseButtonDown returns true to kick off a continuous process. Starting a coroutine, as @Brathnann mentioned, is a great idea. Another common technique is to set a boolean variable to true, and then perform your once-per-frame operation in Update only when that boolean is true.