Wiki

Clone wiki

Core / dragMe

The Draggable Rectangle

Here's a simple class that makes a rect you can drag around the screen (code provided by Simeon Nasilowski).

-- DragMe
DragMe = class()

function DragMe:init()
    self.pos = vec2(0,0)
    self.size = 200
end

function DragMe:draw()
    pushStyle()

    fill(255,0,0)

    rectMode(CENTER)
    rect(self.pos.x, self.pos.y, self.size, self.size)

    popStyle()
end

function DragMe:hit(point)
    if point.x > (self.pos.x - self.size/2) and
       point.x < (self.pos.x + self.size/2) and
       point.y > (self.pos.y - self.size/2) and
       point.y < (self.pos.y + self.size/2) then
        return true
    end        
    return false
end

function DragMe:touched(touch)
    if self:hit( vec2(touch.x, touch.y) ) and
       touch.state == MOVING then
        self.pos = self.pos + vec2( touch.deltaX, touch.deltaY )
    end
end

And here's the Main file:

-- Main
function setup()
    box = DragMe()
end

function draw()
    background(0)        
    box:draw()
end

function touched(touch)
    box:touched(touch)
end

Simeon notes: This won't do touch tracking - that is, if you drag fast enough that your touch jumps out of the rect in one frame, the rect will lose tracking of the touch.

This can be fixed by checking if the touch hit on touch.state == BEGAN, and then tracking the position with the touch regardless until the touch state is ENDED.

(First published in this forum discussion.)

Updated