Quadcopter with Vectors
Highlight the code and copy it.
Then, go to p5js.org and paste the code in the editor.
Hit the "run" button, watch what happens.
Make adjustments to the code, the hit the "run" button again.
Repeat. :)
let quadcopter;
function setup() {
createCanvas(600, 400);
quadcopter = new Quadcopter(width / 2, height / 2);
}
function draw() {
background(220);
// Apply forces based on user input
if (keyIsDown(UP_ARROW)) {
quadcopter.applyThrust(-0.1);
}
if (keyIsDown(DOWN_ARROW)) {
quadcopter.applyThrust(0.1);
}
if (keyIsDown(LEFT_ARROW)) {
quadcopter.rotate(-0.1);
}
if (keyIsDown(RIGHT_ARROW)) {
quadcopter.rotate(0.1);
}
// Update and display the quadcopter
quadcopter.update();
quadcopter.display();
}
class Quadcopter {
constructor(x, y) {
this.position = createVector(x, y);
this.velocity = createVector();
this.acceleration = createVector();
this.angle = 0;
}
applyThrust(amount) {
let force = p5.Vector.fromAngle(this.angle);
force.mult(amount);
this.acceleration.add(force);
}
rotate(angle) {
this.angle += angle;
}
update() {
this.velocity.add(this.acceleration);
this.position.add(this.velocity);
this.acceleration.mult(0);
}
display() {
push();
translate(this.position.x, this.position.y);
rotate(this.angle);
rectMode(CENTER);
fill(100);
// Body
rect(0, 0, 60, 20);
// Rotors
fill(0);
ellipse(-20, -5, 10);
ellipse(20, -5, 10);
ellipse(-20, 5, 10);
ellipse(20, 5, 10);
// Draw vectors
drawVector(this.acceleration, 0, 0, 100, color(0, 255, 0));
drawVector(this.velocity, 0, 0, 10, color(0, 0, 255));
pop();
}
}
// Function to draw vectors as arrows
function drawVector(v, x, y, s, col) {
push();
translate(x, y);
stroke(col);
line(0, 0, v.x * s, v.y * s);
let arrowSize = 4;
rotate(v.heading());
translate(v.mag() * s, 0);
triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);
pop();
}