简体   繁体   中英

Trouble getting the value of global 'camera' variable in THREE.js

I have a THREE.js camera object included in my scene as such:

camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 10000 );
camera.position.z = 6;
camera.position.y = 6;

and it works great.

I'm trying to obtain the camera.position.y property in real time as the user interacts with the scene.

var milkyWay = document.getElementById("chap3content");

var trackAngle = function() {
    var camAngle = window.camera.position.y;
    console.log(camAngle);
    return camAngle;
}


milkyWay.onmousedown = function() { 
  console.log("mouse pressed");
  document.addEventListener("mousemove", trackAngle);
  if (camAngle <= 0.25) {
      console.log("SHOW ME THE MONEY");
    }
}

milkyWay.onmouseup = function() {   
    console.log("mouse released");
    document.removeEventListener("mousemove", trackAngle);
}

The function above works as expected and prints the value of camera.position.y into the console log every time the mouse is down and moved across the scene. The issue I am having is the the moment I reference the camAngle variable in the 'if' conditional, console log throws an error saying that camAngle cannot be found.

What gives? I've been trying to solve this for a very long time and have grown frustrated. I need the value of camera.position.y to have something else appear on the DOM for the user to interact with. Changing to window.camera.position.y makes no difference either :(

The variable camAngle is out of scope for milkyWay.onmousedown

This is standard javascript concept that you can learn about with a search of post like this one .

The simplest solution for you here is to lift camAngle to the global scope. Just have:

var camAngle;

at the top of the script and don't redeclare it in functions.

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