xxxxxxxxxx
84
let vehicle;
let gravity = 3.711;
function setup() {
createCanvas(400, 400);
vehicle = new Vehicle(width / 2, height / 2);
}
function draw() {
background(220);
vehicle.update();
vehicle.display();
vehicle.checkEdges();
vehicle.applyDrag();
}
class Vehicle {
constructor(x, y) {
this.pos = createVector(x, y);
this.vel = createVector(0, 0);
this.acc = createVector(0, 0);
this.angle = 0;
this.maxSpeed = 4;
this.maxForce = 0.1;
}
applyForce(force) {
this.acc.add(force);
}
update() {
this.vel.add(this.acc);
this.vel.limit(this.maxSpeed);
this.pos.add(this.vel);
this.acc.mult(0);
if (keyIsDown(65)) { // A
this.angle -= 0.05;
}
if (keyIsDown(68)) { // D
this.angle += 0.05;
}
if (keyIsDown(87)) { // W
let force = p5.Vector.fromAngle(this.angle);
force.mult(0.1);
this.applyForce(force);
}
if (keyIsDown(83)) { // S
let force = p5.Vector.fromAngle(this.angle);
force.mult(-0.05);
this.applyForce(force);
}
}
display() {
push();
translate(this.pos.x, this.pos.y);
rotate(this.angle);
fill(127);
stroke(200);
triangle(-10, -5, -10, 5, 10, 0);
pop();
}
checkEdges() {
if (this.pos.x > width) this.pos.x = 0;
if (this.pos.x < 0) this.pos.x = width;
if (this.pos.y > height) this.pos.y = 0;
if (this.pos.y < 0) this.pos.y = height;
}
applyDrag() {
let distance = this.pos.dist(createVector(width / 2, height / 2));
let dragMagnitude = map(distance, 0, width / 2, 0, 0.05);
let dragForce = this.vel.copy();
dragForce.normalize();
dragForce.mult(-1 * dragMagnitude);
this.applyForce(dragForce);
}
}