Adding Cannon.js Body to Three.js Mesh causing Vec3 error with groups and multiple shapes

Basically I’ve created a group of 2 meshes in Three.js and a Body containing 2 Shapes in Cannon.

Separately they appear fine but when I copy the Body position to the meshes to add physics the code breaks, nothing appears on screen and when logging the positions, for the Body everythings ok but the mesh its showing as undefined.

(The end goal is to replace the mesh with the model)

Any help would be great, heres the code in question:

import './style.css'
import * as THREE from 'three'
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js'
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js'
import { DRACOLoader } from 'three/examples/jsm/loaders/DRACOLoader.js'
import * as dat from 'lil-gui'

import * as CANNON from 'cannon-es'

/**
 * Base
 */
// Debug
const gui = new dat.GUI()

// Canvas
const canvas = document.querySelector('canvas.webgl')

// Scene
const scene = new THREE.Scene()

/**
 * Models
 */
const dracoLoader = new DRACOLoader()
dracoLoader.setDecoderPath('/draco/')

const gltfLoader = new GLTFLoader()
gltfLoader.setDRACOLoader(dracoLoader)

let mixer = null

let gunModel = null

gltfLoader.load(
    '/models/hamburger.glb',
    (gltf) =>
    {
        gltf.scene.position.set(0, 4, 0)
        gunModel = gltf.scene
        scene.add(gunModel)
        console.log(gunModel.position)
    }
)

/**
 * test wireframe cubes
 */
const YGeo = new THREE.BoxBufferGeometry(2, 6, 2);
const YMat = new THREE.MeshBasicMaterial({
    color: 'green',
    wireframe: true
})
const gun = new THREE.Group();

const blockY = new THREE.Mesh(YGeo, YMat);
blockY.position.x = 4;

const XGeo = new THREE.BoxBufferGeometry(6,2,2);
const XMat = new THREE.MeshBasicMaterial({
    color: 'green',
    wireframe: true
})

const blockX = new THREE.Mesh(XGeo, XMat);
blockX.position.y = 2

gun.add(blockY)
gun.add(blockX)

gui.add(gun.position, 'y', 0, 5, 0.01);
gui.add(gun.position, 'x', -3, 4, 0.01)
gui.add(gun.position, 'z', -3, 3, 0.01)

scene.add(gun)

/**
 * Floor
 */
const floor = new THREE.Mesh(
    new THREE.PlaneGeometry(50, 50),
    new THREE.MeshStandardMaterial({
        color: '#444444',
        metalness: 0,
        roughness: 0.5
    })
)
floor.receiveShadow = true
floor.rotation.x = - Math.PI * 0.5
scene.add(floor)

/**
 * Lights
 */
const ambientLight = new THREE.AmbientLight(0xffffff, 0.8)
scene.add(ambientLight)

const directionalLight = new THREE.DirectionalLight(0xffffff, 0.6)
directionalLight.castShadow = true
directionalLight.shadow.mapSize.set(1024, 1024)
directionalLight.shadow.camera.far = 15
directionalLight.shadow.camera.left = - 7
directionalLight.shadow.camera.top = 7
directionalLight.shadow.camera.right = 7
directionalLight.shadow.camera.bottom = - 7
directionalLight.position.set(5, 5, 5)
scene.add(directionalLight)

/**
 * Sizes
 */
const sizes = {
    width: window.innerWidth,
    height: window.innerHeight
}

window.addEventListener('resize', () =>
{
    // Update sizes
    sizes.width = window.innerWidth
    sizes.height = window.innerHeight

    // Update camera
    camera.aspect = sizes.width / sizes.height
    camera.updateProjectionMatrix()

    // Update renderer
    renderer.setSize(sizes.width, sizes.height)
    renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2))
})

/**
 * Camera
 */
// Base camera
const camera = new THREE.PerspectiveCamera(75, sizes.width / sizes.height, 0.1, 100)
camera.position.set(- 8, 4, 8)
scene.add(camera)

// Controls
const controls = new OrbitControls(camera, canvas)
controls.target.set(0, 1, 0)
controls.enableDamping = true

/**
 * Renderer
 */
const renderer = new THREE.WebGLRenderer({
    canvas: canvas
})
renderer.shadowMap.enabled = true
renderer.shadowMap.type = THREE.PCFSoftShadowMap
renderer.setSize(sizes.width, sizes.height)
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2))

/**
 * Physics
 */
 const world = new CANNON.World({
    gravity: new CANNON.Vec3(0, -9.81, 0)
});

const floorBody = new CANNON.Body({
    shape: new CANNON.Plane(),
    mass: 0
})
world.addBody(floorBody)

const shapeY = new CANNON.Box(new CANNON.Vec3(1,3,1))
const shapeX = new CANNON.Box(new CANNON.Vec3(3,1,1))

const boxBody = new CANNON.Body({
    mass: 1
})
boxBody.addShape(shapeY, new CANNON.Vec3(3, 0, 0), new CANNON.Quaternion())
boxBody.addShape(shapeX, new CANNON.Vec3(0,2,0), new CANNON.Quaternion())
world.addBody(boxBody)

boxBody.position.set(-0.56, 4.13, -0.02)

console.log(boxBody.position)

gui.add(boxBody.position, 'y', 0, 10, 0.01);

/**
 * Animate
 */
const clock = new THREE.Clock()
let previousTime = 0

const tick = () =>
{

    const elapsedTime = clock.getElapsedTime()
    const deltaTime = elapsedTime - previousTime
    previousTime = elapsedTime

    world.step(1/60, deltaTime, 3)

    floor.position.copy(floorBody.position);
    floorBody.quaternion.copy(floor.quaternion);

    // if(gunModel) {
    //     gunModel.position.copy(boxBody);
    //     gunModel.quaternion.copy(boxBody)
    //     console.log(gunModel.position)
    // }

    gun.position.copy(boxBody);
    gun.quaternion.copy(boxBody)
    console.log(gun.position.x)

    if(mixer)
    {
        mixer.update(deltaTime)
    }

    // Update controls
    controls.update()

    // Render
    renderer.render(scene, camera)

    // Call tick again on the next frame
    window.requestAnimationFrame(tick)
}

tick()

Trying to filter 4 different houses from an api

I’m trying to separate characters based on what house they belong to in the API (http://hp-api.herokuapp.com/api/characters)

I have tried using .filter and .map, but have been unable to achieve that goal, I don’t know if this is the right place to ask for help understanding how to achieve my goal.

Here is the code:

const studentArray = [];

async function getStudents(url) {
  const student = await fetch(url);
  const jsondata = await student.json();
  jsondata.forEach((student) => {
    studentArray.push(student);
  });
}







getStudents("http://hp-api.herokuapp.com/api/characters/students").then(() => {
});
<!DOCTYPE html>
<html lang="en">
  <head>
    <script src="/testing/script.js"></script>
    <link rel="stylesheet" href="/testing/styles.css" />
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <main>
      <div id="name" class="container"><button onclick="Gryffindor">Test</button></div>
      <div id="name" class="container"><button onclick="Slytherin">Test</button></div>
      <div id="name" class="container"><button onclick="Ravenclaw">Test</button></div>
      <div id="name" class="container"><button onclick="Hufflepuff">Test</button></div>
    </main>
  </body>
</html>

Adding React Router returns me a blank web page not working

When I return only <NavBar> in the App.jsx file, it prints me out what I want (Navigation bar on the left side with my icons menu) but when I use the Router/Switch modules, the web page is blank any ideas why it is not working ?

import { BrowserRouter, Route, Routes, Switch } from 'react-router-dom'
import NotFound from './Pages/Errors/NotFound';
import NavBar from './Components/NavBar';
import Dashboard from './Pages/Dashboard/Dashboard';
import User from './Pages/User/User';


export default function App() {
  return (
    <BrowserRouter>
      <NavBar/>
      <Switch>
        <Routes>
          <Route exact path="/"  element={<Dashboard />} />
          <Route path = "/user"  element={<User />} />
        </Routes>
      </Switch>
    </BrowserRouter>    
   
  );
}

NodeJS puppeteer timeout 30000ms exceeded error

I am doings a web scraper for SPA’s, however, on some, I run into errors, while it works on others. I am not sure if my targeted selector is wrong sometimes, or there is request throttling due to large data sets returned, or too many requests from the same IP, however, it is less data than the pages regular API queries.

I am using NodeJS, puppeteer, Express and as I said, on some web pages, it works, especially on smaller data sets.

The error handler reports “Error while fetching {my request} timeout 30000ms exceeded error “.

I have used the trouble shooting from other answers setting that parameter to zero.

await page.goto('https://www.autoscout24.ch/de/autos/bmw--3-series?yearfrom=2006&priceto=5000&make=9&model=46&vehtyp=10', {timeout: 0});

I have searched for solutions on SO and on blogs, but none of them work for me.

The targeted URL is https://www.autoscout24.ch/de/autos/bmw–3-series?yearfrom=2006&priceto=5000&make=9&model=46&vehtyp=10 , where I simply want the price value, maybe my puppeteer selector is wrong, the price is well down the DOM tree, see the image:

Screenshot console

The full code is this:

const puppeteer = require('puppeteer');
const express = require('express');
const app = express();
const path = require('path');
const router = express.Router();

app.set('view engine', 'ejs');



(async () => {
try {
const browser = await puppeteer.launch();
const page = await browser.newPage();
const navigationPromise = page.waitForNavigation();


await page.goto('https://www.autoscout24.ch/de/autos/bmw--3-series?yearfrom=2006&priceto=5000&make=9&model=46&vehtyp=10', {timeout: 0});

await page.setViewport({ width: 1440, height: 744 });
await navigationPromise;


await page.waitForSelector('d-inline-block font-weight-bold h2 mr-2 mb-0');
let CarPrices = await page.$$eval('d-inline-block font-weight-bold h2 mr-2 mb-0', price => {
  return price.map(prices => prices.innerText);
});

console.log(`Prices are: ${CarPrices.join(', ')}`);
await browser.close();
app.get('/', function(req, res) {
  res.render('pages/index', { key: `The prices for these cars are: ${CarPrices.join(', ')}` });
});


  app.use('/', router);
  app.listen(process.env.port || 3000);

  console.log('Running at Port 3000');
} catch (e) {
console.log(`Error while fetching prices ${e.message}`);
}
})();

Am I targeting the selector right or is there something off?

Do I have to set the time out value different/in another place?

Whenever I try to execute my script it gives the error “SyntaxEror: Unexpected token ‘case’

I coded myself a bot but it doesnt seem to be working, it keeps giving the error:

case prefix + "pois":
^^^^

SyntaxError: Unexpected token 'case'

I have tried alot of stuff to check what the problems is.
I have tried installing node.js, discord.js, npm and done npm i in the shell but still does not work. (I am trying to run it on Replit). I’m new to coding so please if anyone knows the answer tell it in an easy way that a beginner coder can understand.
Here is my index.js:

var prefix = '$'

case prefix + "pois":

                var id = parseInt(args[1])

                if (id) {
                  fetch(`https://www.rolimons.com/uaid/` + id).then(res => res.text()).then(res => {
                    //// clog(res)
                    if (res != 'Uaid not found, try again later') {
                      var search = res,
                        first = 'uaid_details'
                      var second = `owner_list`;
                      var itemdat = JSON.parse(search.substring(search.indexOf(first) + first.length, search.indexOf(second)).replace(";", "").replace("=", "").replace("var", ''))
                      // clog(itemdat)
                      var search = res,
                        first = 'item_details'
                      var second = `uaid_details`;
                      var itemname = JSON.parse(search.substring(search.indexOf(first) + first.length, search.indexOf(second)).replace(";", "").replace("=", "").replace("var", ''))
                      var search = res,
                        first = 'owner_list'
                      var second = `lucky_cat_uaid`;
                      var owners = JSON.parse(search.substring(search.indexOf(first) + first.length, search.indexOf(second)).replace(";", "").replace("=", "").replace("var", ''))
                      message.reply(`Scanning...`)
                      var em = new discord.MessageEmbed()
                        .setFooter("Ascension||discord.gg/ascension")
                        .setURL("https://www.rolimons.com/item/" + args[1])
                        .setColor("#ffc0cb")
                        .setThumbnail("https://www.roblox.com/thumbs/asset.ashx?width=420&height=420&assetid=" + itemdat["asset_id"])
                        .setTitle(`UAID ` + args[1])
                        .setURL(`https://www.rolimons.com/uaid/` + args[1])
                        .setAuthor(itemname.name, `https://www.roblox.com/thumbs/asset.ashx?width=420&height=420&assetid=` + itemdat["asset_id"])
                      if (itemdata.serial) {
                        em.addField('SERIAL', itemdat.serial)
                      }
                      em.addField('OWNER', (itemdat.owner_name || `Hidden/Deleted`))
                      em.addField(`Last Traded`, itemdat["updated_relative_string"])
                      message.reply(em)
                      if (itemdat["updated_relative_string"].search(`month`) != -1 || itemdat["updated_relative_string"].search(`year`) != -1) {
                        message.channel.send(`Since the current owner has had it for more than a month, we have deemed this uaid(${args[1]}) as CLEAN :white_check_mark:`)

                      } else {
                        comped_detected = false

                        Object.keys(owners).forEach(x => {

                          var item = owners[x][0]
                          if (item && parseInt(x) + 2628000 >= Date.now() / 1000) {
                            fetch(`https://avatar.roblox.com/v1/users/${item}/avatar`).then(res => res.json().catch(err => { })).then(avatar => {
                              avatar.assets.forEach(a => {
                                if (badassets[a.id] != undefined) {
                                  comped_detected = true
                                }
                              })
                              fetch("https://inventory.roblox.com/v1/users/" + item + "/assets/collectibles?sortOrder=Asc&limit=100").then(res => res.json().catch(err => { })).then(p => {
                                // clog(p)
                                var amt = 0
                                if (p.data) {
                                  p.data.forEach(l => {
                                    amt = amt + itemdata[l.assetId][4]
                                  })
                                  if (amt < 5000) {
                                    comped_detected = true
                                  }
                                }
                              })
                            })
                          }
                        })

                        setTimeout(function() {
                          if (comped_detected) {
                            message.reply(`after scanning this uaid, the bot has determined that the uaid is :x: POIS`)
                          } else {

                            message.reply(`After scanning this uaid, the bot has determined that the uaid is :white_check_mark: CLEAN`)
                          }
                        }, 2000)
                      }
                    } else {
                      message.reply(`invalid UAID.`)
                    }
                  })

                } else {
                  message.reply(`please provide a UAID for us to scan.`)
                }

Again help is appreciated Im very new to coding.

Conditionally render select boxes with autogenerated IDs

So I am trying to render different select boxes based upon the current value of another select box. The first select box is for a film name, and then the second select box shows the showings for that specific film. I could conditionally render the options inside, however, I just want to render the div as a whole.

I am doing this using the django framework. The code will produce something like this:

<div hidden id="Ice Age">
... Select box and options
</div>

<div hidden id="James Bond">
... Select box and options
</div>

I then want to access this div and remove the hidden tag, displaying the select box. I am however having issues with my javascript, as I cannot use query selector on the item, as the IDs are created conditionally.

Here is my attempt:

filmSelection.addEventListener('change', (event) => {
    const filmSelectionTemp = document.querySelector('#film'); // Get the film drop down
    let temp = '#' + event.target.value // Create the ID of the currently selected film
    const result = document.querySelector(temp); // Select that div
    result.classList.remove('hidden') // Remove hidden tag
})

This tells me : Uncaught TypeError: Cannot read properties of null (reading 'classList')

Not really sure what is going on.

New to javascript so pls be nice 🙂

Push back to the another array inside map function in JS [closed]

I want to do some Calculation inside array, I want to push back to array after iteration.

let dataValue = [90, 150, 180, 200, 230, 270]

dataValue.map((data) => {
  let ValueAs = angleToVaue(data); //calculations I do I get some output like this  example: 1000, 3500, 7000, 6000

  //I want to put back to array 
  let arraValue =[];
  arraValue.push(...ValueAs);

  console.log(...ValueAs); // error: valueAs is not iterable
});

React: data not loading after being fetched

Using MUI and I have a Select component (a dropdown menu) whose options I want to populate using data from a fetch request. I store the data in the state with an array, named ‘partners’.
Initially, partners.map() did not work because partners was empty, so I was thinking that I should wait for the fetch to finish before rendering. And so this is my code with that in mind:

  const [partners, setPartners] = useState([]);
  React.useEffect(() => {
    fetch('http://localhost:3000/partners')
      .then((resp) => resp.json())
      .then((data) => setPartners(data));
    console.log(partners);
  }, []);

  if (!partners.length) {
    return <Typography>Loading...</Typography>;
  }
  return ( 
    <FormControl>
      <>
        <Select
          onChange={handleFormChange}
        >
          {partners.map(({ name }) => (
            <MenuItem value={name}>{name}</MenuItem>
          ))}
        </Select>
      </>
    </FormControl>
  )

But now, the page is just stuck on ‘Loading…’ and doesn’t change. I’ve tried using !!!partners.length in the if statement too but it didn’t seem to make a difference. The console.log(partners) statement in the useEffect just returns an empty array. Thing is, the data being fetched is most definitely not empty/null so I’m not sure what’s going on. Is it possible that the console.log() is being run before the fetch or setPartners statements fully complete? Is partners even being changed? If so, how is it possible that the check for partners.length doesn’t return True at any point in time?

percentage bar based on data

thanks in advantage for the help.The problem, as the title says, is that I need to find a way to create a percentage bar that shows progresses made by an utent. I have his skill stored in a db and each time he gain a new skill I have to upgrade the percentage bar. How can I do it?
Javascript, Jquery, PHP or wathever is not important.

Customized Typescript Interface for Recharts Custom Tooltip

I am trying to add some more data to my customized Tooltip other than the data available by default. Now, I want to write a type for such a tooltip, already seen one of the solutions which has not passed anything else other than the props which recharts chart internally passes to the custom tooltip.

The solution I am referring to above: Typescript Interface for Recharts Custom Tooltip

my code:
<Tooltip content={ <CustomToolTipComponent detailsType={detailsType} selectedItemUnit={selectedItemUnit} /> } />

I am using this tooltip for a Line Chart.

I tried searching for more solutions to it but can’t find anything on recharts documentation and on any other platforms till now. The solution I mentioned above provides the inbuilt type for the collection of data passed to the Tooltip by default but doesn’t give scope to add any other data type to it.

createSlice store a value returned from a promise function in redux-toolkit

I have a function consumed from a service where it returns a promise object when called, on fulfillment I need to extract a value.

 const isAdmin = some.service.isUserAuthorized({
        group: "group_id",
    }).then((response) => response.isAuthorized)
        .then((value) => {
            return value;
        });
const initialState = {user:"some_name",isAnAdmin:isAdmin }

// it provides promise object as the result, but i need the value of the promise object once completed

export const userDetailsSlice = createSlice({
  name: 'userDetails',
  initialState ,
  reducers: {
  },
})

export default userDetailsSlice.reducer

how do i use a changeable value in a function parameter?

it’s pretty hard to explain, but I know why what I tried doesn’t work I just want to know if there is a solution. I hope you can understand what I want to do through the code

async function copyInvite() {
    let buttons = document.querySelectorAll("button.rl-btn-invite");

    addEventListenerLoop(buttons, 'click', event => { navigator.clipboard.writeText(node.id); });
}



async function addEventListenerLoop(nodes, type, code) {
    for (const node of nodes) {
        node.addEventListener(type, code);
    }
}

I am trying to make a value in the function change based on what node I am doing it on

I tried using mutable values but it either didn’t work or I didn’t try well enough.

How to get Azure AD access token in Static Web App?

I have a vanilla Vue.JS SWA that uses a standard Azure AD authentication via these settings in staticwebapp.config.json:

"auth": {
    "identityProviders": {
      "azureActiveDirectory": {
        "registration": {
          "openIdIssuer": "https://login.microsoftonline.com/common/v2.0",
          "clientIdSettingName": "AZURE_CLIENT_ID",
          "clientSecretSettingName": "AZURE_CLIENT_SECRET"
        }
      }
    }
  }

An app with AZURE_CLIENT_ID is registered in Azure AD. Authentication is called via standard

/.auth/login/aad 

endpoint. I can successfully log in and log out. “/.auth/me” endpoint returns clientPrincipal object with all user details (roles, id, etc) and claims.

Now I want to call MS graph API https://graph.microsoft.com/v1.0/me, but don’t know how to get the access token to set the Authorization header in the request. I can see that there is a AppServiceAuthSession cookie is set, however it is not a token.
I have seen this https://stackoverflow.com/questions/59860238/how-to-convert-azure-cookie-appserviceauthsession-to-a-valid-oauth-jwt-access-to , however reconstructing the whole auth flow looks unnecessary as I am logged in already.

Will appreciate any advice. Many thanks!

Tried to all MS Graph API as is, but as expected, got “message”: “Access token is empty.”
Also had a look at azure/msal-browser module in a hope to get the token silently, but it looks super complex and badly documented for a JS novice like me.

How to fire a function when selecting an idem in a dropdown in jSuites?

I’m trying to create a dropdown menu with jSuites that fires a function once one of the items in the list is selected.

Unfortunately, I can’t figure out how to fire the function. I tried with “onchange” both as attribute of the <div> and within the definition fo the jdropdown, but nothing seems to work.

I attach a fiddle here with a dropdown menu made with that works and does what it should, and two jSuites menus that should behave in the same way but they don’t…

What am I doing wrong?

Can this be done at all?

Any help is welcome…

http://jsfiddle.net/2x4qnj1h/1/

Sorting a number of DIV’s

I’m trying to write a sort function but it keeps going of the rails, gets to complicated.

  • imagine 10 div’s in a container div.
  • people can click the div’s, those appear in a summary box up top.
  • People can click div 8 then div 2 then div 5 for example.
  • but in the summary box i’d like them to be sorted, so div 2, then div
    8 then div 8.

preferably in plain JS, no jquery.

I was thinking of writing what people click to an array with maybe push() or splice(), and then filling the summary box with it somehow, but haven’t managed yet.