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