Start()
method as it is only called once. If we want to check orientation changes as the user is playing the game then we need to check the state of the orientation on a frame-by-frame basis. We do this by putting our orientation code in the Update()
method.We will use the deviceOrientation
attribute of the Input class to determine what the orientation of the device is. This information comes directly from the OS in real time so as the orientation changes, we will be notified and can respond to the change without having to interrupt gameplay.
using UnityEngine; using System.Collections; public class DetectShake : MonoBehaviour { public float shakeThreshold = 2.0f; // Update is called once per frame void Update () { Vector3 accel = Input.acceleration; float x = accel.x; float y = accel.y; float z = accel.z; float shakeStrength = Mathf.Sqrt( x * x + y * y + z * z ); if ( shakeStrength >= shakeThreshold ) { // do the shake action } } }
Now that we know that a device shake has taken place we can perform the specific action that we want associated with the shake.
In our player
class we have a simple representation of the player's health as an integer within our Player
class:
public class Player { public static int MAX_HEALTH = 100; private int health = 0; public Player() { } public int getHealth() { return health; } public void heal() { health = health + 10; if ( health > MAX_HEALTH ) { health = MAX_HEALTH; } } }
In our Player
class is a simple heal method that we call whenever we detect that a shake of the device has happened.
We have implemented the last input features for the game by detecting shakes of the device. Based upon this shake we have changed the user's state and taken an action. While shaking isn't a common action in games today, and I encourage you to use it sparingly, there are certainly times when it represents the best input option available.
13.59.205.183