使用animationcurve进行按钮点击动画的问题[Unity]

时间:2017-08-12 06:17:09

标签: c# unity3d

我有一个点击动画的按钮,并使用动画曲线进行点击动画。效果很好。

问题是,我在协程中的某个地方搞砸了它会导致应用脚本的对象,当我点击它时会快速回到世界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");
    }
}

1 个答案:

答案 0 :(得分:0)

啊!刚刚找到了解决方案。基于ZayedUpal建议尝试使用transform.localPosition,我意识到单凭这一点是不够的,因为它只能引用它的自我。但是,如果我将此对象表示为空游戏对象然后运行,并使用父对象重新定位按钮,它将按预期工作!

重申一下,将tranform.position更新为transform.localPosition,然后将对象教育为空游戏对象,得到了我期待的结果。

如果有人有更好的解决方案,请发布,但就目前而言,这对我来说很合适。