What is a raycast?Would Raycast suffice for a game clock based on sun position?Using Physics.Raycast inside...

English - Acceptable use of parentheses in an author's name

Which likelihood function is used in linear regression?

Can I call myself an assistant professor without a PhD?

Why isn’t SHA-3 in wider use?

What are the uses and limitations of Persuasion, Insight, and Deception against other PCs?

Unique combinations of a list of tuples

Why are the inside diameters of some pipe larger than the stated size?

Best gun to modify into a monsterhunter weapon?

Does this Foo machine halt?

In Pokémon Go, why does one of my Pikachu have an option to evolve, but another one doesn't?

How to vertically align the three columns of my table top, top, middle

Max Order of an Isogeny Class of Rational Elliptic Curves is 8?

Why do oscilloscopes use SMPS instead of linear power supply?

How quickly could a country build a tall concrete wall around a city?

Is TA-ing worth the opportunity cost?

How does The Fools Guild make its money?

Acceptable to cut steak before searing?

Am I overreacting to my team leader's unethical requests?

First amendment and employment: Can an employer terminate you for speech?

What is my malfunctioning AI harvesting from humans?

Why does Intel's Haswell chip allow FP multiplication to be twice as fast as addition?

In a topological space if there exists a loop that cannot be contracted to a point does there exist a simple loop that cannot be contracted also?

How to mark beverage cans in a cooler for a blind person?

Why doesn't the "actual" path matter for line integrals?



What is a raycast?


Would Raycast suffice for a game clock based on sun position?Using Physics.Raycast inside OnCollisionEnter2D functionUnity3D - Determining if a spherical object is grounded using raycastScript no longer working now that it is attached to a child object. Why is this?Unity - UI Raycast Hits ProblemWhat is a faster alternative to a GetComponent from a RaycastHit?undetected colissionRaycast in Unity for ground detection returns false while touching groundHow can I convert Physics2D.Raycast to Physics2D.BoxCast to yield the same results?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ margin-bottom:0;
}







1












$begingroup$


I use this script to build buildings on my terrain, and it works with the collider somehow. But I don't understand what it is that the raycast does to find the right place to put my building.



Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hitInfo;
if (Physics.Raycast(ray, out hitInfo))
{
farmhide.transform.position = hitInfo.point;

farmhide.transform.rotation = Quaternion.FromToRotation(Vector3.up, hitInfo.normal);
}


What is it that this code is doing?










share|improve this question











$endgroup$














  • $begingroup$
    A Raycast will cast the ray. the hit will be the object that the ray contacts. you can retrieve the point in space where that hit intersects by getting the hit.point. the collider is the collider that is attached to the object you hit with the ray and can be retrieved with hit.collider check out the Unity documentation for Raycasthit.collider
    $endgroup$
    – Justin Markwell
    8 hours ago












  • $begingroup$
    Is there a way to make it work with Tag It works with all Collider in Scene
    $endgroup$
    – NADER LABBAD
    8 hours ago










  • $begingroup$
    you can add a check for a tag if need be. it would be something like if(hit.collider.gameObject.tag == "Tag"){//DoStuff}
    $endgroup$
    – Justin Markwell
    8 hours ago










  • $begingroup$
    so Anything crouse Touch any GameObject = hit and hit have Collider from GameObject
    $endgroup$
    – NADER LABBAD
    8 hours ago












  • $begingroup$
    for the most part that will be true. You can also specify layers that the raycast will not interact with also but otherwise yes the Ray will will hit objects that have a collider attached
    $endgroup$
    – Justin Markwell
    8 hours ago


















1












$begingroup$


I use this script to build buildings on my terrain, and it works with the collider somehow. But I don't understand what it is that the raycast does to find the right place to put my building.



Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hitInfo;
if (Physics.Raycast(ray, out hitInfo))
{
farmhide.transform.position = hitInfo.point;

farmhide.transform.rotation = Quaternion.FromToRotation(Vector3.up, hitInfo.normal);
}


What is it that this code is doing?










share|improve this question











$endgroup$














  • $begingroup$
    A Raycast will cast the ray. the hit will be the object that the ray contacts. you can retrieve the point in space where that hit intersects by getting the hit.point. the collider is the collider that is attached to the object you hit with the ray and can be retrieved with hit.collider check out the Unity documentation for Raycasthit.collider
    $endgroup$
    – Justin Markwell
    8 hours ago












  • $begingroup$
    Is there a way to make it work with Tag It works with all Collider in Scene
    $endgroup$
    – NADER LABBAD
    8 hours ago










  • $begingroup$
    you can add a check for a tag if need be. it would be something like if(hit.collider.gameObject.tag == "Tag"){//DoStuff}
    $endgroup$
    – Justin Markwell
    8 hours ago










  • $begingroup$
    so Anything crouse Touch any GameObject = hit and hit have Collider from GameObject
    $endgroup$
    – NADER LABBAD
    8 hours ago












  • $begingroup$
    for the most part that will be true. You can also specify layers that the raycast will not interact with also but otherwise yes the Ray will will hit objects that have a collider attached
    $endgroup$
    – Justin Markwell
    8 hours ago














1












1








1





$begingroup$


I use this script to build buildings on my terrain, and it works with the collider somehow. But I don't understand what it is that the raycast does to find the right place to put my building.



Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hitInfo;
if (Physics.Raycast(ray, out hitInfo))
{
farmhide.transform.position = hitInfo.point;

farmhide.transform.rotation = Quaternion.FromToRotation(Vector3.up, hitInfo.normal);
}


What is it that this code is doing?










share|improve this question











$endgroup$




I use this script to build buildings on my terrain, and it works with the collider somehow. But I don't understand what it is that the raycast does to find the right place to put my building.



Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hitInfo;
if (Physics.Raycast(ray, out hitInfo))
{
farmhide.transform.position = hitInfo.point;

farmhide.transform.rotation = Quaternion.FromToRotation(Vector3.up, hitInfo.normal);
}


What is it that this code is doing?







unity c# raycasting collider






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited 8 hours ago









DMGregory

70.3k16 gold badges126 silver badges195 bronze badges




70.3k16 gold badges126 silver badges195 bronze badges










asked 9 hours ago









NADER LABBADNADER LABBAD

84 bronze badges




84 bronze badges















  • $begingroup$
    A Raycast will cast the ray. the hit will be the object that the ray contacts. you can retrieve the point in space where that hit intersects by getting the hit.point. the collider is the collider that is attached to the object you hit with the ray and can be retrieved with hit.collider check out the Unity documentation for Raycasthit.collider
    $endgroup$
    – Justin Markwell
    8 hours ago












  • $begingroup$
    Is there a way to make it work with Tag It works with all Collider in Scene
    $endgroup$
    – NADER LABBAD
    8 hours ago










  • $begingroup$
    you can add a check for a tag if need be. it would be something like if(hit.collider.gameObject.tag == "Tag"){//DoStuff}
    $endgroup$
    – Justin Markwell
    8 hours ago










  • $begingroup$
    so Anything crouse Touch any GameObject = hit and hit have Collider from GameObject
    $endgroup$
    – NADER LABBAD
    8 hours ago












  • $begingroup$
    for the most part that will be true. You can also specify layers that the raycast will not interact with also but otherwise yes the Ray will will hit objects that have a collider attached
    $endgroup$
    – Justin Markwell
    8 hours ago


















  • $begingroup$
    A Raycast will cast the ray. the hit will be the object that the ray contacts. you can retrieve the point in space where that hit intersects by getting the hit.point. the collider is the collider that is attached to the object you hit with the ray and can be retrieved with hit.collider check out the Unity documentation for Raycasthit.collider
    $endgroup$
    – Justin Markwell
    8 hours ago












  • $begingroup$
    Is there a way to make it work with Tag It works with all Collider in Scene
    $endgroup$
    – NADER LABBAD
    8 hours ago










  • $begingroup$
    you can add a check for a tag if need be. it would be something like if(hit.collider.gameObject.tag == "Tag"){//DoStuff}
    $endgroup$
    – Justin Markwell
    8 hours ago










  • $begingroup$
    so Anything crouse Touch any GameObject = hit and hit have Collider from GameObject
    $endgroup$
    – NADER LABBAD
    8 hours ago












  • $begingroup$
    for the most part that will be true. You can also specify layers that the raycast will not interact with also but otherwise yes the Ray will will hit objects that have a collider attached
    $endgroup$
    – Justin Markwell
    8 hours ago
















$begingroup$
A Raycast will cast the ray. the hit will be the object that the ray contacts. you can retrieve the point in space where that hit intersects by getting the hit.point. the collider is the collider that is attached to the object you hit with the ray and can be retrieved with hit.collider check out the Unity documentation for Raycasthit.collider
$endgroup$
– Justin Markwell
8 hours ago






$begingroup$
A Raycast will cast the ray. the hit will be the object that the ray contacts. you can retrieve the point in space where that hit intersects by getting the hit.point. the collider is the collider that is attached to the object you hit with the ray and can be retrieved with hit.collider check out the Unity documentation for Raycasthit.collider
$endgroup$
– Justin Markwell
8 hours ago














$begingroup$
Is there a way to make it work with Tag It works with all Collider in Scene
$endgroup$
– NADER LABBAD
8 hours ago




$begingroup$
Is there a way to make it work with Tag It works with all Collider in Scene
$endgroup$
– NADER LABBAD
8 hours ago












$begingroup$
you can add a check for a tag if need be. it would be something like if(hit.collider.gameObject.tag == "Tag"){//DoStuff}
$endgroup$
– Justin Markwell
8 hours ago




$begingroup$
you can add a check for a tag if need be. it would be something like if(hit.collider.gameObject.tag == "Tag"){//DoStuff}
$endgroup$
– Justin Markwell
8 hours ago












$begingroup$
so Anything crouse Touch any GameObject = hit and hit have Collider from GameObject
$endgroup$
– NADER LABBAD
8 hours ago






$begingroup$
so Anything crouse Touch any GameObject = hit and hit have Collider from GameObject
$endgroup$
– NADER LABBAD
8 hours ago














$begingroup$
for the most part that will be true. You can also specify layers that the raycast will not interact with also but otherwise yes the Ray will will hit objects that have a collider attached
$endgroup$
– Justin Markwell
8 hours ago




$begingroup$
for the most part that will be true. You can also specify layers that the raycast will not interact with also but otherwise yes the Ray will will hit objects that have a collider attached
$endgroup$
– Justin Markwell
8 hours ago










1 Answer
1






active

oldest

votes


















2












$begingroup$

A raycast is like shining a laser pointer in your scene, to see what the laser hits.



It takes a starting point and a direction as input (together, they make a "ray").



The physics engine takes this point and sweeps it along that direction. As it goes, it searches through all the physics colliders in your scene to check whether the point hits any of them during its travel.



(This is a simplification - in reality the engine has lots of clever acceleration structures and math so it can do this efficiently without looking at every collider or checking every point along the line one by one)



If it finds a collider that's in the path of the travelling point, it returns "true," meaning "yes, I found a hit." If you've provided an out RaycastHit parameter, it will store information about the first hit - the closest object along the ray.



From that RaycastHit, you can learn a lot about the intersection:




  • hitInfo.collider will give you the Collider component that the ray hit. You can use this to get the hit object's GameObject and check its tag with hitInfo.collider.gameObject.CompareTag("someTag"), for example.


  • hitInfo.point will tell you the position in world space where the ray hit the surface of the collider.


  • hitInfo.normal will tell you the direction that the surface of the collider is facing at the point you hit. Your script uses this to orient the buildings to point directly out from the ground, instead of diagonal to the surface.


  • hitInfo.rigidbody will give you the physics Rigidbody that owns the collider you hit, if it was a dynamic or kinematic object.


  • etc.



If you don't want to search every collider in your scene, one of the best ways to control the raycast is to use Physics Layers.



You can expose a public LayerMask raycastLayers; variable in your script, so you can choose in the Inspector which physics layers you're interested in.



Then you can modify your raycast like so:



bool hitSomething = Physics.Raycast(
ray, // Point + direction to sweep
out hitInfo, // Destination for hit information
float.positiveInfinity, // Change this to limit the ray length
raycastLayers, // Only hit colliders on these layers
QueryTriggerInteraction.Ignore // Ignore trigger colliders
);

if (hitSomething) {...


This is more efficient than checking for specific tags, because it lets you filter out false positives at the source.






share|improve this answer









$endgroup$


















    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "53"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: false,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: null,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fgamedev.stackexchange.com%2fquestions%2f174514%2fwhat-is-a-raycast%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    2












    $begingroup$

    A raycast is like shining a laser pointer in your scene, to see what the laser hits.



    It takes a starting point and a direction as input (together, they make a "ray").



    The physics engine takes this point and sweeps it along that direction. As it goes, it searches through all the physics colliders in your scene to check whether the point hits any of them during its travel.



    (This is a simplification - in reality the engine has lots of clever acceleration structures and math so it can do this efficiently without looking at every collider or checking every point along the line one by one)



    If it finds a collider that's in the path of the travelling point, it returns "true," meaning "yes, I found a hit." If you've provided an out RaycastHit parameter, it will store information about the first hit - the closest object along the ray.



    From that RaycastHit, you can learn a lot about the intersection:




    • hitInfo.collider will give you the Collider component that the ray hit. You can use this to get the hit object's GameObject and check its tag with hitInfo.collider.gameObject.CompareTag("someTag"), for example.


    • hitInfo.point will tell you the position in world space where the ray hit the surface of the collider.


    • hitInfo.normal will tell you the direction that the surface of the collider is facing at the point you hit. Your script uses this to orient the buildings to point directly out from the ground, instead of diagonal to the surface.


    • hitInfo.rigidbody will give you the physics Rigidbody that owns the collider you hit, if it was a dynamic or kinematic object.


    • etc.



    If you don't want to search every collider in your scene, one of the best ways to control the raycast is to use Physics Layers.



    You can expose a public LayerMask raycastLayers; variable in your script, so you can choose in the Inspector which physics layers you're interested in.



    Then you can modify your raycast like so:



    bool hitSomething = Physics.Raycast(
    ray, // Point + direction to sweep
    out hitInfo, // Destination for hit information
    float.positiveInfinity, // Change this to limit the ray length
    raycastLayers, // Only hit colliders on these layers
    QueryTriggerInteraction.Ignore // Ignore trigger colliders
    );

    if (hitSomething) {...


    This is more efficient than checking for specific tags, because it lets you filter out false positives at the source.






    share|improve this answer









    $endgroup$




















      2












      $begingroup$

      A raycast is like shining a laser pointer in your scene, to see what the laser hits.



      It takes a starting point and a direction as input (together, they make a "ray").



      The physics engine takes this point and sweeps it along that direction. As it goes, it searches through all the physics colliders in your scene to check whether the point hits any of them during its travel.



      (This is a simplification - in reality the engine has lots of clever acceleration structures and math so it can do this efficiently without looking at every collider or checking every point along the line one by one)



      If it finds a collider that's in the path of the travelling point, it returns "true," meaning "yes, I found a hit." If you've provided an out RaycastHit parameter, it will store information about the first hit - the closest object along the ray.



      From that RaycastHit, you can learn a lot about the intersection:




      • hitInfo.collider will give you the Collider component that the ray hit. You can use this to get the hit object's GameObject and check its tag with hitInfo.collider.gameObject.CompareTag("someTag"), for example.


      • hitInfo.point will tell you the position in world space where the ray hit the surface of the collider.


      • hitInfo.normal will tell you the direction that the surface of the collider is facing at the point you hit. Your script uses this to orient the buildings to point directly out from the ground, instead of diagonal to the surface.


      • hitInfo.rigidbody will give you the physics Rigidbody that owns the collider you hit, if it was a dynamic or kinematic object.


      • etc.



      If you don't want to search every collider in your scene, one of the best ways to control the raycast is to use Physics Layers.



      You can expose a public LayerMask raycastLayers; variable in your script, so you can choose in the Inspector which physics layers you're interested in.



      Then you can modify your raycast like so:



      bool hitSomething = Physics.Raycast(
      ray, // Point + direction to sweep
      out hitInfo, // Destination for hit information
      float.positiveInfinity, // Change this to limit the ray length
      raycastLayers, // Only hit colliders on these layers
      QueryTriggerInteraction.Ignore // Ignore trigger colliders
      );

      if (hitSomething) {...


      This is more efficient than checking for specific tags, because it lets you filter out false positives at the source.






      share|improve this answer









      $endgroup$


















        2












        2








        2





        $begingroup$

        A raycast is like shining a laser pointer in your scene, to see what the laser hits.



        It takes a starting point and a direction as input (together, they make a "ray").



        The physics engine takes this point and sweeps it along that direction. As it goes, it searches through all the physics colliders in your scene to check whether the point hits any of them during its travel.



        (This is a simplification - in reality the engine has lots of clever acceleration structures and math so it can do this efficiently without looking at every collider or checking every point along the line one by one)



        If it finds a collider that's in the path of the travelling point, it returns "true," meaning "yes, I found a hit." If you've provided an out RaycastHit parameter, it will store information about the first hit - the closest object along the ray.



        From that RaycastHit, you can learn a lot about the intersection:




        • hitInfo.collider will give you the Collider component that the ray hit. You can use this to get the hit object's GameObject and check its tag with hitInfo.collider.gameObject.CompareTag("someTag"), for example.


        • hitInfo.point will tell you the position in world space where the ray hit the surface of the collider.


        • hitInfo.normal will tell you the direction that the surface of the collider is facing at the point you hit. Your script uses this to orient the buildings to point directly out from the ground, instead of diagonal to the surface.


        • hitInfo.rigidbody will give you the physics Rigidbody that owns the collider you hit, if it was a dynamic or kinematic object.


        • etc.



        If you don't want to search every collider in your scene, one of the best ways to control the raycast is to use Physics Layers.



        You can expose a public LayerMask raycastLayers; variable in your script, so you can choose in the Inspector which physics layers you're interested in.



        Then you can modify your raycast like so:



        bool hitSomething = Physics.Raycast(
        ray, // Point + direction to sweep
        out hitInfo, // Destination for hit information
        float.positiveInfinity, // Change this to limit the ray length
        raycastLayers, // Only hit colliders on these layers
        QueryTriggerInteraction.Ignore // Ignore trigger colliders
        );

        if (hitSomething) {...


        This is more efficient than checking for specific tags, because it lets you filter out false positives at the source.






        share|improve this answer









        $endgroup$



        A raycast is like shining a laser pointer in your scene, to see what the laser hits.



        It takes a starting point and a direction as input (together, they make a "ray").



        The physics engine takes this point and sweeps it along that direction. As it goes, it searches through all the physics colliders in your scene to check whether the point hits any of them during its travel.



        (This is a simplification - in reality the engine has lots of clever acceleration structures and math so it can do this efficiently without looking at every collider or checking every point along the line one by one)



        If it finds a collider that's in the path of the travelling point, it returns "true," meaning "yes, I found a hit." If you've provided an out RaycastHit parameter, it will store information about the first hit - the closest object along the ray.



        From that RaycastHit, you can learn a lot about the intersection:




        • hitInfo.collider will give you the Collider component that the ray hit. You can use this to get the hit object's GameObject and check its tag with hitInfo.collider.gameObject.CompareTag("someTag"), for example.


        • hitInfo.point will tell you the position in world space where the ray hit the surface of the collider.


        • hitInfo.normal will tell you the direction that the surface of the collider is facing at the point you hit. Your script uses this to orient the buildings to point directly out from the ground, instead of diagonal to the surface.


        • hitInfo.rigidbody will give you the physics Rigidbody that owns the collider you hit, if it was a dynamic or kinematic object.


        • etc.



        If you don't want to search every collider in your scene, one of the best ways to control the raycast is to use Physics Layers.



        You can expose a public LayerMask raycastLayers; variable in your script, so you can choose in the Inspector which physics layers you're interested in.



        Then you can modify your raycast like so:



        bool hitSomething = Physics.Raycast(
        ray, // Point + direction to sweep
        out hitInfo, // Destination for hit information
        float.positiveInfinity, // Change this to limit the ray length
        raycastLayers, // Only hit colliders on these layers
        QueryTriggerInteraction.Ignore // Ignore trigger colliders
        );

        if (hitSomething) {...


        This is more efficient than checking for specific tags, because it lets you filter out false positives at the source.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered 8 hours ago









        DMGregoryDMGregory

        70.3k16 gold badges126 silver badges195 bronze badges




        70.3k16 gold badges126 silver badges195 bronze badges

































            draft saved

            draft discarded




















































            Thanks for contributing an answer to Game Development Stack Exchange!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            Use MathJax to format equations. MathJax reference.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fgamedev.stackexchange.com%2fquestions%2f174514%2fwhat-is-a-raycast%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Taj Mahal Inhaltsverzeichnis Aufbau | Geschichte | 350-Jahr-Feier | Heutige Bedeutung | Siehe auch |...

            Baia Sprie Cuprins Etimologie | Istorie | Demografie | Politică și administrație | Arii naturale...

            Ciclooctatetraenă Vezi și | Bibliografie | Meniu de navigare637866text4148569-500570979m