From the school course everyone knows what the sine and cosine are. For those who forgot:
The sine is the ordinate of the point of the unit circle.
The cosine is the abscissa of the point of the unit circle.
In Unity (C #) they are evaluated by functions:
Mathf.Sin(float Angle); // Sine (angle in radians)
Mathf.Cos(float Angle); // Cosine (angle in radians)
For example, to arrange objects in a circle.
Let’s take as example situation, when you need to place enemy models around the player.
Here how we can do this with a small script:
using UnityEngine;
public class EnemyInCircle : MonoBehaviour {
// Prefab of the enemy
public Object EnemyPrefab;
// Distance to player
public float Distance = 2;
// The angle occupied by the enemies (360 - the entire circumference)
public float Angle = 360;
// Number of enemies
public int count = 15;
void Start ()
{
// Define the starting point
Vector3 point = transform.position;
// translate the angle into radians
Angle = Angle * Mathf.Deg2Rad;
for(int i = 1; i <= count; i++)
{
// Calculating z-coordinate for the enemy
float _z = transform.position.z + Mathf.Cos(Angle/count*i)*Distance;
// Calculating x-coordinate for the enemy
float _x = transform.position.x + Mathf.Sin(Angle/count*i)*Distance;
point.x = _x;
point.z = _z;
// Instantiate enemy prefab in desired point
Instantiate(EnemyPrefab, point, Quaternion.identity);
}
}
}
The position of each enemy is shifted by a certain angle relative to the player.
The square of the side of the triangle is equal to the sum of the squares of the other two sides without the double product of these sides and the cosine of the angle between them.
The general formula for all triangles is:
a2 = b2 + c2 - 2bc * cos (A)
If the angle is a straight line, then the Pythagorean theorem uses:
The square of the hypotenuse is equal to the sum of the squares of the legs.
Formula:
a2 = b2 + c2
The Pythagorean theorem is a special case of the cosine theorem (the cosine of 90 is equal to 0).
The example of using cosine theorem in Unity:
We have:
Therefore, we will give him binoculars with the ability to measure the size of objects:
Knowing the viewing angle and the distance to the extreme points, we can calculate the size of the warehouse.
using UnityEngine;
public class MegaBinoculars : MonoBehaviour {
// Viewing angle
public float Angle = 50;
// Distance to the extreme points of view
public float Distance = 10;
void Update ()
{
if(Input.GetMouseButton(0))
{
Angle = Angle * Mathf.Deg2Rad;
// Calculate the square of the side of the warehouse (our warehouse is square, so this is the area)
float size = Distance*Distance + Distance*Distance - 2 * Distance * Distance * Mathf.Cos(Angle);
Debug.Log(size);
}
}
}