Search Unity

Cant move object to exact position

Discussion in 'Scripting' started by Wehaga, Jan 15, 2022.

  1. Wehaga

    Wehaga

    Joined:
    Jul 20, 2017
    Posts:
    5
    I have a coroutine I'm firing when I hit a button, that would want to imitate the button being pressed then moved back to its original position

    Code (CSharp):
    1.     IEnumerator ButtonPress(Transform objectHit)
    2.     {
    3.         Vector3 originalPosition = objectHit.localPosition;
    4.  
    5.         float percent = 0f;
    6.  
    7.         while (percent <= 1f)
    8.         {
    9.             percent += Time.deltaTime * 1f;
    10.             float interpolation = 2f * (-Mathf.Pow(percent, 2) + percent);
    11.             objectHit.localPosition = Vector3.Lerp(originalPosition, new Vector3(objectHit.localPosition.x, objectHit.localPosition.y, objectHit.localPosition.z + 0.02f), interpolation);
    12.          
    13.             yield return null;
    14.         }
    15.     }
    Now it does work alright, however it doesn't return to the exact position it originated from at the end. Even if I explicitly give it something like:

    objectHit.localPosition = originalPosition;

    after the while loop

    How can I make sure that it goes back, so no matter if a user just mashes on the button clicking a 100 times, the button will stay where it was?

    Thanks!
     
    Last edited: Jan 15, 2022
  2. RadRedPanda

    RadRedPanda

    Joined:
    May 9, 2018
    Posts:
    1,648
    Get the position on
    Start()
    and set it to that position every time.

    Also, instead of using a coroutine to do this, why not just press it inside of OnPointerDown and depress it in OnPointerUp?
     
    Wehaga likes this.
  3. Wehaga

    Wehaga

    Joined:
    Jul 20, 2017
    Posts:
    5
    Thanks a lot! Getting the position in Start() did solve my issue. Though I'm wondering why? Both solutions fetch the position before any modifications were done to it

    With OnPointerDown/Up, how would I control the speed of the button press? If the user just clicks without holding the button down, wouldn't it just make the there and back movement really fast? If I make the press-in say 0.5 seconds and they release the button before that, would it just cut the movement and start going back?

    thanks again!
     
  4. RadRedPanda

    RadRedPanda

    Joined:
    May 9, 2018
    Posts:
    1,648
    My guess here is because of floating point precision, I won't go into detail here though since that's quite a deep rabbit hole.

    Ah, okay, ignore what I said then. I didn't realize you were explicitly trying to have it timed instead of just when they click.
     
    Wehaga likes this.