Day 44: New Enemy Part 1
Objective: Create a new enemy that has a different movement path and has different weapon type.
For this I’m using the same enemy sprite due to my lack of creating art. Next we will need to set up a way point for the enemy to follow. We’ll do this by creating a Empty Object and add different way points under that. Before adding any children to the Parent object, make sure you set the transforms position to zero on the x, y, and z axis.
Once it’s set up turn it into a prefab so we can instantiate it. These can be placed any way you would like. This will allow for a designer to change later without having a programmer change some code.
If you want to have the gizmos as seen above, on the game object beside it’s name there is a square with a drop down. Click it and you can have different options to pick from. Below you can see I’ve set it to a blue oval.
Now once you have the way points set it’s time to set up the logic for this enemy. Later on I plan to refactor this part of the code once my knowledge has expanded for it.
In the Enemy script, we will need a reference for the prefab to instantiate. We’ll need an array to save all of the way points that are children in the prefab. We need a way to know which way point we need to be heading towards and finally a reference to the instantiated object to destroy when the enemy is destroyed as well.
We also need a variable to know which enemy is spawning to do different things.
Next is to move to the start function to add all of the way points to the array for the enemy to follow. To start of we need to see which enemy has been spawned. If it is equal to 2, which is our new enemy, we’ll instantiate our parent that’s holding all of the way points. We need to assign it variable to use later.
Next is to initialize the array, this will set the size of the array to the amount of children. We do this by getting the childCount using the variable we created when instantiating the prefab, _wayPoint.transform.childCount.
We need to loop though all of the children and add into the array. We’ll set the index to match the child starting from zero.
After we get all the children into the array it’s time to move the enemy to that way point.
We’ll create a local variable to figure out the direction we need to go. To use the array of way points, we’ll check the way point array and the current way point. To start with it’ll be zero so the way point at index zero will be the first way point to go to. After figuring out which way point is the destination, we’ll subtract the enemies position from the way point.
Next is to rotate the enemy to it, We’ll set the local rotation to Quaternion.LookRotation. Inside LookRotation we, set the destination to a negative direction. To move the enemy, we’ll use transform.Translate(Vector3.down).
Tomorrow we’ll discuss how the enemy will move onto the next array once it meets the first one and continue on till all way points have been reached!