- Home /
Make enemy damage the player,Enemy do damage to player Script
So i'm working on my first 2D game and I've made my character to do damage to the enemy , but I can't make the enemy to damage my character. Here's the script for my character combat:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityStandardAssets.CrossPlatformInput;
public class PlayerCombat : MonoBehaviour
{
public Animator animator;
public Transform attackPoint;
public float attackRange = 0.5f;
public LayerMask enemyLayers;
AudioSource m_swingSound;
public int attackDamage = 40;
public float attackRate = 2f;
float nextAttackTime = 0f;
void Start()
{
m_swingSound = GetComponent<AudioSource>();
}
private void Update()
{
if (Time.time >= nextAttackTime)
{
if (CrossPlatformInputManager.GetButtonDown("Attack"))
{
Attack();
m_swingSound.Play();
nextAttackTime = Time.time + 2f / attackRate;
}
}
}
void Attack()
{
animator.SetTrigger("Attack");
//Detect enemies in range of attack
Collider2D[] hitEnemies = Physics2D.OverlapCircleAll(attackPoint.position, attackRange, enemyLayers);
//Damage them
foreach (Collider2D enemy in hitEnemies)
{
enemy.GetComponent<Enemy>().TakeDamage(attackDamage);
}
}
void OnDrawGizmosSelected()
{
if (attackPoint == null)
return;
Gizmos.DrawWireSphere(attackPoint.position, attackRange);
}
}
Here's my character health script:
sing System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerHealth : MonoBehaviour
{
public int maxHealth = 50;
public int currentHealth;
public HealthBar healthBar;
void Start()
{
currentHealth = maxHealth;
healthBar.SetMaxHealth(maxHealth);
}
}
Here's the enemy attack script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Enemy : MonoBehaviour
{
public Animator animator;
public int maxHealth = 100;
int currentHealth;
public Enemy_Behaviour enemyBehaviour;
[SerializeField] public GameObject gameObject;
[SerializeField] public AudioSource audioSource;
void Start()
{
currentHealth = maxHealth;
}
public void TakeDamage(int damage)
{
currentHealth -= damage;
animator.SetBool("Attack", true);
animator.SetTrigger("Hurt");
if(currentHealth <= 0)
{
Die();
}
}
void Die()
{
animator.SetBool("isDead", true);
audioSource.Play();
GetComponent<Collider2D>().enabled = false;
this.enabled = false;
enemyBehaviour.enabled = false;
Destroy(gameObject, 2f);
}
}
And here's enemy's behaviour script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Enemy_Behaviour : MonoBehaviour
{
#region Public Variables
public float attackDistance; //Minimum distance
public float moveSpeed;
public float timer; //Cooldown of attacks
public Transform leftLimit;
public Transform rightLimit;
[HideInInspector] public Transform target;
[HideInInspector] public bool inRange; //See if player in range
public GameObject hotZone;
public GameObject triggerArea;
#endregion
#region Private Variables
private Animator animator;
private float distance; //store distance between enemy and player
private bool attackMode;
private bool cooling; //check if enemy is cooling after attack
private float intTimer;
#endregion
void Awake()
{
SelectTarget();
intTimer = timer;
animator = GetComponent<Animator>();
}
// Update is called once per frame
void Update()
{
if (!attackMode)
{
Move();
}
if(!InsideofLimits() && !inRange && !animator.GetCurrentAnimatorStateInfo(0).IsName("Enemy_attack"))
{
SelectTarget();
}
if (inRange)
{
EnemyLogic();
}
}
void EnemyLogic()
{
distance = Vector2.Distance(transform.position, target.position);
if (distance > attackDistance)
{
StopAttack();
}
else if (attackDistance >= distance && cooling == false)
{
Attack();
}
if (cooling)
{
Cooldown();
animator.SetBool("Attack", false);
}
}
void Move()
{
animator.SetBool("canWalk", true);
if (!animator.GetCurrentAnimatorStateInfo(0).IsName("enemy1Attack"))
{
Vector2 targetPosition = new Vector2(target.position.x, transform.position.y);
transform.position = Vector2.MoveTowards(transform.position, targetPosition, moveSpeed * Time.deltaTime);
}
}
void Attack()
{
timer = intTimer;
attackMode = true;
animator.SetBool("canWalk", false);
animator.SetBool("Attack", true);
}
void Cooldown()
{
timer -= Time.deltaTime;
if (timer <= 0 && cooling && attackMode)
{
cooling = false;
timer = intTimer;
}
}
void StopAttack()
{
cooling = false;
attackMode = false;
animator.SetBool("Attack", false);
}
public void TriggerCooling()
{
cooling = true;
}
private bool InsideofLimits()
{
return transform.position.x > leftLimit.position.x && transform.position.x < rightLimit.position.x;
}
public void SelectTarget()
{
float distanceToLeft = Vector2.Distance(transform.position, leftLimit.position);
float distanceToRight = Vector2.Distance(transform.position, rightLimit.position);
if(distanceToLeft > distanceToRight)
{
target = leftLimit;
}
else
{
target = rightLimit;
}
Flip();
}
public void Flip()
{
Vector3 rotation = transform.eulerAngles;
if(transform.position.x > target.position.x)
{
rotation.y = 180f;
}
else
{
rotation.y = 0f;
}
transform.eulerAngles = rotation;
}
}
I would tremendously appreciate the help
Answer by Bmarlyman21 · Nov 20, 2021 at 06:44 PM
I noticed on your Enemy script you have a method called "TakeDamage" which allows the player to damage the enemy. You don't appear to have the same thing on your "PlayerHealth" script. Also in your "Enemy_Behavior" script, you seem to only have functionality for animation in the "Attack" method, and nothing to do with affecting the player's health.
I would add 2 things:
1) Add a method on your PlayerHealth script which subtracts damage from health, just like you have in your Enemy script.
2) Get a reference to PlayerHealth in your Enemy_Behavior script, then call the damage method you've just created.
Let me know if that helps.
No problem, glad I could help! If this was the answer you were looking for, consider marking it as the accepted answer for this post.