Clamping issue using raycast hit points

Hi all I am a unity newbie.

I have a camera which rotates around a fixed position and has the capability of a “zoom” which I achieve by translating along its z-axis(which I believe is the local z axis).
I then send a raycast in the direction of transform.forward and -transform.forward to check for any potential collisions along the path then use the respective hit.point.z values as clamp bounds.

My problem is that the clamp bounds are giving me wrong values. I believe its got something to do with the world vs local space but not sure how to correct if it is possible at all. Any clues ?

My current code is as below , my camera has no ridigbody or collider. The DrawRay seems to be indicating that the raycast is pointing in the correct direction.

var hit1 :float;
var hit2 :float;
var hit : RaycastHit;

if (Physics.Raycast(transform.position,transform.forward,hit)) {
	Debug.DrawRay (transform.position, transform.forward * 10, Color.yellow);
	hit1 = hit.point.z ;
	Debug.Log(hit.distance);
}

if (Physics.Raycast(transform.position,-transform.forward,hit)) {
	Debug.DrawRay (transform.position, -transform.forward * 10, Color.yellow);
	hit2 =  hit.point.z ;
	Debug.Log(hit.distance);
}

transform.Translate(transform.forward * Time.deltaTime *Input.GetAxis("Horizontal") *20,Space.World)		;
transform.position.z = Mathf.Clamp(transform.position.z , hit1, hit2);

hit.point.z references the impact point in world space. You probably want to use hit.distance instead, as it gives you the distance between raycast origin and contact.

It sounds like you’re trying to create a camera which slides forward and back, as if on a track? If so, you’ll probably want to parent it to some other object (to manage overall position/rotation), and then adjust its local position relative to that object (to manage track position).

As an alternative, you can change a camera’s field of view to achieve an actual zoom.