如何在脚本中冻结Rigidbody2D旋转?解决2D平台角色碰撞旋转问题
解决2D平台角色碰撞后旋转的问题
有两种简单的方法可以让角色始终保持旋转为0:
方法1:通过Inspector面板设置(无需改代码)
选中你的角色对象,找到Rigidbody2D组件,在Constraints(约束)选项里,勾选Freeze Rotation Z。这样物理引擎会直接锁定角色的旋转,碰撞时不会产生任何旋转效果。
方法2:通过代码设置约束
如果需要在运行时动态控制,可以在PlayerController脚本里添加Start方法,强制冻结旋转:
using System.Collections; using UnityEngine; // 补充缺失的命名空间 public class PlayerController : MonoBehaviour { //Movement public float speed; public float jump; float moveVelocity; //Grounded Vars bool grounded = true; void Start() { // 冻结Z轴旋转,保留其他物理行为 GetComponent<Rigidbody2D>().constraints = RigidbodyConstraints2D.FreezeRotation; // 若需同时冻结X/Y位置(可选),可使用: // GetComponent<Rigidbody2D>().constraints = RigidbodyConstraints2D.FreezeRotation | RigidbodyConstraints2D.FreezePositionX; } void Update () { //Jumping if (Input.GetKeyDown (KeyCode.Space) || Input.GetKeyDown (KeyCode.UpArrow) || Input.GetKeyDown (KeyCode.Z) || Input.GetKeyDown (KeyCode.W)) { if(grounded) { GetComponent<Rigidbody2D>().velocity = new Vector2 (GetComponent<Rigidbody2D>().velocity.x, jump); } } moveVelocity = 0; //Left Right Movement if (Input.GetKey (KeyCode.LeftArrow) || Input.GetKey (KeyCode.A)) { moveVelocity = -speed; } if (Input.GetKey (KeyCode.RightArrow) || Input.GetKey (KeyCode.D)) { moveVelocity = speed; } GetComponent<Rigidbody2D>().velocity = new Vector2 (moveVelocity, GetComponent<Rigidbody2D>().velocity.y); } //Check if Grounded void OnTriggerEnter2D() { grounded = true; } void OnTriggerExit2D() { grounded = false; } }
补充说明
- 方法1是最推荐的方案,直接通过物理引擎约束实现,性能更好且无额外代码开销。
- 不建议在
Update里强制设置transform.rotation = Quaternion.identity,这种方式会覆盖物理引擎的旋转计算,可能导致碰撞时角色出现抖动等异常行为。
内容的提问来源于stack exchange,提问作者iv1x
相关产品推荐
相关产品推荐

