Time for action – Updating upon device tilt

As discussed earlier, iOS devices have a defined access that allows us to determine changes in the device's orientation. We can detect this as changes in the x, y, or z values in Input.acceleration:

Time for action – Updating upon device tilt

Since our game design requires us to manipulate the camera based upon the tilt, the only step we need is to check for the direction of the orientation change and then rotate the camera accordingly. To accomplish this we can attach a script to a GameObject in whose Update() method we examine the Input.acceleration attributes and determine how the device has changed. Remember also that we have specified that our application be designed to run in landscape mode so we are looking for rotations along the device's Z-axis.

Key Method

Description

Input.acceleration

Returns the accelerometer readings of the device

using UnityEngine;
using System.Collections;

public class CameraRotate : MonoBehaviour {
   public float speed = 10.0f;
  
   // Use this for initialization
   void Start () {   
   }
   
   // Update is called once per frame
   void Update () {
      Vector3 direction = Vector3.zero;
      direction.x = - Input.acceleration.y;
      direction.z = Input.acceleration.x;
      
      if ( direction.sqrMagnitude > 1 )
      {
         direction.Normalize();
      }
      
      direction *= Time.deltaTime;
      
      transform.Translate( direction * speed );
   }
}

With iPhoneSettings.screenOrientation we can now tell the Unity player to change its orientation. You can set the orientation to any one of the iPhoneScreenOrientations available. It is recommended that you don't do anything that would be uncharacteristic to the way the iOS device is expected to operate as Apple may reject your application for that behavior.

What just happened?

By adding a script to our camera we get an Update() notification on a frame by frame basis. We can then look to see what the device orientation is and adjust our orientation accordingly. By updating the iPhoneSettings attributes we can quickly flip our scene to match whatever orientation we find ourselves in.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.117.238.40