How can I store a current mouse position in a variable?

Hello guys!

The title of this topic pretty much tells what my problem is.

I’m trying to create a script that makes you able to open a shelf by clicking on it, and move the mouse
pretty much like in the game Amnesia.

I’m doing a raycast and everything seems to be right up until now. However I have a problem.

When I’m doing the raycast I’m checking for a mouse input when I’m pointing at a shelf, and if
I am indeed looking at one, and click it, I’m storing the mouse position in a variable.
I then check if the mouse position changes when the mouse button is held down, and if it is,
I transform the translate, making the shelf come out of the drawer.

Sadly, it doesn’t quite work the way I’m currently doing it.

This is the part of my script dealing with this:

(...)
		else if( hit.collider.tag == "Skuffe" )

		{

			if( Input.GetMouseButton(0) )

			{

				var mousePosX = Input.mousePosition.x;

				if( Input.mousePosition.x > mousePosX )

				{				

					hit.collider.gameObject.transform.Translate(0, 0, .1 * Time.deltaTime);
				
				}

				Debug.Log(mousePosX);

			}

		}

Anyone have an idea how to fix this? Or maybe a better idea for the same functionallity?
The way I wanted to try and do this was to store the current mouse possition and compare it
to any time when the mouse button is pressed, to see if it differs from when the mouse button
was first pressed, and then act opun that - But how can I do this?

Is it only possible to move the mouse in one direction or why do you use > ? You could try it with !=

Also there are some additional functions that you could use to test it OnMouseDown() or OnMouseUp() for example.
You’re comparing two same values, you set the mousePosX and then compare it with itself, but in the form of Input.mousePosition, see the mistake? :smile:

You could use

void OnMouseDown()
{
   mousePosX = Input.mousePosition.x;
   // some more action you want on initial mouse click?
}

void OnMouseDrag()
{
   //your action if the mouse moves while pressed (dunno if this Drag function also works if you don't move anything actually)
}

void OnMouseUp()
{
   // you could also check the condition here again when we release the mouse button again
   if(mousePosX != Input.mousePosition.x)
   {
      // we defenitely moved the mouse, some action here.
   }
}

Yes, I see the mistake, and I did when I first posted this message as well, but I just didn’t know where to go from here. :smile: Ill have a look at the functions you provided, thanks. :slight_smile: