Lerp Auto Aim

Hello guys,
Very new unity/c# developer here. Basically, I have been trying to add to the Space Shooter tutorial where there would be a secondary gun that automatically aims for an enemy. The “shot” would be created each time i pressed a key. I have been playing around with the Vector3.Lerp to move the shot towards to “enemy”

Here is the script attached to the “shot” prefab.

using UnityEngine;
using System.Collections;

public class lerpTest : MonoBehaviour {
   
    public GameObject other;
   
    private Vector3 newPosition;
    // Use this for initialization
    void Start () {
        other = gameObject.FindGameObjectsWithTag ("Enemy");
        newPosition = other.transform.position;
    }
   
    // Update is called once per frame
    void Update () {
        positionChanging ();   
    }

    void positionChanging (){
        transform.position = Vector3.Lerp (transform.position,newPosition,Time.deltaTime);   
    }

}

I get this compile error:

It says right on the tin. FindGameObjectsWithTag() is a static method, you should access it via the containing class, not an actual instance.

1 Like
// gameObject is "this gameobject instance I'm attached to"
gameObject.FindGameObjectsWithTag("Enemy");

//should be

// GameObject is the class, static functions/variables are accessed by Class.Function(), Class.variable
GameObject.FindGameObjectsWithTag("Enemy");
2 Likes

In addition, you’re using lerp wrong! When it gets working, your bullet will slow down as it gets closer to the enemy. Read this for a great explanation of the magic that is lerp.

An alternative to Lerp is Vector3.MoveTowards, as it moves something at a constant speed (which is what you want a bullet to do anyways).

1 Like

Appreciate the helpful response guys!
Here is the change to my code.

public class lerpTest : MonoBehaviour {
    public GameObject other;

    private Vector3 newPositon;

    void Start () {
        other = GameObject.FindGameObjectWithTag ("Enemy");
        newPositon = other.transform.position;
    }
   
    // Update is called once per frame
    void Update () {
        positionChanging ();   
    }

    void positionChanging (){
        transform.position = Vector3.MoveTowards (transform.position,newPositon,Time.deltaTime);   
    }

}

It does what i programmed it to do. I am spawning many astroids so it seems to pick the first one it detects with the “enemy” tag.