I am working on 3D Shooter game for a class project. Currently, I am spawning a “bullet” (sphere) from a point at the end of the gun. This works fine, however when I am continuously firing the gun, an offset of about 0.2 units up in the Y direction will sometimes randomly be applied, even with no mouse movement, causing the bullet to spawn slightly higher than where it should. I also noticed when the game first starts the bullet will spawn much higher than it should and usually corrects itself after a few seconds of gameplay.
Here is my code for spawning the bullets:
using UnityEngine;
public class Gun : MonoBehaviour
{
public GameObject barrel;
public GameObject bullet;
private float nextShot;
void Update()
{
if (Input.GetButton("Fire1") && Time.time > nextShot)
{
nextShot = Time.time + Player.Instance.FireRate;
GameObject newBullet = Instantiate(bullet, barrel.transform.position, Quaternion.identity);
Debug.Log("spawned bullet at " + newBullet.transform.position);
Debug.Log("barrel position is " + barrel.transform.position);
Rigidbody bulletPhys = newBullet.GetComponent<Rigidbody>();
bulletPhys.AddRelativeForce(-barrel.transform.forward * 25, ForceMode.Impulse);
}
}
}
Both Debug statements print the same exact value every time, so there seems to be no discrepancy between the end of the barrel and where the bullet spawns. There are also no errors in the console.
I have also attached my Player gameobject hierarchy if it helps. The bullets are spawned from the Barrel gameobject.