- Home /
How to make a moving enemy shoot at the player rather than the player's spawn?
Hi. I am making a top-down shooter and I was having an issue with getting a moving enemy to shoot at the player. The enemy in question shoots at the player's initial spawn but not at the player's current location. Below is the script that controls all enemies and enemies shooting. I could use some help.
using UnityEngine;
using System.Collections;
public class Enemy : MonoBehaviour
{
public float speed;
public string shipType;
public float travelTime;
public float restTime;
public GameObject spawner;
public GameObject bullet;
public GameObject player;
public bool canShoot;
public bool lookAtPlayer;
void Start()
{
float posX = transform.position.x + offsetRange * Random.value;
Vector2 offset = new Vector2(posX, transform.position.y);
transform.position = offset;
}
void Update()
{
ShipControl(shipType);
}
void ShipControl(string type)
{
switch(type)
{
case "basic": Move(); break;
case "shooting": Move(); break;
case "moveShoot": Move(); PointAt(); break;
}
}
void Move()
{
if(travelTime > 0)
{
transform.Translate(Vector2.down * speed * Time.deltaTime);
travelTime -= 1 * Time.deltaTime;
}
else if(restTime > 0)
{
if(canShoot)
Shoot();
restTime -= 1 * Time.deltaTime;
}
else
{
if (canShoot)
Shoot();
travelTime += 1;
Move();
}
}
void PointAt()
{
if(spawner != null && player != null)
spawner.transform.up = player.transform.position - transform.position;
}
void Shoot()
{
if(bullet != null && spawner != null)
{
GameObject thisBullet = Instantiate(bullet, spawner.transform.position, spawner.transform.rotation) as GameObject;
canShoot = false;
}
}
}
Sorry about the double post. This is my first time posting a question on here.
Are you sure you set GameObject Player to the player and not accidentally the spawn?
Also, you use the term "spawner" when calculating PointAt(). Could you clarify what this refers to?
"spawner" refers to the EnemySpawner GameObject. The EnemySpawner has no components attached to it, other than the usual Transform Component.
Answer by Vilhien · Jul 17, 2018 at 07:39 PM
I see where you are instantiating your bullets but what code re you using to move them. Also, are you updating the position when you call the bullets to fire? The sounds of it, that you call the position of the player in start only for the bullets. Which is why they would continue to only fire at that position, is my guess.
Your answer
Follow this Question
Related Questions
When the enemy character shoots, the bullet won't go to the position of my player! 2 Answers
Can someone help me to understand why this raycast is not working properly? 1 Answer
Enemy fire rate? help! 2 Answers
AI Script attached to Enemy and is Rotating around player 0 Answers
enemy AI doesnt work when enemy is spawned but does if it is already in the scene 1 Answer