Converting Raycasted Point to Local Space

Hello, I have a script that rotates a gun based on a raycast point (where the raycast hits the terrain or mesh). The script uses a "transform.lookat" function to rotate the gun-barrel to where it should point.

Plus, I only want the gun to rotate up and down (on the x axis locally). I found this code which works great but... there's a problem.

Transform.LookAt(Vector3(hit.point.x, transform.position.y, transform.position.z));

The problem is that the raycasted hit point is in the WORLD space while I need to rotate the gun around a LOCAL space. Does anyone know how to make it work (code is provided as a reference below):

var guntrans : Transform;
function Update () {
    var ray = Camera.main.ScreenPointToRay (Input.mousePosition);
    var hit : RaycastHit;
    if (Physics.Raycast (ray, hit)) 
        {
  // Get your player object's position (could be any way, this is just one possible way)
         var playerT = GameObject.FindWithTag("RocketGun").transform;
  // Now you have where your player is and a 3D point the mouse is over
  Debug.DrawLine (playerT.position, hit.point);
  guntrans.LookAt(Vector3(hit.point.x, guntrans.position.y, guntrans.position.z));
        }
}

If you want to be rotating up and down you should be looking at the Y coordinate, not the X.

I think that you're trying to match the height of the collision point but keep the rest of the rotation matching the parent. If that is the case you could do something like this:

pseudocode:

var parentLookAt = transform.position + parentTransform.forward;
lookat( Vector3(parentLookAt.x, hit.point.y, parentLookAt.z) );

Edit: I realized this code is wrong, it's not quite that simple, here is a modified version which should work:

pseudocode:

var lookAtRelative = hit.point - transform.position;
var lookAtMagnitudeXZ = Vector3(lookAtRelative.x, 0, lookAtRelative.z).magnitude;
var parentForwardXZ = Vector3(parentTransform.forward.x, 0, parentTransform.forward.z).normalize;
var parentLookAtXZ = transform.position + (parentForwardXZ * lookAtMagnitudeXZ);
lookat( Vector3(parentLookAt.x, hit.point.y, parentLookAt.z) );

That is actually quite tricky, at least if I understand your problem correctly. After thinking about it a bit, I think that you can use the quaternions AxisAngle function. You should be able to get the angle as dot product between the current and the new look at vector and the axis is the cross product between your current up vector and the current look at vector. Should that do the job?

Edit: I missunderstood the previous answer, which I think works just as well and is much simpler :P