首页 > 解决方案 > 如何在 Ray 的帮助下定位 GameObject?

问题描述

对于我的基于网格的游戏,我希望敌人拥有玩家可见的视线。敌人只能朝一个方向(上、下、左或右)看,一旦设定,他们就不会改变那个方向。

敌人无法透过障碍物或其他敌人,这就是我设置 Raycast 的原因。此 Raycast 检测玩家是否在与敌人方向一致的直线上。
这是我的 EnemySight 脚本:

PathFollower pathFollower;

    public GameObject sightline;
    public GameObject player;

    float rayLength = 20f;

    bool onSameZAxis = false;

    Ray myRay;
    RaycastHit hit;

    void Start()
    {
        GameObject g = GameObject.Find("Path");
        pathFollower = g.GetComponent<PathFollower>();

    }

    void Update()
    {
        DrawRay();

        if (player.transform.position.z.Equals(transform.position.z) && pathFollower.hasCheckedAxis == false)
        {
            onSameZAxis = true;
        }
        else { onSameZAxis = false; }

        //checks only when enemy stands still if the player is in sight and on same axis
        if (onSameZAxis == true && pathFollower.standsStill == true && PlayerInSight() == true)
        {
            Debug.Log("spotted");
            pathFollower.sawPlayer = true;
            pathFollower.hasCheckedAxis = true;
            //onSameZAxis = false;
            //Debug.Log("In the If-Loop");

        }

    }


    //checks if there is a wall between the player and the enemy
    bool PlayerInSight()
    {
        myRay = new Ray(transform.position + new Vector3(0, 0.15f, 0), -transform.right);

        Debug.DrawRay(myRay.origin, myRay.direction, Color.red);

        if (Physics.Raycast(myRay, out hit, rayLength))
        {
            if (hit.collider.tag == "Player")
            {
                return true;
            }
        }
        return false;
    }

    void DrawRay()
    {
        //Moves the Sightline Object.
    }
}

我已将 Sightline GameObject 设为相应敌人的子对象,因此它与敌人一起移动。问题是它会穿过障碍物和敌人,尽管那时不会检测到玩家。

我正在考虑将我的 Sightline GameObject 的轴心点移动到 Raycast 的 Vector 3 命中,但我不知道这如何工作。

我很高兴有任何建议或解决方案,在此先感谢您!

标签: c#unity3d

解决方案


推荐阅读