建立一個轉向係數的變數
@export var steering_factor := 10.0 ## 轉向係數
在物理偵加入期望速度 與 轉向係數
#期望速度 = 最高速度 * 方向
var desired_velocity := max_speed * direction
#轉向係數 = 期望速度 - 速度
var steering_vector := desired_velocity - velocity
重新修改移動的數度
## 速度 += 轉向係數 * 轉向向量 * 每秒(delta)
velocity += steering_factor * steering_vector * delta
最後在角色移動或停止的時候可以得到一個平滑的過渡
完整的原始碼
extends Area2D
@export var boost_speed := 1500.0 ## 加速度
@export var normal_speed := 600.0 ## 普通速度
var max_speed := normal_speed ## 最高速度 預設為 普通速度
var velocity := Vector2(0,0)
@export var steering_factor := 10.0 ## 轉向係數
func _physics_process(delta: float) -> void:
var direction := Vector2(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() ## 倒數計時開始
## 進行移動
var desired_velocity := max_speed * direction #期望速度 = 最高速度 * 方向
var steering_vector := desired_velocity - velocity #轉向係數 = 期望速度 - 速度
#velocity = direction * max_speed ## 速度 = 方向 * 最高速度
velocity += steering_factor * steering_vector * delta ## 速度 = 轉向係數 * 轉向向量 * 每秒(delta)
position += velocity * delta ## 位置 += 移動速度與方向 * 每秒(delta)
## 倒數計時時間到了呼叫
func _on_timer_timeout() -> void:
max_speed = normal_speed ## 最高速度 = 普通速度
留言