public void DoAIUpdate() { Vector2 targetDirection = m_Snake.TargetMoveDirection; if (m_NotChangeDirectionTimes >= slConstants.SNAKE_RANDMOVEMOENT_WHENNOTCHANGED_TIMES) { if (hwmRandom.RandFloat() < slConstants.SNAKE_RANDMOVEMOENT_WHENNOTCHANGED_PROBABILITY) { targetDirection = new Vector2(hwmRandom.RandFloat(-1, 1), hwmRandom.RandFloat(-1, 1)).normalized; } m_NotChangeDirectionTimes = -1; } CalculateSafeArea(ref targetDirection.x, m_Snake.GetHeadPosition().x, m_SafeAreaMinPosition.x, m_SafeAreaMaxPosition.x); CalculateSafeArea(ref targetDirection.y, m_Snake.GetHeadPosition().y, m_SafeAreaMinPosition.y, m_SafeAreaMaxPosition.y); #if UNITY_EDITOR m_AIDetectGizmos.Clear(); #endif ms_SnakeQuadtreeNodes.Clear(); slWorld.GetInstance().GetSnakeSystem().GetQuadtree().GetRootNode() .GetAllIntersectNode(ref ms_SnakeQuadtreeNodes , hwmBox2D.BuildAABB(m_Snake.GetHeadPosition(), new Vector2(slConstants.SNAKE_DETECT_DISTANCE, slConstants.SNAKE_DETECT_DISTANCE))); bool ignorePredict = IsHitPredict(); int dangerDirection = 0; if ((!IsSafe(m_ClockwiseDetectAngle * targetDirection, slConstants.SNAKE_DETECT_DISTANCE, ignorePredict) && dangerDirection++ > -1) || (!IsSafe(m_CounterclockwiseDetectAngle * targetDirection, slConstants.SNAKE_DETECT_DISTANCE, ignorePredict) && dangerDirection++ > -1) || (!IsSafe(targetDirection, slConstants.SNAKE_DETECT_DISTANCE, ignorePredict) && dangerDirection++ > -1)) { Quaternion angle = dangerDirection == 3 ? m_ClockwiseDetectAngle : dangerDirection == 1 ? m_CounterclockwiseDetectAngle : m_ClockwiseDetectAngle; Vector2 currentCalculateDirection = targetDirection; for (int iCalculate = 0; iCalculate < slConstants.SNAKE_AI_CALCULATE_TIMES; iCalculate++) { currentCalculateDirection = angle * currentCalculateDirection; bool isSafe = IsSafe(currentCalculateDirection, slConstants.SNAKE_DETECT_DISTANCE, ignorePredict); #if UNITY_EDITOR AIDetectGizmos aIDetectGizmos = new AIDetectGizmos(); aIDetectGizmos.StartPosition = m_Snake.GetHeadPosition(); aIDetectGizmos.EndPosition = (Vector2)m_Snake.GetHeadPosition() + currentCalculateDirection * slConstants.SNAKE_DETECT_DISTANCE; aIDetectGizmos.IsSafe = isSafe; m_AIDetectGizmos.Add(aIDetectGizmos); #endif if (isSafe) { targetDirection = currentCalculateDirection; break; } } } m_NotChangeDirectionTimes = m_Snake.TargetMoveDirection == targetDirection.normalized ? m_NotChangeDirectionTimes + 1 : 0; m_Snake.TargetMoveDirection = targetDirection.normalized; }
protected void OnDrawGizmos() { for (int iAIDetect = 0; iAIDetect < m_AIDetectGizmos.Count; iAIDetect++) { AIDetectGizmos iterDetect = m_AIDetectGizmos[iAIDetect]; Gizmos.color = iterDetect.IsSafe ? Color.green : Color.red; Gizmos.DrawLine(iterDetect.StartPosition, iterDetect.EndPosition); } }