简体   繁体   English

Unity Raycast 未能命中

[英]Unity Raycast failing to hit

I've been working on a school project for some time, and I wanted to create a bouncing projectile.我从事学校项目已有一段时间了,我想创建一个弹跳弹丸。 Now, since in the course we mainly learned to use OnTriggerEnter, thats what I've been using instead of a more suitable OnCollisionEnter.现在,由于在课程中我们主要学习使用 OnTriggerEnter,所以我一直在使用它,而不是更合适的 OnCollisionEnter。

That said, the code actually works fine in some instances, while in others the Raycast doesnt hit it's target, even if it's the exact same object.也就是说,代码在某些情况下实际上可以正常工作,而在其他情况下,Raycast 不会击中它的目标,即使它是完全相同的对象。 Here it's the code I've been using to get the normal of the object and then to turn the projectile into the required direction.这是我用来获取物体法线然后将弹丸转向所需方向的代码。 This is run in a script called Projectile.cs, as a component of a projectile with Is Trigger checked.这是在名为 Projectile.cs 的脚本中运行的,作为选中 Is Trigger 的弹丸的一个组件。

    private void OnTriggerEnter(Collider other)
    {
        ...
        RaycastHit hit;
        Physics.Raycast(transform.position, other.ClosestPoint(transform.position), out hit);
        Vector3 r = Vector3.Reflect(transform.forward, hit.normal);
        transform.forward = r;
        ...
    }

I also used to do the Raycast in an if statement, but I deleted it to debug the code.我也曾经在 if 语句中进行 Raycast,但我删除了它以调试代码。

Here is what it looks like when i draw the Raycast in red , and the reflected vector in green .是我用红色绘制 Raycast 和绿色反射矢量时的样子。 If I shoot to the ground (in this case a stretched cube) the Raycast doesn't hit, if I shoot to a wall (still a stretched cube) from one side it works just fine, while if I shoot to the other side the Raycast doesnt hit.如果我向地面射击(在这种情况下是拉伸的立方体),Raycast 不会击中,如果我从一侧射击到墙壁(仍然是拉伸的立方体),它工作得很好,而如果我向另一侧射击Raycast 没有命中。

Second parameter of Raycast function is the direction so it should probably be: Raycast 函数的第二个参数是方向,所以它应该是:

other.ClosestPoint(transform.position) - transform.position;

or you wanted to use或者你想使用

Physics.Linecast(Vector3 startPosition, Vector3 endPosition, out RaycastHit hitInfo);

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

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