- Home /
Clamp a mouse around several 2d objects
I am doing a sort of Duck Shooting game, and I have set my whole environment. However the "environment" is several curtains. I want the mouse to stay in the area in between them.
How would I do this?
Answer by Cherno · Jul 22, 2015 at 06:37 AM
It's a little complicated since Unity doesn't have such a function, you have to dive into user32.dll stuff.
This thread details the method:
Constrain Mouse Cusor While Fullscreen (Windows)
using UnityEngine;
using System.Collections;
using System.Runtime.InteropServices;
public class ClipCursorScript : MonoBehaviour
{
[DllImport( "user32.dll", CharSet = CharSet.Auto, ExactSpelling = true )]
[return: MarshalAs( UnmanagedType.Bool )]
public static extern bool ClipCursor( ref RECT rcClip );
[DllImport( "user32.dll" )]
[return: MarshalAs( UnmanagedType.Bool )]
public static extern bool GetClipCursor( out RECT rcClip );
[DllImport( "user32.dll" )]
static extern int GetForegroundWindow( );
[DllImport("user32.dll")]
[return: MarshalAs( UnmanagedType.Bool )]
static extern bool GetWindowRect( int hWnd, ref RECT lpRect );
[StructLayout( LayoutKind.Sequential )]
public struct RECT
{
public int Left;
public int Top;
public int Right;
public int Bottom;
public RECT( int left, int top, int right, int bottom )
{
Left = left;
Top = top;
Right = right;
Bottom = bottom;
}
}
RECT currentClippingRect;
RECT originalClippingRect = new RECT( );
void Start()
{
currentClippingRect = new RECT(Screen.width / 2 - 10, Screen.height / 2 - 10, Screen.width / 2 + 10, Screen.height / 2 + 10);
ClipCursor( ref currentClippingRect);
}
void OnApplicationQuit()
{
ClipCursor( ref originalClippingRect );
}
}
The currentClippingRect is the rect that will constrain the cursor. Note that it will only work in full screen mode, as it uses screen coordinates of the WHOLE screen, not just what Unity would regard as a screen (the window where the game is ran).
Thanks, but I may need a different solution. I am not experient enough for codes like this :P. Ill try to figure out the code etc, Or try another solution. Couldn't I perhaps make the mouse not be able to pass by certain colliders etc?
No. Unity only supports locking the mouse to the center of the screen. If you use the script above, you have to find the screen coordinates and width + length of the rect in which the cursor should stay and use those values to define the currentClippingRect.
Your answer
Follow this Question
Related Questions
Distribute terrain in zones 3 Answers
If i click on a object i move to the next level (c#) 0 Answers
Create objects on a mouse click in 2D 1 Answer
Make a dotted line from an object to the mouse 2d 2 Answers
Apply force towards mouse click 2D C# 0 Answers