Clamping Velocity.z when touching an object (Major Edit)

Major edit to reflect new approach to problem:

I am currently in the process of creating a 3d 1st person character. I’m currently having a problem with jumping and obstacles, and am attempting to prevent the character from being able to move forward when he is touching an obstacle (all other directions are ok).

My inital code was as follows:

		if (Physics.Raycast (transform.position, transform.TransformDirection (Vector3.forward), 0.6f)) {
			rigidbody.velocity = new Vector3 (
                  rigidbody.velocity.x, 
                  rigidbody.velocity.y, 
                  Mathf.Clamp(rigidbody.velocity.z, -100, 0));
		          }

This worked pretty well, however it only worked in global space, I.E when my character’s idea of “forward” was along the positive direction of the z axis. Any other way and it doesn’t work.

I then tried:

		if (Physics.Raycast (transform.position, transform.TransformDirection (Vector3.forward), 0.6f)) {
		     rigidbody.velocity = transform.TransformDirection(
                  rigidbody.velocity.x, 
                  rigidbody.velocity.y, 
                  Mathf.Clamp(rigidbody.velocity.z, -100, 0));
		          }

This doesn’t work either, I get some kind of insane push in the negative global Z direction whichever way I am facing, so it only works on obstacles that are in front of me in global space as well as local space. It also makes my x directions swap around.

InverseTransformDirection doesn’t work either.

Halp?

In order to make this work, you have to first convert velocity into local space, do the clamp, then convert the velocity back to global space. Something like:

if (Physics.Raycast (transform.position, transform.forward, 0.6f)) {
      Vector3 localDir = Transform.InverseTransformDirection(rigidbody.velocity);
      localDir.z = Mathf.Clamp(localDir.z, -100, 0);
      rigidbody.velocity = Transform.Tranform.TransformDirection(localDir);
}