检测敌人是否面对玩家

3
我正在制作一款游戏,如果距离小于2并且敌人面对玩家,则会出现一个带有重新开始选项的文本。在更新中,if和else语句应该检测敌人是否在玩家前面或后面。但是,无论玩家是否面向npc,在距离小于2时似乎总是调用前方选项。
此脚本附加到敌人身上。
using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public class EnemyFollow : MonoBehaviour {

Transform player; 
Transform enemy; 
public GameObject EnemyCaughtCam;
public Text SheCaughtYou;
public GameObject Restart;

public float Speed = 3f;
public float rotS = 3f;
public float sT = 3f;
NavMeshAgent nav;
float timeTillOptionsMenu = 3.0f;

// Use this for initialization
void Awake() {
    player = GameObject.FindGameObjectWithTag ("MainCamera").transform;
    //enemy = GameObject.FindGameObjectWithTag ("Enemy").transform;
    nav = GetComponent<NavMeshAgent> ();
    EnemyCaughtCam.SetActive(false);
    SheCaughtYou.text = "";
}

// Update is called once per frame
void Update () {
    nav.SetDestination (player.position);
    DistanceDeath();

    if (npcIsFacingPlayer (player)&& !playerIsFacingNpc(player))
        print ("Behind");
    else if (npcIsFacingPlayer (player)&& playerIsFacingNpc(player))
        print ("In Front");
        DistanceDeath ();
}

public void DistanceDeath(){

    float distance = Vector3.Distance(player.transform.position, 
        transform.position);              


    if (distance < 2 ){

        EnemyCaughtCam.SetActive(true);
        SheCaughtYou.text = "SHE CAUGHT YOU!";

        timeTillOptionsMenu -= Time.deltaTime;
        if(timeTillOptionsMenu < 0)
        {
            Restart.SetActive(true);

        }


    }

}

public bool npcIsFacingPlayer(Transform other)
{
    Vector3 toOther =
    other.position - transform.position;
    return (Vector3.Dot(toOther, transform.forward) > 0);
}
public bool playerIsFacingNpc(Transform other)
{
    Vector3 toOther =
    transform.position - other.position;
    return (Vector3.Dot(toOther, other.forward) > 0);
}

}
1个回答

1

首先,你缺少一些括号,其次在调用 DistanceDeath 函数时有一个错别字。下面是如何读取你的函数 Update

// Update is called once per frame
void Update () {
    nav.SetDestination (player.position);

    /** what does the call do here? */
    DistanceDeath(); 

    if (npcIsFacingPlayer (player)&& !playerIsFacingNpc(player))
        print ("Behind");
    else if (npcIsFacingPlayer (player)&& playerIsFacingNpc(player))
        print ("In Front");

    /** are you missing brackets here? Distance Death is always called */
    DistanceDeath (); 
}

谢谢你,但不幸的是,当我添加它们时,它仍然调用了距离死亡函数,我认为这可能与语句本身的逻辑有关,但无法弄清楚。 - Cdalyz
@Cdalyz,好的,我刚刚看到另一个DistanceDeath,在第二行。 - martin
这个有用,移除了第二个 DistanceDeath() ,非常感谢。 - Cdalyz

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接