I'm creating an unity app on PC that reads a mobile device's orientation and rotates a game object based on the phone's angle with the PC screen.
void Update () {
// Set main screen orientation when left trigger is pressed
if(leftPad.GetTrigger())
mainScreenOrientation = InputState.orientation;
Quaternion delta = InputState.orientation * Quaternion.Inverse(mainScreenOrientation);
transform.localRotation = delta;
}
InputState.orientation is the orientation of the phone and is updated every frame. When the user first starts the app, the phone has to be pointed at the screen to register the mainScreenOrientation.
The delta between the current phone and PC screen orientation is calculated and set on the game object's transform.localRotation
All quaternions are defined with y pointing magnetic north, x pointing east and z pointing up
The orientation of the game object is correctly set to identity after the registration but the object seems to be rotating in the wrong axis when the phone is rotated. Any idea what is wrong with this?
Edit:
Turns out there are a few problems with the code
As Jerome mentioned, the orientations had to be remapped as the phone was being used in landscape mode.
Quaternion.Euler(0, 0, 90) * InputState.orientation
Unity uses left-hand coordinates while the input read by the sensor is right. Negate z to convert.
The last problem I have not solved with this implementation is a sudden jump in rotation past a certain angle. Raising the elevation of the phone in landscape mode above the horizon causes the object to rotate by 90 degrees along the z axis.
Not sure why this is happening as I am dealing only with quaternions and there should not be any discontinuity.
What sensor are you using? Accelerometer or Gyro?
The axis used by the phone might be absolute and therefore may need to be remapped depending on the device orientation to align with 3D axis in Unity3D.
More than likely the y and x axis might need to be switched depending on Portrait or Landscape orientation.