Невозможно изменить мне sh цвет при наведении курсора мыши - PullRequest
0 голосов
/ 26 мая 2020

Я пытаюсь изменить цвет меня sh при наведении курсора мыши. Когда мышь «покидает» me sh, me sh должен вернуться к своему обычному цвету.

Вот что я пробовал:

init();
animate(); //calling function that does all the rendering 


//GLOBAL VARS
var scene, camera, renderer;
var raycaster, mouse;

// once everything is loaded, we run our Three.js stuff.
function init() {

  // create a scene, that will hold all our elements such as objects, cameras and lights.
  scene = new THREE.Scene();

  //SET CAMERA
  camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000)
  camera.position.z = 5;

  // create a render and set the size
  renderer = new THREE.WebGLRenderer({
    antialias: true
  });
  renderer.setClearColor("#e5e5e5"); //background color
  renderer.setSize(window.innerWidth, window.innerHeight); //size of renderer

  //bind rendered to the dom element
  document.getElementById("WebGL-output").appendChild(renderer.domElement);


  //RAYCASTER
  raycaster = new THREE.Raycaster();
  mouse = new THREE.Vector2();


  // create a cube
  var cubeGeometry = new THREE.BoxGeometry(20, 0.00001, 20);
  var cubeMaterial = new THREE.MeshLambertMaterial({
    color: 0xffff00
  }); //0xF7F7F7 = gray
  var cube = new THREE.Mesh(cubeGeometry, cubeMaterial);

  // position the cube
  cube.position.x = 0;
  cube.position.y = 3;
  cube.position.z = 0;
  /*
  //USEFUL METHODS
  cube.rotation.x +=0.5
  cube.scale.x +=0.5
  */
  // add the cube to the scene
  scene.add(cube);


  /*  RENDERING A PLANE
  var geometry = new THREE.PlaneGeometry( 20, 20);
  var material = new THREE.MeshBasicMaterial( {color: 0xffff00, side: THREE.DoubleSide} );
  var plane = new THREE.Mesh( geometry, material );
  plane.rotation.set(80,0,0);
  scene.add( plane );
  //plane.position.x = 2;
  */

  //ADDING LIGHTS
  var ambientLight = new THREE.AmbientLight(0x0c0c0c);
  scene.add(ambientLight);
  var spotLight = new THREE.SpotLight(0xffffff);
  spotLight.position.set(-40, 60, -10);
  spotLight.castShadow = true;
  scene.add(spotLight);


  // position and point the camera to the center of the scene
  camera.position.x = -30;
  camera.position.y = 40;
  camera.position.z = 30;
  camera.lookAt(scene.position);


  // when the mouse moves, call the given function
  document.addEventListener('mousemove', onDocumentMouseMove, false);
}

function onDocumentMouseMove(event) {
  // the following line would stop any other event handler from firing
  // (such as the mouse's TrackballControls)
  // event.preventDefault();

  // update the mouse variable
  mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
  mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;


}

function animate() {
  render();
}




function render() {

  // update the picking ray with the camera and mouse position
  raycaster.setFromCamera(mouse, camera);

  // calculate objects intersecting the picking ray
  var intersects = raycaster.intersectObjects(scene.children);

  for (var i = 0; i < intersects.length; i++) {
    intersects[i].object.material.color.set(0xff0000);
  }
  requestAnimationFrame(animate); //pauses when user switches tab
  renderer.render(scene, camera);
}
body {
  /* set margin to 0 and overflow to hidden, to go fullscreen */
  margin: 0;
  overflow: hidden;
}
<div id="WebGL-output"></div>
<script src="https://cdn.jsdelivr.net/npm/three@0.116.1/build/three.min.js"></script>

К сожалению, при рендеринге сцены me sh отображается с красным цветом вместо желтого начального цвета.

1 Ответ

1 голос
/ 26 мая 2020

Когда вы создаете mouse = new THREE.Vector2(), ваши координаты мыши инициируются в (0, 0). Это означает, что при первом рендеринге кадра в центре экрана будет запущен raycast, и материал изменится на 0xff0000.

Если вы хотите, чтобы raycast был "вне экрана" , вы должны инициировать этот вектор со значениями, выходящими за пределы диапазона [-1, 1]: THREE.Vector2(100, 100), так вы не рискуете случайно ударить свои объекты и превратить их в красный цвет.

...