Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMovementController.cs
More file actions
Latest commit
88 lines (78 loc) · 2.7 KB
/
Copy pathMovementController.cs
File metadata and controls
88 lines (78 loc) · 2.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
/*
A movement script, including an animation state machine, for a top-down RPG game
*/
usingSystem.Collections;
usingSystem.Collections.Generic;
usingUnityEngine;
publicclassMovementController:MonoBehaviour
{
// instance variables
publicfloatmovementSpeed=3.0f;
Vector2movement=newVector2();
Animatoranimator;
stringanimationState="AnimationState";
Rigidbody2Drb2D;
// An enum is a set of enumerated constants. Each constant is used to store an integer value to represent each animation state.
enumCharStates
{
walkEast=1,
walkSouth=2,
walkWest=3,
walkNorth=4,
idleSouth=5
}
privatevoidStart()
{
// get components for animation and movement
animator=GetComponent<Animator>();
rb2D=GetComponent<Rigidbody2D>();
}
privatevoidUpdate()
{
// Call UpdateState method to update animation state
// If you are not using the animation, comment out the call to this method to just use movement.
UpdateState();
}
voidFixedUpdate()
{
// Call method to update movement
MoveCharacter();
}
privatevoidMoveCharacter()
{
// the GetAxisRaw method takes a parameter specifying which 2D axis we are interested in, horizontal or vertical,
// and retrieves a -1, 0, or 1 from the Unity Input Manager and returns it.
// 1 = "d" or "right arrow"; -1 = "a" of "left arrow"; 0 = no key pressed.
// This is configurable in the Unity Input Manager settings.
movement.x=Input.GetAxisRaw("Horizontal");
movement.y=Input.GetAxisRaw("Vertical");
// Normalize() will normalize our vector and keep the player moving at the same rate of speed, no matter the direction.
movement.Normalize();
// Set the velocity of the Rigidbody2D component to move the character
rb2D.velocity=movement*movementSpeed;
}
privatevoidUpdateState()
{
// Setting character animation state based on movement direction.
if(movement.x>0)
{
animator.SetInteger(animationState,(int)CharStates.walkEast);
}
elseif(movement.x<0)
{
animator.SetInteger(animationState,(int)CharStates.walkWest);
}
elseif(movement.y>0)
{
animator.SetInteger(animationState,(int)CharStates.walkNorth);
}
elseif(movement.y<0)
{
animator.SetInteger(animationState,(int)CharStates.walkSouth);
}
else
{
animator.SetInteger(animationState,(int)CharStates.idleSouth);
}
}
}