Angle calculation wrong

I am trying to do a raycast at a certain angle, but the direction vector is coming out wrong every time except the first, with no changes being made that I am aware of. Here is the code:

foreach (int i in roadExits)
        {
            print(name + " : " + i);
            float angle = ((i - 1) * 60 + 30) * Mathf.Deg2Rad;
            print(((i - 1) * 60 + 30));
            Vector3 dir = (transform.forward * Mathf.Cos(angle) + transform.right * Mathf.Sin(angle)).normalized;
            print(dir);
            if (Physics.Raycast(transform.position, dir, out RaycastHit rayhit, 1.733f, terrainLayer))
            {
                print("hit");
                if (rayhit.collider.GetComponentInParent<HexScript>().isRoad)
                {
                    print(rayhit.collider.name + " is road");
                    roadConnections.Add(rayhit.collider.gameObject);
                } else {
                    print("isnt road");
                }
            }
        }

The problem is lines 4-7.
One case is when angle is 210 degrees. The first time this is calculated, the direction vector is as expected: (-0.50, 0, -0.87). All subsequent time however it is (-0.50, 0, 0.87).
The print statement on line5 is always correct so it is not that. Any ideas?

Alternatively, if this is a bad way to raycast at an angle, please suggest a better way.
Thanks.

Are you rotating the “transform” at all in your script?


Assuming line 5 always prints correct, and line 7 is the line that prints wrong occasionally, it might be that transform.forward and transform.right are not always what you think they are, and this would likely be because some rotation is applied to the transform.


Im guessing a bit of context, but this looks like it could be a Hex based 2D game, so maybe you want something like Vector3.up and Vector3.right?


Let me know if it helps, some more code might be helpful.