fuzzyworld

godot-shooter / godot-4-testing / files / Player.gd

Branch godot-4-testing · default branch · all branches

Player.gd

Blame: the commit that last changed each line · file · history

11a2e1d9 2023-10-31 Pavel Safronov1extends CharacterBody2D
b856550a 2023-10-30 Pavel Safronov2
11a2e1d9 2023-10-31 Pavel Safronov3@export var move_speed = 200
4@export var health = 8
5@export var max_health = 10
6@export var shot_period_seconds = .1
7@export var bullet: PackedScene
b856550a 2023-10-30 Pavel Safronov8
9#onready var bullet = preload("res://Bullet.tscn")
10
11var dead = false
12var can_fire = true
13
14
15func _process(delta: float) -> void:
16 if Input.is_action_just_pressed("exit"):
17 get_tree().quit()
18 if Input.is_action_just_pressed("restart"):
19 restart()
20 if dead:
21 return
22 if Input.is_action_pressed("shoot"):
23 shoot()
24
25
26func _physics_process(delta: float) -> void:
27 if dead:
28 return
29 handle_mouse_controls(delta)
11a2e1d9 2023-10-31 Pavel Safronov30 move_and_slide()
b856550a 2023-10-30 Pavel Safronov31
32func restart():
33 get_tree().reload_current_scene()
34
35func handle_mouse_controls(delta: float) -> void:
36 global_rotation = global_position.direction_to(get_global_mouse_position()).angle() + PI/2.0
37 var turn_dir = Input.get_action_strength("move_right") - Input.get_action_strength("move_left")
38 global_rotation += turn_dir * delta
39 var direction = Vector2.UP.rotated(global_rotation)
40 var forward_dir = Input.get_action_strength("move_up") - Input.get_action_strength("move_down")
41 if forward_dir != 0:
42 var diff = direction * forward_dir * move_speed * delta
43 position += diff
44
45func kill():
46 if dead:
47 return
48 dead = true
49 $Graphics/Dead.show()
50 $Graphics/Alive.hide()
51 $CanvasLayer/DeathScreen.show()
52 z_index = -1
53
54func hurt():
55 if dead:
56 return
57 health -= 1
58 if health <= 0:
59 kill()
60
61func shoot():
62 if !can_fire:
63 return
64 can_fire = false
65 $ShotTimer.wait_time = shot_period_seconds
66 $ShotTimer.start()
11a2e1d9 2023-10-31 Pavel Safronov67 var b = bullet.instantiate()
b856550a 2023-10-30 Pavel Safronov68 owner.add_child(b)
69 b.transform = $Barrel.global_transform
70
71func allow_fire():
72 can_fire = true