Search Unity

  1. If you have experience with import & exporting custom (.unitypackage) packages, please help complete a survey (open until May 15, 2024).
    Dismiss Notice
  2. Unity 6 Preview is now available. To find out what's new, have a look at our Unity 6 Preview blog post.
    Dismiss Notice

Object rotation with out hit.normals (the correct way question)

Discussion in 'Scripting' started by ricardoprisco, Oct 23, 2018.

  1. ricardoprisco

    ricardoprisco

    Joined:
    Oct 15, 2018
    Posts:
    13
    I have a method that do a raycast to a wall, and return the out hit.normal. Then, apply to object so it can rotate in the right position.

    The problem I was facing before this workaround is that to get my rotation right, I needed to manually rotate the object 90 degrees on the x axis. To prevent this, I come with this manual change on the out hit.normal.

    I think is badly implemented, but works. After the raycast, took out the out hit to Vector3 myhit

    Code (CSharp):
    1.             normal = myhit.normal;
    2.  
    3.             //flipping the normals
    4.  
    5.             float x = normal.x;
    6.             float y = normal.y;
    7.             float z = normal.z;
    8.            
    9.             normal.x = x;
    10.             normal.y = -z; //needed to flip
    11.             normal.z = y;  //needed to change
    12.  
    Object code for rotate

    Code (CSharp):
    1. public GameObject tempghost;
    2. tempghost.transform.rotation = Quaternion.LookRotation(normal);
    Its working, but I feel like its wrong, and its possible to generate errors in the future....
     
  2. hpjohn

    hpjohn

    Joined:
    Aug 14, 2012
    Posts:
    2,190
    LookRtoation has another overload where you can supply 2 directions, (forward and up) instead of only 1 (which is treated as forward only).
    Sounds like you want the hit normal to be the up direction, so you need to use the overload
     
    ricardoprisco likes this.
  3. ricardoprisco

    ricardoprisco

    Joined:
    Oct 15, 2018
    Posts:
    13
    Thank you. Got it working with:
    Code (CSharp):
    1.         tempghost.transform.rotation = Quaternion.FromToRotation(Vector3.up, normal);