Drag continues after reaching the limit.


In my game I’m dragging my objects with mouse/touch and used some integer constraints with to limit where player can drag objects and it works just fine, here is the code that I put in each object’s update method:

void Update()
       if (transform.position.x <= -65)
         transform.position = new Vector3(-65, transform.position.y, transform.position.z);
       else if (transform.position.x >= 48)
         transform.position = new Vector3(48  , transform.position.y, transform.position.z);

Problem is if player drags the object out of the constraint, the object goes there and suddenly goes behind that constraint I put. It looks like the drag has a higher priority and first the finger moves the object to under player’s finger and then sees the update method call’s constraint and then moves the object back.

And if you keep your finger/mouse at that position beyond the constraint and move your finger a bit, same thing happens again.

How I can prevent this?

I’m using the “Advanced” method though, i.e. the one that I have my own Drag Gesture Recognizer and do not ask FingerGesture’s singleton.

Thanks in advance and any help would be highly appreciated.

yea you need to constraint the mouse itself and not the object.

The object is attached by the drag process to the mouse.

I bet if you debug logged its position it would ping pong from the mouse to the limit to the mouse again.

Its because one line of code has to run before the other. It just has to do one before the other.

doesnt matter which.

If the constraint kicks in first then it stops
it gets the go to mouse it goes there

the next frame the constraint kicks it back.

if the mouse goes first it goes there.
the constraint runs and kicks it back.

the next frame it leaps across the screen to the mouse.

You need to head this off at the mouse.

if you want to do it easy use a box collider.

use OnMouseExit

on mouse exit you move the mouse back to the nearest point on the collider

collider component has a function that finds the nearest point of a collider given a point.

you give it the mouse position at exit. you find the nearest point and move it back to that.