4

My glb file wont show up inside my thee.js world. I have followed all the documentations and tutorals but nothing works. the world loads and evry thing works fine its just that the moddle dose not appear. Plaese help me i am on a jurnay to make a game that is compleatly in html/js and i am decently well exerpienced in js. Please keep the code as original as possible and good luck. I have only used stack overflow once so sorry if this is a bad description. I the file is in the same folder as the code file. I know that it is a long snipbit of code but i wanted to make sure that you could see all the code incase it is more than just my importing. I dont know what else to say so sorry i am just stalling a bit. If you can please explain in vary vary vary simple terms what was wrong and how you fixed it. I have to keep stalling becouse there is too much code. I dont know how much longer i have to keep up this typeing. Once again soo sory for stalling i just cant describe this much. I realy relye on stack overflow and wold love if you helped ne.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title>My first three.js app</title>
    <style>
       body { margin: 0; }
       #info {
      position: absolute;
      top: 10px;
      width: 100%;
      text-align: center;
      z-index: 100;
      display:block;
       }
    </style>
    <script src="https://threejs.org/build/three.js"></script>
    <script type="importmap">
      {
        "imports": {
          "three": "https://unpkg.com/[email protected]/build/three.module.js",
          "three/addons/": "https://unpkg.com/[email protected]/examples/jsm/",
          "cannon-es": "https://cdn.jsdelivr.net/npm/[email protected]/dist/cannon-es.min.js"
        }
      }
    </script>
  </head>
  <body>
    <div id="info">0</div>
    <script type="module">
      import * as THREE from "three";
      import { OrbitControls } from "three/addons/controls/OrbitControls.js";
      import { Clock } from "three";
      import { PointerLockControls } from "three/addons/controls/PointerLockControls.js";
      import * as CANNON from "cannon-es";
      import { OBJLoader } from "three/addons/loaders/OBJLoader.js";
      import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
      const score = document.getElementById("info");
      let points = 0;
      let colide = false;
      let checkK = false;
      let Name;
      let boddy;

      const clock = new Clock();
      const world = new CANNON.World();
      world.gravity.set(0, -9.82, 0);
      const loader = new GLTFLoader();

      const physicsMaterial = new CANNON.Material();
      const physicsContactMaterial = new CANNON.ContactMaterial(
        physicsMaterial,
        physicsMaterial,
        { friction: 0.4, restitution: 0.0 }
      );

      


      world.addContactMaterial(physicsContactMaterial);

      function createCannonBox(size, position, masss) {
        this.shape = new CANNON.Box(
          new CANNON.Vec3(size.x / 2, size.y / 2, size.z / 2)
        );
         this.body = new CANNON.Body({
          mass: masss,
          material: physicsMaterial,
        });
        this.body.addShape(this.shape);
        this.body.position.copy(position);
        world.addBody(this.body);
        return this.body;
      }
      function createCannonBall(size, positionn, masss) {
         this.shape = new CANNON.Sphere(size);
         this.body = new CANNON.Body({
          mass: masss,
          material: physicsMaterial,
          shape: this.shape
        });
        this.body.position.copy(positionn);
        world.addBody(this.body);
        return this.body;
      }
      function createCannonKnot(size, position) {
        const Sshape = new CANNON.Sphere(size);
        const Sbody = new CANNON.Body({ mass: 1, material: physicsMaterial });
        Sbody.addShape(Sshape);
        Sbody.position.copy(position);
        world.addBody(Sbody);
        return Sbody;
      }
      function CreateTrimesh(geometry) {
        const vertices = geometry.attributes.position.array;
        const indices = Object.keys(vertices).map(Number);
        return new CANNON.Trimesh(vertices, indices);
      }

      const groundShape = new CANNON.Plane();
      const groundBody = new CANNON.Body({
        mass: 0,
        shape: groundShape,
        material: physicsMaterial,
      });
      groundBody.quaternion.setFromAxisAngle(
        new CANNON.Vec3(1, 0, 0),
        -Math.PI / 2
      );
      world.addBody(groundBody);

      const scene = new THREE.Scene();
      const camera = new THREE.PerspectiveCamera(
        75,
        window.innerWidth / window.innerHeight,
        0.1,
        1000
      );
      camera.position.z = 3;
      const renderer = new THREE.WebGLRenderer();
      renderer.setSize(window.innerWidth, window.innerHeight);
      document.body.appendChild(renderer.domElement);
      const Oloader = new OBJLoader();

      const concreteTexture = new THREE.TextureLoader().load(
        "https://threejsfundamentals.org/threejs/resources/images/wall.jpg"
      );
      const controls = new PointerLockControls(camera, document.body);

      const geometry = new THREE.BoxGeometry(1, 1, 1);
      const material = new THREE.MeshPhysicalMaterial({
        color: 0x00ff00,
        map: concreteTexture,
        clearcoat: 0.1,
      });

      const cube = new THREE.Mesh(geometry, material);
      cube.castShadow = true;
      scene.add(cube);
      
      // here is my attempt

      loader.load( '../free_1975_porsche_911_930_turbo.glb', function ( gltf )
    {
      const sword = gltf.scene;  // sword 3D object is loaded
      sword.scale.set(1, 1, 1);
      sword.position.y = 1;
      scene.add(sword);
    } );

      

      const cubeBody = new createCannonBox(
        new THREE.Vector3(1, 1, 1),
        new CANNON.Vec3(0.5, 4, 0),
        1
      );

      const Sgeometry = new THREE.SphereGeometry(0.5, 40, 20);

      const ball = new THREE.Mesh(Sgeometry, material);
      ball.castShadow = true;
      scene.add(ball);
      const ballBody = new createCannonBall(
        0.5,
        new CANNON.Vec3(0.5, 20, 0),
        1
      )


      

      const cube2 = new THREE.Mesh(geometry, material);
      cube2.castShadow = true;
      scene.add(cube2);
      const cubeBody2 = new createCannonBox(
        new THREE.Vector3(1, 1, 1),
        new CANNON.Vec3(0, 2, 0),
        0
      );

      const groundMaterial = new THREE.MeshPhysicalMaterial({
        map: concreteTexture,
        clearcoat: 1,
        clearcoatRoughness: 1,
        metalness: 0.9,
      });

      const groundGeometry = new THREE.PlaneGeometry(20, 20, 100, 100);
      const ground = new THREE.Mesh(groundGeometry, groundMaterial);
      ground.rotation.x = -Math.PI / 2;
      scene.add(ground);

      scene.background = new THREE.Color(0x87ceeb);

      const light = new THREE.DirectionalLight(0xffffff, 1);
      light.position.set(0, 15, 5);
      light.castShadow = true;
      scene.add(light);
      const light2 = new THREE.AmbientLight(0x404040);
      scene.add(light2);

      light.shadow.camera.near = 0.1;
      light.shadow.camera.far = 40;
      light.shadow.mapSize.width = 1025;
      light.shadow.mapSize.height = 1025;
      light.shadow.radius = 4;

      renderer.shadowMap.enabled = true;

      light.shadow.camera.left = -10;
      light.shadow.camera.right = 10;
      light.shadow.camera.top = 10;
      light.shadow.camera.bottom = -10;
      light.shadow.bias = -0.002;

      camera.position.y = 1;

      var keys = {};
      window.addEventListener("keydown", function (ev) {
        keys[ev.key] = true;
      });
      window.addEventListener("keyup", function (ev) {
        keys[ev.key] = false;
      });
      window.addEventListener("keydown", function (ev) {
        if (ev.code == "KeyE") {
          checkK = !checkK;
        }
      });

      const moveVector = new THREE.Vector3();
      const setVector = new CANNON.Vec3();

      camera.rotation.order = "YXZ";

      const initialCubePosition = cube.position.clone();
      const initialCubePosition2 = cube2.position.clone();
      const initialBallPosition = ball.position.clone();

      const resetInterval = 2.0;
      let lastResetTime = clock.elapsedTime;

      function check() {
        cubeBody2.addEventListener("collide", function (e) {
          colide = true;
         // name = cube;
          //boddy = cubeBody;
        });
        cubeBody.addEventListener("collide", function (e) {
          Name = cube;
          boddy = cubeBody;
        });
        ballBody.addEventListener("collide", function (e) {
          Name = ball;
          boddy = ballBody;
        });
      }

      function go() {
        if (keys.w) moveVector.z -= 0.1;
        if (keys.s) moveVector.z += 0.1;
        if (keys.a) moveVector.x -= 0.1;
        if (keys.d) moveVector.x += 0.1;
        if (keys.c) moveVector.y -= 0.1;
        if (keys.v) moveVector.y += 0.1;
        if (checkK && colide && keys.e) (checkK = false), (colide = false), (boddy.mass = 1);
        if (keys.m) controls.lock();

        moveVector.multiplyScalar(0.6);
        camera.translateX(moveVector.x);
        camera.translateZ(moveVector.z);
        camera.translateY(moveVector.y);

        if (colide && checkK) {
          boddy.mass = 1;
          boddy.quaternion.copy(camera.quaternion);
          Name.position.copy(camera.position);
          Name.translateX(moveVector.x);
          Name.translateY(moveVector.y);
          Name.translateZ(moveVector.z - 3);
          boddy.position.copy(Name.position);
        }
        score.innerText = checkK;
        cube.position.copy(cubeBody.position);
        cube.quaternion.copy(cubeBody.quaternion);
        ball.position.copy(ballBody.position);
        ball.quaternion.copy(ballBody.quaternion);
        cube2.position.copy(cubeBody2.position);
        cube2.quaternion.copy(cubeBody2.quaternion);
        cubeBody2.position.copy(camera.position);
        if (clock.elapsedTime - lastResetTime >= resetInterval) {
          lastResetTime = clock.elapsedTime;
        }
      }

      function animate() {
        const delta = clock.getDelta();
        world.step(delta);
        check();
        go();
        renderer.render(scene, camera);
        requestAnimationFrame(animate);
      }

      animate();
    </script>
  </body>
</html>

The glb file to load into the seen

1 Answer 1

2

Place the GLB file in the public(it does not have to be called this) directory and access the file using the absolute path. eg:

loader.load( '/public/free_1975_porsche_911_930_turbo.glb', function ( gltf ) {
// setup code 
});

or in your case:

loader.load( '/free_1975_porsche_911_930_turbo.glb', function ( gltf ) {
// setup code 
});

The initial / denotes the root of the website and the path to the asset will start here.

A typical folder structure for a single-page JavaScript website:

project-root/
│
├── assets/
│    ├── js/
│    │  └── script.js
│    │  └── target2.glb <- (this not typical)
│    ├── css/
│    │  └── style.css
│    ├── models/
│    │  └── target.glb
│    ├── images/
│    └── fonts/
│
└── index.html

For the script.js to access the target.glb or targer2.glb, it can be done in two ways: absolute path or relative path.

Relative paths are specified relative to the current location of the file eg.

  • '../models/target.glb' and .. (dot-dot) represent the parent directory (assets).
  • './target2.glb' and . (dot) represent the current directory (js)

Absolute paths provide the complete path from the root directory to the file eg.

  • '/assets/models/target.glb'.
  • '/assets/js/target2.glb'.

And first / represent the root directory (project-root).

if your's is as follow,

project-root/
│
├── style.css
├── script.js
├── target.glb
└── index.html <- (maybe accessing from embedded script)

then '/target.glb' will do, but this is not the recommended way to structure the files.

Hope this help.

Sign up to request clarification or add additional context in comments.

5 Comments

This code is running on a school Chromebook and it is a folder with the script and the GLB file. What is the public directory and how do I put the file in it?
@BlazeBranham I added some clarification to my answer.
I am 100% sure that this is the fix and your explanation was great and I now understand what you mean, I think the reason it's not working is that my Chromebook is set up so that the school can monitor it, and it prevents some code from working. Thank you so much for your help and I will use this info for future projects!
IT WORKED, I DID WHAT YOU SAID AND RAN IT ON REPLIT INSTEAD OF JUST RUNNING IT IN THE BROWSER AND IT WORKED. THANK YOUUUU
@Blaze Branham Nice. Glad you had success.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.