現在我們已經能從頭到尾進行整個遊戲並且能重複遊玩,現在我們還有一個功能 分數
的邏輯還沒有實現,分數的實現方式可以依照各個方式決定:可以依照走過的地圖張數、距離、碰撞到的指定物件等等方式來計分,這次我們使用比較單純的計分方式:遊戲時間來計算。
準備檔案:今天修改的檔案為 main
、player
這兩個腳本。
START
後的引擎啟動時間。避免使用系統時間,因為系統時間使用者可以修改。
var start_time: int
func handle_game_start():
# ...
# 重置我們的分數顯示
score_label.text = "0.00"
# 取得遊戲引擎啟動的時間(毫秒)。
start_time = Time.get_ticks_msec()
# 記錄目前狀態
enum GAME_STATE {START, STOP, END}
var game_state = GAME_STATE.END
# 更新狀態(開始/結束)
func handle_game_start():
game_state = GAME_STATE.START
# ...
func handle_game_end():
game_state = GAME_STATE.END
# ...
func _process(delta):
match game_state:
GAME_STATE.START:
hud.update_score(str("%.2f" % ((float(Time.get_ticks_msec()) - start_time)/1000)))
(float(current_time)
:這裡透過轉為浮點數的方式方便我們轉換為秒後能保留小數點後內容。(float(current_time) - start_time)
:相減取得整個開始遊戲後時間。((float(current_time) - start_time)/1000)
:轉換為秒。str("%.2f" % N秒)
:將浮點數轉為固定顯示到小數後兩位的字串。START
按鈕後重置計時器的邏輯。
func _on_start_button_pressed():
# ...
score_label.text = "0.00"
main
程式
extends Node
@export var move_obstacle_scene:PackedScene
var move_obstacles_timer:Timer
var hud:CanvasLayer
var background
var player
enum GAME_STATE {START, STOP, END}
var game_state = GAME_STATE.END
var start_time: int
# Called when the node enters the scene tree for the first time.
func _ready():
move_obstacles_timer = $MoveObstacleSpwanTimer
move_obstacles_timer.timeout.connect(_on_move_obstacle_timeout)
hud = $HUD
background = $Background
player = $Player
hud.game_start.connect(handle_game_start)
player.game_end.connect(handle_game_end)
# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(delta):
match game_state:
GAME_STATE.START:
hud.update_score(str("%.2f" % ((float(Time.get_ticks_msec()) - start_time)/1000)))
func handle_game_start():
await get_tree().create_timer(1.6).timeout
background.start()
player.start()
game_state = GAME_STATE.START
# init score
hud.update_score("0.00")
start_time = Time.get_ticks_msec()
await get_tree().create_timer(4).timeout
move_obstacles_timer.start()
func handle_game_end():
game_state = GAME_STATE.END
move_obstacles_timer.stop()
background.end()
player.end()
hud.show_game_over()
func _on_move_obstacle_timeout():
var instantiated_obj = move_obstacle_scene.instantiate()
var randf_pos = Vector2(randf_range(0, get_viewport().size.x), -3)
instantiated_obj.position = randf_pos
add_child(instantiated_obj)
:)