LoginSignup
30
38

More than 5 years have passed since last update.

Unity Vectorを一通り理解する

Posted at

Unityが用意してくれているVectorをきちんと理解すれば開発も楽になるかなと思います。
リファレンスに載っているVectorを全部使って勉強します。
https://docs.unity3d.com/ja/current/ScriptReference/Vector3.html

Vector3概要

Vector3はクラスではなくStruct。UnityEngineネームスペースに存在している

コンストラクタ

全部で3つ
Vector3(float x, float y, float z)
=>普通にxyz変数に入れられる。

Vector3(float x, float y)
=>z変数には0fが入れられる。

定数

イプシロン

public const float kEpsilon = 1E-05f;

float比較のときに使用する。

プロパティ

normalizedプロパティ

ベクトルを正規化して返す。(ただしベクトル自体は変わらない)
get内でVector3.Normalize関数の演算結果を返している。

magnitudeプロパティ

ベクトルの長さ(ノルム)を返す。
get内でMathf.Sqrt(this.x * this.x + this.y * this.y + this.z * this.z);をやっているだけ。
処理負荷が高いのでなるべく使わない法が良い。

sqrMagnitudeプロパティ

magnitudeプロパティの平方根を求めないバージョン
少しでも処理負荷を下げようとして実装された。
単純に大きさの比較だけをやりたい時に使う。

zeroプロパティ

(0,0,0)のベクトルを返す。
get内でnew Vector3(0f, 0f, 0f);をやって新しいstructを使って返している。

one,foward,back,right,left,up,downプロパティ

zeroプロパティとほとんど同じ。xyz成分が違うだけ。

関数

Lerp(Vector3 a, Vector3 b, float t)

内部で
t = Mathf.Clamp01(t);をして01補正した後、2つのベクトルをleap処理して返す。
2つのベクトルの直線上を補完する。
12月-28-2016 18-49-32.gif

LerpUnclamped(Vector3 a, Vector3 b, float t)

Leap関数のtに対する01補正がないバージョン。

Slerp(Vector3 a, Vector3 b, float t)

球状に2つのベクトルが補完される点においてLeap関数と違う。
12月-28-2016 18-52-44.gif

SlerpUnclamped(Vector3 a, Vector3 b, float t)

Slerp関数のtの01補正がない関数

MoveTowards(Vector3 current, Vector3 target, float maxDistanceDelta)

currentからtargetに向かってcurrentを移動させる関数
currentとtargetの距離がmaxDistanceDelta以下ならtargetをそのまま返す。
maxDistanceDeltaを超えていたらcurrentからtarget方向に向かってmaxDisntaceDelta分進めたベクトルを返す。

Tips

Indexでxyzパラメータにアクセスできる

        Vector3 hoge = new Vector3(0, 1, 2);
        float x = hoge[0];
        float y = hoge[1];
        float z = hoge[2];

indexに0,1,2以外を入れるとエラーが起きるので注意。

30
38
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
30
38