Hello, I know there is a lerp function there that smoothens the camera but I wanted it to work the other way around. Lets say starting position of the player is at the left side of the camera/screen and when the players goes around the right edge (or as long as more than half width) screen travelled I want to camera to snap to the player but with smooth transition and this is the hard part I wanted to make the camera move fast as long as it is less than half the players distance travelled and apply a slow speed as the camera travels more than half the distance of player.
EDIT: No, it’s not gonna work. Just did some tests and, as I expected, the camera just stick to the player. The only way to flee away is to warp the player instantly, but it’s pointless, because the camera will reach him again very fast.
EDIT AGAIN: I’ve changed Lerp
to MoveTowards
and now it seems to be working. The speed
is going to be less than 0
when the camera stays too far beyond the maxDistance
, so I used another if
statement to get it back (closer to the player), otherwise it can’t reach the player:
float currentDistance;
float minDistance = 1f;
float maxDistance = 10f;
float speed;
currentDistance = Vector3.Distance (camera.position, player.position);
speed = (maxDistance - currentDistance) / maxDistance;
if (currentDistance > minDistance) // to keep the camera in distance from the player
{
// multiplier '1.5f' should be less then the player's speed,
// otherwise he could never run away from the camera when it reach him
camera.position = Vector3.MoveTowards (camera.position,
player.position, speed * 1.5f * Time.deltaTime);
}
if (currentDistance >= maxDistance) // to make camera chase the player if he'd ran too far
{
camera.position += (player.position -
camera.position) * 1f * Time.deltaTime;
// or maybe it's better to use 'Lerp' here to get smooth movements
camera.position = Vector3.Lerp (camera.position, player.position, 0.1f);
}