0
\$\begingroup\$

I have a compass that is pointing towards player forward direction.

direction.z = player.eulerAngles.y;
if (_transform.localEulerAngles.y != direction.z)
{
   _transform.localEulerAngles = direction;
}

I have indicators for each objective. I'm trying to rotate the indicator towards quest objectives as seen in image bellow.

float angle = Vector2.Angle(player.transform.position - player.transform.forward, objective.position);
objectivePositionUI.anchoredPosition = new Vector3(
   Mathf.Cos((angle * 2 * Mathf.PI) / 180f) * radius,
   Mathf.Sin((angle * 2 * Mathf.PI) / 180f) * radius,
   0f
);

My result atm

Compass with indicators

My problem here is that the yellow dots (objectives) should be rotated at the same direction as arrow in this case because I am facing the quest objectives head on.

\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

You can do this much more simply, assuming "North" is the world z+ direction and "East" is the world x+ direction:

Vector2 GetCompassPosition(Transform target, float radius) {
    Vector3 offset = target.position - player.transform.position;
    return new Vector2(offset.x, offset.z).normalized * radius;
}

Your pointer can then point with the angle...

float GetCompassAngle(Vector3 direction) {
    return Mathf.Atan2(direction.x, direction.z) * Mathf.Rad2Deg;
}

This will give you an angle of 0 degrees when the direction is directly north (0, 0, 1), 90 degrees when the direction is directly east (-1, 0, 0), etc., to be consistent with the version shown in your question.

You can use it like this. This saves you from reading Euler angles, since they can behave counter-intuitively and lead to bugs.

_transform.localEulerAngles = new Vector3(0, 0, GetCompassAngle(player.forward));
\$\endgroup\$
1
  • \$\begingroup\$ Took a while to get my head around it, but it's working like a charm. Also, I learned something today. Thank you very much! \$\endgroup\$ Commented Nov 9, 2021 at 17:05

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .