- Home /
Why my code fires bullet at random positions?
I see that the bullets are being fired at random positions and not actually in forward direction of the camera. What's wrong here and how should I fix it? I am using pooling and each time the bullet is enabled this code is run:
private void OnEnable()
{
transform.position = Camera.main.transform.position;
transform.rotation =Quaternion.identity;
GetComponent<Rigidbody>().AddForce((Camera.main.transform.forward + new Vector3(0, 0, 0)) * 5000);
Invoke("Destroy", 1.5f);
}
I have also changed it to the below code but even the second one doesn't work.
private void OnEnable()
{
Rigidbody rb = GetComponent<Rigidbody>();
rb.position = Camera.main.transform.position;
rb.rotation = Quaternion.identity;
rb.AddForce((Camera.main.transform.forward + new Vector3(0, 0, 0)) * 5000);
Invoke("Destroy", 1.5f);
}
Answer by AlwaysSunny · Feb 27, 2017 at 03:01 PM
I don't immediately see an issue with the code. Adding a zeroed vector3 does nothing (5000 times 0 is 0), but I'm guessing you know that.
If the camera (where you're spawning your projectiles) has a collider nearby (such as the collider on the player character) it is most likely colliding with your projectiles the instant they are created. There are many valid ways to prevent this behavior - consider reading the manual entry on Physics to get some ideas.
Just a heads up - it's rare that you want a bullet to be a rigidbody. A rock? Sure. A fireball? Possibly. A bullet fired with a force of 5000? It's probably going to travel too quickly to participate accurately in the physics simulation. Definitely look into raycast-based bullet logic if you're after tiny, high-velocity projectiles.
Answer by mmciver · Feb 27, 2017 at 04:02 PM
The 2nd one doesn't work because you should be setting the position of the transform (as the first), not the rigidbody.
I wonder what camera is your main camera. Have you verified that? If you have a different camera around, check to make sure that it isn't flagged as the main camera, thus getting a direction you are not expecting.