オブジェクトのマウスカーソル追尾
Quaternion.Euler / Vector2.Lerp / Mathf.Atan2
マウスカーソル(四角のターゲットサイト)をミサイルが追尾する。また、ミサイルの向きはターゲットサイトを向くような処理を行う。 以下にコードを示す
public class BulletController : MonoBehaviour { // GameControllerオブジェクト情報 private GameObject GMcontrollerObj { get; set; } = default; // サイトのマウスカーソルへの追従補正(0.0 ~ 1.0 大きいほど追従が早い)Vector2.Lerpの第三引数 private float BulletComp { get; set; } = 0.1f; // Start is called before the first frame update void Start() { GMcontrollerObj = GameObject.Find("GMcontroller"); } // Update is called once per frame void Update() { // マウスポインタのワールド座標を取得 Vector2 mousePosWorld = GMcontrollerObj.GetComponent<GMcontroller>().GetMousePositionWorld(); // Bulletオブジェクト(ミサイル)の座標を取得(ワールド座標) Vector2 bulletPosWorld = this.transform.position; // マウスポインタ・Bulletオブジェクトの位置関係を算出 float x = mousePosWorld.x - bulletPosWorld.x; float y = mousePosWorld.y - bulletPosWorld.y; // Bulletオブジェクトから見たマウスポインタの角度を求める(ラジアン) float rad = Mathf.Atan2(y, x); // ラジアンを弧度法に変換(3時方向を0度として反時計回りに+、時計回り方向に-) float deg = rad * Mathf.Rad2Deg; // オブジェクトをZ軸上で回転させる this.transform.rotation = Quaternion.Euler(0, 0, deg); // 線形補正を使用してマウスポインタ方向へ移動 this.transform.position = Vector2.Lerp(this.transform.position, mousePosWorld, BulletComp); }
29行でオブジェクトミサイルの角度を変更するが、角度は3時方向を0度として反時計回りに+180度まで、時計回りに-180度までとしてあらわされるため、オブジェクトは進行方向(ミサイルなら先端)を3時方向にしたスプライト画像である必要がある。
マウスカーソル(四角のターゲットサイト)をミサイルが追従する画像