Rotate direction relative to another direction

Hey all,

I’m missing something blatantly obvious and I can’t figure it out. Basically, I have a fixed camera and am using WASD to move my player. I also use the mouse to aim the player in a certain direction. Here’s what I’m looking for…

Mouse it at top of screen…

  • W plays the forward animation of the character
  • A plays the left animation
  • S plays the backward animation
  • D plays the right animation

Mouse is at the left of the screen…

  • W plays the right animation
  • A plays the forward animation
  • S plays the left animation
  • D plays the backward animation

Mouse is at the bottom of the screen…

  • W plays the backward animation
  • A plays the right animation
  • S plays the forward animation
  • D plays the left animation

I figured this would be easy by creating a quaternion off of the “looking direction” and then rotating the “input direction” by that quaternion. HOWEVER, the following code causes the “temp” variable to be backwards and not forwards. Any ideas?

var inputDirection = new Vector3(-1, 0, 0);
var lookingDirection = new Vector3(-1, 0, 0);
var lookingRotation = Quaternion.LookRotation(lookingDirection);
var temp = lookingRotation * inputDirection;

Debug.Log(temp);

EDIT: I found a video showing something like what I’m trying to achieve… It should give you some context anyway: Top Down Shooter (Isometric Camera, WASD Controls, Aim at Mouse Cursor, Alien Swarm) - YouTube

HALLELUJAH! I got it. The solution seems overly complicated, I’m still wondering if there’s a better way… Alas, here’s the code:

var inputDirection = new Vector3(1, 0, 0);
var lookingDirection = new Vector3(1, 0, 0);

var angle = Vector3.Angle(lookingDirection, Vector3.forward);
var cross = Vector3.Cross(lookingDirection, Vector3.forward);
if (cross.y < 0)
    angle = -angle;

var lookingRotation = Quaternion.AngleAxis(angle, Vector3.up);
var inputRotation = lookingRotation * inputDirection;

Debug.Log(inputRotation);

Basically, I’m taking the direction that the character is facing and calculating the difference in degrees compared to the standard “forward-facing” direction. Then, since Vector3.Angle returns an absolute value of the angle, I calculate the cross product to determine the angle’s polarity. After that, I slam that angle into a quaternion, multiply it by the input direction, and I’m home free.