0
\$\begingroup\$

I am trying to instantiate a cluster of triangles (enemies) in the shape of a polygon and am unsure how to angle them correctly to all be facing away from the center. Thanks to another question, I got the positions roughly right:

for (int i = 0; i < formation.Count; i++)
{
    Vector3 pos = new Vector3(Mathf.Sin((float)i / formation.Count * 2 * Mathf.PI), Mathf.Cos((float)i / formation.Count * 2 * Mathf.PI));  
    GameObject tri = Instantiate(gameObj, pos, /*Quaternion.Euler(0, 0, z)*/, parent) as GameObject;
}

Now I just need to get the angles such that all triangles face away from the center.

\$\endgroup\$
0
\$\begingroup\$

You already have a vector pointing out from the center - it's the one you're using to form the position! So, just orient to point along that direction using LookRotation. :D

for (int i = 0; i < formation.Count; i++)
{
    float angle = i / (formation.Count * 2f * Mathf.PI);
    Vector3 fromCenter = new Vector2(Mathf.Sin(angle), Mathf.Cos(angle));
    Vector2 position = center + radius * fromCenter;
    Quaternion orientation = Quaternion.LookRotation(Vector3.forward, fromCenter);
    GameObject tri = Instantiate(prefab, position, orientation, parent) as GameObject;
}

Here I'm assuming the "nose" of your triangle points in its local y+ direction. If it points a different way, you can apply an additional rotation to make sure the nose points out instead of, eg., clockwise.

\$\endgroup\$
  • \$\begingroup\$ how would I determine the radius? doesn't that depend on the amount of edges? (number of triangles) \$\endgroup\$ – EpicNicks Jul 9 at 13:42
  • \$\begingroup\$ In your example, since you didn't include a radius multiplier, the radius is 1. You can put any number you want there to make the ring of objects larger or smaller. \$\endgroup\$ – DMGregory Jul 9 at 13:43
  • \$\begingroup\$ thanks for the help. For any who may land on this page later, to have all triangles "look away" from the center instead of at it, in Quaternion.LookRotation multiply fromCenter in the above example by -1. \$\endgroup\$ – EpicNicks Jul 9 at 13:50
  • \$\begingroup\$ Sounds like your triangles are oriented so their "nose" points along their local y- then. \$\endgroup\$ – DMGregory Jul 9 at 13:50
  • \$\begingroup\$ both effects end up being really cool; but yeah, the local y- now that I know what that means. \$\endgroup\$ – EpicNicks Jul 9 at 13:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.