- Home /
Using mouse up and down for mouse swipe
I'm trying to use a mouse swipe in my game, similar to that used on touch screens. All I really need to know is if it's a swipe or a click and the direction (up, down, left, right). I found sample code which seemed to make sense but for some reason I can't get it to work. Here is my current code which relates to it:
Vector2 firstPressPos = new Vector2(0,0);
Vector2 secondPressPos;
Vector2 currentSwipe;
//get user input
if (Input.GetMouseButtonDown (0)) {
//get first mouse position
firstPressPos.x = Input.mousePosition.x;
firstPressPos.y = Input.mousePosition.y;
Debug.Log(firstPressPos.x);
Debug.Log(firstPressPos.y);
}
if (Input.GetMouseButtonUp (0)) {
secondPressPos = new Vector2(Input.mousePosition.x, Input.mousePosition.y);
currentSwipe = new Vector2(secondPressPos.x - firstPressPos.x, secondPressPos.y - firstPressPos.y);
Debug.Log(firstPressPos.x);
Debug.Log(firstPressPos.y);
}
This is in a function which is called from Update().
Based on the feedback I'm getting from Debug. The problem seems to lie with firstPressPos. The first set of debug in mouseButtonDown gives an accurate number but the set in mouseButtonUp say it's (0,0). The only explanation I can think of is that somehow it's resetting between the two functions. I have tried declaring firstPressPos as a global value instead of in the function but the result is the same.
Does anyone know why it's not working and how I could fix it?
Answer by robertbu · Mar 05, 2014 at 04:34 PM
Your code here is working. Your problem is that your Debug.Log() at the bottom of the script is outputting 'firstPresPos' rather than 'currentSwipe'. Note using Vector assignment and vector subtraction, you can simplify this code some:
using UnityEngine;
using System.Collections;
public class Swipe : MonoBehaviour {
Vector2 firstPressPos;
Vector2 currentSwipe;
void Update() {
if (Input.GetMouseButtonDown (0)) {
firstPressPos = Input.mousePosition;
}
if (Input.GetMouseButtonUp (0)) {
currentSwipe = (Vector2)Input.mousePosition - firstPressPos;
Debug.Log(currentSwipe+", "+currentSwipe.normalized);
}
}
}
I don't know how you are going to use your swipe, but you may want a normalized swipe. I output both the raw and the normalized in the Debug.Log().
Thank you robertbu. That really did clean up my code and it's working great now.
Your answer
![](https://koobas.hobune.stream/wayback/20220613135433im_/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