How to limit the max camera distance to player (2D)

Hello, I’m a total beginner in scripting and today I wrote my first litle camera movement script, wich is movin the camera on the center point between the player and the cursor.

C# Script:

  • using System.Collections;
  • using System.Collections.Generic;
  • using UnityEngine;
  • public class CameraController : MonoBehaviour
  • {
  • public GameObject Player;
  • private Vector3 mousePosition;
  • private Vector3 offset;
  • float Damping = 5;
  • private Vector3 Center;
  • float ViewDistance = 5;
  • void Start()
  • {
  • }
  • void LateUpdate()
  • {
  • mousePosition = Input.mousePosition;
  • mousePosition = Camera.main.ScreenToWorldPoint(mousePosition);
  • Center = new Vector3((Player.transform.position.x + mousePosition.x) / 2, (Player.transform.position.y + mousePosition.y) / 2, transform.position.z);
  • transform.position = Vector3.Lerp(transform.position, Center, Time.deltaTime * Damping);
  • Debug.DrawLine(mousePosition, Player.transform.position, Color.red);
  • }
  • }

But now I wanted to know how I can manage it to limit the disance the camera can move away from the player.

Please help!
Thanks!

When you paste snippets of code into the forums be sure to use Code Tags.

Using your code as a base, something like this might do the trick:

mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);

midPoint = (Player.transform.position + mousePosition) / 2;

// get the vector between the current and target positions
Vector3 deltaPosition = (Vector2)midPoint - (Vector2)Player.transform.position;

// if that vector is longer than the max distance
if(deltaPosition.magnitude > maxDistance) {
    // clamp it to max distance
    deltaPosition = Vector3.ClampMagnitude(deltaPosition, maxDistance);
    midPoint = Player.transform.position + deltaPosition;
}

midPoint.z = transform.position.z;

transform.position = Vector3.MoveTowards(transform.position, midPoint, Time.deltaTime * Damping);

I didn’t test this code, so forgive me if there’s an error. You’ll need to define whichever variables you’re missing, or rename to your preference.

2 Likes

I figured it out by myself but thank you for the help.

Thank you very much mate, I was looking for a solution to this problem for a couple of hours, but nobody offered one that suited me. Good luck!