Skip to content

Instantly share code, notes, and snippets.

@nickjanssen
Created October 26, 2014 14:50
Show Gist options
  • Save nickjanssen/38d8211367afaef02bc1 to your computer and use it in GitHub Desktop.
Save nickjanssen/38d8211367afaef02bc1 to your computer and use it in GitHub Desktop.
var getDirectionSpriteIndex = function (entity, world) {
var entitiesWithCamera = world.getEntities('camera');
var index = 0;
if (entitiesWithCamera.length) {
var activeCamera = entitiesWithCamera[0].getComponent('camera').camera;
var camWorldPos = new THREE.Vector3();
camWorldPos.setFromMatrixPosition(activeCamera.matrixWorld);
var directionVec = camWorldPos;
directionVec.sub(entity.position);
var rotVec = new THREE.Vector3(0, 0, 1);
rotVec.applyEuler(entity.rotation);
var rotY = (Math.atan2(rotVec.z, rotVec.x));
if ( rotY < 0 ) {
rotY += (Math.PI*2);
}
rotY = (Math.PI*2) - rotY;
// Rotate vector with our own rotation
var tx = ((directionVec.x * Math.cos(rotY)) - (directionVec.z * Math.sin(rotY)));
var tz = ((directionVec.x * Math.sin(rotY)) + (directionVec.z * Math.cos(rotY)));
directionVec.x = tx;
directionVec.z = tz;
var result = Math.atan2(directionVec.z, directionVec.x);
result += Math.PI;
while (result < 0) {
result += (Math.PI * 2);
}
while (result > (Math.PI * 2)) {
result -= (Math.PI * 2);
}
if (result >= 0.39 && result <= 1.17) {
index = 3;
} else if (result > 1.17 && result <= 1.96) {
index = 2;
} else if (result > 1.96 && result <= 2.74) {
index = 1;
} else if (result > 2.74 && result <= 3.53) {
index = 0;
} else if (result > 3.53 && result <= 4.31) {
index = 7;
} else if (result > 4.31 && result <= 5.10) {
index = 6;
} else if (result > 5.10 && result <= 5.89) {
index = 5;
} else {
index = 4;
}
}
return index;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment