You can try using my UI5 library, which has built in dragging features.
If you don’t want to go through that process, you can have a variable (or attribute of a sprite).
When the mouse is pressed on the sprite, set the variable to
When the mouse is released, set the variable to
Each frame, if the variable is true, move the sprite’s position to the mouse’s position.
However, note that the center of the sprite will always be where the mouse is. When initially dragging the sprite, it will appear as if the sprite ‘teleported’ to the mouse. To fix this, we can add 2 more variables: relativeX, relativeY. To avoid ambiguity, the variable I mentioned above will be called ‘Held.’
- When the mouse is pressed on the sprite, set Held to
true. Also set relativeX to the difference between sprite.x and mouseX along with relativeY to the difference between sprite.y and mouseY.
- When the mouse is released, set Held to
false. relativeX and relativeY do not need to be changed.
- Each frame, if Held is true, move the sprite’s position to the mouse’s position plus relativeX and relativeY.
You can check out the end result here.