I added a melee system to my 2.5D sidescroller, so far, the melee itself works fine, though for some reason, the enemies get instantly destroyed instead of just being damaged.
My Script for hits-taken in the Enemy-script looks like this:
public void EnemyDeath()
{
Player pstats = Player.GetComponent<Player> ();
isHit = true;
bloodfront.renderer.enabled = true;
bloodback.renderer.enabled = true;
collider.enabled = false;
pstats.CurrentEXP += 40;
Destroy (gameObject, 0.5f);
}
public void DisCheck(float dist)
{
Debug.Log (dist);
if (dist < 2)
{
EnHealth -= 25;
isHit = true;
StartCoroutine (WaitForNextHit ());
}
}
bool hittable = true;
bool defeated = false;
private IEnumerator WaitForNextHit() {
yield return new WaitForSeconds(0.1f);
hittable = true;
isHit = false;
Debug.Log("WaitForNextHit Done");
}
void Update ()
{
float hitting = 0.1f;
Player pstats = Player.GetComponent<Player> ();
float distx = transform.position.x - pstats.transform.position.x;
float disty = transform.position.y - pstats.transform.position.y;
if (pstats.attackingLeft && distx > -3 && distx < 0 && hittable)
{
hittable = false;
DisCheck (disty);
}
if (pstats.attackingRight && distx < 3 && distx > 0 && hittable)
{
hittable = false;
DisCheck (disty);
}
if (EnHealth <= 0 && !defeated)
{
defeated = true;
EnemyDeath ();
}
if (!isHit)
{
hitting = 0.1f;
transform.position = Vector3.MoveTowards (transform.position, Waypoints [Marker].transform.position, 2 * Time.deltaTime);
if (transform.position == Waypoints [Marker].transform.position)
{
Marker ++;
}
if (Marker == Waypoints.Length)
{
Marker = 0;
}
}
if (isHit)
{
hitting = 1.0f;
}
}
With the bool “defeated” I prevented the player from getting the experience multiple times.
What I want is for the enemy to loose health on a hit just once and be immune to hits for a short moment. Though once the player attacks the enemy, it’s always a direct kill and I don’t know why.
The “IsHit” and “hitting” are for the being hit animation of the enemy, it’s not fully working, but for that I’ll open a different question, since it’s a different issue.