Day 135 — Creating Universal Health Damage

[SerializeField]
private int _maxHealth;
[SerializeField]
private int _minHealth;
[SerializeField]
private int _currentHealth;
private void Start()
{
_currentHealth = _maxHealth;
}
public void Damage(int damageAmount)
{
_currentHealth -= damageAmount;
if (_currentHealth < _minHealth)
{
Destroy(this.gameObject);
}
}
if (Input.GetMouseButtonDown(0))
{
Vector3 center = new Vector3(0.5f, 0.5f, 0);
Ray rayOrigin = Camera.main.ViewportPointToRay(center);
RaycastHit hitInfo;
if (Physics.Raycast(rayOrigin, out hitInfo))
{
Debug.Log("Hit: " + hitInfo.collider.name);
Health health = hitInfo.collider.GetComponent<Health>();
if (health != null)
{
health.Damage(50);
}

}
}
public enum EnemyState
{
Idle,
Chase,
Attack
}
[SerializeField]
private EnemyState _currentState = EnemyState.Chase;
private Health _playerHealth;
private float _attackDelay = 1.5f;
private float _nextAttack = -1f;
void Start()
{
_controller = GetComponent<CharacterController>();
_player = GameObject.FindGameObjectWithTag("Player").transform;
_playerHealth = _player.GetComponent<Health>();
}
void Update()
{
if (_currentState == EnemyState.Chase)
{

Movement();
}
if (_currentState == EnemyState.Attack)
{
if (Time.time > _nextAttack)
{
_playerHealth.Damage(35);
_nextAttack = Time.time + _attackDelay;
}
}
}
private void OnTriggerEnter(Collider other)
{
if (other.tag == "Player")
{
_currentState = EnemyState.Attack;
}
}
private void OnTriggerExit(Collider other)
{
if (other.tag == "Player")
{
_currentState = EnemyState.Chase;
}
}

--

--

--

Hey and welcome! My name is Connor and my goal here is to put out a daily post for a full year about my game development journey.

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Why Open Source Is Good For Business

SRE and Observability: inside a Formula One lap for improvement

My GSoC ’21 Journey: Week 10

Hackathons — A simple guide for beginners

How to use one MongoDB instance in multiple FastAPI routers?

KYVE. Mission Korellia

Docker-Container Day-5

Learn Julia: Collections and Broadcasting.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Connor Fullarton

Connor Fullarton

Hey and welcome! My name is Connor and my goal here is to put out a daily post for a full year about my game development journey.

More from Medium

Cameras and the Sleeping Guard

Learn to code by Making 2.5 D Space Shooter Game.

Adding a health powerup to our prototype

Orbital Transposer Virtual Camera Explained in Unity’s Cinemachine