How to use camera's axis for AddForce.

I’m working on a super simple script to create basically something like the jedi “force push.”

I just want to be able to add a force from the local axis of the camera and not the world or the rigid body being acted upon. Is there an easy way to do this? Here’s my script so far. Currently I have it lifting objects on the world Y axis, which looks cool but isn’t the effect I’m going for.

function Update () {
	
		var hit : RaycastHit;
	if (!Physics.Raycast(Camera.main.ViewportPointToRay(Vector3(0.5, 0.5, 0.0)), hit, 20))
		return;
	
	if (!hit.rigidbody)
		return;


	if (Input.GetButton ("Fire2"))
	{
		
		if (hit.rigidbody)
		{
			hit.rigidbody.AddForce(0,150,0);
			hit.rigidbody.AddTorque(0,5,0);
		}
		
		return;
	}
	

	if (!hit.rigidbody)
		return;

}

Thanks.

You could try using AddExplosionForce, like they do in the FPS tutorial… But I’ve never used it so I can’t give you the details…

Thanks, Dragon Rider.

I was thinking of playing with AddExplosionForce actually, since it would mimic more of the effect I’m aiming for. I’ll play around with it and share the results.

In the meantime, I’d still be interested if anyone knows how (or if) I can use the camera’s local axis for the implementation above.

Try using hit.rigidbody.AddForce (transform.up * 150); instead

Use Rigidbody.AddForceAtPosition to push the target at the point where the ray hits. If you use the direction of the ray as the direction of this force, the target will behave as if it was poked with a camera-mounted snooker cue at the target point (ie, it will get both a push and a torque around its centre of mass, be lifted slightly if the camera is looking upwards, etc).

Ah, wonderful!

Thanks andeeee, I’ll try that out later today and share the results.

Checking back in. It works great and in my experiments I’m now working on another script for temporarily removing gravity on an object. We’ll see where that goes. Unity is a great rabbit hole to fall down. Here’s the current working script if anyone finds it useful.

function Update () {
	
		var hit : RaycastHit;
	if (!Physics.Raycast(Camera.main.ViewportPointToRay(Vector3(0.5, 0.5, 0.0)), hit, 20))
		return;
	
	if (!hit.rigidbody)
		return;




	if (Input.GetButton ("Fire2"))
	{
		
		if (hit.rigidbody)
		{
			direction = hit.rigidbody.transform.position - transform.position;
			hit.rigidbody.AddForce(0,80,0);
			hit.rigidbody.AddForceAtPosition(direction.normalized * 150, transform.position);
			
		}
		
		return;
	}
	

	if (!hit.rigidbody)
		return;

}