Raycast hit
Hi everyone.
Simply I wanted to know if its possible to detect ( and chose) raycast hit to the object 90 degree..
In my project my raycast can hit with different angles i will share a picture and you will understand better..
As you can see the raycast goes with 90 degrees from red cube BUT when it hits to the other object its not hitting with 90. I have a kind of a bool value and it detect hit. What i want is that bool value to change if only raycast hit to the other object with 90 degree..
Is there any way to do this ?
Answer by Epicwolf · Sep 29, 2015 at 08:14 PM
You can use the normal of the object that is hit to check for 90 degree angles. So maybe something like this will work:
if (Physics.Raycast(...)){
// raycast hit something, check for 90 degree angles
// assume hit is your RaycastHit variable
// assume rayDirection is the direction that your raycast travels
// Vector3.Angle() returns the acute angle between two vectors
float angle = Vector3.Angle(hit.normal, rayDirection);
if (angle % 90 == 0){
// angle is a 90 degree angle...?
// ... do stuff here ...
}
}
You might need to check the angle from hit.normal
to Vector3.up
as well. (Perhaps check if the angle to Vector3.up
is 90?)
Answer by lib87 · Sep 30, 2015 at 06:41 PM
I used this method exactly same and im not sure if its working or not.. I did this
float angle = Vector3.Angle(hit.normal, Vector3.up);
if (hit.transform.tag == "Select" )
{
print(this.transform.name + "Vuran");
print(hit.transform.name + "Vurulan");
print(angle.ToString());
if(angle % 90 != 0)
{
print("Test 1 2 Test 1);
Sometimes this looks it works.. But sometimes i move my cube to different angle while other cubes raycast still hit and my test log hits few times.. which is weird...
Actually, you didn't do the exact same thing, (`angle % 90 != 0` should be angle % 90 == 0
, and you are comparing the angle to Vector3.up
) but that doesn't matter because my code didn't really work anyway :P
Here is a better way to do this:
if (Physics.Raycast(...)){
// assume the "direction" variable is the direction you are shooting the raycast
float angle = Vector3.Angle(hit.normal, -direction);
if (angle == 0){
// raycast hit at 90 angle!
// ... do stuff here ...
}
}
What this does is check if the direction from the surface you hit is the opposite of the direction you hit it from. (i.e. if the surface was hit straight at a 90 angle)
If this isn't working, try normalizing direction and maybe hit.normal.
Note that there must be an ABSOLUTE 90 angle in order for angle to equal 0. even 1 degree of rotation will make the angle greater than 0.
Your answer
Follow this Question
Related Questions
Raycast does not seem to properly detect object it hit 0 Answers
Raycast detect in object (problem) 0 Answers
raycast activation by trigger 0 Answers