Need some help with firing projectile at player using Rigidbody Velocity

Alright so i’m using the script below to stop the enemy from moving once the player enters a trigger attached to the enemy, look at the player and then fire projectiles at him. The problem here is that i can’t make the enemy to fire the projectiles exactly at the position of the player. It’s always near him but not exactly at him. Any advice? Maybe there’s another way to do this without using Rigidbody and Velocity?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class FireAtPlayer : MonoBehaviour {
    bool p_detected;
    public Transform target;
    public UnityEngine.AI.NavMeshAgent agent;
    public Rigidbody projectile;
    public Transform spawn;
    public int speed;

    // Use this for initialization
    void Start () {
        speed = 60;
	}
	
	// Update is called once per frame
	void Update () {
        p_detected = GetComponentInChildren<PlayerDetection>().player_detected;
        if (p_detected)
        {
            target = GameObject.FindGameObjectWithTag("Player").transform;
            GetComponent<walking>().enabled = false;
            agent.isStopped = true;
            transform.LookAt(target);
            StartCoroutine(shooting());
        }
        if (!p_detected)
        {
            target = null;
            GetComponent<walking>().enabled = true;
            agent.isStopped = false;
            
        }
	}

    IEnumerator shooting()
    {
        yield return new WaitForSeconds(3);
        Rigidbody clone;
        clone = (Rigidbody)Instantiate(projectile, spawn.position, transform.rotation);
        clone.velocity = Vector3.MoveTowards(transform.position, target.position, speed * Time.deltaTime);

    }
}

!! I think I got it.

It’s because you’re using different values for the initial position:
You’re using TRANSFORM.POSITION instead of CLONE.TRANSFORM.POSITION;
meaning that the direction is wrong meaning it will always miss by a slight margin.

This is because your

   public Transform spawn;

is obviously not the same as the transform or else you wouldn’t have it.

The solution is:

 IEnumerator shooting()
 {
     yield return new WaitForSeconds(3);
     Rigidbody clone;
     clone = (Rigidbody)Instantiate(projectile, spawn.position, transform.rotation);
     clone.velocity = Vector3.MoveTowards(clone.transform.position, target.position, speed * Time.deltaTime);

 }

I would also change it slightly:

IEnumerator shooting()
{
     yield return new WaitForSeconds(3);
     var clone = Instantiate(projectile, spawn.position, transform.rotation);
     var dir = (player.transform.position - clone.transform.position).normalized;
     clone.velocity = dir * speed; 
}