- Home /
Convert an angle to a vector?
I've seen a number of people post this question, but every result is a different application, and I can't properly adapt their answers to my situation.
I have an angle (in degrees.) I want to apply it as a velocity to a rigidbody. Velocity values are stored as Vector3 values, so I need to convert this to a vector3. Of course, I also need to apply a magnitude or speed, and since we are working in 3D space there is technically a need for two angles, but for right now I'm just applying the velocity on the XZ plane. (Maybe in the future I will want to modify this to include a second angle so it can aim up and down?)
Looking at other answers, they use a quaternion with the method AngleAxis, but I can't apply a quaternion, I need a vector. I tried multiplying it by a vector3 to change it to a vector3, but that just changed it to the same Vector3 I multiplied it by for some reason.
This is the code I used:
thisShot.GetComponent<Rigidbody>().velocity = Quaternion.AngleAxis(facingAngle, Vector3.forward) * (Vector3.forward * 10f);
Answer by Eno-Khaon · Sep 08, 2020 at 02:19 AM
I don't really see how Quaternion*Vector multiplication wouldn't give you the result you're looking for here:
Vector3 straight = Vector3.forward;
// Vector3.up for clockwise-based rotation
Quaternion r90 = Quaternion.AngleAxis(-90f, Vector3.down);
Debug.Log(straight + " -> " + (r90 * straight));
// Output: (0, 0, 1) -> (1, 0, 0)
Take the result and scale it as needed and you'll have your force to apply:
Quaternion angleRotation = Quaternion.AngleAxis(desiredRotation, Vector3.down);
// Using a non-fixed baseline as an example (transform.forward)
Vector3 forceDirection = angleRotation * transform.forward;
// Example applying an immediate force, unaffected by mass
rb.AddForce(forceDirection * speed, ForceMode.VelocityChange);
Your answer
Follow this Question
Related Questions
How to project an angle from a vector 3 Answers
Vector3.SignedAngle changes sign for no reason 1 Answer
How to calculate the rotation of a hexagon based on its six vertices position 2 Answers
Change a property based on angle? 1 Answer
Vector3.SignedAngle seemingly avoids values close to 0 and +-180 1 Answer