Trigonometry Demo on GitHub

Trig Demo on YouTube

The is a simple little demo that I did for one of my programming classes which shows that I know how to use basic trigonometry in code. There were two main goals for this project.

- Have the hand on the clock follow the mouse cursor through code.
- Have the numbers of the clock be generated through code as well.

To have the mouse follow the cursor hand I used the following code:

void RotateToMouse()

{

// Gets the mouse location from the screen

Vector3 mouseWorldPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);

// Use the Mathf.Atan2 function to get the angle at which we need to rotate

float angleFromCenter = Mathf.Atan2(mouseWorldPos.y, mouseWorldPos.x);

// Since the angle input from Atan2 is returned in radians, we have to

// convert it to degrees in order to use the Quaternion.Euler method.

float degrees = angleFromCenter * Mathf.Rad2Deg + 180;

transform.rotation = Quaternion.Euler(0, 0, degrees);

}

As you can see from the YouTube video, both of my goals were achieved. How I generated the angle interval for between the numbers is like so:

angleInterval = (-1) Mathf.PI / ((numberOfObjects) / 2);

The reason that I multiplied by -1 in order to get the numbers to go in a clockwise direction when instantiating them, instead of a counter-clockwise direction.

I also have a float called startAngle, which is (PI/2), so that the generation starts at the top like a clock would. Obviously this is adjustable through the code.

*Related*