- Home /
Writing weapon imprecision
Im creating a top-down 2D shooter game. I want my weapons to not shoot perfectly where I aim, but rather have a public float precision
that goes from 0 to 100. Bullets then have a random side deviation from a minimum angle to a maximum angle based on the precision amount. And the bullet should also rotate accordingly based on shoot angle.
I've been trying to do this for days to almost no avail. I'm very new to Unity and don't really understand how Quaternions and stuff work.
This is my code right now:
float lastFire;
public virtual void Fire()
{
if (Time.time > (lastFire + fireRate))
{
var bullet = Instantiate(bulletPrefab, firePoint.position, firePoint.rotation);
var rb = bullet.GetComponent<Rigidbody2D>();
// Shoot bullet
rb.AddForce(firePoint.right * projectileSpeed, ForceMode2D.Impulse);
lastFire = Time.time;
}
Any ideas?
Answer by Llama_w_2Ls · Aug 08, 2021 at 09:32 AM
You can use Random.insideUnitCircle
to get a random Vector2 direction. This will act as your offset. Multiply that by the precision amount and you should get a random deviation of a certain amount depending on the level of precision you set. For example:
// The lower the precision, the less offset there is
Vector2 offset = Random.insideUnitCircle * Precision;
// Adding the vectors together results in bullet deviation
rb.AddForce(firePoint.right + offset, ...);
Hope that's what you asked for. @iKebab897
engi gaming..
Thanks for the early answer. Following your suggestion, I tried the following code:
Vector3 offset = Random.insideUnitCircle * precision;
rb.AddForce((firePoint.right + offset) * projectileSpeed, ForceMode2D.Impulse);
Unfortunately this causes my character to teleport around for some reason when I shoot no matter the precision amount. @Llama_w_2Ls
engineer ga$$anonymous$$g
you need to add this code to the bullet.....i think