Unity中通过transform.localScale翻转动画时位置闪烁问题
Unity角色翻转位置闪烁问题解决方法
问题根源
修改transform.localScale.x导致位置闪烁,核心原因是模型的轴心点(Pivot)不在几何中心,缩放时角色会围绕轴心点偏移,出现跳变。
解决方案
1. 调整模型轴心点到中心(最根本)
- 选中角色模型,使用Rect Transform工具(快捷键T),切换到
Pivot模式,拖动轴心点到角色的几何中心。 - 或者在模型导入设置的
Mesh选项中,将Pivot设置为Center,重新导入模型。
2. 2D角色优先用Sprite Renderer的Flip属性(最简便)
如果是2D Sprite角色,直接操作Sprite Renderer的翻转属性,完全不会影响位置:
private Rigidbody2D theRB; private SpriteRenderer spriteRenderer; void Awake() { theRB = GetComponent<Rigidbody2D>(); spriteRenderer = GetComponent<SpriteRenderer>(); } void FixedUpdate() { float horizontalInput = Input.GetAxisRaw("Horizontal"); theRB.velocity = new Vector2(horizontalInput * moveSpeed, theRB.velocity.y); // 直接设置flipX,无需修改scale spriteRenderer.flipX = horizontalInput < 0; }
3. 父物体控位置,子物体控翻转(通用方案)
适合3D或轴心点无法调整的场景:
- 创建空物体作为角色根节点(如
CharacterRoot),将Rigidbody、移动脚本挂载到根节点上。 - 将角色模型设为根节点的子物体,调整子物体位置,让模型中心与根节点原点对齐。
- 修改脚本翻转子物体的scale,而非根节点:
private Rigidbody2D theRB; private Transform modelTransform; private static readonly Vector3 FlipScale = new Vector3(-1f, 1f, 1f); private static readonly Vector3 DefaultScale = Vector3.one; void Awake() { theRB = GetComponent<Rigidbody2D>(); // 假设模型是根节点的第一个子物体 modelTransform = transform.GetChild(0); } void FixedUpdate() { float horizontalInput = Input.GetAxisRaw("Horizontal"); theRB.velocity = new Vector2(horizontalInput * moveSpeed, theRB.velocity.y); if (horizontalInput < 0) { modelTransform.localScale = FlipScale; } else if (horizontalInput > 0) { modelTransform.localScale = DefaultScale; } }
额外优化建议
- 提前定义静态Vector3变量复用,避免频繁创建新对象产生GC。
- 翻转逻辑放在
FixedUpdate中执行,和物理更新同步,减少帧不同步导致的闪烁。
内容的提问来源于stack exchange,提问作者lex
相关产品推荐
相关产品推荐

