- Home /
Mouse Swipe?
Okay so I'm trying to figure out how to detect a mouse swipe?
Could anyone write an example code so I can learn and understand it, please?
Answer by khellstr · Sep 18, 2013 at 11:20 AM
Hi. I took this out of code I use to drag camera with mouse. I'm learning Unity too, so there might be better ways.
if(Input.GetMouseButtonDown(0)) // check If left mousebutton is down
mouseLastFramePosition = Camera.main.ScreenToViewportPoint(Input.mousePosition);
// Gets mouse position in screen.
isDragging = true;
}
if (isDragging){
Vector3 mouseMovement = Camera.main.ScreenToViewportPoint(Input.mousePosition) - mouseLastFramePosition;
// calculates how much mouse have moved between this and last frame
mouseLastFramePosition = Camera.main.ScreenToViewportPoint(Input.mousePosition);
// Stores mouse position for use in next frame
}
So mouseMovement variable would be used what ever you want to do with swipe. For example move someting:
objectToMove.tranform.Translate(mouseMovement, Space.World );`
if you want to move only in one axis:
objectToMove.tranform.Translate(mouseMovement.x, Space.World );`
Hope this helps
[edit] Put those inside update
I realized that you should check mouseLastFramePosition in every frame for that code to be right. Now when you begin dragging current and last frame positions are same.
So there is a one frame lag before drag begins. Haven't noticed anything in my game project, so fixing that is now last thing in my toDo list.
Your answer
![](https://koobas.hobune.stream/wayback/20220613114404im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Throw with mouse 1 Answer
Mouse Swipe and Code Efficiency 0 Answers
How to move an object using mouse just like the swipe in iOS? 1 Answer
swiping with mouse input 0 Answers
Detect mouse swipe on 2d object 1 Answer