- Home /
Shooting problem - bullet shoots diagonally when facing forward
I'm trying to create a simple shooting script and it's been succesfull, except when I'm facing forward he shoots diagonally to the right.It is a third person action game. Can someone help solve this? Below is my script.
var bulletPrefab:Transform; var shootForce = 1000;
function Update () { if(Input.GetButtonDown("Shoot")) { var instanceBullet = Instantiate(bulletPrefab, transform.position, Quaternion.identity); instanceBullet.rigidbody.AddForce(transform.forward * shootForce); } }
When you say, "when I'm facing forward" - do you mean the camera or the character? Is it a FPS?
I do believe that "Quaternion.identity" alligns after the the "World axes" I am not sure though, and "transform.rotation" alligns after the transforms x,y,z axes. Try replaceing "Quaternion.identity" with "transform.rotation" I am not a 100% sure though.
Yes. OrangeLightning is right. You have to use transform.rotation if you want it to face the gameObjects foward axis rather than the world axis.
Answer by AVividLight · Oct 16, 2010 at 02:39 AM
Try attaching the script to the main camera... That might help...
Answer by Cyb3rManiak · May 11, 2011 at 10:25 AM
Vector3.forward will always return a Vector3 of (0,0,1). This is the forward direction relative to the world coordinate system. What you need is the relative forward of the bullet. Try this...
var instanceBullet = Instantiate(bulletPrefab, transform.position, transform.rotation);
var v3RelativeForward: Vector3 = instanceBullet.transform.TransformDirection(Vector3.forward);
instanceBullet.rigidbody.AddForce(v3RelativeForward * shootForce)AddForce(v3RelativeForward * shootForce);
EDIT: When going over OrangeLightning's comment again, It just stuck me that you're also instantiating the bullet using Quaternion.identity, and just like he said, this means that the bullet's forward will also always be (0,0,1) all the time. I've edited your Instantiate() to use transform.rotation when instantiating the bullet. This will create the bullet aligned with whatever "transform" is pointing to. So if this is the character - the bullet will face to the character's forward direction as well, and the TransformDirection() will make sure that the force you add to it will be in that direction.
Your answer
Follow this Question
Related Questions
Enemy health. Need to take damage from two different bullet prefabs 1 Answer
is there a way to make a script prefab? 1 Answer
Tagging object while instating not working. 3 Answers
Disable & Re-enable Script 1 Answer
When flipping player, instantiated objects spawn on different spot. 2D shooting 0 Answers