优化算法

This commit is contained in:
2025-05-17 01:49:05 +08:00
parent 4608886f5f
commit 5ba424eee1
@@ -96,6 +96,9 @@ public class GearFollower : MonoBehaviour
}
}
private float directionSwitchCooldown = 0.2f;
private float directionSwitchTimer = 0f;
private void UpdateTractionState(Vector2 mousePos)
{
Vector2 gearPos = transform.position;
@@ -116,15 +119,30 @@ public class GearFollower : MonoBehaviour
Vector2 from = edgePoints[currentEdgeIndex];
Vector2 to = edgePoints[nextIndex];
// 判断鼠标是否在当前前进方向上,否则允许换方向
float forwardDot = Vector2.Dot((to - from).normalized, (mousePos - from).normalized);
if (forwardDot < 0) // 鼠标在反方向
// 方向判断优化:使用角度判断是否反方向
Vector2 forward = (to - from).normalized;
Vector2 toMouse = (mousePos - from).normalized;
float angle = Vector2.SignedAngle(forward, toMouse); // -180 ~ 180
// 当角度大于120度,说明鼠标方向明显是反的
if (Mathf.Abs(angle) > 120f)
{
// 允许方向切换
tractionDirection *= -1;
nextIndex = WrapIndex(currentEdgeIndex + tractionDirection);
from = edgePoints[currentEdgeIndex];
to = edgePoints[nextIndex];
directionSwitchTimer += Time.deltaTime;
if (directionSwitchTimer > directionSwitchCooldown)
{
tractionDirection *= -1;
directionSwitchTimer = 0f;
// 更新前进段
nextIndex = WrapIndex(currentEdgeIndex + tractionDirection);
from = edgePoints[currentEdgeIndex];
to = edgePoints[nextIndex];
forward = (to - from).normalized;
}
}
else
{
directionSwitchTimer = 0f;
}
Vector2 targetPoint = GetClosestPointOnSegment(from, to, mousePos);
@@ -149,6 +167,7 @@ public class GearFollower : MonoBehaviour
}
}
private int FindNearestEdgePointIndex(Vector2 pos, out float minDist)
{
int nearestIndex = 0;