首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在unity2d为敌人射击冷却时间

在unity2d为敌人射击冷却时间
EN

Stack Overflow用户
提问于 2022-05-20 02:48:57
回答 1查看 103关注 0票数 2

我是一个团结一致的自上而下的射手,当敌人看到球员的时候,我试图让敌人开枪。到目前为止,这是我的代码

代码语言:javascript
复制
public class EnemyShooting : MonoBehaviour
{
    public Transform firePoint;
    public GameObject bulletPrefab;
    public float bulletForce = 20f;
    public FieldOfView _fieldofview;
   
        void Start()
    {
        _fieldofview = FindObjectOfType<FieldOfView>();
    }

    // Update is called once per frame
    void Update()
    {
       if(_fieldofview.canSeePlayer)
       {
           Shoot();
       }
    }

    void Shoot()
    {
        GameObject bullet = Instantiate(bulletPrefab, firePoint.position, firePoint.rotation);
        Rigidbody2D rb2d = bullet.GetComponent<Rigidbody2D>();

        rb2d.AddForce(firePoint.up * bulletForce, ForceMode2D.Impulse);
    }
}

然而,当玩家被发现时,它只是发送子弹,因为它没有一个冷却的计时器。我尝试过使用Coroutine和Invoke方法,但它不起作用。有什么想法吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-05-20 06:19:56

下面的代码定义了两次。当前冷却和射击冷却。加上底部,你的问题就会解决。

代码语言:javascript
复制
public float shootCooldown = 5; // 5sec for e.g.
private float currentCooldown;

void Update()
{
    if (currentCooldown > 0) // If shoot not in cooldown
    {
        currentCooldown = shootCooldown; // Set current cooldown time to shootCooldown
        if(_fieldofview.canSeePlayer) Shoot();
    }
    else currentCooldown -= Time.deltaTime; // Reduce cooldown over time
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72313043

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档