Home > Software design >  How do I calculate a 2D Vector from a dot product or a signed angle?
How do I calculate a 2D Vector from a dot product or a signed angle?

Time:02-15

I have the following scenario:

I am working on a top-down 2-dimensional (XZ plane) game and i need to calculate the difference of the characters movement direction (moveDir) to the look direction (lookDir).

I would like to calculate a 2D Vector (xy) that holds the following information:

The X value should range from -1 (character facing backwards) to 1 (facing forwards)

The Y value should also range from -1 (character facing left) to 1 (facing right).

To calculate the X value I can use the dot product of moveDir and lookDir. However, I dont understand how to correctly calculate the Y value. I assume that I have to use the signedAngle between moveDir and lookDir, as the signedAngle returns a value of -90 if the character is facing left and 90 if its facing right.

I could probably even use the signedAngle between the vectors for calculating both X and Y values, as a signedAngle of 0 has the same meaning as a dot product of 1 (and also the same applies to a signedAngle of 180 and the dot product of -1).

How do I calculate the missing part?

CodePudding user response:

I figured out the following solution (pseudocode):

y = 1 - absoluteValue(dotProduct(lookDir, moveDir))

if (signedAngle(lookDir, moveDir) <= 0
    y *= -1

CodePudding user response:

As said assuming both moveDir and lookDir are normalized vectors I think you can simply use enter image description here

so

 Vector3.Cross(moveDir, Vector3.forward)

would return a vector to the "left" -> we invert it, now it's a vector to the "right".

At which point you do this exactly doesn't really matter. Either on the moveDir or the Vector3.forward (=> Vector3.back == -Vector3.forward) or the result of Vector3.Cross or the result of Vector2.Dot -> the result should always be the same.

  • Vector3 and Vector2 are implicitly convertible into each other which will simply ignore the Z component or use 0

    • Related