深圳政协委员钟帆飞诈骗30亿

主持正义

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理
  27 随笔 :: 0 文章 :: 90 评论 :: 56257 阅读

人物和怪物的攻击都有CD冷却,在PlayerAttack脚本中添加成员

    //冷却倒计时
    public float attackTimer;
    //CD冷却时间
    public float coolDown = 2.0f;

修改Update

复制代码
    void Update () {
        if (attackTimer > 0)
            attackTimer -= Time.deltaTime;
        if (attackTimer < 0)
            attackTimer = 0;

        if (Input.GetKeyUp (KeyCode.F) && attackTimer == 0) {
            Attack();
            attackTimer = coolDown;
        }
    }
复制代码

运行Game,点击F后,AttackTimer从2到0后才可再次释放攻击。

下面创建怪物的攻击脚本,在Scripts文件夹中选中PlayerAttack,按ctrl+d,赋值一份,重命名为EnemyAttack:

1. 修改类名为EnemyAttack
2. 删除对按键F输入的判断,怪物始终2秒攻击一次玩家
3. 修改Attack内的EnemyHealth为PlayerHeath类

复制代码
public class EnemyAttack : MonoBehaviour {
    public GameObject target;
    //冷却倒计时
    public float attackTimer;
    //CD冷却时间
    public float coolDown = 2.0f;
    // Use this for initialization
    void Start () {
    
    }
    
    // Update is called once per frame
    void Update () {
        if (attackTimer > 0)
            attackTimer -= Time.deltaTime;
        if (attackTimer < 0)
            attackTimer = 0;

        if (attackTimer == 0) {
            Attack();
            attackTimer = coolDown;
        }
    }

    private void Attack(){
        if (Vector3.Distance (target.transform.position, transform.position) < 2) {
            PlayerHealth ph = (PlayerHealth)target.GetComponent ("PlayerHealth");    
            ph.AddjustCurrentHealth (-10);
        }
    }
}
View Code
复制代码

运行Game,玩家和怪物靠近时,每隔2秒,玩家掉血10,玩家按下F,怪物掉血10。

但是有个问题,上图可以看到怪物和玩家距离过近,并且有抖动,那是因为EnemyAI里的向玩家移动的代码,没有限制为,当距离大于2的时候,怪物才向玩家移动,将该距离定义为类的全局变量maxDistance,方便进行修改。

//当距离大于2的时候
if
(Vector3.Distance (target.position, myTransform.position) > maxDistance) { //怪物向着Player的方向移动 myTransform.position += myTransform.forward * moveSpeed * Time.deltaTime;
}

 

posted on   jayce80  阅读(310)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
阅读排行:
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
· SQL Server 2025 AI相关能力初探
点击右上角即可分享
微信分享提示