xxxxxxxxxx
127
let x = 0;
let y = 250;
let vx = 25;
let vy = 0;
let deltaVx = 0;
let deltaVy = 0;
let theta;
let Fthrust = 30;
let mass = 3;
let dt = 0.1;
let r = 12;
let thrusting = false;
let reversing = false;
let xhistory = [];
let yhistory = [];
let iterations = 0;
function setup() {
createCanvas(750, 500);
theta = HALF_PI;
}
function draw() {
background(255);
vx += deltaVx;
vy += deltaVy;
x += vx * dt;
y += vy * dt;
deltaVx = 0;
deltaVy = 0;
if (keyIsDown(LEFT_ARROW)) {
theta += 0.1;
}
if (keyIsDown(RIGHT_ARROW)) {
theta -= 0.1;
}
if (keyIsDown(UP_ARROW)) {
let accelx = Fthrust * cos(theta) / mass;
deltaVx = accelx * dt;
let accely = Fthrust * sin(theta) / mass;
deltaVy = accely * dt;
thrusting = true;
} else {
thrusting = false;
}
if (keyIsDown(DOWN_ARROW)) {
let accelx = -Fthrust * cos(theta) / mass;
deltaVx = accelx * dt;
let accely = -Fthrust * sin(theta) / mass;
deltaVy = accely * dt;
reversing = true;
} else {
reversing = false;
}
let buffer = r * 2;
if (x > width + buffer) {
x = -buffer;
} else if (x < -buffer) {
x = width + buffer;
}
if (y > height + buffer) {
y = -buffer;
} else if (y < -buffer) {
y = height + buffer;
}
strokeWeight(2);
noFill();
stroke(0);
push();
translate(x, height - y);
rotate(HALF_PI - theta);
fill(175);
beginShape();
vertex(-r, r);
vertex(0, -1.5 * r);
vertex(r, r);
endShape(CLOSE);
if (thrusting || reversing) {
push();
if (thrusting) {
fill(255, 165, 0);
}
if (reversing) {
fill(0, 0, 255);
}
noStroke();
rect(-r / 2, r + 1, r, 15);
pop();
}
pop();
if (iterations % 5 == 1) {
xhistory.push(x);
yhistory.push(y);
}
iterations++;
let maxLength = 50;
if (xhistory.length > maxLength) {
xhistory = xhistory.slice(xhistory.length - maxLength);
yhistory = yhistory.slice(yhistory.length - maxLength);
}
for (i = 0; i < xhistory.length; i++) {
strokeWeight(3);
point(xhistory[i], height - yhistory[i]);
}
}