使用C#代码在Unity 4.6中动画/移动/翻译/补间图像

时间:2014-11-25 06:11:00

标签: animation unity3d tween

如何使用Unity 4.6中的C#代码将图像从位置A移动/动画/平移/补间到位置B?

假设Image是一个GameObject,那么它可能是一个Button或者其他什么。 这个必须有一个单行,对吧?我已经谷歌搜索了一段时间,但是所有我能看到开箱即用的东西都是在Update中完成的,我坚信在Update中做一些东西不是编写脚本的快速方法。

2 个答案:

答案 0 :(得分:2)

maZZZu的方法可行,但是,如果你不想使用Update函数,你可以像这样使用IEnumerator / Coroutine ......

//Target object that we want to move to
public Transform target;
//Time you want it to take before it reaches the object
public float moveDuration = 1.0f;

void Start () 
{
    //Start a coroutine (needed to call a method that returns an IEnumerator
    StartCoroutine (Tween (target.position));
}

//IEnumerator return method that takes in the targets position
IEnumerator Tween (Vector3 targetPosition)
{
    //Obtain the previous position (original position) of the gameobject this script is attached to
    Vector3 previousPosition = gameObject.transform.position;
    //Create a time variable
    float time = 0.0f;
    do
    {
        //Add the deltaTime to the time variable
        time += Time.deltaTime;
        //Lerp the gameobject's position that this script is attached to. Lerp takes in the original position, target position and the time to execute it in
        gameObject.transform.position = Vector3.Lerp (previousPosition, targetPosition, time / moveDuration);
        yield return 0;
        //Do the Lerp function while to time is less than the move duration.
    } while (time < moveDuration);
}

此脚本需要附加到您想要移动的GameObject。然后,您需要在场景中创建另一个GameObject ...

代码已注释,但如果您需要澄清某些内容,请在此处发表评论。

答案 1 :(得分:1)

如果您想自己动手,可以使用以下内容:

public Vector3 targetPosition = new Vector3(100, 0, 0);
public float speed = 10.0f;
public float threshold = 0.5f;
void Update () {
    Vector3 direction = targetPosition - transform.position;
    if(direction.magnitude > threshold){
        direction.Normalize();
        transform.position = transform.position + direction * speed * Time.deltaTime;
    }else{ 
        // Without this game object jumps around target and never settles
        transform.position = targetPosition;
    }
}

或者您可以下载示例DOTween包,然后启动补间:

public Vector3 targetPosition = new Vector3(100, 0, 0);
public float tweenTime = 10.0f;
void Start () {
    DOTween.Init(false, false, LogBehaviour.Default);
    transform.DOMove(targetPosition, tweenTime);
}