2017-08-12 84 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得到了我期待的结果。

如果任何人有更好的解决方案,请张贴它,但现在,这对我来说工作得很好。