【问题标题】:Fire bullets at an interval continuously while the fire button is held down按住开火按钮时,以一定间隔连续发射子弹
【发布时间】:2021-05-23 10:31:03
【问题描述】:

在 C# Unity3D 中,我试图让子弹以bulletTime 的间隔发射。单发目前工作得非常好,但是当我按住开火按钮时,只创建并射击了 1 颗子弹,然后什么都没有发生。

// Left mouse button HELD down.
else if (fireAgain && Input.GetMouseButton(0)) 
{   
    StartCoroutine("LoopNShoot");
    fireAgain = false;
}
else if (timerH < bulletTime)
{
    timerH += Time.deltaTime;

    if(timerH >= bulletTime)
    {
        fireAgain = true;
        timerH = 0;
    }
}   
    

IEnumerator LoopNShoot()
{
    pivot.transform.Rotate(triggerAngle,0,0);
        
        GameObject bullet = ObjectPooler.SharedInstance.GetPooledObject(); 
        if (bullet != null) {
                bullet.transform.position = SSpawn.transform.position;
                bullet.transform.rotation = SSpawn.transform.rotation;
                bullet.SetActive(true);
         }

    yield return new WaitForSeconds(.1f);
            pivot.transform.rotation = Quaternion.Slerp(transform.rotation, originalRotationValue, Time.deltaTime * rotationResetSpeed); 
    
}

我想我需要将所有的 if 语句和计时器放在协程中吗?但这似乎也无济于事......

请忽略枢轴和旋转,它适用于某些动画,唯一不起作用的是在按住开火按钮时以设定的间隔连续射击子弹。

【问题讨论】:

  • 你应该重新格式化你的代码。
  • @marsh-wiggle 应该重新格式化什么?

标签: c# unity3d coroutine


【解决方案1】:

您应该删除这些 else 并执行此操作。

private void Update()
{
    if (fireAgain && Input.GetMouseButton(0)) 
    {   
        StartCoroutine("LoopNShoot");
        fireAgain = false;
        timerH = 0;
    }

    if (timerH < bulletTime)
    {
        timerH += Time.deltaTime;

        if(timerH >= bulletTime)
        {
            fireAgain = true;
        }
    }   
}

您也可以重新安排它以更清楚地了解它的工作原理:

private void Update()
{
    if(!fireAgain)
    {
        timerH += Time.deltaTime;

        if (timerH >= bulletTime)
        {
            fireAgain = true;
        }         
    }
    else
    {
        if(Input.GetMouseButton(0)) 
        {   
            StartCoroutine("LoopNShoot");
            fireAgain = false;
            timerH = 0;
        }
    }       
}

我实际上以为你已经选择了我向你展示的Invoke 方法here

【讨论】:

  • 是的,我现在正在使用 Invoke,非常酷,但我现在被禁止问更多问题 2 天,所以我不能问为什么我的子弹会提前消失。我使用 OnEnable { > Invoke >DestroyBullet , 5 seconds > gameObject.setActive(false) 所以我想让我的子弹在被射击 5 秒后重置并禁用它们自己。它工作正常,但过了一段时间后,一些子弹会在 5 秒结束之前消失,有些只会持续 1 秒,其他的会持续 5 秒,我有 50 个池对象,只射击了 10 个,所以不是我的池在运行出去。
猜你喜欢
  • 2021-07-18
  • 2019-10-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-06
  • 1970-01-01
  • 2016-03-18
相关资源
最近更新 更多