加算
プログラム例
using UnityEngine; public class Vector2Sample0 : MonoBehaviour { // Start is called before the first frame update void Start() { Vector2 vect1 = new Vector2(0, 2.5f); Vector2 vect2 = new Vector2(1.2f, 2.3f); Debug.Log(vect1 + vect2); } }
実行結果
(1.2, 4.8)
正規化
プログラム例
using UnityEngine; public class Vector2Sample1 : MonoBehaviour { // Start is called before the first frame update void Start() { Vector2 vect1 = new Vector2(3, 4); Vector2 normal = vect1.normalized; Debug.Log(normal); } }
実行結果
(0.6, 0.8)
内積
プログラム例
using UnityEngine; public class Vector2Sample2 : MonoBehaviour { // Start is called before the first frame update void Start() { Vector2 vect1 = new Vector2(3, 4); Vector2 vect2 = new Vector2(1, 2); Debug.Log(Vector2.Dot(vect1, vect2)); } }
実行結果
11
角度の測定
using UnityEngine; public class Vector2Sample3 : MonoBehaviour { // Start is called before the first frame update void Start() { Vector2 vect1 = new Vector2(1, 0); Vector2 vect2 = new Vector2(1, 1); Vector2 vect3 = new Vector2(-0.5f, -Mathf.Sqrt(3) / 2); Debug.Log("符号無し"); Debug.Log(Vector2.Angle(vect1, vect2)); Debug.Log(Vector2.Angle(vect2, vect1)); Debug.Log(Vector2.Angle(vect1, vect3)); Debug.Log("符号あり"); Debug.Log(Vector2.SignedAngle(vect1, vect2)); Debug.Log(Vector2.SignedAngle(vect2, vect1)); } }
実行結果
符号無し 45 45 120 符号あり 45 -45
ベクトルの大きさ
using UnityEngine; public class Vector2Sample4 : MonoBehaviour { // Start is called before the first frame update void Start() { Vector2 vect = new Vector2(3, 4); Debug.Log("大きさ:" + vect.magnitude); Debug.Log("大きさの2乗:" + vect.sqrMagnitude); } }
実行結果
大きさ:5 大きさの2乗:25
static変数
名前 | x座標 | y座標 |
---|---|---|
Vector2.right | 1 | 0 |
Vector2.up | 0 | 1 |
Vector2.left | -1 | 0 |
Vector2.down | 0 | -1 |
Vector2.zero | 0 | 0 |
位置ベクトル間の距離
using UnityEngine; public class Vector2Sample5 : MonoBehaviour { // Start is called before the first frame update void Start() { Vector2 vect1 = new Vector2(2, 4); Vector2 vect2 = Vector2.left; Debug.Log(Vector2.Distance(vect1, vect2)); } }
実行結果
5