Search Unity

Find the difference between two vectors or angles, or not?

Discussion in 'Scripting' started by JohnPet, Apr 8, 2016.

  1. JohnPet

    JohnPet

    Joined:
    Aug 19, 2012
    Posts:
    78
    Hi, I have a hard time finding just the right code for what I need, a turn increment for the animator property.

    The increment should go from about -1 to 1, calculating the difference of what really? I guess it's the difference between two angles, the one the character is right now, and the one he is looking at/going to move at, but what I currently have doesn't work. Unity's standard third person character uses this technique, but the character moves differently.

    Check the snippet below:

    Code (CSharp):
    1. //What is h and v
    2. Vector3 h = mainCam.right * horizontal;
    3. Vector3 v = mainCam.forward * vertical;
    4.  
    5. //The player's movement
    6. rb.AddForce((h + v).normalized * speed);
    7.  
    8. //What the dir is
    9. storeDirection = transform.position + h + v;
    10. dir = storeDirection - transform.position;
    11.  
    12. //*THE PROBLEM*
    13. float turnInc = Mathf.Atan2(dir.x, dir.z) * Mathf.Rad2Deg;
    Please, my head is gonna break!

    Thank you for your time :)
     
  2. JohnPet

    JohnPet

    Joined:
    Aug 19, 2012
    Posts:
    78
    Finally fixed it! For all of you out there trying to find a turn increment, here's the solution:

    Code (CSharp):
    1. Vector3 forwardA = transform.rotation * Vector3.forward;
    2.             Vector3 forwardB = Quaternion.LookRotation(dir) * Vector3.forward;
    3.            
    4.             float angleA = Mathf.Atan2(forwardA.x, forwardA.z) * Mathf.Rad2Deg;
    5.             float angleB = Mathf.Atan2(forwardB.x, forwardB.z) * Mathf.Rad2Deg;
    6.            
    7.             turnAngle = Mathf.DeltaAngle(angleA, angleB);
    8.            
    9.             anim.SetFloat("Angle", turnAngle * Mathf.Deg2Rad, 0.1f, Time.deltaTime);
    Thank you anyways!
     
    HER20081 likes this.
unityunity