简体   繁体   中英

How to use a variable from one js file in another file?

I have a basic cube scene with Three.js

Now I want the camera to move with perlin noise. So I downloaded this Perlin noise library and pasted it next to the other libraries:

https://github.com/josephg/noisejs

I also linked added the script in the html :

<script src="three.min.js"></script>  
<script src="my-three.js"></script>  
<script src="perlin.js"></script> 

Then i want to use the noise, so i created a variable at the end of the perlin.js file, like this :

var ruido = noise.simplex3(10, 10, 1);

Last step would be to use this variable in the camera, so in my "my-three.js" file i added this line:

camera.position.z = ruido;

But i get a :

Uncaught ReferenceError: ruido is not defined

Somehow the variable is not being received in the "my-three.js" file.

The full "my-three.js" file is:

  var scene = new THREE.Scene();
  var camera = new THREE.PerspectiveCamera( 75, window.innerWidth/window.innerHeight, 0.1, 1000 );

  var renderer = new THREE.WebGLRenderer();
  renderer.setSize( window.innerWidth, window.innerHeight );
  document.body.appendChild( renderer.domElement );

  var geometry = new THREE.BoxGeometry( 1, 1, 1 );
  var material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  var cube = new THREE.Mesh( geometry, material );
  scene.add( cube );

  camera.position.z = ruido;

  var render = function () {
    requestAnimationFrame( render );

    cube.rotation.x += 0.001;
    cube.rotation.y += 0.001;

    renderer.render(scene, camera);
  };

  render();

Thanks in advance.

You should include the perlin.js file before the my-three.js file, since the my-three.js is depended on the perlin.js file.

<script src="perlin.js"></script> 
<script src="my-three.js"></script>  

You can use AMD (Asynchronous Module Definition) approach and libraries that implements it.

https://github.com/amdjs/amdjs-api/blob/master/AMD.md

It solves this and many similar problems with variables, modules, its dependencies and so on.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM