- Home /
Rotate 3d vector based on local forward
Hey all,
I'm trying to rotate a 3d vector [input] so that:
local forward
= (0,0,1) => input is not rotated
= (1,0,0) => input is rotated 90 deg
= (0,0,-1) => input is rotated 180 deg
= (-1,0,0) => input is rotated 270 deg
// movement is on the xz plane
Basically, I've got player input as a vec3 in a top down / twin stick shooter game and i'd like to use to it drive the blend tree animations. However, animations are relative to the direction the player is facing, so the input values need to be rotated to map to the proper animation values. For example if the player is pressing the [move right key] and facing east, i'd like to play the forward animation. If the player is facing south and presses the same [move right key] i'd like to play the strafe to the left animation.
I think https://answers.unity.com/questions/46770/rotate-a-vector3-direction.html is a good start but I couldn't get figure out how to properly apply it here.
How can I achieve this effect? Thanks for any help!
Answer by kirbygc00 · May 24, 2021 at 06:24 AM
Not sure if it's ideal but I ended up going with:
private void UpdateAnimations(Vector3 motion) {
var forward = Owner.transform.forward;
var right = Owner.transform.right;
var dotForward = Vector3.Dot(forward, motion);
var dotRight = Vector3.Dot(right, motion);
Owner.Animator.SetFloat("VerticalMotion", dotForward);
Owner.Animator.SetFloat("HorizontalMotion", dotRight);
}
that's a great approach, imo.
You could also do something like Vector3 localMotion = motion * Owner.transform.rotation
, but honestly if the dot products work I find them a little more intuitive.