Home unity3d What is Raycast in Unity and how does it work?

What is Raycast in Unity and how does it work?




explain with an example what it is and how it works

Answer 1, authority 100%

Raycast is a certain ray emitted from an object in a certain direction of a certain length (or infinite) to determine collisions (collisions) with objects. After emitting a ray, we get an object (or an array of objects if we use Physics.RaycastAll ), with which it collided and then we can determine whether we hit the object we need. Often used in shooting. Sample code with explanations (taken from Unity3D.ru ) :

void Update () {
  // info about ray crossing will be written here, if it is
  RaycastHit hit;
  // the ray itself, starts from the position of this object and is directed towards the target
  Ray ray = new Ray (transform.position, target.position - transform.position);
  // fire the beam
  Physics.Raycast (ray, out hit);
  // if the ray intersects with something, then ..
  if (hit.collider! = null) {
    // if the ray didn't hit the target
    if (hit.collider.gameObject! = target.gameObject) {
      Debug.Log ("The path to the enemy is blocked by the object:" + hit.collider.name);
    // if the ray hits the target
    else {
      Debug.Log ("I hit the enemy !!!");
    // just for clarity, draw a ray in the Scene window
    Debug.DrawLine (ray.origin, hit.point, Color.red);

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions