- Home /
Setting Click and Drag constraints
Hi there.
So, I've got this 2D scene with an orthographic camera looking at a plane. I've got a click and drag script on the camera that allows you to pan across the plane. However, when it gets to the edge, you can keep dragging it until its off screen.
How do you set it so that once it reaches the edge of the plane it cant drag any further? Not sure if there's an easy way of doing this but I would appreciate any help.
Thanks!
Answer by robertbu · Aug 14, 2013 at 03:15 PM
Open approach is to calculate the minimum and maximum that the camera is allowed on the 'x' and the 'y'. The orthographicSize is half of the vertical size seen by the camera. The variables 'planeHeight' and 'planeWidth' is the world unit size of the plane. Note if you are using the build-in plane, it is 10 x 10 when the scale is (1,1,1).
#pragma strict
var planeHeight = 12.0; // world units of plane
var planeWidth = 16.0;
private var minX : float;
private var maxX : float;
private var minY : float;
private var maxY : float;
function Start () {
var halfViewportHeight = Camera.main.orthographicSize;
var halfViewportWidth = halfViewportHeight / Screen.height * Screen.width;
minX = -planeWidth / 2.0 + halfViewportWidth;
maxX = planeWidth / 2.0 - halfViewportWidth;
minY = -planeHeight / 2.0 + halfViewportHeight;
maxY = planeHeight / 2.0 - halfViewportHeight;
}
function LateUpdate () {
transform.position.x = Mathf.Clamp(transform.position.x, minX, maxX);
transform.position.y = Mathf.Clamp(transform.position.y, minY, maxY);
}
Answer by Cyber-X-Zone · Aug 14, 2013 at 03:53 PM
You can use Mathf.Clamp to set minimum and maximum values the camera could go.
Format is : static function Clamp(value: float, min: float, max: float): float;
For Example, add this script to the Main Camera object::
var xMin : float;
var xMax : float;
var zMin : float;
var zMax : float;
function Update () {
transform.position = Vector3(Mathf.Clamp(transform.position.x, xMin, xMax), 0, Mathf.Clamp(transform.position.z, zMin, zMax));
}
First, we specify the 3 Vectors and set the value for x-axis between xMin and xMax variables, such that the Mathf.Clamp forces the value of transform.position.x to be in between the xMin and xMax variables.
The same happens for z-axis, as we apply the transform.position.z between zMin and zMax variables.
But, we don't need to change the the value of y-axis because you only need to pan the camera, so we set the value of y as 0.
For more information, visit: Mathf.Clamp.
Your answer
![](https://koobas.hobune.stream/wayback/20220613112205im_/https://answers.unity.com/themes/thub/images/avi.jpg)