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. Dismiss Notice

Checking the angle of an object?

Discussion in 'Editor & General Support' started by brolol404, Sep 4, 2020.

  1. brolol404

    brolol404

    Joined:
    Feb 14, 2015
    Posts:
    21
    I am writing a script that creates a gameobject at the location of the mouse, but I would like to destroy it if it not on level ground (so the player can't place things on trees or walls, etc.) So, this is the code that I came up with to check if the prefab is level and if it is not, it is destroyed. Will this work (is this the correct way to use Quaterion.Euler)? Is there a better way to do this?

    Code (CSharp):
    1. if (Quaterion.Euler.x != 0 || Quaterion.Euler.z != 0)
    2. {Destroy(prefab)}
    3. else
    4. {prefab = storedprefab}
     
  2. Madgvox

    Madgvox

    Joined:
    Apr 13, 2014
    Posts:
    1,315
    It is not.

    You will need to get the normal of whatever surface you're placing the object on, and then compare that normal to the normal of the world (Vector3.up) using Vector3.Dot. If the two vectors are above some threshold (0.99 or whatever), then you are able to place it. Otherwise, don't allow the placement.
     
  3. brolol404

    brolol404

    Joined:
    Feb 14, 2015
    Posts:
    21
    Thanks.

    Would it look like this?

    Code (CSharp):
    1. RaycastHit hit;
    2. Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    3. Vector3 SurfaceNormal;
    4.  
    5. if (Physics.Raycast(ray, out hit))
    6. {SurfaceNormal = hit.normal;}
    7.  
    8. if (Vector3.Dot(SurfaceNormal, Vector3.up) != 1)
    9. {Destroy(prefab)}
    10. else
    11. {prefab = storedprefab}
    12.  
     
  4. brolol404

    brolol404

    Joined:
    Feb 14, 2015
    Posts:
    21
    Just got a chance to test it and it works! Thanks!
     
    Madgvox likes this.