-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMovementController.cs
More file actions
88 lines (78 loc) · 2.7 KB
/
MovementController.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
*/
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MovementController : MonoBehaviour
{
// instance variables
public float movementSpeed = 3.0f;
Vector2 movement = new Vector2();
Animator animator;
string animationState = "AnimationState";
Rigidbody2D rb2D;
// An enum is a set of enumerated constants. Each constant is used to store an integer value to represent each animation state.
enum CharStates
{
walkEast = 1,
walkSouth = 2,
walkWest = 3,
walkNorth = 4,
idleSouth = 5
}
private void Start()
{
// get components for animation and movement
animator = GetComponent<Animator>();
rb2D = GetComponent<Rigidbody2D>();
}
private void Update()
{
// 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();
}
void FixedUpdate()
{
// Call method to update movement
MoveCharacter();
}
private void MoveCharacter()
{
// 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;
}
private void UpdateState()
{
// Setting character animation state based on movement direction.
if (movement.x > 0)
{
animator.SetInteger(animationState, (int)CharStates.walkEast);
}
else if (movement.x < 0)
{
animator.SetInteger(animationState, (int)CharStates.walkWest);
}
else if (movement.y > 0)
{
animator.SetInteger(animationState, (int)CharStates.walkNorth);
}
else if (movement.y < 0)
{
animator.SetInteger(animationState, (int)CharStates.walkSouth);
}
else
{
animator.SetInteger(animationState, (int)CharStates.idleSouth);
}
}
}