Nícolas
Nícolas

Reputation: 416

When animating a 2d object `Transform.Translate()` stops working

I'm developing an enemy AI in a 2D Game that I'm working on. This enemy swims and I wanted to make a "floating effect" animation for the enemy, so I made an animation where the Y Axis of the game object bounces up and down.

enter image description here

I Use transform.Translate() to move the enemies in the game and it worked just fine until I made this animation. But, when the animation is playing, the enemy can't move in any direction.

public virtual void Move(float speed)
{
    if (canMove)
    {
        transform.Translate(new Vector2(speed, 0) * Time.deltaTime);
    }
}

Upvotes: 0

Views: 498

Answers (1)

derHugo
derHugo

Reputation: 90629

Once you have a keyframe in any state of your animator for a certain property the animator will always overrule any changes done in a script because the animation updates are all done after Update. You could try to either move your code to LateUpdate.

Or in your specific case you do not want the x component of your position keyframed at all. Simply remove all the keyframes for the x (and z) component(s) of the position from the animations so only y has keyframes. This should solve your problem.


Alternatively use your movement script on a GameObject on a higher level in the hierachy as your Animator - meaning add a new GameObject, make the animated object a child of it and place your movement script instead on that parant object.

Upvotes: 1

Related Questions