Hello everyone,
I’m attempting to simulate a light clock a la Einstein’s famous though experiment in p5.
I’ve made mirror and photon objects, and have utilised those in a meta-object called “clock”.
I want to have one static clock and one moving clock, to show the difference in distance that the photon travels in the same duration.
When I call staticClock.displayStaticClock();
all is good, it displays fine. The same when I call movingClock.displayClock();
the clock displays and moves in the manner I want it to (for now, I haven’t got to the actual timing yet, just making sure I can get the thing to move first!
So here’s the kicker - when I call both, either the static clock disappears or it moves at the same time as the moving clock, making it invisible…
I’m pulling my hair out, any help on this would be appreciated.
Here’s a link to my sketch: [https://editor.p5js.org/markAitcheson/sketches/u6UweqK02]
Edit Also, I have a collision function which seems to work for both my top and bottom mirror, when I call the top and bottom collide functions separately, neither of them work!
let movingClock;
let staticClock;
let xSpeed = 1;
let ySpeed = -1;
function setup() {
createCanvas(600, 120);
movingClock = new clock();
staticClock = new clock();
}
function draw() {
background(60);
staticClock.displayStaticClock();
movingClock.move();
movingClock.displayClock();
movingClock.collide();
}
class mirror {
constructor(startX, startY, width, height, radius) {
this.x = startX;
this.y = startY;
this.w = width;
this.h = height;
this.r = radius;
}
show() {
rect(this.x, this.y, this.w, this.h, this.r);
}
move() {
this.x += xSpeed;
}
collide() {
if (this.x < 0 || this.x > width - 100) {
xSpeed *= -1;
}
}
}
class photon {
constructor(startX, startY, radius, xSpeed, ySpeed) {
this.x = startX;
this.y = startY;
this.r = radius;
//this.sec = second();
}
move() {
this.x += xSpeed;
this.y += ySpeed;
}
moveStatic() {
this.y += ySpeed;
}
collide() {
if (this.y < 20 || this.y > height - 20) {
ySpeed *= -1;
}
if (this.x < 0 || this.x > width - 60) {
xSpeed *= -1;
}
}
show() {
ellipse(this.x, this.y, this.r);
}
}
let mirrorTop;
let mirrorBottom;
let light;
class clock {
constructor(startX) {
this.x = startX;
mirrorTop = new mirror(0, 0, 60, 15, 3);
mirrorBottom = new mirror(0, height - 15, 60, 15, 3);
light = new photon(30, height - 20, 10, 1, 1);
}
move() {
mirrorTop.move();
mirrorBottom.move();
}
collide() {
mirrorTop.collide();
//mirrorBottom.collide();
}
displayClock() {
mirrorTop.show();
mirrorBottom.show();
light.move();
light.show();
light.collide();
}
displayStaticClock() {
mirrorTop.show();
mirrorBottom.show();
light.moveStatic();
light.show();
light.collide();
}
}