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);
}
}
// 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");
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).