I am doing the NOC 5.3 Steering Behaviour coding challenge and try to map certain values like: maxSpeed, maxForce, and slowRadius to sliders. I also watched the slider tutorials by dan but struggle to implement this correctly as all examples just change something in the draw loop which seems easier.
Here is my p5.js link: 5.3 Steering Behavior + Sliders for Parameters help
sketch.js:
let slider;
let vehicle;
function setup() {
createCanvas(400, 400);
slider = createSlider(0,10,5);
slider.position(1, 10);
vehicle = new Vehicle(100, 100,slider.value());
}
function draw() {
background(0);
let target = createVector(mouseX, mouseY);
fill(255, 0, 0);
noStroke();
ellipse(target.x, target.y, 32);
let steering = vehicle.arrive(target);
vehicle.applyForce(steering);
vehicle.update();
vehicle.show();
}
vehicle.js:
class Vehicle {
constructor(x, y,speed) {
this.pos = createVector(x, y);
this.vel = createVector(0, 0);
this.acc = createVector(0, 0);
this.maxSpeed = speed;
this.maxForce = 0.4;
this.r = 16;
}
evade(vehicle) {
let pursuit = this.pursue(vehicle);
pursuit.mult(-1);
return pursuit;
}
pursue(vehicle) {
let target = vehicle.pos.copy();
let prediction = vehicle.vel.copy();
prediction.mult(10);
target.add(prediction);
fill(0, 255, 0);
circle(target.x, target.y, 16);
return this.seek(target);
}
arrive(target) {
// 2nd argument true enables the arrival behavior
return this.seek(target, true);
}
flee(target) {
return this.seek(target).mult(-1);
}
seek(target, arrival = false) {
let force = p5.Vector.sub(target, this.pos);
let desiredSpeed = this.maxSpeed;
if (arrival) {
let slowRadius = 50;
let distance = force.mag();
if (distance < slowRadius) {
desiredSpeed = map(distance, 0, slowRadius, 0, this.maxSpeed);
}
}
force.setMag(desiredSpeed);
force.sub(this.vel);
force.limit(this.maxForce);
return force;
}
applyForce(force) {
this.acc.add(force);
}
update() {
this.vel.add(this.acc);
this.vel.limit(this.maxSpeed);
this.pos.add(this.vel);
this.acc.set(0, 0);
}
show() {
stroke(255);
strokeWeight(2);
fill(255);
push();
translate(this.pos.x, this.pos.y);
rotate(this.vel.heading());
circle(0, 0, this.r);
this.angle = this.vel.heading();
stroke(0, 220, 220);
strokeWeight(4);
line(0, 0, this.r / 2, 0);
pop();
}
edges() {
if (this.pos.x > width + this.r) {
this.pos.x = -this.r;
} else if (this.pos.x < -this.r) {
this.pos.x = width + this.r;
}
if (this.pos.y > height + this.r) {
this.pos.y = -this.r;
} else if (this.pos.y < -this.r) {
this.pos.y = height + this.r;
}
}
}
class Target extends Vehicle {
constructor(x, y) {
super(x, y);
this.vel = p5.Vector.random2D();
this.vel.mult(5);
}
show() {
stroke(255);
strokeWeight(2);
fill(255);
push();
translate(this.pos.x, this.pos.y);
rotate(this.vel.heading());
circle(0, 0, this.r);
this.angle = this.vel.heading();
stroke(0, 220, 220);
strokeWeight(4);
line(0, 0, this.r / 2, 0);
pop();
}
}
would appreciate it if someone could help. Thanks!