Starting objects before utilizing them in the useFrame() function in react-three-fiber

I am currently working on a project using react-three-fiber to create a scene. However, I am facing an issue with placing 3D objects at different random positions. I tried using a for loop inside useFrame to set random positions, but this causes the particles to repeatedly move to random positions. I want these positions to be randomized only during initialization and then move the entire mesh. When I try to use the for loop just before useFrame, I encounter an error - "Cannot read property 'setMatrixAt' of undefined". PS: I am attempting to recreate a scene similar to -

import * as THREE from 'three'
import ReactDOM from 'react-dom'
import React, { useRef, useMemo, useState, useEffect } from 'react'
import { Canvas, useFrame } from 'react-three-fiber'
import Effects from './Effects'
import './styles.css'
const tempObject = new THREE.Object3D()

function Boxes({count}) {
  
  const ref = useRef()
  const previous = useRef()

  const particles = useMemo(() => {
    const temp = []
   

  useFrame(state => {
    const time = state.clock.getElapsedTime()
    ref.current.rotation.x += 0.00000
    ref.current.rotation.y += 0.00000
    let i = 0
    for (let x = 0; x < count; x++){
      const id = i++
      tempObject.position.set(Math.random() - 0.5, Math.random() - 0.5, Math.random() - 0.5 ).normalize()
      tempObject.position.multiplyScalar( Math.random() * 40 )
      tempObject.rotation.set( Math.random() * 2, Math.random() * 2, Math.random() * 2 )
      tempObject.updateMatrix()
      ref.current.setMatrixAt(id, tempObject.matrix)
    }
    ref.current.instanceMatrix.needsUpdate = true
  })

  return (
    <instancedMesh ref={ref} args={[null, null, count]}  >;
      <sphereBufferGeometry attach="geometry" args={[1, 4, 4]}/>  
      <meshPhongMaterial attach="material" color="#ffffff" flatShading ="true"/>
    </instancedMesh>
  )
}

ReactDOM.render(
  <Canvas
    gl={{ antialias: false, alpha: false }}
    camera={{ position: [0, 0, 400], near: 5, far: 1000 }}
    onCreated={({ gl }) => gl.setClearColor('pink')}>
    <ambientLight intensity={1.1} color="#222222" />
    <directionalLight color="#ffffff" position={[1, 1, 1]} />
    <Boxes count={1000}/>
    <Effects />
  </Canvas>,
  document.getElementById('root')
)

Answer №1

I encountered a similar problem and it appears that your code is correct. The issue arises when attempting to link the instancedMesh with the ref. It seems that there may be a compatibility issue with older versions of React. I was able to resolve this by updating both the react and react-dom packages from version ^16.9.0 to 16.10.2.

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

Is there a way to make sure a user can't access the response from an AJAX request?

I'm eager to establish a secure AJAX call and response between the client and server. To enhance security, I encrypt my AJAX request using an encryption method and route it like so: url: "/site/web/J+CVKhtwFK9VwSZYiza8zr8YUqWK62VSkobVfgB3+1s=" This ...

Unable to minimize or hide the ace editor widget with Cypress

Today marks the beginning of my journey into posting on this platform, and I am eager to get it right. In my current project using Cypress for writing integration tests, I encountered a challenge while attempting to click on an Ace editor widget within a ...

Can we prevent a component from being mounted every time it is rendered by its parent component?

Is it possible to render the Child component within the Father component without mounting it and resetting its states when the Father component is rendered? I attempted to use the useMemo hook to render the Child component, but it still mounts the compone ...

using JQuery, add a class on click event or on page load

Solved It! After encountering a problem created by some sloppy moves on my part, I managed to solve it. However, another issue arose: adding the class current to li with data-tab="tab-1 upon page load. $('ul.tabs li').click(function(){ ...

Retrieving information through a jQuery ajax call

I've been working on creating an AJAX filter for a car list, but I've hit a roadblock in the final stage. My setup involves two files: index.php and filter.php. Within index.php, I have a form with dropdown lists and sliders. Here's the cod ...

Using Vue.js with Vue Router to handle login functionality and automatically refreshing data

I am currently working on a Vue.js application and have successfully implemented authentication functionality, including checking if the user is logged in. After logging in, I want to fetch some data and store it in localStorage. However, I have encounter ...

Secure login verification coupled with intuitive navigation features

Just starting out with react native and I've created a UI for a restaurant app. Now I'm working on converting all static components to dynamic ones. My first task is figuring out how to implement login authentication and then navigate to a specif ...

Can content be dynamically loaded through ajax in Simile Timeline instead of being loaded upfront?

I am currently utilizing the JavaScript Simile Timeline which includes timeline items with extensive description fields. Rather than including all this information in the initial JSON payload data, I only want to load it when a user clicks on a timeline it ...

Adjust the position of bespoke shapes in Three.js to the central origin

After converting some custom geometries from a STEP file, I have been using the mouse to rotate them. However, they currently rotate around the scene's origin, making it appear as though they are rotating on a virtual sphere due to their distance from ...

What is the best way to search for a specific item in Express.js?

I recently got the Leaderboard API issue fixed, but now I'm encountering a new problem with express Querying. Specifically, I'm attempting to search for a specific Discord ID using quick.db as my database. I've included an excerpt of my expr ...

What is the correct way to integrate $.deferred with non-observable functions?

Imagine you have two functions filled with random code and the time they take to complete is unknown, depending on the user's system speed. In this scenario, using setTimeout to fire function2 only after function1 finishes is not practical. How can j ...

What could be the significance behind these sudden pop-ups of console error messages?

var sendTitle = function() { var title = $("input[name='movie-search-title']").val(); getMovie(title) getQuotes(title) } $("input[name='movie-search-title']").keydown(function(e) { if (e.keyCode == 13) { e.preventDefault(); ...

Having trouble with the `npm start` command while working with react.js?

Currently, I am in the process of setting up React.js. To achieve this, I executed npm install -g create-react-app followed by create-react-app my-app. Afterward, I proceeded to run the npm start command but encountered the error displayed below. https:// ...

Missing sidebar display

Hi there! I am having an issue with my sidebar not appearing correctly when I click on the toggle button. It seems to be moving to the side, but the sidebar itself is blank or transparent. I suspect that the problem lies within my JavaScript file. As a beg ...

Using Javascript to parse SOAP responses

Currently, I am working on a Meteor application that requires data consumption from both REST and SOAP APIs. The SOAP service is accessed using the soap package, which functions properly. However, I am facing challenges with the format of the returned data ...

How to handle a Node.js promise that times out if execution is not finished within a specified timeframe

return await new Promise(function (resolve, reject) { //some work goes here resolve(true) }); Using Delayed Timeout return await new Promise(function (resolve, reject) { //some work goes here setTimeout(function() { resolve(true); }, 5000); } ...

Using 'jquery.get' in combination with a servlet is

I need a servlet that can handle GET requests and return a specific string. A simple example of the code is shown below: public class QueryHandler extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) ...

Height and Width Dilemma in Visuals

Can you help with changing image resolution using jQuery? I have a background image applied to the body using CSS/PHP. My goal is to make the image fill the entire window by applying the screen height and width, without using repeat style. The code I am c ...

When using the Google API load callback, the Angular(4) router does not actually replace routes; instead, it stacks them up each time

I've been attempting to implement Google Authentication in my Angular 4 application. I have successfully loaded the Google platform.js and api.js in my index.html file. When I click on the login button, this is what I have coded: gapi.load('auth ...

I encountered an issue while operating my next.js application which utilizes solidity smart contracts. The error message "Cannot read properties of undefined" was displayed during the process

While working on my next.js app and attempting to fetch user data, I encountered the "cannot read properties of undefined" error. https://i.stack.imgur.com/SBPBf.png I also received the following error in the console https://i.stack.imgur.com/JBtbO.png ...