2D Game Development – World Interactions: Damage Zones and Enemies
Day 062 #100DaysOfCode
Day 016 #100DaysOfGameDev
I was tasked with adding a zone to the game which would damage the character when triggered. To do this, a new script had to be written called DamageZone. This script is just like the HealthCollectible script, except without the health check and without being destroyed.
This worked, but Ruby would stop taking damage if she stopped moving in the damage zone. This was fixed by changing the function in the script from OnTriggerEnter2D to OnTriggerStay2D. The latter causing damage to be applied at all times while the character is in the zone, but damage would then cease to be applied if the character stopped moving, even if still in the zone. The fix for this was to change the Ruby Rigidbody setting for Sleeping Mode to Never Sleep. Now she takes damage when she enters the zone and at all times when within the zone, even if not moving.
Now the problem exists that Ruby takes too much damage too fast, rapidly depleting all of her health. To prevent this and slow down the damage, it is necessary to create those quintessential “invincible frames” where a character is immune to further damage for a fraction of time before being able to take more.
With that resolved it was time to add a bigger threat to Ruby: enemies!
I loaded the enemy robot sprite and gave it both a Rigidbody2D and BoxCollider2D component and configured them. To get the enemy to move, a new script called EnemyController had to be created.
The new controller contained all the information to get the enemy robot to move back and forth, either up and down or left and right, at a set interval of time. Some of the settings for this script have been declared public so they can be set or altered directly from the Inspector.
With movement handled, the task was then to add damage should Ruby come in contact with a robot while it patrols. With proper collision code in place, this was taken care of and everything seemed to be working.