-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathplayer.cs
94 lines (83 loc) · 2.8 KB
/
player.cs
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
using Godot;
using System;
public partial class player : CharacterBody2D
{
public const float Speed = 100.0f;
public const float JumpVelocity = -400.0f;
public const float ACCELERATION = 600f;
public const float FRICTION = 1000f;
private AnimatedSprite2D animatedSprite2D;
private Timer coyoteJumpTimer;
// Get the gravity from the project settings to be synced with RigidBody nodes.
public float gravity = ProjectSettings.GetSetting("physics/2d/default_gravity").AsSingle();
public override void _Ready()
{
animatedSprite2D = GetNode<AnimatedSprite2D>("AnimatedSprite2D");
coyoteJumpTimer = GetNode<Timer>("CoyoteJumpTimer");
}
public override void _PhysicsProcess(double delta)
{
Vector2 velocity = Velocity;
ApplyGravity(delta, ref velocity);
HandleJump(ref velocity);
Vector2 inputAxis = Input.GetVector("ui_left", "ui_right", "ui_up", "ui_down");
HandleAcceleration(delta, ref velocity, inputAxis);
ApplyFriction(delta, ref velocity, inputAxis);
UpdateAnimation(inputAxis);
Velocity = velocity;
bool wasOnFloor = IsOnFloor();
MoveAndSlide();
bool justLeftLedge = wasOnFloor && !IsOnFloor() && velocity.Y >= 0;
if (justLeftLedge){
coyoteJumpTimer.Start();
}
}
private void HandleAcceleration(double delta, ref Vector2 velocity, Vector2 inputAxis)
{
if (inputAxis != Vector2.Zero)
{
velocity.X = Mathf.MoveToward(velocity.X, inputAxis.X * Speed, ACCELERATION * (float)delta);
}
}
private void ApplyFriction(double delta, ref Vector2 velocity, Vector2 inputAxis)
{
if(inputAxis == Vector2.Zero){
velocity.X = Mathf.MoveToward(Velocity.X, 0, FRICTION * (float)delta);
}
}
private void HandleJump(ref Vector2 velocity)
{
// Handle Jump.
if (IsOnFloor() || coyoteJumpTimer.TimeLeft > 0)
{
if (Input.IsActionJustPressed("ui_accept"))
{
velocity.Y = JumpVelocity;
}
}
else if (IsOnFloor())
{
if (Input.IsActionJustReleased("ui_accept") && velocity.Y < JumpVelocity / 2)
{
velocity.Y = JumpVelocity / 2;
}
}
}
private void ApplyGravity(double delta, ref Vector2 velocity)
{
// Add the gravity.
if (!IsOnFloor())
velocity.Y += gravity * (float)delta;
}
private void UpdateAnimation(Vector2 inputAxis){
if (inputAxis != Vector2.Zero){
animatedSprite2D.FlipH = (inputAxis < Vector2.Zero);
animatedSprite2D.Play("run");
} else{
animatedSprite2D.Play("idle");
}
if (!IsOnFloor()){
animatedSprite2D.Play("jump");
}
}
}