Godot 2D Top Down 玩家控制 / (移動加速度)程式碼

Godot 2D Top Down 玩家控制 / (移動)程式碼 該篇進行加速度控制

首先於 專案 > 專案設定 > 輸入映射 建立動作

我們加入 boost 與對應的 空白建

Sprite 加入 子節點 Timer

Timer 的屬性 One Shot 啟用

接著改寫程式碼就可以透過按下空白建使角色加速至 1500.0 並持續
extends Area2D

@export var boost_speed := 1500.0 ## 加速度
@export var normal_Speed := 600.0 ## 普通速度
var max_speed := normal_Speed ##最高速度
var velocity := Vector2(0.0,0.0)

func _physics_process(delta: float) -> void:
	var direction := Vector2(0.0,0.0)
	direction.x = Input.get_axis("move_left","move_right")
	direction.y = Input.get_axis("move_up","move_down")
	
	if direction.length() > 1.0:
		direction = direction.normalized()
	
	if Input.is_action_just_pressed("boost"):
		max_speed = boost_speed
		get_node("Sprite2D/Timer").start()
	
	print("max_speed=", max_speed)
	velocity = direction * max_speed ## 速度 = 方向 * 最高速度
	position += velocity * delta ## 位置 += 移動速度與方向 * 每秒(delta)

Timer 倒數後將速度改為普通速度

選擇 Timer 並於屬性面板選擇 節點

連接 Timeout() 訊號

在 訊號 的 Timeout() 上點選滑鼠左鍵兩下進行連接

接著加入在時間倒數完成後 將 最大速度改為普通速度就完成了使用空白建進行加速度的功能

func _on_timer_timeout() -> void:
	max_speed = normal_Speed
完整的原始碼
extends Area2D

@export var boost_speed := 1500.0 ## 加速度
@export var normal_Speed := 600.0 ## 普通速度
var max_speed := normal_Speed ##最高速度
var velocity := Vector2(0.0,0.0)

func _physics_process(delta: float) -> void:
	var direction := Vector2(0.0,0.0)
	direction.x = Input.get_axis("move_left","move_right")
	direction.y = Input.get_axis("move_up","move_down")
	
	if direction.length() > 1.0:
		direction = direction.normalized()
	
	if Input.is_action_just_pressed("boost"):
		max_speed = boost_speed
		get_node("Sprite2D/Timer").start()
	
	print("max_speed=", max_speed)
	velocity = direction * max_speed ## 速度 = 方向 * 最高速度
	position += velocity * delta ## 位置 += 移動速度與方向 * 每秒(delta)
    
func _on_timer_timeout() -> void:
	max_speed = normal_Speed

下篇: Godot 2D Top Down 玩家控制 / (平穩的加減速)程式碼

留言

這個網誌中的熱門文章