<?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 Rafal Wilinski on Medium]]></title>
        <description><![CDATA[Stories by Rafal Wilinski on Medium]]></description>
        <link>https://medium.com/@rafalwilinski?source=rss-2b6361cb0d0b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*HZt9BPdBLIiFAPG8bb-EiA.jpeg</url>
            <title>Stories by Rafal Wilinski on Medium</title>
            <link>https://medium.com/@rafalwilinski?source=rss-2b6361cb0d0b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 02:09:04 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rafalwilinski/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[Use AWS Lambda, SNS and Node.js to automatically deploy your static site from Github to S3]]></title>
            <link>https://rafalwilinski.medium.com/use-aws-lambda-sns-and-node-js-to-automatically-deploy-your-static-site-from-github-to-s3-9e0987a073ec?source=rss-2b6361cb0d0b------2</link>
            <guid isPermaLink="false">https://medium.com/p/9e0987a073ec</guid>
            <category><![CDATA[sns]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[github]]></category>
            <dc:creator><![CDATA[Rafal Wilinski]]></dc:creator>
            <pubDate>Sun, 03 Jul 2016 22:32:55 GMT</pubDate>
            <atom:updated>2021-01-10T15:56:12.162Z</atom:updated>
            <content:encoded><![CDATA[<p>Recently, I finished making my own, personal website <a href="http://rwilinski.me/">rwilinski.me</a> which I’m recommending you to check out. During multiple iterations of that project one thing worried me:</p><blockquote>Deployment</blockquote><p>Each time I wanted to show off my progress to someone else I had to go to S3 Console and manually upload all the files, change permissions, set MIME types etc.</p><p>I started to look for automatic solutions like AWS CodeDeploy but I didn’t find anything satisfying. CodeDeploy works fine but only for EC2 instances, it assume that your application couldn’t be built using only S3.</p><p><em>Let me know if there are better, prebuild solutions. Even though there are, I think this tutorial might be a good start to work with Lambda.</em></p><h3>So I came up with my own solution</h3><p>Using AWS Lambda, SNS, Github Webhooks and AWS-SDK I’ve a created quite simple process to automate that. Here’s how I’ve done it in a big picture perspective:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f1fc5JcXHoESq_BMQmewRg.png" /><figcaption>Quick overview of our deployment workflow</figcaption></figure><h3>Creating Github — AWS SNS Topic connection</h3><ol><li>First, Login to your <strong><em>AWS console ► SNS ► Create new SNS Topic</em></strong> called something like “github-deploy”. Copy to clipboard<strong> Topic ANR</strong> key.</li><li>Once you’ve done that, head to your <strong><em>GitHub Repository Settings ► Webhooks &amp; Services ► Add Service (SNS)</em></strong></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V0qIEwAO3pRPM8heI48prg.png" /></figure><p>3. Fill necessary fields. Paste here your Access Keys and Topic ANR.</p><p>Done.</p><p>Now, every time you commit something to master, message will be sent to SNS Topic. We also have to handle that information — download repository files and upload them to S3. I’ve done that using Lambda.</p><h3>Setting up AWS Lambda Function</h3><p>Lambda, like many other services in AWS can have it’s Roles and <em>should</em> so we also have to create one if we would like to work with other services.</p><h4>Creating IAM Role</h4><p>Go to your <strong><em>AWS Console ► Identity and Access Management ► Roles ► Create new Role.</em></strong></p><p>When creating new role mind two things:</p><ol><li>Select proper AWS S3 service role: AWS Lambda</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/858/1*0ZeEbCn7FBgsQU68O9K_Lw.png" /></figure><p>2. Attach following policies to that role:</p><ul><li>AmazonS3FullAccess — we are going to save our files to S3 obviously</li><li>AmazonSNSReadOnlyAccess — we need to listen for incoming events</li></ul><p>After creating it, copy <strong>Role ARN</strong>, you’ll need that for local project setup.</p><h3>Creating Lambda function itself</h3><p>When it comes to creating Lambdas, you can try creating Lambda function in browser but I think it’s kind of painful process. You don’t get all the linting, editor is limited, also you cannot add more <em>node_modules</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZnGVTYv-dysgAAXJ3F7jnw.png" /><figcaption>Lambda Creation Panel in Browser</figcaption></figure><p>Instead, I recommend creating a new node project somewhere on your computer and installing <a href="https://github.com/motdotla/node-lambda">node-lambda</a>. This awesome module has an ability to setup, dry-run, package and deploy your lambdas to AWS without much effort.</p><h4>Creating lambda locally</h4><ol><li>Fire following set of commands:</li></ol><pre>cd ~ &amp;&amp; mkdir github-to-s3-deploy &amp;&amp; cd github-to-s3-deploy<br>npm init -f<br>touch index.js<br>npm install node-lambda aws-sdk --save-dev<br>npm install request --save</pre><p>For those who are not familliar with command line, it creates new Node.js project named “github-to-s3-deploy”, creates new file index.js and installs all modules that we’ll need.</p><p>2. Open <strong>package.json</strong> and change scripts section to this:</p><pre>“scripts”: {<br>    “start”: “node index.js”,<br>    “dry-run”: “node-lambda run”,<br>    “deploy”: “node-lambda deploy --configFile deploy.env”,<br>    “setup”: “node-lambda setup”,<br>    “package”: “node-lambda package”<br> },</pre><p>This adds a set of useful commands and doesn’t require us to install “node-lambda” globally.</p><p>Let’s finish setting up our project by executing this line:</p><pre>npm run setup</pre><p>This will add some configuration files to our directory. Your project should now look something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/710/1*TZA4SwO5fF-Tvm9LYEvaeA.png" /></figure><p>Open <strong>.env </strong>file and paste your Access Keys (Session_token is not needed), Role ARN (which you’ve copied before) and fill rest of the parameters as you like. I recommend following settings:</p><pre>AWS_ENVIRONMENT=development<br>AWS_ACCESS_KEY_ID=&lt;your access_key here&gt;<br>AWS_SECRET_ACCESS_KEY=&lt;your secret_here&gt;<br>AWS_SESSION_TOKEN=<br>AWS_ROLE_ARN=&lt;your role anr here&gt;<br>AWS_REGION=us-east-1<br>AWS_FUNCTION_NAME=github-to-s3-deploy-function<br>AWS_HANDLER=index.handler<br>AWS_MEMORY_SIZE=128<br>AWS_TIMEOUT=10<br>AWS_DESCRIPTION=Uploades new version of code each time new commit appears in repo<br>AWS_RUNTIME=nodejs4.3<br>AWS_VPC_SUBNETS=<br>AWS_VPC_SECURITY_GROUPS=<br>EXCLUDE_GLOBS=”event.json”<br>PACKAGE_DIRECTORY=build</pre><h3>Enough of setup. Let’s code</h3><p>Open index.js and paste following code:</p><pre>exports.handler = (event, context, callback) =&gt; { <br>    console.log (event); <br>};</pre><p>It will be base for our further experiments. Run</p><pre>npm run deploy</pre><p>and wait until process completes. After it’s done, head to <strong><em>AWS Console </em></strong>► <strong><em>Lambda </em></strong>►<strong><em> [your function name] </em></strong>►<strong><em> Event Sources</em></strong> and link it to previously created SNS Topic, so Lambda will subscribe to SNS Topic which receives data from Github. It should look something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gk1H37F4QF6h9h4EwSOPeg.png" /><figcaption>Event source setup</figcaption></figure><p>Now, let’s test whole setup. Go back again to Github Webhooks, Choose already integrated SNS Topic and hit “Test Service”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tPe0eRUhdqhh9hrLyJFKtg.png" /></figure><p>After few seconds, Lambda should trigger, and you should be able to see the result using <strong>CloudWatch Management Console.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xl5YIqbWKtFWOcVreiGhpg.png" /><figcaption>CloudWatch Management Console</figcaption></figure><p>In CloudWatch, select <strong>/aws/lambda/[your function name]</strong> and then latest logs revision, you should see something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zbKstK0VXibNTqmCxyZxqg.png" /><figcaption>Detailed logs</figcaption></figure><p>If you don’t see any logs or there are no logs revisions, try waiting a few seconds. If it doesn’t help, make sure you completed all previous steps.</p><h3>Setting up local test environment</h3><p>From this point, you can focus only on code but testing your function will be a very slow process. Each time you iterate, you’ll have to deploy your function, wait a moment to populate it, re-run “Test Service”, check logs etc.</p><p>Fortunately, there’s a much better way to test your lambdas without deploying it to AWS. According to <em>node-lambda</em> documentation:</p><blockquote>Setup — Initializes the event.json, context.json, .env files, and deploy.env files. <strong>event.json is where you mock your event.</strong></blockquote><p>So, we can paste example payload to <em>event.json</em> file and imitate real integration, cool.</p><p>Let’s open it and paste your message from CloudWatch logs or this one, from my message: <a href="https://gist.github.com/RafalWilinski/69f14bdbfba97f8de5d4552879cd9d1a">https://gist.github.com/RafalWilinski/69f14bdbfba97f8de5d4552879cd9d1a</a></p><p>Next, test that by using following command:</p><pre>npm run dry-run</pre><p>You should see something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1008/1*eJsBjVu3UdzfCjYu4dBN9w.png" /><figcaption>npm run dry-run</figcaption></figure><h3>Making it actually work</h3><p>Right now our function does nothing but logs incoming event. Pretty boring so let’s extend that into something like this:</p><pre>‘use strict’;<br>const request = require(‘request’);<br>const AWS = require(‘aws-sdk’);<br>const fs = require(‘fs’);</pre><pre>const path = &#39;static/&#39;;</pre><pre>exports.handler = (event, context, callback) =&gt; {<br>  const downloadsUrl = JSON.parse(event.Records[0].Sns.Message).repository.contents_url.replace(‘{+path}’, path);</pre><pre>  request({<br>    uri: downloadsUrl,<br>    headers: {<br>      ‘User-Agent’: ‘AWS Lambda Function’ // Without that Github will reject all requests<br>    }<br>  }, (error, response, body) =&gt; {<br>    JSON.parse(body).forEach((fileObject) =&gt; {<br>      console.log(fileObject);<br>    });<br>  });<br>};</pre><p>Our function will now extract URL from Github payload to download all files from repository and then iterate over all downloadable files.</p><p>Logging all downloadable files is kind of pointless so let’s replace:</p><pre>console.log(fileObject); </pre><p>with:</p><pre>putFileToS3(fileObject)<br>  .then(() =&gt; updateProgress(payload.data.length))<br>  .catch((error) =&gt; callback(error, `Error while uploading ${fileObject.name} file to S3`));</pre><p>As you can see, I’ve introduced two functions here.</p><ul><li><strong><em>putFileToS3</em></strong> which is quite self-explanatory. It will download file from Github and pipe it to S3</li><li>If <strong><em>putFileToS3 </em></strong>succeeds, it will fire <strong><em>updateProgress</em></strong> function. This piece of code will count uploads which succeeded. If number of <strong>uploaded</strong> images will be equal to number of <strong>files in repository</strong>, then it will fire callback that reports Lambda completion.</li></ul><p><strong><em>putFileToS3</em></strong> should look something like this:</p><pre>const putFileToS3 = (fileObject) =&gt; new Promise((resolve, reject) =&gt; {<br>  request(fileObject.download_url)<br>  .pipe(fs.createWriteStream(fileObject.name))<br>  .on(‘finish’, () =&gt; {<br>    s3.upload({<br>      Bucket: bucketName,<br>      Key: fileObject.name,<br>      Body: fs.createReadStream(fileObject.name),<br>      ACL: ‘public-read’,<br>      ContentType: computeContentType(fileObject.name),<br>    }, (error, data) =&gt; {<br>      if (error) throw new Error(error);<br>      else console.log(data);<br>    });<br> });<br>});</pre><p>This function takes as an argument every file in repository, downloads to local directory and then re-uploads to S3. It’s important to make files public by setting ACL to “public-read”. Since everything in Lambda local filesystem is temporary, we don’t have to worry about removing <em>tmp</em> files.</p><p>One thing that’s also worth noticing is `ContentType`. Since we want <em>html</em> files to be <em>rendered</em>, and <em>JS</em> files to be <em>interpreted</em> while image files just <em>displayed, </em>we have to instruct S3 and browser what should it do with all of these files.</p><p>To do that, I’ve created simple switch which will guess ContentType basing on file type, it goes like this:</p><pre>const computeContentType = (filename) =&gt; {<br>  const parts = filename.split(‘.’);<br>  switch (filename.split(‘.’)[parts.length-1]) {<br>    case ‘png’:<br>      return “image/png”;<br>    case ‘html’:<br>      return “text/html”;<br>    case ‘js’:<br>      return “application/javascript”;<br>    case ‘css’:<br>      return “text/css”;<br>  }<br>};</pre><p>Feel free to extend this if you need more file types or use different extensions.</p><p>After all, let’s get to our helper function which is responsible for reporting task completion — <strong><em>updateProgress</em></strong></p><pre>let processed = 0;</pre><pre>const updateProgress = (totalCount) =&gt; {<br>  processed++;<br>  console.log(`Progress: ${processed} out of ${totalCount}`);<br>   if (processed === totalCount) {<br>     if (confirmationTopicArn) confirmUpload(callback);<br>     else callback(null, ‘Done!’);<br>   }<br>}</pre><p>Very simple function which counts all the succeeded uploads. If that number equals to number of files to upload, we can notify ourselves by mail (if <em>confirmationTopicArn</em> is supplied) nor just end function by invoking <em>callback</em>.</p><h3>Bonus: Sending mail to us about completion</h3><p>If you’re one of those like me who are total control freaks, you should probably consider implementing very basic reporting.</p><p>First, let’s create another SNS Topic dedicated for sending notifications and subscribe your dev mail to that topic:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ELUXNGRLY8CtRt-l0j5tOw.png" /><figcaption>Create Mail subscription, don’t forget to confirm it</figcaption></figure><p>Once again, copy your Topic ANR and save it into <strong><em>.env </em></strong>file under some meaningful key, like <strong>AWS_CONFIRMATION_SNS_TOPIC_ANR. </strong>Save it also in deploy.env file, without that env variable will be not present in live lambda environment.</p><p>When it comes to code, this simple function should do the trick:</p><pre>const confirmUpload = (callback) =&gt; {<br>  sns.publish({<br>    Message: &#39;Deploy successful!&#39;,<br>    Subject: &#39;Github to S3 Deployment&#39;,<br>    TopicArn: process.env.AWS_CONFIRMATION_SNS_TOPIC_ANR,<br>  }, (err, data) =&gt; {<br>    if (err) callback(err, ‘Failed to send confirmation’);<br>    else callback(null, ‘Done!’);<br>  });<br>};</pre><p>And that’s it. If you’ve followed instructions carefully, you should be able to clone whole process and also automate your deployment.</p><p>If you liked it and would like to learn something more, try making it a bit more complicated by including CI somewhere in the middle or even add code linting/formatting as a step before deployment.</p><p>In case you’ve missed something, complete source code is available here: <a href="https://github.com/RafalWilinski/github-to-s3-lambda-deployer">https://github.com/RafalWilinski/github-to-s3-lambda-deployer</a></p><p>If you liked this article, the chances are you’re also exposed to DynamoDB. If you’re not big fan of AWS Console, check out my other project which aims to solve this problem: <a href="https://dynobase.dev/">https://dynobase.dev</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9e0987a073ec" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[2,000,000 Downloads Later — What I’ve learnt from Voxel Rush]]></title>
            <link>https://rafalwilinski.medium.com/2-000-000-downloads-later-what-i-ve-learnt-from-voxel-rush-208fc7c29459?source=rss-2b6361cb0d0b------2</link>
            <guid isPermaLink="false">https://medium.com/p/208fc7c29459</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[apps]]></category>
            <category><![CDATA[game-development]]></category>
            <dc:creator><![CDATA[Rafal Wilinski]]></dc:creator>
            <pubDate>Thu, 08 Oct 2015 18:31:39 GMT</pubDate>
            <atom:updated>2021-05-05T18:18:56.237Z</atom:updated>
            <content:encoded><![CDATA[<p>It’s been a while since I’ve posted something on the internet, and it’s also the first time I’ve ever posted something on Medium. Up to this point I’ve only talked about tech and programming, but today I’ll try to take on something very different, something that most Indies hate.</p><h3><em>Marketing.</em></h3><p><em>And some other minor things besides programming.</em></p><p>After millions of downloads of my games I think I know <strong>a bit</strong> about this topic so I decided to create a list of myths, thoughts and my experiences. Some of these may be very controversial but remember, it’s only my point of view. Feel free to argue with me in the comments section.</p><p>Let’s begin with…</p><h3>“Neither your first game or second game or even twentieth will ever succeed.”</h3><h2>Bullshit.</h2><p>This is something that I see all the time on fanpages like Indie Game Developers. I was 17 years old when I released Voxel Rush, it was my first game and my wish was to gather 1,000 downloads over time. I made <strong>many</strong> mistakes however it went pretty well. And I’ll tell you why - I was fine-tuning my game over and over and it <strong>was</strong> <strong>released three times.</strong></p><p><strong>First Attempt</strong> — publishing on my own, the game controls were broken, it had still “UI”, and was too difficult. I gathered over a thousand downloads in week with an average rating of <strong>2.88 </strong>with<strong> </strong>zero press coverage, and a bad description and listing. My dream came true but not exactly the way I wanted. <em>It was complete disaster. </em>After that “accident” I deleted the whole source code and started working on the same concept. Before releasing the game, I also decided to go to Vivid Games where I hoped to find a publisher. I had a great talk with their co-CEO however obviously<em> </em>they had to refuse my offer because the game was just terrible. After that, in my mind there was only one thought:</p><blockquote>“Just you wait.”</blockquote><p>Here’s how it looks today from a developer console perspective:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ACOAy-Kc5SUbCsl1xfnglA.png" /><figcaption>Today stats, 33 alive copies!</figcaption></figure><p><strong>Second Attempt</strong> — <strong>5</strong> <strong>Months later</strong>, with much more experience and knowledge of programming, along with feedback from players and friends, I finished and polished my concept. Once again, I released on my own, everything was greatly improved, and the game was a bit easier to play. I only posted about it on some forums like AndroidCentral or XdaDevelopers. After 2 or 3 days, when I saw the game was going in the right direction (positive feedback, 5/5 reviews), I thought that it would be cool to advertise it somewhere else, so I started spamming other forums. Looking back from a future perspective, the thing I did was in a sense a really short “soft launch”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*92emReRo06ZSJhnvvfif1A.png" /><figcaption>Todays stats, people are still playing this?</figcaption></figure><p><strong>Third Attempt — another 5 months later</strong>, after over 200k downloads I was really proud of myself, a known to nobody, 17-year-old Indie Game Developer. One day, I got kind of headhunted by a London-based mobile games publisher, Hyperbees. Thankfully they could speak Polish so we could communicate fluently. The agreement was complicated enough and not in my first language so for about a month, we were discussing only my concerns.</p><p>After countless Skype talks and mails, I decided to have a go with them <strong>and I don’t regret that.</strong> A publisher really helps you with advertising, promos, creating websites, press kits etc.</p><p>Remember that even if your game doesn’t succeed, there is a huge variety of perks besides money and downloads. I’m talking about industry parties, exclusive advertising deals, campaigns tailored perfectly for your game, much more exposure and in my case an unforgettable experience and individual English lessons(thanks <a href="https://uk.linkedin.com/in/monikakokoszycka">Mon</a>!).</p><h3>Focus on the first 30 days</h3><p>This very important. In your first 30 days your game can be discovered under the “New Releases” section. Gaining a position in this particular chart is much easier simply because there are much fewer games. If you use that wisely, you should be able to create a “snowball” lasting longer than 30 days.</p><h4><strong>But it cuts both ways.</strong></h4><p>During our third attempt to release the game we decided to start from the very beginning instead of transferring the app to another developer account, and this was one of our worst decisions. We hoped for so much in these 30 days that we unpublished the app that was downloaded over 2,000 times every day; we wrongly thought that these 30 days would give us more exposure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/796/1*4e8pnYX1ZtQOESao2A8zdA.png" /><figcaption>We unpublished game that was being downloaded 2,000 times a day…</figcaption></figure><p>An irreparable loss. It took us over 6 months to get back to that level on the new listing.</p><p>Also, if your game does not gain 10,000 downloads in this period of time, then it will be much harder later and maybe it’s just not good and you should find the causes of that.</p><h3>“Releasing a game on your own is disaster and you’ll get barely any downloads”</h3><h4>More bullshit</h4><p>My case shows the exact opposite in terms of downloads. Let’s compare my second and third release in terms of downloads:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pKyYhGW5WOF9EkGhnOhjxA.png" /><figcaption>150 days after second and third release</figcaption></figure><p>This chart concludes “Total Installs by Device” in the first 150 days after release. As you can see, at some points I significantly surpassed my publisher but at the end of the day it seems that it was worth to co-operating with them. But wait, there’s more! Take look at this one, a slightly over-exaggerated chart:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H9W1S0lcJBX4jg9AauDlCw.png" /><figcaption>Money earned on my own vs with publisher</figcaption></figure><p>Before I started working with Hyperbees it was like charity. The game had no ads, no in-app purchases and ZERO 3rd-party SDKs. Well, I was quite young and stupid. What’s great about having a publisher is that they also take care of tax and all that bureaucracy while you can focus on the product.</p><h3>Press Coverage is very helpful</h3><h4>In my case it wasn’t.</h4><p>Thanks to <a href="https://twitter.com/tommleko">Tom Mleko</a> &amp; <a href="https://twitter.com/hyperbees">Hyperbees</a>, our game won the Big Indie Pitch at Apps World which was awesome; we won VIP tickets for the PocketGamer event in London, some people heard about VR and we had the opportunity to talk with some influential people. But guess what the results in terms of sales/downloads was? Zero.</p><p>Another case, we were organising a “Platform Wars” event with Nvidia which was a huge success, however a few days before we had a really long press coverage in the Chicago Tribune, one of the Top 10 newspapers in the US. Any additional downloads? Only within the limits of a statistical error.</p><p>My game was also featured on numerous Polish tech websites and the conversion rate was miserable.</p><h3>Be aware of AppOfTheDay and similar programs</h3><p>It’s huge boost, however with great power comes great responsibility. Due to AppTurbo and AppOfTheDay we managed to get over 100,000 downloads in only one day. Here’s the result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ImWt6BQPMcYmiTaiy-WbtA.png" /><figcaption>Source: AppAnnie</figcaption></figure><p>And downloads spike:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/994/1*C-2RF5ctdcAmE-n9qaOj8Q.png" /><figcaption>Source: Our Developer Console</figcaption></figure><p>These are pros, but there are also undeniable cons. Here’s how our rating went down:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/978/1*N9u9Hg6DMcWM-HZryeRYTw.png" /></figure><p>We went from 4.83, which at the time was one of the highest ratings on the market, down to 4.07. Even after 18 months we couldn’t recover from that and now we’re stuck at a 4.25 rating. There are two reasons for that negative effect:</p><ol><li>You’re getting random traffic that isn’t not interested in your game. People are downloading your game only because it’s “App of the day” and eventually they’ll become disinterested. Your game has to be VERY engaging from the first moment if you want them to stay.</li><li>A version with a critical bug was in production. Over 60,000 downloads were affected by this bug, where during the first play you were immortal and hitting an obstacle resulted in nothing. This was the main cause of these 1-star ratings.</li></ol><h4>Here’s the conclusion from this</h4><h3>Just do QA one more time</h3><p>It’s both mine and my publishers fault that we pushed this version to production but I totally understand why that happened. We’re all sick of working in such a rush at crunch time so here’s the lesson from this:</p><h4>Don’t rush.</h4><p>Game development is supposed to be also a pleasure for us, <a href="https://medium.com/@morganjaffit/indipocalypse-or-the-birth-of-triple-i-eba64292cd7a">“Triple-I”</a> developers. It’s not a shame to delay your game just to make it better and polish a little bit. Even triple-A studios do that, look at Witcher 3 for example. CD Projekt decided to release the title later, but thanks to that, they managed to deliver such a perfect piece that for me it’s one of the best games I have ever played.</p><p>Also, try to stress test your backend server before such events. Our servers had really big problems trying to handle 1,000 concurrent players; we had to disable some endpoints and never got all the data, which caused massive “memory leaks” in the database.</p><h3>Networking on real events is very important</h3><p>As I mentioned before, we won VIP tickets for the PocketGamer Connects event. We had a great time there, ate delicious food, tasted delicious wine and met awesome people. One of these guys was from Google Play. We had the chance to pitch our game to him and despite the fact that during the presentation our baby crashed(!) and he wasn’t impressed, after a few months thanks to that meeting, our game was featured on Google Play worldwide. However, maybe that’s because we prepared a special, more intense version filled with events, tricky obstacles and configured it to be much faster.</p><h3>The Power of Google Feature</h3><p>So for a week, VR was featured on Google Play under Best Games and New &amp; Updated in some countries. Being featured is probably the best thing that can happen to your game; you get an enormous downloads boost and from our experience, in contrast to App of the Day programs you get really engaged players that are more likely to stay in your game and give you their money. Furthermore, this “downloads spike” will be spread out over time, so there’s less chance that your servers will be DDoSed by a huge amount of players, and you also have more time to react. It’s also worth noting that being featured by Google is simply more effective.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AkNrbqin5KZCmz8ZKtMfhA.png" /><figcaption>Left: Google Play Feature, Right: App of the Day</figcaption></figure><p><strong><em>Ok, but how do I get featured?</em></strong></p><h4>Here’s how you can increase your chance of being featured</h4><ul><li>“Just” make a great game, lol</li><li>Integrate Google Play Services and its latest features like Real-time Multiplayer, Quests, Gifts, etc., and very prominently show them in game</li><li>Try to win or just enter some contests like Big Indie Pitch or &lt;put random string here&gt; Game Awards, and you might get noticed by them</li><li>Network at the events, nowadays connections are as important as money or a great product</li><li>Make something unique. Your selling point was an event called Platform Wars where Android players were fighting against iOS players in a worldwide war.</li></ul><h3>Keep in touch with players</h3><p>his may be obvious, but here’s the thing. Nowadays almost every game has its fan page on Facebook, Twitter account etc. The problem is that as a gamer, if I would like to give you feedback I have to stop playing, go to the home screen, launch the Facebook/Twitter App, search for the developer/game page and then post something. Steeplechase.</p><p>The player needs an immediate method of providing feedback. In Voxel Rush, we decided to add a “Help me!” button at the bottom-right corner of the main menu which opened a mail composed with a basic information already filled in. Through that button we received a tremendous rate of mails with valuable feedback, complaints, bugs etc. etc.</p><p>If you don’t like that, try adding social icons redirecting to your page, but please, for heaven’s sake don’t use <a href="http://facebook.com/%3Cprofile_page_here%3E"><em>http://facebook.com/&lt;profile_page_here&gt;</em></a><em> </em>as the redirect URI. It results in opening the default browser, not an actual app, which is horrible. Make an effort and use <em>facebook:// or twitter://</em> protocols (and check if these apps are installed on the user’s device first).</p><h3>Try to minimize the number of SDKs</h3><p>From our experience SDKs are the main cause of game crashes. They also increase game size and managing them is sometimes a real hassle, especially on Android where you have to care about AndroidManifest and duplicate classes/methods. Third-party SDKs were also the main cause of production delays, forced updates and my frustration. My advice is to stick to as few as you can. Your game should be totally fine with Game Center/Play Services, AdMob, UnityAds and some analytics.</p><p>If you liked this article, check out my other project — <a href="https://dynobase.dev/">Dynobase, Modern DynamoDB Client</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=208fc7c29459" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tutorial — Create C/C++ plugins for Unity3D]]></title>
            <link>https://rafalwilinski.medium.com/tutorial-create-c-c-plugins-for-unity3d-dbde7f67454?source=rss-2b6361cb0d0b------2</link>
            <guid isPermaLink="false">https://medium.com/p/dbde7f67454</guid>
            <category><![CDATA[c]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[unity]]></category>
            <dc:creator><![CDATA[Rafal Wilinski]]></dc:creator>
            <pubDate>Wed, 01 Jul 2015 16:49:36 GMT</pubDate>
            <atom:updated>2016-03-03T21:45:31.419Z</atom:updated>
            <content:encoded><![CDATA[<p>Today I decided to share with you something that I think is not a “common knowledge” and there aren’t many resources on that topic on the internet. In this tutorial I’ll show you how to create plain C/C++ libraries for Unity3.</p><p><strong>Please note that this method will only work on Mac, on Windows you’ll need to use Visual Studio. Windows version is coming soon!</strong></p><p>You may ask, why should I bother writing C or C++ code when Unity supports C#?</p><p>Answer is simple. It’s just <strong>much faster</strong>. Really. I decided to prepare some benchmarks just to show you how C++ outperforms C# based on Mono framework.</p><h3>Benchmarks</h3><p>Reference machine: Macbook Pro 15″ Mid 2014, Intel I7 2.2Ghz</p><ul><li>Fill 10000 x 10000 Integer array with series:<br> <strong>[Unity C#] <em>1.0258</em> seconds vs <em>0.2346</em> seconds [C Library]</strong></li><li>Fill 500 x 500 Integer array with series:<br> <strong>[Unity C#] 3.794<em> milliseconds</em> vs <em>0.35 milliseconds</em> [C Library]</strong></li><li>Fill 10000 x 10000 Integer array with Random numbers:<br> <strong>[Unity C#] <em>4.26</em> seconds vs <em>0.995</em> seconds [C Library]</strong></li><li>Fill 10000 x 10000 Integer array with Perlin Noise:<br> <strong>[Unity C#] 6<em>.015</em> seconds vs <em>2.394</em> seconds [C Library]</strong></li><li>Fill 500 x 500 Integer array with Perlin Noise:<br> <strong>[Unity C#] 20,47<em> milliseconds</em> vs 5.697 <em>milliseconds</em> [C Library]</strong></li></ul><p>As you can see, C library can easily outperform Mono in some tasks. I think this technique is especially useful in procedural generation which I’ve fallen in love with some time ago. I know that these operations may be even 100x faster when calculated on GPU but for know I’ll focus just on pushing logic on C++ + CPU layer. Let’s start creating our libraries!</p><h3>Part 1. Creating C++ Library</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*WKz4jt6QDeSFeyXR.png" /><figcaption>How to create Unity3D C/C++ Plugin</figcaption></figure><p>Open Xcode, click File -&gt; New -&gt; Project. From list of project types select OS X -&gt; Framework &amp; Library -&gt; Bundle.</p><p>Now, we have to create source file with header file in C++ language. To do that, simply click folder containing your project and select “New File…”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/225/0*-uJXm75yIHbAo0EN.png" /><figcaption>Select “New File…”</figcaption></figure><p>Following window should appear. Select C++ file, name it LowLevelPlugin and select “Also create header file”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/0*oklN4FkWCtCOlIqn.png" /></figure><p>After doing that, you should see following project structure/hierarchy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/0*JjcZWXv6v8iRErEc.png" /></figure><p>If after expanding folders you don’t have following structure it means that probably you’ve done something wrong and I recommend to start over again.</p><p>Cool, once you have everything setup, go ahead and open LowLevelPlugin.h file. You should see code like this:</p><pre>#ifndef __LowLevelPlugin__LowLevelPlugin__ <br>#define __LowLevelPlugin__LowLevelPlugin__ <br>#include &lt;stdio.h&gt; <br>#endif /* defined(__LowLevelPlugin__LowLevelPlugin__) */</pre><p>If you don’t understand this code don’t worry. We are going to remove it 😛 Instead, we are going to paste this:</p><pre>#pragma once </pre><pre>#if UNITY_METRO <br>#define EXPORT_API __declspec(dllexport) __stdcall <br>#elif UNITY_WIN <br>#define EXPORT_API __declspec(dllexport) <br>#else <br>#define EXPORT_API <br>#endif</pre><p>This may seem even more complicated than previous one but don’t worry. I’ll explain.</p><p>Purpose of this whole header is to behave differently basing on which platform are you currently compiling your code. It means, that you can easily compile it in Visual Studio on Windows.</p><pre>#pragma once</pre><p>– This is C/C++ specific directive designed to cause the current source file to be included only <strong>once</strong> in a single compilation.</p><p>Next is:</p><pre>#if UNITY_METRO</pre><p>– this tells compiler to something inside this if block only if we are running on Metro based Windows e.g. 8.1. Inside this if block we have</p><pre>#define EXPORT_API __declspec(dllexport) __stdcall</pre><p>– keyword “define” works something like replace function, it’s syntax may be defined something like this #define &lt;String_to_replace&gt; &lt;with_this_text&gt;. In our case, everytime compiler sees EXPORT_API character sequence in code, it replaces it with the second part. Likewise compiler will behave in case when you compile your code on older windows, it will replace EXPORT_API with __declspec(dllexport) and will just remove EXPORT_API in any other case.</p><p>That’s it when it comes to header. Now let’s move on to something that it more interesting, actual source code. Open C source file and paste following code:</p><pre>#include &lt;stdlib.h&gt; <br>#include &lt;math.h&gt; <br>#include &quot;LowLevelPlugin.h&quot; </pre><pre>extern &quot;C&quot; int ** EXPORT_API fillArray(int size) { <br>    int i = 0, j = 0; <br>    int ** array = (int**) calloc(size, sizeof(int*)); </pre><pre>    for(i = 0; i &lt; size; i++) { <br>        array[i] = (int*) calloc(size, sizeof(int)); <br>        for(j = 0; j &lt; size; j++) { <br>            array[i][j] = i * size + j; <br>        } <br>    } <br>    return array; <br>}</pre><p>Some more advanced users will notice that I wrote this code more like in C than C++, that’s because I’m more familiar with plain C rather than C++. If you don’t understand what’s going on here’s short clarification:</p><p>First three lines are IMHO self explanatory. We are simply adding few standard libraries and our just created header file.</p><p>Next up is</p><pre>extern &quot;C&quot; int ** EXPORT_API fillArray(int size) {</pre><p>This is our function declaration. Our function is called “fillArray”, takes one int argument and returns two dimensional integer array. (Yes, ** means two dimensions) Word “extern” extends the visibility to the whole program, the functions can be used anywhere in any of the files of the whole program and outside our library/plugin. We have also our EXPORT_API keyword, I described how it works a bit earlier.</p><p>Next interesting thing is:</p><pre>int ** array = (int**) calloc(size, sizeof(int*));</pre><p>Here I’m defining two-dimensional int array and then I’m allocating memory for it. Since I’m writing code in C, I can’t just create array and assign values. I have to reserve some space in memory for it and then do any operations. In this particular case, I’m allocating next N memory “cells” of size of int* and cast it to two dimensional int array type.</p><p>Same thing I’m doing here:</p><pre>array[i] = (int*) calloc(size, sizeof(int));</pre><p>The only difference is that now I’m allocating memory for every “i’th” row of an array.</p><p>And in the end I’m returning an filled array. I hope that for loops and assigning values is obvious for you so I’ll not explain that in this tutorial.</p><p>Ok, C++ programming is done. How we have to generate library and copy it to the Unity. Simply press this big “Play” like looking button and in couple of seconds you should see bundle file generated right here:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/0*IBOZODygK_7RmeGI.png" /></figure><h3>Part 2. Using library in Unity3d</h3><p>Right click on that file and select “Show in Finder”. Now copy that file and create new Unity3D Project. Inside /Assets/ folder create folder called Plugins and paste here bundle file. You should also create C# script in base directory so your project structure should like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/0*57emjl8Kc74gE_Jk.png" /></figure><p>Now it’s time to hook our library in Unity. To do that we have to do following things.</p><ol><li>At the top of your C# script add</li></ol><p>“using System.Runtime.InteropServices;”</p><ol><li>Add external function declaration. In our case its</li></ol><pre>[DllImport (&quot;LowLevelPlugin&quot;)]<br>private static extern int [,] fillArray(int size);</pre><p>(if you named your library differently, use your custom name)</p><p>3. Create two-dimensional array variable.</p><pre>int [,] array;</pre><p>4. Call function from library and assign result to array variable</p><pre>array = fillArray(size);</pre><p>If you followed instructions carefully, your Unity project now should be able to use C++ library. Congratulations!</p><h3>Part 3. Run benchmarks on your own! (optional)</h3><p>For quick comparsion you can use this code:</p><pre>using UnityEngine; <br>using System.Collections; <br>using System.Runtime.InteropServices; </pre><pre>public class PerformanceTests : MonoBehaviour { <br>    public int size = 512; </pre><pre>    [DllImport (&quot;LowLevelPlugin&quot;)] <br>    private static extern int[,] fillArray(int size); </pre><pre>    void Start () { <br>        ArrayFillTest(); <br>    } </pre><pre>    private void ArrayFillTest() { <br>        var start = Time.realtimeSinceStartup; <br>        int[,] tab = fillArray(size); </pre><pre>        Debug.Log( (Time.realtimeSinceStartup-start).ToString(&quot;f6&quot;) + &quot; secs&quot;); </pre><pre>        start = Time.realtimeSinceStartup; <br>        int[,] array = new int[size,size]; </pre><pre>        for(int i = 0; i &lt; size; i++) { <br>            for(int j = 0; j &lt; size; j++) { <br>                array[i,j] = i * size + j; <br>            } <br>        } <br>        Debug.Log( (Time.realtimeSinceStartup-start).ToString(&quot;f6&quot;) + &quot; secs&quot;); </pre><pre>     } <br>}</pre><p>In my case C is much faster. Results are even more clear in some more complex operations like generating noise. I really recommend this technique for large-scale math operations, It may save you some milliseconds each frame if your game relies heavily on calculations.</p><p>I hope you liked it, feel free to ask questions, any feedback is appreciated.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dbde7f67454" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[Tutorial] Particle Sea in Unity3D]]></title>
            <link>https://rafalwilinski.medium.com/tutorial-particle-sea-in-unity3d-70ff1350fa9e?source=rss-2b6361cb0d0b------2</link>
            <guid isPermaLink="false">https://medium.com/p/70ff1350fa9e</guid>
            <category><![CDATA[design]]></category>
            <category><![CDATA[unity3d]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Rafal Wilinski]]></dc:creator>
            <pubDate>Sun, 26 Apr 2015 21:59:30 GMT</pubDate>
            <atom:updated>2016-03-03T21:30:58.870Z</atom:updated>
            <cc:license>http://creativecommons.org/licenses/by/4.0/</cc:license>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EXmQek6GW84d0VwpmP7Ong.png" /></figure><p>When I saw it, I was totally shocked. Firstly — it looked amazing, Secondly — it was playing smoothly in my browser on a non-high-end PC. <strong>That was my reaction to this: </strong><a href="http://i-remember.fr/en"><strong>http://i-remember.fr/en</strong></a><strong>.</strong> I immediately fell in love with that and the three.js library. I knew I had to recreate the same effect in Unity3d.</p><h3>Hi,</h3><p>Today I decided to share with you my spare time project — Particle Sea and also show you step by step how I managed to create such an effect.</p><p><a href="https://dl.dropboxusercontent.com/u/69335113/ParticleSea/ParticleSea_WEBGL_1.1/index.html"><strong>This is how it looks in action!</strong></a><strong> </strong><em>Feel free to play around with parameters, share your results!</em></p><h3>In short, what we need to do:</h3><ol><li>Create Particle System and array of particles</li><li>Assign particles positions &amp; create Perlin Noise</li><li>Make everything move nice and smoothly — put in loop</li><li>Color!</li></ol><h3>Let’s Start!</h3><p>I assume that you have already created a new, empty project and scene. If not, do so right now, I’ll wait for you. As soon as you’ve done that, create a new empty game object and place it at the origin. This will be the base of our “sea”. Then create a new C# script named<em> ParticleSea</em> and add it to the object. We’ll also a need ParticleSystem component so go ahead and add one.</p><p>If you don’t know how to do that: Go To Components-&gt;Effects-&gt;Particle System</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_KfUZtrgILroJt7a.png" /><figcaption>That’s how it should look like</figcaption></figure><h4><em>Project Setup</em></h4><p>As I said before, at first we need to create a particle system (we’ve done that already) and create an array of particles. Simply open the ParticleSea class you’ve just created and paste following code. Don’t worry, I’ll explain it all thoroughly.</p><pre>using UnityEngine; <br>using System.Collections; <br>public class ParticleSea : MonoBehaviour {<br>    public ParticleSystem particleSystem;<br>    private ParticleSystem.Particle[] particlesArray; <br>    public int seaResolution = 25; </pre><pre>    void Start() { <br>        particlesArray = new ParticleSystem.Particle[seaResolution * seaResolution]; <br>        particleSystem.maxParticles = seaResolution * seaResolution;       <br>        particleSystem.Emit(seaResolution * seaResolution);       <br>        particleSystem.GetParticles(particlesArray); <br>    } <br>}</pre><p>There is really no magic behind this code. We simply we create 3 variables: a particle system, an array of our particles and a number responsible for resolution of our sea. Then, as soon as the game starts, we create set up a new array with space suitable for all the particles. Then we set a maximum particle count to seaResolution squared. In the last two instructions we spawn the desired amount of particles and assign them to an array.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/544/0*5lxuTiAtTNqGsw1p.gif" /><figcaption><em>Don’t forget to assign ParticleSystem</em></figcaption></figure><p>The first point — done!</p><h3>Assigning particles’ position</h3><p>Right now we have our system creating particles. We also have them assigned in <em>particlesArray, </em>so we can start playing with them. What we would like to do is iterate through each one of them and assign a unique position. First we would like to create a simple grid/plane made of these. Let’s start with a new variable:</p><pre>public float spacing = 0.25f;</pre><p>and then paste this code below <em>GetParticles(…)</em> function:</p><pre>for(int i = 0; i &lt; seaResolution; i++) { <br>    for(int j = 0; j &lt; seaResolution; j++) { <br>        particlesArray[i * seaResolution + j].position = new Vector3(i * spacing, j * spacing, 0); <br>    }     <br>}</pre><pre>particleSystem.SetParticles(particlesArray, particlesArray.Length);</pre><p>What’s happening here is simple. We are looping through all of the particles and place each one based on its position. In this case, we place 25 particles in one row and every n-th 25 particles in the next row. When all particles are set, we assign our array of particles back to the particle system.</p><p>We are almost ready to see our script in action, last thing we need to do is change a bit values of ParticleSystem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/338/0*EYID9MBuNYT_t9Y_.gif" /><figcaption><em>Looping: False, Prewarm: False</em>, <em>Start Lifetime: 100</em>, <em>Play on Awake: False</em>, <em>Emission Rate: 0</em></figcaption></figure><p>If you have followed instructions correctly, as soon as you press the play button you should see something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/814/0*oGBgjsRY26MLGtCd." /></figure><p>Great! We have a grid, now we have to skew it only a bit. For that, we’ll need…</p><h3>Perlin Noise</h3><p>I can honestly say it’s great tool/algorithm and I can guarantee you’ll use it many times in your Unity projects. In this tutorial I won’t cover what precisely Perlin Noise is but if you would like to broaden your knowledge in that topic check out <a href="http://en.wikipedia.org/wiki/Perlin_noise">Wikipedia</a> or <a href="http://docs.unity3d.com/ScriptReference/Mathf.PerlinNoise.html">Unity Docs</a>.<br>In our case the only thing you need to know about this noise is that it will produce nice Z-axis output basing on X-Axis and Y-Axis. In order to apply Perlin Noise we’ll need to introduce two new public variables:</p><pre>public float noiseScale = 0.2f; <br>public float heightScale = 3f;</pre><p>and change a bit our existing nested loops:</p><pre>for(int i = 0; i &lt; seaResolution; i++) { <br>    for(int j = 0; j &lt; seaResolution; j++) { <br>        float zPos = Mathf.PerlinNoise(i * noiseScale, j * noiseScale) * heightScale; <br>        particlesArray[i * seaResolution + j].position = new Vector3(i * spacing, zPos, j * spacing); <br>    } <br>}</pre><p><em>Notice that I switched Y value with Z value and pasted zPos in place of Y value.</em></p><p>Here I introducted a new variable — <em>zPos</em>. <em>zPos</em> is calculated by <em>Mathf.PerlinNoise</em> function complemented with the position of the currently processed particle. You multiply that value by <em>heightScale </em>just to make effect more visible.</p><p>If you change the position of ParticleSea prefab to (-12.5,-5,0) and change the parameters of <em>ParticleSea</em> class to <em>Resolution: 50, Spacing: 0.5</em> you should see something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3Ybg9V8OD10cEOmz.png" /><figcaption>Static Particle Sea — so far so good</figcaption></figure><h3>Animating Sea</h3><p>The most exciting part I guess. And it’s all pretty simple. We only need to move some code to <em>Update()</em> function so it is be executed in every frame and leave some in start function and add two or three new variables which will be changing with time. The code that is executed every frame should be something like this:</p><pre>void Update() { <br>    for(int i = 0; i &lt; seaResolution; i++) { <br>        for(int j = 0; j &lt; seaResolution; j++) { <br>            float zPos = Mathf.PerlinNoise(i * noiseScale + perlinNoiseAnimX, j * noiseScale + perlinNoiseAnimY) * heightScale;        <br>            particlesArray[i * seaResolution + j].position = new Vector3(i * spacing, zPos, j * spacing); <br>        } <br>    } <br>    perlinNoiseAnimX += 0.01f; perlinNoiseAnimY += 0.01f;     <br>    particleSystem.SetParticles(particlesArray, particlesArray.Length); </pre><pre>}</pre><p>We also need to create two new global variables:</p><pre>private float perlinNoiseAnimX = 0.01f; <br>private float perlinNoiseAnimY = 0.01f;</pre><p>What happened here? Perlin Noise parameters have been extended by <em>perlinNoiseAnimX</em> and <em>perlinNoiseAnimY</em> parameters. These two guys change value with time so perlin noise function result is also changing. Feel free to change these values a bit. We also need to remove some code from the <em>Start()</em> function so it should look like:</p><pre>void Start() { <br>    particlesArray = new ParticleSystem.Particle[seaResolution * seaResolution]; <br>    particleSystem.maxParticles = seaResolution * seaResolution;    <br>    particleSystem.Emit(seaResolution * seaResolution); <br>    particleSystem.GetParticles(particlesArray); <br>}</pre><p>If you’ve done everything correctly now you should now see something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*AJqSyq2TzS4c6yRa.gif" /><figcaption><em>Feel free to play with values in inspector</em></figcaption></figure><h3>Animating particles color</h3><p>We can make the whole thing even more awesome just by making valleys transparent and changing the colour of the hills. here, the <a href="http://docs.unity3d.com/ScriptReference/Gradient.html">Gradient</a> class is very handy. Simply add another variable:</p><pre>public Gradient colorGradient;</pre><p>And play with it a bit in inspector:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*CK7Lr2VPkb71YNfm.gif" /></figure><p>Finally, we need to change the particle color according to the gradient based on particle Y position in space. In order to do that I slightly modified the body of our second, nested loop:</p><pre>float zPos = Mathf.PerlinNoise(i * noiseScale + perlinNoiseAnimX, j * noiseScale + perlinNoiseAnimY); </pre><pre>particlesArray[i * seaResolution + j].color = colorGradient.Evaluate(zPos); </pre><pre>particlesArray[i * seaResolution + j].position = new Vector3(i * spacing, zPos * heightScale, j * spacing);</pre><p>I think this change is self-explanatory. Basically, I assign the color of a particle by evaluating gradient by <em>zPos</em> variable.</p><p>If you play a bit with gradient and other variables you should easily receive a result like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*LQwjcAyAPfDYtjxv.gif" /><figcaption><em>Black camera background, Resolution: 100, Spacing: 0.3, Noise Scale: 0.05, Height Scale: 3</em></figcaption></figure><p>At the end of the day, ParticleSea class should look like this: <a href="http://pastebin.com/scVBjJtU">PasteBin</a></p><p>I hope you enjoyed this tutorial, Don’t hesitate to ask questions, I more than happy to answer them.</p><p>Feel free to download the whole project a bit pimped-up from GitHub: <a href="https://github.com/Precel/Particle-Sea/tree/master">https://github.com/Precel/Particle-Sea/tree/master</a></p><p><em>Sadly I had to remove some cool postpro effects because I wasn’t the author.<br> You can purchase these awesome effects here: </em><a href="https://www.assetstore.unity3d.com/en/#!/content/22217"><em>https://www.assetstore.unity3d.com/en/#!/content/22217</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=70ff1350fa9e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>