Skip to main content

How to move 3D Model Position THREE.js

I'm trying to create a walking 3D model in three.js. I have both the 3D model and the in place fbx walking animation from Mixamo imported into my project. The model and animation works as expected; the model "walks" due to the loaded animation but stays in the same position. My problem is trying to get the position of the model to increment each frame to give the illusion that the model is walking forwards.

Here is my code:

import './style.css'
import * as THREE from 'three';
import { FontLoader } from 'three/examples/jsm/loaders/FontLoader';
import { TextGeometry } from 'three/examples/jsm/geometries/TextGeometry';
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader';
import { Reflector } from 'three/examples/jsm/objects/Reflector.js';
import { FirstPersonControls } from 'three/examples/jsm/controls/FirstPersonControls.js';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js';
import { FBXLoader } from 'three/examples/jsm/loaders/FBXLoader';


let glow = 0.05;
let clock = new THREE.Clock();


/* CREATE CAMERA */

  const camera = new THREE.PerspectiveCamera( 100, window.innerWidth / window.innerHeight, 0.01, 4000);
  camera.position.setZ(1);
  camera.position.setX(200);
  camera.position.setY(10);
  // camera.lookAt(50, 0, -1200);

/* END CAMERA */


/* CREATE SCENE & FOG */

  const scene = new THREE.Scene();
  var setcolor = 0x3A4544;
  scene.background = new THREE.Color(setcolor);
  //scene.fog = new THREE.Fog(setcolor, 0, 4000);

/* END SCENE & FOG */



/* CREATE RENDERER */

  const renderer = new THREE.WebGLRenderer( { antialias: true, alpha: true } );
  renderer.setSize( window.innerWidth, window.innerHeight );
  renderer.setAnimationLoop( animation );
  renderer.setPixelRatio( window.devicePixelRatio );
  renderer.shadowMap.enabled = true;
  renderer.outputEncoding = THREE.sRGBEncoding;
  document.body.appendChild( renderer.domElement );

/* END RENDERER */


/* CREATE ORBIT CONTROLS */

  const controls = new OrbitControls( camera, renderer.domElement );
  // const controls = new FirstPersonControls( camera, renderer.domElement );
  // controls.movementSpeed = 50;
  // controls.lookSpeed = 0.05;
  // controls.lookVertical = true;
  // controls.constrainVertical = true

/* END ORBIT CONTROLS */


/* CREATE LIGHTS */

  const rectLight = new THREE.RectAreaLight( 0xf9d71c, glow, 150, 100 );
  scene.add( rectLight );
  rectLight.position.set( -8, 100, -290 );
  rectLight.lookAt( 0, 0, 0 );

  const ambientLight = new THREE.AmbientLight(0xaaaaaa, 0.15)
  ambientLight.position.set( 200, 100, 0 );
  ambientLight.lookAt( -300, -300, -300 );
  scene.add(ambientLight)

/* END LIGHTS */


/* CREATE CITY */

  // Floor
  let groundMirror1, geometry;
  geometry = new THREE.PlaneGeometry( 2500, 2500 );
  groundMirror1 = new Reflector( geometry, {
    clipBias: 0.003,
    color: new THREE.Color(0x212227),
    side: THREE.DoubleSide,
    mixBlur: 5    
  });

  groundMirror1.position.y = -50
  groundMirror1.rotateX( - Math.PI / 2);

  scene.add( groundMirror1 );




  // 3D Building Font
  let text = "JOHN JACOBS";
  let textMesh;

  const loader = new FontLoader();
  loader.load('node_modules/three/examples/fonts/droid/droid_serif_regular.typeface.json', function (font) {
    const textGeometry = new TextGeometry(text, {
      font: font,
      size: 40,
      height: 1,
      curveSegments: 12,
      bevelEnabled: true,
      bevelThickness: 2,
      bevelSize: 2,
      bevelOffset: 2,
      bevelSegments: 2
    });

    textMesh = new THREE.Mesh(textGeometry, [
      new THREE.MeshPhongMaterial({ emissive: 0xf9d71c, emissiveIntensity: glow }),
      new THREE.MeshPhongMaterial({ color: 0xffffff })
    ]);

    scene.add( textMesh );

    textMesh.position.y = 1685;
    textMesh.position.x = -2000;
    textMesh.position.z = 250;
    textMesh.rotation.y = ( Math.PI / 2 );
  });


  // 3D Models
  const gltfLoader1 = new GLTFLoader();
  gltfLoader1.load('models/building2/scene.gltf', (gltfScene1) => {
    gltfScene1.scene.scale.set( 20, 20, 20 );
    gltfScene1.scene.position.x = 20;
    gltfScene1.scene.position.z = 180;
    gltfScene1.scene.position.y = -50;
    scene.add(gltfScene1.scene);
  });

  const gltfLoader2 = new GLTFLoader();
  gltfLoader2.load('models/building3/scene.gltf', (gltfScene2) => {
    gltfScene2.scene.scale.set( 80, 80, 80 );
    gltfScene2.scene.position.x = -75;
    gltfScene2.scene.position.z = -400;
    gltfScene2.scene.position.y = -1410;
    gltfScene2.scene.rotation.y = ( - Math.PI / 2 )
    scene.add(gltfScene2.scene);
  });

  const gltfLoader3 = new GLTFLoader();
  gltfLoader3.load('models/building4/scene.gltf', (gltfScene3) => {
    gltfScene3.scene.scale.set( 70, 70, 70 );
    gltfScene3.scene.position.x = -500;
    gltfScene3.scene.position.z = 300;
    gltfScene3.scene.position.y = 75;
    scene.add(gltfScene3.scene);
  });

  const gltfLoader4 = new GLTFLoader();
  gltfLoader4.load('models/main_building/scene.gltf', (gltfScene4) => {
    gltfScene4.scene.scale.set( 10, 10, 10 );
    gltfScene4.scene.position.x = -2600;
    gltfScene4.scene.position.z = -450;
    gltfScene4.scene.position.y = 75;
    gltfScene4.scene.rotation.y = ( Math.PI / 2);
    scene.add(gltfScene4.scene);
  });

  const gltfLoader5 = new GLTFLoader();
  gltfLoader5.load('models/building5/scene.gltf', (gltfScene5) => {
    gltfScene5.scene.scale.set( 10, 10, 10 );
    gltfScene5.scene.position.x = -2600;
    gltfScene5.scene.position.z = -500;
    gltfScene5.scene.position.y = 275;
    scene.add(gltfScene5.scene);
  });

  // 3D model and walking animation
  let mixer;
  const zomLoader = new FBXLoader();
  zomLoader.load('models/characters/Ch44_nonPBR.fbx', (fbx) => {
    
    fbx.position.x = -500;
    fbx.position.z = 0;
    fbx.position.y = -50;
    fbx.rotation.y = ( Math.PI / 2 );
    fbx.scale.set( 1, 1, 1 );

    const anim = new FBXLoader();
    anim.load('models/characters/Walking.fbx', (anim) => {
      mixer = new THREE.AnimationMixer(fbx);
      const idle = mixer.clipAction(anim.animations[0]);
      idle.play();
    })
    scene.add(fbx)
  });

/* END CITY */


/* CREATE WINDOW RESIZE FUNCTION */

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

/* END WINDOW RESIZE FUNCTION */



/* CREATE MAIN ANIMATION FUNCTION */

  animation();
  function animation() {

    requestAnimationFrame( animation );

    //I've tried these two options 
    //fbx.position.x += 0.5;
    //zomLoader(fbx).position.x += 0.5;


    glow = Math.random() - 0.01;
    textMesh.material[0].emissiveIntensity = glow;
    rectLight.intensity = glow;


    if(mixer){
      mixer.update(clock.getDelta());
    }


    //controls.update( clock.getDelta() );
    controls.update();
    renderer.render( scene, camera );

  }

/* END MAIN ANIMATION FUNCTION */

I'm still new to three.js, and the only times I've moved any object were meshs, not imported 3D models. I'm used to using mesh.position.x += 1 inside the main animation function, but when I try to apply that to the model using fbx.position.x += 1, the scene disappears. How can I move the 3D model position to give the illusion the model is walking along the x-axis?

EDIT

I figured it out. I added a global variable let human;, assigned it to fbx and used human.position.x += 1 in the main animation function. Cheers.

Via Active questions tagged javascript - Stack Overflow https://ift.tt/rH9ija7

Comments

Popular posts from this blog

How to show number of registered users in Laravel based on usertype?

i'm trying to display data from the database in the admin dashboard i used this: <?php use Illuminate\Support\Facades\DB; $users = DB::table('users')->count(); echo $users; ?> and i have successfully get the correct data from the database but what if i want to display a specific data for example in this user table there is "usertype" that specify if the user is normal user or admin i want to user the same code above but to display a specific usertype i tried this: <?php use Illuminate\Support\Facades\DB; $users = DB::table('users')->count()->WHERE usertype =admin; echo $users; ?> but it didn't work, what am i doing wrong? source https://stackoverflow.com/questions/68199726/how-to-show-number-of-registered-users-in-laravel-based-on-usertype

Why is my reports service not connecting?

I am trying to pull some data from a Postgres database using Node.js and node-postures but I can't figure out why my service isn't connecting. my routes/index.js file: const express = require('express'); const router = express.Router(); const ordersCountController = require('../controllers/ordersCountController'); const ordersController = require('../controllers/ordersController'); const weeklyReportsController = require('../controllers/weeklyReportsController'); router.get('/orders_count', ordersCountController); router.get('/orders', ordersController); router.get('/weekly_reports', weeklyReportsController); module.exports = router; My controllers/weeklyReportsController.js file: const weeklyReportsService = require('../services/weeklyReportsService'); const weeklyReportsController = async (req, res) => { try { const data = await weeklyReportsService; res.json({data}) console...

ValueError: X has 10 features, but LinearRegression is expecting 1 features as input

So, I am trying to predict the model but its throwing error like it has 10 features but it expacts only 1. So I am confused can anyone help me with it? more importantly its not working for me when my friend runs it. It works perfectly fine dose anyone know the reason about it? cv = KFold(n_splits = 10) all_loss = [] for i in range(9): # 1st for loop over polynomial orders poly_order = i X_train = make_polynomial(x, poly_order) loss_at_order = [] # initiate a set to collect loss for CV for train_index, test_index in cv.split(X_train): print('TRAIN:', train_index, 'TEST:', test_index) X_train_cv, X_test_cv = X_train[train_index], X_test[test_index] t_train_cv, t_test_cv = t[train_index], t[test_index] reg.fit(X_train_cv, t_train_cv) loss_at_order.append(np.mean((t_test_cv - reg.predict(X_test_cv))**2)) # collect loss at fold all_loss.append(np.mean(loss_at_order)) # collect loss at order plt.plot(np.log(al...