【C#】使用Mathf.Sin與Cos取得圓上點座標

最近要使用到算圓,因此想到以前常用的三角函數,sin、cos

Mathf.sin 官方的api裡面註明了

Returns the sine of angle f in radians.

他輸入的是弧度,所以如果想求 圓上某個點的座標,要先把弧度轉換成角度

什麼是弧度呢?

看下圖應該很明顯了XD

img

(取自維基百科)

兩者關係就是

1
2
3
1弧度 = 360°/2π ≒ 57.29° 

1° = 2π/360° ≒ 0.0174533(弧度)

這是比較公式化的,如果自己去算的話,就是照上面的圖,180°,分成180份

然後除以長度,就會得出0.017453….

這樣就知道1度等於0.0174533弧度,假如想求90度的話,就*90就好了

Mathf裡面已經定義好常數給你使用了

分別是

Mathf.Deg2Rad跟Mathf.Rad2Deg

以下簡單示範一下

1
2
3
float angleY = Mathf.Sin(60*Mathf.Deg2Rad);
float angleX = Mathf.Cos(60*Mathf.Deg2Rad);
Point1 = new Vector2(angleX, angleY);
1
Debug.DrawLine(Vector2.zero, Point1,Color.green);

結果: (( 其他線是測試用,上述代碼出現的是綠色那條))

img

而使用Sin可以使用拿來移動物體

使用上像是這樣

1
2
3
4
5
6
7
8
9
10
11
private Vector3 _startPosition;

void Start()
{
_startPosition = transform.position;
}

void Update()
{
transform.position = _startPosition + new Vector3(Mathf.Sin(Time.time), 0.0f, 0.0f);
}

這樣就會有平滑平滑的感覺啦~