This is my object that supposed to follow my target like a homing missile:
public Transform target;
public float movementSpeed;
public float rotataSpeed;
private Rigidbody2D rb;
private void Start()
{
rb = GetComponent<Rigidbody2D>();
}
private void FixedUpdate()
{
Vector2 direction = (Vector2)target.position - rb.position;
direction.Normalize();
float rotateAmount = Vector3.Cross(direction, -transform.up).z;
rb.angularVelocity = -rotateAmount * rotataSpeed;
rb.velocity = -transform.up * movementSpeed;
}
which works fine as the object itself but when I put it under a script that spawns this object, it work funny like it didn't really track the target when it first launch but then it did the U-turn towards my target. I want it to track my target when it first spawn. This is my spawn script:
float secondsbetweenSpawn = Mathf.Lerp(secondsBetweenSpawnMinMax.x, secondsBetweenSpawnMinMax.y, Difficulty.GetDifficultyPercentage());
if (secondsbetweenSpawn < 1.30f)
{
nextSpawnTime = Time.time + secondsbetweenSpawn;
float spawnPillSize = Random.Range(SpawnSizeMinMax.x, SpawnSizeMinMax.y);
Vector2 spawnPosPill = new Vector2(Random.Range(-screenSize.x, screenSize.x), screenSize.y);
GameObject pillDrop = (GameObject)Instantiate(Pill, spawnPosPill, Quaternion.identity);
pillDrop.transform.localScale = Vector2.one * spawnPillSize;
}
target
variable? \$\endgroup\$null reference exception
because when you are Instantiating the prefab you are not assigning the value fortarget
. \$\endgroup\$