- Home /
How can I go about moving my camera smoothly
The following code is crouching for a first person camera. When the player presses left CTRL, the camera moves down on its Y-axis to the crouch height, then if the player presses it again, it will return the height to the original Y Value. How can I make it so that the transition between the two values is smooth?
 void checkCrouch()
     {
         originalHeight = crouchDepth * -1f;
         if (isCrouched == true)
         {
             Debug.Log("nowcrouching");
             Vector3 newPosition = transform.position; // We store the current position
             newPosition.y += crouchDepth; // We set a axis, in this case the y axis
             transform.position = newPosition;
            
         }
         else
         {
             Debug.Log("nolongercrouching");
             Vector3 newPosition = transform.position; // We store the current position
             newPosition.y += originalHeight;// We set a axis, in this case the y axis
             transform.position = newPosition;
 
         }
     }
Answer by rh_galaxy · Oct 05, 2020 at 04:32 AM
You will have to update the Y axis over a period of time, so you store a goal value to go to whenever you change the is crouching and use Lerp() to smooth it out.
 public float crouchDepth = 1.0f;
 public float smoothTime = 0.5f;
 private float smoothTimer = 0;
 private float lastYOffset = 0;
 private float fromYOffset = 0;
 private float toYOffset = 0;
 bool isCrouched = false;
 bool isCrouchedLast = false;
 void Update()
 {
     if (isCrouched != isCrouchedLast) //detect if changed
     {
         if (isCrouched)
         {
             toYOffset = crouchDepth;
         }
         else
         {
             toYOffset = 0;
         }
         fromYOffset = lastYOffset;
         smoothTimer = 0;
         isCrouchedLast = isCrouched;
     }
     smoothTimer += Time.deltaTime;
     float yOffset = Mathf.Lerp(fromYOffset, toYOffset, smoothTimer / smoothTime);
     //if you know the position without the yOffset added this could be simpler...
     Vector3 newPosition = transform.position;
     newPosition.y -= lastYOffset;
     newPosition.y += yOffset;
     lastYOffset = yOffset;
     transform.position = newPosition;
 }
Your answer
 
 
             Follow this Question
Related Questions
Can't get smooth 2d movement for an object using transform.position 1 Answer
"Lerp" back to original position after animation. 0 Answers
Distribute terrain in zones 3 Answers
Rotate Parent using Child as Pivot 0 Answers
transform.position not setting position OR animation setting position even though it shouldn't 0 Answers
 koobas.hobune.stream
koobas.hobune.stream 
                       
                
                       
			     
			 
                