Apply force at hit point (JS)

I’m trying to make it to my gun applies a force at the point of the raycast.
Here’s what I tried, but got a null reference exception.

function FixedUpdate () {
var fwd = transform.TransformDirection (Vector3.forward);
var hit : RaycastHit;
if(Input.GetMouseButtonDown(1)){
if (Physics.Raycast (transform.position, Vector3.forward, hit)) {
var pos = hit.point;
hit.rigidbody.AddForceAtPosition(Vector3.forward, pos);
}
}

}

maybe you are hitting an object, that doesnt have rigidbody?

try adding print for checking what you hit,

..
var pos = hit.point;
print (hit.transform.name);
..

It has a rigidbody.

try with the print…maybe the ray hits the gun itself…?

Gun has no collider.
I put the script on an empty gameobject too.
It only pops up with the null reference thing when I look at my crate model (with rigidbody) and right click.

Declare pos as Vector3 when you initialize it. This may be a typecast thing.

Changed up the code a bit:

function FixedUpdate () {
var fwd = transform.TransformDirection (Vector3.forward);
var hit : RaycastHit;
if(Input.GetMouseButtonDown(1)){
if (Physics.Raycast (transform.position, Vector3.forward, hit)) {
hit.rigidbody.AddForceAtPosition(Vector3.forward, hit.point);
}
}

}

Got this

Bump?

Your hit collider doesn’t have a RigidBody attached to it. Log the name of the GameObject and ensure you’re actually hitting what you think you are.