Add lines without deleting old ones

Hello!
I made a little game, where I can steer a little bike with Gravity. Now this bike should leave walls behind it.
I made a function for that, in which I draw a line with

line(oldPosX, oldPosY, PosX, PosY)

but the line is only visible for one frame, how can I edit it that the line will be there for 10 seconds?
(In draw function I use background())

Thanks for answers :slight_smile:

For now, you’d need to keep a table of your X,Y values, and draw all of them each frame. This table would get one bigger every draw (and you could probably remove elements from it after a while so it didn’t get bigger forever).

Coming up in 1.2.7, you could use setContext to draw to an image rather than the screen - so each go-round, you’d add one more line segment. Then, in draw() you’d just need to sprite() that image to the screen. Does that make sense?

Made a demo at http://bortels.posterous.com/contextdemo of when I mean by “Coming up in 1.2.7”. Here’s the source:

-- setContext() demo
    
function setup()
    w = WIDTH/2
    h = HEIGHT/2
end

function draw()
    if (s) then
        e = ElapsedTime
        x=math.cos(e*5)*w + w
        y=math.sin(e*3)*h + h
        strokeWidth(5)
        stroke(18, 22, 239, 255)
        if (ox) then
            line(ox, oy, x, y)
        end
        ox=x
        oy=y
        -- draw it
        sprite(s, w, h)     
    else -- s is unitialized
        s=image(WIDTH, HEIGHT)
        setContext(s)
        background(0, 0, 0)
    end
end

It flickers. I know why (buffering) - but it shouldn’t, I think. The image should be drawn every frame, no? Most confusing.

Hm, I think it would be better to make a table, because it should crash if you hit the walls, that doesn’t work with setContext() right?

Heh - wasn’t thinking about your example so much as trying to clarify setContext().

Using a table is the traditional way. Depends on how long you want the trail to get - tables could get very, very large if you went for a long time.

Checking for a crash is going to be something you have to do for yourself - setContext() isn’t going to help in that regard.

@DRP an easy way to leave “trails” is to not clear the screen every frame - so you end up drawing on top of your old image. Here’s how you can do that in Codea:

function setup()
    -- This tells Codea to copy buffers so you don't get flickering
    backingMode(RETAINED)
end

function draw()
    -- We don't call background
    -- Instead draw a rect over the whole screen with some transparency 
    -- Edit the opacity to change the speed at which the trails fade out
    noSmooth()
    fill(0, 0, 0, 100)
    rect(0, 0, WIDTH, HEIGHT)

    -- Draw your stuff and move it 
    line(oldPosX, oldPosY, PosX, PosY)
end

Ah okay, I’ll try that. Thanks for answers!