This article will show how to make a new Enemy type that lays mines as it moves down the screen. We will also make the functionality of the Mine.
The new Enemy type is straightforward to implement. We need to override the FireLaser method and instantiate the Mine Prefab instead of the Laser Prefab.
The Mine script will need a Collider and Rigidbody since we will be using the Rigidbody to move.
The Mine script will need some variables. First is a float for the speed at which the Mine will move. Next is a GameObject for the Explosion Prefab that will spawn when the Mine is destroyed. Then a bool to know if the Mine completely stopped moving, reference to the Rigidbody, and finally a Transform for the target.
In Start, we grab the Rigidbody component so it can be referenced.
Since we are using the Rigidbody to move the Mine, we will use FixedUpdate. If the target is not null, we will move the Mine in the direction of the target at the set speed and make sure that the stopped bool is false. If the target is null and the Mine has not entirely stopped, we will reduce the velocity to zero by the set speed till it reaches zero and set the stopped bool to true.
Next, we need two methods that we will call to set and remove the target that the Mine is using.
The last thing we need for the Mine script is an OnTriggerEnter2D method and check the Tag of the other Collider to see if it should damage the Player, destroy itself and spawn the Explosion Prefab.
The TargetDetector script will need a Collider and Rigidbody of its own also, so the Collider doesn’t look to the parent’s Rigidbody. For variables, all that is required is a reference to the Mine script on the parent object.
The last things needed for the TargetDetector script are two OnTrigger methods, one to detect when the Player enters the Collider, the other to detect when the Player exits the Collider, and call methods on the parent to add and remove the target.
Here you can see the Mine Prefab with the child Target Detector.
The Enemy now lays Mines, and the Mine acts as intended.