-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathplayer.gd
82 lines (58 loc) · 2.51 KB
/
player.gd
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
class_name Player
extends Node2D
onready var ray = $RayCast2D as RayCast2D
var speed = 512 # big number because it's multiplied by delta
var tile_size = 64 # size in pixels of tiles on the grid
var last_position = Vector2() # last idle position
var target_position = Vector2() # desired position to move towards
var movedir = Vector2() # move direction
var last_direction = Vector2(0, 1)
func _ready():
position = position.snapped(Vector2(tile_size, tile_size)) # make sure player is snapped to grid
last_position = position
target_position = position
func _process(delta):
# MOVEMENT
if ray.is_colliding():
position = last_position
target_position = last_position
else:
position += speed * movedir * delta
if position.distance_to(last_position) >= tile_size: # if we've moved further than one space
position = target_position # snap the player to the intended position
if is_idle():
get_movedir()
last_position = position # record the player's current idle position
target_position += movedir * tile_size # if key is pressed, get new target (also shifts to moving state)
# TODO: use move_and_slide?
animate_player(movedir)
func is_idle() -> bool:
return position == target_position
# GET DIRECTION THE PLAYER WANTS TO MOVE
func get_movedir():
var LEFT = Input.is_action_pressed("ui_left")
var RIGHT = Input.is_action_pressed("ui_right")
var UP = Input.is_action_pressed("ui_up")
var DOWN = Input.is_action_pressed("ui_down")
movedir.x = -int(LEFT) + int(RIGHT) # if pressing both directions this will return 0
movedir.y = -int(UP) + int(DOWN)
if movedir.x != 0 && movedir.y != 0: # prevent diagonals
movedir = Vector2.ZERO
if movedir != Vector2.ZERO:
ray.cast_to = movedir * tile_size / 2
func animate_player(direction: Vector2) -> void:
var animation: String
var sprite := $Sprite as AnimatedSprite
if direction != Vector2.ZERO:
# gradually update last_direction to counteract the bounce of the analog stick
last_direction = (0.5 * last_direction) + (0.5 * direction)
# Choose walk animation based on movement direction
animation = animation_direction(last_direction) + "_walk"
else:
# Choose idle animation based on last movement direction and play it
animation = animation_direction(last_direction) + "_idle"
# TODO: this still isn't playing the walk animations when tapping movement keys instead of holding them down
if sprite.animation != animation:
sprite.play(animation)
func animation_direction(direction: Vector2):
return Utils.make_compass_for_direction(direction).relative()