Drawing class objects

Hello everyone. I have been working on a small project to do with lines, and drawing. It’s a test game to help me study. I have run into a problem.

Line = class()

function Line:init(x,y,x2,y2)
    
    self.x = x
    self.y = y
    self.x2 = x2
    self.y2 = y2
    
    
end

function Line:draw()
    
    pushStyle()
    stroke(255, 255, 255, 255)
    strokeWidth(25)
    line(self.x, self.y, self.x2, self.y2)
    popStyle()
    
end


-- LineDrawer

function setup()
    
    parameter.number("X1", 0, WIDTH, 100)
    parameter.number("X2", 0, WIDTH, WIDTH - 100)
    parameter.number("Y1", 0, HEIGHT, 100)
    parameter.number("Y2", 0, HEIGHT, HEIGHT - 100)
    
    newLine = Line(X1, Y1, X2, Y2)
    
end


function draw()
    
    background(40, 40, 50)
    
 newLine:draw()   


    

    
    
end

I want the line (newLine) to update every time the parameter value changes. It doesn’t. Instead it stays the same. How can I draw it and allow it to update? Is it possible?

Parameters have a callback function that gets called anytime a parameter value changes. In that callback function, you can update the newLine x,y values. See the built in reference for more info.

You could update every frame by adding this to draw:

newLine.x = X1
newLine.y = Y1
newLine.x2 = X2
newLine.y2 = Y2

Or, you could add callbacks to each parameter:


function setup()

    -- must define newLine first so that the closures below capture it
    newLine = Line(0,0,0,0)

    parameter.number("X1", 0, WIDTH, 100, function(new) newLine.x = new end )
    parameter.number("X2", 0, WIDTH, WIDTH - 100, function(new) newLine.x2 = new end)
    parameter.number("Y1", 0, HEIGHT, 100, function(new) newLine.y = new end)
    parameter.number("Y2", 0, HEIGHT, HEIGHT - 100, function(new) newLine.y2 = new end)

end

Here’s another example of using the callback function.

Line = class()

function Line:init(x,y,x2,y2)
    self.x = x
    self.y = y
    self.x2 = x2
    self.y2 = y2
end

function Line:draw()
    pushStyle()
    stroke(255, 255, 255, 255)
    strokeWidth(25)
    line(self.x, self.y, self.x2, self.y2)
    popStyle()
end

function Line:change()
    newLine.x=X1
    newLine.y=Y1
    newLine.x2=X2
    newLine.y2=Y2
end

-- LineDrawer

function setup()
    newLine = Line(X1, Y1, X2, Y2)
    parameter.number("X1",0,WIDTH,100,newLine.change)
    parameter.number("Y1",0,WIDTH,WIDTH-100,newLine.change)
    parameter.number("X2",0,HEIGHT,100,newLine.change)
    parameter.number("Y2",0,HEIGHT,HEIGHT-100,newLine.change)
end

function draw()
    background(40, 40, 50)
    newLine:draw()   
end

@dave1707 Cheers. I had a picture it had to do with callbacks.