Skip to content

Instantly share code, notes, and snippets.

@jgphilpott
Last active May 16, 2023 19:26
Show Gist options
  • Save jgphilpott/a94db3a3b7859993ab4cb5bb22b83be1 to your computer and use it in GitHub Desktop.
Save jgphilpott/a94db3a3b7859993ab4cb5bb22b83be1 to your computer and use it in GitHub Desktop.
A collection of functions for converting coordinates between different dimensions.
### Dimension Conversions ###
convertDimension =
d2: {}
d3: {}
### 2D Conversions ###
# Credit: https://stackoverflow.com/a/13091694/1544937
convertDimension.d2.d3 = d2$d3 = (x, y, zTarget = 0) ->
vector = new THREE.Vector3()
coordinates = new THREE.Vector3()
vector.set (x / window.innerWidth) * 2 - 1, -(y / window.innerHeight) * 2 + 1, 0
vector.unproject camera
vector.sub(camera.position).normalize()
distance = (zTarget - camera.position.z) / vector.z
coordinates.copy(camera.position).add vector.multiplyScalar distance
return coordinates
convertDimension.d2.d2 = d2$d2 = (x, y) -> new THREE.Vector2 x, y
### 3D Conversions ###
# Credit: https://stackoverflow.com/a/36706930/1544937
convertDimension.d3.d2 = d3$d2 = (x, y, z) ->
halfWidth = window.innerWidth / 2
halfHeight = window.innerHeight / 2
coordinates = new THREE.Vector3 x, y, z
coordinates.project camera
coordinates.x = coordinates.x * halfWidth + halfWidth
coordinates.y = -coordinates.y * halfHeight + halfHeight
return new THREE.Vector2 coordinates.x, coordinates.y
convertDimension.d3.d3 = d3$d3 = (x, y, z) -> new THREE.Vector3 x, y, z
/* Dimension Conversions */
var convertDimension, d2$d2, d2$d3, d3$d2, d3$d3;
convertDimension = {
d2: {},
d3: {}
};
/* 2D Conversions */
// Credit: https://stackoverflow.com/a/13091694/1544937
convertDimension.d2.d3 = d2$d3 = function(x, y, zTarget = 0) {
var coordinates, distance, vector;
vector = new THREE.Vector3();
coordinates = new THREE.Vector3();
vector.set((x / window.innerWidth) * 2 - 1, -(y / window.innerHeight) * 2 + 1, 0);
vector.unproject(camera);
vector.sub(camera.position).normalize();
distance = (zTarget - camera.position.z) / vector.z;
coordinates.copy(camera.position).add(vector.multiplyScalar(distance));
return coordinates;
};
convertDimension.d2.d2 = d2$d2 = function(x, y) {
return new THREE.Vector2(x, y);
};
/* 3D Conversions */
// Credit: https://stackoverflow.com/a/36706930/1544937
convertDimension.d3.d2 = d3$d2 = function(x, y, z) {
var coordinates, halfHeight, halfWidth;
halfWidth = window.innerWidth / 2;
halfHeight = window.innerHeight / 2;
coordinates = new THREE.Vector3(x, y, z);
coordinates.project(camera);
coordinates.x = coordinates.x * halfWidth + halfWidth;
coordinates.y = -coordinates.y * halfHeight + halfHeight;
return new THREE.Vector2(coordinates.x, coordinates.y);
};
convertDimension.d3.d3 = d3$d3 = function(x, y, z) {
return new THREE.Vector3(x, y, z);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment