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

Transform.LookAt vs Mathf.Atan2 for Rotation

Discussion in 'Scripting' started by BrodiMAN, Sep 4, 2018.

  1. BrodiMAN

    BrodiMAN

    Joined:
    Feb 2, 2016
    Posts:
    82
    Hello,

    I created two scripts, placed them on two objects that exist in the same scene. My goal was to determine which script was "best" at performing rotation based on user input. Below are the two scripts.

    Object One:
    Code (CSharp):
    1. void Update () {
    2.         Vector3 input = new Vector3(Input.GetAxisRaw("Horizontal"), 0f, Input.GetAxisRaw("Vertical"));
    3.  
    4.         float angle = Mathf.Atan2(input.x, input.z) * Mathf.Rad2Deg;
    5.         transform.eulerAngles = Vector3.up * angle;
    6.     }
    Object Two:
    Code (CSharp):
    1. void Update () {
    2.         Vector3 rotation = new Vector3(Input.GetAxisRaw("Horizontal"), 0f, Input.GetAxisRaw("Vertical"));
    3.  
    4.         transform.LookAt(transform.position + rotation);
    5.     }
    I was unable to determine any real difference between the two (other than Object One snapping back to Vector3.up when I released the controls). I was curious because I was told by more senior game developers that, if possible, I should use math to determine object movement, and not built-in functions of a game engine.

    So my question: Which way is the "best" way of handling rotation and why? Transform.LookAt is really easy to throw into a game. But, Mathf.Atan2 has the advantage of....math?

    Any advice/thoughts on which I should use and why?
     
  2. GroZZleR

    GroZZleR

    Joined:
    Feb 1, 2015
    Posts:
    3,201
    Really dumb advice, in my opinion. The entire point of using a third-party library is to take advantage of the functionality the authors have already imparted into it.
     
    BrodiMAN likes this.
  3. lordofduct

    lordofduct

    Joined:
    Oct 3, 2011
    Posts:
    8,378
    LookAt does math underneath.

    If that math that it does is the behaviour you desire... then use it.
     
    angrypenguin and BrodiMAN like this.