简体   繁体   English

Raycast 2d在Unity3d中不起作用

[英]Raycast 2d is not working in Unity3d

I'm new to Unity and blocked 2nd day with a simple try to raycast. 我是Unity新手,第二天尝试进行raycast封锁了第二天。 This is the script which I use to raycast: 这是我用来进行广播的脚本:

void Update () {
    Debug.DrawLine(transform.position, transform.position - transform.up);
    RaycastHit2D[] hits = Physics2D.RaycastAll(transform.position, transform.position - transform.up, Mathf.Infinity);
    if(hits.Length > 0)
    {
        Debug.Log("Hit");
    }
}

I have attached this script to a square and put near it another square which acts like a target, also added a 2d box collider to the target. 我已将此脚本附加到一个正方形上,并在其附近放置了另一个充当目标的正方形,并向目标添加了一个2d盒子碰撞器。 I have disabled the "hit itself" feature like is described here: http://answers.unity3d.com/questions/756380/raycast-ignore-itself.html After performing all this steps the raycast hits nothing, the collider of the hit object is always null (checked this in debug mode, also nothing is written in console) . 我禁用了“命中本身”功能,如下所述: http : //answers.unity3d.com/questions/756380/raycast-ignore-itself.html执行完所有这些步骤后,raycast不会命中任何东西,即命中的对撞机object始终为null(在调试模式下选中此选项,也未在控制台中写入任何内容)。 I drew a debug line, and indeed it points to the target square like in screenshots. 我画了一条调试线,实际上它指向屏幕截图中所指的目标方块。 在此处输入图片说明 在此处输入图片说明

Please help me figure out what I'm doing wrong. 请帮助我弄清楚我在做什么错。

Physics.Raycast is for 3D Colliders and this includes Box Collider, Sphere Collider and others. Physics.Raycast适用于3D碰撞机,其中包括Box Collider,Sphere Collider等。 No 2D in their names. 他们的名字中没有2D。

Physics2D.Raycast is for 2D colliders. Physics2D.Raycast适用于2D对撞机。 You need a Box Collider 2D since this is a Sprite Renderer which is a 2D Object. 您需要Box Collider 2D,因为这是2D对象的Sprite Renderer。

EDIT : 编辑

With your edit, the problem is that the direction of the raycast is too short. 在进行编辑时,问题在于光线投射的方向太短。 You have to multiply it by a number. 您必须将其乘以一个数字。 The value of 100 should be fine. 值100应该可以。

public float distance = 100f;

void Update()
{
    Debug.DrawLine(transform.position, transform.position + transform.right);
    RaycastHit2D hit = Physics2D.Raycast(transform.position, transform.position + transform.right * distance, Mathf.Infinity);
    if (hit.collider != null)
    {
        Debug.Log("hit: " + hit.collider.name);
    }
}

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

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