Displaying text letter by letter

Hello everyone, I’m a school-level beginner programmer and I’m trying to display text letter by letter. There is something that I don’t understand about my code, because it works perfectly on a console but just doesn’t update the display window until the function is finished. I was wondering if there is a way to force the update or if maybe there could be a better script for this (of those that I could understand).

def textAnimated(toType,x,y,nxt):
    background(0)
    global t
    global toTypeR
    if nxt==False:
        t=0
        toTypeR=""
    st=millis()
    s=st
    toTypeR=toTypeR+toType[t]
    text(toTypeR,x,y)
    while s<st+100:
        s=millis()
    t+=1
    if t<len(toType):
        textAnimated(toType,x,y,True)

Thank you very much!

2 Likes

Welcome @Polo

Processing uses the draw() function to draw to the display window. You should adapt your code to work with this structure.

def setup():
    # this code executes once at the start
    size(200, 200)
    frameRate(5)

def draw():
    # this code executes every frame
    background(random(255))
    text('Hello, World', 65, 105)
2 Likes

Welcome to the Processing Community, @Polo!

Your textAnimated function contains this conditional block:

    if t<len(toType):
        textAnimated(toType,x,y,True)

Therefore, the function calls itself. Are you intentionally writing the function as a recursion?

EDITED 2x on July 7, 2021 to add the following:

To follow @tabreturn’s advice, you can add this prior to your function definition:

toTypeR = ""
t = 0
def setup():
    size(400, 100)
    noLoop()
def draw():
    textAnimated("This is the text!", 0, 20, True)

You may see the entire text appear all at once, which does not seem to be what you wanted.

Fitting the recursion into the code structure of a Processing sketch to implement an animation can be tricky. You may benefit from reading the following discussion thread for guidance:

Is my fractal optimized? Could it animate?

Though it focuses on Java Mode, it does include a Python Mode example.

Also see Tower Hanoi - Why recursive draw only first and last steps?.

3 Likes

Thank you very much, I’ll try that. I was simply wondering if it was possible to write such a function outside of draw.

1 Like