效果图1:
2.利用程序冻结刚体的Rotation using System.Collections;using System.Collections.Generic;using UnityEngine;public class pengZhuang : MonoBehaviour{//Start is called before the first frame updateprivate Rigidbody rigidbody;void Start(){rigidbody = this.GetComponent<Rigidbody>(); //此脚本挂在此刚体所属物体物体上,并获得刚体组件}void Update(){rigidbody.constraints = RigidbodyConstraints.FreezeRotationY; //冻结刚体绕Y轴的旋转,物体只能绕X轴与Z轴旋转}}效果图2:
3.同时冻结刚体的Position和Rotation using System.Collections;using System.Collections.Generic;using UnityEngine;public class pengZhuang : MonoBehaviour{//Start is called before the first frame updateprivate Rigidbody rigidbody;void Start(){rigidbody = this.GetComponent<Rigidbody>(); //此脚本挂在此刚体所属物体物体上,并获得刚体组件}void Update(){rigidbody.constraints = RigidbodyConstraints.FreezePositionY | RigidbodyConstraints.FreezeRotationY; //冻结刚体在Y轴上的移动,并冻结刚体绕Y轴的旋转}}效果图3:
请注意,如果要同时冻结多个轴时,不能像如下所示:
rigidbody.constraints = RigidbodyConstraints.FreezePositionX;rigidbody.constraints = RigidbodyConstraints.FreezePositionY;rigidbody.constraints = RigidbodyConstraints.FreezePositionZ;rigidbody.constraints = RigidbodyConstraints.FreezeRotationX;rigidbody.constraints = RigidbodyConstraints.FreezeRotationY;rigidbody.constraints = RigidbodyConstraints.FreezeRotationZ;后面的程序会覆盖前面的,运行的最后效果只是冻结了刚体绕Z轴旋转。
效果图4:
5.实例(物体着陆碰撞到地面后,冻结物体在Y轴上的移动和绕Z、X轴旋转,使物体可以在水平面上移动旋转) using System.Collections;using System.Collections.Generic;using UnityEngine;public class pengZhuang : MonoBehaviour{ // Start is called before the first frame update private Rigidbody rigidbody; void Start() { rigidbody = this.GetComponent<Rigidbody>(); } private void OnCollisionEnter(Collision collision) { rigidbody.constraints = RigidbodyConstraints.FreezePositionY | RigidbodyConstraints.FreezeRotationX | RigidbodyConstraints.FreezeRotationZ; //在此物体发生碰撞时,冻结刚体在Y轴上移动,并冻结刚体绕X轴和Z轴旋转 //最后的效果是物体可以在水平面上移动,可以绕Y轴旋转 }}效果图5:
6.冻结除某个轴外所有其他的轴 using System.Collections;using System.Collections.Generic;using UnityEngine;public class pengZhuang : MonoBehaviour{//Start is called before the first frame updateprivate Rigidbody rigidbody;void Start(){rigidbody = this.GetComponent<Rigidbody>(); //此脚本挂在此刚体所属物体物体上,并获得刚体组件}void Update(){rigidbody.constraints = ~RigidbodyConstraints.FreezePositionY; //效果见下图}}效果图6:
如果有不足之处,欢迎留言,相互促进,谢谢!!!