# Why are my angle calculations not working properly?

I am using this code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class HARcieveAngleChanger : MonoBehaviour
{
private float ha;
private float HAZ;
public ConfigurableJoint CJ;
public Vector3 newanchor;
public Vector3 newaxis;

public void OnValueChangedHA(float newValue)
{
ha = (HAGrab.HAUpdate);
UnityEngine.Debug.Log("ha WHAT YO DOING = " + ha);
HAZ =(float)0.8 * (Mathf.Tan(ha))  ;
UnityEngine.Debug.Log("HAZ WHAT YO DOING = " + HAZ);
transform.position = new Vector3(0,0, HAZ);
newanchor.y = (float)-8;
newanchor.z = -HAZ;
newaxis.y = (float)8;
newaxis.z = HAZ;
CJ.connectedAnchor = newanchor;
CJ.secondaryAxis = newaxis;

}

}


From the debug.log(ha), I am getting 45 when I enter a 45 value into the input UI. The HAGrab code gets this. However, the value outputted for HAZ always comes out incorrect (i.e. using trig TOA, tan(angle)*length of alternate side = opposite side, with a 45 degree angle it should come out as 0.8)...

Does anyone have any ideas for why this is the case?

• Did you mean to convert your degree value into radians with Mathf.Deg2Rad, since trig functions take their input in radians? Mar 24 at 21:51
• I had already tried that as i read online to take it in radians, but it still wasn't coming out right so I'm not sure what else it could be
– Stan
Mar 26 at 8:36
• Your first problem with be that your ha variable needs to be in radians. see here. I'm not sure what you are trying to accomplish here, but you will not get the correct calculations using angles here. Convert the angles to radians first, and try to identify the next problem Mar 26 at 15:40
• I went back and tried it again putting the conversion in a different line rather than in the equation itself and is now working, thanks to both of you for the help
– Stan
Mar 29 at 19:26

HAZ = (float)0.8 * Mathf.Tan((ha * Mathf.PI) / 180.0f);

• Unity has a built-in constant for this: Mathf.Deg2Rad Mar 30 at 11:08
• Your math is correct! For reference in environments without the mentioned Deg2Rad, it's generally better practice to wrap the constants together like tan(angle * (PI / 180)). This reduces down to a single runtime multiplication instead of both a multiplication and a division. Mar 30 at 22:13