res://
|--scenes
| |--godot_icon.tscn
| |--main.tscn
|--scripts
| |--main.gd
|--icon.svg
# 暴露出 PackedScene 到屬性面板,儲存後將 icon 的 scene 放到 main scene node上腳本的屬性面板
@export var to_be_created:PackedScene
# 宣告變數
var godot:Node
# 在 ready 時直接生成我們的物件
func _ready():
godot = to_be_created.instantiate()
add_child(godot)
首先來看官方的說明
Vector2 move_toward(to: Vector2, delta: float) const
Returns a new vector moved toward to by the fixed delta amount. Will not go past the final value.
Vector2: 回傳的類別
move_toward:函數名稱
(...):需要的輸入,一個 Vector2 類別輸入及目標,一個 float 值作為移動的量
最後在說明中可以看到這個方法會回傳一個向量
接著實際操作測試
@export var weight:float
# godot.position:起點
# get_viewport().get_mouse_position():目標位置,這裡設為取得到的滑鼠位置
# weight:剛剛宣告的變數,移動的單位
var pos = godot.position.move_toward(get_viewport().get_mouse_position(), weight)
godot.position = pos
完整檔案
extends Node
@export var to_be_created:PackedScene
@export var weight:float
var godot:Node
# Called when the node enters the scene tree for the first time.
func _ready():
godot = to_be_created.instantiate()
add_child(godot)
# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(delta):
var pos = godot.position.move_toward(get_viewport().get_mouse_position(), weight)
godot.position = pos
再來看官方的說明
Vector2 lerp(to: Vector2, weight: float) const
Returns the result of the linear interpolation between this vector and to by amount weight. weight is on the range of 0.0 to 1.0, representing the amount of interpolation.
Vector2: 回傳的類別
lerp:函數名稱
(...):需要的輸入,一個 Vector2 類別輸入及目標,一個 float 值作為插值權重
說明中可以看到這個方法一樣會回傳一個向量不過此函數計算的方式是透過線性插值的方式實作
實際操作測試
@export var weight:float
# godot.position:起點
# get_viewport().get_mouse_position():目標位置,這裡設為取得到的滑鼠位置
# weight:剛剛宣告的變數,插值的權重
var pos = godot.position.move_toward(get_viewport().get_mouse_position(), weight)
godot.position = pos
完整檔案
extends Node
@export var to_be_created:PackedScene
@export var weight:float
var godot:Node
# Called when the node enters the scene tree for the first time.
func _ready():
godot = to_be_created.instantiate()
add_child(godot)
# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(delta):
var pos = godot.position.lerp(get_viewport().get_mouse_position(), weight)
godot.position = pos
:)