- Home /
Adding force to a bullet
I'm making a FPS on Unity (yeah yeah not original but who cares) and I'm doing okay. I've got the FPS control going with the camera following it, I got the imported models and particle effects. There's just a problem that is preventing me from moving on to shooting targets and stuff. I made a little Instantiate script to make bullets appear. The appearing bit works but I want to add force to the bullets, of course, so I made this little Javascript:
var thePrefab : GameObject;
var power : float = 100.0;
function Update () {
if(Input.GetKeyDown(KeyCode.S)){
var instance : GameObject = Instantiate(thePrefab, transform.position, transform.rotation);
thePrefab.rigidbody.AddForce(Vector3(0, 0, power));
Surely this should make the bullets shoot forwards by 100 units when I press the S button, right? Well, nothing happens. When I press S, the bullet appears and then drops to the ground because of rigidbody, but there's no force! Any help!? Sorry if this is a really easy mistake, I'm still learning.
Answer by temptest123 · May 28, 2013 at 12:37 PM
assuming that the rigid body of your prefab is properly setup, you need to add the force to the rigidbody of your instanciated object ('instance'), not the prefab you use as template for instanciation.
Answer by Imankit · May 28, 2013 at 01:00 PM
Write
instance.rigidbody.AddForce(Vector3(0, 0, power));
Answer by DeveLOLper · May 28, 2013 at 01:33 PM
Don't worry now , lads I've figured it out. I took out the force bit off this script and made a new script like this:
[CODE] var force : float = 100;
function Update () {
if(Input.GetKeyDown(KeyCode.S)){
rigidbody.AddForce(transform.forward * force);
}
} [/CODE]