I have written a script to rotate the camera with respect the gyro. As well as when panned using touch.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class WithoutBox : MonoBehaviour {
private Vector3 firstpoint; //change type on Vector3
private Vector3 secondpoint;
private float xAngle = (float) 0.0; //angle for axes x for rotation
private float yAngle = (float) 0.0;
private float xAngTemp = (float) 0.0; //temp variable for angle
private float yAngTemp = (float) 0.0;
private float deltaX = (float) 0.0;
private float deltaY = (float) 0.0;
public Text text;
private float prevGyroY = 0.0f;
private float prevGyroX = 0.0f;
private float prevGyroZ = 0.0f;
private bool flagTouched = false;
public Camera m_Camera;
// Use this for initialization
void Start () {
//Initialization our angles of camera
xAngle = (float) 0.0;
yAngle = (float) 0.0;
this.transform.rotation = Quaternion.Euler(yAngle, xAngle, (float) 0.0);
}
// Update is called once per frame
void Update () {
if (Input.touchCount > 0) {
//Touch began, save position
if (Input.GetTouch (0).phase == TouchPhase.Began) {
firstpoint = Input.GetTouch (0).position;
xAngTemp = prevGyroY - deltaY;
yAngTemp = prevGyroX - deltaX;
}
//Move finger by screen
if (Input.GetTouch (0).phase == TouchPhase.Moved) {
flagTouched = true;
secondpoint = Input.GetTouch (0).position;
//Mainly, about rotate camera. For example, for Screen.width rotate on 180 degree
xAngle = xAngTemp + (firstpoint.x - secondpoint.x) *(float) 180.0 / Screen.width;
yAngle = yAngTemp - ( firstpoint.y - secondpoint.y) *(float) 90.0 / Screen.height;
//Rotate camera
this.transform.rotation = Quaternion.Euler (yAngle, xAngle,(float) 0.0);
}
} else {
//m_Camera.transform.rotation = Quaternion.Euler (90.0f, 0.0f, 0.0f) * new Quaternion (Input.gyro.attitude.x, Input.gyro.attitude.y, -Input.gyro.attitude.z, -Input.gyro.attitude.w);
Quaternion q = Quaternion.Euler (0.0f, 0.0f, 0.0f) * new Quaternion (Input.gyro.attitude.x, Input.gyro.attitude.y, -Input.gyro.attitude.z, -Input.gyro.attitude.w);
prevGyroY = q.eulerAngles.y;
prevGyroX = q.eulerAngles.x;
prevGyroZ = q.eulerAngles.z;
if (flagTouched) {
deltaX = prevGyroX + yAngle;
deltaY = prevGyroY + xAngle;
flagTouched = false;
}
q.eulerAngles.Set (prevGyroX - deltaX, prevGyroY - deltaY, prevGyroZ);
m_Camera.transform.rotation = q;
}
text.text = "xAngle:"+xAngle+"
yAngle:“+yAngle+”
gyroX:“+Input.gyro.attitude.x+”
gyroY:“+Input.gyro.attitude.y+”
gyroZ"+Input.gyro.attitude.z+"
DeltaX:“+deltaX+”
DeltaY"+deltaY+"
prevGyroX:“+prevGyroX+”
prevGyroY"+prevGyroY+"
gyroz:"+prevGyroZ;
}
}
When I pan using touch the camera rotates perfectly but it doesn’t stay there. I’ve been staring at this code from the past two days wasn’t able to crack it. Is there anyone out there who can?