Game Development Reference
In-Depth Information
16 void Awake()
17 {
18 //If mobile platform, then use mobile first person controller
19
#if UNITY_IPHONE || UNITY_ANDROID || UNITY_WP8
20 DesktopFirstPerson.SetActive(false);
21 MobileFirstPerson.SetActive(true);
22
#endif
23 }
24 //------------------------------------------------
25 }
Lines 09-12.
This class defines two public variables:
DesktopFirstPerson
and
MobileFirstPerson
. These are references to each of the controllers, one of
which should be disabled on
Awake
.
Lines 19-22.
The
Awake
event is called implicitly before
Start
, when the scene
begins. Line 19 uses the Platform Dependent Compilation syntax to define two
subsequent lines that should execute, only if the platform is iPhone, Android, or
Windows Phone. The global flag
UNITY_IPHONE
encompasses all iOS devices,
such as iPads and iPhones. In this sample, if the platform is a mobile device,
then the desktop controller is deactivated and the mobile controller is activated.
Notice there is no branch for a desktop platform. Why? We can simply avoid
coding this branch by deactivating the mobile First Person Controller
by default
in the Unity Editor
. This way, the default configuration saves us coding and time!
It's important to understand both what
is
happening and
is not
happening regarding Platform
Dependent Compilation. Line 19 of Listing 5-1 is
not
executed every time the game runs on
every
platform. The
Awake
function is
not
performing a runtime check for the active Unity platform, and
then acting accordingly. The
#if
directive is
not
the same as an
if
statement. The
#if
directive
works at the
compilation
level and not at a
runtime
level. In practice, Listing 5-1 means that when the
Unity platform is switched to desktop, the compiler recompiles the
ControlSwitcher
script and treats
lines 19-22 as
code comments
, since the active platform is not a mobile one. The compiler only
recognizes lines 19-22 as valid when the active platform is mobile.
Go ahead and give this code a try—the result is a universal First Person Controller. Whether you're
on desktop or mobile, your scene now has a First Person Controller ready to use!
Note
If you just want to make a runtime check for the active Unity platform, then use
Application.
Head Bobbing and Sine Waves
Whenever the First Person Controller walks forward or backward, we want the camera to bob or
oscillate up and down smoothly in the Y axis. This is to simulate the involuntary head movement that
occurs naturally whenever most bipeds, like humans, move using their legs. We could, of course,
implement this behavior by resorting to the familiar bobbing motion technique created for the Cash
Power-Up in the previous chapter. But this motion was decidedly
linear
and
mechanical
. That is,