2

Where the bullet spawns when I shoot

Hi, for some reasons my bullet won't spawn where I tell it to. The spawn point is at the end of my barrel, I take its transform position and rotation when I instantiate the bullet, but it spawns higher than the gun (way higher). Here's the code that I have:

    Animation anim;   // Gun animation when shooting
AudioSource gunSound; // Gun sound when firing
public Rigidbody bullet; // I get the rigidbody of the bullet that will be spawned
public Transform spawnPoint; // The position of where it is supposed to spawn


void Start()
{
    anim = GetComponent<Animation>();
    gunSound = GetComponent<AudioSource>();
}

void Update()
{
    if (Input.GetButtonDown("Fire1"))  // If the left mouse button is clicked
    {
        Rigidbody bulletInstance;
        bulletInstance = Instantiate(bullet, spawnPoint.position, spawnPoint.rotation) as Rigidbody; // This is where I don't understand why?!?!
        bulletInstance.AddForce(spawnPoint.forward * 1000f);

        gunSound.Play();
        //anim.Play("GunShot4");
    }
}

Help :)

Manu
  • 65
  • 1
  • 2
  • 8
  • So the bullet isn't appearing at the position of the given transform? Are there any scripts attached to it that might be teleporting it around? – HalpPlz May 22 '16 at 15:41
  • Besides the character controller script which is on the parent of the parent and that does not affect anything with the gun, no there's nothing. And yes, instead of appearing at the spawnpoint (empty gameobject) transform, it spawns higher just like in the picture linked on top of the description (first line) – Manu May 22 '16 at 17:56
  • Ah, it may be that "public Rigidbody bullet" needs to be "public GameObject bullet" and you need to instantiate it "as GameObject" instead of "as Rigidbody". You can reference the rigidbody with gameObject.GetComponent(); – HalpPlz May 22 '16 at 19:03

1 Answers1

1

It can happen, that the origin of the bullet is not at the middle of the model.

  • Thanks, I changed the bullet model with a sphere and it works.. I dragged and dropped my bullet prefab but it seemed like the point of origin was at the right place, but it's fixed :) thanks again! – Manu May 22 '16 at 18:11