【问题标题】:Shooting with a shotgun 2D Top-down Shooter使用霰弹枪射击 2D 自上而下的射击游戏
【发布时间】:2020-12-29 15:57:35
【问题描述】:

我正在尝试用霰弹枪射击,我已经用一颗子弹射击了。代码:

            Vector2 shootingDirection = new Vector2(joystick.Horizontal, joystick.Vertical);
            shootingDirection.Normalize();           
            if (shootingDirection != new Vector2(0, 0))
            {
                if(isShotGun) ShotGunShoot(shootingDirection);
                GameObject bullet = Instantiate(bulletPrefab, crossHair.transform.position, Quaternion.identity);
                bullet.transform.Rotate(0.0f, 0.0f, Mathf.Atan2(shootingDirection.y, shootingDirection.x) * Mathf.Rad2Deg);
                bullet.GetComponent<Rigidbody2D>().AddForce(shootingDirection * 10f, ForceMode2D.Impulse);
            }

        }

但我只是想创建另外两个与主子弹略有偏差的子弹,所以它看起来像一个分数,但它不能正常工作。代码:

    private void ShotGunShoot(Vector2 dir)
    {
        GameObject shotGun = Instantiate(bulletPrefab, crossHair.transform.position, Quaternion.identity);
        shotGun.transform.Rotate(0.0f, 0.0f, Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg - 30f);
        shotGun.GetComponent<Rigidbody2D>().AddForce((dir + new Vector2(-.3f, 0f)) * 10f, ForceMode2D.Impulse);
   
        shotGun = Instantiate(bulletPrefab, crossHair.transform.position, Quaternion.identity);
        shotGun.transform.Rotate(0.0f, 0.0f, Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg + 30f);
        shotGun.GetComponent<Rigidbody2D>().AddForce((dir+ new Vector2(.3f, 0f)) * 10f, ForceMode2D.Impulse);
    }

应该如此

现在来了

感谢您的帮助!

【问题讨论】:

    标签: c# unity3d 2d


    【解决方案1】:

    用于旋转。您可以简单地设置方向(从您的图像中我可以看到您的子弹必须飞向其正确的矢量),例如

    shotgun.transform.right = dir;
    shotgun.transform.Rotate(0, 0, 30);    
    

    对于附加力:这使用世界空间方向。

    你总是在方向上通过并在世界空间中添加额外的偏移量。因此,无论您朝哪个方向射击,额外的偏移始终沿 X 轴方向进行。

    而是通过使用局部力Rigidbody.AddRelativeForce来考虑方向

    shotGun.GetComponent<Rigidbody2D>().AddForceRelative((shotgun.transform.right + new Vector2(0f, 0.3f)).normalized * 10f, ForceMode2D.Impulse);
    

    这现在使用子弹向右的方向,并沿其本地 Y 轴另外使用0.3 的偏移量。


    顺便说一句:如果你给你的预制件正确的类型

    public Rigidbody bulletPrefab;
    

    您可以跳过GetComponent&lt;Rigidbody&gt; 电话。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多