December 31, 2016

Books I read in 2016

0 comments
Each year I write a list of books I read during the year. This is the 2016 list:
  1. A Brief Introduction to Neural Networks. A free book that will give you an introduction to artificial neural networks, which is a group of mathematical models behaving similarly to neurons in the brain.  
  2. Clouds of Glory: The Life and Legend of Robert E. Lee. A biography on Robert E. Lee who was an engineer but also a famous general in the US Civil War. 
  3. The Society of Mind. Written by Marvin Minsky, who is famous for his contributions to artificial intelligence, the book describes how he thinks the human brain works. 
  4. Superintelligence. What will happen when our computers are becoming smarter and smarter? Are they going to kill us or are they going to help us? 
  5. The Devil in the White City: Murder, Magic, and Madness at the Fair that Changed America. This book consists of two stories: the first is about the world fair in Chicago and the second is about a serial killer who used the fair to lure his victims to their deaths. 
  6. The way of the superior man. What's the meaning of life? Why are women so strange? This book is trying to answer those questions. 
  7. Omgiven av idioter (Surrounded by idiots). Is a Swedish book on psychology and why it seems like some people around us are idiots. The answer is that humans behave differently, so to handle people who seems like they are idiots you have to handle them in a special way. You might argue that someone who can't take initiative is an idiot, but that's just how that person is, so you have to tell the person what to do.
  8. Fundamentals of computer programming with C#. Is a free book about the basics of the C# programming language. 
  9. .Net Book Zero. Is a free book about the basics of the C# programming language. 
  10. The Pragmatic Programmer. Is trying to summarize the experience of older programmers so new programmers can learn from them. 
  11. The Best of edw519. Is a free book and summarizes the knowledge of the user edw519 (from Hacker News) who is an experienced programmer. 
  12. Game Programming Patterns. Is a free book and it will teach you basic ideas or building blocks related writing software for games. 
  13. Masters of Doom: How Two Guys Created an Empire and Transformed Pop Culture. Is a biography on John Carmack and John Romero, who created the popular games Wolfenstein 3D, Doom, and Quake. 
  14. Getting Real: The smarter, faster easier way to build a successful web application. This book will teach you a better way to develop new products. If you want to develop a Microsoft Word competitor, then you should build a product with less features, get feedback from customers as soon as possible, and try to stay as small as possible. If you do that (and a few other things explained in the book) then you will be able to compete with a larger company that can't be as flexible as you can.  
  15. Production Volume Rendering. Is a free book and is all about volume rendering which is a technique to display volumetric elements such as clouds on the screen. For example, the clouds in the movie Avatar were generated with volume rendering.
  16. Beyond Band of Brothers: The War Memoirs of Major Dick Winters. Is the biography on the leader (with the red hair) in the television series Band of Brothers.
  17. Panzer Leader. Is a biography on and by Heinz Guderian, who was responsible for making the tank an important part of the German war machine during World War 2.
  18. Ivan's War: Life and Death in the Red Army, 1939-1945. Russia lost millions of soldiers during the Second World War. This is the story of them (and those who survived).
  19. Infantry Attacks. In the movie Patton, where Patton on the battlefield is facing the German officer Erwin Rommel's troops, there's a famous line: "Rommel you magnificent bastard, I read your book." This is that book, and it's about Rommel's endeavors as an officer during the first world war. 
  20. The art of game design. A book about how to design games. 
  21. Mud, Sweat, and Tears: The Autobiography. Bear Grylls has a few popular television shows about how to survive in the wilderness. This is his biography. 
  22. Red Storm Rising. What would happen if NATO and Russia decided to fight a war against each other?
  23. A history of mathematics. As the title says: the history of mathematics from before the Egyptians to the middle of the 20th century.
  24. How to solve it. A book about how to solve mathematical problems. It's obviously not a solution to how to actually solve all mathematical problems, but it gives you insights into how to start solving problems and how other mathematicians have solved their problems. You can probably apply it on other problems as well - not just mathematical problems.
  25. Fermat's Enigma: The Epic Quest to Solve the World's Greatest Mathematical Problem. Fermat's last theorem was one of the most famous mathematical problems. This book tells the story of how the problem was solved. It will also give you a brief overview of the history of mathematics.  
  26. The man who knew infinity. A biography on the Indian mathematician Ramanujan (and also to some extent a biography on the British mathematician G. H. Hardy).
  27. The Wisdom of Crowds. Will teach you when you should (and when you shouldn't) listen to a group of other people. 
  28. Sophie's World: A Novel About the History of Philosophy. Is a dramatization of the history of philosophy, so if you want to get an introduction to philosophy you should read it. 
  29. Save the cat! The Last Book on Screenwriting You'll Ever Need. Is a book about how to write stories for movies, but most likely you can also use it if you are writing a book or a story for a game or a book.  
  30. The Great War of Our Time: The CIA's Fight Against Terrorism - From al Qa'ida to ISIS. Includes stories such as why CIA failed to predict 9/11, why CIA failed to find any weapons of mass destruction in Iraq, what are some misconceptions regarding the embassy attack in Libya, some Edward Snowden criticism, and what really happened when President Bush's dog Barney got a piece of plastic stuck in his throat during an intelligence briefing. 
  31. A theory of fun for game design. Why are some games fun and other games boring?
  32. Game over press start to continue. The book covers the history of Nintendo from the birth of the company to 1999, including stories how Mario was created, how Nintendo traveled to Russia to get the game Tetris, and the history of other companies like Atari and Sega.
  33. Moon Lander: How We Developed the Apollo Lunar Module. Tells the story of how the engineers developed the so-called Lunar Excursion Module, which landed mankind on the Moon in 1969.
  34. Swarm Intelligence: From Natural to Artificial Systems. All about artificial intelligence algorithms inspired by our tiny friends the ants and other insects.
  35. Visual Explanations. A book by Edward Tufte and is about pictures of verbs, the representation of mechanism and motion, process and dynamics, causes and effects, explanation and narrative. You will for example learn how the Space Shuttle Challenger disaster could have been avoided if NASA has used other visualizations. Is filled with images so it's a fast read.
  36. Beautiful Evidence. Is about how seeing turns into showing, how data and evidence turn into explanation. It's by the same author as Visual Explanations, so it's filled with images so it's a fast read. You will learn, for example, why you should have images that explain the text close to text so the reader doesn't have to go back and forth as if you collect all images at the end of the book, like some authors do. This is common sense, but you still have to learn it so that it becomes common sense. You will also learn why the Space Shuttle Columbia was destroyed because of a PowerPoint presentation, which by the way you should avoid because they are too summarized. Use technical reports! There's also a saying that "a picture is worth a thousand words," but you have to make sure that your picture is worth a thousand words. Sometimes a picture can be worth less and then you shouldn't use it. 
  37. Envisioning Information. Is the third book by Edward Tufte I've read this year and is about how to display complex data. You will see beautiful examples of how to display both railroad lines and dance movements. And you will learn how to improve your own visualizations, such as that you should add detail to clarify and why 1 + 1 = 3 (if you have two separated colored lines, there's always a third white line between them).
  38. Adventures Among Ants: A Global Safari with a Cast of Trillions. Is a book about ants written by Mark Moffett who is also known as Doctor Bugs.
  39. Ett halvt år, ett helt liv (A half year, an entire life). A Swedish biography by a UN soldier in the Bosnian War.
  40. Chickenhawk. Is a true story written by Robert Mason, who was a helicopter pilot in the Vietnam war. The battle dramatized in the movie We Were Soldiers was one of the battles he participated in.
  41. Deadliest Sea: The untold story behind the greatest rescue in Coast Guard history. Tells the true story of the sinking of the Alaska Ranger and how the Coast Guard were trying to save the people on the boat.
  42. Black Hawk Down. Is about a failed US military mission in Somalia.
  43. Jacked: The Outlaw Story of Grand Theft Auto. Written by the same author as Masters of Doom, it tells the story of the popular game series Grand Theft Auto (GTA), from GTA I to GTA IV. It includes stories like when the GTA team hired a cop to protect them while researching violent neighborhoods in New York for the game. Since GTA is a violent game you will also learn about if you can blame the game for inspiring violence, such as an incident where two teenagers began shooting at cars on a highway after playing the game.
  44. Essential Mathematics for Games and Interactive Applications. Is a super-good book (some nerds consider it a bible) if you want to learn how to apply mathematics to games. You will learn the basics of graphics (including lightning and shaders), interpolation, collisions, and much more.
  45. Elon Musk: Tesla, SpaceX, and the Quest for a Fantastic Future. Is a biography on Elon Musk. A few years ago I wrote my own biography on Elon Musk, so it was fun to compare the books.     

December 14, 2016

Short December Updates

0 comments
Update 1. Self-driving Car
Last year I learned about an algorithm called Hybrid A* (A star), which is what a self-driving car could use to navigate in a confined space like a parking lot. I decided to implement it in Unity, and it became very popular. I've sent the project to several PhD students from schools in US, Sweden, Japan, and Germany, who wanted to use it as well as to other people who have been interested in how to implement the Hybrid A* algorithm.
To display the search tree the algorithm is using, I used Unity's Line Renderer. It turned out that it was those line renderers that had the biggest performance impact on the final product, and I used techniques like object pooling to try to increase the performance without much success. But a few weeks ago I found something called GL which is a low-level graphics library used by Unity. And GL has a line function called GL.LINES which is much faster than line renderers if you want to display a lot of lines! So here's a pro-tip: Use GL.LINES if you want to display a lot of lines!
With that said I think this is the final version of the self-driving car:


Update 2. A New Beginning
Ludum Dare was on this weekend. It's a competition where you are making a game in 48 or 72 hours depending on how hardcore you are. You are not winning anything except fame and honor, so when I participate in the competition I always try to learn something new or experiment with a crazy idea.
Each competition has its own theme, and the theme this competition was "One Room." My idea was to maybe not make a game, but one of those "art installations" where you are in a traditional game, but it's not a game. If you don't know what I'm talking about you should check out Dear Esther on YouTube.
My art installation is called A New Beginning, and I'm not going to spoil it here because you should experience the game because that was the point of it.


Not everyone liked the game because some players didn't have the patience to play it through. Some players are used to those fast-action games and become bored if they don't get it after the first few seconds. But some players liked it:
I survived, don't give up!   This game made me feel something, stuck in a room, facing an unavoidable threat.  And I tried to move everything around in despair, soon the room was a mess, and soon it was to late. The narrator caught my attention about a second chance. That is interesting!   
I don't know what to think about the narrator that teaches me life. Ok, and I didn't do anything to deserve surviving, or to deserve to die. To conclude this game creates emotions, well done. Thanks for making this game!    

Update 3. Learn how to optimize your Unity project
If you are making a game you need to make a fast game, especially if you are making a game for mobile phones. Something you might not first think about from a performance perspective is how much battery your game is using, and you can actually optimize the game so it's using less of your precious mobile phone's battery. All this is a bottomless pit and everything about how to actually optimize is spread out across the Internet. So to solve this problem I decided to try to collect all links in one page, and you can find the collection here: Learn how to optimize your Unity project.

October 28, 2016

If you read one article about Rectangle-Rectangle Intersections read this one

0 comments

I've made an autonomous traffic intersection in which self-driving cars can find their way through the intersection faster than if the intersection had traffic lights. How much faster you might ask? The answer is about 10 seconds according to my simulations. The problem is that if you add pedestrians and bikes to the equation, everything will break down, but that's a later problem!

To be able to know if a self-driving car can drive through the intersection without colliding with another car, you approximate each car with a slightly larger rectangle (to be on the safe side) and then you predict where the rectangle will be in the future with your favorite integration method. Each integration step you test if the (pink) rectangle is intersecting with any of the other (pink) rectangles. It looks like this:


Using a fast rectangle-rectangle intersection method is important to make the algorithm as fast as possible. But how can you find out if two rectangles with orientation in 2d space are colliding? The first idea I had was to divide the rectangles into two triangles and then detect if any of the four triangles are intersecting. If you google 2d triangle-triangle intersection, you will find that one way of doing this is:
  1. Approximate the triangles with rectangles and check if they intersect with an AABB-AABB intersection algorithm. These approximated rectangles have no rotation (they are called OBB if they have rotation) so you can't use this algorithm to solve the main problem, but you can use it to speed up the algorithm.
  2. If the approximated AABB rectangles are intersecting, then test if any of the edges of each triangle is intersecting with any of the edges of the other triangle with a line segment-line segment intersection algorithm.
  3. If the above fails, but the approximated rectangles are intersecting according to the first test, it means that one of the triangles could be inside the other triangle. To find out if that is true, you test if one of the corners of the triangle is inside the other triangle (and vice versa) with a point-in-triangle intersection algorithm
If the above sounds complicated I've written a more detailed explanation (with C# code in Unity) here: Are two triangles in 2D space intersecting? And maybe this image explains it better:


The problem with testing if two rectangles are intersecting by using the triangle-triangle intersection algorithm is that you maybe have to do the above four times. What if there is a better way? One other way to test if two rectangles are intersecting is using the Separating Axis Theorem, or SAT

SAT is a little bit more difficult to understand, but when you have understood the basic ideas (and have repeated both the dot product and vector projections), you will be able to apply the intersection algorithm to all convex polygons. So it's possible to test if both triangles and rectangles are intersecting with SAT, because a rectangle is a polygon with four sides. If you want a more detailed explanation of the SAT algorithm, I've written a longer article here: Are two rectangles with orientation in 2D space intersecting?

But what I found is that even though SAT includes fewer steps, it's actually slower. The reason is that the triangle-triangle intersection algorithm doesn't always need to go through all steps to see if the triangles are intersecting. So an important lesson is to take out your timer and test how fast each algorithm is. But as today's Momentum quote said: "Live as if you were to die tomorrow. Learn as if you were to live forever" at least I've learned something new!

October 22, 2016

No more red traffic lights!

0 comments

Waiting for a traffic light turning green is never fun! But what if there was a world without any traffic lights? Well, when all cars on our roads are self-driving then it's possible to create an intersection without any traffic lights. This idea is called Autonomous Intersection Management. The basic idea I've used here originates from the report A Multiagent Approach to Autonomous Intersection Management. The authors of the report released this video so that's what we are aiming for here:


But the version you can test here is more complicated as each car is simulated in Unity, which makes it more realistic, so a car is not just a mathematical model of a car as they are in the report mentioned above. So each car in my simulation has an engine torque, braking torque, realistic wheels, drag force, and much more. This makes it much more difficult to simulate future positions of the car, which we have to do to check for collisions in the intersection.

The basic idea is that each car knows where it is going, such as driving forward or turning left, so it has a path through the intersection with waypoints. It can't change lane, and it can drive forward and turn left in one lane and drive forward and turn right in the other lane. To get a smooth curve between the waypoints I used a spline interpolation method called Bezier curve. The intersection looks like this:


When the car is close to the intersection, the intersection checks if the path through the intersection is clear by using the car's velocity and acceleration. To simulate the future positions of the car, I approximate each car with a rectangle and then I'm using an integration method called Forward Euler. At each integration step, I check for rectangle-rectangle collision with the other rectangles that are stored at this future time step which are approximations of other cars. This is happening until the car is outside of the intersection. The rectangles are also a little bit larger than the car to be on the safe side:


If the first car that has arrived to the intersection can't find a clear path, the intersection checks if next car in the queue can find a clear path, and so on until there are no-more cars to check. The problem now is that the first car in the queue might wait for a path for an infinite amount of time. To solve this, there's a timer saying that if the first car in the queue has waited for 10 seconds, then the intersection should prioritize this car until it finds a path through the intersection.

But what if an emergency vehicle arrives? In that case the intersection will prioritize all cars in the same lane as the emergency vehicle until the emergency vehicle has entered the intersection. It will at the same time prioritize all cars in the lane next to the lane the emergency vehicle is in, because those lanes will never cross in the intersection.


The simulation is not yet 100 percent good, so some collisions will happen, but that's just a matter of fine-tuning all the parameters. Anyway, the version described above looks like this:


But is an autonomous traffic intersection faster than traffic lights? It's easy to add traffic lights to the simulation and then calculate the average time it takes for a car to drive through the intersection. According to my studies, the average time it takes a car to drive through an intersection with traffic lights is about 1 minute. You can compare this with the average time it takes a car to drive though an autonomous traffic intersection, which was about 50 seconds.

Looks interesting? You can test it here: Automatic traffic intersection.

October 18, 2016

Why Gamification Beats Peanut Butter on Pancakes

0 comments
The 21-day Gamification Course is a free e-mail course by Yu-kai Chou, who has written the book Actionable Gamification. But what on earth is gamification? According to Wikipedia, gamification is:
...the application of game-design elements and game principles in non-game contexts to improve user engagement, organizational productivity, flow, learning, crowd-sourcing, employee recruitment and evaluation, ease of use and usefulness of systems, physical exercise, traffic violations, and voter apathy, among others. A review of research on gamification shows that a majority of studies on gamification find positive effects from gamification. However, individual and contextual differences exist.

If you are making a game it's obviously a good idea to understand the game-design elements and game principles. But if you are not making a game, you may also need to apply the ideas behind gamification. Last year I read the book Superbetter, which is promising to give you a framework so you can apply the ideas behind gamification to improve your own life. The book says: "Playing SuperBetter for 30 days improves mood, reduces symptoms of anxiety & depression and increases belief in the ability to successfully achieve goals."

One of the interesting ideas from the book Superbetter is what you should do if you have experienced a traumatic event. If you, within a few hours after that event, play a game like Tetris, then you will minimize the risk of getting post-traumatic stress from the traumatic event. So as in Wikipedia's definition, gamification can be applied to many more areas than just traditional games. With that in mind, let's learn more about gamification.

Introduction

Gamification is the art of stealing all the fun and addicting elements found in games and applying them to real-world or productive activities. But why is it called gamification if it can be applied to so many other areas? The reason is that the game industry was the first to focus on human-focused design because games have no other purpose than to please the user playing the game. This is actually not entirely true because there are games with a purpose other than to be fun, such as a game helping victims with burn injuries heal their wounds, but you get the idea.

Human-focused design is a design process which is trying to optimize for the human in the system and not the efficiency of the system. You can compare it with the iPhone, which didn't have a stylus because Steve Jobs focused on the human and not the technology, which is called function-focused design. Games have to focus on the human because a game is not a game if not a human is playing it. But if you are building something else, like a nuclear reactor, then you can focus on designing an efficient system.

The game industry might not be old, but it has spent a lot of time to master motivation and engagement, so you can now learn something from games, such as why the game World of Warcraft is addicting? I personally had a classmate who disappeared from school because he became addicted to World of Warcraft. What if there was a way to make school as fun as games? This is what you will learn here!

You can argue that it is the challenges and limitations, such as rules and obstacles, that makes a game fun. A game like soccer has a challenge (win the game against the opposing team) and limitations (you can only kick the ball with your feet), but everyone, including me, doesn't enjoy playing soccer. So a game needs more than just challenges and limitations to be fun.

Why do you want to do something?

Why do you like to play soccer, and why do I hate to play soccer? There are 8 fundamental reasons (called core drives, or CD) why you and me want to do something:
  1. Meaning. You want to do something because you feel it has a purpose.
  2. Accomplishment. You want to do something to overcome challenges.
  3. Empowerment. You want to do something because you like to be creative and test different strategies.
  4. Ownership. You want to do something if you feel like you own what you are doing.
  5. Social influence. You want to do something because other people around you are doing it. 
  6. Scarcity. You want to do something now because you think the opportunity may be lost if you are not doing it now.
  7. Unpredictability. You want to do something because you want to see what's happening after you have done it. 
  8. Avoidance. You want to do something to avoid something negative happening if you are not doing it. 
The difference between these core drives is not always clear! For example, being part of an exclusive shopping network is:
  • 1. Meaning - You want to be a part of the elite.
  • 2. Accomplishment - You made it into the club.
  • 4. Ownership - You get to buy the best stuff!
  • 5. Social influence - Now your friends are jealous of you.
  • 6. Scarcity - You are part of this 1 percent ultra exclusive club!

A summary of each core drive

1. Meaning. You believe you are doing something greater than yourself or that you were "chosen" to do something important. Examples:
  • Spend your spare time updating Wikipedia. You believe that by updating Wikipedia your work will affect millions of people around the world in a positive way.
  • Being a member of a limited network, such as "an exclusive, member-based online shopping site for clothing and accessories, which runs time-limited sales which can only be viewed by its members." 

2. Accomplishment. You have an internal drive to make progress, develop skills, and overcome challenges. This is the core drive that is the easiest to design for because you can simply add leaderboards, points, and trophies. But don't forget the challenge, because you don't want to get rewards for free. Examples:
  • I wrote a book about Elon Musk (the challenge) and my "leaderboards, points, and trophies" is the book's Goodreads rating. Each time I get a good rating I feel proud and sometimes I take a print-screen of the rating and attach it to a tweet.
  • When you buy something on the auction site eBay, you feel that you won. So even though you might have paid more compared to what you initially wanted to pay, you feel that you won against the other guy who were bidding against you.  

3. Empowerment. You need ways to express your creativity by repeatedly trying to figure things out and try different combinations. This makes you feel good and you take action because you find the action enjoyable on its own. You also need to be able to see the result of your creativity by receiving feedback so you can improve what you have done. Examples:
  • The game Minecraft is popular because you can be creative in it and do whatever you want. Other people can join the map and give you criticism, but you can also give yourself criticism because you see what you've created.   
  • Websites that let you play around with your personal economy so you can test different strategies. What's happening if you invest 20 percent in stocks and save 30 percent in your savings account?   


4. Ownership. You are motivated when you feel like you own something, and you want to make what you own better. Besides being the major core drive for wanting to accumulate wealth, this deals with many virtual goods or virtual currencies. If you in a game spend a lot of time to customize your profile or avatar, you automatically feel more ownership towards it. This is also the core drive that makes collecting stamps or puzzle pieces fun (for some). Examples:
  • In Pokemon the player has to catch all Pokemons.
  • McDonald's had a physical game where you had the chance to get a piece of the game when you bought a hamburger. When you accumulated all the pieces McDonald's gave you a reward. 
  • You've spent a lot of time writing blog posts on your blog (you now own it) and you want to improve it by increasing the number of readers.


5. Social Influence. This drive incorporates all the social elements that drives you, such as mentorship, acceptance, social responses, companionship, competition, and envy. When you see a friend who is amazing at some skill or owns something you also want to own, you become driven to reach the same level. This also includes your drive to draw closer to people, places, or events that you can relate to. If you see a product that reminds you of your childhood, the sense of nostalgia would likely increase the odds of you buying the product. Examples:
  • The online game Parallel Kingdom has mentors that spend time with you when you've just started the game. They give you items and a push in the right direction. Players who get help tell themselves: "I can't possibly quit this game now and let my mentor down. He/she just gave me his valuable items! I can't let his/her effort go to waste." So they continue playing because someone else has done a favor for them. 
  • A hotel wanted to persuade their guests to reuse their towels, so they tested two different signs: "Please help us save the environment by reusing your towel," and "80 percent of the guests that stayed in this room reused their towels." It turned out that the second sign was most effective because we humans tend to do what other humans do. If you are told other people are reusing their towels, then you will also reuse them.  


6. Scarcity. This is the drive of wanting something because you can't have it and you want it immediately. Many games can say "come back in 2 hours later to get your reward." The fact that you can't get something right now motivates you to think about it all day long, so you might pay to have it at once. Examples:
  • Facebook started at a small scale for just Harvard students. When Facebook opened up to everyone, you wanted to join because you previously couldn't.
  • Until the mid 20th century, diamond engagement rings were a small and dying industry in America. But then someone came up with the idea to restrict the supply of diamonds to make them a status symbol. The diamonds themselves aren't actually that rare.
  • The game Candy Crush gives you the opportunity to either pay to get something now or wait sometime. Some pay because they want it immediately. 
  • You are more motivated to buy a product with a limited edition, even though you don't know how many "limited" is. 100 products? 1 million products? It doesn't matter to you! 

7. Unpredictability. You want to know what's happening next. If you don't, your brain is engaged and you think about all the time. This is why you watch movies or read books. However, this drive is also the primary factor behind gambling addiction. There are experiments showing how rats continuously press a lever because of unpredictable rewards. What if the next press will result in cheese? Examples:
  • What if the next lottery ticket will make you rich?
  • What if the famous person on Twitter is finally replying to your tweets?

8. Avoidance. This core drive is based upon the avoidance of something negative happening, such as avoiding losing previous work or avoiding admitting that everything you did up to this point was useless because you are now quitting. The problem is that you are much more likely to change your behavior to avoid a loss than to make a gain. Examples:
  • It's much harder to sell a stock if you have lost money on the stock than it is to sell a stock with a profit. This is why so many people are losing money in the stock market! What you should do is to sell the losers and hold on to the winners. 
  • When spending time on an auction on eBay you don't want to lose the auction. 

The Octalysis framework

You can summarize the 8 fundamental reasons (core drives) why you want to do something in the co-called Octalysis framework:


You can connect the different sides of the octagon to the different parts of your brain. But that's boring so let's see examples of the framework in action:

Twitter



Farmville



Example: Blogging

Why do you want to have a blog? As said before, there are 8 fundamental reasons (core drives) why you want to blog:
  1. Meaning. You believe that by writing articles you can help people and make the world a better place. You will also become a better writer. 
  2. Accomplishment. It's a challenge to write a blog: you have to come up with new ideas about what you are going to write, and you have to update frequently.
  3. Empowerment. By experimenting with the blog design and different types of articles you can be creative and see how many readers you can get.
  4. Ownership. You've spent a lot of time with the blog so now you feel like you own it, so you want to improve it.
  5. Social influence. It's more fun to blog when you see that people are reading the blog, and it's fun to compete with other people who are writing similar articles.  
  6. Scarcity. Writing a blog is a long-term investment. You don't know which articles will become popular, so you have to wait and see. 
  7. Unpredictability. It's fun to see which articles will become popular. 
  8. Avoidance. You measure how many people are visiting your blog and it's painful to see when the trend line is down. If the trend line is down, you want to write more articles to avoid the fact that all the hard work up to this point has been a waste of time.  

Example: Selling video games

While writing this article I read the book Game Over: How Nintendo Conquered The World. It explained how Nintendo used gamification to sell more video games:
...it was wise to market video games like movies - released cautiously, rationed so that demand outpaced availability, and then withdrawn from circulation as soon as interest began to wane. This rationing tactic, treading games like priceless objects (Scarcity), worked. After all the hyper about a new game took hold (Meaning), kids dragged their parents to stores, but outlets couldn't keep the games in stock. A kid who was absolutely dying to get "Link" [a game] would arrive at the store, only to find it sold out. Maybe he would try a few other stores without success (Empowerment and Unpredictability), but then he would buy another Nintendo game. Then, a week or month later, a new supply of "Link" would come in. The kid wanted "Link" more than ever then, and unless his were the most iron-willed of parents, they would succumb.
The Atari wave (the competing game company) had floundered in large part because of a flooded market. By design, Nintendo did not fill all of the retailers' orders, and it kept half or more of its library of games inactive.

I also suspect that the kid's friends, and those around him who had found a copy of the game, were influencing the kid to buy the game (Social influence). When the kid finally bought the game, the kid had overcome the challenge to find the game (Accomplishment and Avoidance as in not finding the game at all). Now when the kid has spent a lot of time to find the game, the kid now feels like the kid owns the game (Ownership) and will thus enjoy it more.

But why is Nintendo's share of the market today much lower than Nintendo's share of the market in the 1990s if they have figure out the secret to how to sell games? The answer is that today it's much more difficult to create a hype about a new game (Meaning) because so many good games are being produced each year. Nintendo is also doing their best to avoid creating a hype about a new game because they are preventing YouTubers from playing their games, and since many gamers are buying the games the YouTubers are playing (Social influence), no-one is buying Nintendo games.    

Summary

This was just a short summary of the 21-day Gamification Course. If you want to learn more you should take the course yourself. I learned a lot, even though I had studied the area before by reading books like Influence, Yes!, and Superbetter. So I will continue to study the area because a good product is not good unless you have users who are actually using the product. And since you can use gamification in other areas as well, such as avoiding post-traumatic stress, you now see why gamification actually beats peanut butter on pancakes. 

October 9, 2016

Why are some games fun and other games boring?

0 comments

I've read the book A theory of fun for game design by Raph Koster. While the word game can include games like chess, the book has a focus on digital games, such as computer games, which the author also has worked with. Neither should you confuse game design with game theory, which is used in areas like in politics and economics, and is about how competitors make optimal choices.

Compared with many other areas, such as math, the design of digital games is a relatively new area. I think I played my first computer game in like 1995 and it was also around that time when computer games started to become mainstream. So there isn't really a complete theory of how to make digital games interesting to play, but this book is trying to develop the basics of such a theory. I've already read another similar book called The art of game design by Jesse Schell. While the latter book has far more content, you can read "A theory of fun for game design" in a weekend. But I still think you should read both books.

Game design is tricky to study because a game is a combination of many different areas. If you want to be a good game designer, you have to be an expert in cognitive psychology, computer science, environmental design, and storytelling - and that's just to name a few. To really understand why you think some games are fun and other games are boring, you need to see them from all these points of view.

The basic idea the book is trying to give the reader is that we humans are still cavemen, and that's why we like to play games. Our primitive brain is consuming patterns, such as recognizing faces. The same thing is happening when we play games because a game consists of patterns we are trying to recognize. It's when we have recognized, or learned, a new pattern that we have fun.

What's happening when we have have fun is that endorphin is released into our system, and this is always happening when we have learned something new or mastered a task in an environment where there's no pressure - not just when we play games. Why is this happening? The reason is that it's important for the survival of the human species that we learn, so our bodies reward us for it with moments of pleasure. So if you are making a game you have to make sure the player is always learning something.

This release of endorphin can make games have other purposes than just making us have fun. According to the book Game Over Press Start To Continue:
Some serious ill children in a hospital who played Nintendo required half as much pain medication as those who didn't. Television had no effect on the amount of medication required.
According to doctors, playing Nintendo games has the power to alleviate pain for two reasons. First, the intensive interaction with video games requires a degree of concentration that acts as a diversion and distraction from pain - and everything else. Secondly, the highly excited state achieved during this interaction generates a steady flow of endorphin into the bloodstream. Endorphin is the naturally occurring proteins that mask pain and cause a sense of euphoria. Nintendo playing can cause a sort of high, but so can jogging.  
 
To make sure the player is always learning something new you have to come up with puzzles:
  • The player wants new puzzles. What's happening when you think a game is boring to play is that you have stopped learning something new, which is the same thing as saying that you know the answers to all puzzles in the game. The easiest way to add new puzzles is to add multiplayer, which is why chess is so popular. If you play chess against a physical person then each new game is a new puzzle to solve, so chess consists of an endless amount of puzzles.
  • These puzzles should be different, but not too different. A new puzzle might force a whole new system on the brain, and often the brain doesn't like that because it doesn't like to do more work than it has to. You think this is exhausting, so you will stop playing the game. So the game designer shouldn't mix too many different types of puzzles. This is yet again why chess is popular. Each new game of chess is a new puzzle, but the difference between each new game of chess is not too different.  
  • The player has to understand the puzzles. You will not try to solve patterns and puzzles that appear as noise to you, instead you'll likely select problems you think you have a chance at solving. So if the you don't understand the puzzle, you will stop playing the game.  
  • The player must want to solve the puzzles. You and me like to learn different things and we have different experiences when we start playing the game. So everyone will not like your game, which is why you have to come up with puzzles your specific audience likes to solve. You will never be able to make a game for everyone. The puzzles you come up with should be puzzles that your audience has solved before. If we encounter a problem we've seen before, our first approach is to try the solution that has worked before, even if the circumstances aren't the same. We are lazy!

An actual image from the book

These puzzles can be everything between heaven and earth. But, as said before, we humans are still cavemen, so what we think is fun is actually training us to be better cavemen: 
  • Players like to run and shoot, which is actually teaching them to escape dangerous animals and hunt for food. 
  • Players like to cheat, which is another cavemen skill. They didn't have any rules back in the old cavemen days, so the best cheater was the one who was most likely to survive. In a battle, tricking the enemy to attack the weak point when in fact it's the strong point is a cheat, but it's the winning strategy making the cavemen survive.
  • A players who's playing the easiest level 200 times just to build up enough resources so the player can cruise through the rest of the game with little risk is the same as what the cavemen did when they stockpiled food to survive the winter.
  • Players like realism even though they are not aware of it. If we see a character in the game, which has been modeled to look like a real person, we can tell if there's something wrong with the character. If the character is not 100 percent realistic, our primate brain thinks the character may be sick, so our primate brain is telling us to stay away from the character which is why we don't like it. This is why so many movies featuring animated "realistic" characters has failed. The same is true for physics. It has been shown that in games considered to have the "best controls" shared an important characteristic: When you hit the jump button, the character spent almost the same amount of time in the air.   

So the basic idea behind a digital game is easy. The book argues that to test if a game is fun to play, the best test is to play the game without any graphics, music, story, etc. If that's fun, then everything else will improve the game. Some game developers tend to add a story to a boring game, but we don't play games because of stories, so most players tend to skip the story or quit the game if the player can't skip the story. Graphics is important, but as we have seen with games like Minecraft, graphics is not what makes a game a fun game. Finally, the book argues that a game should provide the player insights into the player itself.  

If you don't want to read the book, or if you read the first version of the book, or if you are just bored, the author made a video presentation called A theory of fun 10 years later

October 4, 2016

The most boring article about curves you'll ever read

0 comments
I'm using Paint.net as my main painting program. It may not be as good as Photoshop, but it's free and far better than what is delivered with Windows. If you want to make a curve in Paint.net you have two options: Cubic Spline or Bézier Curve. Both curve types are almost the same, but just almost. But have you ever wondered how the computer is creating those curves? The answer is interpolation.

This summer I read a book called Essential Mathematics for Games and Interactive Applications and it included an entire chapter on interpolation. If you want to connect two points with a curve you need to do what the game Mafia did: learn interpolation:


If you want to build curvy roads you have to do what the game Cities: Skylines did: learn interpolation:


Interpolation is actually a big topic within math. You can define interpolation as "a method of constructing new data points within the range of a discrete set of known data points." The easiest form of interpolation is linear interpolation, where you follow a straight line from A to B (the known data points).

But curves are more interesting than straight lines. I recently had the need to connect two points with a curve, so I was forced to learn everything about interpolation. If you want to connect two points with a curve you have two main options:
  1. Generate a Catmull-Rom spline. You should use this alternative if you want to control the shape of the curve by moving the points that make up the curve. I suspect that this is the method Paint.net is using to generate a cubic spline because a Catmull-Rom spline is a cubic spline. 
  2. Generate a Bezier Curve. You should use this alternative if you want to control the shape of the curve even though the points that make up the curve are fixed. If you use this curve you get two handles that you can move around to determine the shape. This curve type was developed to make aerodynamic car bodies.   

Both of these curve types are actually quite easy to generate. To generate the Bezier curve you just have to make a few linear interpolations between the end points and control points. The problem is to move along the curves. What's happening when you generate these curves is that the derivative is not constant, with the result that the step size is not constant. You move along the curves with a parameter called t. This t is between 0 and 1, where t is 0 at the start of the curve and t is 1 at the end. But because the derivative is not always constant, 0.5 is not necessarily at the middle of the curve. This is the result if you have a Bezier curve (you can see that the lines at the beginning of the curve are longer than the lines as the end of the curve):

 
To solve this problem you have to go to your bookshelf, find the book you used when you studied numerical methods, dust it off, and repeat both Simpson's rule and Newton's method. It was about 12 years since I used that book, so it was really dusty. Anyway, if you use those methods, you will be able to generate a Bezier curve with constant steps (to generate a Catmull-Rom spline with constant steps you follow the same procedure):


If all this sounds complicated, I've written a tutorial on how to do it: Everything about interpolation in Unity with C# code.

September 23, 2016

Why you should forget everything you learned about bed pillows

0 comments
Do you know the history of bed pillows? This is the history according to Wikipedia:
The first people to use pillows were those who lived in early civilizations of Mesopotamia around 7,000 BC. During this time, only the wealthy used pillows. The number of pillows symbolized status so the more pillows one owned the more affluence he or she held. Pillows have long been produced around the world in order to help solve the reoccurring problem of neck, back, and shoulder pain while sleeping. The pillow was also used to keep bugs and insects out of people's hair, mouth, nose, and ears while sleeping.
Pillow use has been associated with the mummies and tombs of ancient Egypt dating back to 2055–1985 B.C. Ancient Egyptian pillows were wooden or stone headrests. These pillows were mostly used by placing them under the heads of the deceased because the head of a human was considered to be the essence of life and sacred. The ancient Egyptians used these wooden or stone pillows in order to provide support to a corpse's head, uphold body vigor, keep blood circulating, and keep demons away. 
The Romans and Greeks of ancient Europe mastered the creation of the softer pillow. These pillows were stuffed with reeds, feathers, and straw in order to make them softer and more comfortable. Only upper-class people typically owned these softer pillows, however all classes of people were allowed to use some type of pillow while sleeping in order to give them support. People in ancient Europe started to use pillows when going to church in order to kneel on while praying and to place holy books on. This is a tradition that still lives on today. Additionally, the Romans and Greeks used their pillows by placing them under the head of those deceased just like the ancient Egyptians did.
Chinese pillows were traditionally solid, though sometimes used with a softer fabric over them. Over many Chinese dynasties, pillows were made from a wide range of materials including bamboo, jade, porcelain, wood, and bronze. Ceramic pillows became the most popular. The use of the ceramic pillow first appeared in the Sui Dynasty between 581 and 618 while mass production appeared in the Tang Dynasty between 618 and 907. The Chinese decorated their pillows by making them different shapes and by painting pictures of animals, humans, and plants on them. One common type of pottery used was Cizhou ware. Chinese ceramic pillows reached their peak in terms of production and use during the Song, Jin, and Yuan dynasties between the 10th and 14th century, but slowly phased out during the Ming and Qing dynasties between 1368 and 1911 with the emergence of better pillow making materials.
So what can we learn from the history of bed pillows? The bed pillow was used to keep bugs and insects out of people's hair, mouth, nose, and ears while sleeping. I'm not sure about this, why can't insects climb up on the pillow? And what about the Chinese use of ceramic pillows? This is how they looked like:

Source: Victoria and Albert Museum

Who on earth would you like to sleep on a ceramic pillow? According to this article, the author speculates that they were used to encourage a better sleeping position for the body, or to maintain the highly complex hairstyles worn by women during the Ming dynasty. Other reason might have been that the material qualities of ceramics were thought to have health benefits for the sleeper, and that bed pillows were thought to influence and guide dreams in the hope of producing male heirs.

But back to the present. This happened: my bed pillow was torn apart (it was old so I didn't have a pillow fight), and after cleaning the pillow material from the floor, I had to sleep without a pillow. After a good night's sleep I asked myself: why are we using bed pillows? So I decided to do some research. According to this article, the benefits of sleeping without a bed pillow are:
  • It will save you money. But bed pillows are not expensive, and even though every cent counts in the end, you shouldn't sleep without a pillow just to save money.
  • It will lead to less neck, back, and shoulder pain, higher quality sleep, and even fewer wrinkles.
...and the benefits of sleeping with a bed pillow are:
  • It improves sleep quality and fits more physiologically and mechanically with the natural curve of the cervical spine. Sleeping on your back without a pillow changes your neck angle from its normal daily position. When standing, your neck also has a certain curve to it. If you sleep on your back, that curve is also distorted.

So if you sleep without a pillow you will get a higher quality sleep, and if you are sleeping with a pillow it will improve sleep quality? So instead of listening to articles that argue back and forth, the human guinea pig in me decided to experiment to sleep without a bed pillow.

Three weeks have now passed, and I can say that I'm not missing my pillow. I feel a little bit more rested, I feel that my posture has improved, and my neck hasn't begun to hurt even though I sometimes sleep on the side. One of the articles argued that "Sleeping on your back without a pillow changes your neck angle from its normal daily position," but if the bed is soft, won't that compensate for it? Anyway, it's hard to tell after just three weeks because other conditions might have changed, such as the weather. It's a little bit cooler these days and that might have made me feel more rested. So I might do a follow-up to this article in a few weeks.

If you want to take it to the extreme, some argue you should sleep on a hard surface:


But I think I have to wait until my bead breaks until I begin to sleep on the floor...

September 8, 2016

How can engineers solve a problem like ISIS?

0 comments
I'm an engineer so I like to solve problems - not only smaller problems but also more global problems. There are a lot of global problems out there, like North Korea. I don't think I can solve a problem like North Korea, even though there are peaceful solutions. But it can't possible hurt to think about the solutions in the back of my head, and maybe one day I will come up with a solution no one else has thought about. What if Elon Musk had said: "It's not possible for one man to solve the problem of expensive rockets, so I will not try!" But it turned out it was possible for one man to solve that problem: SpaceX.

Another global problem we have is terrorism. While the probability that the North Korean problem will affect me personally is low, the probability that terrorism will affect me is still low, but considerably higher.


To come up with a solution to terrorism, I decided to read the book The Great War of Our Time: The CIA's Fight Against Terrorism - From al Qa'ida to ISIS. It is written by Michael Morell, who has had several high ranking positions within CIA, including the job as he who had to give the President of United States his daily briefings on terrorism threats. So the book includes several anecdotes from George W. Bush, including what really happened when Bush's dog Barney got a piece of plastic stuck in his throat during one of these intelligence briefings, and the quote by Bush himself: "Fuck diplomacy. We are going to war."

The book is not including any details on how CIA is working to solve problems like terrorism, because that's classified. But the book will give you an overview of terrorism, from 9/11 to ISIS. This overview includes stories such as why CIA failed to predict 9/11, why CIA failed to find any weapons of mass destruction in Iraq, what are some misconceptions regarding the embassy attack in Libya, that cyber crime is now generating as much money as the illegal drug trade, and an entire chapter on Edward Snowden criticism. But it also includes more personal stories, such as the confusions within CIA after 9/11:
I seriously thought a nuclear detonation in New York or Washington was a possibility - to the point of telling my wife that if such an attack were to happen in Washington to put the kids in the car and start driving west and not stop. It was surreal.  

The book argues that it is impossible to beat an organization like ISIS with bombs alone. The reason is, according to the book, that terrorists organizations have "nine lives":
When the West and its allies keep pressure on al Qa'ida, when it has to worry about its own security more than it can about its operations, al Qa'ida loses capability. When that pressure is not there, when it is free to operate, its capabilities grow. It is a pattern that has played out over and over again, wherever al Qa'ida has operated.   
So the west can put pressure on ISIS, but it will not defeat ISIS. The west has put pressure on al Qa'ida since 2001, but al Qa'ida is far away from being defeated.

What you also need is to stop the supply of people who's joining terrorist organizations. This is also more cost effective. The dollars spent by the US government on programs related to stopping radicalization are an infinitesimally small percentage of the government's overall counter terrorism budget. The problem is that it involves other countries, so it's far easier to drop expensive bombs on ISIS than it is to change a country that supply ISIS terrorists.

But one country that has succeeded in stopping the supply of new terrorists is Indonesia:
Between 9/11 and 2006, Indonesia suffered sixteen terrorist attacks, resulting in more than three hundred deaths. In the next eight years, there were only five attacks, causing fourteen deaths. And, as of early 2015, only about 150 Indonesians had gone to fight in Syria, a remarkably low number for its population and for its terrorist past. While excellent intelligence and law enforcement work have played a role - and these tools will remain vital, particularly as many terrorists will be released from prison over the next few years - so have the Indonesian governments's counter-radicalization programs.
At the core of Jakarta's program is a willingness to work with any entity that can reach young people with the right messages. The program is systematic and reaches almost every part of Indonesian society. The messages are essentially two - that the extremist interpretation of Islam is not consistent with the Koran, and that there is great value in tolerance.
Religious organizations in Indonesia are popular within society and are therefore an important channel for delivering the government's counter-narrative to al Qa'ida [for every narrative of al Qa'ida's, there must be a counter-narrative delivered loudly and widely]. Jakarta, for example, works with imams and mosques to offer a variety of perspectives on Islam, particularly to youth and student groups. Schools are also a focus - courses emphasize inclusion and tolerance. All the world's religions are now studied, not just Islam, and schools are working to provide multiple perspectives on some of the issues that have played a role in radicalization, such as the relationship between Israel and the Palestinians.
Popular culture is also used. The government communicates with young people through popular musicians who communicate carefully crafted messages aimed at counteracting radical ideas. Music with lyrics about tolerance as an alternative to extremism has become popular in Indonesia and indeed throughout Southeast Asia. All of this is supported by a variety of media - books, articles, newsletters, the Internet, television, and radio. TV and the Internet focus on urban populations. Radio stations reach rural areas.
All of this, of course, requires focus, effort and resources. It needs to be done throughout the Muslim world. It needs to be led by the governments in question. And it needs to be supported by the United States.

So what can engineers do to stop the supply of terrorists? Yesterday I found the article Google's clever plan to stop aspiring ISIS recruits. It says that Google can use a combination of its search advertising algorithms and YouTube to target aspiring ISIS recruits and hopefully preventing them from joining the terrorist organization. What Google has found is that "there's a lot of online demand for ISIS material, but there are also a lot of credible organic voices online debunking their narratives." This is exactly what the book said: "For every narrative of al Qa'ida's, there must be a counter-narrative delivered loudly and widely."

What the software developed by Google is doing is that it can place ads alongside results for any keywords and phrases it has determined people attracted to ISIS are searching for. When you click on these ads, you arrive at Arabic- and English-language YouTube channels. These channels have videos like testimonials from former extremists, imams denouncing ISIS's corruption of Islam, and videos from inside the ISIS's caliphate in Syria and Iraq showing it is not the paradise they say it is. One of these anti-ISIS videos is showing a line of people trying to get food.

This new software seems to be working. When they tested it during two months, they found that searchers clicked on the anti-ISIS ads three or four times more often than a typical ad campaign. And those who clicked spent more than twice as long viewing the anit-ISIS videos compared with the best estimates of how long people view other YouTube videos.

September 4, 2016

Traffic Light Simulator - a Ludum Dare Game

0 comments
Ludum Dare is a competition where you are making a game in 48 hours. You have to make everything yourself, so you can't download any textures or models from someone else. There's also a less hardcore competition going on at the same time where you are making a game in 72 hours and can use other people's textures and models. In the latter competition you can also work in a team, but in the 48 hour competition, you have to work on your own.

I don't know if it's easier to make a good game if you are living in a time zone in US compared with in any other part of the world? If you are living in Europe, the competition begins at 3 AM on Saturday morning and ends 3 AM on Monday morning. So if you have a job to go to on Monday, you can't work the entire 48 hours. If you are living in US, the competition begins on Friday evening and ends on Sunday evening. So I suspect it's easier to maybe come up with ideas on Friday evening, and then work for "two days" to make the game itself?

Anyway, each competition has a theme, and the theme this time was "Ancient Technology." You can stretch this theme so you won't be disqualified if the game is not 100 percent based on that theme. My original ideas included:
  • Leonardo Da Vinci's tank
  • A ship game where you are controlling one of those sailing ships from Ben Hur
  • A game where you attack a castle with a trebuchet, which is a catapult
But after brainstorming ideas I came up with an ancient technology called traffic lights, so I made a Traffic Light Simulator (click on the link if you want to play it or download the entire source code).


Have you ever heard the history of traffic lights? Neither had I so I decided to read about it on Wikipedia. The story goes as follows:
The world's first, manually operated gas-lit traffic signal was short lived. Installed in London in December 1868, it exploded less than a month later, injuring or killing its policeman operator. 
My original plan was to include exploding traffic lights, but in the end I realized that it wouldn't work. A single exploding traffic light would ruin the game, because all cars and pedestrians would collide with each other. But in hindsight it would be possible for the player to rebuild the traffic light, but 48 hours is just 48 hours so everything is easier in hindsight.

After about 48 hours I ended up with a game where you control 12 traffic lights in an intersection. There are both pedestrians and cars from the era (which I modeled in Blender. The game itself was created in Unity). The game begins slowly with just a few cars and pedestrians, but as you get more points, more cars and pedestrians will arrive. You will be punished (get negative points) if a car crashes or a pedestrian is hit by a car, and you will get points if the cars and pedestrians arrives safely to their final destination. If a car crashed it will begin to smoke and you have to click on it multiple times to remove it or other cars may hit it.

To make the game more stressful, the cars begin to honk if they have to wait for too long. I also added an ambulance that will make an annoying sound I made in a cool software called Bfxr. Remember that you are not allowed to download the sound of an ambulance, so I had to make my own ambulance sound. It all looks like this:





What you win in a Ludum Dare competition is fame and honor, so you are not taking part in the competition to make money. But you will learn something new, you can test an idea you've had in the back of your head, and if the game is good you can improve and sell it. You will also get feedback. A week has passed since the competition and people have had the time to play my game. The feedback so far includes:
  • That was really sweet, although the traffic lights weren't always clear to where they pointed. I think I killed a person or two...
  • I really enjoy this game!!! Best which I had seen on this LD! Fun and difficult. btw. why all drivers are drunk?
  • Very nice idea and well done! And quite difficult to manage after some time. It would be nice though to see where the cars and pedestrians want to go when they approach the intersection.
  • It starts off very slow, and i think it would be a lot more fun had it been faster. Overall, a nice entry.
  • The idea and the game is very fun. I would like some kind of end goal. But overall well done.

So why are the drivers acting as if they were drunk? The cars are following a series of waypoints, but the cars are not that good a driving between the waypoints. The reason is that they are just caring if they should drive left or right to reach the waypoint, so when they realize they should drive in the opposite direction, they have driven a little bit too far. I think the easiest way to solve this problem is by using a PID controller. I tried to implement one in the game, but ran out of time, so I had to leave them drunk. 48 hours is after all just 48 hours... 

September 2, 2016

Why marketing your company by sharing your knowledge is working

0 comments
A few years ago I found a YouTube video where Jason Fried (@jasonfried), who co-founded 37signals, argued that the best way to market your company is by sharing your knowledge. You can find the article here: How to market your company by sharing your knowledge. Among other things, he said that:
  • We tend to buy products from someone who taught us something - not just from big companies
  • You should out-teach your competitors - not out-spend them 
  • We don't want to give away our knowledge because we are afraid that someone will steal it and use it against us, but you shouldn't worry about your competitors - but be aware of them. 
  • PR firms are a waste of money and advertising is expensive and can be difficult depending on the company you have 
  • If you teach, you will get an audience that will come back to you and spread the word about you to their friends 
  • One article by Jason Fried took 15 minutes to write, but more than 800,000 people has read it. How expensive would it be to drag in 800,000 people with ads?

I've tried to apply this since I wrote the article. Not every article on this blog has the purpose to teach something to someone, but most articles have this purpose. I've also extended this to not just write articles on this blog, but also explained how to program complicated games in Unity. Last week I wrote an article about how to Use Linear Algebra to solve problems in Unity with C#, and guess what? Microsoft's official .NET Blog gave it a link: The week in .NET – 8/30/2016.


Why is this link important? Well, Google is using links to determine at which position you should rank in the search results when someone is searching for something related to that link. And links from popular sites, like Microsoft, are more important than links from less-known sites. So even though in might not first look like much with a tiny link, that link is actually really important. And I wouldn't have got the link if I hadn't shared my knowledge to you! Moreover, I didn't spend a single dollar on writing the article and I also learned a lot by writing the article.

August 31, 2016

Can you explain how to use PID controller to follow that path?

0 comments
I few months ago I wrote an article about the Hybrid A Star pathfinding algorithm for self-driving cars. It turned out to be a popular article, and someone asked in the comments section: "Can you explain how to use PID controller to follow that path?" And the answer is: yes I can!

PID controller is a technique to minimize an error you have. If you have a self-driving car, this error is the length of the difference between the car's actual position and the position it should have. This error is called Cross Track Error, or just CTE:


The math is simple and you just need a few lines of code to make it work, but the technique is not commonly known among those who haven't taken a course in control technology. I took a course in control technology, but I forgot about the PID controller, only to rediscover it last year when I took a course in self-driving cars.

The PID controller consists of three parts: the P, the I, and the D. I made a video to explain why you need the P and the D, and you only need the I in real-life if there's an error in the technology you have. There aren't many errors in the computer so you will not notice why you need the I in the video:


This was just a tiny introduction, but I've written an entire tutorial on how you can write your own PID controller in Unity (with C#): Minimize an error with a PID controller.

August 30, 2016

Fun with linear algebra

0 comments

Let's have some fun with math, especially linear algebra!

- Is this your idea of fun, Erik?

- Yes, when you see what you've learned is actually working in real life, then that's fun. Not fun as in drinking whiskey, but you get the idea...

When I studied linear algebra in school I had no idea when I would need to know if two vectors are pointing in the same direction or why you would ever need to use the cross product. But a few years later, I've found some practical problems to solve where I actually needed to know if two vectors are pointing in the same direction. I've collected these problems and their mathematical solutions in a new tutorial series: Use Linear Algebra to solve problems in Unity with C#.

The problems I've solved so far are:

The idea is to minimize the text and instead have finished code with comments that you can just copy and paste. Some of these problems you have solve in a rush. When I competed in the Ludum Dare competition, where the idea is to make a game in 48 hours, I needed to know if two line segments are intersecting with each other. But I couldn't solve the problem fast enough so I had to come up with another idea, which took some extra time and thus made the final game worse.