5555
This commit is contained in:
@@ -11,7 +11,7 @@ public class Rope : MonoBehaviour
|
||||
|
||||
[SerializeField] float nodeColliderRadius = 0.2f;
|
||||
[SerializeField] float gravityStrength = 2;
|
||||
[SerializeField, Range(1, 500)] int totalNodes = 100;
|
||||
[SerializeField] float totalLength = 10f; // 新增总长度参数
|
||||
[SerializeField, Range(0, 1)] float velocityDampen = 0.95f;
|
||||
[SerializeField, Range(0, 0.99f)] float stiffness = 0.8f;
|
||||
[SerializeField, Range(1, 10)] int iterateCollisionsEvery = 1;
|
||||
@@ -36,9 +36,20 @@ public class Rope : MonoBehaviour
|
||||
LineRenderer lineRenderer;
|
||||
GameObject nodeTester;
|
||||
SphereCollider nodeCollider;
|
||||
int totalNodes; // 现在由代码计算
|
||||
|
||||
void Awake()
|
||||
{
|
||||
// 计算节点数量
|
||||
totalNodes = Mathf.FloorToInt(totalLength / nodeDistance) + 1;
|
||||
float remainingLength = totalLength % nodeDistance;
|
||||
|
||||
// 如果剩余长度大于0,增加一个节点
|
||||
if (remainingLength > 0 && totalLength > nodeDistance)
|
||||
{
|
||||
totalNodes++;
|
||||
}
|
||||
|
||||
// 初始化数组
|
||||
currentNodePositions = new Vector3[totalNodes];
|
||||
previousNodePositions = new Vector3[totalNodes];
|
||||
@@ -59,9 +70,12 @@ public class Rope : MonoBehaviour
|
||||
Vector3 startPos = transform.position;
|
||||
for (int i = 0; i < totalNodes; i++)
|
||||
{
|
||||
// 如果是最后一个节点且有剩余长度,使用剩余长度
|
||||
float distance = (i == totalNodes - 1 && remainingLength > 0) ? remainingLength : nodeDistance;
|
||||
|
||||
currentNodePositions[i] = startPos;
|
||||
previousNodePositions[i] = startPos;
|
||||
startPos.y -= nodeDistance;
|
||||
startPos.y -= distance;
|
||||
}
|
||||
|
||||
// 设置线渲染器
|
||||
@@ -141,7 +155,6 @@ public class Rope : MonoBehaviour
|
||||
|
||||
// 预计算所有常用值
|
||||
float halfStiffness = 0.5f * stiffness;
|
||||
float sqrNodeDistance = nodeDistance * nodeDistance;
|
||||
int nodeCountMinusOne = totalNodes - 1;
|
||||
|
||||
for (int i = 0; i < nodeCountMinusOne; i++)
|
||||
@@ -150,13 +163,19 @@ public class Rope : MonoBehaviour
|
||||
Vector3 node2 = currentNodePositions[i + 1];
|
||||
Vector3 diff = node1 - node2;
|
||||
|
||||
// 计算期望的距离 - 如果是最后一个段且有剩余长度,使用剩余长度
|
||||
float desiredDistance = (i == nodeCountMinusOne - 1 && (totalLength % nodeDistance) > 0)
|
||||
? (totalLength % nodeDistance)
|
||||
: nodeDistance;
|
||||
|
||||
float sqrDesiredDistance = desiredDistance * desiredDistance;
|
||||
float sqrDistance = diff.x * diff.x + diff.y * diff.y + diff.z * diff.z;
|
||||
|
||||
// 只有当距离差异超过一定阈值时才调整
|
||||
if (Mathf.Abs(sqrDistance - sqrNodeDistance) > 0.001f)
|
||||
if (Mathf.Abs(sqrDistance - sqrDesiredDistance) > 0.001f)
|
||||
{
|
||||
float distance = Mathf.Sqrt(sqrDistance);
|
||||
float difference = nodeDistance - distance;
|
||||
float difference = desiredDistance - distance;
|
||||
Vector3 direction = diff / distance; // 比 normalized 更快
|
||||
|
||||
Vector3 adjustment = direction * (difference * halfStiffness);
|
||||
|
||||
Reference in New Issue
Block a user