Shooting a bullet with the same rotation as the gameobject that spawns it. 2D

Greetings,

I’ve created a little 2D tank and the barrel of the tank follows the player always pointing at a 45 degree angle. At the end of that barrel I have put an empty game object which spawns the bullets, however the bullet doesn’t seems to get the rotation of the gameobject, it simply fires up.

This is my barrel game object script.

  public class MultiShoot : MonoBehaviour {
    
        public GameObject bullet;
    
        public float startShotTime = 0.5f;
        public float delayShotTime = 0.5f;
        // Use this for initialization
        void Start()
        {
            InvokeRepeating("ShootMissle", startShotTime, delayShotTime);
        }
    
        // Update is called once per frame
        void Update()
        {
    
        }
    
        void ShootMissle()
        {
            Instantiate(bullet, new Vector2(gameObject.transform.position.x, gameObject.transform.position.y + 0.80f), Quaternion.identity);
        }
    }

This is the bullet script

public class MultiBullet : MonoBehaviour {

    float speed = 5f;
    private Rigidbody2D rb;

	// Use this for initialization
	void Start () {
        rb = GetComponent<Rigidbody2D>();
        
	}
	
	// Update is called once per frame
	void Update () {
        rb.velocity = transform.up * speed;
	}

    private void OnTriggerEnter2D(Collider2D collision)
    {
        //Add explosion Effect
        if (collision.gameObject.tag == "Player")
        {
            // Add game over screen here
            Debug.Log("Player Killed");
            Destroy(gameObject);
        }
        Debug.Log("BOOM");
        Destroy(gameObject);
    }
}

I do want the bullet to go in a straight line but in proportion to the angle of the game object.

Look at this line:

Instantiate(bullet, new Vector2(gameObject.transform.position.x, gameObject.transform.position.y + 0.80f), Quaternion.identity);

Especially “Quaternion.identity”; Quaternions are the way to define rotations in Unity. The constant “Quaternion.identity” describes a rotation of zero into all directions, the initial value of every Quaternion so to speak. The reason why your bullets are all flying into the same direction is that they are all spawned with the same (zero) rotation.


To solve this you could simply copy your gameObjects rotation (~quaternion) into the freshly instantiated bullet:

Instantiate(bullet, new Vector2(gameObject.transform.position.x, gameObject.transform.position.y + 0.80f), gameObject.transform.rotation);

Btw I think the bullet should rather move forward than up but that depends