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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
|
using UnityEngine;
using System.Collections;
public class PlayerMovementScript : MonoBehaviour {
Rigidbody2D rb2d;
//Movement
float MaxSpeed;
public float MaxNormalSpeed = 10f;
public float MaxSprintSpeed = 15f;
public float ForceFactor = 60f;
public bool FacingRight = true;
//Movement animation
GameObject PlayerTrail;
//Jump
public float jumpShortSpeed = 10f;
public float jumpSpeed = 30f;
bool jump = false;
bool jumpCancal = false;
public bool grounded = true;
void Start ()
{
rb2d = gameObject.GetComponent<Rigidbody2D>();
MaxSpeed = MaxNormalSpeed;
PlayerTrail = GameObject.FindGameObjectWithTag("PlayerTrail");
}
void Update ()
{
//Jump
if (Input.GetButtonDown("Jump") && grounded)
{
jump = true;
}
if (Input.GetButtonUp("Jump") && !grounded)
{
jumpCancal = true;
}
}
void FixedUpdate()
{
//Horizontal
rb2d.AddForce(Vector2.right * Input.GetAxis("Horizontal") * ForceFactor);
//Left-Right Movement
if (rb2d.velocity.x > 0.0001f)
{
transform.localScale = new Vector3(1, 1, 1);
FacingRight = true;
}
if (rb2d.velocity.x < -0.0001f)
{
transform.localScale = new Vector3(-1, 1, 1);
FacingRight = false;
}
//Max Speed
if (rb2d.velocity.x > MaxSpeed)
{
rb2d.velocity = new Vector2(MaxSpeed, rb2d.velocity.y);
}
else if (rb2d.velocity.x < -MaxSpeed)
{
rb2d.velocity = new Vector2(-MaxSpeed, rb2d.velocity.y);
}
//Sprint
if (Input.GetAxis("Sprint") == 1)
{
MaxSpeed = MaxSprintSpeed;
}
if (Input.GetAxis("Sprint") == 0)
{
if (rb2d.velocity.x > MaxNormalSpeed )
{
MaxSpeed = Mathf.Lerp(rb2d.velocity.x, MaxNormalSpeed, .1f);
}
else if (rb2d.velocity.x < -MaxNormalSpeed)
{
MaxSpeed = Mathf.Lerp(-rb2d.velocity.x, MaxNormalSpeed, .1f);
}
}
//Sprint animation
if (rb2d.velocity.x == MaxSprintSpeed || rb2d.velocity.x == -MaxSprintSpeed)
{
PlayerTrail.SetActive(true);
}
else if (rb2d.velocity.x < 10.1f && rb2d.velocity.x > -10.1f)
PlayerTrail.SetActive(false);
//Jump
if (jump)
{
rb2d.velocity = new Vector2(rb2d.velocity.x, jumpSpeed);
jump = false;
}
if (jumpCancal)
{
if (rb2d.velocity.y > jumpShortSpeed)
rb2d.velocity = new Vector2(rb2d.velocity.x, Mathf.Lerp(rb2d.velocity.y, jumpShortSpeed, .6f));
jumpCancal = false;
}
}
public void StopPlayer()
{
rb2d.velocity = new Vector2(0, 0);
PlayerTrail.SetActive(false);
}
}
|