- Home /
Make input code execute once on MouseDown
Hey all,
I have a small problem i need to make the following Code execute once only on MouseDown but have no idea how to do it
if (Input.GetMouseButtonDown (0)) {
TileRay = Camera.main.ScreenPointToRay (Input.mousePosition);
if (Physics.Raycast (TileRay, out TileRayHit))
;
TileSelected = TileRayHit.transform.name;
MouseFirstPressPosition = new Vector2 (Input.mousePosition.x, Input.mousePosition.y);
{
Debug.Log (TileSelected);
Debug.Log (MouseFirstPressPosition);
}
}
if (Input.GetMouseButtonUp (0)) {
MouseSecondPressPosition = new Vector2 (Input.mousePosition.x, Input.mousePosition.y);
MouseCurrentSwipe = new Vector2 (MouseSecondPressPosition.x - MouseFirstPressPosition.x, MouseSecondPressPosition.y - MouseFirstPressPosition.y);
MouseCurrentSwipe.Normalize ();
{
Debug.Log (MouseSecondPressPosition);
}
}
if (!(MouseSecondPressPosition == MouseFirstPressPosition)) {
if (Mathf.Abs (MouseCurrentSwipe.x) > Mathf.Abs (MouseCurrentSwipe.y)) {
if (MouseCurrentSwipe.x < 0) {
Debug.Log ("Swipe Left");
MouseMovementDirection = "Left";
} else {
Debug.Log ("Swipe Right");
MouseMovementDirection = "Right";
}
} else {
if (MouseCurrentSwipe.y < 0) {
Debug.Log ("Swipe Down");
MouseMovementDirection = "Down";
} else {
Debug.Log ("Swipe Up");
MouseMovementDirection = "Up";
}
}
}
The Code works and does exactly what i want but i keeps returning the TileSelected and MouseMovement Direction constantly. not good when you a making a tile game that relies on if statements to move tiles.
No it wasn't inside a OnGUI function. I managed to figure it out Thanks to HYOERSAVV. Using a If statement for mouse button up made it work perfectly. Thank you.
Answer by HYPERSAVV · Jan 03, 2015 at 05:20 AM
If you are not clearing out the values of MouseFirst/SecondPressPosition, then there will always be two values to compare and therefor you will most likely always hit that third if statement. Perhaps you could roll that third if statement into the if statement for GetMouseButtonUp, I'm assuming you only want to do this after the mouse was released.