Hey guys, I'm trying to shoot a projectile out of the end of a gun but can't seem to figure out how to get the rotation right when I'm adding force to it. Here's my code:
All it does is shoot upwards. Any ideas?
Answer by hexagonius
Mar 21 at 06:08 AM
you can't just assign Quaternion values to a vector, that's producing garbage. AddForce is in world space. since it's a vector it's easier to use an axis of your gun. assuming your gun has it's z axis in forward direction, the vector you need to apply force to is gun.transform.forward.it's even easier to add an empty game object as your muzzle to where the bullet will spawn. then you can use it's position and forward to launch.
Okay so it's in the correct direction now, but it doesn't add any force. It just instantiates then falls.
public GameObject origin;
public Rigidbody me;
public float bulletSpeed = 10000f;
void Start ()
Vector3 dir = new Vector3 (-origin.transform.rotation.x, 0f, 0f);
me.AddForce (dir * bulletSpeed, ForceMode.Impulse);
Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.
The best place to ask and answer questions about development with Unity.
To help users navigate the site we have posted a site navigation guide.
If you are a new user to Unity Answers, check out our FAQ for more information.
Make sure to check out our Knowledge Base for commonly asked Unity questions.
If you are a moderator, see our Moderator Guidelines page.
We are making improvements to UA, see the list of changes.
Answers and Comments
129 People are following this question.
More problems with arrow shooting
change angle towards direction
Having projectile face mouse position
How can I get a rigid body object to face in the direction my joystick is pointing smoothly?
Script makes plane point in general direction but doesn't point fully... read description please!