Sunteți pe pagina 1din 7

Unity character controller tutorial

animations javascript code example


By
Piffa
– March 24, 2012Posted in: DIARY OF A BEGINNER GAME PROGRAMMER, Tutorials and
Howto

Move and animate a model with Unity character controller


tutorial
In this Unity character controller tutorial we will write a simple javascript code example to move
our character and play custom animations for different keyboard inputs. The goal is to create a
personal character controller script that parses our keyboard inputs and transforms it in player
character movements in space with the right animation. To read an introductionary tutorial to
player movement with keyboard inputs and to character 3d modelling and animating click con
the following link :

 Tutorial How to move the Player with keyboard inputs in Unity3d keyboard input
javascript
 Import animated model from Blender to Unity and play the animation with scripting

Get started with Unity character controller tutorial


To get started with this Unity character controller tutorial we will need to start a new Unity
Project and select the Character Controller unitypackage only to import. Then proceed to set up
a simple scene with a plane, a directional light and a Main Camera. You can find how to set up
this simple Unity scene in the previous tutorials. Since we started this project importing the
Character Controller unitypackage we will work with Unity’s default player animated model
named Constructor that you can find via the Project Tab in Standard Assets >> Character
Controllers >> Sources >> PrototypeCharacter. Grab the Constructor prefab and drop it into
the scene, press the Unity play button and you can see how nothing happens when you press
WASD keyboard input controls. This Unity character controller tutorial will show you how to
create your own personal character controller to make the character move with WASD controls.

To begin working with the Unity character controller code we must add a new custom keyboard
input key, because we want our character to walk at a certain speed but also to run at an higher
speed. Go in Unity and select the EDIT menu, then Project Settings and then Input. In the
Inspector will be opened a panel named Axes, it’s an array that contains the total number of key
control inputs available to Unity and each key individual name and sensitivity settings. You can
see that there are two Jump Axes in the list, we must change the last one in our custom Run
button. Click on the last Jump in the Axes list to open its properties dropdown menu, change the
Name field to “Run” and the Positive Button field to “left shift”. What you type in the Name
field is how you will call that key from the scripts, while the Positive Button field is the actual
input, you can read the Unity Input manager documentation by CLICKING HERE.

Open New unity project and set up simple scene

Unity default Constructor modelAdd Run input axis with left shift

Add new Run input key with left shift

Working with Character Controller component


If you press the Unity play button after placing the Constructor prefab in the scene you should
not be able to control the character via keyboard input. Also the camera taking the point of view
will be our default Main Camera. The Animation component is needed to play the animation and
to list and store the model’s available animations. The Character Controller component is what
gives our model a physical hitbox for collisions, it is the green capsule around the constructor
worker model, we will need our script to interface with it to use some of its many useful
function.

Create a new javascript file in the Project tab and name it PlayerControl.js, from there drag and
drop it on our Constructor in the Hierarchy tab to assign it to the worker. Double click the
PlayerControl script to open it and edit in MonoDevelop. You should see two function named
Start and Update in the javascript code. We will need to hook to the Character Controller
component because it contains some functionality defined by Unity devs that we can definitively
use. To do so, we will need to write some code in the Start function, because we only need to
identify the Character Controller component once since it never changes, making the same thing
in the Update function would be an unnecessary waste of hardware resources. the javascript code
example is commented to help understanding of code.

?
1 /* WASD keyboard input player movement control with jump
and mouse rotation - Unity javascript Gameobject.net*/
2
3
#pragma strict
4 var charController:CharacterController ;
5 /* Create a variable of type CharacterController to store
6 our component and call it in the script */
7 var walkSpeed : float = 1 ;
var runSpeed : float = 1.8 ;
8 var rotationSpeed : float = 250 ;
9 var jumpForceDefault : float = 2 ;
10 var cooldown : float = 5 ;
11
12 private var jumpForce : float;
13 private var gravityPull : float = 1;
/* Jump action related costants */
14
15
16 private var isRunning : boolean ;
17 private var isWalking : boolean ;
18 private var isStrafing : boolean ;
19 private var isJumping : boolean ;
private var isAttacking : boolean ;
20 private var isIdle : boolean ;
21 /* Create boolean status variables to identify animation
22 status, e.g. what am i doing right now? */
23
24 function Start (){
25 var cc : CharacterController;
cc = gameObject.AddComponent("CharacterController");
26 /* Adds a Character Controller component to gameobject */
27
28 charController = GetComponent(CharacterController);
29 /* Assigns it in the charController variable to use it */
30
// Set all animations to loop
31 animation.wrapMode = WrapMode.Loop;
// except shooting
32
animation["attack"].wrapMode = WrapMode.Once;
33
34 // Put idle and walk into lower layers (The default layer is always 0)
35 // This will do two things
36 // - Since shoot and idle/walk are in different layers they will not affect
37 // each other's playback when calling CrossFade.
// - Since shoot is in a higher layer, the animation will replace idle/walk
38 // animations when faded in.
39 animation["attack"].layer = 1;
40
41 // Stop animations that are already playing
42 //(In case user forgot to disable play automatically)
43 animation.Stop();
44
45
}
46
47
48
49 function Update(){
50
51 charController.Move(transform.up * Time.deltaTime * -gravityPull * 1);
52
53 /* Gravity */
54
55 if(Input.GetAxis("Vertical") > 0){
/* If the Vertical input axis is positive (by default by
56 pressing W or up arrow) */
57 if(Input.GetButton("Run")){
58 isRunning = true ;
59 animation.CrossFade("run");
60 /* While Run button is pressed play run animation, with
Crossfade try to blend nicely different animations )*/
61 charController.Move(transform.forward*Time.deltaTime*runSpeed) ;
62 /* While Run button is pressed move faster !) */
63 /* Use the Move function, Time.deltatime makes things go
64 equally fast on different hardware configurations,
65 by moving in the forward direction with walkspeed */
isRunning = true ;
66 /* Set the isRunning flag as true since i am running */
67 Debug.Log("isRunning value is" + " " + isRunning);
68 /* Tell me what i am doing now */
69 }
else{
70 isWalking = true ;
71 /* Else if i am moving forward and not running i walk */
72 animation["walk"].speed = 1;
73 animation.CrossFade("walk");
74 /* While walk button is pressed play walk animation ! */
charController.Move(transform.forward*Time.deltaTime*walkSpeed) ;
75 Debug.Log("isWalking value is" + " " + isWalking);
76 /* Tell me what i am doing now */
77 }
78 }
else if(Input.GetAxis("Vertical") < 0){
79 isWalking = true ;
80 /* Do the same for the back direction, no back run! */
81 animation["walk"].speed = 0.5;
82 /* revert walk animation playback */
animation.CrossFade("walk");
83 charController.Move(transform.forward*Time.deltaTime*-walkSpeed/2) ;
84 /* Move function but in the opposite to forward
85 direction by using a negative (-) vector */
86 Debug.Log("isWalking value is" + " " + isWalking);
87 /* Tell me what i am doing now */
}
88 else{
89 isWalking = false ;
90 isRunning = false ;
91 /* if not running or walking set these states as false */
92 }
93 if(Input.GetButtonDown("Jump") && !isJumping){
94 jumpForce = jumpForceDefault ;
95 isJumping = true ;
96 animation.Play("jump_pose") ;
97 /* Capture Jump input and prevent double air jump with
&& !isJumping, makes these lines working only while
98 not already in a Jump. */
99 }
100
101if(isJumping){
102charController.Move(transform.up * Time.deltaTime * jumpForce);
103jumpForce -= gravityPull ;
Debug.Log("isJumping value is" + " " + isJumping);
104/* If isJumping is true (i am in Jump state), move the
105character up with jumpForce intensty, then gravityPull
106kicks in and will take you on the ground. */
107 if(charController.isGrounded){
108isJumping = false ;
/* Check if the character is touching the ground with
109Unity default isGrounded function, if its grounded
110 end the Jumping action by setting isJumping false */
111 }
112 }
113
if(!isWalking && !isRunning && !isJumping){
114 animation.CrossFade("idle");
115 /* If i am not doing any action , play the idle anim */
116
117 }
118
119 if(Input.GetAxis("Horizontal") > 0){
120charController.transform.Rotate(Vector3.up * Time.deltaTime * 20 *
rotationSpeed, Space.World);
121}
122if(Input.GetAxis("Horizontal") < 0){
charController.transform.Rotate(Vector3.up * Time.deltaTime * 20 *
123-rotationSpeed);
124
125}
/* rotate the character with left and right arrows */
126
127
128charController.transform.rotation.y += Input.GetAxis("Mouse X") *
129Time.deltaTime * rotationSpeed ;
130/* rotate the character with the mouse */
131
132if(Input.GetButtonDown("Fire1")){
isAttacking = true ;
133slash() ;
134isAttacking = false ;
135}
136/* Play attack animation calling slash function */
137
138/* If you wish to add STRAFE command just replicate the
code for the forward and back direction , i am not
139doing this in this character controller tutorial
140because the Constructor model is not provided
141with the strafe animation. */
142
143}
144
145function slash(){
animation.CrossFade("attack");
146Debug.Log("isAttacking is" + isAttacking);
147}
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174

Thank you for following this basic Unity character controller tutorial in javascript! Please feel
free to comment if you have questions, correct errors or need help !

Page 1 of 11

Related posts:

1. Tutorial How to move the Player with keyboard inputs in Unity3d keyboard input
javascript
2. Import animated model from Blender to Unity and play the animation with scripting

3. The best and easiest tool to make a video game : UNITY3D Editor

4. Easiest Unity video tutorials for beginners game programmers

S-ar putea să vă placă și