Interrupt a function which depends on Smoothdamp

Hey ! Thanks in advance for answering my (probably stupid) question, but I’ve been pulling my hair at it for a few hours :x

I’m trying to code a camera for a 2D platformer. Of course I want it to follow the player horizontally at any time, but I only want it to follow vertically when the character lands on a new platform (if it was following vertically all the time, that would be dizzying if the player is a spastic jumper).

It works perfectly in-game, however the function keeps being called and called and called as the cameraHeight is never quite exactly the player’s height so my concern is more “performance related”…I guess it is due to the Smoothdamp slowing at the edges but I’m not sure… and I sure as hell can’t seem to get out of this loop T_T

I tried to break it when the absolute distance between them was very low, but it was still taking to much time and it was clearly noticeable on screen.

Here is the code, again thanks in advance for glancing at it a bit. It would really help me sleep better =)

Best regards


using UnityEngine;
using System.Collections;

public class camera : MonoBehaviour {
public Transform player;
Vector3 newPos;
float cameraHeight;
float newCameraHeight;
bool grounded;
player_controller playerPos;
float velocity = 0.1f;
bool movingCamera =false;
	
	void Start () 
	{
		playerPos = player.GetComponent<player_controller>();
	}

	void Update()
	{

// if the player is on the ground BUT the camera is not on his level, then we want the camera to move vertically to his new location and stop

		if ((playerPos.grounded == true) &&(cameraHeight!=player.transform.position.y)) 
		{
				newCameraHeight = player.transform.position.y;
				movingCamera = true;
		}

		if (movingCamera == true)
		{
			movingCameraHeight();
		}

// the camera follows the character horizontally, and vertically only when cameraHeight is changed by the function below.
newPos = new Vector3 (player.position.x, cameraHeight, transform.position.z);
transform.position = newPos;

	}

	void movingCameraHeight()
	{
		cameraHeight=Mathf.SmoothDamp(cameraHeight,newCameraHeight,ref velocity,0.3f);

//when the camera is done catching up with the player’s height, it should stop… “normally”. I actually rarely see “End Function” in the console

		if (cameraHeight==player.transform.position.y) 
			{
				movingCamera=false;Debug.Log("End Function");
			}
	
	}

}

Ok I managed to get the function only called once when the level of the player has changed (it doesn’t depend on the player’s y anymore because the smootdamp messed with it), so it’s much better, but the function still never stop going.

if ((playerPos.grounded == true) &&(newCameraHeight!= playerPos.newPlayerHeight )) 
		{
				newCameraHeight = playerPos.newPlayerHeight;
				movingCamera = true;
			Debug.Log("Function Gets Called");
		}

Any idea to make the function come to an end ? :slight_smile: