首页 > 解决方案 > Unity:敌人检查前的玩家不起作用,Physics.Raycast?

问题描述

这个游戏场景有两个用例,如下:

玩家无法被敌人看到:

在此处输入图像描述

玩家可以被敌人看到:

在此处输入图像描述

我正在使用以下代码来决定玩家和敌人之间的视线是否清晰,敌人可以攻击,即只有在玩家和敌人之间没有墙壁或任何其他碰撞器时,敌人才应该攻击:

    void playerInRangeOfEnemy()
        {
            // After checking player is in range of the enemy, check for the line of vision between them
            Transform Player = FindObjectOfType<Player>().transform;
            Vector2 rayDirection = Player.position - transform.position; // --> transform.position is of the enemy
            RaycastHit hit;
            if(Physics.Raycast(transform.position, rayDirection, out hit, minAttackDistance))
            {        
                Debug.Log("Ray hitting the player"); // Not logging in either of the two cases mentioned above
                if (hit.collider.gameObject.CompareTag("Player"))
                {
                    // The following line is also not being logged
                    Debug.Log("Make the enemy attack the player");
                }
            }
        }

敌人和玩家都是动态刚体。minAttackDistance只是我要投射的光线投射的长度,现在设置为 100 以进行测试。

如何使条件为真以便执行两个日志?上面的代码有什么更新吗?

标签: unity3d

解决方案


您使用的是 3d 物理而不是 2d。请改用 Physics2D.Raycast。


推荐阅读