AI for Enemies

As I put the finishing touches on my AI script for the two enemies in our new title, Cosmotic Blast, I wanted to out line some of what went into the design.

Enemies Movement

Enemies had to head towards you, close the gap but also not run into you. So I used this equation to find a point / vector in space to set as a target.

Vector3 locationTarget = ((target.transform.position - transform.position) + (transform.position - target.transform.position).normalized * distance);

Saying that equation in english: Take the targets position and subtract enemies position to get a vector from enemy to target. Now add back a vector from the target to the enemy but only at a given distance. See how that makes a point in space at distance from the target. If you’re to close, it could be behind you.

To avoid targets, I found all near by objects with a OverlapShereNonAlloc() with a given distance. Then applied a opposing force to the enemy. So in a loop …

force += (transform.position - nearByObjects[i].transform.position).normalized * speed;

The speed is a variable since some enemies art faster at avoiding things than others. This also makes it avoid other enemies so they fly around with a nice spacing.

I can also reverse this force for Upgrade objects so the enemy takes them for their self. Muhahah!

Enemies Shoot!

First things first, you got to aim at your target:

Vector3 pos = target.transform.position - transform.position;
Quaternion rot = Quaternion.LookRotation(pos);
transform.rotation = Quaternion.Lerp(transform.rotation, rot, Time.deltaTime * speed);

Why Lerp? Lerp makes it so it slowly rotates towards a target at a given speed. The speed is based on what level the enemy is at.

Next, got to shoot. Well this is more complex, because it depends on what the enemy is shooting but to start it off, I do a Physics.Raycast and find if the “Player” is in front of the enemies canon … then I fire().

if (physics.Raycast (transform.position, canon.gameObject.transform.forward, out hit, range, rayMask)) {
    if (hit.transform.tar == "") {

The rayMask hides the Raycast from different gameObjects.

All the rest

All the rest is inherited from the classes that the ship uses, like upgrades and shield, etc.

Fun fun happy times.

Leave a Reply