How do I tie an object to the mouse? (with playground example)

Solved! For some reason I didn’t need the * 2 + 1 and * 2 - 1 bits.

I also decided to use engine render width and height rather than the inner window width and height. This code doesn’t work in the playground but does work with my full screen app.

window.addEventListener("mousemove", function (event) {
  event.preventDefault();
  if (!player) return;
  mouseVector.set((event.clientX / engine.getRenderWidth()), (event.clientY / engine.getRenderHeight()), 0.5);
  let uvec = BABYLON.Vector3.Unproject(mouseVector, 1, 1, BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  var dir = uvec.subtract(camera.position).normalize();
  var distance = -camera.position.z / dir.z;
  var pos = camera.position.clone().add(dir.scale(distance));

  player.position = pos;
});
3 Likes