| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364 |
- using UnityEngine;
- public class HomingEffect : BallEffectBase
- {
- private float _retargetTimer;
- private blockScript _targetBlock;
- private HomingEffectDefinition Config => definition as HomingEffectDefinition;
- public override void OnBallReset(BallScript ball)
- {
- _retargetTimer = 0f;
- _targetBlock = null;
- }
- public override void ModifyVelocity(BallScript ball, ref Vector2 velocity, float deltaTime)
- {
- HomingEffectDefinition config = Config;
- if (config == null)
- return;
- if (velocity.sqrMagnitude < 0.0001f)
- return;
- _retargetTimer += deltaTime;
- if (_targetBlock == null || _retargetTimer >= config.RetargetInterval)
- {
- _retargetTimer = 0f;
- _targetBlock = FindClosestBlock(ball.transform.position);
- }
- if (_targetBlock == null)
- return;
- Vector2 currentDir = velocity.normalized;
- Vector2 targetDir = ((Vector2)_targetBlock.transform.position - (Vector2)ball.transform.position).normalized;
- float maxRadians = config.TurnRateDegreesPerSecond * Mathf.Deg2Rad * deltaTime;
- Vector3 steered = Vector3.RotateTowards(currentDir, targetDir, maxRadians, 0f);
- velocity = ((Vector2)steered).normalized * velocity.magnitude;
- }
- private static blockScript FindClosestBlock(Vector2 position)
- {
- blockScript[] blocks = FindObjectsByType<blockScript>(FindObjectsSortMode.None);
- blockScript best = null;
- float bestSqrDistance = float.MaxValue;
- for (int i = 0; i < blocks.Length; i++)
- {
- blockScript b = blocks[i];
- if (b == null)
- continue;
- float sqrDist = ((Vector2)b.transform.position - position).sqrMagnitude;
- if (sqrDist < bestSqrDistance)
- {
- bestSqrDistance = sqrDist;
- best = b;
- }
- }
- return best;
- }
- }
|