简体   繁体   English

Raycast无法检测到击中对象统一C#2d

[英]Raycast doesn't detect hitting object unity C# 2d

Quite new to Unity and I've been playing around with Raycasting the past few days. 对Unity来说还挺新的,过去几天我一直在玩Raycasting。 I have run into this problem where the line that the raycast is meant to represent is not detecting that this has happened. 我遇到了一个问题,射线广播本应代表的那一行没有检测到这已经发生。 So when the Raycast line hit the object I want it to simply display HIT onto the console to show that this is working. 因此,当Raycast线碰到对象时,我希望它仅将HIT显示在控制台上以表明它正在工作。 I have a feeling that the reason it isn't working is due to the fact that the line I'm seeing through debug and the line that is actually being used different. 我感觉它不起作用的原因是由于我通过调试看到的行与实际使用的行不同。

The code is: 代码是:

void rayCast()
    {
        if (player.transform.position.x <= enemy.transform.position.x)
        {
            RaycastHit2D hitLeft = Physics2D.Raycast(transform.position, -transform.right, rayDistance, 1 << LayerMask.NameToLayer("Player"));
            Vector3 left = transform.TransformDirection(Vector3.left);
            Debug.DrawRay(transform.position, left * rayDistance, Color.green);

            if (hitLeft.collider != null)
            {
                Debug.Log("Player is within range");
            }
            else
            {
                Debug.Log("out of range");
            }
        }


        if (player.transform.position.x >= enemy.transform.position.x)
        {
            RaycastHit2D hitRight = Physics2D.Raycast(transform.position, transform.right, rayDistance, 1 << LayerMask.NameToLayer("Player"));
            Vector3 right = transform.TransformDirection(Vector3.right);
            Debug.DrawRay(transform.position, right * rayDistance, Color.green);

            if (hitRight.collider != null)
            {
                Debug.Log("Player is within range");
            }
            else
            {
                Debug.Log("out of range");
            }
        }
    }

Thank you in advance for any help. 预先感谢您的任何帮助。

Problem is here: 问题在这里:

RaycastHit2D hit = Physics2D.Raycast(transform.position, transform.right, rayDistance, 1 << LayerMask.NameToLayer("Player"));

It looks like you always raycast to the right. 看起来您总是向右光线投射。 You probably want it to switch left and right, like you do when you're drawing your line. 您可能希望它像在画线时一样左右切换。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM