Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

[Tutorial] How to improve your raycasts Using the dot product (includes download link)

Discussion in 'Scripting' started by charlesamat, May 30, 2019.

  1. charlesamat

    charlesamat

    Joined:
    Feb 5, 2014
    Posts:
    66


    Unity's built-in Raycast function is an extremely valuable tool. It allows you to cast a ray into the scene and determine whether or not it collides with anything. This is useful for common mechanics such as line-of-sight and collision detection.

    But sometimes Raycast can be too precise, and using it can result in an unresponsive feel for the player. Luckily, we can use the dot product in cases like this to simply determine whether or not a ray is close to a target.

    This unity tutorial uses basic object selection as an example to demonstrate how powerful this simple algorithm can be.

    Learn more about Dot Product at https://betterexplained.com/articles/vector-calculus-understanding-the-dot-product

    Download the project at https://www.patreon.com/posts/27222309
     
  2. dgoyette

    dgoyette

    Joined:
    Jul 1, 2016
    Posts:
    4,120
    Nice video. One reaction: Did you consider including some distance-based preference along with just the "closest"-based preference? I can see this being awkward if you're looking at a nearby large object, such that maybe you're only 90% directly lined up with it, and then you hit a smaller background object at a higher accuracy, causing the far away object to become the selected one.
     
  3. charlesamat

    charlesamat

    Joined:
    Feb 5, 2014
    Posts:
    66
    Yes you'd ideally want to factor in distance but I left it out to keep the overall tutorial more focused.