How do I get touches to register in a class

Like making a sprite go to where you touch but the sprite is in a class?

Here you go:

##main

-- Touchable sprite

function setup()
    tsprite = TSprite(10,50,"Platformer Art:Crate")
end

function draw()
    background(40, 40, 50)
    strokeWidth(5)
    tsprite:draw()
end

function touched(touch)
    tsprite:touched(touch)
end

##TSprite class

TSprite = class()

function TSprite:init(x, y, spr)
    self.x = x
    self.y = y
    self.spr = spr
end

function TSprite:draw()
    sprite(self.spr, self.x, self.y)
end

function TSprite:touched(touch)
    self.x = touch.x
    self.y = touch.y
end

Wow you should do a tutorial series, very easy to understand and thanks again @Dalorbi for the quick reply :slight_smile:

Drag 1 finger around the screen, then 2, then 3.

edit: I’m left handed, so if you’re right handed, change line self.x=t.x+100 to self.x=t.x-100 .


displayMode(FULLSCREEN)

function setup()
    itab={}    -- touch id table    
    stab={}    -- sprite table
    table.insert(stab,sp(0,0,readImage("Planet Cute:Character Boy")))
    table.insert(stab,sp(0,0,readImage("Planet Cute:Character Pink Girl")))
    table.insert(stab,sp(0,0,readImage("Planet Cute:Character Princess Girl")))
end

function draw()
    background(40, 40, 50)
    for b in pairs(stab) do
        stab[b]:draw()
    end
end

function touched(t)
    if t.state==BEGAN then
        table.insert(itab,t.id)
    elseif t.state==ENDED then
        for a,b in pairs(itab) do
            if t.id==itab[a] then
                table.remove(itab,a)
            end
        end
    end
    for b in pairs(stab) do
        stab[b]:touched(t)
    end
end


sp=class()

function sp:init(x,y,spr)
    self.x=0
    self.y=0
    self.sp=spr
    self.tab=#stab+1
end

function sp:draw()
    sprite(self.sp,self.x,self.y)
end

function sp:touched(t)
    if t.state==MOVING then
        for z=1,#itab do
            if t.id==itab[z] and self.tab==z then
                self.x=t.x+100
                self.y=t.y
            end
        end
    end
end

This is weird when I put it into my code I get an error: attempt to index local value: touch, a nil value

Thanks for the reply @dave1707 but I don’t get what your trying to show me?

Oops never mind everything is good i was not supposed to call class:touched(touch) in main:draw :stuck_out_tongue: