Rotating a GameObject in Unity3D using the gyroscope | ASSIST Software Romania
get in touch

LIKE

SHARE

FOLLOW

Alexandru Boca

Senior Unity Developer at ASSIST

Games are the most entertaining activities that we can do on a PC or a mobile device. From the simple mouse and keyboard on a PC to the touch screen and sensors of a mobile device. This post is here to explain how to implement an aiming system to a mobile game development project. Attached you have the script, just attach it to your camera and you are ready to go.

For those familiar to Unity, this is a usual check up done in the Awake() function to verify if the device has a gyroscope sensor or if the application is running in the editor. Future updated will contain this functionality on Android and Windows devices, for now is just for iOS devices.

//check if the gyro is enabled
#if UNITY_IPHONE
    if(Input.gyro.enabled){
        enabledGyro = true;

        //debug
        ToDebug("Gyro Enabled");
    } else {
        //TODO: show a warning message
    }
#endif

#if UNITY_ANDROID
    //TODO : Android Gyro Version
#endif

#if UNITY_WINDOWS_PHONE
    //TODO : Windows Phone Gyro Version
#endif

#if UNITY_EDITOR 
    ToDebug("No gyro in the Unity Editor");
#endif

“x” and “y” holds the rotation rates from the gyro which will be filtered and normalized for future use.

//get values from the gyroscope
x = Input.gyro.rotationRate.x;
y = Input.gyro.rotationRate.y;

After the values from the gyro are normalized two function will use these values, one for the X rotation axis or up and down and one for Y rotation or left and right.

//rotate the camera up and down(x rotation)
function RotateUpDown(axis : float){
	transform.RotateAround(transform.position , transform.right, -axis * Time.deltaTime * gyroSensitivity);
}

//rotate the camera rigt and left (y rotation)
function RotateRightLeft(axis : float){
 	transform.RotateAround(transform.position, Vector3.up, -axis * Time.deltaTime * gyroSensitivity);
}

For more information download the script file and follow the comments in the code.

Download

Ready to make it happen?

Drop us a line. We’d love to hear from you and see how we can help in solving your digital challenges. As one of the best software outsourcing companies in Romania, Eastern Europe, Europe and the world really, we are sure we can ASSIST.

GET IN TOUCH