Tween "glitchy" and not smooth

I’m making a tutorial class to demonstrate how to use the ui in the app that I am making, but am confused on the use of Tweens. This is my first time using tables and Tweens in my code, so i dont know if this is correct. When i use the tween in this function, it starts smooth and then goes back and forth within several frames before going to the end. Here’s the code;


function Tutorial:init()
    self.position = {
    x = WIDTH/2 -250,
    y = HEIGHT/2 +125 
     }
end

function Tutorial:draw()

    self.destx = WIDTH/2
    background(255, 0, 0, 255)
    tween (1, self.position, {x = self.destx, y = HEIGHT/2+125},      
       tween.easing.linear)
    fill(82, 255, 0, 255)
    ellipse (self.position.x, self.position.y, 100)
end

function Tutorial:touched(touch)
    -- Codea does not automatically call this method
end

tween() is meant to be called once, not in draw. The way you’re doing it, it’s creating a new tween 60 times per second, and each one is trying to assign the variable to what it thinks it should be. Here’s a working version, tap to make it start:


--# Main
-- Tween Help

-- Use this function to perform your initial setup
function setup()
    print("Hello World!")
    tut = Tutorial()
end

-- This function gets called once every frame
function draw()
    -- This sets a dark background color 
    background(40, 40, 50)
    
    -- This sets the line thickness
    strokeWidth(5)

    -- Do your drawing here
    tut:draw()
end

function touched(touch)
    if touch.state == BEGAN then
        tut:start()
    end
end


--# Tutorial
Tutorial = class()

function Tutorial:init()
    self.destx = WIDTH/2
    self.position = {
    x = WIDTH/2 -250,
    y = HEIGHT/2 +125 
     }
end

function Tutorial:start()
    tween(1, self.position, {x = self.destx})
end

function Tutorial:draw()
    background(255, 0, 0, 255)
    fill(82, 255, 0, 255)
    ellipse (self.position.x, self.position.y, 100)
end

function Tutorial:touched(touch)
    -- Codea does not automatically call this method
end

I also removed some unnecessary code in the tween call - you don’t have to specify the easing type (it’s linear by default), and if you have x and y in the target table, but you only want to change x, you don’t have to even have to include the y.

Ok, thanks @skythecoder, that makes sense

@Mr_Ninja - a tween should not be started in the draw function - at least, don’t restart it every time you run draw - no wonder you are having problems

Think of a tween as a for loop that interpolates some values that you have set. Every time draw runs, the tween calculates how much time has passed, and updates the values.

So a tween should be started outside of draw, and then the draw function will update it.

@Mr_Ninja as a side note, self is also a table so you could mak your code shorter by putting:

self.x=aValue
self.y=AnnotherValue
tween(aDuration,self,{x=destinationX,y=destinationY)