Search Unity

Aim Lock-On Help

Discussion in '2D' started by NickDeGrood, Mar 13, 2018.

  1. NickDeGrood

    NickDeGrood

    Joined:
    Mar 13, 2018
    Posts:
    6
    I'm trying to make a script that automatically finds the nearest enemy, then brings the player over to them, grapple hook style. It's sort of like the dash slash in Specter Knight. I've got the code that find the nearest target, but I don't know where to proceed. This is what I have so far.

    Transform player;
    Transform target;
    int radius = 10;
    private void Update()
    {
    Collider2D[] targets = Physics2D.OverlapCircleAll(player.position, radius, 8); // find all targets in range

    if (targets != null)
    {
    int index = -1;
    float distance = radius * radius;

    for (int i = 0; i < targets.Length; i++) // test for shortest distance
    {
    float current = (targets[i].transform.position - player.position).sqrMagnitude;

    if (current < distance)
    index = i;
    }
    if (index != -1)
    // Select target enemy
    }
    }