Rigidbody bullet force not being applied
Sorry in advance, because I know this has been asked before, but I can not figure out the issue for the life of me. I have followed the unity scripting tutorial for instantiate as best I can and it just isn't working.
I am just trying to fire a cannonball from the end of a cylinder.
public class ShootTurret : MonoBehaviour { public GameObject cannonballPrefab; public Transform turretEnd; public float fireRate = 1.0F; private float nextFire = 0.0F;
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.Space) && Time.time > nextFire)
{
nextFire = Time.time + fireRate;
Rigidbody cannonballInstance;
cannonballInstance = Instantiate(cannonballPrefab, turretEnd.position, turretEnd.rotation) as Rigidbody;
cannonballInstance.AddForce(new Vector3(0f,0f,-100000f), ForceMode.Impulse);
}
}
I am trying to fire it in the -z axis even though that is normally back. Does anyone see why my bullets are just dropping straight down?
Things you can check: 1- Check if ball is colliding with the turret when it is instantiated. 2- You are applying a static global force to the ball. you need to apply force in turrets forward direction (might be a different axis if you are using a *.fbx file) :
cannonballInstance.AddForce(100000f * turretEnd.forward, Force$$anonymous$$ode.Impulse);
Hope that helps.
I have an empty game object in front of the turret and that is what the turretEnd variable is being set to so there shouldn't be any collisions upon instantiation. I have rotated the empty gameobject so the +z points in the direction I want the bullet to go in. Here is a picture of the setup. http://imgur.com/dd7vXak. The ball is still dropping directly in front of the cannon upon instantiation. I am also getting an "Object Reference not set to an instance of an object" error on the cannonballInstance.AddForce line, but I don't see why.
Solution: The cannonballInstance is a GameObject not just a rigidbody. The way to fix this was to instantiate as GameObject, get the rigidbody component from the GameObject, then apply the force to the rigidbody. Here is a pastebin. http://pastebin.com/0NUjg7TE
Your answer
Follow this Question
Related Questions
Creating a rope in 3D for grappling 0 Answers
How to make rigidbody not effect movement while still using it for collisions? 0 Answers
Instant rotation bug when rotating clockwise 0 Answers
Addforce function not adding force in a 2D game and cannot figure out why 2 Answers
Script removing rigidbody component, NOT game object 1 Answer