Damage usually works hand in hand with collision detection, as when the two hitboxes collide it triggers the code to activate. Having your health as a numerical value which can rise and deplete in-game is as simple as creating a public float variable. Here's an example of code used to store health in a player, and a copy of it is placed inside every instance of an enemy (as posted by (ankit.tiks007, 2015) from Unity answers): "
public static float health = 100;
void OnCollisionEnter(Collision col){
if(col.gameObject.name == "Player"){
health-=5;
}
Essentially all the code listed above does is when an enemy, which contains said code, collides with the player character, it reduces 5 from their maximum pool of 100 health. Using the health value, various tasks could then be coded in more depth, such as destroying the character when the health reaches 0, knocking them back upon the collision to show force, or creating a duplicate of the enemy code I listed that's designed to be inside healing items instead, where it raises the player's health by 5 instead of reducing it to add another layer of skill to the game.
No comments:
Post a Comment