简体   繁体   中英

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.

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. 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.

    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.

Here is what it looks like when i draw the Raycast in red , and the reflected vector in green . 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.

Second parameter of Raycast function is the direction so it should probably be:

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

or you wanted to use

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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