Trouble with dragging

Hi,

I’m still extremely new to this, so please bear with me if I’m missing something obvious. I decided to try to implement dragging in the PiratePig project, so that the tile you’re attempting to swap tracks mouse movement. I added the following four lines to the TileContainer_onMouseDown function:

originalTileX = event.target.x;
originalTileY = event.target.y;
trace("Mouse click at (" + event.stageX + ", " + event.stageY + ")");
trace("Picked up tile at (" + originalTileX + ", " + originalTileY + ")");

as well as the following function:

private function TileContainer_onMouseMove (event:MouseEvent):Void {
   if (selectedTile != null) {
     var differenceX = event.stageX - cacheMouse.x;
     var differenceY = event.stageY - cacheMouse.y;
     selectedTile.x = originalTileX + differenceX;
     selectedTile.y = originalTileY + differenceY;
     trace("Mouse moved to(" + event.stageX + ", " + event.stageY + ")");
     trace("Tile moved to (" + selectedTile.x + ", " + selectedTile.y + ")");
   }   
}

(Note that cacheMouse is just a Point containing the event.stageX and event.stageY properties from the original MOUSE_DOWN event.)

The strange behavior that I’m seeing is that as I drag the mouse, the tile seems to follow me only about halfway in both the X and Y directions (that is, the farther I move away from the origin, the greater the distance between the tile and the mouse pointer). However, the difference between the X and Y coordinates of the mouse event and those of the tile remains exactly the same.

Try this:

selectedTile = event.target;
originalTileX = selectedTile.x;
originalTileY = selectedTile.y;
cacheMouse.x = selectedTile.parent.mouseX;
cacheMouse.y = selectedTile.parent.mouseY;

Then:

var differenceX = selectedTile.parent.mouseX - cacheMouse.x;
var differenceY = selectedTile.parent.mouseY - cacheMouse.y;
selectedTile.x = originalTileX + differenceX;
selectedTile.y = originalTileY + differenceY;

PiratePig uses some scaling, and when scaling’s involved, it’s easiest and safest to let OpenFL calculate mouseX and mouseY for you.

Thanks, that worked great. In retrospect it makes total sense but I’m not sure how I might have found this information on my own. Is there any kind of base reference I can read that explains the object model that I’m working with?

Flash and/or OpenFl will calculate the local and global coordinates for you. When you’ve got it all working properly you could rotate and scale the app however you like and it would still work.

stageX gives the x coordinate with reference to the stage’s coordinate system. If you move, scale or rotate the game, then that’s no longer relevant.