test

test

// bouncing ball example

var x, y, dx, dy;
var r = 30; // radius
var g = 0.1; // gravity

var mySnd;

function preload() {
    mySnd = loadSound("https://courses.ideate.cmu.edu/15-104/f2018/wp-content/uploads/2018/12/139875__y89312__44-1.wav");
    mySnd.setVolume(0.5);
}


function setup() {
    createCanvas(400, 400);
    x = 200;
    y = 40;
    dx = 0;
    dy = 0;
}

function draw() {
    background(200, 220, 250);
    fill(0, 250, 0);
    ellipse(x, y, r, r);
    x = x + dx;
    y = y + dy;
    var travel_since_bounce = y - (height - r / 2);
    if (travel_since_bounce > 0) {
        // after bounce we should have gone in the other direction
        // so undo travel and travel in the opposite direction,
        // therefore we need to subtract travel * 2 from y
        y = y - travel_since_bounce * 2;
        dy = -dy; // change direction
        mySnd.play();
    }
    dy = dy + g; // gravity
}

Leave a Reply