Hello everyone, i’m now trying to learn what is “Raycast”.
so i have four questions about this subject:
1. from the script reference i understand that after you writing “Raycast”
you need to open Brackets and write there three function: origin,direction and distance.
so my question is what are the difference between direction and distance?.
2. what exactly the direction function do?.
3. i always see people writing something before the “Raycas”, for example:
Physics.Raycast
or
Collider.Raycast
can someone explain me what exactly “Raycast” supposed to do?.
Note: (this code is written in C# and please answer correctly.)
A raycast draws a logical line in 3d space from the point of origin in the specified direction.
The line will collide with any colliders and report back the position and normals of those collisions.
To create a ray from object A to object B for instance you would
Ray r = new Ray(A.transform.position, B.transform.position - A.transform.position);
You can omit distance and it cast the ray to infinity.
Then you can cast that ray to see what it hits (f anything) with methods like
RaycastHit hit = Physics.RayCast(ray);
What’s the point of telling people to ‘answer correctly’ when you don’t understand the basics of coding… anyway
Yes and no. There are several options. some you specify direction only, some direction distance. Go read about Function Overloading if you need further clarification (basic programming)
Tells the raycast which direction to test (obviously)
Because Raycast is a function that is part of the Physics class.
This script will create a Raycast between pointA and pointB and detect collision by tag. I actually tried this with Physics2D and RaycastHit2D, but I changed the code for 3D space…
private RaycastHit rayHit;
private float distance;
public Transform pointA, pointB;
public Color lineColor;
//Drag point objects to pointA and pointB in the Inspector to get transform.
//These can be any 2 objects. You could get them in start function if you want..
void Update()
{
//Drawing and creating raycast...
distance = Vector3.Distance(pointA.position, pointB.position);
rayHit = Physics.Raycast(pointA.position, -(pointA.position - pointB.position), distance);
Debug.DrawRay(pointA.position, -(pointA.position - pointB.position), lineColor);
//Collision detection...
if(rayHit.collider != null)
{
if(rayHit.collider.tag == "ObjectTag")
{
Debug.Log("Object Hit: " + rayHit.collider.tag);
}
}
}