我有一個在
這是我的角色代碼:
extends KinematicBody2D
var _inputVec = Vector2.ZERO
var VELOCITY = Vector2.ZERO
var LAST_INPUT = Vector2.ZERO
const MAX_SPEED = 70
const ACCELERATION = 500
const FRICTION = 500
onready var animationPlayer = $AnimationPlayer
func _ready():
print("game started!")
func _physics_process(delta):
_inputVec.x = Input.get_action_strength("ui_right") - Input.get_action_strength("ui_left")
_inputVec.y = Input.get_action_strength("ui_down") - Input.get_action_strength("ui_up")
_inputVec = _inputVec.normalized()
if _inputVec != Vector2.ZERO:
if _inputVec.x > 0:
animationPlayer.play("playerRunRight")
elif _inputVec.y < 0:
animationPlayer.play("playerRunUp")
elif _inputVec.y > 0:
animationPlayer.play("playerRunDown")
else:
animationPlayer.play("playerRunLeft")
VELOCITY = VELOCITY.move_toward(_inputVec * MAX_SPEED, ACCELERATION * delta)
LAST_INPUT = _inputVec
else:
VELOCITY = VELOCITY.move_toward(Vector2.ZERO, FRICTION * delta)
if Input.is_action_just_pressed("ui_lmb"):
if LAST_INPUT.x > 0:
animationPlayer.play("playerAttackRight")
elif LAST_INPUT.y < 0:
animationPlayer.play("playerAttackUp")
elif LAST_INPUT.y > 0:
animationPlayer.play("playerAttackDown")
else:
animationPlayer.play("playerAttackLeft")
else:
if LAST_INPUT.x > 0:
animationPlayer.play("playerIdleRight")
elif LAST_INPUT.y < 0:
animationPlayer.play("playerIdleUp")
elif LAST_INPUT.y > 0:
animationPlayer.play("playerIdleDown")
else:
animationPlayer.play("playerIdleLeft")
VELOCITY = move_and_slide(VELOCITY)
完整專案可在我的Github 存盤庫中找到
uj5u.com熱心網友回復:
請記住,_physics_process每個(物理)幀運行一次。
因此,您按下滑鼠左鍵的一幀,就必須執行這一行:
animationPlayer.play("playerAttackRight")
但是下一個(物理)幀,您還沒有按下滑鼠左鍵,所以這個條件是錯誤的:
if Input.is_action_just_pressed("ui_lmb"):
然后這一行開始執行:
animationPlayer.play("playerIdleRight")
因此,您只能看到大約一幀"playerAttackRight"影片。
您將需要跟蹤當前狀態(運行、攻擊、空閑)。規則是您可以立即從運行變為空閑,但您只能在攻擊影片結束時從攻擊變為空閑。
當然,您可以使用變數跟蹤當前狀態。您可以通過輸入和變數狀態的值來決定新狀態。然后分別讀取狀態變數并決定播放哪個影片。您可能還想在某些影片結束時設定狀態變數。
要在影片結束時執行某些操作,您可以使用以下任一資源來產生:
yield(animationPlayer, "animation_finished")
這將使您的代碼在收到"animation_finished"信號后恢復。
或者,否則您可以連接到"animation_finished"信號。
順便說一句,您還可以對影片進行排隊:
animationPlayer.queue("name_of_some_animation")
雖然AnimationPlayer像你一樣使用是可以的。當它變得復雜時,您應該考慮另一個工具:AnimationTree.
創建一個AnimationTree節點,給它你的影片播放器,并將根設定為一個新的AnimationNodeStateMachine. 您可以在那里創建狀態機,并配置它們之間的轉換是立即轉換還是最后轉換。
然后,從代碼中,您可以獲取狀態機播放物件,如下所示:
var state_machine = $AnimationTree.get("parameters/playback")
你可以問它當前的狀態是什么:
var state:String = state_machine.get_current_node()
您可以將其用作決定要去哪個州的一部分。然后告訴它你想讓它進入不同的狀態,就像這樣:
state_machine.travel("name_of_some_state")
使用它會尊重您設定的轉換,因此您不必在代碼中擔心它。
您可以在以下位置找到有關使用的更多資訊AnimationTree:
- 使用影片樹
- 控制影片狀態
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/393546.html
上一篇:如何繪制L形影片線?
