Quantcast
Channel: Questions in topic: "unit"
Viewing all articles
Browse latest Browse all 68

How should I rotate a 2D unit vector by X degrees?

$
0
0
As the title says, I have a 2D unit vector, and I simply need to rotate it by X degrees. I've done a lot of googling, and couldn't really find what I needed (most similar problems I found were quite a bit more complex). Also I'd be calling this up to 4 times per update, so I'm hoping for a solution that isn't horrible on performance. Oh and X degrees is actually coming from the camera's Y rotation. So if there's a better way to offset the vector by the camera's Y rotation that involves not using degrees, I suppose that'd be just as useful. (And by better I mean more efficient.) Tried multiplying my vector like the following as suggested online: `Quaternion.AngleAxis(Camera.main.transform.rotation.y, Vector3.forward) * new Vector2(Input.GetAxis("P1MoveHorizontal"), Input.GetAxis("P1MoveVertical"))` Didn't make any difference. And Quaternion.AngleAxis(Camera.main.transform.rotation.y, Vector3.forward) * new Vector2(Input.GetAxis("P1MoveHorizontal"), Input.GetAxis("P1MoveVertical")) Gives me an error where Quaternion cannot multiply with a vector2. Tried this: float sin = Mathf.Sin(Camera.main.transform.rotation.y); float cos = Mathf.Cos(Camera.main.transform.rotation.y); float tx = Input.GetAxis("P1MoveHorizontal"); float ty = Input.GetAxis("P1MoveVertical"); Move(new Vector2((cos * tx) - (sin * ty), (cos * ty) + (sin * tx))); Made a difference, but still not the correct directions. I even tried convert the unit vector to degrees, adding the camera's rotation in degrees, and then converting it back into a vector: float directionAngle = Mathf.Atan2(Input.GetAxis("P1MoveVertical"), Input.GetAxis("P1MoveHorizontal")); directionAngle += Camera.main.transform.rotation.y; Move(new Vector2(Mathf.Sin(directionAngle), Mathf.Cos(directionAngle))); But EVEN THIS which I was certain would work but was hoping to avoid for inefficiency, is not working at all as expected. Without even inputting a direction my object moves around in circles and wanders off the scene.

Viewing all articles
Browse latest Browse all 68

Trending Articles