facebook twitter hatena line email

Unity/3d/向き

提供: 初心者エンジニアの簡易メモ
2022年12月13日 (火) 04:45時点におけるAdmin (トーク | 投稿記録)による版 (こちらを向かせる)

移動: 案内検索

ターゲットの向きを向く

enemyObj.transform.LookAt(playerObj.transform);

こちらを向かせる

注意:負荷が高いかもなので、近くのオブジェクトだけとかの対応が必要かも。

全体処理を行うLookAtScene.cs

public class LookAtScene : MonoBehaviour
{
    [SerializeField] GameObject charaCubePrefab;
    [SerializeField] GameObject player;
    void Start()
    {
        for (int i = 0; i < 10; i++)
        {
            GameObject charaCube = Instantiate(charaCubePrefab);
            charaCube.transform.localPosition = new Vector3(1f * i - 2.5f, Random.RandomRange(-5f, 5f), Random.RandomRange(-1f, 1f));
            charaCube.GetComponent<CharaCubeController>().player = player;
        }
    }
}

CharaCubeのPrefabにつけたCharaCubeController.cs

public class CharaCubeController : MonoBehaviour
{
    public GameObject player;
    
    void Update()
    {
        var dir = transform.position - player.transform.position;
        var lookAtRotation = Quaternion.LookRotation(dir, Vector3.up);
        var offsetRotation = Quaternion.FromToRotation(Vector3.forward, Vector3.forward);
        transform.rotation = lookAtRotation * offsetRotation;
    }
}

参考:https://nekojara.city/unity-look-at

アバターにつけた名前をカメラに向ける

var dir = userNameText.transform.position - Camera.main.transform.position;
var lookAtRotation = Quaternion.LookRotation(dir, Vector3.up);
var offsetRotation = Quaternion.FromToRotation(Vector3.forward, Vector3.forward);
userNameText.transform.rotation = lookAtRotation * offsetRotation;