How to make Enemy Shoot in Player Direction

Tristan Engel
2 min readMay 31, 2021

--

In this article we will make the enemies shoot at the player. We start off with the pseudocode. There are 3 parts that need to be done. The enemy projectile prefab creation, enemy script fire feature, enemy projectile script.
(We changed up the player laser and created a new enemy projectile)

Enemy Projectile Creation

Create a prefab with a a sprite
Add Component: Rigidbody2D
Add Component: Collider 2D adjust when necessary
Is Trigger checked
Gravity Scale set to zero
Add Component: Script

We chose a round projectile so we can move it in any direction looking good.

Enemy Script

Enemy fires every x seconds
handle to enemyshot prefab
fire coroutine
while enemy is alive
instantiate enemyshot
wait x sec

IEnumerator FireRoutine()
{
while (_isAlive)
{
yield return new WaitForSeconds(_fireInterval);
Instantiate(_enemyShot, transform.position + _offset, Quaternion.identity);
}
}

Enemy Projectile Script

Enemy laser move to player

handle to player
findobject of type
set player position as target
target minus own position = direction
normalize direction
(When normalized, a vector keeps the same direction but its length is 1.0.)

move enemy projectile in the calculated direction
destroy enemy projectile after X seconds

private GameObject _player;
private Vector3 _targetPlayer;
[SerializeField] private float _speed = 2f;
private Vector3 _direction;

// Start is called before the first frame update
void Start()
{
_player = GameObject.Find("Player");
//null check into get current target location
if (_player != null)
{
_targetPlayer = _player.transform.position;
}
else
{
Debug.LogError("EnemyShot.player is NULL");
}
//calculate direction to move (normalized scales values of vector to be max 1)
_direction = (_targetPlayer - transform.position).normalized * _speed;

Destroy(gameObject, 10f);
}

// Update is called once per frame
void Update()
{
transform.Translate(_direction * Time.deltaTime);
}

Enemy_shot hit detection

if tag is player
then player.damage()
then destroy self

private void OnTriggerEnter2D(Collider2D other)
{
if (other.tag == "Player")
{
other.GetComponent<Player>().Damage();
Destroy(this.gameObject);
}
}

Game Balance

Game balance is now changed greatly so tweak the numbers: spawnrate, fire rate, bullet speed etc.

Don’t forget to add SFX for the immersion.

--

--

Tristan Engel
Tristan Engel

Written by Tristan Engel

Aspiring developer that’s self-learning Unity & C# to transition to a career with Unity. I got a passion for creating interactive experiences.

No responses yet