Quantcast
Viewing all articles
Browse latest Browse all 8905

Unityで2つのベクトルの向きが同じになるように回転させる

はじめに

Unityでスクリプトからオブジェクトを回転させるときに
そのオブジェクトが持つベクトルとあるベクトルの向きを同じになるように回転させました。
たまに使うので備忘録です。

サンプルコードとイメージ図

VectorRotationSample.cs
// Vector3 p1, p2, p3, p4;// GameObject target;Vector3refVec=(p1-p2).normalized;// これと同じになるようにVector3vec=(p3-p4).normalized;// これを動かす(p3, p4はtargetに含まれる任意の2点)Quaternionrot=Quaternion.FromToRotation(refVec,vec);target.transform.rotation=rot*target.transform.rotation;// 左から掛ける

Image may be NSFW.
Clik here to view.
image.png

p3とp4のベクトルの向きがp1とp2のベクトルの向きに合うようにp3とp4を持つオブジェクトを回転させています。

使用例

こんな感じの用途に使いました。
右手と左手間のベクトルに合うようにコントローラを回転させています


Viewing all articles
Browse latest Browse all 8905

Trending Articles