Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Using a Class to Make Objects

Hi all, it's me once again with questions. I wanted to see if anyone could help me on making a simple program that wherever you touch on the screen a rectangle appears. But I want each rectangle to be independent per se. As in they each have their own coordinates and can be identified individually amongst the others. I'm pretty sure that a class is the way to go (probably the only way) but I can't seem to write one that works and I feel that it is my lack of "syntax knowledge" on how to use classes (if that makes sense) that's making this more problematic.

Thank you in advance! :)

Tagged:

Comments

  • IgnatzIgnatz Mod
    Posts: 5,396

    I've written quite a number of posts on classes, and there are some good Lua class tutorials out there, too. I suggest you read everything you can find and try again.

    My stuff is below:
    https://coolcodea.wordpress.com/2013/06/19/index-of-posts/

  • dave1707dave1707 Mod
    Posts: 7,469

    @Perscirious Classes aren't the only way to do what you want. Here's an example that uses just a table to create rectangles where you touch a blank screen area. If you touch a rectangle, you can move it around.

    displayMode(FULLSCREEN)
    
    function setup()
        rectMode(CENTER)
        tab={}
    end
    
    function draw()
        background(40, 40, 50)
        fill(255)
        for a,b in pairs(tab) do
            rect(b.x,b.y,80,40)
        end
    end
    
    function touched(t)
        if t.state==BEGAN then
            val=0
            for a,b in pairs(tab) do
                if t.x>b.x-40 and t.x<t.x+40 and t.y>b.y-20 and t.y<b.y+20 then
                    val=a
                end
            end
            if val==0 then
                table.insert(tab,vec2(t.x,t.y))
            end
        end
        if t.state==MOVING and val>0 then
            tab[val].x=t.x
            tab[val].y=t.y      
        end
    end
    
Sign In or Register to comment.