Defense Structures

👍

Reminder - Keep Daily Backups

When working on a strategy game with a kit as big as the Complete Kit - always keep a working daily backup! Save yourself the trouble of rolling-back changes and losing work.

What are defense structures?

The city building kit comes with defense building examples. These, like the Cannon, Archer Tower, and Catapult defend your village from attacking players and protect your base resources from being stolen.

748

Examples of the defense structures in the store.

Can I add my own defense structures?

Yes. In addition to customizing the existing 3 examples, we've added 3 placeholders for defense structures you can customize and setup on the bottom half of the menu.

748

Placeholders for new defense structures

You could add more defense structures extending this menu even further. For more details about the defense structure shop menu, please read the Shop Menu > Defense Weapons documentation page.

Where to find the defense store menu in Unity?

Open the game scene hierarchy and locate the ScrollViewDefense in UIAnchor > Anchor - Center > Shop > Main. Look at the below screenshot.

266

UIAnchor. Click to view larger.

Where are the prefabs?

All of the game object prefabs are set in the Game scene Game manager. Look at the below screenshots:

275

Game scene Game Manager > SaveLoadMap

283

Inspector Defense prefabs. Click to view closer.

In addition, you will want to look at GameManager > Creators > WeaponCreator (prefabs are also there) and Map01 scene GameManager > SaveLoadBattle. This is discussed in the Buildings > Part 2: Customize Menus section of the documentation. Prefabs are used by the creator for construction and by SaveLoadBattle for loading during battle.

GameManager > Creators > WeaponCreator

In the GameManager > Creators > WeaponCreator we have the list of game object prefabs used by the creator in addition to certain build settings used by the Scripts/Creators/BaseCreator.cs script. Let's describe these below. But first, here's how to open the WeaponCreator Inspector.

276

Game scene Game Manager

370

Defense prefabs in the WeaponCreator Inspector

In the Inspector you'll notice a few arrays, here's a description of each one. It's the same for every type of game object you can build in the game except for the RemovableCreator (removables are not for players to construct but rather remove -- see Player Removable Objects doc for details)

Array TitleDescription
Structure PfThe structure prefab. Order in this list matches the exact order of the XML items which the Creator matches the prefab with.
Grass Pf1x1 to 5x5 dark green grass collider grid prefabs list. These you don't have to edit, they are shared by all structures in the game based on their grid size.
Construction PfUnder construction prefab list. There's 3 different sizes of this for 1x1 to 3x3 grid size construction projects.
Grass TypesSize of this array matches the the Structure Pf array size. We tell which Grass Pf element to use with each structure. Depends on structure size whether they take 1x1 (Grass Pf element 0) like a wall segment or 3x3 (Grass Pf element 2) like the large gold vault. Tatami is the only object that takes grass collider 5x5 ( Grass Pf Element 4).
Construction TypesArray size matches Structure Pf. Like grass types, we match the construction prefab grid size too. Since there's 3 different sizes of construction prefabs, this ranges from values 0 to 2. By default, we set most structures to use the 3x size.
Pivot CorrectionsArray size matches Structure Pf. Odd size grid structures (1x1 and 3x3) need a pivot correction so they don't appear accidentally off-center, taking more grid space than necessary. Pivot Correction does this.
Is ArrayArray size matches Structure Pf. If set to 1, uses the row making field builder for construction instead of the usual construction. The only objects that use this are the wall segments that let you pick a start and end point and automatically constructs a repeating row of the structure between the points.
Is InstantArray size matches Structure Pf. For items you set TimeToBuild to 0 (instant build) in the XML, you also want to set the elements Is Instant boolean to 1 in this array. The only objects that use this in the demo are the wall segments.

Where are the defensive weapon scripts?

The scripts for defense weapons are all located in the Scripts/Weapons folder.

TurretControllerBase.cs

This script controls the rotation, target addition, and projectile creation among other elements of the defense structure.

// TurrentControllerBase.cs Excerpt Functions

// Launch the cannonball
	protected void LaunchProjectile()
	{
    // Fire sound effect
		((SoundFX)soundFx).CannonFire();   
	  // Spawn the projectile
		Instantiate(projectilePf, projectileSpawnPointTr.position, projectileSpawnPointTr.rotation);
	}

	// Adds the unit game object to the target list for the defense structure
	public void AddTarget(GameObject target)
	{
		targetList.Add (target);
	}
	
	// Removes the unit game object to the target list for the defense structure
	public void RemoveTarget(GameObject target)
	{
		targetList.Remove (target);
	}

PerimeterCollider.cs

This script determines the perimeter around the defense structure and whether units have entered the range of a defense structure. When they enter the collider range, OnTriggerEnter() runs which adds the game object to the list of targets the turret controller is attacking.

// Scripts/Weapons/PerimeterCollider.cs
//
// The following function triggers when a unit gameobject
// has come within range of the defense structure colliders

	void OnTriggerEnter(Collider collider)
	{
    // check if a unit has collided with the weapon's range
		if (collider.gameObject.tag == "Dobbit") {	 
			collisionCounter++;						
      // adds the gameobject to the target list
			((TurretControllerBase)turretController).AddTarget(collider.gameObject);
      // starts firing
			((TurretControllerBase)turretController).fire = true;
			inCollision = true;	
		}

	}

When the game object exits the collider range, OnTriggerExit() runs which removes the game object from the list of targets the turret controller is attacking.

// Scripts/Weapons/PerimeterCollider.cs
//
// This function triggers when the unit exits the weapon range
// it removes the target from the list of gameobjects the defense
// structure will attack
// 
	void OnTriggerExit(Collider collider)
	{
    // gameobject that collided was a unit
		if (collider.gameObject.tag == "Dobbit") {	
      // subtracts from the current target list
			collisionCounter--;	
			// removes the target from the list
			((TurretControllerBase)turretController).RemoveTarget(collider.gameObject);

      // if there are no more targets in rnage, then we turn off the attack
			if(collisionCounter == 0)
			{		
				inCollision = false;

        // for a special structure, the catapult, we stop the animation loop
				if (transform.parent.GetComponent<StructureSelector> ().structureType == "Catapult") 
				{
					transform.parent.GetComponent<WeaponAnimationController> ().StopAnimations ();
				}
			}
		}
	}

Projectile.cs and Arrow.cs

The scripts for both the cannon projectiles and the archer tower arrows. These scripts instantiate the projectile collision and unit death.

// Scripts/Weapons/Projectile.cs Excerpt
//
// The following function triggered by PerimeterCollider.cs
// which determines when a unit enters the range of a weapon
// and has been hit by the projectile from the defense structure

    void OnTriggerEnter(Collider collider)
    {
      // Successfully hits a unit
		if(collider.gameObject.tag == "Dobbit")
		{	       
			Vector3 pos = collider.gameObject.transform.position;

      // Calculates the game object's remaining life, if greater than >30
			if(collider.gameObject.GetComponent<FighterController>().life>30)
			{	
        // create sparks where they collided 
        // and play the soldier hit sound effects
				Instantiate(Sparks, new Vector3(pos.x, pos.y, explosionZ), Quaternion.identity);//contact.point
				((SoundFX)soundFx).SoldierHit();
			}
				else
			{
          // Unit no longer has the health for the attack
          // Kill and mark with a tombstone
				Instantiate(Vortex, new Vector3(pos.x, pos.y, explosionZ), Quaternion.identity);
				Instantiate(Grave, new Vector3(pos.x, pos.y, zeroZ), Quaternion.identity);
				Instantiate(Ghost, new Vector3(pos.x, pos.y, ghostZ), Quaternion.identity);

			// Removes the unit from Helios controller script
          ((Helios)helios).KillUnit(collider.gameObject.GetComponent<FighterController>().assignedToGroup,

       // gets the index value
				collider.gameObject.GetComponent<Selector>().index);
				((SoundFX)soundFx).SoldierExplode();
			}
			// destorys the original unit game object
			collider.gameObject.GetComponent<FighterController>().Hit();
	        Destroy(gameObject);
		}
		  
    }

Defense Structure Example (Cannon)

Like many free-to-play strategy games, there are defense weapons like the below example included in the new City Building Kit version.

636

Defense weapon cannon example. Click to view larger.

XML example for a defense structure

Here's an example of the simple cannon weapon in the XML. The Scripts/Creators/BaseCreator.cs will use these settings.

<Weapon>
	<Name>Cannon</Name>	
    <!--  name displayed in the store -->		
  
	<Description>Heavy Artilery.</Description>
    <!--  Description displayed in the store -->		
								
	<Currency>Gold</Currency>	
    <!-- Gold, Mana, or Crystals purchase currency -->		
  		
	<Price>100</Price>
  <!-- amount of resource necessary to pay for the building -->						
			
	<TimeToBuild>30</TimeToBuild>
  <!-- the time (in minutes) needed to create the building -->

	<Life>200</Life>
  <!-- hitpoints of the building -->
  
	<XpAward>100</XpAward>
  <!-- experience awarded for the completion of an object -->					
  
	<FireRate>2</FireRate>
  <!-- shots per second -->
  <!-- for version 6.0 this is defaulted to 1 shot per 2 seconds in Scripts/Weapons/TurrentControllerBase.cs where you see fireRate = 2.0f -->
</Weapon>

There are other values shown in the XML provided with the kit but we've just included these as a template for developers to work with.

Where can I edit the fire rate for defense weapons?

Also, the Scripts/Weapons/TurrentControllerBase.cs script sets the FireRate for all weapons to a default of 1 shot every 2 seconds for developer testing of the kit.

To activate the FireRate XML object seen above, you'll need to edit the Scripts/Weapons/TurrentControllerBase.cs script to read and use the XML value rather than the default set near the top of the TurrentControllerBase.cs script as seen in the following excerpt:

// Bullet shooting rate
  // 2.0f = one shot every 2 seconds
  // You could also try 1.3f = one shot every 1.3 seconds 
	protected float 
		fireRate = 2.0f,
		elapsedTime;

For more details about the XML, please see the Shop Menu > Defense Weapons documentation.

Test weapon fire and automated controls

In Scripts/Weapons/WeaponAnimationController.cs we've left some functions for you to test weapon usage with. This includes both manual key control and automated firing.

// Excerpt from Scripts/Weapons/WeaponAnimationController.cs
// The following lines are commented out
// But uncommenting them will enable either manual fire control testing
// of your defense structures or testing automated fire.

	// Update is called once per frame
	void Update () 
	{	
    // Uncomment to enable manual key fire controls
		//ManualFireControl ();
    // Uncomment to enable auto fire testing
		//TestAutoFire ();
	}

Test manual fire animation controls and movement of your defense structure with keyboard controls.

KeyDescription
ARotate Clockwise
DRotate Counterclockwise
WFire the weapon
SStop firing
// Excerpt from Scripts/Weapons/WeaponAnimationController.cs
//
// Manual fire controls for rotation and firing
// A = Rotate Clockwise
// D = Rotate Counterclockwise
// W = Fire the weapon
// S = Stop firing
//
	private void ManualFireControl()
	{
		if (Input.GetKey(KeyCode.A)) 
		{
			RotateCW();
		}
		if (Input.GetKey(KeyCode.D)) 
		{
			RotateCCW();
		}
		if (Input.GetKey(KeyCode.W)) 
		{
			Fire ();
		}		
		if (Input.GetKey(KeyCode.S)) 
		{
			Stop ();
		}
	}

Test automated firing with this randomization script.

// Excerpt from Scripts/Weapons/WeaponAnimationController.cs
//
// Tests automated firing. chooses a random pattern of movement
// firing, and stopping based on one of the 4 cases
	//Test AutoFire
	private float 
		fireTimer = 0,
		fireTime = 0.1f;

	private void TestAutoFire()
	{
		fireTimer += Time.deltaTime;
		if(fireTimer>fireTime)
		{
			fireTimer = 0;
			int i= Random.Range(0,3);
			
			switch (i) 
			{
			case 0:
				RotateCW();
				break;
			case 1:
				RotateCCW();
				break;
			case 2:
				Fire ();
				break;
			case 3:
				Stop ();
				break;			
			}			
		}
	}