Instantiated Object sometimes spawning with a vertical offset

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.
8411397--1111566--upload_2022-9-2_17-16-40.png

First thing I notice is you are doing physics in Update().

Physics should be done in FixedUpdate()

What is likely happening is you are getting two (2) Update() calls without an intervening FixedUpdate() call, which is when the physics move, so your two bullets appear at the same spot and bump against each other.

Two good discussions on Update() vs FixedUpdate() timing:

But at the end of the day, do you even want bullets hitting each other at all? I like to put my bullets all on a special layer and then tell the physics engine “this layer never collides with itself.”

1 Like

Hey Kurt-Dekker,

Thank you for the response and article links! I implemented the special bullet layer and converted the Update to a FixedUpdate as you suggested and the problem seems to be resolved.

Thanks a bunch!

1 Like