Unity玩家角色碰撞墙体时出现抖动问题求助
Unity角色撞墙抖动问题解决方案
当角色向墙体移动发生碰撞时,物理引擎会尝试将角色从墙体中推开,但你的代码在FixedUpdate里持续强制设置水平速度,导致物理修正和代码强制移动之间产生冲突,进而引发抖动。以下是几种可行的解决方法:
方案1:检测碰撞后停止强制水平移动
通过检测角色水平方向是否与墙体碰撞,若碰撞则不再强制设置水平速度,交由物理引擎处理碰撞状态:
using UnityEngine; public class Movement2 : MonoBehaviour { [Header("Movement")] public float Speed = 4f; public float jumpPower = 3f; private Rigidbody2D rb; private GroundCheck gr; private float horizontal; private void Start() { rb = GetComponent<Rigidbody2D>(); gr = GetComponent<GroundCheck>(); } private void Update() { horizontal = Input.GetAxisRaw("Horizontal"); if (gr.grounded && Input.GetButtonDown("Jump")) { rb.velocity = new Vector2(rb.velocity.x, jumpPower); } } private void FixedUpdate() { bool isTouchingWall = false; ContactPoint2D[] contacts = new ContactPoint2D[10]; int contactCount = rb.GetContacts(contacts); for (int i = 0; i < contactCount; i++) { if (Mathf.Abs(contacts[i].normal.x) > 0.9f) { isTouchingWall = true; break; } } if (!isTouchingWall) { rb.velocity = new Vector2(horizontal * Speed, rb.velocity.y); } } }
方案2:用MovePosition替代直接设置velocity
MovePosition会更平滑地处理物理移动,减少与碰撞系统的冲突:
修改FixedUpdate方法:
private void FixedUpdate() { Vector2 targetPosition = rb.position + new Vector2(horizontal * Speed * Time.fixedDeltaTime, 0); rb.MovePosition(targetPosition); }
方案3:调整物理设置优化碰撞
- 给角色的Rigidbody2D设置
Collision Detection为Continuous,适配快速移动的物体 - 确保角色与墙体的碰撞体无初始重叠,避免物理引擎频繁修正位置
- 适当调整角色的
Linear Drag参数,降低碰撞后的速度突变
内容的提问来源于stack exchange,提问作者Mighty
相关产品推荐
相关产品推荐

