コガネブログ

平日更新を目標に Unity や C#、Visual Studio、ReSharper などのゲーム開発アレコレを書いていきます

【Unity】マウスの方向に自機を向ける

ソースコード

using UnityEngine;

public class Player : MonoBehaviour
{
    private void Update()
    {
        var screenPos = Camera.main.WorldToScreenPoint( transform.position );
        var direction = Input.mousePosition - screenPos;
        var angle = GetAim( Vector3.zero, direction );
        transform.SetLocalEulerAnglesY( -angle + 90 );
    }

    public float GetAim( Vector2 from, Vector2 to )
    {
        float dx = to.x - from.x;
        float dy = to.y - from.y;
        float rad = Mathf.Atan2(dy, dx);
        return rad * Mathf.Rad2Deg;
    }
}

使用例

f:id:baba_s:20171130114919g:plain

参考サイト様