Reset sketch in p5js

Viewed 2436

so i'm playing around with p5js and made a ball bounce while at the same time lose momentum after each bounce. I want to be able to make the ball reset after 30 seconds or a minute has passed. So i'm basically resetting the sketch after a minute, does anyone how to go about that? i know i have to use minute() or millis() but can't quite figure it out. Here's my code:

var py = 100 // postion y
var spd = 5 // speed
var gravity = 0.1

function setup() {
  createCanvas(400, 400);
}


function draw() {
    background(0);
    fill('red');
    stroke('blue');
    ellipse(width/2, py, 25, 25);
    py = py + spd;
    spd = spd + gravity;

    if (py > 400 || py < 0) {
    spd = -0.95 * spd;
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.0.0/p5.min.js"></script>

1 Answers

Add a function (start) which initialize the parameters and geht the number of milliseconds (thousandths of a second) since starting the sketch (start_time) by millis(). This is the start time of the animation:

let py, spd, gravity, start_time;

function start() {
    py = 100 // postion y
    spd = 5 // speed
    gravity = 0.1
    start_time = millis()
}

Call start() in setup():

function setup() {
    createCanvas(400, 400);
    start();
}

Evaluate in draw() if the current time exceeds the start time plus a time spawn (10 seconds in the following example. If the time is exceeded, the call start() again:

function draw() {

    // [...]

    let current_time = millis();
    let timespane = 10 * 1000; // 10 seconds
    if (current_time > start_time + timespane) {
        start();
    }
}

Optionally, you can restart the process, when a key is pressed, too (e.g. return):

function keyPressed() {
    if (keyCode == RETURN) {
        start();
    }
}

See the example:

let py, spd, gravity, start_time;

function start() {
    py = 100 // postion y
    spd = 5 // speed
    gravity = 0.1
    start_time = millis()
}

function setup() {
    createCanvas(400, 400);
    start();
}

function keyPressed() {
    if (keyCode == RETURN) {
        start();
    }
}

function draw() {
    background(0);
    fill('red');
    stroke('blue');
    ellipse(width/2, py, 25, 25);
    py = py + spd;
    spd = spd + gravity;

    if (py > 400 || py < 0) {
        spd = -0.95 * spd;
    }

    let current_time = millis();
    let timespane = 10 * 1000; // 10 seconds
    if (current_time > start_time + timespane) {
        start();
    }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.0.0/p5.min.js"></script>

Related