- Home /
Why does animation clobber my positioning code?
Okay so I have two objects in my world, one with a looping animation, and one without. The below code is supposed to take the object and move it in front of my avatar. I attach the below code to both objects and the object without the looping animation does exactly what was intended. The object with the looping animation stays in some random place in the world. If I turn the animation off in the inspector the object works as it's supposed to, put it back on and the problem occurs again. Any ideas?
var objectToFollow;
var ufoVisible = false;
function Update ()
{
if(gameObject.Find("localPlayer")==null)
{}
else
{
if(ufoVisible)
{
objectToFollow = GameObject.FindWithTag("Player").transform;
transform.rotation = objectToFollow.rotation * Quaternion.Euler(0,-90,0);
animation.Play("Take 001");//added
}
else
{
objectToFollow = GameObject.FindWithTag("Player").transform;
transform.position = objectToFollow.TransformDirection(Vector3.forward * 4) + objectToFollow.position;
transform.rotation = objectToFollow.rotation * Quaternion.Euler(0,-90,0);
animation.Stop("Take 001");//added
}
}
if(Input.GetKeyUp("u"))
{
if(ufoVisible)
{
ufoVisible = false;
}
else if(!ufoVisible)
{
ufoVisible = true;
}
}
}
Answer by HolBol · Jul 12, 2011 at 08:05 PM
It's because when animating, you should always keep the model at the pivot, because the animation plays in local space with the model. You'll just have to adjust the numbers until it fits right, or reanimate.
I guess I'll just change order of operations to attach, animate, loop animation.
Pretty unsatisfying answer though :(
Well it's just something that you have to understand, animations play in local space - it'd be horrible if they didn't. ;)
problem still. I edited my code from above to reflect what I'm doing now. You can see that I now turn the animation off when the game starts. Then when I want to turn the animation on I manipulate its position first and then turn the animation on, however the position still doesn't change.
I edited it once again and got rid of all the position code except for the initial positioning. So now when the game starts the position of the ufo is correct, right in front of my avatar. As soon as the animation starts, even though no positioning code is being hit, the ufo gets shot off into the world to some random place. -_-
Answer by DaveA · Jul 12, 2011 at 08:33 PM
I may be way off here, but an idea: Seems that animation curves affect the transform. So does the code, but the animation is 'winning' this fight. What if you reparent the object, with the animation curves on the child, and the animation code on the parent (or vice-versa)?
This would still mean that the animation's re-positioning happens after the re-positioning in the Update function, won't it? Giving LateUpdate a try could work though, perhaps. The problem is I have no idea 'when' in a frame the animation is played, I wouldn't be surprised it's saved for the end.