首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >来自NPC的Raycast

来自NPC的Raycast
EN

Stack Overflow用户
提问于 2020-04-03 20:27:12
回答 2查看 332关注 0票数 0

我有一个NPC在我的游戏,我需要他去发现球员的位置。我正试着用射线广播来达到这个目的。当球员在全国人大前面时,他就能察觉到他。这是一个3D战术RPG游戏。每个字符每次只能移动一个瓷砖。

然而,问题是,他无法察觉球员是在他的左,右,或身后。有什么办法可以改变光线投射角度吗?

我创建了这个协同线来使用全国人大的射线广播。我称之为开始方法中的协同线:

代码语言:javascript
复制
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");

        }
    }
EN

回答 2

Stack Overflow用户

发布于 2020-04-03 20:57:04

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

示例:

代码语言:javascript
复制
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
EN

Stack Overflow用户

发布于 2020-04-04 18:17:09

我找到了这个“解决方案”来解决我的问题,我不知道这是否是解决问题的最好方法,不过到目前为止它还在起作用:

代码语言:javascript
复制
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");
        }
    }

我把这个协同线称为开始方法中的协同线。如果在更新方法中调用它,会不会出错?

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61019892

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档