Unity/3d/向き
提供: 初心者エンジニアの簡易メモ
ターゲットの向きを向く
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; } }