Larger Raycast

Hi, i would like to have your inputs on a raycast subject.

I want my script to react aach time it’s facing an other objet. I use a raycast and it’s fine.

Now i would like it to also detect when the objet nearly in line with my player. Right now i’m ray casting more ray around my player axis. But I guess this very time consuming. And for small far away object it doesn’t always work. Do you have an idea on that ?

Best regards,

Yls

You could use Physics.SphereCast
Or you could raycast between the 2 objects and check the angle between them.

From what i interpret you want to know if your player is almost facing an object? If that is the issue then i would suggest to calculate the angle formed between the direction in wich the object is relative to the player and the player forward vector. the Mathf library has a function to do this but i don’t have acces to unity here to provide you with some code for it. Once you have that sorted out you can work with that angle value. 180 the object is behind, 0 in front, etc, etc.

I think ur answer is in math.

Consider 2 options:

raycast from the player forward. That ray returns a normal. Use Vector3.Dot(playerForward, raycast.Normal); This returns a value between 1 and -1. -1 would mean that the objects colliding face is perfectly aligned with the player. By accepting a -0.9 or less, you give a little give to it.

use Vector3.Dot(player.transform.InverseTransformPoint(object.transform.position).normalized, Vector3.forward); This again returns a value between 1 and -1. 1, in this case is in front of the player. adding a little slop (0.9 or greater) and you get a similar result.

Hi !

Thanks for your reply. I should have explain a little more.

The issue is that there is a lot ( around 100) of small objects and i would prefere not to test them all each time. Right now i’m raycasting a matrix 3*3 so 9 raycast and with your solution (which are more acurate) i have to perform 10 time more raycast.

I think that the Physics.SphereCast might be the best option.

Best regards,

Why not make a mesh collider that’s the shape you want to check against?

Yes Physics.SphereCast is best option and you can also check distance between two objects.

The AngryPenguin solution seems great. Do you think it’s more efficient ? It has a great advantage : I can make a pyramide shape so that the collision box gets larger with the distance. But testing a mesh collider may seems more time consuming isn’t it ?