facebook twitter hatena line email

「Unity/3d/向き」の版間の差分

提供: 初心者エンジニアの簡易メモ
移動: 案内検索
(ページの作成:「==ターゲットの向きを向く== enemyObj.transform.LookAt(playerObj.transform);」)
 
(ターゲットの向きを向く)
行1: 行1:
 
==ターゲットの向きを向く==
 
==ターゲットの向きを向く==
 
  enemyObj.transform.LookAt(playerObj.transform);
 
  enemyObj.transform.LookAt(playerObj.transform);
 +
 +
==こちらを向かせる==
 +
全体処理を行うLookAtScene.cs
 +
<pre>
 +
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;
 +
        }
 +
    }
 +
}
 +
</pre>
 +
CharaCubeのPrefabにつけたCharaCubeController.cs
 +
<pre>
 +
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;
 +
    }
 +
}
 +
</pre>
 +
参考:https://nekojara.city/unity-look-at

2022年11月23日 (水) 04:41時点における版

ターゲットの向きを向く

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