Homing Magic

p4

I manage to make the magic ball tracing enemies.

Here is my code

using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;

public class ProjectileTracking : MonoBehaviour
{
    [SerializeField] private float trackingRange = 2.5f;
    [SerializeField] private float turnSpeed = 1f;
    [SerializeField] private Transform trackingRoot;

    private void Update()
    {
        TrackEnemies();
    }

    private void TrackEnemies()
    {
        List<EnemyHealth> _enemies = new List<EnemyHealth>();
        var _objs = Physics2D.OverlapCircleAll(transform.position, trackingRange);
        foreach (var _obj in _objs)
        {
            var _health = _obj.GetComponent<EnemyHealth>();
            if ((_health))
            {
                _enemies.Add(_health);
            }
        }

        if(_enemies.Count == 0)
        {
            return;
        }

        var _nearestEnemy = _enemies.OrderBy(ene =>
        {
            var _dist = Vector3.Distance(ene.transform.position, trackingRoot.position);
            return _dist;
        }).First();

        var _dir = _nearestEnemy.transform.position - trackingRoot.position;
        var _angle = Mathf.Atan2(_dir.y, _dir.x) * Mathf.Rad2Deg;
        var _objRot = Quaternion.AngleAxis(_angle, Vector3.forward);
        trackingRoot.rotation =  Quaternion.RotateTowards(trackingRoot.rotation, _objRot, turnSpeed * Time.deltaTime);
        Debug.DrawRay(trackingRoot.position, _dir);
    }
}

By the way, what is the difference between “Homing” and “Tracking” ?

5 Likes

This is awesome! I love homing projectiles, specially shiny magic ones.
I wonder how would this sound in context with SFX.

1 Like

Privacy & Terms