unity中Rigidbody组件的其他属性和方法
Rigidbody组件的其他属性和方法
- velocity和angularVelocity
- RigidbodyConstraints
- Sleep和WakeUp
- ClosestPointOnBounds
- OnJointBreak
- CollisionDetectionMode
- SweepTest和SweepTestAll
- IsSleeping
velocity和angularVelocity
- velocity:刚体的线速度,类型为Vector3,可以直接设置或读取
- angularVelocity:刚体的角速度,类型为Vector3,同样可以直接设置或读取
public class VelocityExample : MonoBehaviour
{
public Rifidbody rb;
void Start()
{
rb = GetComponent<Rigidbody>();
}
}
RigidbodyConstraints
可以用来限制刚体的运动和旋转,例如可以锁定刚体的某轴的移动或旋转
public class ConstraintsExample : MonoBehaviour
{
public Rigidbody rb;
void Start()
{
rb = GetComponent<Rigidbody>();
//锁定X轴和Y轴的移动,只允许Z轴移动
rb.constraints = RigidbodyConstraints.FreezePositionX | GigidbodyConstraints.FreezePositionY;
//锁定所有轴的旋转
rb.constraints != RigidbodyConstraints.FreezeRotation;
}
}
Sleep和WakeUp
Sleep可以让刚体进入休眠状态,以节省计算资源,WakeUp可以让刚体从休眠状态中唤醒
public class SleepExample : MonoBehaviour
{
public Rigidbody rb;
void Start()
{
rb = GetComponent<Rigidbody>();
}
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
//让刚体进入休眠状态
rb.Sleep();
}
}
}
ClosestPointOnBounds
可以获取刚体边界上离指定点最近的点
public class ClosestPointExample : MonoBehaviour
{
public Rigidbody rb;
public Vector3 targetPoint;
void Start()
{
rb = GetComponent<Rigidbody>();
}
void Update()
{
if (Input.GetKeyDown(KeyCode.C))
{
//获取刚体边界上离目标点最近的点
Vector3 closestPoint = rb.ClosestPointOnBounds(targetPoint);
Debug.Log("Closest point on bounds:" + closestPoint);
}
}
}
OnJointBreak
可在连接刚体的关节断裂时调用,可以处理关节断裂后的逻辑
public class JointBreakExample : MonoBehaviour
{
public Rigidbody rb;
void Start()
{
rb = GetComponent<Rigidbody>();
}
void ObJointBreak(float breakForce)
{
Debug.Log("Joint broke with break force: " + breakForce);
//可以在这里添加断裂后的逻辑
}
}
CollisionDetectionMode
可以设置刚体的碰撞检测模式,包括Discrete、Continuous和ContinuousDynamic
public class CollisionDetectionModeExample : MonoBehaviour
{
public Rigidbody rb;
void Start()
{
rb = GetComponent<Rigidbody>();
//设置碰撞检测模式为连续检测
rb.collisionDetectionMode = CollisionDetectionMode.Continuous;
}
}
SweepTest和SweepTestAll
可以用来检测刚体在移动时是否会与其他物体碰撞
public class SweepTestExample : MonoBehaviour
{
public Rigidbody rb;
public Vector3 direction;
void Start()
{
rb = GetComponent<Rigidbody>();
}
void FixedUpdate()
{
//执行Sweep测试
RaycastHit hit;
if(rb.SweepTest(direction, out hit, 1f))
{
Debug.Log("Hit: " + hit.collider.name);
}
}
}
IsSleeping
可以用来检查刚体是否处于休眠状态
public class IsSleepingExample : MonoBehaviour
{
public Rigidbody rb;
void Start()
{
rb = GetComponent<Rigidbody>();
}
void Update()
{
if (rb.IsSleeping())
{
Debug.Log("Rigidbody is sleeping");
}
else
{
Debug.Log("Rigidbody is awake");
}
}
}