xxxxxxxxxx
102
// Parameter t, 0 <= t <= 1
// needed for the vehicle to travel the curve
let t = 0
// The current portion of the curve the car is
// travelling along. ab and bc are the end points
// and will be the midpoints between (a,b) and (b,c)
// b is the control point
let curve = { a: undefined,
ab: undefined,
b: undefined,
bc: undefined,
c: undefined }
// Just a line with an arrowhead
function arrow(x1, y1, x2, y2) {
line(x1, y1, x2, y2)
let r = 8 // Arrowhead radius
let u = createVector(x2-x1, y2-y1).normalize()
let a = 0.94, b = 0.34 // Arrowhead half angle
beginShape()
vertex( x2 + (-a * u.x - b * u.y) * r,
y2 + ( b * u.x - a * u.y) * r )
vertex( x2, y2 )
vertex( x2 + (-a * u.x + b * u.y) * r,
y2 + (-b * u.x - a * u.y) * r )
endShape()
}
// Draw a pointer at position p,
// pointing in direction u
function ship(p, u) {
u.mult(8)
let p1 = wrap( p5.Vector.sub(p, u) )
let p2 = wrap( p5.Vector.add(p, u) )
if(p1.dist(p2) > 20) {
return
}
stroke("orange")
strokeWeight(2)
arrow(p1.x, p1.y, p2.x, p2.y)
}
// The ship's position and direction on
// the quadratic bezier curve
// [a, c] = start and end points, b = control pt,
// 0 <= t <= 1
function where_at(a, b, c, t) {
let w = p5.Vector.lerp(a, b, t)
let x = p5.Vector.lerp(b, c, t)
let y = w.lerp(x, t)
x.sub(w).normalize()
ship(y, x)
}
function next_point(prv) {
let ang = random(PI)
return p5.Vector.fromAngle(ang).mult(80).add(prv)
}
function advance() {
t = 0
curve.a = curve.b
curve.b = curve.c
curve.c = next_point(curve.c)
curve.ab = curve.bc
curve.bc = p5.Vector.lerp(curve.b, curve.c, 0.5)
}
function wrap(p) {
return createVector( (p.x + width) % width,
(p.y + height) % height )
}
function setup() {
createCanvas(400, 400);
curve.a = createVector(200, 200)
curve.b = next_point(curve.a)
curve.c = next_point(curve.b)
curve.ab = p5.Vector.lerp(curve.a, curve.b, 0.5)
curve.bc = p5.Vector.lerp(curve.b, curve.c, 0.5)
}
function draw() {
background(0);
stroke(200)
strokeWeight(3)
point(wrap(curve.a))
point(wrap(curve.b))
point(wrap(curve.c))
where_at(curve.ab, curve.b, curve.bc, t)
t = t + 0.02
if(t > 1) advance()
}