【问题标题】:Unity CollisionEnter2D being called multiple times every collision?每次碰撞都会多次调用 Unity ONCollisionEnter2D?
【发布时间】:2021-02-03 03:40:25
【问题描述】:

所以我目前正在开发一个统一的 Boss 格斗游戏,其中激光会在玩家第一次射击 Boss 后的特定时间间隔(比如 10 秒)内从上方发射。发生的情况是,当 Boss 被多次击中时,它会产生多个不同的激光弹。我正在使用 InvokeRepeating 来执行此操作,我认为这不是最有效的方法,因此如果有人对此有任何想法,将不胜感激。这是代码(可能很乱,我对游戏开发很陌生)

using UnityEngine;

public class startboss : MonoBehaviour
{
    public bool fight = false;

    public Sprite awake;

    public bool player_dead = false;

    public float spawntime = 10f;
    public float spawndelay = 10f;
    public bool spawn = false;



    // Start is called before the first frame update

    void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.collider.tag == "Bullet")
        {
           
            spawn = true;
            fight = true;
            if (fight == true)
            {
                gameObject.GetComponent<SpriteRenderer>().sprite = awake;
                if (spawn == true)
                {
                    InvokeRepeating("Shoot", spawntime, spawndelay);
                }
            }
        }
    }

                public GameObject laserprefab;
    public Transform laserpoint;
    public Transform laserpoint2;
    public float seconds = 10;
    public Rigidbody2D rblaser;

    // Start is called before the first frame update

    // Update is called once per frame

    // Start is called before the first frame update

    void Shoot()
    {
        Instantiate(laserprefab, laserpoint.position, laserpoint.rotation);
        Instantiate(laserprefab, laserpoint2.position, laserpoint2.rotation);
    }
}

【问题讨论】:

  • 对不起,如果这不符合此处常规帖子的公式,这是我的第一个,非常抱歉,如果我没有遵守一些礼仪。
  • 我知道你是“新人”,但是将bool 变量设置为true,然后立即检查if(x == true){...} 有点不必要:-D 它不会奇迹般地从一行改变状态到下一个;)
  • 您的问题到底是什么?正在发生什么与您的预期?您能否详细说明,或者您的问题是关于 InvokeRepeating 和性能?
  • @Tomek 感谢您的帮助。基本上激光炮弹是每 10 秒发射一次,但是当真正的敌人被射击时,它会复制激光,例如当我射击老板时,它每 10 秒每个爆破器产生 1 个激光,但如果我射击老板 3更多次,它每 10 秒每 1 个冲击波产生 3 个激光。抱歉,如果这令人困惑。
  • 在我看来,您在每次碰撞时从您的冲击波中重新订阅事件处理程序?您只需要订阅 EventHandler OnCollisionEnter2D 例如当您加载/初始化场景/boss 等时。

标签: c# unity3d game-development


【解决方案1】:

看起来你正在创建一个新的 InvokeRepeating("Shoot", spawntime, spawndelay);每次射击老板时,它都会开始另一个重复射击的实例。因此,如果您向老板射击 3 次,您将进行 3 次重复射击。

您可以将射击移到碰撞之外并使用计时器倒计时而不是 InvokeRepeating 以获得更多控制权。如果需要,您可以将计时器设置为 0 或在碰撞时停止/启动计时器。

    //Declair timer and time
    float fireTimer = 0.0f;
    float fireTime = spawnTime;

    void Update(){ 
         
         //Add time to the timer.
         fireTimer += Time.deltaTime;
         
         //If timer = time then fire and reset the timer.
         if(fireTimer == fireTime){
              Shoot();
              fireTimer = 0.0f;
         }
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-30
    • 1970-01-01
    相关资源
    最近更新 更多