1
\$\begingroup\$

I have a GameObject called "Sun" in the sky. A game object called "GameManager" keeps track of time in the game, it is responsible for updating the hours and days.

For my sun I do something like this to get a percentage to use for the position of the sun on the orbit circle:

 float percentage = (((float)theGameManager.GetHourOfDay() / (float)GameManager.numberOfHoursInADay) * 360.0f);

I have a piece of code that can return the point in a circle if given a radius, an angle and an origin point.

public static Vector3 GetPointInCircle(float radius, float angleInDegrees, Vector3 origin)
{
    Vector3 resultingPoint = new Vector3(0.0f, 0.0f);
    resultingPoint.x = origin.x + radius * Mathf.Cos(angleInDegrees);
    resultingPoint.y = origin.y + radius * Mathf.Sin(angleInDegrees);

    return resultingPoint;
}

I use this function to determine the suns position each frame, as the angle i am passing is just the percentage of the circle, i expect the percentage variable to give increasingly bigger angles that make up 360 degrees. It does.

However when I set the suns new position using:

Vector3 newPos = new Vector3(MathsHelper.GetPointInCircle(sunOrbitRadius, percentage, new Vector3(50.0f, 0.0f, 50.0f)).x,
MathsHelper.GetPointInCircle(sunOrbitRadius, percentage, new Vector3(0.0f, 0.0f, 0.0f)).y, transform.position.z);

transform.position = newPos;

and the resulting behavior is the sun jumping to totally random positions around the circle, often picking ones that are near the start and end of the circle (by hour 4 the y value is already negative, which shouldn't be the case).

I notice if I swap out the percentage variable for Time.time it works perfectly, however this does not give me control over the sun in accordance to GameManagers day tracking and I feel like I am missing something obvious as to me it looks as though the math should work.

Additionally, I am using C# in Unity.

\$\endgroup\$
  • 4
    \$\begingroup\$ Mathf.Cos and Mathf.Sin both appear to use radians. Have you tried converting your degree angle into radians first? \$\endgroup\$ – milk Jul 20 '16 at 1:06
  • \$\begingroup\$ Thank you greatly, I converted the degrees to radians and now my orbit works perfectly in accordance to the length of the days :) \$\endgroup\$ – Kyle Motherwell Jul 20 '16 at 7:50

Your Answer

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

Browse other questions tagged or ask your own question.