1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
| class_name Player extends CharacterBody2D
// 将属性和需要的节点抽取出来 var move_speed: float = 100.0 var direction: Vector2 = Vector2.ZERO var cardinal_direction: Vector2 = Vector2.DOWN var state: String = "idle"
@onready var animation_player: AnimationPlayer = $AnimationPlayer @onready var sprite: Sprite2D = $Sprite2D
func _ready() -> void: pass func _process(delta: float) -> void: direction.x = Input.get_action_strength("right") - Input.get_action_strength("left") direction.y = Input.get_action_strength("down") - Input.get_action_strength("up")
velocity = direction * move_speed // 如果状态或者方向改变了就更新 if SetState() || SetDirection(): UpdateAnimation() pass
func _physics_process(delta: float) -> void: move_and_slide()
// cardinal_direction是保持的状态方向,比如说之前向上,但是不按方向键也要维持向上的状态 // direction是按键运动的方向,按方向键之后要更新方向 func SetDirection() -> bool: var new_dir: Vector2 = cardinal_direction if direction == Vector2.ZERO: return false if direction.y == 0: new_dir = Vector2.LEFT if direction.x < 0 else Vector2.RIGHT if direction.x == 0: new_dir = Vector2.UP if direction.y < 0 else Vector2.DOWN if cardinal_direction == direction: return false cardinal_direction = new_dir sprite.scale.x = -1 if cardinal_direction == Vector2.LEFT else 1 return true // 判断空闲状态还是行走状态,idle或walk func SetState() -> bool: var new_state: String = "idle" if direction == Vector2.ZERO else "walk" if new_state == state: return false state = new_state return true
// 更新需要运行的动画 func UpdateAnimation() -> void: animation_player.play(state + "_" + AnimationDirection()) func AnimationDirection() -> String: if cardinal_direction == Vector2.DOWN: return "down" elif cardinal_direction == Vector2.UP: return "up" else: return "side"
|