xxxxxxxxxx
156
let plane;
let terrainSize = 800;
let terrainResolution = 40;
let terrain;
let mountainSize = 100;
let mountainHeight = 300;
function setup() {
createCanvas(800, 600, WEBGL);
plane = new Plane();
terrain = generateTerrain();
}
function draw() {
background(0);
// Handle user input
handleInput();
// Update the plane's position and orientation
plane.update();
// Set up camera
camera(0, -200, 400, 0, 0, 0, 0, 1, 0);
// Draw the terrain
drawTerrain();
// Draw the plane
plane.display();
}
function handleInput() {
// Rotate left
if (keyIsDown(LEFT_ARROW)) {
plane.rotateY(-0.02);
}
// Rotate right
if (keyIsDown(RIGHT_ARROW)) {
plane.rotateY(0.02);
}
// Pitch up
if (keyIsDown(UP_ARROW)) {
plane.rotateX(-0.02);
}
// Pitch down
if (keyIsDown(DOWN_ARROW)) {
plane.rotateX(0.02);
}
// Yaw left
if (keyIsDown(65)) { // 'A' key
plane.rotateZ(0.02);
}
// Yaw right
if (keyIsDown(68)) { // 'D' key
plane.rotateZ(-0.02);
}
// Move forward
if (keyIsDown(87)) { // 'W' key
plane.move(0.1);
}
// Move backward
if (keyIsDown(83)) { // 'S' key
plane.move(-0.1);
}
}
function generateTerrain() {
let terrain = [];
let halfSize = terrainSize / 2;
let stepSize = terrainSize / terrainResolution;
for (let x = -halfSize; x < halfSize; x += stepSize) {
for (let y = -halfSize; y < halfSize; y += stepSize) {
let z = noise(x * 0.01, y * 0.01) * mountainHeight;
terrain.push(createVector(x, y, z));
}
}
return terrain;
}
function drawTerrain() {
noStroke();
// Draw terrain
fill(50, 200, 50);
for (let i = 0; i < terrain.length; i++) {
let vertex = terrain[i];
push();
translate(vertex.x, vertex.y, vertex.z);
box(terrainResolution, terrainResolution, 2);
pop();
}
// Draw mountain
fill(150, 75, 0);
let mountainX = map(plane.position.x, -terrainSize / 2, terrainSize / 2, -mountainSize / 2, mountainSize / 2);
let mountainY = map(plane.position.y, -terrainSize / 2, terrainSize / 2, -mountainSize / 2, mountainSize / 2);
let mountainZ = map(plane.position.z, -terrainSize / 2, terrainSize / 2, 0, mountainHeight);
push();
translate(mountainX, mountainY, mountainZ);
box(mountainSize, mountainSize, mountainHeight);
pop();
}
class Plane {
constructor() {
this.position = createVector(0, 0, 0);
this.rotation = createVector(0, 0, 0);
}
update() {
this.position.add(this.rotation);
}
display() {
push();
translate(this.position.x, this.position.y, this.position.z);
rotateX(this.rotation.x);
rotateY(this.rotation.y);
rotateZ(this.rotation.z);
fill(255);
noStroke();
box(40, 20, 100);
pop();
}
rotateX(angle) {
this.rotation.x += angle;
}
rotateY(angle) {
this.rotation.y += angle;
}
rotateZ(angle) {
this.rotation.z += angle;
}
move(speed) {
let direction = p5.Vector.fromAngles(this.rotation.y, this.rotation.x);
direction.normalize();
direction.mult(speed);
this.position.add(direction);
}
}