以下是各个小怪继承的父类【Enemy】脚本。
主要功能包含:
1.怪物自身受到伤害;
2.受伤闪烁红色+粒子特效;
3.玩家与怪物触碰受到伤害。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public abstract class Enemy : MonoBehaviour //抽象类
{
public int health;
public int damage;
public float flashTime;
public GameObject BloodEffect;
private SpriteRenderer sr;
private Color originalColor;
private PlayerHealth playerHealth;
// Start is called before the first frame update
public void Start()
{
playerHealth = GameObject.FindGameObjectWithTag("Player").GetComponent<PlayerHealth>();
sr = GetComponent<SpriteRenderer>(); //获取原始图
originalColor = sr.color; //初始颜色赋值
}
// Update is called once per frame
public void Update()
{
if (health <= 0)
{
Destroy(gameObject);
}
}
public void TakeDamage(int damage)
{
Debug.Log("Takedamage");
health -= damage;
FlashColor(flashTime);
//生成粒子特效,流血
Instantiate(BloodEffect, transform.position, Quaternion.identity);
GameController.camShake.Shake();
if (health <= 0)
{
Destroy(gameObject);
}
}
void FlashColor(float time)
{
sr.color = Color.red;
//延迟时间
Invoke("ResetColor", time); //还原颜色
}
//还原
void ResetColor()
{
sr.color = originalColor;
}
void OnTriggerEnter2D(Collider2D other)
{
//若检测到player并且为胶囊体碰撞框时
if (other.gameObject.CompareTag("Player") && other.GetType().ToString() == "UnityEngine.CapsuleCollider2D")
{
if (playerHealth != null)
{
playerHealth.DamagePlayer(damage);
}
}
}
}