LoginSignup
17
13

More than 5 years have passed since last update.

Unityのvelocity(速度)変更処理の詳細

Last updated at Posted at 2014-06-15

よく下記ようなコードで速度を与えるというものが出てくるが、内部では何が行われているのか。

例として、右(right)に向かう場合。

rigidbody2D.velocity = transform.right.normalized * 2.0f;

transform.right (Transform#right)

これは、Vector.3.rightメソッドに、自身の回転を加えたものを返す。
Vector3.rightは回転角無しの右向きのVector3インスタンスなので、それを自身の向きに変換する必要がある。

right
public Vector3 right
{
    get
    {
        return this.rotation * Vector3.right;
    }
  …
}

ちなみに、Vector3.rightはxに1fを設定したVector3のインスタンス。

right
public static Vector3 right
{
    get
    {
        return new Vector3 (1f, 0f, 0f);
    }
}

transform.right.normalized (Vector3#normalized)


public Vector3 normalized
{
    get
    {
        return Vector3.Normalize (this);
    }
}

自身のベクトルから単位ベクトル(長さが1のベクトル)を作成している。
Vector3のNormalizeメソッドに自身を引数としている。

Normalize

public static Vector3 Normalize (Vector3 value)
{
    float num = Vector3.Magnitude (value);
    if (num > 1E-05f)
    {
        return value / num;
    }
    return Vector3.zero;
}

ちなみに、Magnitudeの実装。自身を引数とした平方根を算出。

Normalize
public static float Magnitude (Vector3 a)
{
    return Mathf.Sqrt (a.x * a.x + a.y * a.y + a.z * a.z);
}

transform.right.normalized * 「スピード」 (Vector3 #operator *)

最後にtransform.right.normalized * -0.8f;
の「* 2.0f」の部分。


operator *

public static Vector3 operator * (Vector3 a, float d)
{
    return new Vector3 (a.x * d, a.y * d, a.z * d);
}


ここまでで作成された長さ1のベクトルに指定数を掛け合わせたVector3のインスタンスが作成される。

まとめ

と、こんな感じの一通りの処理。
まとめると、

  • 指定の向きベクトルを作成
  • 自身の回転を加算
  • 長さ1の単位ベクトルに変換
  • スピードを掛け合わせる

です。

17
13
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
17
13