【问题标题】:Why the value Vector3.Distance return become bigger when two object close to each other为什么当两个对象彼此靠近时,Vector3.Distance 返回的值会变大
【发布时间】:2019-09-21 12:24:30
【问题描述】:

正如标题所说,我使用 Vector3.Distance 来获取两个对象的距离,比如敌人追逐玩家, 而且我发现即使是敌人“抓住”了玩家,两个物体也很接近,我的意思是它们都在同一个位置,相互重叠,但是这个api返回的值不是我想象的那样,值保持在0附近一段时间,然后它开始变得越来越大。 我想知道是否有什么理由解释这一点,这很奇怪。

我使用 NavMeshAgent 将“player.transform.position”设置为目的地。

enter image description here

另一张图片: enter image description here

public override void Reason(GameObject player, GameObject npc)
{
    NPCControl npcControl = npc.GetComponent<NPCControl>();
    float distance = Vector3.Distance(npc.transform.position, player.transform.position);

    Vector3 Ppos = player.transform.position;
    Debug.Log("P(" + Ppos.x + ", " + Ppos.y + ", " + Ppos.z + ")");
    Vector3 Epos = npc.transform.position;
    Debug.LogWarning("E(" + Epos.x + ", " + Epos.y + ", " + Epos.z + ")");
    float Dst = Vector3.Distance(Ppos, Epos);
    Debug.LogError("P-E(" + Dst + ")");
}

解决方法: 我更改了如下代码部分,出现此问题的原因仍然需要深入挖掘。

Vector3 from = new Vector3(npc.transform.position.x, 0f, npc.transform.position.z);
    Vector3 to = new Vector3(player.transform.position.x, 0f, player.transform.position.z);
    float distance = Vector3.Distance(from, to);

【问题讨论】:

  • 这没什么好说的,你能把值贴出来吗?
  • 可能是因为您没有传入正确的值或使用不正确.. 没有看到您的代码很难分辨
  • 我发布了价值。似乎敌人的位置。y一直在变化
  • 如果你在做 2d 游戏,最好使用 Vector2.Distance。

标签: unity3d


【解决方案1】:

你可以尝试的是:

在下面的 2 个公共变量中分配您想要的 2 个对象之间的距离

public GameObject Object1;
public GameObject Object2

private float distance;

void Update()
{
    distance = Vector3.Distance(Object1.transform.position, Object2.transform.position);
    Debug.Log(distance);
}

这似乎是最简单有效的方法。

【讨论】:

    猜你喜欢
    • 2012-11-11
    • 2019-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-03
    • 2013-02-16
    • 1970-01-01
    相关资源
    最近更新 更多