【问题标题】:Detect if enemy is facing Player检测敌人是否面向玩家
【发布时间】:2015-05-16 05:00:55
【问题描述】:

我正在制作一个游戏,如果距离小于 2 并且敌人面向玩家,文本会出现重新启动选项。在更新中有一个 if 和 else 语句应该检测敌人是在玩家后面还是前面。然而,一旦距离小于 2,无论玩家是否面向 npc,似乎都会调用 in front 选项。

这个脚本附在敌人身上:

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);
}

}

【问题讨论】:

    标签: c# unity3d transform distance


    【解决方案1】:

    首先,您缺少一些括号,其次是 stra DistanceDeathcall,这是您的函数 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,还有一个DistanceDeath我刚刚看到,第二行
    • 这行得通,删除了第二个 DistanceDeath() ,感谢一百万
    猜你喜欢
    • 2021-04-11
    • 1970-01-01
    • 2016-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多