Avoid neighbours
A Perlin noise flow field with added behaviour to avoid neighbours.
import coracle.*
import kotlin.math.cos
import kotlin.math.sin
class PerlinNoiseDrawing2: Drawing() {
val agents = mutableListOf()
val agentCount = 450
var scale = 0.01f
var speed = 1.2f
var elapsed = 0
var frame = 0
override fun setup() {
(450, 450)
size
(agentCount){
repeat.add(Agent(random(width), random(height)))
agents}
}
override fun draw() {
(0xffffff, 0.75f)
stroke++
frame.forEach { agent ->
agents
agent.avoidNearest()
.updateFlowField()
.checkBounds()
.draw()
}
++
elapsedif(elapsed > 350){
.newSeed()
Perlin= random(0.001f, 0.02f)
scale = random(0.8f, 2f)
speed = 0
elapsed }
(0x000000, 0.035f)
foreground}
class Agent(x: Float, y: Float): Vector(x, y) {
inner
var age = 0
var deathAge = random(100, 340)
fun updateFlowField(): Agent{
if(frame % 3 != 0) return this
++
ageval a = TAU * Perlin.noise(x * scale, y * scale)
var direction = direction(Vector( x + (cos(a)).toFloat(), y + (sin(a) ).toFloat()))
.normalize()
direction*= 0.8f
direction this.x += direction.x * speed
this.y += direction.y * speed
return this
}
fun avoidNearest(): Agent{
var closestDistance = Float.MAX_VALUE
var closestIndex = -1
.forEachIndexed { index, other ->
agentsif(other != this){
val distance = distance(other)
if(distance < closestDistance){
= index
closestIndex = distance
closestDistance }
}
}
val closest = agents[closestIndex]
if(distance(closest) < 35) {
var direction = direction(closest)
.normalize()
direction*= -0.3f
direction
this.x += direction.x
this.y += direction.y
}
return this
}
fun checkBounds(): Agent{
if(age >= deathAge || x < 0 || x > width || y < 0 || y > height ){
= random(width)
x = random(height)
y = 0
age = random(100, 340)
deathAge }
return this
}
fun draw() = point(x, y)
}
}