0
\$\begingroup\$

So I'm trying to make a simple weapon where I just instantiate a bullet at the Shoot Point's gameobject position. For some reason when I press down on my mouse the bullet just flies up. Any ideas on why this could happen?

Vector3 velocity = bullet.transform.forward * 1000 GameObject bulletGameObject = Instantiate(bullet, shootPoint.transform.position, Quaternion.identity);
Rigidbody bulletBody = bullet.GetComponent<Rigidbody>();
bulletBody.velocity = velocity;
Destroy(bulletGameObject, 4f);
\$\endgroup\$
1
\$\begingroup\$

Here bullet is referring to the bullet prefab you're copying to make your new instance to fire. (I like naming my prefab variables things like bulletPrefab to make this extra-obvious)

So you're assigning its velocity based on the prefab's forward direction, not on the direction the gun is pointing. If you happened to save your prefab pointing straight up, then that's where every bullet will go, regardless of the gun's facing direction.

You probably want something more like:

Vector3 velocity = shootPoint.transform.forward * firingSpeed;

Assuming your shootPoint transform is oriented with its local z+ axis pointing in the direction you want to shoot.

The other thing you'll want to watch for is if both the player/gun and the bullet have colliders, and they overlap when the bullet is spawned at shootPoint. The physics engine might see this and try to apply an impulse to separate the overlapping colliders, knocking your bullets off-course. To fix this, you can...

  • Use physics layers so the player does not interact with their own bullet colliders

  • Use IgnoreCollision to selectively ignore collisions between the gun and its bullets, as you fire each bullet

  • Make the bullet collider a trigger so it doesn't participate in collision resolution (but can still detect collisions with OnTriggerEnter etc)

\$\endgroup\$
0
\$\begingroup\$

Check the local z-axis of your prefab. When you assign velocity value to a gameobject it will move in local Vector3.forward (constant value) direction.
The best solution is to create empty object and assign your model as child, rotate child to line up with parent's z-axis.
Make that new object (parent of you bullet's model) as new prefab and instantiate it. Additionally to be sure that bullet goes the same direction as the gun is pointing instead of Quaternion.identity use transform.rotation.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.