简体   繁体   English

通过实例化 function (Unity C#) 创建猎枪射击

[英]Creating shootgun shoot by instantiate function (Unity C#)

I have problem with instantiate function, if I shoot in different rotation, shape of this shoot changed.我在实例化 function 时遇到问题,如果我以不同的旋转方式拍摄,这个拍摄的形状会改变。 In x axis (streaight from respawn) it looks good (cone), but for example in y axis it looks "flat".在 x 轴(从重生开始)它看起来不错(锥形),但例如在 y 轴上它看起来“平坦”。 Any ideas how to fix it?任何想法如何解决它? Code here:代码在这里:

pellets[i] = Random.rotation;
p = (GameObject)Instantiate(pellet, barrelExit.position, barrelExit.rotation);
Destroy(p, lifeTime);
p.transform.rotation = Quaternion.RotateTowards(p.transform.rotation, pellets[i], spreadAngle);
p.GetComponent<Rigidbody>().AddForce(p.transform.right * pelletFireVelocity);

I don't fully understand your use of RotatateTowards by fixed angle instead of randomizing it feels like it would generate more or less empty cone, however might not understand that.我不完全理解您通过固定角度使用RotatateTowards而不是随机化,感觉它会产生或多或少的空锥,但可能不理解。 I think you should replace spreadAngle with Random.Range(0.f, spreadAngle)我认为你应该用Random.Range(0.f, spreadAngle)替换spreadAngle

Also on the side note I think you should give a try to object pooling.另外,我认为您应该尝试使用 object 池。

Random.rotation is inappropriate here. Random.rotation在这里不合适。 You're not interested in sampling from every possible rotation, only rotations around your camera's forward.您对从每个可能的旋转中采样不感兴趣,只对围绕相机向前的旋转感兴趣。

Instead, use Random.Range to get a value between -spreadAngle and spreadAngle .相反,使用Random.Range获取-spreadAnglespreadAngle之间的值。 Then, you can rotate that much around your camera's forward using Quaternion.AngleAxis and multiplying the result by the barrel's rotation.然后,您可以使用Quaternion.AngleAxis围绕您的相机向前旋转那么多,并将结果乘以桶的旋转。

This is also preferable to using RotateTowards to clamp your spray, as that would result in more pellets being fired around the edges of the spray.这也比使用RotateTowards夹住喷雾更可取,因为这会导致在喷雾边缘周围发射更多的颗粒。 Using Random.Range and Quaternion.AngleAxis will result in a uniform distribution.:使用Random.RangeQuaternion.AngleAxis将导致均匀分布。:

Camera mainCam; // cache result of Camera.main here for performance

Start()
{
...
    mainCam = Camera.main;
...
}

...

float randomAngle = Random.Range(-spreadAngle, spreadAngle);
pellets[i] = Quaternion.AngleAxis(randomAngle, mainCam.forward) * barrelExit.rotation;
p = (GameObject)Instantiate(pellet, barrelExit.position, barrelExit.rotation);
Destroy(p, lifeTime);
p.transform.rotation = pellets[i]; 
p.GetComponent<Rigidbody>().AddForce(p.transform.right * pelletFireVelocity);

By the way, you should consider pooling these pellets, rather than creating and destroying many of them at a time.顺便说一句,您应该考虑将这些弹丸集中起来,而不是一次创建和销毁其中的许多弹丸。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM