Creating Enemy Homing Attack

Eric Veciana
4 min readDec 17, 2022

Objective: Create an enemy fire that follows the player

Since this is a new enemy attack, the first thing we need to do is create a new script for this attack. Then, go ahead and create two variables grabbing the Transform and the Rigidbody.

We are going to want to grab the players transform because this is going to be the target for the homing attack. The Rigidbody is the current position of the enemy attack.

When creating a homing attack, we will be using the cross product of the player position and the enemy attack’s current position. The cross product is an equation between two vectors that creates a third vector. The result being with this, it will constantly propel the homing attack towards the target.

Now, let’s get into the homing function.

The first thing we want to do is grab the direction we will be going. For this, let’s grab the sum of a minus b; When a = target position and b = current position.

Now, it is giving me an error stating that using (-) on Vector3 is ambiguous between Vector2 and Vector3. To solve this, I need to add a Vector3 on the rigidbody position.

Since we don’t know the length of the target, we will normalize it so that the magnitude equals one, because the length of these cross vectors should be one. This will change the length to one without changing the direction.

For the next part, we are going to want to use .Cross to put the cross product into effect.

We want our .Cross function to be a product of the direction we want our object to be propelled and the direction the object will be facing.

First, I created a local variable to make the transform.up into ‘transform.down’ since my object is facing downwards and transform.down doesn’t exist. We want to use transform instead of a vector for this, because vector.down is always going to be down in the global space, while transform.down changes in respect to the transform position.

Now, let’s make this function into a local variable so that we can use it to create our angular velocity.

In order to have our float work properly with the vector3 here, I had to place a ‘z’ coordinate at the end of this line. We now have our rotate amount. We can add this into an equation now to create the angular velocity of our rigidbody.

Now, with this, the object was turning away from the target, so I simply added a minus in front of the rotate amount to make it turn towards the player.

Then, I simply added the speed of the projectile and that’s it! Should be functioning perfectly now.

*I don’t need to multiply by deltaTime because rigidbody is an absolute value.

Lastly, don’t forget to null check the target!

This game is now playable on itch.io. I try to update it frequently. Give it a play and let me know what you think!

--

--