fuzzyworld

godot-shooter / starfield-background / files / Player.gd

Branch starfield-background · default branch · all branches

Player.gd

1.8 KB · history · blame

1extends KinematicBody2D
2
3export var move_speed = 200
4export var health = 8
5export var max_health = 10
6export var shot_period_seconds = .1
7export var bullet: PackedScene
8
9var PopupControl = preload("res://Popup.tscn")
10
11var dead = false
12var velocity = Vector2.ZERO
13var can_fire = true
14
15
16func _process(delta: float) -> void:
17 if Input.is_action_just_pressed("exit"):
18 if OS.get_name() == "OSX":
19 get_tree().quit()
20 else:
21 restart()
22 if Input.is_action_just_pressed("restart"):
23 restart()
24 if dead:
25 return
26 if Input.is_action_pressed("shoot"):
27 shoot()
28 $Graphics/Alive/Control/HealthLabel.text = "%s / %s" % [health, max_health]
29 $Graphics/Alive/Control.global_rotation = 0
30
31
32func _physics_process(delta: float) -> void:
33 if dead:
34 return
35 handle_mouse_controls(delta)
36 velocity = move_and_slide(velocity)
37
38func restart():
39 get_tree().reload_current_scene()
40
41func handle_mouse_controls(delta: float) -> void:
42 global_rotation = global_position.direction_to(get_global_mouse_position()).angle() + PI/2.0
43 var turn_dir = Input.get_action_strength("move_right") - Input.get_action_strength("move_left")
44 global_rotation += turn_dir * delta
45 var direction = Vector2.UP.rotated(global_rotation)
46 var forward_dir = Input.get_action_strength("move_up") - Input.get_action_strength("move_down")
47 if forward_dir != 0:
48 var diff = direction * forward_dir * move_speed * delta
49 position += diff
50
51func kill():
52 if dead:
53 return
54 dead = true
55 $Graphics/Dead.show()
56 $Graphics/Alive.hide()
57 $CanvasLayer/DeathScreen.show()
58 z_index = -1
59
60func hurt():
61 if dead:
62 return
63 health -= 1
64 if health <= 0:
65 kill()
66
67func shoot():
68 if !can_fire:
69 return
70 can_fire = false
71 $ShotTimer.wait_time = shot_period_seconds
72 $ShotTimer.start()
73 var b = bullet.instance()
74 owner.add_child(b)
75 b.transform = $Barrel.global_transform
76
77func allow_fire():
78 can_fire = true