How to limit where a sprite can move when using onMouseDrag

Hi, I am fairly new to Unity so please bear with me I have tried looking for the answer everywhere, but have had no luck.

Basically I am using onMouseDrag to move a sprite around the background for a classroom (1366x768) that has a table. However, I want to limit where the sprite can go so that it does not end up off screen or off of the table on my background.

My sprite has the 2d box collider and rigidbody components attached (gravity is set to zero and it is at a fixed angle). I thought that by placing four 2d box colliders around the area I want to keep the sprite in it would be enough to contain it but the sprite simply goes straight through them.

I also read up about using Mathf.Clamp to restrict the area but I do not really understand how to use it from the examples I have seen.

Below is my code for moving the sprite:

using UnityEngine;
using System.Collections;

public class MovementScript : MonoBehaviour {

	float x;
	float y;

	void Update() {
		x = Input.mousePosition.x;
		y = Input.mousePosition.y;

	public void OnMouseDrag() {
		transform.position = Camera.main.ScreenToWorldPoint (new Vector3 (x, y, 1.0f));

Any help would be greatly appreciated, thank you!

Clamp(value, min, max) gives you value if it’s between min and max. If value < min, it gives you min. If value > max, it gives you max.

You want something like this (pseudocode):

x = clamp(Input.mousePosition.x, minX, maxX);
y = clamp(Input.mousePosition.y, minY, maxY);

Clamp Reference