How to prevent NaN?

So, i was making a script to make the game object rotate accordingly to the controller joystick. It’s working and all but there’s this error showing up whenever I run it.

“transform.rotation assign attempt for ‘Player1’ is not valid. Input rotation is { NaN, NaN, NaN, NaN }.
P1_Rotate:FixedUpdate() (at Assets/Scripts/P1_Rotate.cs:36)”

Here’s my code;

using UnityEngine;
using System.Collections;

public class P1_Rotate : MonoBehaviour {
	//Rotating Variables
	private float moveX;
	private float moveZ;
	private float hypothenus;
	private float angle;
	void Start () {
	// Update is called once per frame
	void FixedUpdate () {
		moveX = Input.GetAxis("P1_Sideward");
		moveZ = Input.GetAxis ("P1_Forward");

		hypothenus = (Mathf.Sqrt ((moveX*moveX) +(moveZ *moveZ)));

		if (moveZ <= 0.1f) {
			angle = (-((Mathf.Acos (moveX  / hypothenus))) * Mathf.Rad2Deg);

			angle = (((Mathf.Acos (moveX / hypothenus))) * Mathf.Rad2Deg);

		this.transform.eulerAngles = (new Vector2 (0,angle));


I found out the problem that a NaN is returned because if there’s no input in the joystick the values of moveX and MoveZ will be zero thus the variable angle will divide by zero.

The problem is it is (Somehow) unavoidable to have a zero value for hypotenuse. or is there anyway to avoid this?

thanks in advance!

i think you’re trying to get the angle specified by two orthogonal offsets (eg x and y).

acos(x / hyp) may get you what you want,
but Mathf.atan2() is specifically for this scenario.

i think you could replace lines 20 through 28 with a single line like:

angle = Mathf.Atan2(movex, movez);

it’s more stable, takes care of the if/else business and also watches for divide-by-zero.

Why not simply wrap your rotation code in an if statement?

if (hypothenus != 0) {
        if (moveZ <= 0.1f) {
             angle = (-((Mathf.Acos (moveX  / hypothenus))) * Mathf.Rad2Deg);
        etc ...


This could be an error with the input configuration. Try using Input.GetAxis(“Horizontal”) and Input.GetAxis(“Vertical”) which are the default controls.