通过复制玩家位置来跟随玩家的幽灵敌人 AI

时间:2020-12-28 19:29:07

标签: c# arrays unity3d queue position

好的,计划很简单。 我的计划是制作一个简单的 AI 来记录每个玩家的位置,然后使用这些位置跟随玩家。所以AI总是会落后玩家几步。但是当玩家停止移动时,AI 应该会与玩家发生碰撞,然后玩家就会死亡。

所以我的问题是当玩家被 AI 追赶时,它总是在敌人 AI 能够接触到玩家之前失去位置......

我使用Queue来制作位置列表,这是我尝试使用List<>后有人推荐的。 Here's a video showing the problem

 public Transform player;
public Transform ghostAI;

public bool recording;
public bool playing;
Queue<Vector2> playerPositions;

public bool playerLeftRadius;




void Start()
{
    playerPositions = new Queue<Vector2>();

}

// Update is called once per frame
void Update()
{

    if (playerLeftRadius == true)
    {
        StartGhost();
    }

    Debug.Log(playerPositions.Count);


}

private void FixedUpdate()
{
    if (playing == true)
    {
        PlayGhost();
    }
    else
    {
        Record();
    }
}


void Record()
{
    recording = true;
    playerPositions.Enqueue(player.transform.position);
}

void PlayGhost()
{

    ghostAI.transform.position = playerPositions.Dequeue();       
    
    
}

public void StartGhost()
{
    playing = true;
}

public void StopGhost()
{
    playing = false;
}


private void OnTriggerExit2D(Collider2D other)
{
    Debug.Log("Player leaved the zone");
    playerLeftRadius = true;

}

如何改进它以使其能够触摸玩家?

1 个答案:

答案 0 :(得分:0)

在玩家触摸区域的那一刻,方法 OnTriggerExit2D() 被调用。然后,调用方法 PlayGhost() 并停止 Record()。因此,在玩家离开区域后,幽灵无法记录玩家位置。 您可以在方法 else 中删除 FixedUpdate() 以修复它。

private void FixedUpdate()
{
    if (playing == true)
    {
        PlayGhost();
    }
    Record();
}