- Home /
Animations preventing rotation
Hello,
I am making a 2D top-down game in which the player object moves along the X and Y axes and rotates in the Z axis. The player object has two animations: "Idle", which has no curves, and "Move", which contains only a Sprite Renderer Colour curve (the player flashes different colours as they move). Transitions between these two states are controlled by an animator bool 'moving', which is set in the player's Update method - sample code:
anim.SetBool("moving",true);
This system works perfectly. However, I also wanted the player object to rotate to face the current direction. To make this happen I added this code to the end of its Update method:
float targetAngle = Mathf.Atan2(moveDirection.y, moveDirection.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.Euler(0, 0, targetAngle), turnSpeed * Time.deltaTime);
This code also works. The problem I have is that it only works if the Animator for the player prefab is disabled in the inspector, and I cannot make both the animations (which, again, have no rotation component) and the rotation code work. If the animator is enabled, the animations work and the player's rotation does not change; if the animator is disabled the rotation changes as it should but (obviously) the animations do not play. How can I make them work together?
P.S. I'm aware of root motion and baking; I've tried every possible combination of options, including 'Bake into Pose', 'Loop Pose' and 'Based Upon (at Start)' in the animation options and 'Apply Root Motion' in the Animator settings. None of these have any visible effect. The closest I've got is by checking 'Animate Physics' in the Animator settings, which causes the rotation to start but be reset by each loop of the 'Move' animation, meaning that the player object is constantly shuddering between two angles.
Ok, so I sort-of-solved this myself by creating a child object for the player and outsourcing all the animation to it. This meant writing quite a lot of new code to pass methods back and forth between the parent and the child and so on, but it works. If there's a more elegant solution I'd love to hear it.
Your answer
Follow this Question
Related Questions
Matching character's rotation to the rotation of a animation - How? 0 Answers
How to do Turn animations with root motion (root bone rotations)? 2 Answers
Animation stops too early on all keyframes with apply root motion 1 Answer
Mecanim Root Motion Rotation - 180 degree turn. 2 Answers
Root Motion slowly veers off track 1 Answer