<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Wojciech Stanisz on Medium]]></title>
        <description><![CDATA[Stories by Wojciech Stanisz on Medium]]></description>
        <link>https://medium.com/@wojciech.stanisz?source=rss-40c59ee9b85e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*k5LsT_1nEZT-kRUI</url>
            <title>Stories by Wojciech Stanisz on Medium</title>
            <link>https://medium.com/@wojciech.stanisz?source=rss-40c59ee9b85e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 22:04:48 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@wojciech.stanisz/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Building Reigns: How to reign over mobile game development using Reanimated 2. Pa]]></title>
            <link>https://medium.com/swmansion/building-reigns-how-to-reign-over-mobile-game-development-using-reanimated-2-pa-55ae2017df50?source=rss-40c59ee9b85e------2</link>
            <guid isPermaLink="false">https://medium.com/p/55ae2017df50</guid>
            <category><![CDATA[reanimated]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[mobile-games]]></category>
            <dc:creator><![CDATA[Wojciech Stanisz]]></dc:creator>
            <pubDate>Mon, 21 Jun 2021 09:13:59 GMT</pubDate>
            <atom:updated>2021-06-22T08:51:09.616Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7O1GFTCWd_2MlAwgznarBw.png" /></figure><h3>Building Reigns: How to reign over mobile game development using Reanimated 2. Part 3</h3><p>This is the last post in a series dedicated to building a clone of Reigns game in React Native using Reanimated 2 and Gesture Handler. If you haven’t seen the first two parts you can find part one where we implemented the gesture handler <a href="https://blog.swmansion.com/reanimated-2-the-game-9402622c1fe5">here</a> and the second part where we focus mostly on the animations <a href="https://blog.swmansion.com/building-reigns-how-to-strengthen-reign-over-mobile-game-development-using-reanimated-2-66c127a210e9">here</a>. Our last meeting will finalize our project by adding game logic, show questions, and making the initial animation.</p><p>Like in the previous articles, you can find the code in the Github repository that you can visit by clicking the iteration link next to the title of each chapter.</p><h3>Add basic logic — <a href="https://github.com/wojtus7/reanimated-story-cards/tree/iteration-6">iteration-6</a></h3><p>The time has come. Our creation will be alive! (At least a little bit).</p><p>In order to make the game playable, we need to determine when the player makes a decision by swinging the card to the side of the screen. To do so, we will use two metrics: velocity and position.</p><p>By combining the current position and multiplying velocity by a given time (in this example it will be 0.2 sec) we can simulate toss and see where the released element is going to land. Based on this information we can decide if the player made a decision by moving the card to any side of the screen or should it return to the deck on the center of the screen.</p><p>To make such recognition possible we have to modify the gestureHandler (created in <em>iteration-1).</em></p><p>Conditional statements are pretty simple here. The one thing you should know about them is that there are different useful pieces of information inside the event object, for example: velocity. What’s more interesting is the runOnJS function with quite a distinct syntax. This strange line of code lets us call JS functions inside Reanimated’s code block. In this case, we don’t pass any prop to our function but instead, this syntax allows us to pass props to the function using second brackets like:</p><p>runOnJS(func)(prop1, prop2);</p><p>An important note here: You shouldn’t try to run JS functions declared outside reanimated code blocks inside it without runOnJS.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/0*JNaF9sYPL5ulhbcW" /><figcaption><em>Upgraded onEnd handler in useAnimatedGestureHandler created earlier.</em></figcaption></figure><p>Worth noting here is that you should always pass velocity to the withSpring hook to keep smooth and persistent animation.</p><p>The actual handler lives in the <em>Screen.js</em> file and is passed to the Card via prop.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/484/0*vwJljTppYIRj8kcJ" /></figure><p>Handler sets the showCard flag to false to remove the old card loads the next card data and switches the flag to show it again. Each time Card gets a new date, it fires flip animation. This way, every new card is shown in a smooth, animated manner.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/474/0*1jUc7nGd-GsElYwH" /><figcaption><em>useEffect used to control basic logic of the application.</em></figcaption></figure><p>As you can see there is also a small trick here. The card is rendered and then flipped, but only after 200 milliseconds await.</p><p>What’s worth noting here is using the new withDelay hook. This is a simple hook that will delay the start of an animation by a given time. This is a really simple way to make sure all data in the front of the card (like avatar picture) actually managed to load and show up, without any visual glitches. There should be some more advanced logic but I didn’t want to add unnecessary complexity to an already big example.</p><p>To make the card active after the end of animation I used the animation callback of withTiming function. You can read more about it <a href="https://docs.swmansion.com/react-native-reanimated/docs/api/withTiming/#callback-functionoptional">here</a>.</p><h3>Start game animation — <a href="https://github.com/wojtus7/reanimated-story-cards/tree/iteration-7">iteration-7</a></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/401/1*3eOWYdmsN5FQbujr5fEzAw.gif" /><figcaption><em>Result of iteration-7 code.</em></figcaption></figure><p>At this stage, we should make a couple of animated cards slide into the welcome screen of the game. To do so, we need to import them in the <em>Screen.js </em>file like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/636/0*5IaRnI7dUdbWLDCg" /></figure><p>As you can see, I created separate Static and Animated reverse cards. That’s because we need one reversed card always on the bottom to simulate the deck. But since we animate 5 different cards into the screen, it would be a waste to keep all 5 of them on the screen for the rest of the game, if we are not going to use them anymore. Following that logic, we have separate components for animated cards, and one separate for the static card that will stay on the screen for the rest of the game.</p><p>Let’s take a closer look at the animated card, shall we?</p><p>Previously, using Animated.View we created a separate animatedStyle for each card. It worked because each style was unique. But now, since we need to create a couple of components with the exact same styles and the only difference will be timing it will be better to automatize it somehow. How?</p><p>The answer is: ‘worklet’.</p><p>Let’s take a look at Card in <em>PlaceholderBackCards.js</em>. As you can see, I used useAnimatedStyle in a little different manner here. Instead of passing an object that contains static useAnimatedStyle inside, I used the useAnimatedStyle hook to wrap the function that will get the index.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/706/0*myBTP0LTWRCbrZnB" /></figure><p>cardTransform function is a ‘worklet’. That means we can use it in Reanimated 2 code. This way I can pass an index and make a small adjustment in style based on a given variable.</p><p>What’s worth noting here is using the withDelay hook. In my case, the delay itself is calculated based on the passed index.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/593/0*1WIU-uU5KYrd2zg6" /></figure><h3>Animated questions — <a href="https://github.com/wojtus7/reanimated-story-cards/tree/iteration-8">iteration-8</a></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/401/0*jrtgCCPSqr38NC0B" /><figcaption><em>Result of iteration-8 code.</em></figcaption></figure><p>Question time!</p><p>First things first, let’s add the question component to the main render. As you can see the component is not shown conditionally this time. The visibility of the component will be controlled by showQuestion flag passed as a prop to the component.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/653/0*NYTfWGLOVJP_3Euz" /></figure><p>This time we don’t need to create any shared values or create any useEffect to handle our animation. If your animations are really simple and need to be performed once the props change you can simply put them straight into the useAnimatedStyle and calculate them directly inside the returned style object.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/0*23nYWEA0QxwJWqHi" /></figure><p>Lastly, we have to use our new animatedWrapper, as a style for Animated.View and we are done!</p><p>Viola! That was <strong>fast</strong>!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/611/0*BCcTm4VJwf0sIj8h" /></figure><h3>Animated elements: final touch — <a href="https://github.com/wojtus7/reanimated-story-cards/tree/iteration-9">iteration-9</a></h3><p>Final iteration!</p><p>Time for an ultimate trial!</p><p>This time it’s gonna be different. I won’t describe each step. This time <strong><em>YOU </em></strong>will do it yourself. If you followed all the previous steps I’m pretty sure you can do it. I haven’t used any new technique or API so figuring out what happened in the last iteration will be a pretty good exercise. Good luck!</p><p>I strongly recommend looking for new things in <a href="https://github.com/wojtus7/reanimated-story-cards/blob/iteration-9/Screen.js"><em>Screen.js</em></a><em> </em>and finding new components there.</p><p>But if you don’t feel like trying today and just wanna see how the last iteration looks like, and how it works, here’s part for you:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*ewEKnGzTJ9uc9rhSfvBuCA.gif" /><figcaption><em>Result of the final iteration</em></figcaption></figure><p>In <a href="https://github.com/wojtus7/reanimated-story-cards/blob/iteration-9/Screen.js"><em>Screen.js</em></a><em> </em>you can find a new PowerIndicators component with currentMood prop. currentMood is an object containing two arrays: happy and sad containing info on who should be amazed by the player’s answer and who should be enraged. Those arrays are set in the handlers of left and right answers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/0*KrZ6FQFdJH94q_l2" /></figure><p>currentMood property is processed in the <a href="https://github.com/wojtus7/reanimated-story-cards/blob/iteration-9/PowerIndicators.js"><em>PowerIndicators.js</em></a> to get info about each person and push it as a prop to the next components in which we are checking if the selected person should react to the current action and handle this information in <a href="https://github.com/wojtus7/reanimated-story-cards/blob/iteration-9/PowerPerson.js"><em>PowerPerson.js</em></a><em> </em>file by firing suitable animation. In case somebody is happy with the player’s answer it’s gonna be a heart, and in case somebody is not in fond of the action it’s a rainy cloud.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/473/1*wAD4doErLVvLXcln1_Zc9w.png" /><figcaption>Power person mood animations.</figcaption></figure><p>In the return statement, we can see that the heart and cloud images are hardcoded and the only thing that is changing are the styles of the animated wrapper.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/701/0*MlPHuJiODG_6a_B8" /></figure><p>That’s it. Whole application. What a journey!</p><h3>Time to steal some hearts!</h3><p>Now you know it all. You are ready to make the best animations out there with brand new, cutting-edge technology! If you want to learn more you can always read the<a href="https://docs.swmansion.com/react-native-reanimated/docs/"> official documentation</a> or read about the library itself<a href="https://blog.swmansion.com/reanimated-2-0-stable-release-is-out-564c9c910891"> here</a>.</p><p>The possibilities are endless! You can create games, apps, try to recreate your old project, or enhance existing react-native ones! Time to steal the hearts of your users!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=55ae2017df50" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swmansion/building-reigns-how-to-reign-over-mobile-game-development-using-reanimated-2-pa-55ae2017df50">Building Reigns: How to reign over mobile game development using Reanimated 2. Pa</a> was originally published in <a href="https://medium.com/swmansion">Software Mansion</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Reigns: How to strengthen reign over mobile game development using Reanimated 2.]]></title>
            <link>https://medium.com/swmansion/building-reigns-how-to-strengthen-reign-over-mobile-game-development-using-reanimated-2-66c127a210e9?source=rss-40c59ee9b85e------2</link>
            <guid isPermaLink="false">https://medium.com/p/66c127a210e9</guid>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[mobile-games]]></category>
            <category><![CDATA[app-development]]></category>
            <category><![CDATA[reanimated]]></category>
            <dc:creator><![CDATA[Wojciech Stanisz]]></dc:creator>
            <pubDate>Thu, 27 May 2021 09:18:42 GMT</pubDate>
            <atom:updated>2021-05-27T09:20:25.563Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nKeEnkHA1HlOxopKk8Moiw.png" /></figure><p>This is the second post in a series dedicated to building a clone of Reigns game in React Native using Reanimated 2 and Gesture Handler. If you haven’t seen the first part where we focused on the gesture handling implementation you can find it <a href="https://blog.swmansion.com/reanimated-2-the-game-9402622c1fe5">here</a>. This time around we are going to focus more on the visuals. We’ll create dynamic text and flip animations, imitate shadows, and put graphics to make our card look superb!</p><p>Like in the previous article you can find the code in the Github repository that you can visit by clicking the iteration link next to the title of each chapter.</p><h3>Animated text — <a href="https://github.com/wojtus7/reanimated-story-cards/tree/iteration-2">iteration-2</a></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/401/0*8YO8FLLpieVXgSpj" /><figcaption><em>Result of iteration-2 code.</em></figcaption></figure><p>As the very first step of this part of the tutorial, we are going to add text to our card that reacts to its transition in the following manner: it will show the right option only when the card is moved a little to the right and the left option only when the card is swiped to the left.</p><p>The new render looks something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dyKF8K3tLyfW-e-N" /></figure><p>As you can see there are two new separate text wrappers (highlighted blue and green) instead of one conditional text render like:</p><pre>&lt;Animated.Text&gt;<br>  {x.value &gt; 0 ? rightText : leftText}<br>&lt;/Animated.Text&gt;</pre><p>We have to remember that it’s not that simple to use shared value in code. We can’t use it simply in the code even if the component itself is Animated.View or Animated.Text. If we really wanted to make only one text wrapper we should use the useAnimatedProps hook (you can read about it <a href="https://docs.swmansion.com/react-native-reanimated/docs/api/useAnimatedProps/">here</a>), but for simplicity in this example we always render two separate components and animate their opacity based on the card’s movement.</p><p>The second thing that you may notice is that each animated text wrapper got some separate animatedSideTextWrapper style assigned to it. Those style objects look almost the same with the small exception that the interpolator got opposite input values. An example for the right wrapper looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/658/0*CgHHDcilxyZ2b5E6" /><figcaption><em>Right text wrapper’s style.</em></figcaption></figure><p>The last thing worth noting in this step is topTextWrapper style object because the values assigned are a little odd at a first glance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/430/0*-UFwqeCl5qoppMXX" /></figure><p>Interesting values here are width , left and right . The simple explanation for them would be that we want to rotate one component inside a different component and that’s really troublesome. I think there’s no use in explaining in words something that you can understand with only one picture:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/430/0*4TqzO8D5xD9x81-8" /><figcaption><em>Broken card styles.</em></figcaption></figure><p>To solve the problem we can just create a component a little too big so the rotation won’t expose the boundaries, just like we did in the styles above.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/426/0*xKAShTgk9L6F79-W" /><figcaption><em>Card after fixing the styles.</em></figcaption></figure><h3>Flip animation — <a href="https://github.com/wojtus7/reanimated-story-cards/tree/iteration-3">iteration-3</a></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/406/0*02XzPZpZzb9x7Ylf" /><figcaption><em>Result of iteration-3 code.</em></figcaption></figure><p>A very important part of Reigns is showing the next cardin a smooth deck-like manner. To make animation possible we will add a new wrapper that contains the whole card and rotate it accordingly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CnHB_qBUqTboW22G" /></figure><p>Theoretically, we could use Animated.View located directly below to get only one Animated.View responsible for both animation but since it’s used to animate finger movement I wanted to keep it as simple and as clear as possible. I did this by keeping the single responsibility for each Animated.View,so we get a separate View to turn the card around and to move it around using gestures.</p><p>To rotate our card we will need a new shared value. Just to keep learning something new our new value will start with initial value 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/388/0*7VbDByOQ6YxVh96u" /><figcaption><em>New shared value initialization.</em></figcaption></figure><p>Now’s the time to use it. Let’s use the useAnimatedStyle. Inside we can see three props changed based on openAnimation shared value: scale, perspective, and rotateY.</p><p>The only necessary change is rotateY moved by 180 degrees but scale and perspective are making the animation so much prettier! You can try to tweak all those values to see how it changes the look!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/652/0*kSjrseS07GqHTg8A" /><figcaption><em>Style logic controlling our card’s flip animation.</em></figcaption></figure><p>Movement shared values like x and y are controlled by gesture handler. This time we would rather flip the card by using a trigger inside the code. That’s why I added a new button that controls the openAnimation shared value. It should be animated from initial 1 to 2 and back again. This time around we can use a new function: instead of withSpring — that we are already familiar with — we can use new withTiming.</p><p>It works almost the same as withSpring but this time around it’s not calculated based on physics values, but it’s based on some predefined bezier curve the animation will follow. All animation adjustments can be set in the config object, but in my case, I only adjusted the duration of the animation to make it a little longer than the default value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/675/0*SjjRuUsdf7nSnN__" /><figcaption><em>Pressing this button will flip the card.</em></figcaption></figure><h3>Creating card’s front and back — <a href="https://github.com/wojtus7/reanimated-story-cards/tree/iteration-4">iteration-4</a></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/381/0*9S4omDaULckBtewE" /><figcaption><em>Result of iteration-4 code.</em></figcaption></figure><p>This step’s gonna be easy!</p><p>This time around the only thing we add is just some graphics for the card front and reverse. For that reason, in our render method, we can find new <em>CardPerson.js</em> and <em>CardReverse.js</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6Ur0VOrTY8IC4Wk7" /></figure><p>But…we can’t just simply add them. We also need to write a logic that will determine when to show the card and which side of the card should be presented. Since we know the card flip animation is based on openAnimation shared value that travels between values 1 and 2, we can safely assume we should stop rendering the reverse just in the middle when the value exceeds 1.5.</p><p>For that reason, we can add a new opacity prop to previously created animatedFront style, that will switch whenever the value exceeds 1.5 .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/636/0*p-h9Rlim5HyBQsLD" /></figure><p>And very similar animatedBack style but with reversed values:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/649/0*99NB8OVb2WPdOboO" /></figure><h3>Animated shadows — <a href="https://github.com/wojtus7/reanimated-story-cards/tree/iteration-5">iteration-5</a></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/412/0*nVV2yTUk3MfHUu6k" /><figcaption><em>Result of iteration-5 code.</em></figcaption></figure><p>Adding shadows will bring some additional depth to our animation. It’s a simple, yet effective trick to add some depth to any 3D animation. I’m totally aware this trick won’t work in all cases, but adding it on a simple 2D plane can be a breeze using the new Reanimated.</p><p>First things first, we need to update our render. To keep the single responsibility rule introduced earlier I decided to create two new Animated.View — one for each side of the card.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hV8jUqEccucHwkVU" /><figcaption><em>New shadow components added to our render method.</em></figcaption></figure><p>The trick here is to use position: absolute combined with relatively high zIndex and size spread over the whole component so the shadow would cover the component but won’t infringe the internal flow while covering it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/349/0*HaT3uh2wQX2J_kc3" /><figcaption><em>Shadow basic styles.</em></figcaption></figure><p>Finally, we can connect it with our openAnimation shared value. If you have a really sharp eye you can spot I used Extrapolate.CLAMP instead Extrapolate.EXTEND in the interpolation function. That’s because I didn’t want the opacity value to wander around out of control. CLAMP will keep the last given value and won’t extrapolate it further. It makes sure that the opacity will never go below 0 or above 1. If that ever happened, it would have a disastrous effect: the react-native component would be confused, and every value not in range between 0 and 1 would return just 1. That means strange visual glitches out of our control.</p><p>NOT EPIC.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/550/0*cRKcqgWmTdqLNkv2" /><figcaption><em>Shadow animated styles.</em></figcaption></figure><h3>We’ve done a lot!</h3><p>We are almost done with work around our card. It looks amazing isn’t it? During our journey we used a lot of different tools around reanimated 2 and I hope you are getting familiar with it!</p><p>Can you see the schema already?</p><p>First, we create shared we can use:</p><pre>const mySharedValue = useSharedValue(0);</pre><p>Then we start creating Animated.View with useAnimatedStyle object inside:</p><pre>&lt;Animated.View style={animatedStyle} /&gt;</pre><p>Created useAnimatedStyle always use some sharedValue to calculate new style:</p><pre>const animatedFront = useAnimatedStyle(() =&gt; {<br>  return {<br>    height: mySharedValue.value,<br>  };<br>});</pre><p>And finally, we use some reanimated mechanism like withTiming or withSpring to animate it:</p><pre>mySharedValue.value = withTiming(100);</pre><p>You are a quick learner! 👏</p><p>Next time we will make the application alive by creating basic game logic to control the whole experience, start menu and loading animation! It’s also gonna be the last part of our journey so stay tuned and see you soon!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=66c127a210e9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swmansion/building-reigns-how-to-strengthen-reign-over-mobile-game-development-using-reanimated-2-66c127a210e9">Building Reigns: How to strengthen reign over mobile game development using Reanimated 2.</a> was originally published in <a href="https://medium.com/swmansion">Software Mansion</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Reigns: How to reign over mobile game development using Reanimated 2.]]></title>
            <link>https://medium.com/swmansion/reanimated-2-the-game-9402622c1fe5?source=rss-40c59ee9b85e------2</link>
            <guid isPermaLink="false">https://medium.com/p/9402622c1fe5</guid>
            <category><![CDATA[reanimated]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[animation]]></category>
            <category><![CDATA[mobile-games]]></category>
            <dc:creator><![CDATA[Wojciech Stanisz]]></dc:creator>
            <pubDate>Tue, 18 May 2021 10:21:19 GMT</pubDate>
            <atom:updated>2021-06-15T13:13:14.619Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QKqG25zeY9_qlzUolU6p4Q.png" /></figure><p>This week we start a three-part series of articles focused on building a clone of <a href="https://apps.apple.com/us/app/reigns/id1114127463">Reigns</a> in React Native using <a href="https://github.com/software-mansion/react-native-reanimated">Reanimated 2</a> and <a href="https://github.com/software-mansion/react-native-gesture-handler">Gesture Handler.</a> The tutorial is backed by a Github repo with the full source code for the project.</p><p>Now, in this part, I lead you through the basics of Reanimated 2 new API and I will show you how it can be used to build nice gesture-based interactions for our game.</p><h3>Why I even started building Reigns?</h3><p>Every time I explore a new library I start by digging into examples to see what’s even possible, if the library is actually working and if I can understand the code right away. Then I explore further — I try to change some code and see if I can work with it.</p><p>I had the same approach to Reanimated 2. Or at least — I wanted to approach it the same way I always do, but at the time (which was 9 months ago) there were nearly no examples. When I started to use the library for the first time it was an early alpha version so there was merely a playground with one slider and some examples in the docs about specific functions.</p><p>Nothing fancy.</p><p>Nothing to really play around with.</p><p>If you learn the same way as I do — exploring and tweaking some existing examples — let me tell you, Reanimated 2 was a real challenge. That’s why I decided to create my own example for everybody to try Reanimated 2 out!</p><p>Disclaimer: in this tutorial, I’m using icons created by<a href="https://www.freepik.com/"> FreePik</a> downloaded from<a href="https://www.flaticon.com/"> FlatIcon</a> library. This is one amazing set of icons I highly encourage you to take a look at.</p><h3>What we’re going to work on?</h3><p>As an example project, I wanted to take something that would combine a lot of different techniques and solutions at once. While looking for inspiration I was going through my Switch games library. And there it was.</p><p><a href="https://store.steampowered.com/app/474750/Reigns/">Reigns</a>.</p><p>Long story short — this is a phenomenal game and you just have to try it out yourself! The overall game rules are:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*-1Qs9swErILYTEj-deEWgw.gif" /><figcaption><em>Example in its final state.</em></figcaption></figure><ul><li>players have to answer continuous questions selecting from two available options;</li><li>each question is presented in a form of an animated card that players can swipe left or right to select an answer;</li><li>each answer has consequences. Some decisions can appeal to one group while being oppressive to others. The player has to rule in a way that no group is privileged or discriminated against in the long term.</li></ul><p>That’s all you have to know to follow this tutorial.</p><p><em>Let’s go!</em></p><h3>Before we start — a few words on technicalities.</h3><p>To take full advantage of this tutorial you need to know the basics of react-native. I assume you have a basic understanding of how react-native works and how to write simple components.</p><h3>First step</h3><p>I created a<a href="https://github.com/wojtus7/reanimated-story-cards"> GitHub repo</a> I highly recommend cloning and building on your own machine. It contains step-by-step changes sorted into separate branches called <em>iterations </em>with the following numbers from 0 to 9. It helped me to focus only on important changes in this text while providing a wider, more interesting example, without forcing you to dig through a big codebase.</p><p>Each chapter of this article is named: <em>name (iteration-X),</em> so you can follow the branches accordingly.</p><p>The following project is based solely on<a href="https://github.com/software-mansion-labs/reanimated-2-playground"> Reanimated 2 Playground</a>. If you have any trouble building it I recommend you check out the<a href="https://github.com/software-mansion-labs/reanimated-2-playground/issues"> issues</a> first.</p><h3>Overview — <a href="https://github.com/wojtus7/reanimated-story-cards/tree/iteration-0">iteration-0</a></h3><p>Before we start to dig deeper into the Reanimated library I wanted to talk a little about the initial state of the project. You can see a lot of files but for now, we are interested only in 3 of them:</p><ul><li><em>useGeneratedCards.js</em></li><li><em>Screen.js</em></li><li><em>Card.js</em></li></ul><p><em>useGeneratedCards</em> is our small database, containing separate cards that will be shown in the game. Example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/696/0*_KK-JyuCnewiO_uO" /><figcaption><em>Example card from useGeneratedCards.js.</em></figcaption></figure><p>question, leftText and rightText are just strings to be shown during each turn. onLeft and onRight are used in answer handlers: they inform us what are the consequences for each answer. Three possible personas to amuse are Woman, Knight, and Joker. Last things are image and background that determine the final looks of the card.</p><p>Next, we have <em>Screen.js</em>. This is the main screen of the application. We will hold all necessary components there. For now, we can see that it returns a simple wrapper with a single Card in it.</p><p>We don’t have any logic yet so for the time being current card is hardcoded.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/564/0*eyrOKHYiFVJW2EKL" /><figcaption><em>The initial state of Screen.js.</em></figcaption></figure><p>The <em>Card.js</em> itself is a tiny component with a small render that contains a static card preview. I kept Styles simple for clarity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/510/0*11CtBgwGXjO0sQN-" /><figcaption><em>Card.js contains only a simple View for the time being.</em></figcaption></figure><p>If you successfully built the project the screen should look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*E2O_hy7oqZNDw3-X" /><figcaption><em>Just a square. ⬜️</em></figcaption></figure><p>Cool!</p><p>We are ready to put some life into that static card of ours!</p><h3>Gesture handler + Reanimated 2 — <a href="https://github.com/wojtus7/reanimated-story-cards/tree/iteration-1">iteration-1</a></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*U38rEtl6vxomqi9w" /><figcaption><em>Result of iteration-1 code.</em></figcaption></figure><p>Gesture Handler and Reanimated libraries are very closely related. More than often we need to animate some movement initiated by a finger gesture.</p><p>That’s also the case here. We want to smoothly follow the finger swiping left and right, while dynamically showing the card content. For cases like this, we can use PanGestureHandler and connect it with a bright new useAnimatedGestureHandler hook introduced in Reanimated 2.</p><p>But before we can focus on the gesture handler itself we need to take care of a few things.</p><p>First, we need to make sure that we can animate our Card. For that, we simply replace View with powerful Animated.View. It works the same as standard View for the most part but now we can use<em> shared values</em> to set the styles 🎉.</p><p>But wait… What are those <em>shared values</em> in the first place?</p><p>Let me explain!</p><p>Reanimated can’t use any JS variables to animate objects. We need to create specific values to be used in animations. Those are called <em>shared values</em> since they are shared between JS thread and UI thread of the react-native application.<a href="https://dev.to/goodpic/understanding-react-native-architecture-22hh"> (More about UI and JS threads here)</a>.</p><p>We want to be able to move our card in any direction so we will need two shared values that will move our component in both the x and y axes. The default values for those variables should be 0 since we don’t want any translation applied from the start.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/322/0*NcldAwgZsUjUFt52" /><figcaption><em>Shared values initialization.</em></figcaption></figure><p>Now we need to edit our render function wrapping brand new Animated.View with PanGestureHandler. This component will track all pan gestures such as swiping.</p><p>The final render looks more or less like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/657/0*UNZGmbGqZDCewpTN" /><figcaption><em>Card with PanGestureHandler and Animated.View.</em></figcaption></figure><p>But wait there’s more!</p><p>We have two new elements introduced here that I haven’t mentioned before: gestureHandler and animatedMovableCard.</p><p>Let’s start with the first one. gestureHandler is constructed with useAnimatedGestureHandler hook imported straight from the Reanimated library. This is a new simple and amazing way to transform your input into shared values. It also can have a separate block of code for every single event like: onStart , onActive and onEnd. <br>EPIC!</p><p>The simplest version of handler for our example would contain only onActive updating x and y based on the position of the finger, and reset the position when the finger is released using onEnd handler.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/496/0*0mOZNkOc9xSrNcUx" /></figure><p>But it’s not enough. We strive for perfection here! Upgrade!</p><p>First things first, we need to create onStart where we use ctx object and keep the initial position of the card there. ctx is an object we can use to store any variables between onStart , onActive and onEnd without the need to create new shared value in the component. In our example, saving initial position for x and y value can be quite useful in preventing some strange visual glitches. For example, when the user catches the card in the middle of the move and the card is off-center (eg. when the card is released without choosing any side and should animate back to the original position) we want to add this initial translation to the event translation itself.</p><p>That’s exactly what we’re going to do in onActive : add initial ctx values to captured event.translation.</p><p>Finally, we want our card to animate smoothly to the starting position. There are a couple of ways to animate some value to a given value. First, I’m going to introduce you to the mechanism that can smoothly animate any variable to a given value using physics: withSpring. Additionally, to make things spicier we can create our own config we want to use in a given spring animation. Pretty!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/532/0*xAaljf59OzscI5cr" /><figcaption><em>The final version of our gesture handler.</em></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/365/0*jNXvq4_QLbgfC53C" /><figcaption><em>Custom spring config used in `withSpring` above.</em></figcaption></figure><p>Now that we have our gesture handler ready, it can start updating the shared values as we pan the finger. However, this won’t result in any movements of the grey box. The only thing left is to map the values to actual Animated.View styles such that to tell how the UI should update when the gesture is happening.</p><p>Now, let’s look at the second element I previously mentioned -animatedMovableCard. We can see that it contains a useAnimatedStyle hook. Inside it, we can create any function that can use shared values and return some style object. In our case, we just use x as translateX and y as translateY . That would be enough to make our card move, but to make it prettier we can add some rotationZ such that it rotates a little as it goes away from the center.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/521/0*bA_3xgfTeBsqP55o" /><figcaption><em>Animated.View’s animated style.</em></figcaption></figure><p>To calculate rotation we can use brand new reimplemented Reanimated 2’s interpolate function. The new one expects 4 arguments: shared value, input table, output value, kind of extrapolation.</p><p>In the above example, we want to make interpolation based on x that will be mapped in that way so x.value = 50 would return 0.05 and x.value = -25 would return -0.025 , and thanks to the use of Extrapolate.Extend all values beyond the given range will be extrapolated correctly in a given manner eg. x.value = 750 will be 0.75.</p><h3>Just a first step</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*9g7MIGJW2WB2HLR2" /><figcaption><em>Part 1 final effect.</em></figcaption></figure><p>Every journey begins with a single step. In our case, it was a rather giant leap.</p><p>During this short time, we covered a lot about Reanimated 2. We got familiar with new shared values, we used new useAnimatedGestureHandler and totally new useAnimatedStyle.</p><p>That’s a pretty solid foundation, but it means nothing without exercise! Go into the example and have fun with it! Change things, tweak, break and fix all you want, and stay tuned for the next part where we’re gonna add more awesome things like flip animation, shadows, loading animation, and much more!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9402622c1fe5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swmansion/reanimated-2-the-game-9402622c1fe5">Building Reigns: How to reign over mobile game development using Reanimated 2.</a> was originally published in <a href="https://medium.com/swmansion">Software Mansion</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>