【问题标题】:How can I make a GameObject point towards another GameObject in Unity?如何在 Unity 中将游戏对象指向另一个游戏对象?
【发布时间】:2019-06-12 20:41:41
【问题描述】:

我试过这段代码,但它不能正常工作。 编辑:LookAt 使 GameObject 不可见

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 makes the GameObject invisible ...你是什么意思?它只旋转对象......它是否可能由于背面剔除而变得“不可见”?
  • .@DanHasAPan EnemyPoint 附加到什么样的对象上?另外,你能编辑这个问题并在LookAt“使游戏对象不可见”的地方包含你正在使用的代码吗?

标签: c# unity3d


【解决方案1】:

您可以使用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);

【讨论】:

  • Wait 不是在相机中使用 LookAt 吗?
  • @DanHasAPan 是的,LookAt 可用于任何Transform。相机确实有一个,但EnemyPoint 附加到的 GameObject 也有。
【解决方案2】:

这个线程很老了,但我认为我可能只是投入其中。在第 13 行中,您使用了错误的触发函数。使用 Mathf.Atan2(y, x) 产生的反正切 y/x 在 -π 到 +π 的范围内,相反,您使用的是 Mathf.Atan(y),它只基于 y only 进行计算并且不考虑还要考虑 x 值。

float rotZ = Mathf.Atan2(difference.y, difference.x) * Mathf.Rad2Deg //Get arctangential of x and y and turn it into degrees with 180/π 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-18
    相关资源
    最近更新 更多