- Home /
Shooting Script -- Bullet won't fire in correct direction First Person View 3D
Hello again, it seems like just the other day when I was here last...oh wait it was lol. Sorry for the humor, I've gotten quite a bit done on my game today since I had 9 hours to work on it today. Hooray for days off!
So, I have a projectile, it fires, it destroys itself if it hits the environment (haven't gotten to the enemy yet so not sure how that will go) but it only fires in one direction for some reason. Regardless of where the player is facing. You'll see "Vector3.right" in the code that's because if I put ".forward" it fires to the right of the player (even after adjusting the pivot points. The stuff that's coded it out is the first and second attempt at this. The third is where I'm at now, I've been working on this and reading several answers and youtube videos as you'll see or maybe recognize from the lines of code.
public GameObject bEmitter;
public GameObject Bullet;
public float bForce;
public GameObject player;
public void OnMouseDown()
{
/*GameObject tbHandler = Instantiate(Bullet, bEmitter.transform.position, Quaternion.identity);
tbHandler.transform.Rotate(new Vector3(0,1,0) * Time.deltaTime * 90, Space.Self);
Rigidbody tRB;
tRB = tbHandler.GetComponent<Rigidbody>();
// tRB.transform.Rotate (Vector3.forward * Time.deltaTime * 1, Space.World);
tRB.AddForce(Vector3.right * bForce);
Destroy(tbHandler, 3.0f);*/
GameObject instBullet = Instantiate(Bullet, bEmitter.transform.position, Quaternion.identity) as GameObject;
Rigidbody instBulletRigidbody = instBullet.GetComponent<Rigidbody>();
instBulletRigidbody.AddForce(Vector3.right * bForce);
}
Answer by logicandchaos · Jan 23, 2020 at 01:16 AM
Well the orientation depends on how the object is created, but I think your issue is you are using:
Vector3.right
when you should be using:
player.transform.position.forward
This is because when you want to get the orientation of the player object, calling it from Vector3 gets a static value for right/forward rather than from the player.
Thanks for both of your help! Unfortunately it would only let me accept one but you both helped out tremendously.
Answer by Fariborzzn · Jan 23, 2020 at 01:13 AM
nice to hear that man congratulations! Vector3.right is in world space use transform.forward because it's in local space and the bullet will fire in the proper direction. transform.forward is a vector facing the local-space forward, meaning it is a vector that faces to the forward of your object. This vector will be different depending on which way your object with the transform is facing.
Hey there was no answer when I started typing $$anonymous$$e!! :P
Your answer
Follow this Question
Related Questions
Don't allow the player to shoot while projectile is travelling 1 Answer
Multiple Cars not working 1 Answer
Bullet ricochet 0 Answers
Distribute terrain in zones 3 Answers