Last active
October 15, 2020 13:29
-
-
Save r4j0x00/c4eb4497e5b3a57744b78c5834344316 to your computer and use it in GitHub Desktop.
Compute pi digits with collisions p5.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let a = null; | |
let b = null; | |
let collisions = 0; | |
let digits = 6; | |
let steps = Math.pow(10, digits); | |
class Block { | |
constructor(x, mass, velocity) { | |
this.x = x; | |
this.y = windowHeight*0.9; | |
this.width = 100; | |
this.height = -100; | |
this.velocity = -velocity; | |
this.mass = mass; | |
} | |
collide(block) { | |
let bx1 = block.x; | |
let bx2 = bx1 + block.width; | |
let ax1 = this.x; | |
let ax2 = ax1 + this.width; | |
if(ax1 > bx1) | |
return (bx2 >= ax1); | |
return (ax2 >= bx1); | |
} | |
hitWall() { | |
return (this.x <= 0); | |
} | |
updateCollision(block) { | |
if(this.collide(block)) { | |
collisions++; | |
let v1 = (((this.mass-block.mass)/(block.mass+this.mass)) * this.velocity) + (2*block.mass*block.velocity)/(block.mass+this.mass); | |
let v2 = (((block.mass-this.mass)/(block.mass+this.mass)) * block.velocity) + (2*this.mass*this.velocity)/(block.mass+this.mass); | |
this.velocity = v1; | |
block.velocity = v2; | |
} | |
} | |
update() { | |
if(this.hitWall()) { | |
collisions++; | |
this.velocity *= -1; | |
} | |
this.x += this.velocity; | |
} | |
draw() { | |
rect(this.x, this.y, this.width, this.height); | |
} | |
} | |
function setup() { | |
createCanvas(windowWidth, windowHeight); | |
a = new Block(windowWidth/2, Math.pow(steps,2), 1/steps); | |
b = new Block(300, 1, 0); | |
textSize(32); | |
} | |
function draw() { | |
background(39, 41, 48); | |
text('Collisions: '+collisions, 10, 30); | |
fill(107, 0, 4); | |
rect(0, windowHeight*0.9, windowWidth, windowHeight*0.9); | |
fill(82, 235, 255); | |
for(i=0;i<steps;++i) { | |
a.update(); | |
b.update(); | |
a.updateCollision(b); | |
} | |
a.draw(); | |
b.draw(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://www.youtube.com/watch?v=m1Mmph4q6Pc