How do I move an object from anywhere on the screen?


I have an object and I would like to drag it around, when I click/tap on the screen.

The trick is that I want to move it around no matter where I click on the screen. The object needs to hold its position relative to the mouse click or touch.

ex: Suppose the object is at the top of the screen, I want to be able to start dragging it around if I click and drag at the bottom of the screen.

Any ideas?

One way to do this is with 2 sets of co-ordinates - oldX, oldY and newX and newY.

  1. Set oldX and oldY to the x and y values of the first click/touch. This is set only once.

  2. Set newX and newY to the current mouse/touch position.

  3. Add the difference between the old and new co-ordinates to the current co-ordinates of the object.

  4. Set oldX to newX and oldY to newY

  5. repeat from step 2

Another way is to have 2 sets of co-ordinates - touchX & touchY and objX & objY.

  1. On first touch or mouse down, set touchX & touchY to the position of the touch/mouse. Set objX & objY to the position of the object.

  2. Add the difference between touchX & touchY and the current mouse/touch position to objX & objY to get the object’s position.

  3. Repeat step 2