Hi everyone,
I’m currently making a 2d space shooter. While making the player spawn script I turned the player into a prefab and deleted all current objects (except from a single enemy) from the scene. I then spawned the player in only to find that the enemy AI won’t follow the player, it justs flies over to the same position and circles it.
I believe it is something to do with me turning the player object into a prefab, as everything was working fine beforehand.
Here is the enemy AI script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyAI : MonoBehaviour {
public float rotSpeed = 45f;
public Transform player;
public Transform spawn;
public GameObject bullet;
public float fireDelay = 0.25f;
public float cooldownTimer = 0;
public float speed = 5f;
public Vector3 offset = new Vector3(0.01f, 0.01f, 0);
public Transform sightStart, sightEnd;
public bool spotted = false;
public bool spotted2 = false;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void FixedUpdate()
{
RayCasting();
if (player == null)
{
//Find player ship
GameObject go = GameObject.FindWithTag("Player");
if (go != null)
{
player = go.transform;
}
}
if (player == null)
return;
Vector3 dir = player.position - transform.position;
dir.Normalize();
float zAngle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg - 90;
Quaternion desiredRot = Quaternion.Euler(0, 0, zAngle);
transform.rotation = Quaternion.RotateTowards(transform.rotation, desiredRot, rotSpeed * Time.deltaTime);
Vector3 pos = transform.position;
Vector3 velocity = new Vector3(0, speed * Time.deltaTime, 0);
pos += transform.rotation * velocity;
transform.position = pos;
cooldownTimer -= Time.deltaTime;
if (cooldownTimer <= 0 && spotted == true)
{
cooldownTimer = fireDelay;
GameObject bulletGo = (GameObject)Instantiate(bullet, spawn.position, spawn.rotation);
bulletGo.layer = gameObject.layer;
}
}
void RayCasting()
{
Debug.DrawLine(sightStart.position, sightEnd.position, Color.red);
spotted = Physics2D.Linecast(sightStart.position, sightEnd.position, 1 << LayerMask.NameToLayer("Player"));
spotted2 = Physics2D.Linecast(sightStart.position, sightEnd.position, 1 << LayerMask.NameToLayer("Enemy"));
}
}