How can I determine which direction the player is moving based on mouse rotation direction?
I have a character that will move up down left and right normally, but when we aim, it will be looking at the direction of the mouse or joystick. I got all working except trying to properly animate the character in this situation. I am looking for basic movements, forward, back, left and right.
I cannot figure out how to determine if my character is now moving backwards if it had a rotation to the right (ie. 66 degrees).
I have seen several items referring to either comparing the previous rotation and position. I saw another using the 'Horizonal' and 'Vertical' inputs but this does not work because at some point 'Horizontal' and 'Vertical' do not correspond to the movements if the character is rotated.
I have an empty game object with the character controller and the movement script. Nested is the character model which gets rotated.
I have attached a clip of what I am trying to do https://drive.google.com/file/d/1Vj60N4ShJSksn6S2vDj8cDaoM8rNdtj4/view?usp=sharing
Answer by thefenry · Jul 19, 2020 at 08:14 PM
I just found out a way to do this. Hopefully it helps others. I found the answer on reddit here.
Vector3 inputVector = (Vector3.forward * Input.GetAxis("Vertical")) + (Vector3.right * Input.GetAxis("Horizontal"));
Vector3 animationVector = _playerModel.transform.InverseTransformDirection(inputVector);
var VelocityX = animationVector.x;
var VelocityZ = animationVector.z;
this._playerAnimator.SetFloat("x", VelocityX);
this._playerAnimator.SetFloat("z", VelocityZ);
I my case I have my movement script on a parent empty object. This object rotates the child player model, which is the one getting animated. If you do this then you will need to reference the player model like I am doing. Otherwise you can you transform if you are using the parent object.
I am using a character controller on my parent object not a rigidbody, but it may work the same either way.
From my understanding the key part is 'InverseTransformDirection' which is taking my physical world horizontal and vertical vectors and then converting them based on the rotation of my player model. This then makes the movements be relative to the players rotation rather than the worlds rotation and I can move backwards or strafe correctly as I am moving my mouse for rotation and wasd for movement.
Your answer
Follow this Question
Related Questions
Strange rotation behaviour 0 Answers
Camera Rotation every time a key is pressed 0 Answers
How can I make the camera not overreach a limit of rotation one axis. 0 Answers
Movement of a sphere 0 Answers
Problem with player direction using virtual joysticks 0 Answers