Unity 2D俯视角游戏:非玩家场景对象相机抖动问题求助
问题分析与解决
核心问题定位
- 更新时机不匹配:相机在
FixedUpdate中更新,场景内其他物体逻辑若在Update执行,会导致帧间位置采样不同步,视觉上出现抖动。 - 玩家移动代码错误:
Rigidbody.velocity是每秒速度单位,无需乘以Time.deltaTime,错误计算会导致玩家运动不流畅,间接引发其他物体的相对抖动。 - 亚像素偏移:2D俯视角游戏中,物体位置未对齐整数像素时,渲染会出现模糊/抖动,相机跟随玩家后,其他未对齐物体的抖动会被放大。
具体修复步骤
1. 修正玩家移动代码
修复速度计算错误,统一使用Time.fixedDeltaTime(适配FixedUpdate的时间步长):
private void move() { // velocity本身是每秒速度,移除多余的Time.deltaTime rb.velocity = -transform.up * speed; if (Input.touchCount > 0) { var touch = Input.GetTouch(0); if (touch.position.x > Screen.width / 2) { transform.Rotate(0, 0, Time.fixedDeltaTime * rotateSpeed); rotationTimeRight += Time.fixedDeltaTime; if (rotationTimeRight > 0.5f) { rotationTimeRight = 0; var trace = Instantiate(rotationTraceRight, transform.position + new Vector3(0, 0.3f, 0), rotationTraceRight.transform.rotation); Destroy(trace, 5.0f); } } else { transform.Rotate(0, 0, -Time.fixedDeltaTime * rotateSpeed); rotationTimeLeft += Time.fixedDeltaTime; if (rotationTimeLeft > 0.5f) { rotationTimeLeft = 0; var trace = Instantiate(rotationTraceLeft, transform.position + new Vector3(0, 0.3f, 0), rotationTraceLeft.transform.rotation); Destroy(trace, 5.0f); } } } else { rotationTimeRight = 0; rotationTimeLeft = 0; } }
2. 调整相机更新时机到LateUpdate
LateUpdate会在所有Update和FixedUpdate执行完毕后运行,确保相机获取玩家最终位置,同时添加像素对齐解决亚像素抖动:
private void LateUpdate() { Vector3 desiredPosition = targetTransform.position + offset; // SmoothDamp的smoothTime参数是时间值,无需乘以Time.deltaTime(内部已处理帧同步) Vector3 smoothedPosition = Vector3.SmoothDamp(transform.position, desiredPosition, ref velocity, smoothSpeed); // 强制对齐整数像素,消除亚像素渲染抖动 smoothedPosition = new Vector3(Mathf.Round(smoothedPosition.x), Mathf.Round(smoothedPosition.y), smoothedPosition.z); transform.position = smoothedPosition; }
3. 统一场景物体的像素对齐
给所有场景精灵添加以下脚本,确保位置始终对齐整数像素:
public class PixelSnap : MonoBehaviour { private void LateUpdate() { Vector3 pos = transform.position; transform.position = new Vector3(Mathf.Round(pos.x), Mathf.Round(pos.y), pos.z); } }
也可直接在Sprite Renderer设置中开启Pixel Perfect(需导入Unity Pixel Perfect包)。
4. 优化刚体设置
- 将玩家Rigidbody2D的
Interpolate选项设为Interpolate或Extrapolate,消除FixedUpdate与Update之间的位置跳变。 - 若无需固定旋转,关闭
Fixed Angle选项,确保旋转平滑。
验证流程
- 先修复玩家移动代码的速度计算,确认玩家运动流畅。
- 迁移相机逻辑到
LateUpdate并添加像素对齐,观察相机跟随效果。 - 给其他精灵添加像素对齐脚本,检查抖动是否消失。
内容的提问来源于stack exchange,提问作者Fatih Suleyman ER
相关产品推荐
相关产品推荐

