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

LIKE

SHARE

Facebook Share Tweet LinkedIn Share

FOLLOW

LinkedIn Follow Xing Follow

Head of Mobile Technologies 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.

 

→ If you want to find out more about the author of the article click play on the below video.

Subscribe on YouTube

Download

Vous souhaitez nous contacter ? 

Si vous êtes intéressés par nos services de développement de logiciel, si vous souhaitez rejoindre notre équipe, ou si vous souhaitez tout simplement en savoir plus sur nous, nous sommes à votre disposition. Contactez-nous ! Écrivez-nous et un membre de l'équipe ASSIST vous répondra dans les plus brefs délais. Nous pourrons certainement vous ASSISTer.

CONTACTEZ-NOUS