Spaces:
Running
Running
File size: 21,569 Bytes
45931a3 294d1f9 45931a3 294d1f9 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 |
<!DOCTYPE html>
<html>
<head>
<title>First Person Terrain Walker with Sky</title>
<style>
body { margin: 0; padding: 0; background: black; }
canvas { display: block; }
#instructions {
position: fixed;
top: 12px;
left: 12px;
background: rgba(0,0,0,0.4);
color: white;
padding: 10px;
font-family: Arial, sans-serif;
border-radius: 8px;
}
#downloadTexture {
display: block;
margin-top: 10px;
padding: 5px 10px;
background: #4CAF50;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
font-family: Arial, sans-serif;
}
#downloadTexture:hover {
background: #45a049;
}
#downloadTexture:disabled {
background: #cccccc;
cursor: not-allowed;
}
</style>
</head>
<body>
<div id="instructions">
WASD or Arrow Keys - Move<br>
Space - Jump<br>
Mouse - Look around<br>
Click to start<br>
<button id="downloadTexture" disabled>Download Texture</button>
</div>
<script type="importmap">
{
"imports": {
"three": "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js",
"three/addons/": "https://unpkg.com/[email protected]/examples/jsm/",
"three/examples/": "https://unpkg.com/[email protected]/examples/jsm/"
}
}
</script>
<script type="module">
import * as THREE from 'three';
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
import { PointerLockControls } from 'three/examples/controls/PointerLockControls.js';
import { Sky } from 'three/addons/objects/Sky.js';
import { Lensflare, LensflareElement } from 'three/addons/objects/Lensflare.js';
const USE_SPARSE = true;
// Scene setup
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 0.5;
document.body.appendChild(renderer.domElement);
// Weapon sway parameters
let currentWeaponSway = { x: 0, y: 0, z: 0 };
let targetWeaponSway = { x: 0, y: 0, z: 0 };
const maxSwayAmount = 0.03;
const swaySpeed = 0.1;
const swayLerpFactor = 0.1;
let lastSwayUpdate = 0;
const swayUpdateInterval = 150; // milliseconds
// Download button setup
const downloadButton = document.getElementById('downloadTexture');
let extractedTexture = null;
// Function to extract and download texture
function extractAndSaveTexture(mesh) {
if (!mesh.material || !mesh.material.map) {
console.warn('No texture found on this mesh');
return null;
}
const texture = mesh.material.map;
const canvas = document.createElement('canvas');
canvas.width = texture.image.width;
canvas.height = texture.image.height;
const ctx = canvas.getContext('2d');
ctx.drawImage(texture.image, 0, 0);
return canvas.toDataURL('image/png');
}
// Download button click handler
downloadButton.addEventListener('click', () => {
if (extractedTexture) {
const link = document.createElement('a');
link.href = extractedTexture;
link.download = 'terrain_texture.png';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
});
// Sky setup
const sky = new Sky();
sky.scale.setScalar(450000);
scene.add(sky);
const skyUniforms = sky.material.uniforms;
skyUniforms['turbidity'].value = 10;
skyUniforms['rayleigh'].value = 3;
skyUniforms['mieCoefficient'].value = 0.005;
skyUniforms['mieDirectionalG'].value = 0.7;
const sun = new THREE.Vector3();
const phi = THREE.MathUtils.degToRad(90 - 2);
const theta = THREE.MathUtils.degToRad(180);
sun.setFromSphericalCoords(1, phi, theta);
skyUniforms['sunPosition'].value.copy(sun);
// Lighting Setup
const ambientLight = new THREE.AmbientLight(0xfffdfd, 0.6);
scene.add(ambientLight);
const sunLight = new THREE.DirectionalLight(0xfffdfd, USE_SPARSE ? 0.9 : 3.0);
sunLight.position.set(50, 500, 50);
sunLight.castShadow = true;
sunLight.shadow.mapSize.width = 4096;
sunLight.shadow.mapSize.height = 4096;
sunLight.shadow.camera.near = 0.1;
sunLight.shadow.camera.far = 2000;
sunLight.shadow.camera.left = -500;
sunLight.shadow.camera.right = 500;
sunLight.shadow.camera.top = 500;
sunLight.shadow.camera.bottom = -500;
sunLight.shadow.bias = -0.0001;
scene.add(sunLight);
// Add Lensflare
const textureLoader = new THREE.TextureLoader();
const textureFlare0 = textureLoader.load('/public/textures/lensflare/lensflare0_alpha.png');
const textureFlare1 = textureLoader.load('/public/textures/lensflare/lensflare3.png');
const textureFlare2 = textureLoader.load('/public/textures/lensflare/lensflare3.png');
const lensflare = new Lensflare();
lensflare.addElement(new LensflareElement(textureFlare0, 700, 0));
lensflare.addElement(new LensflareElement(textureFlare1, 512, 0.6));
lensflare.addElement(new LensflareElement(textureFlare2, 170, 0.7));
lensflare.addElement(new LensflareElement(textureFlare2, 120, 0.9));
sunLight.add(lensflare);
const fillLight = new THREE.DirectionalLight(0xffffff, 1.2);
fillLight.position.set(-50, 50, -50);
scene.add(fillLight);
const rimLight = new THREE.DirectionalLight(0xffffff, 0.8);
rimLight.position.set(0, 20, -100);
scene.add(rimLight);
// Controls setup
const controls = new PointerLockControls(camera, document.body);
document.addEventListener('click', function() {
controls.lock();
});
// Movement
let moveForward = false;
let moveBackward = false;
let moveLeft = false;
let moveRight = false;
let canJump = false;
const onKeyDown = function(event) {
switch(event.code) {
case 'KeyW':
case 'ArrowUp':
moveForward = true;
break;
case 'KeyA':
case 'ArrowLeft':
moveLeft = true;
break;
case 'KeyS':
case 'ArrowDown':
moveBackward = true;
break;
case 'KeyD':
case 'ArrowRight':
moveRight = true;
break;
case 'Space':
if (canJump) {
verticalVelocity = jumpForce;
canJump = false;
}
break;
}
};
const onKeyUp = function(event) {
switch(event.code) {
case 'KeyW':
case 'ArrowUp':
moveForward = false;
break;
case 'KeyA':
case 'ArrowLeft':
moveLeft = false;
break;
case 'KeyS':
case 'ArrowDown':
moveBackward = false;
break;
case 'KeyD':
case 'ArrowRight':
moveRight = false;
break;
}
};
document.addEventListener('keydown', onKeyDown);
document.addEventListener('keyup', onKeyUp);
// Physics variables
const gravity = -35;
let verticalVelocity = 0;
const playerHeight = 2;
const jumpForce = 14;
const groundErrorMargin = 0.2; // Added error margin for ground detection
let isGrounded = false;
const bounceCoefficient = 0.4;
// Raycaster for ground detection
const raycaster = new THREE.Raycaster();
// Modified terrain loading with texture extraction
const loader = new GLTFLoader();
let terrain;
// Gun model setup
let gunModel;
const gunLoader = new GLTFLoader();
gunLoader.load('/public/models/laser-gun.glb', (gltf) => {
// Scale and position the gun relative to camera
gunModel = gltf.scene;
gunModel.scale.set(0.3, 0.3, 0.3);
gunModel.position.set(0.35, -0.23, -0.54);
gunModel.rotation.y = Math.PI * 1.6;
gunModel.rotation.z = Math.PI * 0.2;
gunModel.rotation.x = Math.PI * 0.1 + currentWeaponSway.x;
gunModel.rotation.y = Math.PI * 1.6 + currentWeaponSway.y;
gunModel.rotation.z = Math.PI * 0.2 + currentWeaponSway.z;
// Add the gun to the camera
camera.add(gunModel);
scene.add(camera); // Need to add camera to scene for gun to be visible
});
loader.load('/public/models/pond-sparse.glb', (gltf) => {
console.log("model loaded! preparing it..");
terrain = gltf.scene;
terrain.scale.set(100, 100, 100);
terrain.rotation.y = Math.PI;
if (USE_SPARSE) {
terrain.rotation.x = -Math.PI * 2.15;
}
let textureFound = false;
terrain.traverse((node) => {
if (node.isMesh) {
node.castShadow = true;
node.receiveShadow = true;
if (node.material) {
node.material.roughness = 0.8;
node.material.metalness = 0.2;
// Extract texture if available
if (node.material.map && !textureFound) {
extractedTexture = extractAndSaveTexture(node);
if (extractedTexture) {
downloadButton.disabled = false;
textureFound = true;
}
}
}
}
});
scene.add(terrain);
const box = new THREE.Box3().setFromObject(terrain);
const center = box.getCenter(new THREE.Vector3());
terrain.position.x -= center.x;
terrain.position.z -= center.z;
terrain.position.y = 0;
raycaster.ray.origin.set(0, 100, 10);
raycaster.ray.direction.set(0, -1, 0);
const intersects = raycaster.intersectObjects(scene.children, true);
if (intersects.length > 0) {
camera.position.set(0, intersects[0].point.y + 2.5, 10);
} else {
camera.position.set(0, 20, 10);
}
camera.lookAt(new THREE.Vector3(0, 0, 0));
},
undefined,
(error) => {
console.error('An error happened:', error);
const geometry = new THREE.PlaneGeometry(100, 100, 20, 20);
const material = new THREE.MeshStandardMaterial({
color: 0x808080,
roughness: 0.8,
metalness: 0.2,
wireframe: true
});
terrain = new THREE.Mesh(geometry, material);
terrain.castShadow = true;
terrain.receiveShadow = true;
scene.add(terrain);
});
// Movement speed and physics
const velocity = new THREE.Vector3();
const direction = new THREE.Vector3();
const speed = 0.5;
const delta = 1/60;
function checkGround() {
if (!terrain) return {
distance: Infinity,
normal: new THREE.Vector3(0, 1, 0),
hasHeadCollision: false
};
// Ground check ray
raycaster.ray.origin.copy(camera.position);
raycaster.ray.direction.set(0, -1, 0);
const groundIntersects = raycaster.intersectObjects(scene.children, true);
// Head collision check ray
raycaster.ray.origin.copy(camera.position);
raycaster.ray.direction.set(0, 1, 0);
const headIntersects = raycaster.intersectObjects(scene.children, true);
const hasHeadCollision = headIntersects.length > 0 && headIntersects[0].distance < 1.0;
if (groundIntersects.length > 0) {
return {
distance: groundIntersects[0].distance,
normal: groundIntersects[0].face.normal.clone(),
hasHeadCollision: hasHeadCollision
};
}
return {
distance: Infinity,
normal: new THREE.Vector3(0, 1, 0),
hasHeadCollision: hasHeadCollision
};
}
function animate() {
requestAnimationFrame(animate);
if(controls.isLocked) {
const groundInfo = checkGround();
const distanceToGround = groundInfo.distance;
// Calculate current movement speed
const currentSpeed = Math.sqrt(velocity.x * velocity.x + velocity.z * velocity.z);
// Update weapon sway based on movement
updateWeaponSway(currentSpeed);
updateGunPosition();
// Check if we're below terrain or if there's no terrain below us
raycaster.ray.origin.copy(camera.position);
raycaster.ray.direction.set(0, -1, 0);
const belowIntersects = raycaster.intersectObjects(scene.children, true);
// Check if we're below terrain by casting a ray upward
raycaster.ray.origin.copy(camera.position);
raycaster.ray.direction.set(0, 1, 0);
const aboveIntersects = raycaster.intersectObjects(scene.children, true);
// If we're below terrain (ray hits something above us) or if there's no ground below us
if ((aboveIntersects.length > 0 && aboveIntersects[0].distance < playerHeight) ||
belowIntersects.length === 0) {
// Find a safe position above terrain
raycaster.ray.origin.set(camera.position.x, 200, camera.position.z);
raycaster.ray.direction.set(0, -1, 0);
const rescueIntersects = raycaster.intersectObjects(scene.children, true);
if (rescueIntersects.length > 0) {
// Teleport player to safety
camera.position.y = rescueIntersects[0].point.y + playerHeight;
verticalVelocity = 0;
isGrounded = true;
canJump = true;
} else {
// If no safe position found, reset to initial position
camera.position.set(0, 20, 10);
verticalVelocity = 0;
}
}
// Handle head collisions
if (groundInfo.hasHeadCollision && verticalVelocity > 0) {
verticalVelocity = 0;
}
const slopeAngle = Math.acos(groundInfo.normal.dot(new THREE.Vector3(0, 1, 0)));
const maxClimbableAngle = Math.PI / 4;
// Improved ground detection with error margin
if (distanceToGround > playerHeight + groundErrorMargin) {
verticalVelocity += gravity * delta;
isGrounded = false;
} else if (distanceToGround < playerHeight - groundErrorMargin) {
if (verticalVelocity < 0) {
verticalVelocity = Math.abs(verticalVelocity) * bounceCoefficient;
camera.position.y = camera.position.y + (playerHeight - distanceToGround);
}
isGrounded = true;
canJump = true;
} else {
if (Math.abs(verticalVelocity) < 0.1) {
verticalVelocity = 0;
isGrounded = true;
canJump = true;
} else {
verticalVelocity *= 0.8;
isGrounded = false;
}
}
verticalVelocity = Math.max(verticalVelocity, -20);
camera.position.y += verticalVelocity * delta;
direction.z = Number(moveForward) - Number(moveBackward);
direction.x = Number(moveRight) - Number(moveLeft);
direction.normalize();
if(moveForward || moveBackward) velocity.z = -direction.z * speed;
if(moveLeft || moveRight) velocity.x = -direction.x * speed;
const moveDirection = new THREE.Vector3(-velocity.x, 0, -velocity.z).normalize();
const slopeDirection = groundInfo.normal.clone().projectOnPlane(new THREE.Vector3(0, 1, 0)).normalize();
const slopeFactor = 1.0 - (moveDirection.dot(slopeDirection) * (slopeAngle / (Math.PI / 2)));
const slopeSpeedMultiplier = slopeFactor > 0
? 1.0 - (Math.min(slopeFactor, 1.0) * 0.5)
: 1.0 + (Math.min(Math.abs(slopeFactor), 1.0) * 0.3);
const movementSpeed = isGrounded ? speed * slopeSpeedMultiplier : speed * 0.8;
if (moveForward || moveBackward || moveLeft || moveRight) {
controls.moveRight(-velocity.x * movementSpeed);
controls.moveForward(-velocity.z * movementSpeed);
} else {
controls.moveRight(-velocity.x * movementSpeed);
controls.moveForward(-velocity.z * movementSpeed);
}
velocity.x *= 0.9;
velocity.z *= 0.9;
}
// Update sky and render
const time = performance.now() * 0.0001;
const distance = 400000;
sun.x = distance * Math.cos(time);
sun.y = distance * Math.sin(time) * 1.25;
sun.z = distance * Math.sin(time) * 0.25;
sky.material.uniforms['sunPosition'].value.copy(sun);
sunLight.position.copy(sun).normalize().multiplyScalar(500);
renderer.render(scene, camera);
}
function updateWeaponSway(currentSpeed) {
const now = performance.now();
if (now - lastSwayUpdate < swayUpdateInterval) return;
lastSwayUpdate = now;
// Calculate sway amount based on movement speed
const movementFactor = Math.min(currentSpeed / speed, 1);
const swayAmount = maxSwayAmount * movementFactor;
// Generate random sway targets
targetWeaponSway.x = (Math.random() * 2 - 1) * swayAmount;
targetWeaponSway.y = (Math.random() * 2 - 1) * swayAmount;
targetWeaponSway.z = (Math.random() * 2 - 1) * swayAmount * 0.5;
}
function updateGunPosition() {
if (!gunModel) return;
// Interpolate current sway towards target
currentWeaponSway.x += (targetWeaponSway.x - currentWeaponSway.x) * swayLerpFactor;
currentWeaponSway.y += (targetWeaponSway.y - currentWeaponSway.y) * swayLerpFactor;
currentWeaponSway.z += (targetWeaponSway.z - currentWeaponSway.z) * swayLerpFactor;
// Apply sway to gun model's rotation
gunModel.rotation.x = Math.PI * 0.1 + currentWeaponSway.x;
gunModel.rotation.y = Math.PI * 1.6 + currentWeaponSway.y;
gunModel.rotation.z = Math.PI * 0.2 + currentWeaponSway.z;
}
// Handle window resize
window.addEventListener('resize', onWindowResize, false);
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
}
animate();
</script>
</body>
</html>
|