Game Development Reference
In-Depth Information
Engage thrusters
Now, we are ready to create the
PlayerController_2D
script. Let's get started:
1. First, go to
Assets
|
Create
|
Javascript
(for Unity JavaScript developers) or
As-
sets
|
Create
|
C# Script
(for C# developers) and name our script as
Player-
Controller_2D
.
2. Double-click on the script; it will open the
MonoDevelop
window.
3. Now, we will see three windows in the
MonoDevelop
screen:
◦ On the top-left is
Solution
; we can see our project folder here, but it will
only show the folder that contains a script
◦ On the bottom-left, we will see a
Document Outline
; this window will
show all the functions, classes, and parameters in the file
◦ The last window on the right will be used to type our code
4. Let's get our hands dirty with some code—first start with defining the following
functions to initialize the variables: the
Awake()
and
Start()
function.
Tip
Awake ()
Awake ()
is called when the script instance is being loaded. It used to initialize
any variable or game state before calling the
Start()
function. In the
Awake()
function, we usually put any
GetComponent()
or
Find()
object function,
which will make it easier to set up all the parameters during
Start()
.
5. We need to remove the autogenerated code and replace it with the following code:
// Unity JavaScript user:
#pragma strict
@script RequireComponent(AudioSource)
@script RequireComponent(BoxCollider2D)
@script RequireComponent(Rigidbody2D)
// Distance from the character position to the ground
private final var RAYCAST_DISTANCE : float = 0.58f;
// This number should be between 0.35 to 0.49
private final var CHARACTER_EDGE_OFFSET : float =
0.40f;