4
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Unity 2Dで敵の方向を向く

Last updated at Posted at 2021-05-26

##1.0 目的
Unity 2Dでゲームを作る際に、オブジェクトを敵など特定のオブジェクトの方向を向かせるための方法です。(下の画像のような)
いろいろな方法があると思いますが、1番シンプルだと思える方法を忘備録として記事します。
今回はスクリプトで実装していきます。

##2.0 Unity 3Dでは
3DではLookAt関数があり、この関数を使うと、簡単に指定したオブジェクトへ方向を変えることができます。

##3.0 Quaternionクラス
Unityでは回転を取り扱うためのQuaternion(クォータニオン)というクラスが準備されています。

##4.0 FromToRotation関数
QuaternionクラスにFromToRotation関数があります。引数はVector3の fromDirection(向いている方向から) と toDirection(向きたい方向)です。fromDirection から toDirection への回転を作成できます。
通常、ワールド空間で Transform を回転させ、座標の 1 つ、例えば、y 座標をターゲットの方向 toDirection に向かせるために使用します。

##5.0 C#スクリプト
ではスクリプトです。

RotationTest.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class RotationTest : MonoBehaviour
{
    public Transform arrowTrans // 動かすオブジェクトのトランスフォーム
    public Transform ballTrans // ターゲットのオブジェクトのトランスフォーム

    // 向きたい方向を計算
    Vector3 dir = (ballTrans.position - arrowTrans.position);

    // ここで向きたい方向に回転させてます
    arrowTrans .rotation = Quaternion.FromToRotation(Vector3.up, dir)
}

Vector3.upはVector3(x, y, z) = (0, 1, 0)と同じです。シンプルにオブジェクトの上方向を表しています。
これで目的の方向に向くようになります。
注)下図のようにリアルタイムに方向を変えるためにはUpdate関数などで連続処理が必要になります。

GIF 2021-05-26 13-46-42.gif

4
0
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
4
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?