Guide on importing a JS file into the main JS file using Three.js

I'm fairly new to Threejs and I am trying to organize my code by putting some of my threejs code in a separate JS file and then using it in my main.js file. Here is a simplified version of what I am trying to do:

main.js

import * as THREE from 'three'
import Box from './classes/Parts.js'
const box = new Box()
scene.add(box)

Parts.js

class Box {
  constructor() {
    this.geom = new THREE.BoxGeometry(2, 2, 2);
    this.mat = new THREE.MeshBasicMaterial({
      color: 0xff0000
    });
    this.mesh = new THREE.Mesh(this.geom, this.mat);
  }
}
export default Box;
This is similar to this.

However, I am encountering the following error:

THREE.Object3D.add: object not an instance of THREE.Object3D.

What am I doing wrong here?

Answer №1

In order to add custom objects to the scene graph, they must be derived from the THREE.Object3D class. Your Box class does not meet this requirement. Here is the revised code:

class Box extends THREE.Mesh {
  constructor() {
    const geom = new THREE.BoxGeometry(2, 2, 2);
    const mat = new THREE.MeshBasicMaterial({
      color: 0xff0000
    });
    super(geom,mat);
  }
}
export default Box;

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

Looking for a method to substitute "test" with a different value

Showing a section of the menu using <li id="userInfo" role="presentation" data-toggle="tab" class="dropdown"> <a href="#" name="usernameMenu" class="dropdown-toggle" data-toggle="dropdown" role="button"> <span class="glyphicon glyph ...

Issue with DropdownListFor validation using jQuery when the onchange event triggers submission

DropdownListFor @Html.DropDownListFor(x => x.selectedDateFilter, new SelectList(Model.bydatefilter, "id", "dt", Model.selectedDateFilter), "--Select Date--", new { onchange = @"this.f ...

The mssql node is experiencing an issue where it is unable to accept work due to the pool being

Recently, I encountered an issue with my node js app that utilizes the npm mssql module. Despite purchasing a cloud Windows 2012 server, I faced an error when trying to execute a stored procedure. The error is thrown at ps.prepare("exec usp_Get_Cars @para ...

The React functional component captures a snapshot of its state when initializing a websocket event handler

When using a react functional component, it captures a snapshot of the state at the time of subscription. For example, refer to the code below. If I click the setSocketHandler button and then press the setWelcomeString button. If I receive a message over ...

Disabling the global ajax datatype causes issues with Rails remote links

I have successfully developed a rails application that submits a form remotely and then displays form validation errors if the validation process fails. The form itself is working perfectly. However, I've come across an issue where the way I've ...

Ways to define a variable based on a CSS class attribute?

I need help figuring out how to create a variable in my script that is defined by the width attribute of a CSS class. The snippet I have currently doesn't seem to work as expected. var dist = $('.nav').css(width()); The goal of my script i ...

SOLVING the issue of page flicker in SVELTE

Within the application below, I am experiencing a peculiar page flicker effect that is often associated with AJAX requests. However, in this scenario, the cause is not AJAX-related but rather a conditional statement that triggers the rendering of different ...

Having trouble with the webpage not loading correctly after implementing react-router-dom

I recently installed 'react-router-dom' and 'react' in order to implement a routing feature in my project. Despite adding 'react-router-dom' to my devDependencies within the package.json file, I am encountering issues with the ...

What is the reason behind the requirement in Javascript (ES.next) that a function must be declared as async in order to utilize await functionality?

Shouldn't a compiler or parser be intelligent enough to recognize when a function utilizes await, and automatically convert it to an async function? Why is there a requirement for me to explicitly type the async keyword? It just clutters the code, an ...

Authentication with Laravel and Vue.js

After successfully implementing Laravel-Vue.js Authentication using Passport API, I am now able to obtain the token and send requests to api/user. Initially, I used the normal authentication process by sending data through a POST request to /login, which r ...

Massive React State Array containing hundreds of Input elements, sluggish state updates triggered by onChange events

I am working on a React form that consists of multiple complex inputs, each with its own complex state. To manage the state of all these inputs, I have a parent component where each input is wrapped in a child component. The parent component holds a state ...

ffmpeg is successfully converting less than half of my images into a video

Utilizing ffmpeg to convert a series of images into a timelapse video has been seamless when executed through the command line. ffmpeg -r 3 -i /var/folders/qj/n910kwdj4gvbmy_z2ffc5lcc0000gp/T/tmp-22129yvIsrbso4TEu/image%03d.jpg -s hd1080 -vcodec libx264 t ...

Clicking on the delete option will remove the corresponding row of Firebase data

I am encountering an issue that appears to be easy but causing trouble. My goal is to delete a specific row in an HTML table containing data from Firebase. I have managed to delete the entire parent node of users in Firebase when clicking on "Delete" withi ...

Angular: controller's property has not been initialized

My small controller is responsible for binding a model to a UI and managing the UI popup using semantic principles (instructs semantic on when to display/hide the popup). export class MyController implements IController { popup: any | undefined onShow(con ...

As soon as I inserted the image, the text vanished into thin air

The phrase "welcome" is not displaying after I included the av tag <!DOCTYPE html> <html> <style> @font-face { font-family: OpenSans; src: url(OpenSans-Bold.ttf); } * { ...

The hide-columns feature in Ng-table does not allow for manual column hiding from the controller

I've configured ng-table with checkboxes to toggle column visibility, and it's functioning smoothly. Here's the HTML: // Switchers to show/hide columns <div style="margin-bottom: 20px"> <label class="checkbox-inline" ng-repeat= ...

In Google Chrome, the edges of hexagons appear jagged and not smooth

I have encountered an issue in Chrome where I created a hexagon group using HTML and CSS. While it displays fine in Firefox, the edges of the hexagons appear distorted in Chrome. Here are my code snippets: HTML <div class="col-sm-12 margin-left-100" i ...

Ways to retrieve the total of all the values stored within an object created using a constructor function

Currently, I am in the process of creating an RPG character builder where each character is allocated 10 points to distribute among their characteristics and select advantages. Character Constructor function character(str, dex, con, int, wis) { this ...

Automatic Full-Screen Switching Upon Video Playback in HTML5

Currently, I have a video clip set to play when the timer reaches a certain point. My goal is for the video to automatically enter full-screen mode when it starts playing and return to its original position when it stops, as the timer will continue ticking ...

Issue with PassportJs not forwarding users after successful authentication

I'm facing some challenges with implementing Passport for authentication. I have set up my signup strategy in the following way: passport.use('local_signup', new localStrategy({ usernameField: 'username', passwordField:&apo ...