let target = [150, 30];
let Tx = [300, 350];
let Rx = [50, 300];
let tx_target_distance;
let rx_target_distance;

let v_target = [6, 5];
let v_target_vec;
let target_speed;
let framerate = 60;

function setup() {
  createCanvas(400, 400);
  frameRate(framerate);
  target_speed = sqrt(sq(v_target[0]) + sq(v_target[1]));
  v_target_vec = createVector(v_target[0], v_target[1]);
}

let toTarget = [];
let toRx = [];

let f = 2; // Hz
let c = 50; // pixels/sec
let lambda = c / f;

let dt = 1 / framerate;
let distance_per_tick = (c / f) * dt;
let time = 0;
function draw() {
  time += dt;

  target[0] += v_target[0] * dt;
  target[1] += v_target[1] * dt;

  tx_target_distance = dist(target[0], target[1], Tx[0], Tx[1]);
  rx_target_distance = dist(target[0], target[1], Rx[0], Rx[1]);

  background(220);
  strokeWeight(10);
  stroke("black");
  noFill();
  point(target[0], target[1]);
  point(Tx[0], Tx[1]);
  point(Rx[0], Rx[1]);

  if (time - int(time) < dt) {
    toTarget.push(0);
  }
  strokeWeight(1);
  stroke("blue");
  for (let x in toTarget) {
    toTarget[x] += distance_per_tick;
    circle(Tx[0], Tx[1], 2 * toTarget[x]);
    if (toTarget[x] > tx_target_distance) {
      toTarget.shift();
      toRx.push([target[0], target[1], 0]);
    }
  }

  stroke("green");
  for (let x of toRx) {
    circle(x[0], x[1], 2 * x[2]);
    x[2] += distance_per_tick;
    if (dist(x[0], x[1], Rx[0], Rx[1]) < x[2]) {
      toRx.shift();
    }
  }
  stroke("red");
  line(
    target[0],
    target[1],
    target[0] + 100 * v_target[0],
    target[1] + 100 * v_target[1],
  );
  line(target[0], target[1], Rx[0], Rx[1]);
  line(target[0], target[1], Tx[0], Tx[1]);

  let phi_T = v_target_vec.angleBetween(
    createVector(Tx[0] - target[0], Tx[1] - target[1]),
  );
  let phi_R = v_target_vec.angleBetween(
    createVector(Rx[0] - target[0], Rx[1] - target[1]),
  );
  let psi = target_speed * (cos(phi_R) + cos(phi_T));
  let apparent_freq = psi / lambda;
  print(apparent_freq);
}
