Copying and Pasting cs Code

In cs, like in almost any computer programming language, reading data from a file can be tricky. You add extra lines of code to tell the computer what to do. Sometimes you can copy and paste these lines from other peoples’ code.

For example, you can follow the pattern in this listing:

     void SetUpRotation( Vector3 centerPos, Vector3 headPos )
     {
         // Now it's getting hairy. The devil is in the details here, the big issue is jumping of course.
         // * When jumping up and down we don't want to center the guy in screen space.
         // This is important to give a feel for how high you jump and avoiding large camera movements.
         //
         // * At the same time we dont want him to ever go out of screen and we want all rotations to be totally smooth.
         //
         // So here is what we will do:
         //
         // 1. We first find the rotation around the y axis. Thus he is always centered on the y-axis
         // 2. When grounded we make him be centered
         // 3. When jumping we keep the camera rotation but rotate the camera to get him back into view if his head is above some threshold
         // 4. When landing we smoothly interpolate towards centering him on screen
         Vector3 cameraPos = cameraTransform.position;
         Vector3 offsetToCenter = centerPos - cameraPos;

         // Generate base rotation only around y-axis
         Quaternion yRotation = Quaternion.LookRotation( new Vector3( offsetToCenter.x, 0, offsetToCenter.z ) );

         Vector3 relativeOffset = Vector3.forward * distance + Vector3.down * height;
         cameraTransform.rotation = yRotation * Quaternion.LookRotation( relativeOffset );

         // Calculate the projected center position and top position in world space
         Ray centerRay = m_CameraTransformCamera.ViewportPointToRay( new Vector3( 0.5f, 0.5f, 1 ) );
         Ray topRay = m_CameraTransformCamera.ViewportPointToRay( new Vector3( 0.5f, clampHeadPositionScreenSpace, 1 ) );

         Vector3 centerRayPos = centerRay.GetPoint( distance );
         Vector3 topRayPos = topRay.GetPoint( distance );

         float centerToTopAngle = Vector3.Angle( centerRay.direction, topRay.direction );

         float heightToAngle = centerToTopAngle / ( centerRayPos.y - topRayPos.y );

         float extraLookAngle = heightToAngle * ( centerRayPos.y - centerPos.y );
         if( extraLookAngle < centerToTopAngle )
         {
             extraLookAngle = 0;
         }
         else
         {
             extraLookAngle = extraLookAngle - centerToTopAngle;
             cameraTransform.rotation *= Quaternion.Euler( -extraLookAngle, 0, 0 );
         }
     }