- Home /
AddForce wont apply force to gameobject...help please
I am created a top-down shooter and i have the player rotate towards the mouse...i have a script attached to the player to instantiate a grenade to be thrown when the mouse button is clicked. The grenade shoots BUT just drops right to the ground, no force is applied once its instantiated...here is my code...
var speed = 40; var cratePrefab:Transform;
//static var canShoot = false;
function Update() { if(Input.GetButtonDown("Fire1")) { //only shoots if player has ammo if(Collisions.GRENADE_AMMO > 0) { Collisions.GRENADE_AMMO -= 1; //GameObject.Find("g_count").guiText.text=""+Collisions.GRENADE_AMMO; var crate = Instantiate(cratePrefab,GameObject.Find("shootpoint").transform.position,Quaternion.identity); crate.rigidbody.AddForce(Vector3.forward * speed); } } }
all help is greatly appreciated!!
Answer by skovacs1 · Oct 21, 2010 at 07:09 PM
Make sure that your crate is not colliding with the one throwing it. You can use Physics.ignoreCollision or make sure to offset it to avoid that problem.
If that's not it, assuming your cratePrefab has a non-kinematic rigidbody and depending on your scale, your speed is probably too low to either be noticeable or to overcome your drag or other factors. Forces don't actually represent speeds directly, but force applied and that's why they have to be much larger. With a force of 40, your object should achieve a speed of 4 units forward initially. Try something like 400 or 4000. If you want to force the initial speed and direction, you could also use crate.rigidbody.velocity
to set the speed explicitly.
I got it to actually SHOOT using velocity, but now its only moving in the Z direction no matter where i am ai$$anonymous$$g. I'm new to unity and i understand why its doing that but how can i change this:
crate.rigidbody.velocity = Vector3(0,0,speed);
so that the velocity is applied to wherever the player is facing...something like transform.position...
maybe i can use local coordinates ins$$anonymous$$d of Vector3??
The velocity Vector3(0,0,something) would indicate a movement along the world z axis by something. To get a local direction, you would either use crate.rigidbody.velocity = crate.TransformDirection(Vector3(0,0,something)); or you could just simply do crate.rigidbody.velocity = transform.forward * something; skovacs1 0 secs ago