Trouble with Build and Run

Hi guys, I’m doing an application that displays a figure in 3D space, that rotates according to an accelerometer input from a real world object.

Everything works just fine in the editor, but when I do a Build and Run, the object is shown in a flash, but then it fades away and the screen is just blue.

I have narrowed it down to this part of the script:

float bottom = Mathf.Abs(Mathf.Sqrt(Mathf.Pow(x, 2.0f) + Mathf.Pow(y, 2.0f) + Mathf.Pow(z,2.0f)));
        pitch = (Mathf.Asin(-y / bottom) * (180 / Mathf.PI));

        Quaternion temp = Quaternion.Euler(0, 180, pitch);
        target.transform.rotation = Quaternion.Slerp(target.transform.rotation, temp, lerpFactor);

Can anyone give me some advice? Thanks in advance!

/Niels Rask

I don’t know what’s causing the problems you’re seeing, but here’s a few tips:

  • I’d suggest simply writing x*x rather than Mathf.Pow(x, 2.0f); it’s clearer and easier to read, and might also be faster (depending on how Pow() is implemented).

  • Any real number squared is non-negative, the sum of N non-negative numbers is non-negative, and the square root of a non-negative number is non-negative. Therefore, there’s no need for Mathf.Abs() here.

  • In the first statement, you’re computing the length of the vector (x, y, z), and are therefore essentially duplicating functionality that’s already present as part of the Unity API. Better, IMO, simply to write ‘float bottom = new Vector(x, y, z).magnitude’ (or whatever the equivalent is in the language you’re using).

  • Use Mathf.Rad2Deg rather ‘180 / Mathf.PI’.

  • Add some debug output (e.g. using GUI.Label()) indicating whether ‘bottom’ is ever zero or near-zero, and whether ‘-y / bottom’ is ever outside the range [-1, 1] (the first case will most likely result in the latter, of course). If either or both of these things is happening, that could be the cause of the behavior you’re seeing.