2017-08-12 54 views
0

我有一個按鈕,它可以點擊動畫,併爲點擊動畫使用動畫曲線。很棒。使用動畫曲線進行按鈕點擊動畫的問題[Unity]

問題是,我在協程的某個地方搞砸了,它會導致腳本應用到的對象,當我點擊它時,會回到世界0。如何根據曲線移動物體到達世界空間,而不是在第一次點擊時彈出到世界0?

這裏是我的按鈕腳本:

using System.Collections; 
using System.Collections.Generic; 
using UnityEngine; 

public class Button : MonoBehaviour { 

    //create a placeholder for the animation coroutine 
    IEnumerator currentCoroutine; 

    //create public animation curve for adjustments 
    public AnimationCurve curveAnim; 

    public float posDisplacement; //animation value (movement distance, opacity, etc.) 
    public float speed; //the speed at which the animation curve should complete in (like a magnitude) 

    //animaiton coroutine 
    IEnumerator kickback(){ 
     float curveTime = 0f; //beginning time of the animation curve 
     float curveAmount = curveAnim.Evaluate (curveTime); //a place to store the value of the curve at any point in time 

     //while loop to execute the curve until it completes 
     while (curveTime < 1.0f) { 
      curveTime += Time.deltaTime * speed; //reference curve at time - speed affects the duration at which the curve completes 
      curveAmount = curveAnim.Evaluate (curveTime); //store the current curve value from the time * speed 

      //do something using the value of the curve at time 

      //this will move the current object in z in reference to the animaiton curve by multiplying the value of the curve by the animation value 
      transform.position = new Vector3(transform.position.x, transform.position.y, curveAmount*posDisplacement); ] 

      //break after completing 
      yield return null; 
     } 
    } 

    //Button events 

    void OnTouchDown(){ 
     //Debug.Log ("Touch Down!"); 
    } 

    void OnTouchUp(){ 

     //check if a coroutine is already running. If so, stop it and then start it again 
     if (currentCoroutine != null) { 
      StopCoroutine (currentCoroutine); 
     } 

     currentCoroutine = kickback(); //assign what the currently running coroutine is 
     StartCoroutine (currentCoroutine); //run the current coroutine OnTouchUp 
     //Debug.Log ("Touch Up!"); 
    } 

    void OnTouchStay(){ 
     //Debug.Log ("Staying..."); 
    } 

    void OnTouchExit(){ 
     //Debug.Log ("Exited"); 
    } 
} 
+0

你嘗試使用transform.localposition而不是transform.position? – ZayedUpal

+0

是的,同樣的結果。我認爲這與我試圖只更新遊戲對象的z軸的方式有關,但我不知道其他選項,我可能嘗試更新對象的位置。我將一個float乘以一個動畫曲線,所以我假設我的曲線在0處結束,位置將爲0.如果是這種情況,也許我試圖以錯誤的方式移動我的對象... – dotcommer

回答

0

啊!剛想出一個解決方案。根據ZayedUpal的建議,嘗試使用transform.localPosition,我意識到僅靠這一點是不夠的,因爲它只能引用它自己。但是,如果我將這個對象放在一個空的遊戲對象中,然後運行,並使用父對象來重新定位按鈕,它將按預期工作!

所以重申,更新tranform.positiontransform.localPosition,然後將對象父母化爲空遊戲objet得到了我期待的結果。

如果任何人有更好的解決方案,請張貼它,但現在,這對我來說工作得很好。