- Home /
Clickable AND draggable object
I have a few objects which I can drag around the screen using the methods OnMouseDown()
and OnMouseDrag()
. I want to make those objects a button too, that is to click/touch them quickly so they do their own stuff.
I can imagine a simple way measuring the time between OnMouseUp()
and OnMouseDown()
but I will probably end up wasting energy fixing bugs for something that might be already done...
So is there an specific method to recognize a click? Obviously without altering the dragging capability.
i think you have answered your own question. cheers!
Answer by javoastudillo · Mar 16, 2017 at 04:54 AM
Since some people including me like to see coding, I came to post the simple couple of lines I used. No dragging flags, so an eventual really quick dragging could be detected as a click. Anyway the workaround would be setting a smaller threshold.
private float init;
[SerializeField] private float clickThreshold = 0.2f;
// stuff
void OnMouseDown () {
init = Time.time;
// more stuff
}
void OnMouseUp () {
if (Time.time - init < clickThreshold) {
Click ();
}
// click-unrelated stuff
}
void Click () {
// click stuff
}
Answer by Glurth · Mar 06, 2017 at 05:34 PM
No, you need to specify the "Click" conditions yourself.
What happens if I hold the mouse down over the object for 10 seconds, don't move it, and then release; is this a click?
For some Designers, yes, for your suggested method, no.
To make a draggable-button, personally I would use a boolean flag, and make MouseUp activate a Click, unless(check then clear flag) an OnDrag operation was initiated(clear flag), since the last mouseDown (set flag).
I might also define the behavior a bit differently if the button was NOT also draggable (e.g. only click if mouse is still over the button, during MouseUp). Certainly, some designers might disagree with that, it's a matter of taste.
Your answer
Follow this Question
Related Questions
Is it possible to drag a file from the desktop into a desktop application 2 Answers
NGUI Mouse position doesn't match with dragged object 0 Answers
Jigsaw Drag and Drop Game? Help! 0 Answers
Help with selecting and deselecting an object? 1 Answer
Unity Networking/Multiplayer and OnMouseDown() Question 0 Answers