Object movement together with the Unity 2D camera

I'm making a 2D top-down game on unity. There was the following problem, I have control fingers left-right, there are borders in the background that the camera rests on the X-axis, the main object is in the middle of the screen and moves along the X-axis with the camera, i.e. the object is in the middle of the camera. The essence of the problem: when swiping, for example, to the right, the camera reaches the edge of the background, and rests on it, the object also moves to the edge, but when swiping in the opposite direction, the camera and the object starts moving at the same time until the next edge is reached. Tell me how to make the swipe from the edge to the opposite side first move the object to the middle of the camera, and then the camera together with the object to the opposite edge. I hope the essence of the problem is clear. Thanks.

 1
Author: TheHotboll, 2020-03-17

1 answers

public float TargetX; // куда смотрим
float HalfCameraWidth = 10; // указать половину ширины камеры
float LeftBorder = 0; // левая граница обзора
float RightBorder = 100; // правая граница обзора

void Update () {
    float NewX = TargetX; // следит за целью
    if (NewX < LeftBorder+HalfCameraWidth)
        NewX = LeftBorder+HalfCameraWidth; // коррекция левого ограничения обзора
    else if (NewX > RightBorder-HalfCameraWidth)
        NewX = RightBorder-HalfCameraWidth; // коррекция правого ограничения обзора
    Vector3 CamPos = Camera.main.transform.localPosition;
    Camera.main.transform.localPosition = new Vector3(NewX, CamPos.y, CamPos.z);
}
 0
Author: Yaroslav, 2020-03-17 13:32:34