The skybox in Three.js appears to be malfunctioning following a camera rotation

Working with JavaScript, I am attempting to build a basic skybox inspired by this demo. Everything is going smoothly except for one issue - when I rotate the camera (using orbitControls.js) and the z value is not at its minimum, the textures start to glitch and appear broken.

Here's the source code:

var camera, scene, renderer, controls, skybox;

var toRadians = function(deg) {
    return deg * Math.PI / 180
}

var toDegrees = function(radians) {
    return radians * (180 / Math.PI);
}

var init = function() {

    // setting up the scene
    scene = new THREE.Scene();
    scene.fog = new THREE.FogExp2( 0xffffff, 0.00010);

    // creating the camera
    camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 1, 20000 );
    camera.position.z = 5000;
    scene.add( camera );

    // adding the skybox
    var urlPrefix = "http://three.dev/skybox/textures/";
    var urls = [urlPrefix + "px.png", urlPrefix + "nx.png",
                urlPrefix + "py.png", urlPrefix + "ny.png",
                urlPrefix + "pz.png", urlPrefix + "nz.png"];
    var textureCube = THREE.ImageUtils.loadTextureCube( urls );

    var shader = THREE.ShaderLib[ "cube" ];
    shader.uniforms[ "tCube" ].value = textureCube;

    var material = new THREE.ShaderMaterial( {

        fragmentShader: shader.fragmentShader,
        vertexShader: shader.vertexShader,
        uniforms: shader.uniforms,
        depthWrite: false,
        side: THREE.BackSide

    } ),

    skybox = new THREE.Mesh( new THREE.BoxGeometry( 10000, 10000, 10000 ), material );
    scene.add( skybox );

    // setting up render settings
    renderer = new THREE.WebGLRenderer( {alpha: true, antialias: true} );
    renderer.setSize( window.innerWidth, window.innerHeight );
    renderer.setClearColor( 0xffffff, 1 );
    renderer.autoClear = false;

    controls = new THREE.OrbitControls( camera, renderer.domElement );
    controls.rotateSpeed = 0.5;
    controls.minDistance = 500;
    controls.maxDistance = 6000;

    document.body.appendChild( renderer.domElement );

    window.addEventListener( 'resize', onWindowResize, false );

    // initiating the rendering process
    render();

}

function onWindowResize() {

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

  renderer.setSize( window.innerWidth, window.innerHeight );

  render();

}

var update = function() {

}

var render = function() {
    update();
    controls.update();

    requestAnimationFrame( render );
    renderer.render(scene, camera);
}

window.onload = function(){
    init();
}

Answer №1

When enhancing your 'main' scene, consider adding a skybox for a more immersive experience. For a skydome effect, it's recommended to create a separate 'background' scene that complements the main scene. The debate between skydomes and skyboxes boils down to polygon conservation versus visual appeal, with the latter usually offering a more realistic sky representation. In this instance, a dome/sphere will be utilized.

var renderer = new THREE.WebGLRenderer({alpha: true, antialias: true});
var mainScene = new THREE.Scene();
var mainCamera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 1, 20000);

var skydome = {
    scene: new THREE.Scene(),
    camera: new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 1, 20000)
};

skydome.material = new THREE.MeshBasicMaterial({color: 0x0F0F0F}); // Using MeshBasicMaterial for the skydome

skydome.mesh = new THREE.Mesh(new THREE.SphereGeometry(100, 20, 20), skydome.material);

skydome.scene.add(skydome.mesh);

During the rendering process, focus on adjusting the rotation of the skydome camera, while maintaining its position.

var render = function(){
    requestAnimationFrame(render);
    skydome.camera.quaternion = mainCamera.quaternion;
    renderer.render(skydome.scene, skydome.camera); // Render the skydome first
    renderer.render(mainScene, mainCamera); // Then overlay the main scene on top of the skydome
};
renderer.autoclear = false; // Ensure both scenes are rendered

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error encountered with React Hooks - TypeError

What I Aim to Achieve Our goal is to utilize Next.js to create a button named 'ConnectMetamask' that, upon clicking, triggers the predefined hooks and stores the value in a variable called 'userSigner'. This functionality is implemente ...

A step-by-step guide on including chess.js in your Create React App

I'm facing an issue while trying to incorporate the chess.js npm library into my Create React App. The error message "Chess is not a constructor" keeps popping up. Below is the code snippet I am using: import React from 'react'; import &apos ...

Tips for making sure custom fonts are loaded before running any JavaScript code

Upon loading my page, I run a JavaScript function to determine if specific text fits within its parent div. If it doesn't fit, then adjustments must be made. The text is styled with a custom font, which can be loaded either through @font-face or Goog ...

How to effectively refine a group query in Firestore to obtain specific results

My database structure is set up like this (simplified version): Collection: item_A -> Document: params = {someParameter: "value"} -> Document: user_01 -> Sub-collection: orders_item_A -> Document: order_AA ...

Navigate the Angular interceptor route to display a 404 error page when clicking on a `<a href="#">` tag

When using href="#" as a placeholder in html, I encountered an issue where Angular was unable to recognize it and would route to the 404 page despite having the following configuration in the module. How can this problem be resolved? .config( function m ...

Error message: Unexpected token "(" in the asynchronous aspect of Meteor

Currently running meteor version 1.5.1, I am facing a bug while attempting to import an npm module (kraken-api) on the server side: import KrakenClient from 'kraken-api'; > W20170726-22:02:48.177(2)? (STDERR) packages/modules.js:677 ...

switch from material ui lists on/off

Trying to learn React through coding, I've encountered an issue with displaying the 'StarBorder' icon next to folders when clicked. Currently, clicking on any folder displays the 'StarBorder' icon for all folders. Any tips on how t ...

Can you explain the purpose of the "letter:" included in the code and how it is utilized?

g: function testFunction() { return true; } h: function anotherTestFunction() { } i: console.log('test') I'm intrigued by the mystery of this code snippet. As is written, I am executing it in NodeJS version 16 or higher and trying to un ...

Determine the present height of the current class and substitute it with another class that has the same

My wordpress blog theme has an ajax pagination feature that works well, except for the fact that when a user clicks on the next page link, the entire posts area disappears while the new content is loading. I would like to maintain the same container dimens ...

Include the session variable as an argument in the onload() function call

I've encountered a problem while trying to send the session variable $_SESSION["post-code"] as a parameter in the following code snippet... <body onload="getLocation('<?php echo $_SESSION['post-code'];?>')"> Within my ...

Fade out the div element when clicked

For my game project, I needed a way to make a div fade out after an onclick event. However, the issue I encountered was that after fading out, the div would reappear. Ideally, I wanted it to simply disappear without any sort of fade effect. Below is the co ...

Combine two or more Firebase Observables

Currently, I am working on creating an Observable using FirebaseObjectObservable. However, before I can accomplish this, I need to query a Firebase list to obtain the key IDs required for the FirebaseObjectObservable. The structure of my data is as follow ...

Unable to get the div to properly follow when scrolling, even when using the fixed position attribute

My webpage is divided into two sections - left and right. I've used divs to create the left navigation and right content. However, when scrolling down the page, only the right portion scrolls while the left navigation remains fixed. I'm looking ...

Parsing error: Unforeseen token encountered. Consider adding a supplementary loader to manage the output of these loaders

Could someone please break down this syntax message?.length === 1 and show me how to convert it into standard JavaScript? https://i.stack.imgur.com/20Ui6.png I am encountering an error when trying to use a Vue.js component that I downloaded from another ...

Navigating through content using jQuery scroll bar

Could someone please assist me with scrolling the content on my website? For example, I have a link like this: <a href="#">content3</a> When a user clicks that link, I would like the content to scroll to div content3. I am looking for guidan ...

Discover the underlying element that is being blurred when clicked

Is there a method to determine which element triggered the blur event when clicked outside? I want to update a ui-select value to match what the user typed in if they click outside of the dropdown. However, if they click on a dropdown item, I want to disc ...

Error: Call stack size limit reached in Template Literal Type

I encountered an error that says: ERROR in RangeError: Maximum call stack size exceeded at getResolvedBaseConstraint (/project/node_modules/typescript/lib/typescript.js:53262:43) at getBaseConstraintOfType (/project/node_modules/typescript/lib/type ...

What is the best way to upload an image BUFFER to a website using puppeteer?

What I have learned to do: Save an image file from a source like imgur as a buffer and download it to disk Display an image on a page by uploading it from disk using elementHandle.uploadFile(path) However, this method only works locally on my machine. My ...

Ways to address issues in my tree-building algorithm when the parent ID is missing

Currently, I'm in the process of creating a function to build a tree. Everything seems to be functioning correctly until I encounter a scenario where a document is added with a parentID that doesn't exist in the list. The root node is intended to ...

Alert: VirtualizedList warns of slow updates for a large list despite optimized components

Struggling with avoiding the warning message "VirtualizedList: You have a large list that is slow to update" while utilizing the <FlatList> component in React-Native. Despite thorough research and attempts at finding a solution, including referencin ...