Restricting Cursor Movement to a Screen Section. (Clamp)

Currently, I am working on a minigame which drags and drops game objects onto a moving platform. I want the game to focus on timing but currently the game allows the cursor to drag the game object all the way to the platform making precision a non-factor. So I want to constrict the cursor to the top section of the gamescene so the player has to drop the gameobject instead of dragging it all the way to the Platform. The current script I am working with is:

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

public class PassengerDrag : MonoBehaviour {

    private Vector3 mOffset;
    private float mZCoord;


    void OnMouseDown(){

        mZCoord = Camera.main.WorldToScreenPoint(gameObject.transform.position).z;

        // Store offset = gameobject world pos - mouse world pos
        mOffset = gameObject.transform.position - GetMouseAsWorldPoint();
    }


    private Vector3 GetMouseAsWorldPoint(){

        // Pixel coordinates of mouse (x,y)
        Vector3 mousePoint = Input.mousePosition;

        // z coordinate of game object on screen
        mousePoint.z = mZCoord;

        // Convert it to world points
        return Camera.main.ScreenToWorldPoint(mousePoint);
    }


    void OnMouseDrag(){
        transform.position = GetMouseAsWorldPoint() + mOffset;
    }
}

I don’t think you can constrain the OS cursor, but you can constrain your own copy of it by drawing it yourself, perhaps with a UI.Image object.

To constrain it, define a RectTransform-containing blank GameObject that is your bounds, then clip the cursor within that rectangle.

The RectTransformUtility class has helpful methods that you might need as well.

2 Likes

How would I do that?

I’m not sure which part you don’t understand. Can you be more specific?