Skip to content

Interactive truchet

Move your mouse along the screen to spin the truchet tiles.
Double click to change the shape of the tiles.

A grid of Truchet tiles, spun every so way

let a = {[[20 + 40 * 10, 20 + 40 * 6]]: Math.PI/2}
let va = {}
let truchet = 0
var setup, windowResized

setup = windowResized = function() {
  createCanvas(windowWidth, windowHeight);
  textAlign(CENTER, CENTER)
  
  for (let x = 20; x < width; x += 40) {
    for (let y = 20; y < height; y += 40) {
      a[[x,y]] = a[[x,y]] || 0
      va[[x,y]] = va[[x,y]] || 0
    }
  }
}

function draw() {
  background(220)
  
  strokeWeight(2)
  let totalVa = 0
  for (let x = 20; x < width; x += 40) {
    for (let y = 20; y < height; y += 40) {
      a[[x,y]] += va[[x,y]]
      let corr = sin(4 * a[[x,y]] + PI) / 4
      let ncorr = (
        sin(2 * (a[[x,y]] - a[[x,y-40]] || 0) + PI) / 4 +
        sin(2 * (a[[x,y]] - a[[x,y+40]] || 0) + PI) / 4 +
        sin(2 * (a[[x,y]] - a[[x-40,y]] || 0) + PI) / 4 +
        sin(2 * (a[[x,y]] - a[[x+40,y]] || 0) + PI) / 4
      ) / 4
      let d = mag(mouseX - x, mouseY - y)
      let t = (mouseX - x) * (mouseY - pmouseY) - (mouseY - y) * (mouseX - pmouseX)
      va[[x,y]] += t / max(d, 5) / (max(d, 40) ** 2) * (mouseIsPressed ? 5 : 3)
      va[[x,y]] += corr / 4 * 0.05
      va[[x,y]] += ncorr / 4 * 0.05
      va[[x,y]] *= 0.93
    }
  }
  for (let x = 20; x < width; x += 40) {
    for (let y = 20; y < height; y += 40) {
      let aligned = sin(2 * a[[x,y]] + PI) ** 2
      let corr = sin(4 * a[[x,y]] + PI) / 4
      // if (floor(map(aligned, 1, 0, 0, 1.999)) != z) continue
      
      resetMatrix()
      translate(x + 0.5, y + 0.5)
      rotate(a[[x,y]] + corr)
      // scale(map(aligned, 0, 1, 1, 1/sqrt(2)))
      // stroke(220)
      stroke(map(aligned, 0, 1, 240, 100))
      fill(255)
      rect(-20, -20, 40, 40)
      stroke(0)
      noFill()
      if (truchet == 0) {
        line(-20, -20, 20, 20)
      } else if (truchet == 1) {
        arc(20, -20, 40, 40, PI/2, PI)
        arc(-20, 20, 40, 40, PI*3/2, 0)
      } else if (truchet == 2) {
        fill(220)
        noStroke()
        triangle(-20, -20, 20, -20, 20, 20)
      } else if (truchet == 3) {
        line(-20, 0, 0, 20)
        line(20, 0, 0, -20)
      }
      fill(0)
      noStroke()
    }
  }
}

function doubleClicked() {
  truchet = (truchet + 1) % 4
}

(Originally seen at https://editor.p5js.org/bojidar-bg/sketches/ERHA34QBv)

Experiments tagged p5 (46/85)

Experiments tagged interactive (16/26)

Experiments on this site (46/85)