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

How to detect if a Raycast hit an approxmately plane Surface to place Towers in a 3D Tower Defense?

Discussion in 'Physics' started by Padrox_, Mar 13, 2022.

  1. Padrox_

    Padrox_

    Joined:
    Jun 12, 2021
    Posts:
    15
    Hey,

    I'm making a Tower Defense Game, using the URP.
    To actually place towers, I shoot a Raycast from the Tower and use the hit position of the RaycastHit to place the tower, it actually works but I would like to find a solution to be able to place towers on almost plane surface:
    If I have a mesh like a sphere, I would like the player to be able to place the tower on the top surface of the sphere where it's almost flat, same for planes.

    I came across an idea which is to calculate the DotProduct() of the hit.point + Vector3.up and the normalized Vector following the face of the hit.collider. It will return a float between 0 and 1 describing how big the angle is. I think i can exploit this result and use it with a given treshold to know if my surface is approximately flat.



    How could I get the normalized vector that follows the surface hit by the Raycast (The blue vector represented on this drawing) to do this DotProduct calculation?



    Thank you in advanced,
    Padrox.
     
  2. AlTheSlacker

    AlTheSlacker

    Joined:
    Jun 12, 2017
    Posts:
    326
    Most of the work is already done for you: https://docs.unity3d.com/ScriptReference/RaycastHit.html look at the normal property.

    This will give you the surface normal, which is the vector that is perpendicular to the tangential plane of the surface at the hit point. For your example of a sphere, it would be the radial vector from the surface point. So if you dot product this and Vector3.up, you will get the angle off vertical that you are looking for.

    Depending on your camera angle you may wish to add some checks to make sure the normal vector is positive in y to prevent the players clicking on any undercut faces.
     
    Last edited: Mar 14, 2022
  3. Padrox_

    Padrox_

    Joined:
    Jun 12, 2021
    Posts:
    15
    Hello ! Thank you for your reply.
    You actually solved my issue, thank you very much!
    Padrox
     
    AlTheSlacker likes this.