- Home /
Any ideas how to fix unintentional and unwanted bullet spread?
Hi, unity newbie here. I've got a problem where the bullet from my gun angle themselves up or down when moving (upwards when moving backwards and downwards when moving forwards). It only happens every seven or eight bullets though which is the part that confuses me the most. I'll post a video of the problem here: https://youtu.be/HdeU2iorKNs
Here is the script for firing the gun
public class PlayerShootPistol : MonoBehaviour
{
public Camera Cam;
public GameObject Projectile;
public Transform FirePoint;
public float ProjectileSpeed = 30;
public float FireRate = 4;
private Vector3 Destination;
private float TimetoFire;
Animator anim;
void Start()
{
anim = GetComponentInChildren<Animator>();
}
void Update()
{
if (Input.GetButton("Fire1") && Time.time >= TimetoFire)
{
TimetoFire = Time.time + 1 / FireRate;
ShootProjectile();
anim.SetBool("Fire", true);
StartCoroutine(Stopanim());
}
void ShootProjectile()
{
Ray ray = Cam.ViewportPointToRay(new Vector3(0.5f, 0.5f, 0));
RaycastHit hit;
Vector3 Destination;
if (Physics.Raycast(ray, out hit) && gameObject.tag != "Projectile")
Destination = hit.point;
else
Destination = ray.GetPoint(75);
Vector3 directiontithoutspread = Destination - FirePoint.position;
var projectileObj = Instantiate(Projectile, FirePoint.position, Quaternion.identity) as GameObject;
projectileObj.transform.forward = directiontithoutspread.normalized;
projectileObj.GetComponent<Rigidbody>().velocity = (Destination - FirePoint.position).normalized * ProjectileSpeed;
}
IEnumerator Stopanim()
{
yield return new WaitForSeconds(0.3f);
anim.SetBool("Fire", false);
}
}
}
and here is the bullet collision detection script in case that helps:
public class PistolBulletControls : MonoBehaviour
{
private bool Collided;
private Rigidbody rb;
public GameObject Ricochet;
void Start()
{
rb = GetComponent<Rigidbody>();
StartCoroutine(TimedOut());
}
void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.tag != "Projectile" && !Collided)
{
Collided = true;
GameObject Effect = Instantiate(Ricochet, transform.position, transform.rotation, rb.transform) as GameObject;
Vector3 temp = rb.transform.position;
Effect.transform.parent = null;
Effect.transform.position = temp;
Destroy(gameObject);
}
}
IEnumerator TimedOut()
{
yield return new WaitForSeconds(5f);
Destroy(gameObject);
}
}
Sorry if I have put anything weird here since it's my first post on this forum, any help would be greatly appreciated. Thank you :)
Answer by xxmariofer · Mar 25, 2021 at 03:44 PM
Hello, I have watched your video really slowdown, and it looks that behaviour only appears when animation of the shoot is delayed or played before shoot, so probably "FirePoint" is the gun and changing the guns position in the animation changes the bullet direction