Skip to content

Technical Design

Dirk ten Have edited this page May 24, 2024 · 103 revisions

Player Animations:

De animaties zijn geïntegreerd via scripts in de player movement script en de player attack script. Als de speler beweegt, dan krijg je een animatie dat de speler loopt, als de speler via de muis aanvalt, doet de speler een aanval animatie. De animaties zijn anders voor andere classes, zoals voor de archer en de knight, zijn de animaties anders, want de knight hoeft alleen te zwaaien met zijn zwaard en voor de archer heb je dat de speler eerst een arrow pakt en dan gaat aimen voordat het aanvalt.

Script Layout:

Walking Anim

De bovenste script is het script voor de movement, als de speler beweegt, gaat de speler ook bewegen met de animatie waarvan het ook nodig is. De script van beneden is hoe de speler de animatie gebruikt voor bijvoorbeeld de melee attack, of de archer attack.

Universal Health Script

This script is used by every single object that needs health, like the player, enemy, structures or the main base.

Damage Dealing (Universal Health)

This script gets used to damage to damage each object that are bound to categories, the Enemy, the Player, the Structure and the main base. the Enemy deals damage to the base, structures or player, the Player deals damage to enemies, and some structures can deal damage to the enemy.

graph TD;
    A[Player] -->|DealDamage| B[Enemy]
    C[Structure] -->|DealDamage| D[Enemy]
    E[Enemy] -->|DealDamage| F[Player]
    E -->|DealDamage| G[Structure]
    E -->|DealDamage| H[Base]
Loading

Technical Design: Made by Dirk ten Have

Health Bar:

De Healthbar wordt gebruikt samen met de universal health, wat de speler, main gebouw, andere gebouwen of enemies kunnen gebruiken, zodat ze niet bijvoorbeeld na een hit dood gaan. Als het HP bij de healthbar op 0 is, gaat degene die er aan is geassigned met deze healthbar dood gaat. Verder is het ook mogelijk om een maximale HP threshold te geven aan degene die de healthbar krijgt. Verder als degene die de healthbar heeft damage krijgt, dan veranderd de healthbar ook met de hoeveelheid health het nog heeft.

Script Layout:

Schermafbeelding 2024-05-24 100817

Structure Building:

This script gets used when the player is on an placeholder place, where they are able to buy structures from the shop, if the player already has placed an structure on there, they can't create another structure on the same place.

I made it all inside of one script to make it work by giving the script unto the player, I made the UI useable for everyone.

     [SerializeField] private GameObject buildUI;
     [SerializeField] private GameObject[] structures;
        
     private bool _canBuild;
     private Transform _getTransform;

     private void Start() => buildUI.SetActive(false);
        
     private void Update()
     {
           if (Input.GetKeyDown(KeyCode.E) && _canBuild)
             buildUI.SetActive(true);
     }
        
     private void OnTriggerEnter(Collider other)
       {
           if (other.CompareTag("BuildSite"))
           {
              _getTransform = other.transform;
           if (_getTransform.childCount == 0)
              _canBuild = true;
       }
    }

    private void OnTriggerExit(Collider other)
    {
       buildUI.SetActive(false);
       _canBuild = false;
    }

Inside of the UI of to even build the structure, you need an button for that, and what I used to create an function to let it spawn was by using this part of the code:

     public void Build(int numberOfStructure)
     {
         _canBuild = false;
         GameObject spawnedObject = Instantiate(structures[numberOfStructure], _getTransform.position, Quaternion.identity);
         spawnedObject.transform.parent = _getTransform;
         spawnedObject.transform.localPosition += Vector3.up;
            
         buildUI.SetActive(false);
     }

Structure Behaviour:

This script gets used when the enemy is close in range of the structure, the structure will then shoot at the enemy that would deplete the health. It will only target the first enemy target, and not the 2nd one that is in range for now.

So with that there are 2 states, the Search state and the Attacking state.

graph TD;
    A[Structure] -->|Search State: Looking for enemy| B[Target]
    A -->|Found Target: Enemy detected| C[Attack State]
    C -->|Attack State: Shooting enemy| B
    C -->|Out Of Range or Enemy Defeated: Returning to search| A
    B -->|Out Of Range or Death| A
Loading

Ping system:

A script that handles the ping system: pings are GameObject prefabs that will be instantiated when you call a function

Enemy

Made by: Daan

EnemyMovementAndAttack

The first iteration of the enemy system was functional, however it was buggy and didn’t allow for any enemy variation. Therefore we decided to make a 2nd iteration. This system had its movement, targeting and attacking divided into 3 separate scripts, and was altered to use the universal weapon system. This new enemy system allowed for ranged and melee enemies to be made using the same scripts, and also added the ability to select what objects the enemy should target (In case we wanted an enemy that only focused on the base instead of the player, or vice versa). The enemy still used Unity's navmesh system for their pathfinding as this was the quickest and easiest way to do it.

This flowchart describes the enemy's intended behaviour Enemy flowchart(1)

Enemy Movement

The EnemyMovement script is where the scripts communicate with the NavMeshAgent component to tell the enemy where and when to move. The SetTarget function is used to communicate the current target to the NavMeshAgent. In the Update function the script checks wether or not it has reached its set stopDistance from the target. When it has the CheckLineOfSight function will start to be called, this checks if there are any obstacles between the enemy and the player, if there are the enemy will continue to move towards the player. If the enemy is within its stopping distance and has line of sight to the player the StopMove coroutine is called. This coroutine stops the player after a delay, otherwise ranged enemies would often stop halfway behind a wall and shoot it instead. When the enemy is stopped the FaceTarget will quickly lerp the enemy rotation towards the target, and keep doing so untill the target leaves its stopping distance/line of sight.

Enemy Targeting

The EnemyTargeting is where the target for the enemy is determined. On start the ResetTargetToMainBase is called so that the enemy will always spawn with a target. The DetectPlayers function uses an OverlapSphere to check if any players are close, and there are, will call the SetNearestPlayerAsTarget function with the player as a parameter. If the function stops detecting players ResetTargetToMainBase is also called. SetNearestPlayerAsTarget First checks to see if there are multiple players nearby. If there is only a single player then that player will be set as the _enemyTarget. If there are multiple players in range, the function will instead check which is the closest and set that as the target. The UpdateTarget function is required for the navemesh agent to follow its target if it moves as they do not do so by default. UpdateTarget simply communicates the current target's position to the navemesh agent every few frames, and also calls the GetTargetEdge function beforehand. GetTargetEdge will get the closest edge of the target's hitbox instead of its center so that the enemy doesn't end up walking against the target and doing nothing. GetTargetEdge then sets the enemy's target to the calculated position.

Enemy Attack

The EnemyAttack script does not do a lot by itself, but is made to work with the universal weapon system. The Start function calls the SpawnWeapon function on the weapon ScriptableObject thats given to the script to initialize the weapon. The Attack function calls the attack function on the scriptable object aswell.

image

Enemy References

The EnemyReferences script simply holds a few references that are required in more than one script to avoid having to do this for each script individually.

image

Weapons

Made by: Daan

In this game we wanted to handle the attacking using weapons. This was so that the same system could be used for all things that needed to attack, and so that all those things needed a single attack script. We wanted these weapons to be easily adjustable and make it easy to add more of them. For this reason I decided to use Unity's ScriptableObjects. This way we could make a weapon in a few clicks and easily drag and drop them onto whatever we wanted. The Weapon parent class has all the necessary functions and variables that the scripts using the weapon need to interact with. Then I made the RangedWeapon and MeleeWeapon classes that inherit from Weapon.

image

Classes

Weapon

This is the parent ScriptableObject class from which all weapon classes inherit. The SpawnWeapon function instantiates the model and sets its position to the parent given to the script. DespawnWeapon destroys the model. Attack is to be defined in the classes that inherit from this class, it is defined here so that an Attack script can call the Attack function on every kind of weapon without having to change the script. SetAttackDirection sets the position where the weapon attack should be done and also sets its direction towards the mouse position.

public abstract class Weapon : ScriptableObject  
{  
  [Header("Weapon stats")]  
  [SerializeField] protected int damage;  
  [SerializeField] public float attackDelay;  
 
  [Header("Visuals")]  
  [SerializeField] protected GameObject weaponModel;  
  
  public GameObject hitboxHolder;  
  protected Vector3 p_attackSpawnPosition;  
  protected Quaternion p_attackDirection;  
  
  protected GameObject p_model;  
  
public virtual void SpawnWeapon(Transform parent)  
 {  
	  p_model = Instantiate(weaponModel);  
	  p_model.gameObject.transform.SetParent(parent);  
	  p_model.transform.position = parent.transform.position;  
	  p_model.transform.rotation = parent.transform.rotation;  
 }
   
public virtual void DespawnWeapon()  
 {  
	  Destroy(p_model);  
 }  
  
public abstract void Attack();  
  
public void setAttackDirection(Quaternion dir, Vector3 pos)  
 {  
	 p_attackDirection = dir;  
     p_attackSpawnPosition = pos;  
 }
}

Ranged Weapon

The RangedWeapon class inherits from the Weapon class. The only thing this class changes is that it adds a projectile variable and that it overrides the Attack function to instantiate the projectile in the attack direction.

public class RangedWeapon : Weapon  
{  
 [Header("Projectile settings")]  
 [SerializeField] private GameObject projectile;  
  
  public override void Attack()  
	 {  
		 Instantiate(projectile, p_attackSpawnPosition , p_attackDirection);  
	 }
 }

Melee Weapon

The MeleeWeapon class is a little more complicated. It overrides the SpawnWeapon function to additionally spawn a Collider for the melee attack and also to apply a script to that collider that handles dealing damage. DespawnWeapon also additionally destroys those two components. In the Attack function I wanted to use an Coroutine to toggle the collider, however I quickly realised that this is impossible in this script itself as that requires Monobehaviour. To get around this is I made a simple script called WeaponMonoInstance that I would use to handle this coroutine instead. The ToggleHitbox function simply toggles the hitbox on and off.

public class MeleeWeapon : Weapon
    {
        [Header("Hitbox Settings")]
        [Tooltip("The amount of time the hitbox should be active")]
        [SerializeField] private float hitBoxDuration = 0.1f;
        [Tooltip("How far the hitbox should be placed in front of the player")]
        [SerializeField] private float hitboxOffset = 1;
        [SerializeField] private Vector3 hitboxScale = new Vector3(1, 1, 1);

        private BoxCollider _hitbox;
        private WeaponMonoInstance _monoInstance;
        private DealDamageOnCollision _damageScript;

        public override void Attack()
        {
            if (WeaponMonoInstance.instance != null)
                WeaponMonoInstance.instance.StartCoroutine(ToggleHitbox());
        }

        private IEnumerator ToggleHitbox()
        {
            if(_hitbox != null)
                _hitbox.enabled = true;
            yield return new WaitForSeconds(hitBoxDuration);
            if(_hitbox != null)
                _hitbox.enabled = false;
        }

        public override void SpawnWeapon(Transform parent)
        {
            base.SpawnWeapon(parent);
            _damageScript = hitboxHolder.AddComponent<DealDamageOnCollision>();
            _hitbox = hitboxHolder.AddComponent<BoxCollider>();
            _damageScript.SetDamage(damage);
            _hitbox.size = hitboxScale;
            _hitbox.center = new Vector3( 0, 0, hitboxOffset);
            _hitbox.isTrigger = true;
            _hitbox.enabled = false;
        }

        public override void DespawnWeapon()
        {
            base.DespawnWeapon();
            Destroy(_hitbox);
            Destroy(_damageScript);
        }
    }

Attack Scripts

The attack scripts are all very similar. In the Start function they call the SpawnWeapon function on from the weapon given to the script and give it a spawnPoint. The Update function is where the attack function is called depending on either input for the player or a condition for enemies. There is also a timer that ticks down in Update. the Attack function in all of these scripts first checks to see if the _attackTimer is zero. If it is zero then it will first call the weapon's SetAttackDireciton function, and after it will call the weapon's Attack function. It will then set the _attackTimer equal to the weapon's attackDelay value.

Technical designs made by Byron

Player turning

The turning of the player will use an raycast. The cursor will aim at a point in the scene it'll return a vector 3 which I can use to subtract from the current position so I know what the direction/offset is of the way I want to aim. I also have an extra feature on the getmouseposition which ignores certain layers so it targets certain area's

 private void HandlePlayerTurning()
 {
     bool success = GetMousePosition().success;
     Vector3 position = GetMousePosition().position;
     if (success)
     {
         Vector3 direction = position - transform.position;
         direction.y = 0;
         body.forward = direction;
     }
 }

 private (bool success, Vector3 position) GetMousePosition()
 {
     Ray ray = playerCamera.ScreenPointToRay(Input.mousePosition);
     if (Physics.Raycast(ray, out RaycastHit hitInfo, Mathf.Infinity, ~ignoredLayers))
         return (success: true, position: hitInfo.point);

     else
         return (success: false, position: Vector3.zero);
 }

Enemy wave spawning

On wave 1 each zone will have the exact same amount of zombies that it will spawn. It'll use a for loop so it iterates through the total spawn amount. It uses a random number generator with its ranges being the the minimum and maximum their zone then it will spawn until it has spawned the amount of enemies its required to.

graph TD;
     Start((Start))--> Wave-starts
    Wave-starts--> Get-current-wave;
    Get-current-wave--> Calculate-enemies-Count
    Calculate-enemies-Count-->Spawn-enemies
    Add-Health-Correlating-To-Wave-->Spawn-enemies
    Spawn-enemies-->Killed-all-enemies?
    Killed-all-enemies?--> |Safe period| Wave-starts;
Loading

Fake players / Mock up players

The fake players will use Unity's navmesh agents for the walking as we can bake the map and the fake players will adjust to the changes and doesn't require us to program anything extra to have him to know what places are obstacles.

The fake player also is required to detect enemies and players Ill add an collider which has an trigger which detects who walks in. If its an player it will do nothing but will remember the player for the emote system. If its an enemy it will look at the enemy and shoot at it with Daan's weapon system. And finally if there is nothing in the collider the fake player will start moving randomly again.

image

Class system

Every class has his own UI element. Every Class will have its own unity button to fire a function attached to the onclick event. in as that class, an icon which will be an sprite so we can give the player visual feedback as to which class the player is going to play as. An TextmeshPro text element for the title to give the class an name and finally an extmeshPro text element for the description to tell the player about the class and has some guidance as to how to play the chosen class. If we have extra time perhaps add an TextmeshPro text element for levels.

To load the classes in ill use an resource folder to get all the classes. I can use the size of the class folder to see how many empty class UI element it needs to spawn in. When one has spawned in ill load the first class in the class folder and give the empty class UI element all the data it needs to synchronize with that specific class. It will set the icon, description, title and will get the player and turn them into that class.

This is an empty class UI element.

image

This is the data which we use to make an new class

image

Fade effect

Using an Unity's threading/Ienumerator I can efficiently spread the task of the fade effects on a diffrent string while also being able to safely use an while loop. De functie is static so it can be used from all sorts of places. The function has 2 arguments which are: Canvas group and a float duration. See the flow chart to see how it works for each fade function.

FadeIn

graph TD;
   Start((Function called))--> image-to-alpha-0
    image-to-alpha-0--> Get-tick-amount;
    Get-tick-amount-->While-not-Finished
    While-not-Finished--> add-tick-to-alpha
    add-tick-to-alpha-->is-alpha-1?
    is-alpha-1?-->No
    No-->add-tick-to-alpha
    is-alpha-1?-->Yes
    Yes-->End-Coroutine
Loading

Reworked Emote system

The emotes itself aren't complicated. Press a number key 1 through 4 and an diffrent emote will appear over that players head. However since multiplayer doesn't work the fake player will respond if the player is in its collider. If an actuall player is inside its range it will get the players Emote script and will use it to respond to the player with the exact same emote when the player emotes.

Reworked Ping system

Re using my turning script I can get the location of where the mouse is aimed in the scene. When opening the ping menu Ill use the last known mouse location and make it spawn there. On the ping menu the player should have a variety of ping to pick from and to place. Since we dont have an actuall multiplayer function Ill have the fake players always head towards the pings

How it should work

image

The yellow exclamation point is an ping all the black dots are fake players which immediatly get a path to the ping. It will take the shortest path there no matter where they are.

Technical design made by Guido

Universal Health:

The universal health script is een script dat de health system voor elke game object managed in het unity project. Het zorgt voor: taking damage, healing, triggering events wanneer health veranderd of wanneer een gameobject dood gaat.

image

De int maxhealth laat de max health zien van het gameobject Kan niet een negatief getal zijn. De int current health laat de huidige health value zien van het gameobject Het getal zit altijd tussen de 0 en MaxHealth value. De bool isfullhealth laat zien of de gameobject max health is Kan alleen maar werkend zijn gebaseerd op de health value.

image

De heal health functie werkt als volgt: Deze functie wordt aangeroepen en zorgt ervoor dat er health value wordt gegeven aan de currenthealth value. Als de currenthealth groter is dan maxhealth wordt de currenthealth vast gezet naar een max van de maxhealth zodat die niet kan overflowen. En dan wordt de bool (een waarde dat alleen true of false kan zijn) isfullhealth true gezet en kan de gameobject geen healing meer krijgen. Hieronder is een sequence diagram van deze code

sequenceDiagram
    participant Player
    participant UniversalHealth
    participant GameObject

    Player->>UniversalHealth: TakeDamage(amount)
    UniversalHealth->>UniversalHealth: _currentHealth -= amount
    alt _currentHealth <= 0
        UniversalHealth->>UniversalHealth: Die()
        UniversalHealth->>GameObject: Destroy(gameObject)
    end
    
    Player->>UniversalHealth: HealHealth(amount)
    UniversalHealth->>UniversalHealth: _currentHealth += amount
    alt _currentHealth >= _maxHealth
        UniversalHealth->>UniversalHealth: _currentHealth = _maxHealth
        UniversalHealth->>UniversalHealth: isFullHealth = true
    else
        UniversalHealth->>UniversalHealth: isFullHealth = false
    end
Loading

Ping system

image

De lastmouseposition is een vector 3 die bijhoudt waar je muis als laatst is geweest in de wereld voordat je een ping create. De bool haspinged wordt aangeroepen wanneer er gepingd is en de gameobject gecreate is direct daarna gaat deze bool aan. De delaybetweenpings is een private float die aangepast kan worden in de inspector vanwege de serialize field en deze variabele houdt de tijd bij voordat je opnieuw kan pingen.

De heightoffset variabele is een private, in de inspector aanpasbare value die de hoogte van waar de ping geplaatst wordt aanpast gebaseerd op de locatie van de waar de ping wordt gezet en zet het object dan hoger dan de originele locatie zodat het object niet in de grond zit.

image

Hier wordt een ienumerator aangemaakt die bij gaat houden wanneer een bepaalde tijd voorbij is dat dan de ping object die geplaatst is gedestroyed wordt. Hieronder staat een sequence diagram die dit laat zien:

sequenceDiagram
  participant User as User
  participant PingSystem as PingSystem
  participant UnityEvent as UnityEvent
  participant GameObject as GameObject
  participant Coroutine as Coroutine

  User ->> PingSystem: Press "E" key
  PingSystem ->> PingSystem: Update()
  PingSystem ->> PingSystem: GetMousePosition()
  PingSystem -->> PingSystem: _lastMousePosition set
  PingSystem ->> GameObject: background.SetActive(true)
  User ->> PingSystem: Select Ping Type (SetPing)
  PingSystem ->> Coroutine: DestroyPingAfterTime(pingIndex)
  Coroutine ->> GameObject: Instantiate(pingPrefab)
  PingSystem ->> UnityEvent: onPing.Invoke()
  Coroutine ->> Coroutine: Wait for delayBetweenPings seconds
  Coroutine ->> GameObject: Destroy(ping)
  Coroutine -->> PingSystem: _hasPinged set to false
Loading

Experience function

sequenceDiagram
    participant Player
    participant ExperienceScript
    participant UI

    Player->>ExperienceScript: Start()
    ExperienceScript->>UI: showSlider.maxValue = maxExperience
    ExperienceScript->>UI: showSlider.value = 0
    ExperienceScript->>UI: showExperience.text = _currentExperience + "/" + maxExperience
    ExperienceScript->>UI: showLevel.text = "Level: " + _currentLevel

    Player->>ExperienceScript: AddExperience(experience)
    ExperienceScript->>ExperienceScript: _currentExperience += experience
    ExperienceScript->>UI: showSlider.value = _currentExperience
    ExperienceScript->>UI: showExperience.text = _currentExperience + "/" + maxExperience
    ExperienceScript->>UI: showLevel.text = "Level: " + _currentLevel

    alt if (_currentExperience >= maxExperience)
        ExperienceScript->>UI: showSlider.value = 0
        ExperienceScript->>ExperienceScript: maxExperience += experiencePerLevelIncrease + _currentLevel * experienceTimesLevelMultiplier
        ExperienceScript->>ExperienceScript: _currentExperience = 0
        ExperienceScript->>UI: showSlider.maxValue = maxExperience
        ExperienceScript->>ExperienceScript: _currentLevel += 1
        ExperienceScript->>UI: showExperience.text = _currentExperience + "/" + maxExperience
        ExperienceScript->>UI: showLevel.text = "Level: " + _currentLevel
    end
Loading

Clone this wiki locally