Setting limits for click and drag GameObject

Hi everyone,

I’m making a 2D menu that you scroll up and down through the levels.

I’ve got the following Click and Drag script on my GameObject:

using UnityEngine;
using System.Collections;
[RequireComponent(typeof(BoxCollider))]

public class Drag : MonoBehaviour
{
private Vector3 screenPoint;
private Vector3 offset;
private float _lockedYPosition;

void OnMouseDown() {
_lockedYPosition = screenPoint.y;
offset = gameObject.transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z));
Screen.showCursor = false;

}

void OnMouseDrag()
{
Vector3 curScreenPoint = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z);
Vector3 curPosition = Camera.main.ScreenToWorldPoint(curScreenPoint) + offset;
curPosition.x = _lockedYPosition;
transform.position = curPosition;
}

void OnMouseUp()
{
Screen.showCursor = true;
}
}

It drags on only one axis but I want to prevent it from dragging too far up or down and disappearing off the screen. I’ve tried with Box Colliders and Rigidbody but this seems to be a bit too unstable. I’ve briefly looked into doing it by calculating the min and max height/width and have the following script to print the GameObjects coordinates, but don’t know how to implement them:

#pragma strict

function Start () {

}

//Unity will constantly check the position of the GameObject.
function Update () {
//Creates a variable to check the objects position.
var myPosition = transform.position;
//Prints the position to the Console.
Debug.Log(myPosition);
}

Could anyone point me in the right direction of how to go about this?

I am no expert but I’d say after getting your Y value from the screen point

check to see if it is too high and if so, reset it back, like

if(Y > 100)    // 100 is the limit you want for example
{
     Y = 100;
}

// now you can push this value to your menu's Y.

I usually make an object and move it around to see where my high and low coordinates are. just for reference.

Hope this helps,…don’t forget,…you can and prolly should post this in the Scripting help section.

http://forum.unity3d.com/forums/12-Scripting

cheers

How would I go about implementing it once I have the values? Could you maybe provide some pseudo code?
And sorry about posting it in the wrong place, it took me long enough to find how to post on the forums haha!