Skip to content

Instantly share code, notes, and snippets.

@hyzhak
Last active December 17, 2015 06:58
Show Gist options
  • Save hyzhak/5569041 to your computer and use it in GitHub Desktop.
Save hyzhak/5569041 to your computer and use it in GitHub Desktop.
Implement parallax effect by project 3D to 2D
/**
* Component of position in 3D environment
*/
m.$c('ng3D', {
x: 0.0,
y: 0.0,
z: 0.0
});
/**
* Component of parallax effect
*/
m.$c('ngParallax', {
//basis of parallax effect
//1 is original plane, 0.5 - further, 0.25 - twice times further
basis: 0.5
});
/**
* Marker for converting 3D to tune parallax property
*/
m.$c('ngConvert3DtoParallax');
/**
* ngConvert3DtoParallax
*
* Use z to calculate basis of parallax effect.
* Need recalculate each time z has changed
*
*/
m.$s('ngConvert3DtoParallax', {
$require: ['ng3D', 'ngConvert3DtoParallax'],
$addEntity: ['$entity', function($entity) {
if (!$entity.ngParallax) {
$entity.$add('ngParallax');
}
$entity.ngParallax.basis = 1 / (1 + $entity.ng3D.z);
$entity.$remove('ngConvert3DtoParallax');
}]
});
/**
* ngSimpleParallax
*
* Apply parallax effect to calculate 2D position ng2D
* by 3D position (ng3D), parallax basis (ngParallax)
* and look at position (ng2DViewPort).
*
*/
m.$s('ngSimpleParallax', {
$require: ['ng3D', 'ngParallax'],
$addEntity: ['$entity', function($entity) {
if (!$entity.ng2D) {
$entity.$add('ng2D');
}
}],
$update: ['$entity', 'ng2DViewPort', function($entity, ng2DViewPort) {
var ng3D = $entity.ng3D;
var ng2D = $entity.ng2D;
var basis = $entity.ngParallax.basis;
ng2D.x = ng2DViewPort.lookAt.x +
basis * (ng3D.x - ng2DViewPort.lookAt.x);
ng2D.y = ng2DViewPort.lookAt.y +
basis * (ng3D.y - ng2DViewPort.lookAt.y);
}]
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment