SHMUP 2.0

Week two's work on the SMHUP involved changing the enemy to allow for more than one type. So each type of enemy would inherit from a common base script, Enemy, and do special actions for that type in it's own script. Inheritance at it's finest...
But seriously, inheriting from a base class/script is always a good way to go whenever two different objects do the same thing. Such as taking damage, or even moving.

For example, an enemy and a player would inherit the same base script since both objects would need health, damage, movement speed and would have to do movement, taking damage and dealing that damage. Inheritance just simply, cleans up the code.

Back to the brief, the first and only type of enemy we made, was one that would track the player if it had line of sight but was unable to turn towards the player fast enough if the player left the enemies line of sight. This resulted in somewhat intelligent tracking but not complete tracking like the missiles the player fires.
The tracking was done using the code below...

//Forward movement
transform.position += transform.forward * moveSpeed * Time.deltaTime;

//Rotating towards player if in line of sight
if(player.transform.position.z <= transform.position.z) {  
    targetRot = Quaternion.LookRotation(player.transform.position - transform.position);
    adjRotSpeed = Mathf.Min(rotSpeed * Time.deltaTime, 1);
    transform.rotation = Quaternion.Lerp(transform.rotation, targetRot, adjRotSpeed);
}

In essence, the enemy would get line of sight, rotate towards the player while moving forward. If the player moves further and the enemy still has them in their sights (Overwatch reference), the enemy would rotate further to line up.
But if the player moves away too fast and outside the line of sight, the enemy would rotate as much as it could then simply continue moving forward, disappearing off the map.

A preview of what the above implementation looks like...

More on inheritance though, it's concept that is quite useful. Instead of writing 6 different scripts that share the same code exactly but end up doing something else, you might as well write one more script and dump all the common code into that and have the other scripts inherit from the common script. It's all about optimisation or in this case, clean code.
And you can mostly assume that most games that have very similar characters or GameObjects probably have a parent script which contains movement or handling the health of said object while the child script does the special stuff such as AI or other stuff that escapes my mind right now.

Tom Lynn

Read more posts by this author.

Australia http://rubbix.net