Rigidbody Velocity Not Added Properly

I have a problem with adding velocity via JavaScript. This is that an object which is instantiated with the correct rotation and position is only given velocity as if the character were facing straight(level with ground).

I am doing this for a class in video game developement, and this assignment is already late, so it is ‘imperative’ for me to get it finished soon.

My Coding:

function Shoot(){
	if(CanBeShot==true&&Reloading==false){
		//Insantiate a bullet at the tip of the gun
		var firedBullet:Rigidbody=Instantiate(Bullet,gunPos.position,gunPos.rotation);
		//Gun position(gunPos) is set to the tip of the gun, which has no collider
		firedBullet.velocity=transform.TransformDirection(Vector3(0,0,BulletSpeed));
		//Instantiate a flash effect
		Instantiate(MuzzleFlash,gunPos.position,gunPos.rotation);
		Physics.IgnoreCollision(firedBullet.collider,transform.root.collider);
		//Subtract from remaining ammo
		AmmoRemaining--;
		//Irrelevant to the problem:
		CanBeShot=false;
		yield WaitForSeconds(0.5);
		CockingSound.audio.Play();
		yield WaitForSeconds(0.5);
		CanBeShot=true;
	}
}

Code in tutorial:

var instantiatedProjectile:Rigidbody=Instantiate(projectile,transform.position,Vector3(0,-1,0),transform.rotation);
instantiatedProjectile.velocity = transform.TransformDirection(Vector3(0,0,speed));
Physics.IgnoreCollision(instantiatedProjectile.collider,transform.root.collider);

Which direction is +Z on the gun? (the blue arrow, when the translate tool is set to local.) Is this script on the gun, or some other object?

o The line transform.TransformDirection(Vector3(0,0,BulletSpeed)); says to push the bullet along local +Z. Because standard Unity assumes that +Z is always forwards. Lots of people have models that aim +y or -z, … . Several well-known ways to fix that.

This is so common, that transform.forward is a shortcut for tran.transDir(V3(0,0,1));. Both mean “my local forward.” So most people would just write: velocity=transform.forward*bulletSpeed;.

o In transform.transDir... the transform refers to you – the thing with the script on it. So if this script is on the player, it will fire the bullet whichever way the player is facing. It looks like the player “knows about” the gun through gunPos. So use gunPos.transDir... or just gunPos.forward.

Why are you using two different transforms to set the rotation and velocity? Currently there is no relationship in your script between the bullet rotation and the bullet velocity.

You need to either set the velocity based on the firedBullet.transfrom.forward or gunPos.forward. Change line 6 to the following.

firedBullet.velocity = firedBullet.transform.forward * BulletSpeed;