Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Rotating an object to move with new target vectors

Discussion in 'Scripting' started by _jacks, Nov 27, 2014.

  1. _jacks

    _jacks

    Joined:
    Nov 27, 2014
    Posts:
    27
    So I have an object with a rigidbody component

    I defined a target vector and would like the object to translate its position to the new vector,
    I would like the target to rotate facing the new vector.

    How can I do this with code? I'm having trouble with the use of Quaternion
     
    Last edited: Nov 27, 2014
  2. Dantus

    Dantus

    Joined:
    Oct 21, 2009
    Posts:
    5,667
  3. Dantus

    Dantus

    Joined:
    Oct 21, 2009
    Posts:
    5,667
  4. _jacks

    _jacks

    Joined:
    Nov 27, 2014
    Posts:
    27
    Hi Dantus

    Thanks for the reference but I still can't get it work.

    Given a Vector3 target how can one rotate on Y axis according to the target vector?

    I just want the object to face the random Vector3 target
     
    Last edited: Nov 29, 2014
  5. Dantus

    Dantus

    Joined:
    Oct 21, 2009
    Posts:
    5,667
  6. _jacks

    _jacks

    Joined:
    Nov 27, 2014
    Posts:
    27
    Code (csharp):
    1.  
    2. displacement = Quaternion.LookRotation (transform.position - target.normalized, Vector3.forward);
    3. displacement.x = 0.0f;
    4. displacement.z = 0.0f;
    5. transform.rotation = Quaternion.Slerp (transform.rotation, displacement, Time.deltaTime * 0.3f);
    6.  

    So this is the code I have, but it's not working the way I want. I had thought I wanted it to rotate on the X,Z axis but I was wrong, as it turns out I want to rotate on the Y axis so it turns left or right respectively according to where the new random Vector3 target destination is

    Can you help? I'm not fully understanding what this current code does compared to what I want it to do..

    So you can imagine if I point somewhere on the horizon and said OK horse look at that destination it would do so but it would also look behind me if I had said to do that
     
  7. Dantus

    Dantus

    Joined:
    Oct 21, 2009
    Posts:
    5,667