agmcleod
agmcleod

Reputation: 13621

Three.JS translate target

Probably just missing something simple here. I have a spot light pointing behind the camera at a plane geometry, along with some randomly positioned boxes. Just trying to do a simple top down like demo. I translate the camera on WASD, copy the position, set the Y to zero, and have the camera look at that position, then translate the light's target to that position as well. The camera moves fine but the light does not change target. At least from what I can tell.

I create my light & target:

this.playerLight = new THREE.SpotLight(0xffffff);
this.playerLight.castShadow = true;
this.playerLight.position.set(0, 40, 0);
this.spotlightTarget = new THREE.Object3D();
this.spotlightTarget.position.set(0, 0, 0);
this.playerLight.target = this.spotlightTarget;
this.playerLight.shadowCameraVisible = true;
this.scene.add(this.playerLight);

Then my keydown event handling:

window.addEventListener("keydown", function (e) {
  var moved = false;
  switch ( event.keyCode ) {
    case 87: // W
      e.preventDefault();
      _this.camera.position.x -= 0.2;
      moved = true;
      break;
    case 65: // A
      e.preventDefault();
      _this.camera.position.z += 0.2;
      moved = true;
      break;
    case 83: // S
      e.preventDefault();
      _this.camera.position.x += 0.2;
      moved = true;
      break;
    case 68: // D
      e.preventDefault();
      _this.camera.position.z -= 0.2;
      moved = true;
      break;
    default:
      return true;
  }

  if (moved) {
    var lookAtPos = _this.camera.position.clone();
    lookAtPos.y = 0;
    _this.camera.lookAt(lookAtPos);
    _this.playerLight.position.x = lookAtPos.x;
    _this.playerLight.position.z = lookAtPos.z;
    _this.spotlightTarget.position.set(lookAtPos.x, lookAtPos.y, lookAtPos.z);
  }
}, false);

Any ideas?

Upvotes: 1

Views: 663

Answers (1)

WestLangley
WestLangley

Reputation: 104793

Your spotlight target has been translated, but the spotlight does not follow.

Spotlight.target is a property of the light, but it is not part of the scene graph in three.js r.69.

So, unfortunately, target.matrix and target.matrixWorld are not being updated.

The work-around is to add spotlight.target to the scene. Another workaround is to set an object that is already in your scene as the target:

spotLight.target = myObject;

three.js r.69

Upvotes: 2

Related Questions