I've been experimenting with the jQuery UI draggable/droppable interaction to allow a user to set ships for a game of Battleship. As far as I can tell, droppable interactions work just fine when the drop location is appropriately sized to fit a draggable item, but in the Battleship game, you have ships of several different lengths that fit into a number of squares ranging 2-5.
If you check out this jsFiddle (http://jsfiddle.net/cDqGN/), and mess around with the ship of length two (versus the single block), you'll see it's fairly easy to screw up the drop, with the ship getting stuck between squares, or getting dragged a square to the right of where you intended to drop it.
Does anyone know of any tricks with this interaction to get it to go better?
In particular, this is the interaction as I have it now:
function handleDrop( event, ui ) {
ui.draggable.position( { of: $(this), my: 'left top', at: 'left top' } );
ui.draggable.draggable( 'option', 'revert', false );
}
I found a solution using the grid
option; I added the line below into your handleDrop
function:
ui.draggable.draggable( "option", "grid", [ 52, 52 ] );
(It's 52x52 because the squares are 50x50, plus 1 on each side for the line width). After the ship is dragged to the board, you can then place the ship more precisely.
Here is the update jsFiddle: http://jsfiddle.net/cDqGN/1/
来源:https://stackoverflow.com/questions/18088833/draggable-droppable-for-battleship-game