我正在Godot(版本4.3)中开发一款2D游戏,并且有一个由多个精灵(例如身体、头部、装备)组成的角色。这些精灵都是 CharacterBody2D 根节点的子节点。
我想翻转角色,使其根据移动方向向左或向右。我试图通过更改根节点的scale.x来实现这一点,期望所有子精灵相应地翻转。
这是我当前的代码:
extends CharacterBody2D
@export_group("Instances")
@export var animationPlayer: AnimationPlayer
const SPEED = 150.0
var facing_direction = 1 # 1 means right, -1 means left
var initial_scale_x # Variable to store the original scale
func _ready():
animationPlayer.play("Idle")
initial_scale_x = scale.x # Store the original scale
func _physics_process(_delta):
var direction = Vector2.ZERO
# Collect input for movement direction
if Input.is_action_pressed("ui_right"):
direction.x += 1
if Input.is_action_pressed("ui_left"):
direction.x -= 1
if Input.is_action_pressed("ui_down"):
direction.y += 1
if Input.is_action_pressed("ui_up"):
direction.y -= 1
# Movement and animations
if direction.length() > 0:
animationPlayer.play("Run")
velocity = direction.normalized() * SPEED
else:
animationPlayer.play("Idle")
velocity = Vector2.ZERO
# Flipping the character based on movement direction
if direction.x != 0 and facing_direction != sign(direction.x):
scale.x = initial_scale_x * sign(direction.x)
facing_direction = sign(direction.x)
move_and_slide()
问题:
角色翻转没有按预期工作:
我尝试过的:
问题: 当我更改根节点的scale.x 时,为什么我的角色不能始终在左右之间翻转?我错过了什么吗?如何在不单独调整每个精灵的情况下正确翻转具有多个精灵的角色?
附加信息:
我很感激任何提示或解决方案!
问题是,scale.x 并没有像你想象的那样做。请参阅文档:
“2D 中的负 X 尺度无法从变换矩阵中分解。由于 Godot 中用变换矩阵表示尺度的方式,X 轴上的负尺度将更改为 Y 轴上的负尺度并旋转 180 度分解时。”
因此,通过将scale.x设置为-1,真正发生的情况是你的scale.y设置为-1并且旋转设置为180。
太有趣了,如果你替换你的代码就会简单地工作:
scale.x = initial_scale_x * sign(direction.x)
与
scale.x = -1