سؤال

when I drag my sprite, instead of dragging it from the same position, it will re-locate the sprite with the currently clicked X, Y position. this is because the sprite will draw right away on the clicked position.

    if (super.mouseDragging && System.currentTimeMillis() - super.mouseTimer >= 200) {
        PosX = super.mouseX;
        PosY = super.mouseY;
    }

PosX/PosY = the position of the sprite.

How do I exactly make it so when you click on the sprite, it won't relocate it with the new X,Y and just process the dragging smoothly? I thought of adding offsets off the current position but I am not sure how exactly.

Is there a proper way of doing this?

Example of good dragging:

http://scratch.mit.edu/projects/2098337/

        grabbedX = super.mouseX - PosX;
        grabbedY = super.mouseY - PosY;
        PosX = super.mouseX - grabbedX;
        PosY = super.mouseY - grabbedY;

X: -108 Y: -82
X: 108 Y: 83
X: -108 Y: -83
X: 108 Y: 84
X: -108 Y: -84
X: 107 Y: 85
X: -107 Y: -85
X: 107 Y: 85
X: -107 Y: -85
X: 107 Y: 85
X: -107 Y: -85


    if (x >= client.PosX && x <= client.PosX + 229 
            && y >= client.PosY && y <= client.PosY + 70) {
        this.mouseDragging = true;
        this.mouseTimer = System.currentTimeMillis();
        System.out.println("yes");
    }
    else {
        System.out.println("no");
    }
هل كانت مفيدة؟

المحلول

You got it. Calculate the offset between the object origin and the clicked position, then maintain the offset as you set the position during dragging. If you don't do this, you'll see that initial "jump" as it is sets the object's origin at the clicked mouse position (that is unless you happen to grab the object at its origin).

I normally do something like this when the object is "grabbed". This is calculated once, say for example in your mousePressed() method:

Point origin = thing.getPosition();
scene.grabbedOffsetX = (mousePos.x - origin.x);
scene.grabbedOffsetY = (mousePos.y - origin.y);

Then when you redraw during the dragging operation you factor in the previously calculated offset. The offset remains constant throughout the dragging operation. This would be for example in your mouseDragged() method:

thing.setPosition(mousePos.x - grabbedOffsetX, mousePos.y - grabbedOffsetY);
repaint();
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top