I’m thinking about how to make my combat better similar to how it’s done in TES Daggerfall.
In my game it works like this:
- The player gets within some distance of the enemy
- The enemy moves towards the player
- The enemy shoots a raycast
- If the raycast hits the player, play the hit animation and decrease player’s health
This is the code for it:
void Update()
{
if (Physics.Raycast(transform.position, transform.rotation * -Vector3.forward, out RaycastHit info, raycastDistance))
{
if (_canAttack && info.collider.gameObject.TryGetComponent<PlayerHealth>(out var playerHealth))
{
StartCoroutine(CooldownAttack(playerHealth));
}
}
}
private IEnumerator CooldownAttack(PlayerHealth playerHealth)
{
animator.SetTrigger("Attacking");
_canAttack = false;
Invoke(nameof(ResetAnimation), animationDowntime);
yield return new WaitForSeconds(0.75f); // Wait a little before decreasing player health
playerHealth.UpdateHealth(-enemyData.attackStrength);
yield return new WaitForSeconds(attackDowntime);
_canAttack = true;
Debug.Log("Can attack again");
}
private void ResetAnimation()
{
animator.SetBool("Attacking", false);
_canAttack = true;
}
The two biggest issues with this are: 1) the player gets damaged even if they move away while the enemy’s attack animation is playing, and 2) the attack animation seems to play for a very short time.
Any help is appreciated.