Schodemeiss
Schodemeiss

Reputation: 1174

Vector2 grid direction based on Camera rotation without diagonals?

In Unity, I have a 2D grid which is built around Vector2's. What I'm trying to do is get the REAL "Right" (or any Direction) based on the cameras rotation.

For example, if the Camera is facing 90 degrees, then Vector2.right needs to be Vector2.up. I've seen lots of examples of this in Vector3, but I don't seem to be able to apply the same logic to Vector2. Especially when the Camera is 40 degrees, right suddenly becomes up AND right. How do I clamp it to the "nearest" direction? I don't want the "cursor" to ever move diagonally - always just in the closest direction based on the camera and the key pressed. I have some code snippets so folks can see how close I've got:

if (Input.GetKey(KeyCode.RightArrow))
{
    CameraDirection = CameraTransform.TransformDirection(Vector3.right);
}

Vector2 GridDelta = new Vector2((int)Mathf.Round(CameraDirection.x), (int)Mathf.Round(CameraDirection.z));

Unfortunately, GridDelta can sometimes come out as (1, 1), which I'd rather it was a single direction each time.

Any help would be hugely appreciated!

Upvotes: 0

Views: 276

Answers (1)

ryeMoss
ryeMoss

Reputation: 4333

I believe this problem is occurring because at 45degrees the normalized vector does not equal (.5, .5) but is (.7071, .7071) which comes from 1/(2^.5). At 40deg, the normalized vector will be something like (.72, .62), which is why rounding gives you (1,1).
One way to get around this would be to first divide by 2*.7071, and then round to the nearest integer. This essentially gives you a new halfway point to compare your non-linear vector components to. This is a bit of a hack, and you may have to deal with the special situation of having the camera at exactly 45degrees (and maybe some rounding issues). But otherwise this would work.

    Vector3 CameraDirection = Camera.main.transform.forward; // normalized directional vector of camera.

    Vector2 GridDelta = new Vector2((int)Mathf.Round(CameraDirection.x/1.414f), (int)Mathf.Round(CameraDirection.z/1.414f));

Upvotes: 0

Related Questions