- Home /
Rigidbody.AddForce with Raycast?
if (Physics.Raycast (transform.position, transform.TransformDirection (Vector3.forward), hit, range)) {
if (hit.collider.attachedRigidbody) {
hit.rigidbody.AddForce (Vector3.forward * force);
}
}
I assumed adding a rigidbody force would take into account the direction the ray was coming from, but I was wrong. I've tried Quaternion.identity and transform.localRotation, but the compiler doesn't understand it. How can I add force to a rigidbody in a forward direction from the point that the rigidbody was hit?
Answer by FLASHDENMARK · Nov 03, 2012 at 11:38 PM
Are you looking for rigidbody.AddForceAtPosition?
Is this right?
hit.rigidbody.AddForceAtPosition (hit.transform.position, transform.position * hitForce);
No. You cannot describe a RaycastHit's position by using 'hit.transform.position'. You will have to use 'hit.point' ins$$anonymous$$d.
Would this work?
hit.rigidbody.AddForceAtPosition (transform.TransformDirection (Vector3.forward) hitForce Time.deltaTime, hit.point);
var hit : RaycastHit; var hitForce : float;
That is not entirely right either. If you take a look at the documentation you will see that the function takes a 'force' and a 'position' parameter, (but remember you will have to convert the force into a Vector3). The force is of course the amount of force you wan't to apply. And the position is where the force is added.
This is how I would write it:
hit.rigidbody.AddForceAtPosition(transform.forward * force, hit.point);
Aren't you converting the Vector3 into a force by multiplying it by hitForce? I don't see any difference in using 'transform.forward' and 'transform.TransformDirection (Vector3.forward)'.