How to add dragging by mouse to your game
Page 1 - The Theory
What you will need:
[SPRITE] 1 pixel by 1 pixel sprite
- with behaviour [b]'Pin'[/b].
[INPUT] 'Mouse' or 'Touch' object
[OBJECT] Any object you want to be drag-able
- add behaviour [b]'Pin'[/b].
[VAR] A variable to ensure you can only drag one item at a time. I called mine STATE_dragmode = 0/1
[VAR] A variable to store which object is currently being dragged. I called mine dragging - (stores the UID of the object).
[VAR] A dropcount variable which acts as a delay between drags.
Lets get dragging objects
1. Start by adding a 1 x 1 pixel sprite to your project (give it the 'pin' behaviour) - I called mine mouseLock.
2. Add a global variable that will be used to determine if we are already dragging an object. I called this STATE_dragmode with the value 0 for not dragging and 1 for dragging.
3. Add another global variable that will be used to delay the dragging process when you release an object.
4. Next add an event 'System -> Every Tick'
Set the [b]'position'[/b] of the 1 x 1 pixel sprite (mouseLock) to the [b]'x'[/b] of Mouse.X
Set the [b]'position'[/b] of the 1 x 1 pixel sprite (mouseLock) to the [b]'y'[/b] of Mouse.Y
Add a compare event comparing if [b]'dropcount'[/b] is greater than 0
Subtract 1 from dropcount
The Drag Code
5. Add an event for 'Left Mouse' Down or 'Is in Touch' ensuring you check that the object you want to be drag-able is underneath the cursor.
Add a condition to the event that checks if STATE_dragmode = 0 (only allow the drag IF we're not already dragging)
Set the STATE_dragmode variable to
Set the dragging variable to the objects' UID (unique id).
Also inside this event 'Pin' the object to mouseLock.
6. Now add a 'Left Mouse' Down event (but invert it - meaning the mouse is not held down)
'UnPin' the object.
Set dropcount to 20 or (higher depending on how much delay between dragging you want)
Set STATE_dragmode to 0 (stops the drag mode)
Run your game / program or app.
Move the mouse and you will now be able to drag the object.
(optional extra - when the object is first dragged set it to move to top of layer)
If you want to see the code and how simple it is to set up then goto the next page. Or you can also download the example .capx file.