- Home /
AddForce at Local ??
Hello everyone, i'm trying to create emtpy shells after i fire, and adding them some force to spread, but i have a problem. My code is :
var newshell =Instantiate(shell,shellspreader.transform.position,Quaternion.identity);
newshell.transform.Rotate(new Vector3(0,0,Random.Range(-180,180)));
newshell.transform.Rotate(new Vector3(0,-90,0));
newshell.rigidbody.AddForce(1000,0,0);
everything is OK,almost, there is one thing. When i fire, the shell goes to the right at 1000 force as i wanted, when i turn right in 90 degrees and fire,shells go forward at 1000, when i turn right in 180 degrees(which is my back) , the shells go left at 1000 force, when i turn right in 270 degrees, or left in 90 degrees the same, shells go back, it's like they always want to go to the same direction. Here is the photo explanation about my problem :
any ideas how to fix it ?
Thanks :)
Answer by aldonaletto · Oct 12, 2011 at 11:26 AM
You should use the weapon transform as a reference to apply the force:
...
newshell.transform.Rotate(new Vector3(0,-90,0));
newshell.rigidbody.AddForce(transform.right * 1000);
...
This will work if this script is attached to the weapon (or to the player, or to any object aligned to the weapon), since transform.right is used to direct the force.
Answer by Ecnalyr · Oct 12, 2011 at 11:19 AM
Change the line to: change AddForce (uses global space) to AddRelativeForce (uses local space).
I think this should work. . .
var newshell =Instantiate(shell,shellspreader.transform.position,Quaternion.identity);
newshell.transform.Rotate(new Vector3(0,0,Random.Range(-180,180)));
newshell.transform.Rotate(new Vector3(0,-90,0));
newshell.rigidbody.AddRelativeForce(1000,0,0);
didn't work, now shells always go to back, it just changed the position they always go, but you are right, i think it's about that global or local space issue, thanks but still need help :).
Need to change the direction of the applied AddRelativeForce.
(1000, 0, 0) apparently is sending them backwards because that is the direction you are telling them to go.
See: http://unity3d.com/support/documentation/ScriptReference/Rigidbody.AddRelativeForce.html
Try (0,1000,0), (0,-1000,0), (0,0,1000), and (0,0,-1000) depending on what direction the object is facing, one of those should work.
It's going to the wrong direction because AddRelativeForce is relative to the shell rigidbody, which was rotated to a random angle around z and to -90 around y.