using UnityEngine;
public class ConstantBounceForce : MonoBehaviour
{
public float bounceForce = 10f; // 反弹力大小
private Rigidbody rb;
void Start()
{
rb = GetComponent<Rigidbody>();
}
// 当刚体碰撞到其他物体时触发
void OnCollisionEnter(Collision collision)
{
// 获取碰撞法线,即与碰撞物体接触的表面的法线方向
Vector3 normal = collision.contacts[0].normal;
// 计算反向力的方向,即碰撞法线的反方向
Vector3 reverseForceDirection = -normal;
// 施加反向力到刚体上,并且忽略摩擦力的影响
rb.AddForce(reverseForceDirection * bounceForce, ForceMode.Impulse);
rb.velocity = reverseForceDirection * bounceForce;
}
}
20240412_111920
加上
using UnityEngine;
public class Buoyancy : MonoBehaviour
{
public Transform targetPoint; // 汇集点
public float maxBuoyancyForce = 10f; // 最大浮力大小
public float maxDistance = 5f; // 最大作用距离
private Rigidbody rb;
void Start()
{
rb = GetComponent<Rigidbody>();
rb.useGravity = false; // 关闭重力
}
void FixedUpdate()
{
// 计算物体到汇集点的距离
float distanceToTarget = Vector3.Distance(transform.position, targetPoint.position);
// 计算浮力大小,距离越近,浮力越大
float buoyancyForce = Mathf.Clamp(1f - (distanceToTarget / maxDistance), 0f, 1f) * maxBuoyancyForce;
// 计算浮力方向,向汇集点施加力
Vector3 buoyancyDirection = (targetPoint.position - transform.position).normalized;
// 添加浮力到物体上
rb.AddForce(buoyancyDirection * buoyancyForce);
}
}
20240412_112948
加上
using UnityEngine;
public class ConstantAngularVelocityOnCollision : MonoBehaviour
{
public float desiredAngularSpeed = 30f; // 指定的角速度大小
public float interpolationSpeed = 0.1f; // 插值速度
private Rigidbody rb;
void Start()
{
rb = GetComponent<Rigidbody>();
}
Vector3 desiredAngularVelocity;
private void FixedUpdate()
{
// 计算刚体当前角速度的大小
float currentAngularSpeed = rb.angularVelocity.magnitude;
// 如果当前角速度大小不为零,计算新的角速度大小,并保持原来的方向
if (currentAngularSpeed != 0)
{
// 计算当前角速度的单位向量
Vector3 currentAngularDirection = rb.angularVelocity.normalized;
// 计算新的角速度大小,并保持原来的方向
Vector3 newAngularVelocity = currentAngularDirection * desiredAngularSpeed * Mathf.Deg2Rad;
// 应用新的角速度到刚体上
desiredAngularVelocity = newAngularVelocity;
}
// 如果当前角速度大小为零,直接设定指定的角速度大小
else
{
desiredAngularVelocity = transform.up * desiredAngularSpeed * Mathf.Deg2Rad;
}
rb.angularVelocity = Vector3.Lerp(rb.angularVelocity, desiredAngularVelocity, interpolationSpeed);
}
}
20240412_113157