- Home /
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 }. UnityEngine.Transform:set_eulerAngles(Vector3) 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);
}
else{
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!
Answer by elenzil · Sep 26, 2016 at 11:23 PM
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.
Thanks for the suggestion but, i tried this approach by commenting out line 20-28 what happened is it returned values from -1 to 3. maybe it has something to do with input setting but I'm not sure.
that range sounds reasonable. don't forget * $$anonymous$$athf.Rad2Deg.
Answer by habsi70 · Sep 26, 2016 at 06:30 PM
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 ...
}
Answer by jjulio93 · Sep 26, 2016 at 08:25 PM
This could be an error with the input configuration. Try using Input.GetAxis("Horizontal") and Input.GetAxis("Vertical") which are the default controls.
Your answer
![](https://koobas.hobune.stream/wayback/20220612093407im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
InputPositionWithLocalOffset Issue o.0 0 Answers
Transform.rotate returns NAN error. 0 Answers
FIXED - Editing animation clips gives NaN on rotation value 2 Answers
How to check for NaN 4 Answers
please help Input rotation is { NaN, NaN, NaN, NaN }. 1 Answer