NPC的广播

问题描述 投票:-1回答:2

我的游戏中有一个NPC,我需要他来检测玩家的位置。我正在尝试为此目的使用射线广播。当玩家在NPC面前时,他可以检测到他。这是一款3D战术RPG游戏。每个角色每回合只能移动一个图块。

但是,问题是他无法检测到玩家在他的左侧,右侧还是身后。有什么方法可以改变光线投射角度吗?

我创建了这个协程以使用NPC的射线广播。我在Start方法中将此协程称为:

ienumerator detectplayer()
    {
        yield return new waitforseconds(1f);

        ray ray = new ray();
        raycasthit hit;

        ray.origin = transform.position + transform.forward;
        ray.direction = transform.forward;

        vector3 foward = transform.transformdirection(vector3.forward) * 10;

        float duration = 15f;

        debug.drawray(ray.origin, foward, color.red, duration);

        if (physics.raycast(ray, out hit))
        {
            print("the game object" + hit.collider.gameobject.name + "is in front of the npc");

        }
    }
c# unity3d
2个回答
0
投票

我猜您正在使用Unity?在这种情况下,您可以使用Physics.OverlapSphere并检查播放器的对撞机]

示例:

Collider[] colliders = Physics.OverlapSphere(NPC.transform.position, HOW FAR THE NPC CAN SEE);
for(int i = 0; i < colliders.length; i++){
  if(colliders[i].gameObject.tag == "player"){
    //DO SOMETHING
  }
}

0
投票

我已经为我的问题找到了这个“解决方案”,我不知道这是否是解决问题的最佳方法,但是到目前为止,它仍然有效:

IEnumerator DetectPlayer()
    {
        yield return new WaitForSeconds(1f);

        Ray frontRay = new Ray();
        RaycastHit hit;

        frontRay.origin = transform.position + transform.forward;
        frontRay.direction =  transform.forward;

        Vector3 foward = transform.TransformDirection(Vector3.forward) * 10;
        float duration = 15f;
        Debug.DrawRay(frontRay.origin, foward, Color.red, duration);

        if (Physics.Raycast(frontRay, out hit))
        {
            print("The game object " + hit.collider.gameObject.name + "is in front of the npc");
        }

        if(Physics.Raycast(transform.position,-transform.right,out hit))
        {
            print("The game object " + hit.collider.gameObject.name + " is on the right of the npc");
        }

        if(Physics.Raycast(transform.position, transform.right,out hit))
        {
            print("The game object " + hit.collider.gameObject.name + " is on the left of the npc");
        }

        if(Physics.Raycast(transform.position, -transform.forward,out hit))
        {
            print("The game object " + hit.collider.gameObject.name + " is behind the npc");
        }
    }

我在Start方法中将此协程称为内部。如果在Update方法中调用它会出错吗?

© www.soinside.com 2019 - 2024. All rights reserved.