Utilizing a GLTF asset as the main Scene element in a Three.js project

I'm struggling with incorporating a gltf model as the main scene in Three.js. Specifically, I have a gltf model of an apartment that I want to load from inside and not outside the apartment. I also need the controls to work seamlessly within the apartment. Despite my efforts in loading the model onto the scene, I can't seem to render the scene from inside the model.

Here is the code I've been working on for weeks, both in TypeScript and JavaScript. Any guidance or assistance would be greatly appreciated. Thank you!

Typescript code

import * as THREE from '/build/three.module.js'
import { OrbitControls } from '/jsm/controls/OrbitControls'
import { GLTFLoader } from '/jsm/loaders/GLTFLoader'
import Stats from '/jsm/libs/stats.module'

const scene: THREE.Scene = new THREE.Scene()
const axesHelper = new THREE.AxesHelper(5)

var light = new THREE.SpotLight();
light.position.set(5, 5, 5)
scene.add(light);

const camera: THREE.PerspectiveCamera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000)
camera.position.z = 2

const renderer: THREE.WebGLRenderer = new THREE.WebGLRenderer()

renderer.outputEncoding = THREE.sRGBEncoding
renderer.setSize(window.innerWidth, window.innerHeight)
document.body.appendChild(renderer.domElement)

const controls = new OrbitControls(camera, renderer.domElement)

const loader = new GLTFLoader()
loader.load(
    'apartment.glb',
    function (gltf) {
        scene.add(gltf.scene);
    },
    (xhr) => {
        console.log((xhr.loaded / xhr.total * 100) + '% loaded')
    },
    (error) => {
        console.log(error);
    }
);

window.addEventListener('resize', onWindowResize, false)
function onWindowResize() {
    camera.aspect = window.innerWidth / window.innerHeight
    camera.updateProjectionMatrix()
    renderer.setSize(window.innerWidth, window.innerHeight)
    render()
}

const stats = Stats()
document.body.appendChild(stats.dom)

var animate = function () {
    requestAnimationFrame(animate)

    controls.update()

    render()

    stats.update()
};

function render() {
    renderer.render(scene, camera)
}
animate();



JavaScript code



import * as THREE from '/build/three.module.js';
import { OrbitControls } from '/jsm/controls/OrbitControls';
import { GLTFLoader } from '/jsm/loaders/GLTFLoader';
import Stats from '/jsm/libs/stats.module';


const scene = new THREE.Scene();
const axesHelper = new THREE.AxesHelper(5);

var light = new THREE.SpotLight();
light.position.set(5, 5, 5);
scene.add(light);

const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.z = 2;
const renderer = new THREE.WebGLRenderer();

renderer.outputEncoding = THREE.sRGBEncoding;
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);


const controls = new OrbitControls(camera, renderer.domElement);
const loader = new GLTFLoader();
loader.load('apartment.glb', function (gltf) {
    scene.add(gltf.scene);
}, (xhr) => {
    console.log((xhr.loaded / xhr.total * 100) + '% loaded');
}, (error) => {
    console.log(error);
});

window.addEventListener('resize', onWindowResize, false);
function onWindowResize() {
    camera.aspect = window.innerWidth / window.innerHeight;
    camera.updateProjectionMatrix();
    renderer.setSize(window.innerWidth, window.innerHeight);
    render();
}
const stats = Stats();
document.body.appendChild(stats.dom);
var animate = function () {
    requestAnimationFrame(animate);
    controls.update();
    render();
    stats.update();
};
function render() {
    renderer.render(scene, camera);
}
animate();

Answer №1

After overcoming a frustrating issue, I finally found the solution. Initially, I had to switch to a plane model without a roof. Secondly, ensuring that the pivot point was correctly positioned at the center and the model aligned with the plane grid made all the difference compared to my previous attempts.

By having the model open in the room rendered within the scene rather than the entire model itself, along with the central pivot point and proper alignment on the grid, I avoided the need to search for it when rendering. Thank you for taking the time to read and provide assistance.

With this problem resolved, I could effortlessly load multiple glb models and position them as desired in the scene.

My advice for using a model as your scene is to confirm the pivot point is centered and the model rests on the grid, not above or below it. Also, ensure it's an open model so that your light and camera can penetrate inside.

Below is the final code snippet I utilized:

import * as THREE from '/build/three.module.js'
import { OrbitControls } from '/jsm/controls/OrbitControls'
import { GLTFLoader } from '/jsm/loaders/GLTFLoader'

// Code snippet continues here... (truncated for brevity)

If there are any suggestions or corrections you'd like to offer, please feel free to share. I'm open to learning and improving. Thank you!

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

Guide on configuring Angular validation to trigger on blur events and form submission

Validation in Angular is currently set to update on model change, but this method can be unfriendly for user interface as it displays errors upon keyup. An optimal solution would involve displaying error messages on blur and also on form submission. After ...

Endless cycle of React hooks

I am struggling to understand why I keep encountering an infinite loop in my useClick function. I can see that I am updating the state value inside the useEffect using setVal, but according to the second parameter, useEffect should only run on onClick as ...

Toggle the backgroundImage visibility by setting it to either hidden or displayed using jquery

$('.arrow').css("background-image", "url('../img/arrow.png')").hide(); I have implemented a custom solution using CSS and jQuery to hide the downward arrow when scrolling down on my webpage. `$( document ).ready(function() {
 co ...

Issue with array push not working within nested Promise

I recently encountered an issue with my Express API route that retrieves an artist's details along with an array of releases for that artist. My current goal is to iterate over this array, extract each URL, and then make additional API calls to retri ...

$filter is functioning correctly, however it is generating an error message stating: "Error: 10 $digest() iterations reached. Aborting!"

Here is an example of a JSON object that I am working with: { "conversations":[ { "_id": "55f1595d72b67ea90d008", "topic_id": 30, "topic": "First Conversation", "admin": "<a href="/cdn-cgi/l/e ...

The table's content extends beyond the confines of the page

I have an HTML page where I am embedding an SSRS report. The report extends beyond the page as shown in the image below: This is the table that is generated: <table cellpadding="0" cellspacing="0" id="ctl00_MainContent_FiveYearReportViewer_fixedTable" ...

In Firefox, long strings are automatically truncated, while in Google Chrome they display perfectly without any truncation

Here is a block of code where I am using a web service to retrieve a JSON string. It is encapsulated in an XML tag, which I then read and parse with jQuery's parser jQuery.parseJSON(xml.getElementsByTagName("string")[0].firstChild.nodeValue); $.ajax ...

How to Use jQuery in Thymeleaf to Toggle All Checkboxes

Why isn't the function of selecting and deselecting all fields working correctly for me? Can anyone explain what may be causing this issue? ..... <head> <meta name="viewport" content="width=device-width, initial-scale=1.0&q ...

Guide on showing a component exclusively for iPads with React and TypeScript

I need help displaying an icon only in the component for iPad devices, and not on other devices. As a beginner in coding for iPads and mobile devices, I am unsure how to achieve this specific requirement for the iPad device. Below is the code snippet tha ...

Encountering an issue with importing createSagaMiddleware from 'redux-saga' while working on my create-react-app project

Within my create-react-app, I have the following import: import createSagaMiddleware from 'redux-saga'; However, there seems to be an issue with importing createSagaMiddleware in my system. The versions I am currently using are: node 12.13.0 n ...

Is there a way to design a catalog page for my website that doesn't include a shopping cart or detailed product pages?

I am looking to create a catalogue feature similar to Newegg's for my website, but with a simplified approach. I have never attempted something this advanced before and I am wondering if it is possible to achieve. My plan is to use PHP and JS for the ...

Arranging information extracted from an XML document following an ajax request

Here is a snippet of XML data sample to work with: <?xml version="1.0" encoding="ISO-8859-1"?> <CATALOG> <CD> <TITLE>Empire Burlesque</TITLE> <ARTIST>Bob Dylan</ARTIST> <COUNTRY>U ...

Launch all external links in Browser (NWjs)

While attempting to create my own independent version of Google Chat using NWjs, I encountered some obstacles. When a link is opened in the NWjs window, it opens in another NWjs window instead of the default system browser, which is what I want. I attemp ...

Shopping Directive Coverage Discrepancy

In my application, there is a shop item directive that includes a price attribute. When a user interacts with the directive, the total cost (a variable stored in the main controller) should be updated by the price of the item that was clicked. Unfortunate ...

Transferring SQL-generated JSON object from PHP to JavaScript

Seeking assistance with passing a JSON object from PHP to Javascript. The object is populated from an SQL Database using the following PHP code snippet. <?php $conn = mysql_connect("localhost","root",""); if(! $conn ) { die('C ...

A step-by-step guide on incorporating a .env file into a React JS project that is written with TypeScript

I'm currently working on a React JS project with TypeScript. I know that we can utilize a .env file to define some configurations, like so: .env file REACT_APP_SOME_CONFIGURATION = "some value" We can then use these configurations in our c ...

`Populating fields in Firebase``

I am currently in the process of transitioning from a Mongoose + Express app to using Firebase + Express. However, I am facing some challenges with populating related fields similar to how it is done in Mongoose. Is there a more efficient way to achieve th ...

Creating a list that renders responsively using ReactJS

I'm currently working on implementing a responsive search bar that filters through a list of pure components (up to 100 components displayed at once). However, I've noticed there is a slight half-second delay between typing the first letter and s ...

Error message "Uncaught TypeError: Unable to read property 'defaultView' of undefined" was encountered while using Google Maps

I am encountering an issue when attempting to load a Google map in React: "Uncaught TypeError: Cannot read property 'defaultView' of undefined" The problem seems to be isolated within this particular component, as the rest of the app renders su ...

Update of Angular Material Table rows triggers a popup, however only the values from the first array are populated in all edited rows

Developed an application with two components (A & B) that includes a popup dialog for editing: Component A fetches the data from a service and loads it into a data table Component B initializes the data when a pop event is triggered from A. Usually, ...