【问题标题】:OverlapCircle won't find playerOverlapCircle 找不到玩家
【发布时间】:2020-05-17 15:47:07
【问题描述】:

我一直在尝试让我正在研究的游戏的 NPC 能够在玩家靠近时“感知”。我制作了这个脚本,由于未知的原因,布尔“找到”保持为假,当我自动将其设置为真时,它恢复为假(它仍然将玩家位置发送到 goTo 脚本,所以至少作品)。有谁知道如何解决这个问题?

public class NPCLookForPlayerScript : MonoBehaviour {

public bool found;    //player found
public float awareness;   //how large is the circlecast
public int keepLooking; //for how much time, after losing sight of the player, he tries to keep on looking for him
public GameObject player;  //variable to lock on to the player
int timer;    //variable to decrement while player isn't in line of sight

NPCGoToScript goTo;

// Use this for initialization
void Start () {
    goTo = GetComponent<NPCGoToScript>();
}

// Update is called once per frame
void Update () {
    //he's always looking for the player
    Collider2D coll = Physics2D.OverlapCircle((Vector2)transform.position, awareness);

    //if the player is found, keep looking for him
    if (coll.gameObject == player)
    {
        found = true;
        timer = keepLooking;
    }

    //if the player was found, 
    if (found)
    {
        timer = timer - 1;    //less time to look for the player
        goTo.newPosition(player.transform.position);
    }

    //if the player is out of sight for too much time, stop looking for him
    if (timer <= 0)
    {
        found = false;
    }
}

void OnDrawGizmos()
{
    Gizmos.color = Color.green;

    Gizmos.DrawWireSphere((Vector2)transform.position, awareness);
}

}

由于有人让我注意到变量的值没有写在代码中,让我明确一点:我正在研究统一,这个脚本有公共值可以由检查器修改,即非常有用,因为此脚本必须用于不同类型的 NPC。所以值不为零。意识 = 5f 和 keepLo​​oking = 20。玩家字段确实有玩家游戏对象。

【问题讨论】:

  • 你确定你没有检测到自己吗?或者,您似乎在将 collider2d 与游戏对象进行比较?
  • @BugFinder 肯定的,我已经尝试过很多次走出圆圈的半径,但检查员总是显示 found=false
  • @BugFinder 好的,我明白了你的意思,如果 (coll==player) 错了,我更正了它,但它仍然无法正常工作
  • 然后是时候做一些调试日志了。您的重叠圆可能会捡起其他东西并将其返回给您-让它打印出它所击中的东西..然后,将其更改为蒙版以仅捡起玩家,或者,使用重叠圆并检查其中一件事是否是一名球员..
  • @BugFinder 您能否向我解释一下如何使用overlapcircleall 并检查其中一个碰撞是否是玩家?我以前试过这样做,但代码太重了。感谢您的帮助

标签: c# unity3d


【解决方案1】:

您永远不会为任何字段设置初始值:)。

timer 已声明但从未设置为任何值,因此它基本上等于 0。此外,awareness(您的半径)也从未设置,默认情况下为 0.0f。

所以你的代码...

  1. 执行半径为零的Physics2D.OverlapCircle(即没有圆)

  2. 跳过coll == player语句中的逻辑,因为没有圆与玩家发生碰撞。

  3. 跳过found语句中的逻辑导致发现为假

  4. 然后执行timer &lt;= 0语句中的逻辑,导致timer为0(从未定义)

  5. 继续将 found 设置为 false 每一帧,永远永远,直到漫长的晚安

只有当您在检查器中手动将 found 设置为 true 时,才会发生获取转换数据的播放器,然后只有一帧会导致它在下一个语句中恢复为 false。

您需要为您的字段提供大于 0 的值。

【讨论】:

  • 它们没有在代码中设置,因为我必须为每个 npc 使用不同的值,所以我直接在 inspetor 中统一设置它们。意识的值为 5f,而 keepLo​​oking 的值为 20
猜你喜欢
  • 1970-01-01
  • 2019-09-17
  • 2022-10-24
  • 1970-01-01
  • 2016-10-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-19
相关资源
最近更新 更多