public class Enemy { private int health; private int attackPower; public Enemy(int startingHealth, int startingAttackPower) { health = startingHealth; attackPower = startingAttackPower; } public void attack(Player target) { int damage = attackPower - target.getDefense(); target.takeDamage(damage); } public void takeDamage(int amount) { health -= amount; if (health <= 0) { die(); } } private void die() { // remove enemy from game } }
using UnityEngine; public class Enemy : MonoBehaviour { public int health; public int speed; void Update() { transform.Translate(Vector3.left * speed * Time.deltaTime); } void OnTriggerEnter2D(Collider2D collision) { if (collision.CompareTag("Player")) { Player player = collision.GetComponentThis example defines an Enemy class as a component of a GameObject in a Unity game. It has health and speed fields and an Update() method that moves the enemy to the left. It also has a OnTriggerEnter2D() method that checks for collisions with a player and calls the player's takeDamage() method if necessary. If the enemy's health drops below 0, the GameObject is destroyed. Package/library: Unity 2D Physics package.(); player.takeDamage(1); if (health <= 0) { Destroy(gameObject); } } } }