summaryrefslogtreecommitdiff
path: root/Player.gd
blob: 6e2bfd90960d039bfb9d71588a4ea84a2bd66dd7 (plain)
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
extends CharacterBody2D


const SPEED = 60

const JUMP_VELOCITY = -400

# Get the gravity from the project settings to be synced with RigidBody nodes.
var gravity = ProjectSettings.get_setting("physics/2d/default_gravity")

var is_jumping = false
var was_jumping = false
var last_velocity = Vector2(0,0)


func _physics_process(delta):
	# Get the input direction and handle the movement/deceleration.
	# As good practice, you should replace UI actions with custom gameplay actions.
	var direction = Input.get_axis("ui_left", "ui_right")
	if direction:
		velocity.x = direction * SPEED
		if is_on_floor():
			$AnimationTree.active = true
			$AnimationTree.get("parameters/playback").travel("Walk")
		if velocity.x > 0:
			$AnimatedSprite2D.flip_h = false
		else:
			$AnimatedSprite2D.flip_h = true
	else:
		velocity.x = move_toward(velocity.x, 0, SPEED)
	
	if velocity == Vector2(0,0):
		$AnimationTree.active = false
		if $AnimatedSprite2D.animation == "jump_land" or $AnimatedSprite2D.animation == "walk_end":
			await $AnimatedSprite2D.animation_finished
		$AnimatedSprite2D.play("idle")
	
	# Add the gravity.
	if not is_on_floor():
		velocity.y += gravity * delta
	
	# Handle jump.
	if Input.is_action_just_pressed("jump") and is_on_floor():
		velocity.y = JUMP_VELOCITY
		$AnimationTree.active = true
		$AnimationTree.get("parameters/playback").travel("Jump")
		is_jumping = true
	if Input.is_action_just_released("jump"):
		$AnimatedSprite2D.play("jump_fall")
		$AnimationTree.active = false
		if velocity.y < 0:
			velocity.y = 0
	if not is_on_floor() and velocity.y > 0:
		$AnimatedSprite2D.play("jump_fall")
		$AnimationTree.active = false
	if is_jumping and is_on_floor():
		was_jumping = true
		is_jumping = false
	#print(last_velocity.y > 0 and velocity.y == 0)
	if was_jumping or (last_velocity.y > 0 and velocity.y <= 0): # TODO: state machine
		was_jumping = false
		$AnimatedSprite2D.play("jump_land")
	
	# Wall jump
	if is_on_wall() and not is_on_floor() and direction and Input.is_action_just_pressed("jump"):
		velocity.y = JUMP_VELOCITY
		velocity.x += abs((SPEED*2) / (JUMP_VELOCITY/gravity)) * -direction

	move_and_slide()
	last_velocity = velocity