添加陷阱,挂载一计时掉血脚本。因为是固定时间掉血,所以计时器写在FixedUpdate里就行
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Damagable : MonoBehaviour
{ bool flag;//陷阱开关
private float damageCD = 1f;
private float damageCDLeftTime;
// Start is called before the first frame update
void Start()
{
flag = true;//默认冷却完毕
damageCDLeftTime = damageCD;
}
// Update is called once per frame
void Update()
{
}
void FixedUpdate(){
//Debug.Log(damageCDLeftTime);
if(!flag){
damageCDLeftTime -= Time.deltaTime;
//Debug.Log(damageCDLeftTime + " " + flag);
if(damageCDLeftTime <= 0){
flag = true;
damageCDLeftTime = damageCD;
}
}
}
void OnTriggerStay2D(Collider2D other){
//Debug.Log("update");
PlayerControl pc = other.GetComponent<PlayerControl>();//检测碰撞物体是否挂载了PlayerController脚本,有的话就是玩家了
if(pc != null && flag){
pc.ChangeHealth(-1);
flag = false;
damageCDLeftTime = damageCD;
}
}
}
然后人物在陷阱里固定不动时,只会扣一次血,debug发现OntriggerStay2D函数没在运行,是平面刚体组件休眠节省资源的原因,我们需要调整一下参数:参考