[英]how can i make a gameobject always face towards a certain other gameobject and move towards it?
[英]How can I make a GameObject point towards another GameObject in Unity?
我試過這段代碼,但它不能正常工作。 編輯:LookAt 使游戲對象不可見
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyPoint : MonoBehaviour {
public float offset;
public Transform target;
private void Update()
{
Vector2 difference = target.position - transform.position;
float rotZ = Mathf.Atan(difference.y) * Mathf.Rad2Deg;
transform.rotation = Quaternion.Euler(0f, 0f, rotZ + offset);
}
}
您可以使用LookAt 。
旋轉變換,使
forward
向量指向target
的當前位置。
transform.LookAt(target);
只需將它放在您的 objectA 上,然后在target
字段中拖放任何其他 objectB → objectA 的forward
向量將始終指向objectB
。
另一種覆蓋也將世界位置作為Vector3
代替,因此您也可以使用
transform.LookAt(target.position);
這基本上會做完全相同的事情。
如果您需要另一個指向目標的軸,您仍然可以使用LookAt
,然后使用Rotate
。 例如,為了不使物體的forward
而是up
矢量指向目標,您可以使用
transform.LookAt(target);
transform.Rotate(Vector3.right * 90);
這個線程已經很老了,但我想我可能只是投入。在第 13 行中,您使用了錯誤的觸發函數。 使用Mathf.Atan2(y, x)
產生 -π 到 +π 范圍內的反正切 y/x,相反,您使用的是Mathf.Atan(y)
,它僅基於y 進行計算,而不需要還要考慮 x 值。
float rotZ = Mathf.Atan2(difference.y, difference.x) * Mathf.Rad2Deg //Get arctangential of x and y and turn it into degrees with 180/π
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.