点之间的随机射击位置(从矢量方向和点开始设置)

时间:2018-05-07 21:33:43

标签: c# unity3d 2d

这是我的第一个问题。
对于我的2D射击游戏中的武器代码,我有两个点(基地和发射器)和一个点(C)之间形成的方向矢量,我把步枪瞄准。

我正在尝试实现一种精确的锥形(两点之间的随机镜头,与C点等距,形成与方向矢量垂直的线)

这是方案:

enter image description here

点L和R的位置尚未定义。 我需要帮助:

  • 定义L和R的位置给定距离矢量(Emitter-Base)和C
  • L和R之间的随机点

我尝试没有成功,所以我要求帮助。 提前致谢。 此致

1 个答案:

答案 0 :(得分:0)

我将给你一些简化的例子。这个假设当你发射子弹时,它将在预定义的锥形内部随机进入。

Public GameObject bulletPrefab;
Public GameObject pointOnGunBulletShootsFrom; // In your image this would be the emitter
private float halfAngleofCone = 30f; // In your image this would be the distance between C and L.
private float bulletSpeedModifier = 100f; // If you have another way of propelling your bullets you can remove this and the addforce section.

private void FireBulletInsideCone()
{
   GameObject bullet = Instantiate(bulletPrefab, pointOnGunBulletShootsFrom.transform.position, pointOnGunBulletShootsFrom.transform.rotation);
   float angleToAdjustBy = Random.Range(0,halfAngleofCone);
   bullet.transform.Rotate(Vector3.up * angleToAdjustBy );
   bullet.rigidbody.AddForce(transform.forward * bulletSpeedModifier);
}

void Update()
{
    if(Input.GetKeyDown(KeyCode.Space))
    {
       FireBulletInsideCone();
    }
}

以下是您可能需要设置枪的图片。为了保持清洁,您可能需要在枪前面添加一个面向前方的游戏对象,以充当GameObject pointOnGunBulletShootsFrom 脚本使用的。在您的情况下,您的发射器可能已经考虑到了这一点。 enter image description here