2D Game Development – World Interactions: Collectibles
Day 061 #100DaysOfCode
Day 015 #100DaysOfGameDev
Learning how to modify the Character script, I added some lines of code to create a Health stat and a Speed stat. The Speed stat is just a variable substitute for code that was previously written to determine how fast the character will move, but the Health stat has its own Function written.
The new Function uses a new Mathf command that I haven’t seen before: Clamp. This limits any values that get assigned to the variable to stay within a defined minimum and maximum, as set by the parameters of the function.
Because the Health and Speed stats are both public, they will show up in the Unity Inspector where they can be modified at will.
Next, I added an object intended to be picked up by the character. It is given a 2D Box Collider, like other objects, only this one is made into a Trigger.
A Trigger requires something to happen and, in this case, I needed to write a new Script to define what this will be. The new script is called HealthCollectible and will define what will happen when the Character triggers the Health Collectible. Now to write it!
The HealthCollectible script references the RubyController script when a collision is detected. Since the BoxCollider of the health pack was give Trigger status, it now checks to make sure the player is the object making the collision, else it will just ignore it and not do anything.
Once the player is verified as the collider, the script then “collects” the health (i.e. destroys it) and grants the player more health. If the player is already at maximum health, the script ignores the collision and does not destroy the health pack so it may be used at another time.