Skip to content

Instantly share code, notes, and snippets.

@floz
Forked from kenjiSpecial/screenToWorldAtZ.js
Created January 12, 2021 08:24
Show Gist options
  • Save floz/5715ee393504b2279a41f0cc23c924b7 to your computer and use it in GitHub Desktop.
Save floz/5715ee393504b2279a41f0cc23c924b7 to your computer and use it in GitHub Desktop.
function screenToWorldAtZ(positionX, positionY, z, camera){
var vector = new THREE.Vector3();
var dX, dY, dZ;
if(this.curObject && this.curObject.parent ){
dX = this.curObject.parent.position.x;
dY = this.curObject.parent.position.y;
dZ = this.curObject.parent.position.z;
}else{
dX = 0; dY = 0, dZ = 0;
}
vector.set(
positionX,
positionY,
0.5 );
camera.updateProjectionMatrix();
camera.updateMatrixWorld();
vector.unproject( camera );
var dir = vector.sub( camera.position ).normalize();
var distance = (z- camera.position.z) / dir.z;
var pos = camera.position.clone().add( dir.multiplyScalar( distance ) );
pos.x -= dX;
pos.y -= dY;
pos.z -= dZ;
return pos;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment