trying to follow this tutorial and my missile won’t hit the target directly, it just goes in the direction of the target and keeps looping around the scene.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class guidedmissile : MonoBehaviour
{
private float acceleration = 20f;
[SerializeField]
private float accelerationTime = 7f;
[SerializeField]
private float missileSpeed = 20f;
private float turnRate = 50f;
[SerializeField]
private float trackingDelay = 3f;
public Transform target;
private bool missileActive = false;
private bool isAccelerating = false;
private float accelerateActiveTime = 0f;
private Quaternion guideRotation;
private bool targetTracking = false;
private Rigidbody rb;
private void Start()
{
rb = GetComponent<Rigidbody>();
ActivateMissile();
}
IEnumerator TargetTrackingDelay()
{
yield return new WaitForSeconds(Random.Range(trackingDelay, trackingDelay + 3f));
targetTracking = true;
Debug.Log("TargetTrackingisActivated");
}
private void ActivateMissile()
{
missileActive = true;
accelerateActiveTime = Time.time;
StartCoroutine(TargetTrackingDelay());
}
private void GuideMissile()
{
if(target == null) return;
if(targetTracking)
{
Vector3 relativePosition = target.position - transform.position;
guideRotation = Quaternion.LookRotation(relativePosition, transform.up);
}
Debug.Log("Tracking");
}
private void Update()
{
Run();
GuideMissile();
}
private void Run()
{
if(Since(accelerateActiveTime) > accelerationTime)
isAccelerating = false;
else
isAccelerating = true;
if(!missileActive) return;
if(isAccelerating)
missileSpeed += acceleration * Time.deltaTime;
rb.velocity = transform.up * missileSpeed;
if(targetTracking)
transform.rotation = Quaternion.RotateTowards(transform.rotation, guideRotation, turnRate * Time.deltaTime);
Debug.Log("Missile Speed" + missileSpeed);
Debug.Log("time" + accelerateActiveTime);
}
private float Since(float since)
{
return Time.time - since;
}
}