Bullets spawn behind the craft

Hi there!

So, I’ve this problem, where I’m trying to fire a bullet from the same location as the player fighter craft. However, the bullet spawns from behind the fighter, and after setting the Colliders on both objects, they collide and eventually, the craft ends up being destroyed by its own bullets.

Here’s the function used to fire the bullets (a Coroutine that fires a burst of five bullets):

IEnumerator gun_fire()
    {
        isFiring = true;
        GunSource.Play();
        for (int x = 0; x < 5; x++)
        {
            Instantiate(bulletPrefab, transform.position, transform.rotation);
            bulletCount -= 1;
            yield return new WaitForSeconds(bulletCool);
        }

        isFiring = false;
    }

So, is there any way of preventing this? (it seems that adding some Vector3 coordinates to transform.position doesn’t work since they still spawn out of place…

Thanks for any help.

João Borrego

sure, this is a basic of shooting ! even Hideo Kojima has to do it.

one simple solution is to learn about the neat LAYERS system Unity3D has in their physics. it’s great.

it is explained fully in the Unity docs. your bullet layer should only interact with your enemy (or whatever) layer, and >>> NO OTHER <<< layers.

your ‘hero’ (or whatever) layer will be a different layer, so the bullets will be harmless to the hero.

it’s the best and easiest solution.

Like Fattie said, you need to make sure that the bullets do not effect the player, so use a layer called player that the player uses and have the bullets not effect that, but every other layer. Do this like:

if (object.layer/*or object.name or object.tag*/ == "Player") return false; //or 0 etc