Last active
February 24, 2021 06:18
-
-
Save aranda-adapptor/b6b4dd0755967afb3cee819f2bae43bc to your computer and use it in GitHub Desktop.
Now make it 3D
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Stars positions should be spread evenly between -0.5 and 0.5. | |
// We apply the screen width/height adjustment in the animated style function. | |
for (var i = 0; i < starCount; i++) { | |
stars.push({ | |
id: i, | |
x: Math.random() - 0.5, | |
y: Math.random() - 0.5, | |
}); | |
} | |
const Star: React.FC<StarProps> = (props) => { | |
const animatedStyle = useAnimatedStyle(() => { | |
const t = props.time.value; | |
const { x, y } = props; | |
// For the 3D effect, we can use the star's id as the Z value | |
const z = props.id / starCount; | |
// Animate the Z value by adding time. | |
// Modulo 1 resets stars back to the start when they reach 1 | |
const depth = (z + t) % 1; | |
// Calculate the perspective effect. | |
// The x and y value are divided by the star's depth | |
const invZp = 0.4 / (1 - depth); | |
return { | |
transform: [ | |
// Apply window size and perspective to x and y | |
{ translateX: windowWidth * (0.5 + x * invZp) }, | |
{ translateY: windowHeight * (0.5 + y * invZp) }, | |
// Scale the star based on it's depth | |
{ scaleX: depth }, | |
{ scaleY: depth }, | |
], | |
}; | |
}); | |
// ... | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment