- Home /
Gyroscope in Landscape mode snaps object to random rotation
Hello, so basically i have a Cannon facing forward (Z axis) at the origin point (0,0,0). The cannon may rotate around the Y axis (left and right) and around the X axis (up and down). Also, the cannon must always be facing forward in the positive Z axis direction (As shown in the image , the cannon doesn't look back into the grey area). I've implemented the gyroscope functionality and tried with my smartphone, the problem is that when the game starts, the cannon snaps into some weird rotation which i assume is coming from the gyroscope... so i would also like to set the initial direction facing forward the Z axis no matter how the user is grabing the phone (either sitting, laying down, etc). The game object tree view is the following and the script is in the parent object:
- Cannon - [p(0,0,0) r(90,0,0) s(1,1,1)] [Script]
- CannonObject
- Main Camera
- FireSpawn
And the script is this:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CannonController : MonoBehaviour {
float fireTimer = 0.5f;
public const float BUFF_TIMER = 5F;
public static float strongTimer = BUFF_TIMER;
public static bool isStrong = false;
private static bool cannonLock = false;
public static int slowMoShoots = 0;
public const int MAX_SLOWMO_SHOTS = 2;
private bool gyroEnabled;
private Gyroscope gyro;
private GameObject cannonContainer;
private Quaternion rot;
void Update()
{
if (!cannonLock) {
if (gyroEnabled) {
Quaternion aux = gyro.attitude * rot;
aux.z = 0f;
transform.localRotation = aux;
}
}
fireTimer -= Time.deltaTime;
strongTimer -= Time.deltaTime;
fireTimer = Mathf.Clamp(fireTimer, 0, BUFF_TIMER);
strongTimer = Mathf.Clamp(strongTimer, 0, BUFF_TIMER);
if (strongTimer == 0)
isStrong = false;
}
void Start () {
Cursor.visible = false;
gyroEnabled = EnableGyro();
}
private bool EnableGyro()
{
if (SystemInfo.supportsGyroscope)
{
gyro = Input.gyro;
gyro.enabled = true;
rot = new Quaternion(0, 0, 1, 0);
return true;
}
return false;
}
}
Thank you in advance.
Your answer
![](https://koobas.hobune.stream/wayback/20220612192842im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Projectile Rotation To Match Direction Shot? Mobile Joystick 2 Answers
Rotate with raw gyro data. 0 Answers
3rd player orientation using gyro with offset 0 Answers
why is my character rotation always 180° after joystick is released. 1 Answer
relative orientation to initial coordinate system,relative rotation coordinate transformation 0 Answers