Unity3d。如何使动画位置从最后位置开始

时间:2014-09-04 18:47:45

标签: animation unity3d position relative

如何在Unity中相对于最后一个位置实现动画。通常,当在Unity中实现动画时,每个循环都从相同的位置开始。我想实现相对于动画对象的最后位置的动画,以避免使用力或数学计算。

1 个答案:

答案 0 :(得分:1)

我怎么弄清楚:

Unity动画相对于上一个位置而没有循环

此代码解决了基于最后相对位置的动画问题。在这个例子中,每次按下Fire1时,一个框将被动画化,从X = 0移动到X = 10使用动画将帮助我们提供更丰富的过渡和基于曲线的平滑移动,而不会出现循环问题。

我们的想法是将动画对象放在空父对象中,这样对象的动画就会基于本地位置。

动画完成后,我们更新对象及其父位置以匹配最后一个位置。

如果您有任何疑问,请询问。

#pragma strict

/**
* Animation in Unity Relative to last position without looping
* @autor Knskank3
* http://stackoverflow.com/users/1287772/knskan3
* 04/09/2014
**/

/*
    This code solves the problem regarding animations based on last relative ImagePosition
    In this example, each time we press Fire1 a box will be animated to move from X = 0 to X = 10
    Using the animation will help us to provide richer transitions and smooth movements based on curves
    without the problem of looping
*/


// This var will determine if the animation is started
public var animation_started : boolean = false;
// This var will determine if the animation is finished
public var animation_finished : boolean = true;

function Update () {

    // if user triggers Fire1
    if( Input.GetButtonUp('Fire1')){

        // initialize the flags
        animation_started = true;
        animation_finished = false;

        // Start the animation
        // this animation moves the box from local X = 0 to X = 10 using a curve to deaccelerate
        animation.Play("boxanim");
    }

}

/* This function is trigger at the end of the animation */
public function animationFinished() : void {
    animation_finished = true;
}

/*  
    At the end of the frame if the animation is finished
    we update the position of the parent to the last position of the child
    and set the position of the child to zero inside the parent.
*/
function LateUpdate () {
    // if the animation is finished and it was started
    if(animation_finished && animation_started) {
        // set the flag
        animation_started = false;
        // update the parent position
        transform.parent.position = transform.position;
        // update the box position to zero inside the parent
        transform.localPosition = Vector3.zero;
    }
}