Advertisement
CassataGames

Untitled

Feb 21st, 2023
502
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.34 KB | None | 0 0
  1. using Sirenix.OdinInspector;
  2. using UnityEngine;
  3.  
  4. public class HomingBehavior : BulletBehavior
  5. {
  6.     public string targetTag = "Player";
  7.  
  8.     private Rigidbody _rb;
  9.     private Transform _target;
  10.     [SerializeField] private float range = 15;
  11.  
  12.     [SerializeField] private float redirectSpeed = 5; // How much rotation is allowed to occur within one second
  13.     private Vector3 _storedVelocity;
  14.     private Vector3 _storedNewVelocity;
  15.     // The angle where the projectile starts to tracking between 0-1
  16.     private readonly Vector2 _lockOnFOV = new Vector2(45, 15);
  17.  
  18.     private void FixedUpdate()
  19.     {
  20.         // Verify target is in front of the projectile velocity.
  21.        
  22.         // Track Target
  23.         TrackTarget(Vector3.Distance(_rb.position, _target.position));
  24.     }
  25.  
  26.     private float ValidTargetDirection(Transform target)
  27.     {
  28.         Transform transformProjectile;
  29.         var rigidBody = (transformProjectile = transform).GetComponent<Rigidbody>();
  30.         var targetDirection = target.position - transformProjectile.position;
  31.         var angle = Vector3.Angle(rigidBody.velocity.normalized, targetDirection);
  32.         var normalizedLockOnRatio = Mathf.InverseLerp(_lockOnFOV.x, _lockOnFOV.y, angle);
  33.         return normalizedLockOnRatio;
  34.     }
  35.    
  36.     private void TrackTarget(float distance)
  37.     {
  38.         if (distance >= range) return;
  39.         var position = _target.position;
  40.         _storedVelocity = _rb.velocity;
  41.         _storedNewVelocity = (position - _rb.position).normalized * _rb.velocity.magnitude;
  42.         _rb.velocity = Vector3.Lerp(_storedVelocity, _storedNewVelocity, Time.deltaTime * redirectSpeed * ValidTargetDirection(_target));
  43.        
  44.         // Rotate the bullet towards the target's anticipated position
  45.         var targetVelocity = _target.GetComponent<Rigidbody>().velocity;
  46.         var targetFuturePosition = position + targetVelocity;
  47.         var rotation = Quaternion.LookRotation(targetFuturePosition - _rb.position);
  48.         _rb.MoveRotation(rotation);
  49.     }
  50.  
  51.     private void OnEnable()
  52.     {
  53.         _rb = GetComponent<Rigidbody>();
  54.         _target = GameObject.FindWithTag(targetTag).transform;
  55.     }
  56.  
  57.     private void OnDrawGizmos()
  58.     {
  59.         if (!Application.isPlaying) return;
  60.         Gizmos.color = Color.green;
  61.         Gizmos.DrawRay(_rb.position, _rb.velocity);
  62.     }
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement