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. Voting for the Unity Awards are OPEN! We’re looking to celebrate creators across games, industry, film, and many more categories. Cast your vote now for all categories
    Dismiss Notice
  3. Dismiss Notice

Rotate Vector3 by Direction

Discussion in 'Scripting' started by KingForever, Apr 15, 2018.

  1. KingForever

    KingForever

    Joined:
    Apr 15, 2018
    Posts:
    1
    Hey folks!

    I'm creating a custom Character Controller that deals with the normal of a Raycast. I cannot for the life of me figure out how best to rotate the resulting vector3 by the direction my player is looking. My current code is
    Code (CSharp):
    1. Vector3 _dir = (Quaternion.AngleAxis(-90f, Vector3.right) * _hit.normal);
    Where _hit is the hit of a raycast. I need to figure out how to rotate the Y axis of _dir so that the resulting vector is facing the same direction as my player.
    Any help would be greatly appreciated!
     
  2. Doug_B

    Doug_B

    Joined:
    Jun 4, 2017
    Posts:
    1,596
    Maybe something like this?
    Code (CSharp):
    1. Player.transform.up = _dir.up;
     
  3. JoshuaMcKenzie

    JoshuaMcKenzie

    Joined:
    Jun 20, 2015
    Posts:
    897
    you simply multiply the player's quaternion by the target vector direction. for example:

    Code (CSharp):
    1. // get the world direction the player is facing
    2. Vector3 playerForward = playerTransform.rotation * Vector3.forward;
    3.  
    4. // get the world direction the fighter jet perceives as up
    5. Vector3 jetUp = fighterJetTransform.rotation * Vector3.up;
    now if its a simple cardinal direction you can use the helper properties on the transform to get them for you

    Code (CSharp):
    1. // get the world direction the player is facing
    2. Vector3 playerForward = playerTransform.forward;
    3.  
    4. // get the world direction the fighter jet perceives as up
    5. Vector3 jetUp = fighterJetTransform.up;
    but if you are looking to a specific offset from those cardinal directions you can apply those vector offset to the first example
     
    Doug_B likes this.