Syncing character animation with game object's local transform (SOLVED!)
So I'm working on a top down 3D mobile game and what I'm trying to achieve is this: I have two joysticks for my game (mobile), the left controls X and Y movement along the world's transform. The right joystick rotates the character. No matter which direction the character is facing, the left joystick always moves the character relative to the world's axes. And that's how I want it to remain.
The trouble I'm running into is that, while I can get the run animations (forward, back, strafe left, strafe right) to work and be in sync with character movement so long as the character's transform is aligned with the world, what I want to happen is that say the character is turned 90 degrees right, the animations adjust so that when the left joystick is pushed forward--positive in the Y--the character starts strafing left, etc.
I've tried many versions of transform.InverseTransform..., but I can't for the life of me work out how to get the animations doing what I want. Thanks in advance!
private void UpdateAnimator()
{
Vector2 currentSpeed = speed * TCKInput.GetAxis("LJoystick");
float forwardSpeed = currentSpeed.y;
float sidewaysSpeed = currentSpeed.x;
GetComponent<Animator>().SetFloat("VelocityY", forwardSpeed);
GetComponent<Animator>().SetFloat("VelocityX", sidewaysSpeed);
}
Solved it and the answer is posted in the comments below for anyone who needs it.
Answer by DanWerkhoven · Jun 22, 2019 at 05:15 AM
So I figured since this place says there are 373 people following this question, that I'd post the answer I got in case anyone else is still searching for how the heck to do this.
It turned out the issue was actually with the joystick controller package I was using within Unity. I switched to a different one that used the CrossPlatformInputManager, and got it working using the InverseTransformVector. Here's what worked for me in getting the animations to rotate properly with the character:
private void UpdateAnimator()
{
float speedZ = CrossPlatformInputManager.GetAxis("LVertical");
float speedX = CrossPlatformInputManager.GetAxis("LHorizontal");
Vector3 currentSpeed = speed * transform.InverseTransformVector(speedX, 0f, speedZ);
float forwardSpeed = currentSpeed.z;
float sidewaysSpeed = currentSpeed.x;
animator.SetFloat("VelocityZ", forwardSpeed);
animator.SetFloat("VelocityX", sidewaysSpeed);
}
Your answer
Follow this Question
Related Questions
Animation clip doesn't play 1 Answer
Animator and code controlled bone rotations 0 Answers
Animation does not move! 2 Answers
Rotating transform more than 180 degrees 2 Answers