# Shoot projectile same direction weapon faces

I want to be able to shoot a projectile from a weapon mounted on a vehicle. Right now I am able to do it but only in front of the vehicle. I managed to rotate the weapon to the direction the mouse is facing, but the projectile still goes straight.

I believe that the issue is that the velocity of the projectile is the problem here. Right now I have it like this:

if (playerShooting || NPCShooting)
{
if ((timer >= cooldown) && hasEnergyAvailable())
{
timer = 0;
GameObject intantiatedProjectileContainer = Instantiate(projectileContainer, transform.position, transform.rotation) as GameObject;
Rigidbody instantiatedProjectile = intantiatedProjectileContainer.GetComponentInChildren<Rigidbody>();

if (playerController)
{
instantiatedProjectile.velocity = transform.TransformDirection(new Vector3(0, 0, speed + transform.root.GetComponent<PlayerController>().getZSpeed()));
}
}
}


Where speed is the projectile speed and it's added to the vehicle speed.

I thought that this should shoot forward but with the parent rotation, can someone tell me what I'm missing here? Thanks!

• Is the projectile always going straight (from the vehicles point of view) so for example, always going north if the vehicle is facing north? If the projectile you fire is actually moving, I don't think it's the velocity that is the problem but rather the direction in which you are shooting it? – D.Kallan Oct 7 '19 at 12:46
• You could get the direction the gun is facing with gun.transform.forward and use that, but I am not able to help you more than that if you do not provide more code :D – Milos Romanic Oct 7 '19 at 12:46
• @D.Kallan Yes, that's what it does. When The vehicle (spaceship in this casu is facing up, the projectile goes up, when it's facing right the projectile goes right. Always goes forward from the vehicle position and rotation, instead of the Weapon rotation. Sorry, Milos, I've added a bit more of code. – Hector Oct 7 '19 at 15:41
• Ok, I've found the issue. It turns out I was doing this later in the code: instantiatedProjectile.velocity = transform.root.transform.TransformDirection(new Vector3(0, 0, speed + transform.root.GetComponent<PlayerController>().getZSpeed())); This was giving the projectile the speed direction on the ship (root). Sorry, my bad! – Hector Oct 7 '19 at 16:32

Transform weapon;
Transform weaponMuzzle;

float ForceAmount = 10.0f;// or any value you want

private void Shoot()
{
GameObject bullet = Instantiate(BulletPrefab, weaponMuzzle.position, Quaternion.Identity);

You need to AddForce to a bullet in the same direction of weapon.Forward() and instantiate the bullet on the location of your weapons muzzle. You'll have to make an empty gameObject and put it on the position of the weapon's head and and set it to weaponMuzzle in the inspector.