// ball size float r; // position, velocity and angle float x, y, v, vang, a, aang; // time step float ts = 0.5; void setup() { size(300,300); background(255); // white ellipseMode(RADIUS); r = 10; x = r; y = height - r; v = 10.0; vang = 70; a = 0.3; aang = 270; } void draw() { clearToWhite(); updateVelocity(); updatePosition(); checkBounceX(); checkBounceY(); drawBall(x, y); } void clearToWhite() { fill(255,70); noStroke(); rect(0,0,width,height); } void checkBounceX() { if( x < r || width - r < x ) { if( vang < 180 ) { vang = 90 - (vang - 90); } else { vang = 270 - (vang - 270); } if( x < r ) { x = r; } else { x = width - r; } } } void checkBounceY() { if( y < r || height - r < y ) { if( 90 < vang && vang < 270 ) { vang = 180 - (vang - 180); } else { vang = 360 - (vang - 360); } if( y < r ) { y = r; } else { y = height - r; } } } void updateVelocity() { float ax = a * cos(radians(aang)); float ay = a * -sin(radians(aang)); float vx = v * cos(radians(vang)); float vy = v * -sin(radians(vang)); vx = vx + ts * ax; vy = vy + ts * ay; v = sqrt(vx * vx + vy * vy); float tmp = vx / v; float rad = acos(tmp); float ang = degrees(rad); if( 0 < vy ) { ang = 360 - ang; } vang = ang; } void updatePosition() { float vx = v * cos(radians(vang)); float vy = v * -sin(radians(vang)); x = x + ts * vx; y = y + ts * vy; } void drawBall(float x, float y) { fill(255); stroke(0); ellipse(x, y, r, r); }