- Home /
How do you add force to a clone after you spawn it?
I want to make a gun, so far it spawns bullets but those bullets travel forward. this is my code
void FixedUpdate() { bulletSpawnPoint = GameObject.Find("BulletSpawnPoint").transform.position; if (Input.GetKey (KeyCode.Z)) { Instantiate (bullet); bullet.transform.position = bulletSpawnPoint; bullet.GetComponent<Rigidbody> ().AddForce (0, 300, 0); }
What should I do?
@nathanthesnooper is right. But you should also just store a reference to your bulletSpawnPoint. GameObject.Find is expensive to run every frame. There's a line in the documentation ( here ) that says this is a bad idea.
Answer by nathanthesnooper · Dec 22, 2016 at 05:48 AM
If it's 3D, use transform.forward.
As for actually applying the force, you want to do something like this.
GameObject newBullet = (GameObject)Instantiate(bullet) as GameObject;
newBullet.transform.position = bulletSpawnPoint;
newBullet.GetComponent<Rigidbody>().AddForce(transform.forward);
Answer by Yay_For_Humzah · Dec 22, 2016 at 01:49 PM
Ok so the bullet prefab needs to have a script attached to it that either at start or in update adds force
thanks a lot that helped me a lot but i have another question. 1) How can I make just the rotation of bullet static. I have tried this checking the check box of static on top right side, in transform inspector.
Answer by Rosh7X · Apr 10, 2017 at 01:03 PM
No you can add force to the Bullet through the gun script, just when you instantiate the bullet you give it a name, then you can do something like this
Bullet.Getcomponent < Rigidbody >().Addforce(transform.forward)
Not at home so I don't have an actual script to show you. Hope this helps