Hi, I’m trying to access the mobile gyrometer to provide simple camera rotation when the user moves around their phone. The camera is parented to a first-person body, and uses a joystick to transform left, right, forward, and back.
I also want users to be able to touch the screen and drag to rotate as well, if that is move convenient for them. This drag-to-rotate works like this:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
public class MouseLook : MonoBehaviour
{
public float mouseSensitivity = 100f;
public Transform playerBody;
float xRotation;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
float mouseX = 0;
float mouseY = 0;
if(Input.touchCount >0 && Input.GetTouch(0).phase == TouchPhase.Moved)
{
if (EventSystem.current.IsPointerOverGameObject(Input.GetTouch(0).fingerId))
return;
mouseX = Input.GetTouch(0).deltaPosition.x;
mouseY = Input.GetTouch(0).deltaPosition.y;
}
mouseX *= mouseSensitivity;
mouseY *= mouseSensitivity;
xRotation -= mouseY * Time.deltaTime;
xRotation = Mathf.Clamp(xRotation, -80, 80);
transform.localRotation = Quaternion.Euler(xRotation, 0, 0);
playerBody.Rotate(Vector3.up * mouseX * Time.deltaTime);
}
}
I am having trouble getting these pieces to work together nicely.
Here’s what gyroscope looks like:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GyroscopeCameraRotation : BasicCameraRotation
{
private float x;
private float y;
public bool gyroEnabled = false;
readonly float sensitivity = 50.0f;
private Gyroscope gyro;
void Start()
{
gyroEnabled = EnableGyro();
}
private bool EnableGyro()
{
if (SystemInfo.supportsGyroscope)
{
gyro = Input.gyro;
gyro.enabled = true;
return true;
}
return false;
}
void Update()
{
if (gyroEnabled)
{
GyroRotation();
}
}
void GyroRotation()
{
x = Input.gyro.rotationRate.x;
y = Input.gyro.rotationRate.y;
float xFiltered = FilterGyroValues(x);
xFiltered = Mathf.Clamp(xFiltered, -50, 80);
RotateUpDown(xFiltered*sensitivity);
float yFiltered = FilterGyroValues(y);
yFiltered = Mathf.Clamp(yFiltered, -50, 50);
RotateRightLeft(yFiltered * sensitivity);
}
float FilterGyroValues(float axis)
{
if (axis < -0.1 || axis > 0.1)
{
return axis;
}
else
{
return 0;
}
}
}