vb381
vb381

Reputation: 181

Unity - limiting camera movement

I have 2D project and I want to be able move camera by touch to the right and back... I found one tutorial, moving camera with swipes so it is working fine but how can I set maximum distance to move camera?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TouchController : MonoBehaviour
{
float touchStart = 0f;
Vector3 cameraDestination;
public float cameraSpeed = 0.1f;
Camera m_MainCamera;
// Use this for initialization
void Start()
{
    cameraDestination = Camera.main.transform.position;
}
// Update is called once per frame
void Update()
{
    if (Input.GetMouseButtonDown(0))
    {
        touchStart = Input.mousePosition.x;
    }
    if (Input.GetMouseButtonUp(0))
    {
        float delta = Input.mousePosition.x - touchStart;
        if (delta < -50f)
        {
            cameraDestination = new Vector3(Camera.main.transform.position.x + 500,
                Camera.main.transform.position.y, Camera.main.transform.position.z);
            // move the camera right
        }
        else if (delta > 50f){
            cameraDestination = new Vector3(Camera.main.transform.position.x - 500,
                Camera.main.transform.position.y, Camera.main.transform.position.z);
            // move the camera left
        }
    }
    if (Vector3.Distance(Camera.main.transform.position, cameraDestination) > 0.1f)
    {
        if (Camera.main.transform.position.x > cameraDestination.x)
        {
            Camera.main.transform.position = new Vector3(Camera.main.transform.position.x - cameraSpeed,
                Camera.main.transform.position.y, Camera.main.transform.position.z);
        }
        else
        {
            Camera.main.transform.position = new Vector3(Camera.main.transform.position.x + cameraSpeed,
                Camera.main.transform.position.y, Camera.main.transform.position.z);
        }
    }
}

}

Upvotes: 0

Views: 195

Answers (1)

Bip901
Bip901

Reputation: 808

Your question is unclear, but I assume you want to set a limit for the camera's position. For this you'll need 2 points - the minimum point (x = the smallest X value the camera is allowed to have, y = the smallest Y value the camera is allowed to have) and the maximum point (same thing but represents the upper bound).

Vector2 minPosition, maxPosition;

Then, every time you move your camera, check the following conditions and only then move it:

if (cameraDestination.x < maxPosition.x && cameraDestination.x > minPosition.x) //Ensures the camera's X value is within the allowed range
if (cameraDestination.y < maxPosition.y && cameraDestination.y > minPosition.y) //Ensures the camera's Y value is within the allowed range

Upvotes: 2

Related Questions