# Question
Title: Is it a legal concern if a procedural name generator might generate the names of real people?
*(This question is similar in spirit to this question, but I think this case is sufficiently different and specific enough to warrant a new question.)*

## Background

In one of my current side projects, I have a little procedural name generation system for NPCs. Its purpose is akin to the random profiler in Watch\_Dogs and the way it procedurally generates little NPC identities and blurbs to flesh out the game world, in that the system exists to spit out some generic NPC identities and give bits of information about them. Which can sometimes give very funny results, in Watch\_Dogs's case.

The procedural system in my project is fairly basic, and it generates:

1. a random **first name**, taken from a list of the most common baby names in North America. (i.e. Anna, Nancy George, William, etc.)
2. a random **last name**, taken from a list of the most common surnames in North America. (i.e. Rogers, Smith, Walker, Brown, etc.)

As a result of this dataset, the generator typically spits out generic names like "John Smith" and "Marcy Walker," which is what I wanted it to do and it works as intended.

## The question

In the process of testing, I have noticed something about this generation system: because it is specifically designed to generate normal-sounding names that could plausibly exist, **it can inadvertently generate the names of real, famous people.** For example, it has the potential to spit out "Chris Pine," "Will Smith," "Tom Hanks," and probably a few others, simply because it pulls from lists of common names and could plausibly stumble across and combine those options. From a player's point of view, it would probably be a little surprising to stumble across an NPC named Tom Hanks just wandering around the world.

This leads me to my question: If I were to ever release this game commercially, **is it possibly going to be a legal concern if a procedural name generator sometimes inadvertently spits out the names of famous, real people? Are there other potential ways this could be a problem from a game design standpoint?** Would it count as some kind of unauthorized-use-of-identity issue? And, if so, should I program in some "blacklists" of names that the procedural generator should avoid spitting out, i.e. by giving it lists of celebrity names to avoid?

# Answer
> 3 votes
I doubt it; just the name isn't enough if you're not copying the character.

I am not a lawyer. Check with a lawyer. They will tell you. Sometimes, even if it's legal, a determined company can make your life hell by suing.

As MaximusMinimus says, "This is a work of fiction. Any similarity to actual persons, living or dead, or actual events, is purely coincidental" is a common disclaimer, and "Someone on the internet said it was OK" will not hold up in court.

---
Tags: procedural-generation, legal
---


# Question
Title: Why do computer graphics applications use piecewise polynomial curves of degree 3 rather than curves of higher-order, say degree 100?
just wondering why is that? can't get my head around it. wouldn't the use of degree 100 be better? I'm really new to this stuff.

# Answer
the higher the degree the more parameters you have to tweak. For example for a 100 point bezier curve there are 100 points to tweak and each point affects *every* part of the *entire* bezier curve, a piecewise curve lets you localize any tweaks you want to make.

The higher degree the more intricate the calculations, degree 100 in a polynomial equation means you need to raise a number to the 100th power. This can lead to numeric instability or those terms are meaningless anyway.

A cubic polynomial has enough flexibility to give you a curve match on transitions between adjoining curve. This is good enough that you can hide the transition between subsequent bits in.
> 5 votes

# Answer
You use whatever fits the job.

If you need code to do arbitrary degree in term of Bézier curves, here it is:

```
// https://stackoverflow.com/questions/785097/how-do-i-implement-a-bézier-curve-in-c
vector_4 getBezierPoint(vector<vector_4> points, float t)
{
    size_t i = points.size() - 1;

    while (i > 0)
    {
        for (size_t k = 0; k < i; k++)
        {
            points[k].x += t * (points[k + 1].x - points[k].x);
            points[k].y += t * (points[k + 1].y - points[k].y);
            points[k].z += t * (points[k + 1].z - points[k].z);
            points[k].w += t * (points[k + 1].w - points[k].w);
        }

        i--;
    }

    return points[0];
}

```
> 0 votes

---
Tags: graphics, curves, beziers, splines
---


# Question
Title: OpenGL draw functions and multi-threading. How they work together?
I want to apply multi-thread in a simple way to control and draw 4000 objects. I am using SDL and OpenGL.

control : locations, collisions, calculations ... etc

draw : OpenGL draw functions glDrawArrays,glDrawElements etc

For 4000 objects i think like this:

do you think it works ?

# Answer
It is definitely possible and useful to make your rendering multithreaded, but it wouldn't work the way you've proposed. Keep in mind that with OpenGL, you're drawing all the objects for a frame into the same context. If you have 2 threads changing state in the same context at the same time, things are going to get very confused. So you have to be very careful with your threads.

Another way to architect this would be to have 3 threads and 3 contexts in the same share group. It would work something like this:

```
thread | t = 1             | t = 2             | t = 3             | t = 4            |
1      | calc pos. @ t = 1 | draw @ t = 1      | calc pos. @ t = 3 | draw @ t = 3     |
2      | idle              | calc pos. @ t = 2 | draw @ t = 2      | calc pos @ t =  4|
3      | idle              | idle              | disp. frame 1     | disp. frame 2    |

```

And so on. So thread 1 calculates all objects positions at time t = 1. Threads 2 and 3 are initially idle.

At time t = 2, thread 1 draws all 4,000 objects into a texture-backed FBO in context A. Meanwhile, thread 2 starts calculating the objects positions at time t = 2. Thread 3 is still idle.

At time t = 3, thread one starts calculating the positions of the objects at time t = 3. Thread two meanwhile is drawing the objects at their positions from t = 2 into a different texture-backed FBO in context B. Now thread 3 kicks in and simply blits the frame 1 texture to the screen.

As you probably figured, at time t = 4, thread 1 draws the objects from their positions at t = 3. Thread 2 calculates the objects positions for t = 4. Thread 3 blits the frame 2 texture to screen.

This way, any given context is only drawn to on a single thread. Threads alternate whether they are calculating object positions or drawing objects. One thread is dedicated to just drawing the frames to the screen.

Note that you will need some sort of synchronization primitive to ensure that things happen in order and not before parts are ready. Something like a semaphore would probably work well. So thread 2 would wait on a semaphore before starting to calculate frame 2's positions. When thread 1 finished calculating frame 1's objects' positions, it would signal the semaphore so thread 2 could start the calculations for frame 2. You could do the same thing for drawing and blitting.
> 3 votes

# Answer
The most important feature is response time to user interaction. The render engine must scale well with increasing number of visible objects. The best way to solve this issue is to use progressive rendering instead of multi-threaded rendering. Progressive rendering renders all objects across several consequent frames instead of trying to complete everything in just one frame. Each next frame increases the amount of detail in distance from the viewer. There is only one OpenGL render thread with this approach. This OpenGL thread can be the same as the main GUI thread.
> 0 votes

---
Tags: opengl, sdl, multithreading
---


# Question
Title: From a game design point of view, what are the implications of using realistic distances in an open world map?
I'm starting an open world game and the plan is to have a single "open world" map that should contain a medieval citadel (1.4 km/2 - taking as example Palmanova in Italy) and some countryside around it.

The plan is to delimit the map with a river and some hills.

What I realized so far is that most open-world games take a specific approach when it comes to size their areas, it's unlikely you'll ever find a realistically sized citadel, they will tend to be all pretty small, and it will take no more than a few minutes to run from one side to the other of it.

An example that comes to mind is The Witcher 3, the Novigrad/Velen map is 15.2 km2 but the city is approx 0.25km2, which is a lot smaller than what I plan to build for my map.

To walk from one side to the other of my citadel the player should take around 15 minutes (according to Google Maps), while, as I said, in most games you can run through a city in a matter of 1 or 2 minutes.

Keep in mind there will be no vehicles and I'd still like to have the countryside take most of the map area to keep everything proportioned and realistic.

The question is, is it a good idea to build such a "large" citadel? What gameplay issues could I face? How should I handle the fact that the countryside will end up being extremely huge (and empty?) if I want to keep it properly proportioned with the citadel?

# Answer
Almost no game uses realistically scaled maps for cities. The problem with creating cities which are even close to the size of real cities is:

* Maps become difficult for the player to navigate. They can easily get lost.
* It is very hard to make all of that content interesting. Creating a large amount of good content is time-consuming and draining. So when you want to create a huge city while you are on a budget, you have to cut a lot of corners. That means resorting to lots of copy&paste environments and procedural generation. The result will be a game which is "as wide as an ocean, but as shallow as a puddle". Lots of environment to explore, but it takes too long to find anything interesting in it.
* Maps take a very long time to traverse. Traversal might be interesting if it happens in a new and interesting environment (see last point), but when it happens in an environment the player has already explored, or which isn't that interesting to explore in the first place, then it turns into a tedious chore. The player will wish that points of interest were closer together, so they can spend less time walking and more time enjoying actual gameplay.
* And then there are of course technological challenges. Having all that data for a seamless city without loading screens requires advanced techniques for rendering and simulation. The larger the world, the deeper you have to reach into your bag of tricks to make sure you stay within the resource constraints of your target platform.

And no, Unreal Engine 5 with its new automatic LOD system and world partitioning will *not* magically solve all your problems. When you use them in practice, you will see that they do have limitations, problems and quirks of their own you need to work around. In the worst case, you might find out that they aren't suitable for the unique technical challenges you face in your game and you will have to roll your own solution anyway. Also, LOD and environment loading are just two problems of many. There will still be plenty of your own systems which you need to adapt to work despite constant loading and unloading of world content and which are going to run into resource constraints when you try to simulate them in the whole world at once.

In conclusion: **Quality is more important than quantity!** It's better to have a smaller game world which is tightly packed with creative, unique and interesting content than a larger game world which is boring and bland.

I am looking forward to exploring the world of your game.
> 36 votes

# Answer
You've already removed the main negative of a 1:1 scale map by focusing it on a small area instead of an entire city or countryside, but a citadel is still on the large side. The biggest issue here is travel time. Basically, if I want to walk to the store in real life, it might take me 12 minutes (from Google maps). That's alright; a little longer than I might like, but only because I'm carrying groceries. In a game, if I get a quest to go to the store, and it's going to take 12 minutes just to get there, that's completely unacceptable. Games shouldn't waste the player's time getting to the gameplay.

So, here's how to cheat. Aside from the obvious solution of changing the scale, you can also change the walking/running speed, have rapid transportation options, cluster useful locations together, and not have quests that require the player to cross the map. For a citadel, I'd make large portions of it simply not relevant to gameplay. (A lot of the north-east portion burned down in a fire and hasn't been rebuilt. The south-east portion is gated mansions that are only accessible in one quest where you don't get to explore, etc.) I would also make a citadel that's significantly below average in size. (This is different from changing the scale in that it's still 1:1 scale, just using a smaller space as a base.)
> 8 votes

# Answer
## It works if you treat most of the citadel as part of your world map

I remember an MMO I played a while back (can't remember which one) that got away with this just fine because about half the quests were actually inside the main city. So instead of a small city that you are constantly leaving and coming back to; the city itself was the quest space, and only small sections of the city were clusters of shops that made up elements of the game you would traditionally define as "the city" from a gameplay perspective.

The city was divided up into 3-4 sections; so, as a low level you would be in the residential section using a cluster of mom-and-pop stores as your home base area and going off to do quests taking down gangs and breaking into someone's home to steal something, etc. in all of the surrounding areas of the city. Then as you got higher level you would move on to the docks section of the city where there was a better small cluster of businesses, and tougher missions; so, on and so forth. This was basically the same experience as moving to a new home city you often find in games. From what I recall, you did not actually have very many quests outside of the city until you were about a lvl 20; so, while the city was the size of the world maps used in some games, it was okay because the city itself was treated as a the world map.

So taking 15 minute to walk from one side of the citadel to the other is not a deal breaker at all as long as you have enough things to do along the way. As long as you are never spending more than 1-2 minutes to get from one Point of Interest to the next, how big the citadel is is not important.
> 2 votes

# Answer
I don't think most players really think in forms of scale when traversing a world. It's more about interesting stuff relative to times spend.

If your player has to run for 2 minutes between to interesting points, they'll be bored for 2 minutes. The world may feel vast, but the boredom will make this a negative.

So, how can you work around that?

* You could make your game about free-running or other traversal. Make the getting from A to B a challenge. The better the player is the faster he gets there, or the more points he collects on the way.
* Spread smaller points of interest in between those points. Collectathons are an entire genre build upon the idea of spreading small things to collect between actual interesting points. But you're not limited to collectibles. It could also be NPCs to talk with, or enemies to fight.
* Fast travel. If you don't want vehicles you could just have the player select the point of interest on a map and teleport him there. But then you have to ask yourself how the player unlocks the fast travel points. Get there once? Gets it from a quest? Scanning/binoculars minigame? A good fast travel system completely negates the need for a city between the points, though.

But those don't really solve your issue, I think. You should not do something in a game because "it's realistic". If players want realism they don't play games. Instead you should think about what purpose a vast region serves the player/gameplay.

* Are there animals roaming the area to hunt?
* Are there treasures hidden?
* Is it a big sandbox with NPCs the player can interact with, and/or quests take place?
* Houses to rob?
* Are there some sick ramps and rails to skate on?
* Is the player a giant robot and the city will have some really nice effects when he tumbles through it fighting a Kaiju?
> 1 votes

# Answer
When you start modelling, is easy to think that using realistic distances to normalize your world with will be awesome! However the first problem comes with the insane amount of detail real life has, and then, how boring moving in real life really is. Maybe the reason why people play games, instead of going "out there"?

However, when you are making your own world, you usually change the scale to somewhat that makes sense. For me, that happened to be 3.5 M as the minimal sphere, streets are 14 M, including 2 lanes, and opposite sidewalks. This kind of dimensions "make sense" when you look through the game camera...

The other thing you need to keep in mind is to minimize the max distance at which opposite objects can be. You calculate this with the mesh density: if too high, FPS will take a dive down, if its too low, the content may be a little stale.

But the most important is: you put what you need in your Citadel, and if you don't need it, you don't put it. Maybe there is no direct path between one side of the Citadel to the other? Perhaps you need to choose going into the Market, which will add ten minutes to traverse? Or maybe the other route is through the mud pit, which may present you with a terminal encounter of the wrong kind?
> 0 votes

# Answer
Another point that I don't see in any of the answers: in some engines you will start to run into numerical precision issues when using very large maps.

For example, the Unity engine uses the 32-bit `float` type for all floating-point engine functions, such as position. At large distances from the world origin, the precision limitations of a 32-bit float start to cause glitches such as jittery movement. I've also seen some visual effects (e.g. ambient occlusion) glitch out at similar distances.

The Unity Editor displays a precision warning when any object is further than 100km from the world origin on any axis. This means that the maximum safe playable area is `200km x 200km = 40,000km`. That's much bigger than what you'd find in a typical first-person or third-person game, but can potentially be an issue in endless open-world games (e.g. Minecraft), flight simulators, naval simulations, etc.
> 0 votes

# Answer
GTA, Cyberpunk and other similar open world games have city maps of mostly correct scale. MSFS has a kind of realistic world map. The key - these games didn't require devs to build every single house and players to walk all those distances.

For travel, first option would be to limit players to certain zones, making full map size irrelevant. While this is a huge citadel, you are in outer ring of defenses in chapters 1 and 2, travelling around in a circle or something, trying to get suitable clothes to be allowed inside. Then you get nice clothes and reach inner parts ... but all your newfound wealth makes you a target in outer areas. There is still a long 10 minute walk from one side to the other but you would do that walk just once - while you are fleeing the citadel after killing the noble, rest of the time would be spent in smaller areas you can traverse easily.

To keep world open and especially when you get to the countryside you might want to ditch the "no vehicles" policy and use carriages, magic portals/maps and similar that get you from point A to point B (nearly) instantly. This takes out some exploring, but you might give players these options only later to preserve initial mystery yet not bore them to death in later stages of the game. For example they might require suitable clothes to get in a carriage - initial beggar won't be allowed to ride one. Or they need to find the magic map, or the wizards created/allowed magic portals later. Or whatever else fits.

As for countryside, it will be and it should be boring if you are making something realistic. Yeah, this is an endless field of wheat, what else would it be? From inside the citadel it would look like uniform "field" texture with "forest" texture in the next part etc - as if you were building a view from citadel that doesn't let you walk in those fields. While players could explore these fields and forests in detail, few would. A quest or two along "interrogate farmer", "catch that wolf", "fight bandits that blocked the road through the forest" or "notice path through the field and investigate where does it lead" are mostly all things you would realistically do there. You obviously need to get to those quests by faster means than walking for an hour to reach the bandit ambush in the forest.

Even if 95%+ of the map is "boring areas", this isn't a problem by itself. Our real maps are mostly "boring areas" too. Just make sure that you don't require players to spend any significant amount of time there, and don't spend any significant amount of time on them yourself either. As a simple rule, amount of time you spend building an area should be proportional to player time spent in an area. But this doesn't restrict size of the area.
> -1 votes

---
Tags: game-design, maps, scale
---


# Question
Title: Designing MMORPG with secret quests that can remain secret for a while
First of all, I know how difficult it is to design and build MMORPG game. I do not plan to do it anytime soon, this is more of an exercise to stretch my design muscles. Just a thought experiment exploring how this game mechanic could be implemented. It's not about why it's good/bad idea or why it can't work, but about how to go about implementing it.

Imagine your run of the mill MMO a'la WoW. They have a ton of quests and even more guides on how to find them, how to finish them, what's the loot and all the stuff. I would like to introduce secret quests that function pretty much in same way as normal quests do, with the exception that you can't see them highlighted in any way and you need to do specific action/talk to specific NPC at specific place/time or something along those lines to to trigger them. Let's forgo for a moment if this is good idea from gameplay point of view, I am more interested in knowing if it is possible to keep them secret so that first few people who find them won't run to internet and tell everybody and their grandpa and ruin the experience for everybody else.

I came up with only two solutions so far and neither is good or feasible.

**First**, the bad one, is to randomly disable/enable them so even if somebody hears about them, they won't be likely to find it doing same steps. This has a huge downside of frustrating players and doesn't really fulfil secret-ness requirement.

**Second**, complicated one. Generate tons of one-time quests (or limit how many people can get it to some very small number (dozens, perhaps)), with reasonably random triggers. This has boatload of difficulties (making sure they are interesting, completable, and rewards are intriguing) and probably impossible to do in a way that wouldn't look broken very quickly. On the other hand, it would do exactly what I want it to do.

I have my experience with designing games, so I have an idea about how things work, what players want and what makes them come back and have fun. The idea might be bad from this point of view, but I find it very intriguing and worth investigating bit further. What I am looking for is some out of the box ideas how to deliver sense of great reward when finding such secret quest but not make it frustrating to people that don't find them

# Answer
I'd propose a very easy solution.

**Hierarchical Quest Requirements**

Basically, your quest prerequisites are:

* A state/states the player has to be in ( 10000 reputation with PotatoCows + 10 quests finished for Banshees )
* A set of actions the player has to finish ( Kill Goblin Queen, Save Evil Brother and baptize him )

Let's classify actions using tags. The approach is dead simple:

* Kill Goblin Queen -\> *KilledGoblinQueen*
* SavePrincess -\> *SavedPrincess*

The tags approach will be very useful to visualize the idea but is by no means necessary to implement it.

So tags are basically the state of the player and very importantly - they're **hidden information**.

Now comes the fun part:

> Quests can have tag prerequisites.

*So to get a high-profile quest - you would have several tag prerequisites in addition to your previous set of requirements.*

This is actually the lowest level. To further add depth to the system - you can have **those high-profile quests** give you tags.

Once you have several layers of tags ( again - **hidden information** ) - it will be very hard for players to backtrack what precise set of actions lead to the **epic quest**.

To further make the quests harder to actually get - you can use an unorthodox combination of tags ( it can very much still make sense ).

An example of that would be:

* You help a girl collect flowers, then save a from a wolf
* You help the king find a scholar to help tutor his son
* **Hidden information**: *the scholar helps the king identify the girl as his daughter*

> Those actually unlock a quest to save the princess from the dragon.

Now once you have the model for such a quest you have two things to do:

* Create a multitude of those quests
* Create many scattered relationships in-between
* Layer the quests into several layers of requirements

The more layers you add - the more hidden information for the players that find the quest to reverse-engineer.

The good thing is that if players start finding the way to your best quests - you can easily add an extra layer or two to the whole hierarchy for your new secret quests and exponentially increase the difficulty by doing so.
> 12 votes

# Answer
If it's not random, and there are no prerequisites, then it's going to be found and posted on a wiki.

The only other option I can think of it is to make it a one-time occurrence per account, and make the prerequisites complex enough that you don't necessarily know how you caused it to happen, but easy enough that once the full requirements are discovered everyone can participate. I have seen this approach work well with other games to keep something a secret for awhile (enough to build up hype about the quest) without frustrating people with RNG or some other type of artificial difficulty that prevents them from participating.

For example: A certain NPC, at a certain time of day, with a certain combination of items in your inventory (maybe weird or useless items that people would normally sell, but are easy to acquire), or while wearing a certain piece of low-level equipment that most people wouldn't wear all the time.

This will make it fairly difficult for one person to determine exactly what caused it, but the community can work together to figure it out. Once the do, everyone who reads that wiki/forum will have easy access, and can excitedly share the "secret" with their friends.

**Example** There is a game I used to play that had a crafting system where the recipes were unknown. Because of the server-client nature of the game, it wasn't possible to decompile anything to retrieve them, a la Minecraft. Instead, the developers would elude to a new recipe, and often tell the players what could be crafted, but not which ingredients were required, or how many of each ingredient (e.g. 3 A, 15 B, 1000 C, 1 D). Sometimes they would give hints, or ingredients and counts could be deduced based on previously discovered recipes. Crafting weapons might always require 1 D, but different weapons required 500-2000 C.

Usually the community would brute force and find the recipe fairly quickly, within a few days. They would work together to create spreadsheets of what was tried, so that the brute forcing could be distributing among players who wished to contribute. If the community struggled for too long, the developers would offer hints (e.g. "you need a few A, 15 B, and whole lot of C"). Once a recipe was discovered, it would be shared on the wiki and everyone in the game would have access to craft the new item (assuming they had the ingredients). This was a great way to get people who were interested to work together for a few hours or few days every time a new recipe was released, without frustrating anyone who wasn't interested in this aspect of the game in the long term.
> 2 votes

# Answer
You could make a AI that starts events based on their surroundings. Maybe two npc's that meet at a point and start figthing and the player can choose to help one. The npc species could then increase/decrease their trust in the player and unlock hidden quests.

This way players also get an unique expiriance.

I wouldn't trigger quests just random, but let the decisions of AI's add a more dynamic game play.

You could do that also with oter states like weather to trigger events.

**Example:** A little girl goes out to play with a boy around 12.00 - 16.00 if it's parrents allow it and the boy is outside. If its raining a beast spawns in the region and sees the girl and kidnap her. The player could help the parrents to find the girl.

In this example we have 4 states that have to be true for this event to happen.

And the player has multiple ways to approach this event but the outcome will mostly be the same and the player has to figure the solution at his own/with friends out.
> 2 votes

# Answer
I would approach this question with the following thought processes.

* Objective
* Restrictions
* Ingredients

tl;dr, Scroll all the way to the bottom for my idea

---

**Objective**

What is your primary objective in implemeting this feature? I can think of a couple.

1. To provide a difficult puzzle that induce a collaborative effort by the community to solve.
2. To create an experience that forces the player to figure it out by themselves
3. To create a sense of achievement for the player that completed this mission

There are probably many other reasons for creating this feature (You can give me them and I will elaborate on them). Addressing these 3, I shall give some reference titles.

**Difficult puzzle to be solved by the community**

There are many games you can reference for this.

* Fez - Red Cube puzzles
* Mu Complex - Website Puzzle
* Call of Duty - Zombie survival easter eggs
* In general, any game's easter eggs

This motivation would be to create a puzzle that is very difficult for the individual to solve. It would give the creator a feeling of amazement as you watch the community as a whole, work together at a common goal.

**Forcing the player to figure out on his own**

This might be a bad idea. Not everyone like solving difficult puzzles and some may get stuck. Knowledge of this might deter players from starting the game, knowing they may not get the full experience as one will **have** to figure it out on his own. To that end, I cannot give any titles that has fully implemented this feature.

The only way to *force* the player to figure out on his own without ANY possibility of tutorials would only be to randomize the quest. This would be equivalent to gambling where one may have the chance to get an easy success where others may have a hard time figuring it out. Writing narrative for such quests would also be dreadful.

**Giving the player a sense of achievement**

This is very well established motivation for creating such a feature. In order to encourage players to obscure the contents of this quest, the full glory of finishing this quest must be felt by the player. (Note this is only *Encouraging* the player to not reveal it. Some players will reveal it anyways)

One VERY good example I can give is NotPron. This game clearly states on its front page the following information

The clear motivation here is that if you are able to finish the full game, you are part of the 0.0001% that persevered till the very end. This motivation is a strong one in a psychological standpoint. To be exclusive, the only few to hold this glory. Sharing on the solutions will negate this glory.

You can most definitely find tutorials on the game online. But never full tutorials. The level changes minutely periodically but the core concept of each level never change. This means that if you understand the puzzle, a changed solution will never stop you.

---

**Restrictions**

This is your limitations. This means that any solutions you think of must still fit the game genre's intended objective. In the case of MMORPGs, that would be teamwork and fairness as well as not alienating the game community that comprises the "Life" of your game.

* You cannot randomize the quest fully as some may get an easier quest than others.
* You cannot make it that solution is unique to everyone story dependent as that would make narrative writing for the game setting extremely difficult.
* You have to balance the reward of the quest such that any that finishes it is satisfied without making those that are not able to finish it feel cheated or inferior.
* You still have to encourage teamwork as this is an "MMORPG"

---

**Ingredients**

This would be what you can do. Fun fact: I actually had some of these ideas while writing this post. Compile a list of what you can work with and then work from there

* Randomization
* Team effort
* Faction based objective
* Manual Alterations
* Quest Ingredients - (Go to, speak to, kill, binary decisions, etc)

---

**My take at this issue**

How I would implement this would be as follows.

* Divide my players into factions
* Create a monthly/quaterly bonus that serves as the motivation
* Segregate the community into their individual factions - Make them unable to talk to each other ingame
* Make them understand that allowing the other faction to achieve this objective would serve them no good.
* Write a unique narrative monthly/quaterly for this unique ***Grand Quest***

Other ideas (May not be feasable)

* Each faction can region quests that would give a small piece of the puzzle (Quest item perhaps?).
* Every player can contribute to the faction results.
* Create the tools for accomplishing this feature (This can be an out of game website where players can work together to solve the puzzle and unlock something ingame)

This quest would then be collaboratively solved by the community of each faction. By doing a faction quest, you encourage collaboration while still maintain a sense of competition. By changing the quest only when its completed, you cut down on the strain on your writers.

---

**Additional Info**

Addressing the further info in the comments, you might want to refer to the implmentation of quests in Dark Souls.

A summary:

* Quest can be completely Narrative Driven. This means no quest objective markers, no quest tracker, no guidance whatsoever. The quest can start without the player knowing, and end without the player knowing.
* Quest can have a failure state. This would be the default state for reaching the quest "End" without completing the preqrequisites. This might not be as good for an MMORPG.
* Rewards can be integrated into the narrative like as it is supposed to be given the player. Make the player not realise its part of a quest.

If the player doesnt know its a quest, there there will be no tutorial to speak of. Though guides may still cover it and someone will realise that not everyone gets it.
> 2 votes

# Answer
If your goal is to make them very well hidden, not just something at the end of a long chain, make them not appear in a quest log and require solving some obscure puzzle. For added difficulty, spread out the objectives around the world so that they are unlikely to be completed by accident.

For example, enemies in a certain zone could drop a piece of paper with a riddle on it. It's classified as junk so most players will just vendor it, but if one takes the time to puzzle it out, they find that it leads to a chest behind some ruins in the corner of another zone. This then kicks of the rest of the quest, etc.

This also reminds me of a recent hidden quest in WoW that still only took players about two weeks. So I suppose your success at keeping it hidden depends on how many players you have and how dedicated they are, in addition to how obscure you make it.
> 0 votes

# Answer
This is just a short answer and a possible recommendation, but you can make it so the player also has to have a minimum amount of affinity with specific npc’s. For example, let’s say the minimum amount of affinity required with the cleric, bridesmaids, little girl, king, and librarian(assuming it is not extremely easy to raise and the maximum affinity is 100) is 50 for the cleric, 40 for the bridesmaids, 75 for the little girl, 90 with the king, and 60 for the librarian . These all have to be met and so if one minimum requirement is not met, then the player won’t be able to do the quest. This will make it very difficult to spread how to get the hidden class as they probably won’t remember their original affinities with all these people. It can also rise with some so like the cleric could be at 70 and king at 95, girl at 84, etc. It would become theoretically impossible to track these values on top of completing specific tasks and quests. Well only impossible if you include maximum affinities as well.
> 0 votes

---
Tags: game-design, mmo
---


# Question
Title: How is this lantern glow effect achieved?
I was wondering if anyone knows how this lighting effect is achieved. It's clearly not a bloom shader. My best guess right now is that it's a billboarded transparent sprite, which is animated to give it a pulsing effect. I'm pretty sure the visual effect is separate from the surrounding point light. If anyone could positively identify the technique that's being used, I'd appreciate it.

# Answer
> 11 votes
> My best guess right now is that it's a billboarded transparent sprite, which is animated to give it a pulsing effect.

Exactly that. This is simple enough even for older hardware. There's also some kind of point light involved, but the light could also be baked into a light map. So with this combination you won't even need any extra shaders.

---
Tags: rendering, directx, lighting
---


# Question
Title: How would I incorporate gravity and gravity affecting obstacles into A* pathfinding in a 2d side-scrolling game?
I want to be able to modify the A\* pathfinding in a way that I can get my NPC from his current position to any point that's within reach. The tricky part is that this takes place in a side-scrolling world where gravity is an issue. There's workarounds to that. My goal is to not only make the pathfinding clean, but be able to add other obstacles and movement aiding objects like jump pads.

In that image I have my NPC and his target position. Between them is a jump pad. When stepping on a jump pad, it launches him into the air high enough to reach his goal. This is what it looks like with a relatively unmodified A\* script:

and that's how it should look. But that's just lucky jump pad placement. The NPC doesn't perceive it in any way. Here it looks a lot different just by having the starting position changed:

what I'm trying to do is have a way for the NPC to recognize that the jump pad will take him to his target. Or on the other hand:

What if the best way to get up there is a different jump pad on the opposite side?

Or if the best way is to go down then back up

and would it be any more difficult to add them back to back?

I watched the brackey's video so I know about making a "custom" A\* script. I just can't find anywhere how I'd introduce both gravity to it, and my jump pads. Any help is MASSIVELY appreciated.

# Answer
A\* is very smart but also very dumb. It is a graph search algorithm; that means that A\* assumes that any two connected points in the graph are reachable without checking back into the game itself to verify your NPC could reach any of those points. It will just search through connected points in the graph to find the most efficient path between them. It seems like your path-finding script is using the wrong type of graph to represent the places your NPC can reach. Imagine this was a top-down game where your NPC could move up, down, left, and right all the same. The green path would be totally acceptable in that case and the blue path would be very, very far out of the way.

There are a couple of things you can do here.

# Create a Navmesh

You need to see what A\* sees; find a way to display the graph it searches through and you will see the problem right away; then you can alter that graph so it more naturally represents what your NPC can do. By fixing the input, you will fix the output. Thus, i would recommend you explicitly create a navmesh that naturally represents the places your NPC sprite can move between and how it moves between them (by hand or by algorithm); it might look like this:

The different connection colors represent different types of movement (jumping versus just walking for example). Generating a navmesh can be pretty hard, but there are lots of resources that should get you started. Once you have your navmesh, getting your NPC to the goal would probably look something like this:

1. Request a path from your pathserver/a\* search
2. Iterate through the waypoints on the path
    1. Depending on the type of connection between the waypoints, take a certain action: I.E. walk, jump, or use a door or object
    2. once the action is complete, advance to the next waypoint
3. Arrive at the goal

# Treat your NPC like a robot

Note, this is usually not a good approach for games, I'm just including it to hopefully help you understand why a navmesh is useful.

Suppose your NPC was a robot: it would probably have a set of `controls`. The controls would be something like:

1. Walk with velocity `x`
2. Jump with velocity `x,y`

Your NPC would also have a `state`. That state could be:

1. Position `x,y`
2. Energy `e`

If you applied a `control` to a `state`, you would get a new `state`, perhaps with a different energy and position.

You want to plan in terms of these *controls* instead of the *states* those controls result in, which is the source of the disconnect you have in your game currently. You can modify the A\* algorithm to accomplish this surprisingly easily: when you expand the children of your current node, instead of finding the neighbor nodes, you sample a set of `controls`, resolve each of those `controls` into new child `states`, and then proceed as usual with your A\* algorithm. You can find an example of this approach that I implemented here.

The point of a navmesh is to encode this sort information directly into the graph so it can be computed exactly once. However, if you have a sufficiently complicated model for your NPC, you might need to explore robotics approaches like the one described here.
> 2 votes

---
Tags: unity, c#, 2d, path-finding, side-scroller
---


title: Trigger Button with specific key only

text:
# Question
Title: Trigger Button with specific key only
I am having trouble understanding how to trigger a UI button with a specific joystick key only.

Currently i have a pause menu in which i have several buttons. By pressing start i set the game time scale to 0 and activate the menu using this:

```
void Update()
    {
        if (Input.GetButtonDown("Submit"))
        {
            ResumeStartButton();
        }
    }

public void ResumeStartButton()
    {
        isPaused = !isPaused;
        if (isPaused)
        {
            pausePanel.SetActive(true);
            Time.timeScale = 0f;
            usingPausePanel = true;
            player.SetActive(false);
        }
        else
        {
            pausePanel.SetActive(false);
            Debug.Log("Resume game with start button");
            Time.timeScale = 1f;
            usingPausePanel = false;
            player.SetActive(true);
        }

    }

```

Once the menu is active, i can navigate through the buttons with the joystick, however the buttons respond only to the "Submit" button i defined earlier.

I tried using this function:

```
public void Resume()
    {
        if (Input.GetButtonDown("MenuSelect_A"))
        {
                isPaused = !isPaused;
            if (isPaused)
            {
                pausePanel.SetActive(true);
                Time.timeScale = 0f;
                usingPausePanel = true;
                player.SetActive(false);
            }
            else
            {
                pausePanel.SetActive(false);
                Debug.Log("Resume game");
                Time.timeScale = 1f;
                usingPausePanel = false;
                player.SetActive(true);
            }
        }

    }

```

And call it using an OnClick event on the editor, however it does not work. I have also tried to use onClick on the script directly by creating `resumeButton.onClick.AddListener(Test)` and by using AddListener:

```
void Start()
    {
        isPaused = false;
        pausePanel.SetActive(false);
        inventoryPanel.SetActive(false);
        usingPausePanel = false;

        resumeButton.onClick.AddListener(Test);

    }

public void Test()
    {
        if (Input.GetButtonDown("MenuSelect_A"))
        {
            Debug.Log("Do something you donkey!");
        }
        else
        {
            Debug.Log("Wrong button");
        }
    }

```

However this does not work either: While the menu is active none of the messages appear and when i exit the menu using the start button only the second sentence, "Wrong button" appear.

Can somebody tell me what am i doing wrong? I think that there should be an easy way to solve this with OnClick events but i don't understand what precisely.

For information, I am using the old input manager. I was considering switching to the new system since my project is in still in its beginning.

Any tip will be appreciated!

# Answer
In the end I solved the problem by switching to the new Input System:

* I created a dedicated action map for the UI menus (the 'pauseMap') and one for the player control 'playerMap',
* Whenever I press the start button from the 'playerMap', it activates the menu and now the gamepad buttons are used to move through the menu and press buttons (then each button do its job with 'OnButtonClick' events),
* When I press the start button from the 'pauseMap' it disables the menu and switches back to 'playerMap'.
> 0 votes

---
Tags: unity, input, unity-ui, joystick
---


# Question
Title: How can I create a good physics colliders for these models in Unity3D
I need to make a 3D colliders in Unity with those forms. I don't want to use any Asset Store asset if it's possible. There are two models: both are cylinders but they have some deformations (see image below).

I need to make a collider of both cylinders but it needs to be accurate (I mean, the holes mustn't be in the collisions). As I said, I don't want to use any thing Asset Store if it's possible. So it have to ve with primitive shapes or with mesh colliders, that I can't get them to work propertly with my meshes.

Thanks.

# Answer
For shapes like this, I tend to use a series of box colliders. It may be easier to make a child box object that you can rotate and scale in to position, and then disable the rendering on these objects once you are happy with their placement.

You'll want to trace the outline with these boxes. The less boxes you can use the better. Look at the faces along the edge of your model and get as close as possible to the edges. Depending on your needs, you may not need to be 100% accurate with this.
> 1 votes

---
Tags: unity, collision-detection, 3d, mesh
---


# Question
Title: How to raycast down to the floor plane to determine world space coordinates in Godot
I've been trying to find a solution to this task and despite finding answers to similar issues, they were always somewhat overcomplicated (e.g. finding a position on a texture) or the problem was caused by something else and the solution didn't apply.

I'm working on a board game in 3D. As such, I need to frequently transform my viewport's mouse coordinates into world coordinates to move the pieces. Because the entire game happens on a plane, I'm not concerned with the Y axis - I just need to raycast from my camera, through the mouse cursor, onto the world plane and acquire the `(x, 0, z)` coordinates. I can't, however, rely on the board, as the game board itself is floating in a "void" and coordinates around the board should be detectable (and game-wise illegal).

I was unable to find a `Node` type to use as an infinite plane for ray collision.

The `Camera`'s `project_position ( Vector2 screen_point, float z_depth )` method doesn't seem to be a viable choice either, as my camera should be able to rotate around the board freely and not be locked in the top-down view (otherwise this method would be the perfect solution, to my understanding?).

I'm very new to game development and the techniques overall, any help and pointers how to best achieve the task are greatly appreciated!

# Answer
> 6 votes
I'm not sure I understand your limitations, so I will give you a few approaches, and hopefully this gets you to the solution along the way.

*This is not an exhaustive list.*

---

## Pickable Object

If you have a `CollisionObject` (e.g. the board), you can set `input_ray_pickable` to `true` on it.

Then connect the `input_event` signal or override the `_input_event` method, where you will get - among other parameters - the position in 3D of the pointer when it is over the 3D object.

---

## RayCast Node

If you can't - or rather not - depend on pickable objects, but still have something to collide with, you can use a `RayCast` node. To make it follow the pointer, you can do this:

```
var ray_length = 100 # some large number
var mouse_pos = get_viewport().get_mouse_position()
$RayCast.transform.origin = camera.project_ray_origin(mouse_pos)
$RayCast.cast_to = camera.project_ray_normal(mouse_pos) * ray_length
$RayCast.force_update_transform()
$RayCast.force_raycast_update()

```

Pay attention to `project_ray_origin` and `project_ray_normal`. Should give you the direction for the ray that goes toward the `mouse_pos`, given the camera projection and `Viewport` size. On the other hand, `project_ray_origin` should give you the origin for the ray, which is the position of the Camera *when the camera projection is perspective, but the method also supports orthogonal projection.*

Calling `force_update_transform` and `force_raycast_update` is only necessary if you are moving the `RayCast` multiple times in the same physics frame.

You would then check `$RayCast.is_colliding()` (which is a way to detect if the pointer is out of the board, for example), and read `get_collision_point` to get the position. You can also read `get_collider` which will give you the object the `RayCast` collided with (which you can check if it is the board).

Note: make sure the `RayCast` is enabled, it is disabled by default.

---

## Ray-plane intersection

If you want to intersect with an axis aligned plane instead of some object, we can handle it with some vector algebra.

We need to define our ray, and our plane.

For the ray part, the code is basically what we did for the `RayCast` node above:

```
var mouse_pos = get_viewport().get_mouse_position()
var origin = camera.project_ray_origin(mouse_pos)
var direction = camera.project_ray_normal(mouse_pos)

```

Conceptually, we define a parametric form of the ray like this:

```
origin + direction * distance

```

Where `distance` is the parameter. We can assume that `direction` is a unit vector (a vector of length one) so that `distance` gives you the length from `origin`.

The plane will be defined by an coordinate set to a constant, in this case `y = 0`.

We want to find a point along the ray, that satisfy that (`y = 0`). We can have a parametric form of the ray like this:

```
(origin + direction * distance).y = 0

```

That is:

```
origin.y + direction.y * distance = 0

```

Solve for `distance`:

```
distance = -origin.y/direction.y

```

Note that this code would be a division by zero when `direction.y = 0`. That is, if the ray is parallel to the plane (in which case there is no intersection), so you want to check for that.

With that, we can write the rest of the code:

```
if direction.y == 0:
    return

var distance = -origin.y/direction.y
var position = origin + direction * distance

```

And that `position` should be intersection with the `y = 0` plane.

**Addendum**: The intersection could be behind the camera (when the camera is looking away from the plane, for example the plane is below the camera and the camera is looking upwards), in which case the distance will be negative, you may want to check for that too.

---
Tags: raycasting, coordinates, godot
---


# Question
Title: Why is my OpenGL code not rendering anything?
I have been following the LearnOpenGL Hello Triangle tutorial, and nothing is rendering except the clear color.

Any help finding what is wrong would be appreciated.

Using LWJGL 3.2.3 OpenGL and GLFW bindings on MacOS.

My code:

```
// ---- WINDOW SETUP ----------------------------------
    glfwInit();

    glfwWindowHint(GLFW_VISIBLE, GLFW_FALSE);
    glfwWindowHint(GLFW_RESIZABLE, GLFW_FALSE);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GLFW_TRUE);

    long window = glfwCreateWindow(WIDTH, HEIGHT, TITLE, NULL, NULL);
    if (window == NULL) throw new IllegalStateException("Could not create window");

    glfwMakeContextCurrent(window);
    GL.createCapabilities();

    int[] fbWidth = new int[1];
    int[] fbHeight = new int[1];
    glfwGetFramebufferSize(window, fbWidth, fbHeight);
    glViewport(0, 0, fbWidth[0], fbHeight[0]);
    log.info("Framebuffer size: {} x {}", fbWidth[0], fbHeight[0]);

    glfwShowWindow(window);
    log.info("Created window");

    // ---- BUFFER SETUP ----------------------------------

    float[] vertices = {
            -0.5f, -0.5f, 0.0f,
             0.5f, -0.5f, 0.0f,
             0.0f,  0.5f, 0.0f
    };

    int vao = glGenBuffers();
    glBindVertexArray(vao);

    int vbo = glGenBuffers();
    glBindBuffer(GL_ARRAY_BUFFER, vbo);
    glBufferData(GL_ARRAY_BUFFER, vertices, GL_STATIC_DRAW);
    glVertexAttribPointer(0, 3, GL_FLOAT, false, 0, 0L);
    glEnableVertexAttribArray(0);

    glBindBuffer(GL_ARRAY_BUFFER, 0);

    glBindVertexArray(0);

    log.info("Created buffers");

    // ---- SHADER SETUP ----------------------------------

    String vertexShaderSource =
            "#version 330 core\n" +
            "layout(location = 0) in vec3 aPos;\n" +
            "void main() {\n" +
            "    gl_Position = vec4(aPos, 1.0);\n" +
            "}";
    String fragmentShaderSource =
            "#version 330 core\n" +
            "out vec4 fragColor;\n" +
            "void main() {\n" +
            "    fragColor = vec4(1.0f, 0.5f, 0.2f, 1.0f);\n" +
            "}";

    int vertexShader = glCreateShader(GL_VERTEX_SHADER);
    glShaderSource(vertexShader, vertexShaderSource);
    glCompileShader(vertexShader);
    if (glGetShaderi(vertexShader, GL_COMPILE_STATUS) == GL_FALSE) {
        log.error("Vertex shader compilation failed:");
        log.error(glGetShaderInfoLog(vertexShader));
        return;
    }

    int fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
    glShaderSource(fragmentShader, fragmentShaderSource);
    glCompileShader(fragmentShader);
    if (glGetShaderi(fragmentShader, GL_COMPILE_STATUS) == GLFW_FALSE) {
        log.error("Fragment shader compilation failed:");
        log.error(glGetShaderInfoLog(fragmentShader));
        return;
    }

    int shaderProgram = glCreateProgram();
    glAttachShader(shaderProgram, vertexShader);
    glAttachShader(shaderProgram, fragmentShader);
    glLinkProgram(shaderProgram);
    if (glGetProgrami(shaderProgram, GL_LINK_STATUS) == GL_FALSE) {
        log.error("Shader program linking failed:");
        log.error(glGetProgramInfoLog(shaderProgram));
        return;
    }

    glDeleteShader(vertexShader);
    glDeleteShader(fragmentShader);

    log.info("Loaded shaders");

    // ---- MAIN LOOP ------------------------------------

    while (!glfwWindowShouldClose(window)) {
        glClearColor(0.1f, 0.2f, 0.3f, 1.0f);
        glClear(GL_COLOR_BUFFER_BIT);

        glUseProgram(shaderProgram);

        glBindVertexArray(vao);
        glDrawArrays(GL_TRIANGLES, 0, 3);
        glBindVertexArray(0);

        glfwSwapBuffers(window);
        glfwPollEvents();
    }

    // ---- CLEANUP --------------------------------------

    glDeleteProgram(shaderProgram);
    glDeleteBuffers(vbo);
    glDeleteVertexArrays(vao);

    glfwDestroyWindow(window);
    glfwTerminate();

```

# Answer
```
int vao = glGenBuffers();
glBindVertexArray(vao);

```

This should be using glGenVertexArrays, not glGenBuffers.
> 1 votes

---
Tags: opengl, lwjgl, glfw
---


title: Lights beyond the fourth do not appear?

text:
# Question
Title: Lights beyond the fourth do not appear?
In my scene there are 6 point lights. But 2 of them do not illuminate my floor plane.

If I disable any of the working lights, then one of the non-working lights starts working.

It's like my level can't take more than 4 point lights? I'm using Unity's URP. How can I solve this?

# Answer
Let me tell you URP limitations:

* Main Directional Light 1
* Per Object: 8 (4 for GLES2). Can be point, spot, and directional Lights.
* Per Camera: 256 (32 on mobile platforms)

For more info: URP vs Build In Render Pipeline
> 1 votes

---
Tags: unity, lighting, unity-urp
---


# Question
Title: In game development, what aspects to consider when choosing a 32-bit architecture over a 64-bit architecture?
I was developing a graphics engine from scratch using Direct3D11 and some APIs, but I stumbled in a situation where it would beneficial to me to use a certain library, but it's binaries are only available on 32 bits.

I've changed my engine to 32 bits and didn't see much difference in terms of speed, would it be troublesome to use it on 32 bits? What other surprises lie around the corner?

# Answer
> 4 votes
The most obvious thing to consider is that using a 32-bit architecture for your executable allows you to address about ~4gb of RAM on Windows while using a 64-bit architecture allows the program to address 128gb+. This means that you can put much more stuff into RAM before experiencing issues.

A situation where this *could* **¤** be an issue is loading your 3d models and their textures into Video RAM. For instance, the machine's graphics card allows to load 8gb of data (the nVidia DLL will manage this just fine even using a 32-bit app), and you want to take advantage of it, so you'll create nice models with big, highly detailed textures, which will end up taking 6gb of memory.

With a 64-bit architecture, you would simply have to load everything into RAM, then have the graphics API load it into Video RAM. But with a 32-bit architecture, you'll need to cut down your loading process into smaller pieces: load a chunk of data into RAM, send it to VRAM, unload it from RAM, then repeat with the other chunks, until everything is done.

---

¤ Note that this will often depend on how you do things, what you need in your game, and how you've arranged your architecture; I used a framework where this was an issue: we loaded an image from disk into RAM, but there was no check telling us that memory couldn't be assigned, so the rest of the code tried to upload a "null" image into VRAM. We either had strange bugs, at strange places, or some parts of the models just appeared black.

---
Tags: c++, directx11, win32
---


title: Are there tilemaps without images?

text:
# Question
Title: Are there tilemaps without images?
I would like to use Tiled or a different editor to create a simple world (top-down). But I don't want to use any images. I just need colors to distinguish the different types of terrain.

What would be a good approach?

I thought about using Tiled and creating a Map with a tilesize of 1px. As Tiles I could use 1px by 1px big images containing just one color. But this feels odd and not nice.

# Answer
Tiled creates data unrelated to the image you use, so you can do what you want with the data created.

In the TMX format, tiles' positions are stored separately from the image associated with them. It's just an ID. You can retrieve this ID in your program independently from the image since they are not directly related.

So it doesn't change anything very relevant in your output file whether you use a tileset with a single color or a fancier tileset. It's just comfort for you when you create your map. All you need after is to identify the ID corresponding to each tile.
> 1 votes

---
Tags: tilemap, tiled
---


# Question
Title: In a puzzle game, how can we put pressure on the player without using a time limit?
We're currently working on a game inspired by "Keep Talking and Nobody Explodes" for the gameplay and "Lifeline" for the narrative part. Our game is named "Are You There?"; it's a game where you play an agent in a bunker who is the only person who can help an astronaut in her rocket.

In the first version linked above, we first added a timer during the alert phase for putting pressure on the player, and to reinforce the narrative way.

But we don't like timers in puzzle games :D. We found it artificial and counterproductive to ask to the player to "think fast" (even if our game is more a memory game than a puzzle game).

So here is our question: how can we put pressure on the player without using some kind of countdown (and which will fit with the narration)?

Our last hypothesis is to set up an "integrity gauge" for the rocket, which will decrease for every error. But, will it be enough to simulate gameplay and narrative pressure?

# Answer
There are a lot of tricks you can pull to create the impression of urgency without actually having a real urgency in your game mechanics.

## Writing and presentation

First of all, do not underestimate the power of a well-written and well-presented narrative. Just having NPCs state in a convincing manner that time is running out and the player needs to act fast can create a sense of urgency. It's not like the NPCs have to get specific about how much time there is *actually* left. "Please rescue me quickly" can imply anything between "Please rescue me within seconds" to "Please rescue me within weeks".

But keep in mind that urgency through narrative alone only works as long as there isn't too much ludonarrative dissonance! One example of ludonarrative dissonance in this case could be to offer the player less urgent sidequests and nobody calling them out for wasting their time with those instead of taking care of the more pressing matters.

Music, sound effects and visual effects can also enhance the sense of urgency by contributing to the atmosphere of the game.

## Giving the impression of a hidden time limit which does not actually exist

If writing and presentation alone are not enough to convey urgency, then there is another trick you can pull to give the player the impression that they are under a hidden time limit while they are actually not: Have scripted events conveying urgency which are triggered by the players progress. Like stuff "spontaneously" breaking on the ship as soon as the player reaches certain milestones in the current puzzle.

The trick is to not trigger those events immediately when reaching a certain milestone, but to do that with a delay of a few seconds. That way the player does not immediately realize that the event was connected to their actions. So the player will assume that the event was triggered by a hidden timer running all the time, and that this timer might trigger more bad stuff if they don't hurry up.

This works even better when said event isn't just cosmetic but actually has an effect on the current puzzle. That way the player will actually believe that they are now suffering from direct consequences of their tardiness, even though that event was going to happen anyway. So they are going to try to act faster in the future. This of course bears the risk that the player might end up sequence-breaking if they are too fast. So only do this when events which matter at the end of the puzzle, but do not affect the beginning. when you have an event which changes a puzzle in a way which starts to matter at stage 3 of said puzzle, start the timer after completing stage 1 but if it hasn't happened yet when completing stage 2, trigger it immediately.

## The number of options available to the player affect the perceived pacing of a scene

And then there is an entirely different trick I recently heard in the development commentary of the point&click adventure series *Deponia* and which I wholeheartedly agree with:

* If you want a slow scene where the player gets immersed in the world, analyzes the situation and thinks before they act, then give them a lot of options of what to do. Lots of places to go, lots of objects to interact with and multiple ways of interacting with them.
* If you want to have a fast scene with a sense of urgency where the player acts quickly and intuitively, then give the player very few things they can do, perhaps even just one. The player will think and act fast because there is not much for them to think about. This results in the player progressing as fast as the timing you wish to convey.

Note that this effect is most efficient when you regularly switch between the two. The complex scenes will feel more immersive and the simple scenes will feel more urgent. And these two different moods will also bleed into each other. The player will feel the need to act more analytical during the fast scenes and be more confident to act on their intuition during the slow scenes.
> 32 votes

# Answer
1. ***Time the overall game (or phase)***, a middle-ground and less intrusive than timing each turn. This is commonly done in e.g. room-escape games, text adventure games, puzzles. Your **final score is determined from a lookup table of 'time to complete', 'hints taken' and 'number of collaborative players' minus any penalties**. This reduces things from a hard 'time limit' to a soft time limit. Often scores are quoted as 0-5 stars or 0-20 points or whatever.

* this allows you to have 'soft' time penalties for doing the wrong action, setting off traps or alarms, wasting resources or time etc.
    * sometimes you graduate the hints as cryptic, hard, easy, spoonfeeding. Can assign different penalty for each
    * you could even have a soft reward: *"if you completed Phase (n-1) in \< X minutes, you get a clue/helper/object/money/ally/hint/headstart on Phase n"* Or just "go online to get some secret ending video/message/flair/badge/highscore board".
2. ***Audio and visual cues***, gradually get more urgent:

* the app companion for FUSE (2-5p real-time coop dice game about defusing bombs) has atmospheric music with audio cues about time ticking or passing, timer beeps, gradually increasing tempo and pitch, raised voices. Listen to it, it is very good.
    * the digital implementation of boardgame Pandemic has parallel 'doom tracks' of 0..8 *outbreaks* (8=fail) and *epidemics* (increased infection rate, which leads to chain-reaction outbreaks in multiple adjacent cities). The game subtly changes the world map background color according as you get more epidemics, see video @8:30. I think it may also increase the spin speed with which disease cubes are displayed.
> 7 votes

# Answer
I think that the "time is running out" concept is not itself artificial in nature, it just feel artificial when you put a big flashing countdown clock in front of the player. Kind of like how sanity meters in (Lovecraftian) horror games feel artificial if they are too mechanical. But if you make it a lot more fuzzy, then I think it helps immersion.

So you could do something centered around various systems in the rocket failing, with varying impact, and convey urgency through emotional reactions of the astronaut, and/or vital signs, and various other sensor readings, that allow the player to estimate how dire the situation is, etc.

But this is trickier than it sounds. You need to make sure that the game doesn't feel unfair to the player. E.g. you can't make it too random; there needs to be some level of predictability (at least in the statistical sense), so that players can form heuristics (rule-of-thumb "best practices") and strategies. (Hell, you could even throw in a couple of these in the "Operator's Manual" available to the agent). This in turn may mean that you need to rethink your puzzle design - maybe the solutions and failure conditions shouldn't be entirely clear cut. E.g. maybe this calls for allowing several solutions to the same problem, or even emergent solutions. Or maybe a randomized failure event (like a breakdown of some system in the craft that serves to increase the sense of urgency) shouldn't prevent the player from completing the puzzle they are currently working on, but should instead reduce the overall positive impact of them completing it.

Another thing that can be effective to increase tension and drama is to have puzzles that involve making tradeoffs. E.g. in order to fix something, the player has to give up something else, and has to evaluate the cost of that. This also has potential to introduce narrative conflict - e.g. maybe the astronaut disagrees with what the player wants to do. You could expand on that idea in different ways. For example, maybe in the first few introductory levels the astronaut is a calm and experienced person, and their remarks could serve as hints. But in a level (or a scenario) later on in the game, the astronaut could be hurt and scared and could insist on doing something that has an immediate benefit to them, but is not a good long-term strategy. Or they could go completely nuts, demanding from the player to do something completely irrational.

Again, getting this right could be quite challenging, both in terms of modeling these behaviors and in terms of achieving the right balance - so maybe a good way to approach this is to try and make small (possibly throwaway) prototypes to serve as a low-cost way to test these ideas, and learn and make mistakes, before you go all in.
> 4 votes

# Answer
**Annoy them after a while**. I had a game where I sometimes dropped an angry cow on the board which jumped on your pieces and blocked your view (it was actually programmed to tend to hop towards the piece you were manipulating). Tapping unreliably knocked it away and tapping several times completely removed it, with an extra-long delay for it to come back. So it wasn't any real penalty at all.

As you might guess, at first it was an "attractive failure". I tried to get the cow, stopped playing and watched it, and so on. But after a while I hated the thing and really, really wanted to make a move quickly before the dumb thing plopped itself down and cowed the place up. It was somewhat irregular, which somehow made it even more annoying. Without having any actually effect, it generated time-pressure (and you do not want to get 2-cowed! How bad do you have to be for that?)
> 4 votes

# Answer
It depends on the nature of the puzzle.

For some types of puzzles, you can think of it in terms of marginal cost and marginal benefit. In other words, what does the player gain by spending more time, vs what do they lose by spending that time.

Suppose a game like the cups and balls. This probably wouldn't normally be considered a "puzzle", but just consider the moving of the cups to be equivalent to any method of obscuring information (which could be done through more "puzzling" logical challenges).

The rules of the game are simply that the player must tell what cup the ball is under after a certain minimum amount of time (and therefore minimum amount of obscurity) has occurred. Now, they can choose to answer at that point, or they can choose to think about it and delay their answer to think it over more. The catch is that if they choose to delay, the cups will periodically be shuffled again and again.

Back to the model of marginal cost and marginal benefit. We can see that in some cases, the player will want to delay so that they can think over their logic to make sure they are confident in their answer. Therefore, we can say there is a **marginal benefit to spending more time**. For the more time you spend, the greater your confidence will be about which cup is the correct one, and therefore your chances of success increase.

At the same time, we can see that the player doesn't want to spend more time, because every time the cups shuffle, more obscurity is created and the player becomes less confident in what the correct answer is. Therefore, we can say there is a **marginal cost to spending more time**. For the more time you spend, the lesser your confidence will be about which cup is the correct one, and therefore your chances of success decrease.

Now the puzzle has two opposing forces, both of which will dictate how much time the player is willing to spend. So long as the marginal benefit is greater than the marginal cost, the best course of action (by definition) is to spend more time on the puzzle. In order to put pressure on the player, you want a mechanism whereby the marginal cost will gradually rise and overtake the marginal benefit.

In this case, since the marginal benefit is proportional to the player's problem solving ability, we can consider it to be somewhat constant. The marginal cost, meanwhile, is proportional to how fast the cups are shuffling, which can be precisely controlled (again, this is equivalent to any logical puzzle which obscures the solution, or adds more work). The solution to put pressure on the player then, is to have the shuffling frequency progressively increase.

Consider the chart above. The green line is the marginal benefit of spending time, or the player's solving ability. The red line is the marginal cost, or the rate of obscurity. As long as the green line is higher, the player is gaining progress or confidence in their answer. As long as the red line is ahead, they are losing progress or confidence. As the red gets closer to the green, it may be beneficial on average to keep working, but the potential detriment of individual mistakes also gets higher.

The green line is only dictated by the player's ability to solve the puzzle, but the red line is what you get to control in the design of the game (namely through the difficulty and frequency of puzzles). Use these mechanisms to control the red curve in a way that you think is fair and enjoyable.
> 2 votes

# Answer
Do not present a timer, make it part of what motivates the player.

You are in space with an astronaut - where air is scarce and CO2 needs to be recycled. For that to happen (solar) energy is needed to work the ductwork and provide for the apparatous that removes CO2 / pumps O2 / works the repair drones for ship maintenance.

* the astronaut uses air up: the available O2 storage is slowly decreasing - this provides a slow sense of urgency
* rising CO2 levels will make breathing impossible when ever they reach a certain threshold the air simply is not breathable anymore (real danger)
* energy may be sparse due to malfunctions of solar sails, being shadowed by a moon, malfunctioning energy lines, ...
* sometimes bad things happen:

+ microastroids puncture sections, they drain of O2 before shut off
    + malfunctions of the CO2 regenerators: CO2 removal is decreased
    + contamination: septic line broke, that part of the ship is now poisoned unless cleared
    + electricity shortage due to shadow, malfunction, arcing where it should not, solar sail gets punctured, ...
* sometimes good things happen:

+ you stumble over an unused O2 container
    + solar sails got cleaned by solar winds and work more efficiently
    + you are able to deploy some emergency sails
    + rerouting energy through those other handwavium paths circumvents burned out sections and more energy reaches the areas it is needed
    + you are able to fiddle some rescue capsule battery into your stations system for a boost of energy
    + scrubbing the CO2 algae clearing tanks makes them work 110% for some limited time
    + a O2 bubble flashes over the puzzle and the player clicks it for some O2 gain
    + you defrost your favorite plant and it helps you with CO2-\>O2 conversion
    + you find the prototype of a new kind of spacesuit that has build in recycling capabilities
    + certain things might be beneficial (solar eruption -\> more energy from solar sails) but on the other hand averse (damages the hydroponic - so less CO2 conversion)
    + ...

You got multiple ways to further / diminish urgency - some of them by dropping random O2 bubbles or CO2 cleanups on the player to click it. You can have puzzles related to fixing equipment, gather resources. You can have random events that influence any one of the 3 angles for time pressure - you can even have the player choose: is it better to take the puzzle to get the energy rerouted or to search this darkened section for O2 canisters.

The player needs to balance the 3 things (O2, CO2, Energy) between certain min/max levels and chooses puzzles accordingly - if things get out of those areas change up the game mechanics:

Low energy leads to dimmer / fluctuating lighted screens, low oxygen tints everything in red and makes things on the borders of the screen blurry and wavy. Too much CO2 makes the mouse react sluggish (0.1s) and sometimes needs a second/third click to make things work.

Nothing major - just some influence is enough.
> 2 votes

# Answer
Points decrease after a set amount of time. The faster you player, the more points you make. The longer you take, the less points you get for a correct move.
> 1 votes

# Answer
It should probably be situational and be based on making the situation progressively (with a taper of course) more miserable for the player, the longer they take to solve the puzzle.

In the case you've presented, I might have the astronaut grow progressively more distraught, perhaps they're freaking out because they only have just so much oxygen, or because the fuel is leaking, or whatever, and you're not moving fast enough. Perhaps they start out nagging, then pleading more urgently, then getting desperately loud, and eventually they move up to screaming constantly at you to "FIX THE #^@$% THING BEFORE I DIE!".

Edit: As someone else suggested, any music playing could amp up with their despair. Also, perhaps they remotely trigger lights and klaxons in your bunker to "get your attention".

It's psychological stress, but no actual time limit is involved.
> 0 votes

---
Tags: game-design, puzzle
---


# Question
Title: Ensure that random enemies don't spawn just near the player
I need to find a method using which I can ensure that random enemies and objects don't spawn just near the player. In fact, if they do, the player will be more likely to collide with them and lose.

These enemies and objects spawn relatively to the player's score and to some userevents.

I've tried to use a recursive function in these objects' classes in order to check whether the object's coordinates obey to the condition that they shouldn't be near the player's coordinates and if they are valid (they obey to that condition), I can blit their images to the screen.

But I found that this idea isn't a good one and demands lots of code so I abandonned it.

So is there any other method to implement that ?

## NOTE :

Enemies coordinates are generated randomly like this:

```
self.x = random.randrange(2, 502, 20)
self.y = random.randrange(2, 502, 20)

```

Then, they're blitted to the screen at these coordinates :

```
screen.blit(myenemy.img, (self.x, self.y))

```

# Answer
The simplest system I can think of consists in testing the position of the new enemy before your `screen.blit()`, like so:

```
def distance_square(a, b):
    return (b.x - a.x) * (b.x - a.x) + (b.y - a.y) * (b.y - b.y)

def init_enemy(min_distance):
    while True:
        self.x = random.randrange(2, 502, 20)
        self.y = random.randrange(2, 502, 20)
        if distance_square(self, player) > (min_distance * min_distance):
            break
    # Then blit the enemy, etc.

```

I left the distance squared as a slight optimization, since it is faster to compute a simple multiplication.

The logic is very simple here: rather than seeking a specific algorithm to generate a random number that meets your conditions, it is probably simpler (and perhaps faster) to just generate a new random number. Here, I generate forever until I find a position that meets your requirements.

However, you may want to set some safety net to avoid a very, very unlikely but possible loop that run for a long time. And you can of course implement this loop right into your game loop depending on how you designed it. It's all up to you and as it depends on the specific needs of your project. This is just a template.
> 3 votes

---
Tags: pygame, coordinates, spawning
---


# Question
Title: How to select a sprite with the mouse in c# XNA?
I'm attempting to create a chess game, for the movement I need to be able to click on a piece with the mouse, and then the square I'd like to move it to. Each piece on the board is a sprite, and I'm struggling to find a way to select a sprite in order to then move it, what would be the best way to do this? I'm programming in c# with XNA framework btw. Thanks in advance :)

# Answer
> 0 votes
I think the best way would be to make a rectangle for the position and hitbox of each of your chess pieces. After that make a rectangle for the mouse pointer, and use the Rectangle.Intersects method to check if your mouse hitbox intersects with one of the pieces hitboxes, and of course do your logic there.

---
Tags: c#, xna, sprites, monogame, picking
---


# Question
Title: How to set transform.up without locking the y-axis?
I'm trying to make an object's transform.up to a normal of the raycastHit point. I tried using this line of code:

```
transform.up = Vector3.Lerp(transform.up, normal, 1 * Time.deltaTime);

```

This works well but locks the y-axis rotation as a result the object can't rotate and just keeps going forward. I tried using Quaternion.LookRotation. But I couldn't make it affect the object's rotation. Here is what I tried:

```
bodyRotation = Quaternion.LookRotation(transform.forward, normal);
transform.rotation = Quaternion.Slerp(transform.rotation, bodyRotation, 100 * Time.deltaTime);

```

How can I set the transform.up without locking the y-axis?

# Answer
> 1 votes
When you assign a value to `transform.right`/`up`/`forward`, you're implicitly telling Unity "I care *only* about the direction of this one axis - do whatever is cheap and easy with the other two". If you care about both the up and forward direction, then you need to take responsibility for constructing a quaternion with your desired orientation.

Fortunately, this is easy, as I've covered in several past answers:

```
Quaternion TurretLookRotation(Vector3 approximateForward, Vector3 exactUp) {
    Quaternion zToUp = Quaternion.LookRotation(exactUp, -approximateForward);
    Quaternion yToz = Quaternion.Euler(90, 0, 0);
    return zToUp * yToz;
}

```

You can incorporate this like so:

```
var targetRotation = TurretLookRotation(transform.forward, normal);

transform.rotation = Quaternion.RotateTowards(transform.rotation, targetRotation, speed * Time.deltaTime);

```

I've used `RotateTowards` in place of `Lerp`/`Slerp` here, because your lerping expressions were not not correctly adjusting for `deltaTime`.

---
Tags: unity, rotation, quaternion
---


# Question
Title: Designing persistence in an ECS world subdivided into chunks
I'm designing a kind of simple open world with ECS. The whole world is too large to be loaded at once, so I load and unload chunks according to player's position. Nothing fancy, pretty much standard nowadays.

In this world, I have entities that I need to update frequently. There are a couple of thousands of them. These entities share some components and a tag to retrieve them, but can refer to different archetypes. These entities are placed by hand, before runtime. No entity of this kind is created on runtime.

I need to update these entities every five minutes. I do not need them to update in a single frame, it can be scheduled over multiple frames (so performance is not exactly critical here but as always, the more performant the better).

# Problems:

1. I need to update every entity, even if not loaded according to player's position
2. I need to save and load the state of these entities

Currently, the position of these entities is guaranteed to remain the same and it is guaranteed too that two entities can't share a same position. However, it may change.

# Considered solutions:

## Solution A

I create a singleton "manager" that holds a container. Keys are the position of the entities. I iterate trough the container to update the values, so I don't need to load entities.

I update the entities currently loaded with the new values retrieved from the manager.

Pros:

* Fast
* Easy to work with
* No need to load entities (and meshes and so on)
* Trivial to serialize and save
* Do not require additional work on the world creation

Cons:

* Not flexible as the position is now a key (could be a problem if I want the system to evolve)
* May cause issues when parallelizing
* Having positions as keys is probably a very bad idea
* **Defeats the principles of ECS as data is not "owned" by the entities, but is centralized**

## Solution A (alternative):

This time, with a script I execute before runtime, I set an ID to each entity in my world as part of a component. I use this ID to store the data in my container (which is now a simple array and not some sort of a dictionary).

Pros:

* Very fast
* Easy to work with
* No need to load entities (and meshes and so on)
* Trivial to serialize and save

Cons:

* Does require additional work on the world creation
* Still not very flexible (but better than positions)
* May cause issues when parallelizing
* **Still defeats the principles of ECS as data is not "owned" by the entities, but is centralized**

## Solution B

This time, all the data remains in the entities. I have to separate my chunks into two parts: a part with the entities I need to update (let's call that an update-chunk), a part with the rest of my entities (a regular-chunk).

I first have to create a save for my entities: I load every update-chunk, I update the entities, I serialize them then unload them.

Then, for each update: I deserialize my entities, I update the entities, I serialize them again.

When a chunk is loaded: I deserialize my entities and I load the regular-chunk only.

Pros:

* I'm using ECS, yeah!
* ... Nothing much

Cons:

* Ridiculously inconvenient and complicated
* I need to serialize over and over again
* Probably very, very bad performance
* I save a lot of data I already "saved" in my base configuration (so many duplicates)
* Difficult to set up as I have to create twice as much chunks
* I have to load meshes/textures associated with the entities even if I do not need to render them (I can't change this behavior in the framework I use, or I need to code another system and this is getting far too complex)
* Probably more but that's way enough to disqualify this solution

# Conclusion:

I'm pretty much convinced I'm doing something wrong and that I missed something really important.

**Solution A** may perfectly work (after all, I have no need to absolutely use ECS for everything) but it bothers me that I can't figure out how to solve this problem with ECS.

# Answer
Solution A (Alternative) seems reasonable given the constraints you mention in your question and I suggest giving it a try. Regarding your hesitancy to stray from an ECS; notice that there is a *fundamental* conflict between the chunk system, ECS and these updating entities: Your components are stored on a per-chunk basis (as far as I can tell), the chunk system makes unloaded components inaccessible via serialization, and yet the entities must be accessible to be updated. This is a hint that a solution outside of your current framework may be reasonable.

How radically different your solution might end up from your current systems is highly dependent on how many invariants you can place on your updates. Lets say each update will only ever affect the entity itself and the effects of the update are only needed when the player is within loading distance of the entity (for example a light that changes colour every five minutes), now you can create a solution that simply stores the amount of time spent unloaded with each chunk and between deserialization and rendering let the entities within chunks consume this time to appear as though this unloaded time had passed. On the other end if the updates that need to occur are much more depthful, lets say some physics interactions need to happen like a rube goldberg machine, then we arrive closer to solution B where loading and updating distant chunks may be necessary for correct behaviour.

Importantly, notice that since your updates are fundamentally global, most solutions must circumvent your chunk system. The unloaded time queue adds data that never gets serialized and deserialized as the player moves around, the deserialize-update solution must undo the work of the chunk system to make components accessible for updates, and your solution A stores a global list that is unchanged by player position.
> 1 votes

# Answer
We had to solve a similar problem when developing Starlink: Battle for Atlas. The game takes place in a system of seven planets, and although only a small chunk of the current planet around the player is fully-loaded at any given time, the allied and enemy factions continue to battle it out on the far side of the planet and all the other planets.

We did this by distinguishing between two forms of entity:

* a "fully realized" entity with its full AI brain, animation and rendering features, physics, etc. and...
* a "sim unit" that's stripped down to just the bare minimum state we need to tick the away-from-player simulation, like a position, health, faction ID, etc.

You could employ a similar strategy within your ECS. It might look something like this:

At authoring time, you attach a SimUnitMapping component to each entity that needs this kind of persistence. This component associates the fully-realized entity with a specific SimUnit ID (like a serial number or GUID), and optionally some metadata about what needs to be persisted in its de-rezzed form.

When an entity with a SimUnitMapping component is about to be unloaded, it's processed by a dedicated system. That system reads the components on that entity and spawns a new SimUnit entity with the corresponding ID, populating it with the correct components and values to persist the state you need persisted. (These components could be the very same ones you use on the fully-realized version, or specialized slimmed-down versions with their own low-fi systems for the background sim)

Similarly, when you enter a new chunk and need to load the entities there, loading an entity with a SimUnitMapping component tells you to look up the SimUnit with the matching ID, and copy over its persistent state. Then you can delete the SimUnit, transferring responsibility for its updates to the fully-realized copy, until it is again unloaded.

In this way you keep using entities throughout - you never have to leave the ECS paradigm. You just pass data back and forth from one collection of entities to another, and can specialize each collection to the needs of either background simulation or foreground player interaction.

If you need to be ticking these SimUnit entities even before the player loads their realized versions in the first place, you can do so by generating a list of all SimUnits as a build process step, and instantiating all those entities when starting the game, before loading the first chunk.
> 1 votes

---
Tags: architecture, serialization, entity-component-system, open-world
---


title: Two sided sprites

text:
# Question
Title: Two sided sprites
What is the most efficient way of making two sided sprites in Unity's new 2D tools? I'm looking to make playing cards with a backside and a front side.

# Answer
> 8 votes
I did this successfully by rotating the sprite to 90 degrees on the Y-axis, then changing the sprite texture and finally rotating it back again.

```
while(turningCard)
{
    transform.rotation = Quaternion.Slerp(startRotation, endRotation, rotateTime);

    if (CheckIfAngleBigEnough())
    {
        ChangeSprite();

        ChangeRotationDirection();
    }

    yield return null;

}

```

# Answer
> 2 votes
The answer by @Ayyappa helped me greatly. Here's an updated and working implementation of the suggested shader, which will enable you to set separate textures for each side of a quad-based card, and a Color to either tint or fade the card:

```
Shader "Card"
{
    Properties
    {
        _Color ("Color", Color) = (0, 0, 0, 1)
        _FrontTex ("Front Texture", 2D) = "white" {}
        _BackTex ("Back Texture", 2D) = "white" {}
    }

    SubShader
    {
        Tags
        {
            "Queue" = "Transparent"
            "RenderType" = "Transparent"
        }

        Cull Off
        Blend SrcAlpha OneMinusSrcAlpha

        Pass
        {
            CGPROGRAM

            #pragma vertex vert
            #pragma fragment frag
            #pragma target 3.0

            #include "UnityCG.cginc"

            struct v2f
            {
                float4 vertex : SV_POSITION;
                float2 texcoord : TEXCOORD0;
            };

            float4 _Color;
            sampler2D _FrontTex;
            sampler2D _BackTex;
            float4 _FrontTex_ST;
            float4 _BackTex_ST;

            v2f vert(appdata_base v)
            {
                v2f o;

                o.vertex = UnityObjectToClipPos(v.vertex);
                o.texcoord = v.texcoord;

                return o;
            }

            fixed4 frag(v2f i, fixed facing : VFACE) : SV_TARGET
            {
                if (facing > 0)
                    return tex2D(_FrontTex, i.texcoord) * _Color;
                else
                    return tex2D(_BackTex, i.texcoord) * _Color;
            }

            ENDCG
        }
    }
}

```

GitHub Gist snippet

# Answer
> 1 votes
Either two sprites backing together, or a custom shader with no Backface culling could be the way to go, you could use a mod of the original sprite shader which is here : Unity Built-in Shaders (select the last version and you should find them in the same order as in the menu)

I did a shader once with a different texture on each side, with the same vertex count but i'm not close to my code right now.

EDIT : If you go for the custom shader dont forget to create a material and associate it with your sprites. I just realized by the way that there could be an issue with the fact that the Sprite renderer accepts only one texture, but you could trick it by making a texture with the front and back on the same texture, and then offsetting your UV's to match the correct positions.

# Answer
> 1 votes
I gave a quick try(infact took some time to get used to shader lab syntax ;) as i was trying after quite some time).

Let me know if this shader works for you.

Basically checking the frag color by sign value of dot product of view direction and normal of the vertex. Btw, I set the culling to off.

Thanks for letting me trying this out. Very happy with the output ^\_^ . I'm aware of doing without shader but thought of giving this a try with shader.

Sorry for replying abit late to your post.

Link : http://pastebin.com/8dKBzsY6

Update: Here is the explanation of the code. This is infact how Back-face culling works. The Dot product between The camera view direction and the vertex normal will tell which way the vertex is oriented. Whether its away from camera or towards the camera.

Dot product value of those two vectors goes negative if the vectors are away from each other.

So , the same math is used to find out which texture we need to show.

In the code, I took two texture samples (\_FirstTex,\_SecondTex) as properties.

**Vertex Shader**

1) First we need to convert vertex co-ordinate which is in object space to Clip Space.

2)Next we use world View space direction(\_WorldSpaceCameraPos) provided by unity cg includes(UnityCG.cginc,UnityShaderVariables.cginc) and normalize it. (Infact there is no real importance of normalising here as we just need sign of dot product.)

3)We then need to convert vertex normal to world space.(Please check the comment there for converting to same co-ordinate system). We can do the other way as well(converting view direction to object space).

4)Find the dot product and save the value in color.w to pass it to fragment shader.

**Fragment Shader**:

1)We find out the sign of the dot product value and based on that decide which texel to fetch.

2)Return the texel color.

Let me know if you need any further clarification.

---
Tags: 2d, unity, sprites
---