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);
}
}