Search code examples
c#mathdrag-and-dropmouseeventdraggable

Moving object with mouse?


I am currently trying to move a 2D texture in SharpDX. I can successfully move it but it jumps quite a bit every few frames. For example, if I'm dragging from bottom, right to top, left, I'll get an occasional jump where the origin of the image is at 75% bottom, right and then goes back to where it was a few frames later. This is quite odd in my opinion and I think it's possibly due to the event or the mouse position.

I'm updating the texture's position via the MouseMove event on my form:

private void MouseMove(object sender, MouseEventArgs e) {
    if (e.Button == MouseButtons.Left) {
        testSprite.Position = new Vector2(e.X - testSprite.Position.X,
                                          e.Y - testSprite.Position.Y);
    }
}

I think this is mostly due to the way I'm setting the X and Y values. Am I doing the math correctly here or is that what is causing my issue? I chose to write it this way because I don't want the texture's origin (0, 0: top, left) to jump to the mouse position, but instead move smoothly with the mouse from its current position.


Clarity

  • Is my math for assigning X and Y correct?
    • Yes: What else could cause this jump?
    • No: What is the correct math?

While debugging and trying different approaches I have learned that:

  • Setting the Position to just e.X,Y gives smooth movement.
    • However, this jumps to mouse position which is not desired.

Solution

  • Dragging process stages:

    Start at MouseDown:
    - check whether object is touched
    - remember ObjectPos0, MousePos0
    - set isDragging flag (denotes that MouseDown is on object)

    On MouseMove (if isDragging):
    - ObjectPos = ObjectPos0 + (MousePos - MousePos0)
    - redraw

    On MouseUp (if isDragging):
    - fix final position
    - make needed work
    - clear isDragging flag