Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to use Code in my own code #41

Open
abingandabong opened this issue Dec 18, 2024 · 0 comments
Open

How to use Code in my own code #41

abingandabong opened this issue Dec 18, 2024 · 0 comments

Comments

@abingandabong
Copy link

I have a question about incorporating the code into my own code. I am making a flight simulator and I am trying to use this terrain for the game. this is my code so far:

import * as THREE from 'three';
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';

// Scene setup
const loader = new GLTFLoader();
const scene = new THREE.Scene();

const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 100000);
camera.position.set(0, 20, 100);
scene.add(camera);

const light = new THREE.AmbientLight(0xffffff); // White light
scene.add(light);

const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setClearColor(0x87CEEB); // Light blue background
document.body.appendChild(renderer.domElement);

// Initialize OrbitControls
const controls = new OrbitControls(camera, renderer.domElement);
controls.enableDamping = true;
controls.dampingFactor = 0.05;
controls.screenSpacePanning = false;
controls.maxPolarAngle = Math.PI / 2;
controls.update();

let plane;
const speed = 0.5; // Plane speed
const raycaster = new THREE.Raycaster();
const mouse = new THREE.Vector2();

// Variables to manage tilt
let isTiltingUp = false;
let isTiltingDown = false;
const tiltSpeed = 0.01; // Speed of tilt

// Load the plane model
loader.load('plane.gltf', function (gltf) {
plane = gltf.scene;
scene.add(plane);

plane.position.set(0, 10, -900);
plane.rotation.y = Math.PI / 2;

camera.position.set(20, 15, 50);
controls.target.copy(plane.position);
controls.update();

}, undefined, function (error) {
console.error(error);
});

// Add a crosshair canvas
const crosshairCanvas = document.createElement('canvas');
crosshairCanvas.style.position = 'absolute';
crosshairCanvas.style.top = '0';
crosshairCanvas.style.left = '0';
crosshairCanvas.style.pointerEvents = 'none'; // Allow mouse events to pass through
crosshairCanvas.width = window.innerWidth;
crosshairCanvas.height = window.innerHeight;
document.body.appendChild(crosshairCanvas);

const crosshairContext = crosshairCanvas.getContext('2d');

// Draw a fighter jet-style crosshair
function drawCrosshair(x, y) {
crosshairContext.clearRect(0, 0, crosshairCanvas.width, crosshairCanvas.height);

const size = 20; // Crosshair size
const lineWidth = 2; // Crosshair line width
const color = 'red';

crosshairContext.strokeStyle = color;
crosshairContext.lineWidth = lineWidth;

// Draw horizontal line
crosshairContext.beginPath();
crosshairContext.moveTo(x - size, y);
crosshairContext.lineTo(x + size, y);
crosshairContext.stroke();

// Draw vertical line
crosshairContext.beginPath();
crosshairContext.moveTo(x, y - size);
crosshairContext.lineTo(x, y + size);
crosshairContext.stroke();

// Draw center circle
crosshairContext.beginPath();
crosshairContext.arc(x, y, size / 2, 0, 2 * Math.PI);
crosshairContext.stroke();

}

// Update mouse position from crosshair
function updateMouseFromCrosshair(x, y) {
mouse.x = (x / window.innerWidth) * 2 - 1; // Normalize X
mouse.y = -(y / window.innerHeight) * 2 + 1; // Normalize Y
}

// Handle mouse movement
document.addEventListener('mousemove', (event) => {
const x = event.clientX;
const y = event.clientY;
drawCrosshair(x, y);
updateMouseFromCrosshair(x, y);
});

// Function to apply tilt to the plane
function applyTilt() {
if (!plane) return;

if (isTiltingUp) {
    plane.rotation.x += tiltSpeed; // Tilt up
}

if (isTiltingDown) {
    plane.rotation.x -= tiltSpeed; // Tilt down
}

// Clamp tilt to prevent flipping
plane.rotation.x = THREE.MathUtils.clamp(plane.rotation.x, -Math.PI / 6, Math.PI / 6);

}

// Move the plane towards the crosshair
function movePlaneTowardsCrosshair() {
if (!plane) return;

// Cast a ray from the camera through the mouse position
raycaster.setFromCamera(mouse, camera);

// Get the direction the crosshair is pointing
const direction = raycaster.ray.direction.clone();
direction.normalize();

// Orient the plane towards the target direction
plane.lookAt(plane.position.clone().add(direction));

// Apply tilt
applyTilt();

// Move the plane forward in the direction it's facing
plane.translateX(-speed); // Move along the local forward direction

}

// Handle keyboard controls for tilting
document.addEventListener('keydown', (event) => {
if (event.key === 'ArrowDown') {
isTiltingUp = true;
} else if (event.key === 'ArrowUp') {
isTiltingDown = true;
} else if (event.key === 'r') {
renderer.setAnimationLoop(() => {
movePlaneTowardsCrosshair(); // Move plane and apply tilt
controls.target.copy(plane.position); // Keep camera on plane
controls.update();
renderer.render(scene, camera);
});
}
});

document.addEventListener('keyup', (event) => {
if (event.key === 'ArrowDown') {
isTiltingUp = false;
} else if (event.key === 'ArrowUp') {
isTiltingDown = false;
} else if (event.key === 'a') {
renderer.setAnimationLoop(() => {
controls.target.copy(plane.position); // Keep camera on plane
controls.update();
renderer.render(scene, camera);
});
}
});

// Handle window resize
window.addEventListener('resize', () => {
renderer.setSize(window.innerWidth, window.innerHeight);
crosshairCanvas.width = window.innerWidth;
crosshairCanvas.height = window.innerHeight;

camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();

});

I want to add the code you provided:

// Generate a terrain
var xS = 63, yS = 63;
terrainScene = THREE.Terrain({
easing: THREE.Terrain.Linear,
frequency: 2.5,
heightmap: THREE.Terrain.DiamondSquare,
material: new THREE.MeshBasicMaterial({color: 0x5566aa}),
maxHeight: 100,
minHeight: -100,
steps: 1,
xSegments: xS,
xSize: 1024,
ySegments: yS,
ySize: 1024,
});
// Assuming you already have your global scene, add the terrain to it
scene.add(terrainScene);

// Optional:
// Get the geometry of the terrain across which you want to scatter meshes
var geo = terrainScene.children[0].geometry;
// Add randomly distributed foliage
decoScene = THREE.Terrain.ScatterMeshes(geo, {
mesh: new THREE.Mesh(new THREE.CylinderGeometry(2, 2, 12, 6)),
w: xS,
h: yS,
spread: 0.02,
randomness: Math.random,
});
terrainScene.add(decoScene);

to it. It just gives me a blank screen when I try. Do I need to import the module in my three js code? I already did npm install three.terrain.js? it would be great if you could give me the code and tell me what to improve if u have time thanks in advance :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant