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

How to georeference a BIM model

Oh, what of Big O notation and Complexity [Part 2]

How to Design Job Scheduler

DOMINOS ON AWS CASE STUDY

Why developers should think more like product owners

Learn Julia: Collections and Broadcasting.

Generating MAME Bezel Layouts with Python

A Multisite Drastically Reduces the Technological Debt in an Organisation

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

How To Play Sound Effects In Unity (Creating A Global Sound Manager)

2D Mobile: Setting Up The Player

Week 24: How to add SFX to you game without going mad

Unity Tutorial — Toon Shade in HLSL