Calc angle.

I need to be calculated the angle between normal to the ground and the one has my object. Take a look:

I’ve made that script:

using UnityEngine;
using System.Collections;

public class PlaneBehaviour : MonoBehaviour
{
	void Update()
    {
		//Get values
		float horizontal = Input.GetAxis("Horizontal") * Time.deltaTime;
		float vertical = Input.GetAxis("Vertical") * Time.deltaTime;
		
		//Apply
		transform.Translate((Vector3.forward * 100) * Time.deltaTime);
        transform.Rotate(vertical, 0, horizontal);
		
		float angle = -((Vector3.Angle(Vector3.up, transform.forward)) - 90);
		
		Debug.Log(angle);
	}
}

With my code the angle is being calculated well is I move my object up and down. Problem comes when I rote my object. Instead of have the angle marked in red, I get 90 degrees (marked in blue):

Cheers!!

This looks like a job for… DA DA DA!

The vector dot product!!

alt text

The the result of the dot product between two vectors A and B (A · B) is equal to the cosine of the angle between them (cos(θ)) multiplied by the magnitude of vector A (|A|), or:

|A|cos(θ) = A · B

Then all you have to do is solve for θ, the angle between the A and B:

|A|cos(θ) = A · B

cos(θ) = (A · B) / |A|

θ = acos((A · B) / |A|)

Unity has a dot product function, a vector magnitude function, and a arc cosine (inverse cosine) function, so that you can do this in code. The result is in radians, so if you want degrees Unity also provides a function that converts radians to degrees.

Edit:

I realized that Vector.Angle most likely does this already, so I looked over your code some more, and I realized that you are probably getting 90 degrees in the second image because you are using Vector3.up in this line of code:

   float angle = -((Vector3.Angle(Vector3.up, transform.forward)) - 90);

According to the documentation, Vector3.up is a constant that represents (0, 1, 0).
So your second picture is wrong. The actual vectors being used for the calculations are these:

and that angle between them is 90 degrees. The math is correct; it’s your expectation that isn’t. If you wanted it to detect the shortest angle among all axes, that’s another thing.