godot-shooter / godot-4-testing / files / Player.gd
Branch godot-4-testing · default branch · all branches
Player.gd
| 1 | extends CharacterBody2D |
| 2 | |
| 3 | @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 |
| 8 | |
| 9 | #onready var bullet = preload("res://Bullet.tscn") |
| 10 | |
| 11 | var dead = false |
| 12 | var can_fire = true |
| 13 | |
| 14 | |
| 15 | func _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 | |
| 26 | func _physics_process(delta: float) -> void: |
| 27 | if dead: |
| 28 | return |
| 29 | handle_mouse_controls(delta) |
| 30 | move_and_slide() |
| 31 | |
| 32 | func restart(): |
| 33 | get_tree().reload_current_scene() |
| 34 | |
| 35 | func 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 | |
| 45 | func 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 | |
| 54 | func hurt(): |
| 55 | if dead: |
| 56 | return |
| 57 | health -= 1 |
| 58 | if health <= 0: |
| 59 | kill() |
| 60 | |
| 61 | func shoot(): |
| 62 | if !can_fire: |
| 63 | return |
| 64 | can_fire = false |
| 65 | $ShotTimer.wait_time = shot_period_seconds |
| 66 | $ShotTimer.start() |
| 67 | var b = bullet.instantiate() |
| 68 | owner.add_child(b) |
| 69 | b.transform = $Barrel.global_transform |
| 70 | |
| 71 | func allow_fire(): |
| 72 | can_fire = true |