缩放根节点时,具有多个精灵的角色无法正确翻转

问题描述 投票:0回答:1

我正在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()

问题:

角色翻转没有按预期工作:

  • 初始状态:角色面朝右。
  • 当我向左移动时:角色正确地翻转到左侧。
  • 当我再次向右移动时:角色不会翻转回面向右侧,而是保持面向左侧。
  • 当我再次向左移动时:角色再次翻转,因此在向左移动时它最终面向右侧。

我尝试过的:

  • 更改根CharacterBody2D节点的scale.x,假设所有子精灵都会随之翻转。
  • 存储原始比例(initial_scale_x)并在翻转时使用它。
  • 确保face_direction正确更新。

问题: 当我更改根节点的scale.x 时,为什么我的角色不能始终在左右之间翻转?我错过了什么吗?如何在不单独调整每个精灵的情况下正确翻转具有多个精灵的角色?

附加信息:

  • 角色由位于CharacterBody2D节点正下方的多个Sprite2D节点组成。
  • 代码中没有其他部分影响比例或方向。
  • 我使用 move_and_slide() 进行基于速度的移动。
  • 动画效果很好;问题仅在于翻转精灵。

我很感激任何提示或解决方案!

sprite game-development godot gdscript
1个回答
0
投票

问题是,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
© www.soinside.com 2019 - 2024. All rights reserved.