AddForce in direction of different object?
Hey guys, I'm trying to shoot a projectile out of the end of a gun but can't seem to figure out how to get the rotation right when I'm adding force to it. Here's my code:
All it does is shoot upwards. Any ideas?
Answer by hexagonius · Mar 21, 2017 at 06:08 AM
you can't just assign Quaternion values to a vector, that's producing garbage. AddForce is in world space. since it's a vector it's easier to use an axis of your gun. assuming your gun has it's z axis in forward direction, the vector you need to apply force to is gun.transform.forward.
it's even easier to add an empty game object as your muzzle to where the bullet will spawn. then you can use it's position and forward to launch.
Okay so it's in the correct direction now, but it doesn't add any force. It just instantiates then falls.
public GameObject origin;
public Rigidbody me;
public float bulletSpeed = 10000f;
void Start ()
{
Vector3 dir = new Vector3 (-origin.transform.rotation.x, 0f, 0f);
me.AddForce (dir * bulletSpeed, Force$$anonymous$$ode.Impulse);
}
Your answer
Follow this Question
Related Questions
How do i find player rotation and convert that into a force facing that direction. 0 Answers
Why does my rigidbody move it's transform while rotating? 1 Answer
How to change the direction of a rigidbody without adding to its speed? 1 Answer
Torque rigidbody toward desired rotation on two axes ignoring Y axes? 0 Answers