Forum Archive

DraggableImages demo code

ccc

I wanted to create some games (checkers, chess, etc.) so the first step is DraggableImages...

Please let me know if you spot issues.

https://gist.github.com/cclauss/5380169

omz

Looks good. One minor issue I see is that the dragged image "jumps" when you don't start the touch exactly at the center. You could avoid this pretty easily like this:

def touch_moved(self, touch):
    if self.touchedLayer:
        self.touchedLayer.frame.x += touch.location.x - touch.prev_location.x
        self.touchedLayer.frame.y += touch.location.y - touch.prev_location.y

(There are other ways of course, but this would be the easiest)

Btw, you don't have to iterate over all the layers in the draw method, you can update and draw just the root layer instead:

self.root_layer.update(self.dt)
self.root_layer.draw()

This will automatically draw all the child layers as well.

If you want to enable dragging more than one image simultaneously (multi-touch), you could do it like this:

def touch_moved(self, touch):
    if touch.layer != self.root_layer:
        touch.layer.frame.x += touch.location.x - touch.prev_location.x
        touch.layer.frame.y += touch.location.y - touch.prev_location.y