# Question
Title: How do I get a job in the games industry as "the one with the ideas"?
So, I am very interested in making great games that the consumers will love, but I am not the best at programming or art, and I don't have a team. If I show that my ideas can bring in a steady stream of profit, will big game companies like Ubisoft hire me and give me a team to develop them?

# Answer
> 134 votes
> will big game companies like Ubisoft hire me and give me a team to develop them?

Having worked as a game designer at Ubisoft for 10 years: no, they will not.

The role you're describing is what we often call the "**idea person**" - it's a common belief among players and folks outside the game industry that there's someone like this as the seed/leader of many game projects, but **it's not a real position that exists in actual game companies**.

The closest parallel might be a "Creative Director", but this differs from the role you describe in a few ways:

* **The creative director does not come up with all the ideas for a game**. Their role is to lead the team and curate the artistic vision of the experience. The game pitches they work on, even if they become the most visible champion of them, are frequently workshopped by teams of people, and informed by high-level directives from the company leadership / marketing & business analyses, etc.

Even in "auteur" -focused games with famous household-name creatives like Hideo Kojima or Sid Meier headlining them, I'd be willing to bet that many if not most of the specific ideas and solutions in those games arose from the collaboration of the whole development team, supported by their creative leadership but not dictated/micro-managed (at least, if they're *good* creative directors )

The way I put it to my game design students: as the number of people working on your team increases, the probability that *you* have all the best ideas drops toward zero. A great designer or director recognizes this, and knows how to collaborate with their team to get the best work from everyone. I like to use the analogy my role as a designer as an "idea shepherd", tending to the *team's* flock of ideas, guiding and grooming them into a harmonious ensemble, and occasionally putting down those ideas whose time has passed.

A creative director I worked with at Ubi described the role as shining a spotlight, highlighting a wedge of possibility space for us to explore as a team. Too narrow a beam, and we spend too much time course-correcting as we zig-zag in and out of the target, making little forward progress. Too broad, and the game is aimless and lacking coherence. Finding that balance and communicating/motivating the team to explore it together is the CD's role. Charting the specific course for how to explore it is something entrusted to the experts who make up the team.
* **No one is hired directly into a creative director role**. Unless you're founding your own studio and appointing yourself that role, it's something you work up to over years. Not just by having good ideas, successful solutions, and shipping popular/profitable games, but also by demonstrating skills in managing and leading teams, collaborating with specialists from all departments, successfully championing projects through the corporate/editorial hierarchy, and in some cases being an effective public spokesperson for the game at things like conference reveals and community events.

So, there's a lot more to it than having good ideas. There are many folks who have at least a few ideas with a tonne of potential, who could never lead a successful team to execute on them. So just showing up with a great idea isn't enough to convince anyone to hand you the reins to a team and the budget to fund it. You need to build a track record, reputation, and trust over years of work in the industry.

Many folks who eventually work their way into design leadership roles - either as directors or lead designers and the like - start smaller. They might be hired as a junior designer focused on smaller-scale tasks like updating documentation or tuning a specific feature, or a level designer tasked with laying out and scripting play scenarios, or even a QC tester working in tandem with developers to find and diagnose bugs. Then through experience, they gradually move up the ranks as they grow their skills, develop a track record and rapport with their teams, and demonstrate their ability to collaborate with and lead fellow creators.

Jumping straight to the helm of a game is mostly a fluke of luck for the few successful indies, or a historical artifact for folks who happened to be at the right place at the right time in the early days of the industry. It's not really a career path you can plan for.

It's also important to point out that ideas are not in short supply. Everyone who's ever touched a game has dozens of ideas they're sure could be immense hits - and perhaps many of them could be, with the right execution. But it's that execution that makes the game a success, not really the idea. Most game ideas suck \- including yours, and mine. "No battle plan survives contact with the enemy". Turning the seed of an idea into a successful game is the hard part, and that requires team collaboration and iterative refinement. I've never seen a game that went straight from pitch to player's hands unchanged. What game studios need are people who can get their hands dirty in that collaborative process of iteration to *make* an idea into a good game, not just more ideas.

---

**So: what *can* you do instead with your ideas and enthusiasm for games?** If getting hired just for the strength of your ideas isn't in the cards, what else can you try?

* **Make your own games**. It doesn't matter if you're "not the best at programming or art" - even the folks who *are* the best in the biz today didn't start that way. They worked their way there through practice.

Just start small: your first game will not be your dream game. Pick something tiny in scope to match your current level of skill - maybe re-implement a classic arcade game, then for an extra challenge, try adding your own new twist. If you're not confident in your art, use free art packs, or pick a game that doesn't depend on fancy visuals. If you're not confident in your programming, try using templates/assets that let you remix common building blocks, or node-based scripting tools like PlayFab/Unreal Blueprints.

If you run into snags, this site and other game development communities are here to help you.

If your first attempts end up bad/not fun, don't be discouraged: that's entirely normal. There's a saying in the games industry, "your first ten games will suck, so get them over with as fast as you can". Each attempt, even unsuccessful, will teach you more, and you'll quickly build up a foundation of skills that will allow you to tackle more challenging problems.
* **Join game jams**. These are short (usually free) events where folks try to make a new game from scratch in a weekend/week/month (depending on the jam). The games are often experimental and just for fun, so the stakes are low and it's easier to jump into than interviewing for a paid position right away. Some jams will have matchmaking services to help pair up lone contributors with teams they can help.

This will help you get experience making games with other people, practicing the collaborative skills I emphasized above, and getting used to the iterative process of going from initial spark to playable build. They also let you test out ideas that might be too unproven to throw a budget behind right away. And they can help you make connections to other creators who might be able to help you find paid positions, and you'll build up a portfolio of game creations you can use when promoting yourself and demonstrating your skills to employers.
* **Support other creators**. Don't expect to jump straight to being the creative boss. Maybe you can find indies or hobbyists in your communities who need playtesters and feedback, or community moderators for fan discussion sites/Discords. Maybe you can find a paid role as a QC tester or intern at an existing studio, and work your way up. You might not get to work on your own ideas right away, but by being a good collaborator you can earn greater trust and responsibilities (if the company has good professional development paths).
* **Go to school**. This isn't for everyone, and it's not a guaranteed ticket to the industry, nor a requirement to be a good game developer. But some folks find a structured learning environment to be helpful in developing their skills, and the diploma/degree you get and the portfolio you develop along the way to be a useful way to prove yourself to potential employers - or at least get past the initial HR/recruiter filter.

Just beware of predatory programs that use the hype around games to lure students, teach them a superficial sampling of game-related tasks, then set them loose without ever developing a deep specialization in any one department that would be enough to get hired at a big studio. If you want to be a game or level designer, look for a program specific to *design*, with the majority of courses in the program map being about that specialty (shameless plug - the Bachelor of Game Design program I teach in at Sheridan College is one I'd consider to be a good example in this regard). If you want to be a 3D artist, look for a dedicated 3D modelling/animation program. If you want to be a programmer, look for a dedicated computer science program. A "royal sampler" program that's just 1-2 years and offers a sprinkling of everything should be a red flag.

# Answer
> 22 votes
There are a few aspects to this situation.

1. Video game companies usually have a large backlog of unused ideas.
2. The hardest part of making a video game is not coming up with the idea, but implementing it well.
3. Most video games never make a profit, so even among established teams there's no way to tell if their next product will be commercially successful or not.

So for #1, the industry generally does not have a position for a person who "just has good ideas". The closest it comes to this is probably Creative Director. These people *might* have the idea to start with, but it is then their job to guide the development team along the way to make sure it stays true to their vision. It's a hard job, and people who have it usually get there by having other production roles first.

On #2, since there are tons of ideas hanging around already, the real issue is finding good people to put on the implementation team. As mentioned there needs to be a Creative Director to guide the production, but that's loads more work than "having good ideas".

Which brings us to #3. Even someone who's already proven they can make successful games isn't successful every time. When there is a new idea, even from someone who has a proven track record, it has to go through a rigorous process to be vetted for full production. This involves a lot of steps, including early prototyping and various checkpoints along the way. So there's no real way for someone outside the industry to prove their ideas will be successful, because not even industry veterans are always successful.

Just as an example, Supercell, maker of the amazingly successful Clash of Clans, Clash Royale, Hay Day, Boom Beach and Brawl Stars, makes lots of games that fail. Their process includes a long period of "soft release" where the game isn't out in all territories where they test it to see if it has good enough KPIs (Key Performance Indicators) to be a viable product.

Here's some information on them: https://www.gamesindustry.biz/supercells-killed-games-celebrating-lessons-not-failures

> Since its founding nearly 10 years ago, Supercell has fully launched five mobile titles including Brawl Stars -- a surprisingly small number for such a successful company. I was told that, not including the studio's live titles, Supercell typically has between four and six games in development at any given time, and sometimes as many as eight. With only five total full launches, that's a lot of killed games.

I've personally played Rush Wars and Everdale, both Supercell games that didn't make it through the soft release process. So even one of the most valuable game companies still makes games that don't reach commercial success.

In closing, I'll share a bit about my story. I joined the industry in 2000 as a programmer/designer. My job was to design and program Shockwave games for browsers, about one per month. So I did have a position where I came up with ideas. But I still had to get each one approved by the producers before being given the go ahead to start production. Each game was made by me and one artist.

Over the years, I did lots of various programming jobs, with occasional design work. My goal had always been to be a game designer. But it look a long time to convince companies I worked for that I should be one. Good programmers are always in short supply. Eventually I landed this design job on Dead by Daylight in 2018, and I've been on that project ever since. Even so, every idea I come up with has to be vetted by at least the Lead Designer, sometimes also the Game Director before it can go into production.

So even as a live balance designer, I would not consider myself "the one with ideas". A large part of my job is not just coming up with things to update, but documenting them, communicating them to the rest of the team, and monitoring data on their performance once they go live.

None of this is intended to discourage anyone. It's just that it's easy to have the wrong impression of how ideation actually works inside the industry.

# Answer
> 8 votes
People sometimes have the belief the idea is the most important part of making a creative work successful, whether that be book, movie, video game, or something else. More often than not, the people who push this belief haven't gone through the process of building and selling a Creative Work. I feel that this often stems from a few assumptions:

1. A bad idea can't be made into something good.
2. You can accurately gauge the worth and viability of an idea before trying it out.
3. The most memorable parts are always from creative vision and NEVER from problem solving.

All the above beliefs are wrong. I could lecture about why, but that's really boring and opinionated so instead I'll give some real world examples.

> A bad idea can't be made into something good.

Once upon a time a writer was in an argument with a stranger on the internet about whether the idea or the execution mattered more. The writer argued that the idea didn't matter, only the execution while the stranger argued the exact opposite. They went back and forth until the writer said, "Give me the two most incompatible ideas you can think of and I'll write a story using them". The ideas given were **Pokémon and the Ancient Roman Legion**.

That was the story behind how Jim Butcher wrote the *Codex Alera* series.

> You can accurately gauge the worth and viability of an idea before trying it out.

Way back in the 1990's, Blizzard Entertainment was working on the game Diablo. When working, management came to the team with two requests:

1. Change the graphics from Claymation to 3D models.
2. Change the combat from turn-based to active.

The first change they didn't have problems with. However, they vehemently were opposed to the second change. Management kept pushing them to change so they decided to make a prototype so they could prove to management that it was a terrible idea. Once they built the prototype, the developers discovered that the active style was way more fun than the turn-based style. They've kept this active style for the series to this day.

> The most memorable parts are always from creative vision and NEVER from problem solving.

The idea for *Plants vs. Zombies* came about because when they were building a tower defense game, they needed something that player wouldn't expect to be able to move when placed (Plants) and something dumb that came in waves (Zombies). Creepers in *Minecraft* were made because of a bug. YouTube started off as a dating site where singles communicated through videos. The dating part didn't do well, but they realized that they had an excellent video sharing site. These days, everyone uses YouTube.

# Answer
> 6 votes
**TL;DR** With over 15 years in the video game industry, I can tell you: there are no jobs for idea people. Ideas are not valued as much as ability to execute and perform. Your best best: go to school and get a game design or software engineering degree (with a focus on gameplay programming if possible), or learn enough programming to do everything yourself (except art, almost everyone outsources art). There's tons of opportunity, with free or cheap online classes, stuff you needed to commit a four year program to access just a decade ago. There are tons of tools, including incredible game engines that would have cost thousands to license just a decade ago. With little to no programming skill, you can get your ideas made on your own, or at least with minimal assistance. That is how you best show your ideas have value.

Idea people are only team members with the power and/or respect to have their ideas listened to. The "easiest" way to get there without design or programming skill is get loads of money to start your own company. This is also the easiest way to lose loads of money and make a name that no one wants to work with. Of course, this is actually only easy for people born into loads of money. Also, making people do your ideas instead of theirs is a great way to get people to never want to work with you again.

So, you don't have money or family to force doors open for you, then what?

Well, get honest with yourself. What do you really want out of being "the one with ideas"? Is it fame, like Sid Meier, having your name in the title? Is it power, being able to tell people how to make the game of your dreams? Is it money, to make millions from your ideas and you live a life of luxury? Or is it something that's hard to name other than "fun," you simply want to make games because you love games and a creative passion to make them for others to enjoy?

Of those, only the last one is a good reason to get into the game industry. You will find more fame pursuing front-of-camera entertainment, like acting, politics (at least if you're American), or "content creator." You'll find more power pursuing business, a legal career, or politics. You'll find more money in every single tech industry that's not games, also politics (if you have no morals).

Real talk: your passion is real and powerful and important. Also, nearly everyone in games has that same passion (or at least they did when they started). Your ideas are real and have immense potential. Also, almost every one in games has hundreds of ideas they want to make, too. Passion and ideas are not enough. They are not valuable. You also cannot thrive by making your passion or your ideas more important than everyone else you work with (unless you have the money, power, or fame to get away with it, even then, that rarely goes well for long).

One path (my path as example) is to get your foot in the door, tester most likely. Then beat the odds and make full time. Then get into production, likely as an associate or line producer. From there, you can leverage your experience to do more design tasks, but you're already in the room hearing ideas. Whether you are welcome to contribute significantly will vary widely from team to team and company to company.

This was me. I did great, even found a niche in narrative design. I wrote scripts for games, including big hitters like Disney and EA! Even then, I wasn't "the one with ideas." Much of the gameplay and locations had been decided. I mostly connected existing ideas. And due to experience and connections, I finally made my dream as Creative Director for a startup publisher after 13 years. I was the guiding force for all our projects. Despite being "the one with ideas," I couldn't responsibly force others to take them. My team also had ideas, and I wanted their ideas heard. This was good otherwise they never would have hired me despite our history together. Our partners also had ideas, and we all wanted to respect our partners. My job was mostly: suggest, massage, collect, and collaborate.

Also: I couldn't code. So my ideas were always translated by someone else, usually lots of someones. I performed well and all my coworkers liked my work, but I was deeply dissatisfied that I couldn't make *my* ideas happen. I couldn't show anyone what those ideas were; only tell; only explain. When the company folded in less than two years (due to financials mishandled by our parent company, not because of our work; this is *extremely* common) I went back to school to learn programming. It's never too late. But then that changed my life. I also discovered a whole work world of competent people managers, with work-life balance and 2x pay rates unheard of in games. So, I haven't gone back to games and now I have skills valuable outside of games. Honestly, some fair amount of burn out watching people chase money over fun has been a big factor in not rushing back.

In my day, testers were rarely outsourced, so it was an easier way in. These days, the way in is more likely with a degree in programming or design, or a portfolio that communicates accomplishment with making your ideas reality. A good intern program at a school is super helpful, too. Without at least some of that, its unlikely you'd get hired at all. On the other hand, it's also much easier for a single person to make and publish a multi-platform game these days. So really ask yourself, is your goal to work at a big company or to make your ideas into games? It feels good the first few times, your name buried in the credits. It's real magic when you're on a small team, but riskier with less pay. By yourself (maybe a partner or two for coding help and/or art at some point), you get almost complete freedom for almost no pay.

Perhaps the best way to become an idea person these days is to learn programming and/or design (most artists are not as highly valued) and put out games with any of the free-to-use/easy-to-develop game engines. When its just you, you're automatically the idea person. *You have to be*, which can be a drawback with so much pressure and so little certainty.

If you are *extremely* lucky, you could have a multi-million dollar hit and your pick of jobs. Congratulations, you're "the one with an idea" that made millions, more importantly, you're a game designer with a proven hit. You probably won't be *the* idea person, not with only one hit, but a few years more hard work anywhere might get you into that position.

If you are just lucky, you make a game that pays the bills. Congratulations, you're still an idea person. More importantly, you're a game designer that doesn't have to worry about food (at least for however long that game can pay your bills). This could get you a job, probably low to mid level, so you won't be "the one with ideas" for a while. Maybe you could find a niche quickly, like narrative or UI/UX and command ideas with a limited scope from there.

Again, those are very rare. Most likely, you'll have learned valuable skills that will let you get better on the next project. This can be true even you publish and no one ever buys it. This can be true even if you give up on the project entirely! This won't likely get you a job on its own, but it makes a good portfolio addition.

Still, even being *extremely* lucky, a massive company like Ubisoft is not likely to hire you for your ideas. They might want you for your experience and skill, but not your ideas. If your game was a big enough hit, with continued profits (aka monetization), someone might offer to buy you out and then you could negotiate a directorship. Maybe. Most likely, you just have a better resume than most can hope for. Your best path would be to invest in what is now your own company, and keep putting out the hits. Which is still extremely difficult, even if its just sequels. But it ensures you remain the one with "ideas."

If that does work, then with a proven track record, you'll almost certainly enjoy the freedom of running your own studio (or at least being creative director with *trusted* colleagues running the business) rather than join a big company. The path there is having your studio acquired a big company, who already have their ideas and franchises. You will at best be a creative director, maybe a studio head, both of whom is more of an idea collector than the sole idea generator. But at this point, most who sell do it for the money, or to get away from the "hit franchise" and do something they can't do because their studio is too big to risk it, or just retire. A company I worked for sold because our skills, not IP or ideas, were valuable, especially the 12 of us bundled. The founders sold because, despite continued popular titles, they would have run out of funds in a year. It was way cheaper to buy us than head-hunt for 12 people with our skills.

Sid Meier, probably the industry's first famous and most well known "idea guy" got his start in 1981, already with a background in non-game programming (which was the only kind, really). He co-founded MicroProse in 1982. His name was made by putting out solid titles, all flight sims. Even then, it wasn't until Robin Williams (yes, that one! he was a huge gamer since early days and attended the tiny software conferences popping up in California) told Bill Stealey, the CEO and other co-founder, that Sid's name meant something, they should promote him like a star. They did on *Sid Meier's Pirates!*, because it was thought that Sid's flight sim fans would try this game, instead of ignoring it for the different genre it was. They were correct and *Sid Meier's Civilization* came shortly after.

This is back when computer games was barely a $1 million industry, not the $1 billion industry it is today. No celebrity comedians are going to make you an idea generator (certainly not without a string of titles under your belt). It was easier in the 80s and 90s because no one cared. Now video games are market movers. Everyone cares.

> If I show that my ideas can bring in a steady stream of profit, will big game companies like Ubisoft hire me and give me a team to develop them?

Absolutely! But, how do you prove that without a studio or skills in programming and design and a proven track record?

2nd TL;DR: In order to prove your ideas are worthy of a company like Ubisoft, you have to have published successful games! It's a huge gamble to do it on your own, but that way you can be the one with "ideas" from day 1. Otherwise, get training and degrees to get hired, and you might be able to get there in a decade or two, if you don't burn out before then. Although the big companies do often grind people down, any creative work for extended periods runs a risk of burnout. Being the person putting ideas out there means putting your heart out there, and that means anyone can poke it and stab it for any reason at all. Forget ideas, forget company names, forget titles. Focus on the core of your passion. Think small. Make a game for a loved one. For yourself. Do the other stuff to make a living, to make a name, to get a job with Ubisoft, whatever sounds great, but you definitely don't need Ubisoft, or any other company, to make you happy.

PS Oh right, and Sid these days? He basically manages Firaxis now, enabling others to bring their ideas together. He can't even get his big ideas made. His stated passion is a dinosaur game, publicly announced in 2001 and publicly shelved in 2005. They're just "too busy" making games based on others' ideas to make his idea. So, in the end, even "the one with ideas" isn't free.

# Answer
> 3 votes
> How do I get a job in the games industry as "the one with the ideas"?

That's not an actual job-description in the games industry outside of some very naive startup companies.

There is no individual person in most companies who comes up with the idea for the game that everyone else is going to make, and even if there is, they generally don't keep ownership of the ideas beyond that point.

**The reality is that *everyone* has ideas.**
Ideas are really really cheap. I went on holiday last month and wrote down and even fleshed out two cool ideas for games while sitting by the pool. No exaggeration.
(For the curious: A mobile game where you control a sheepdog to herd flocks of sheep, and a Subnautica-but-in-space sci-fi survival game)

Every games developer who ever earned a red cent in their career has at least a couple ideas for fun games.

In a company of 50 people, there's probably more than a hundred ideas for games to build just sitting on people's scratch-pads waiting for a pitch.
Games Companies don't need an Ideas Man, and they certainly don't need to pay for one full-time.

# Answer
> -2 votes
Super Mario's artist Miyamoto graduated from Kanazawa Municipal College of Industrial Arts. He originally sought a career as a manga artist, until developing an interest in video games. With the help of his father, he joined Nintendo in 1977 after impressing then-president Hiroshi Yamauchi with his toys.

Wikipedia lists numerous video games based on novels; here's a partial list:

* The Witcher Series.
* Metro Series.
* Cyberpunk 2077.
* Tom Clancy's Rainbow Six.
* S.T.A.L.K.E.R. Series.
* Dante's Inferno.
* American McGee's Alice.
* Call Of Cthulhu.

'Ori and the Blind Forest,' inspired by the works of Hayao Miyazaki.

Everyone wants to do design a moving or a video game, so you have to establish your creative talent through your communicative creativity: videos, books or art-forms which garner a cult following.

If your CV gives even a small cult status in creative media, you have a better chance. Directing a video game is also about inspiring energy and communications to many people, a bit like film direction.

1. Write some game scenario portfolio's so that you have studied the art of communicating your talent.
2. Find a channel for your creativity that doesn't require millions of dollars.

* Run a crowdfunding campaign
* short movies,
* plasticine animations,
* sci-fi,
* video stories using AI art,
* creative YT channel,
* children's books,
* adult books,
* artforms
* infomercials

---
Tags: game-design, game-industry, career
---


# Question
Title: error X4532 Cannot map expression to gs_5_0 instruction set
Using DX11 I have this line starting with TC = txDiffuse in a geometry shader that generates the error message. Can someone explain me the problem or if it is not possible to sample in geometry shader (gs\_5 model).

```
 [maxvertexcount(6)]
 void GS_Deferred( triangle GS_INPUT input[3], inout TriangleStream<PS_DEFERRED> CubeMapStream )
 {
     PS_DEFERRED output;
     for( int f = 0; f < 2; ++f )
     {
         output.RTIndex = f;
         for( int v = 0; v < 3; v++ )
         {
             GS_INPUT I = input[v];
             if ( f==0 )
             {
                 float3 TC = float3(1,1,1);;
    ------>      TC = txDiffuse.SampleLevel(samLinear, I.Tex, 0);//same with Sample()
                 output.Color = float4(I.Col.rgb*TC, 1);
             }
             if ( f==1 )
             {
                float3 NBump = I.Norm;
                if ( Flag & BUMPNORM )
                {
                    float3x3 BTNMatrix = float3x3(I.BiN,  I.Tan, I.Norm);
                    NBump = normalize(mul(txNormal.Sample(samPoint, I.Tex).rgb*2 - 1,BTNMatrix));
                }
                output.Color = float4(NBump*0.5+0.5,1);
             }
             output.Pos = I.Pos;
             CubeMapStream.Append( output );
          }
          CubeMapStream.RestartStrip();
      }
  }

```

# Answer
> 1 votes
After having corrected a typo and a couple of other things, I get something on screen but I realized that in fact as vertex shaders have always done, geometry shaders are just outputing the vertex color that is then interpolated in the pixel shader. Indeed I can't expect the geometry shader to produce perpixel interpolation required for using a texture as material. So I moved this sampling to the pixel shader where things are correctly done.

Now regarding the behavior of my initial geometry shader, a couple of settings and CPU coding were missing to have it working properly.

For instance I learned on the way that a rendertargetarray needs the corresponding depthstencilarray if you need depth test. Finally I get what I was expecting: objects being displayed in selected layers of my 4 layers of data used for screen space reflection as colors, normals and depth (in this latter case I have twice the same Zbuffer so an optimization is needed). See picture.

Below the modified geometry shader doing all this.

```
cbuffer cbMesh : register(b1)
{
    matrix World;
    matrix IT_VW;
    float4 FactorColor;
    float4  VisibilityLayer;//xyzw = O/1. the key param for the drawing on selected layers. x=layer 0 .. w=layer 3
    dword   Flag;//adding some object specific shading
    float3 pad;
}

struct VS_INPUT
{
    float3 Pos : POSITION;
    float3 Norm : NORMAL;
    float4 Col : COLOR0;
    float2 Tex : TEXCOORD0;
};

struct GS_INPUT
{
    float4 Pos : SV_POSITION;
    float3 Norm : NORMAL;
    float4 Col : COLOR0;
    float2 Tex : TEXCOORD0;
    float3 Tan : TANGENT;
    float3 BiN : BINORMAL;
};

struct PS_DEFERRED
{
    float4 Pos : SV_POSITION;
    float4 Color0 : COLOR0;
    float2 Tex : TEXCOORD0;
    float3 Tan : TANGENT;
    float3 BiN : BINORMAL;
    uint RTIndex : SV_RenderTargetArrayIndex;
};

GS_INPUT VS_Deferred( VS_INPUT input )
{
    all classical calculs here
}

[maxvertexcount(24)]
void GS_Deferred( triangle GS_INPUT input[3], inout TriangleStream<PS_DEFERRED> CubeMapStream )
{
    for ( int f=0;f<8;++f)
    {
        PS_DEFERRED O;
        float Visible = 1;
        O.RTIndex = f;
        //f=0, 4 always all visible (e.g. VisibilityLayer.x always 1)
        if (( f==1 )|| (f==5)) Visible = VisibilityLayer.y;
        if (( f==2 )|| (f==6)) Visible = VisibilityLayer.z;
        if (( f==3 )|| (f==7)) Visible = VisibilityLayer.w;
        if ( Visible )
        {
            for( int v = 0; v < 3; v++ )
            {
                O.Tex = input[v].Tex;
                O.Pos = input[v].Pos;
                O.BiN = input[v].BiN;
                O.Tan = input[v].Tan;
                O.Color0 = ( f < 4)?input[v].Col:float4(input[v].Norm,1);
                CubeMapStream.Append( O );
            }
            CubeMapStream.RestartStrip();
        }
    }
}

float4 PS_Deferred(PS_DEFERRED Input): SV_TARGET
{
    float4 Color = Input.Color0;
    if (Input.RTIndex < 4)
    {
        float3 TC = ( Flag & dwColorTex0)?txDiffuse.SampleLevel(samLinear, Input.Tex, 0).rgb:float3(1,1,1);
        Color = float4(Color.xyz*TC,Color.a);
    }
    else
    {
        if ( Flag & BUMPNORM )
        {
            float3x3 BTNMatrix = float3x3(Input.BiN,  Input.Tan, Color.xyz);
            Color.xyz = normalize(mul(txNormal.Sample(samPoint, Input.Tex).rgb*2 - 1,BTNMatrix));
        }
        Color.xyz = Color.xyz*0.5+0.5;
    }
    return Color;
}

```

---
Tags: hlsl, geometry-shader
---


# Question
Title: When device is put in landscape mode, a cube in the corner of the screen no longer appears to face forward
I've made a cube in the corner of my screen always face forward:

```
transform.rotation = Quaternion.LookRotation(Vector3.forward);

```

If I hold my iPad upright, in portrait mode, the cube looks correct:

But when I rotate my iPad sideways, in landscape mode, the cube no longer appears to face forward:

Why does this problem occur?

# Answer
The farther an object is from the forward axis of a perspective camera, the more "diagonally" the camera is looking at it, so the more you'll see of its side faces:

By default, when you change the aspect ratio of your game window or screen (like by turning a device from portrait to landscape mode), Unity keeps the vertical field of view constant.

That means as the screen gets wider/squatter, you see the same portion of the world top-to-bottom, but you see *more* of the world left-to-right. So the left edge of the new screen view is farther away from the camera's axis in world space than it was when the screen was tall/narrow.

That's why you see so much more of the side of the cube when changing device orientation.

There are a few things you can do to fix this:

1. Use `LookRotation(cubePosition - cameraPosition)` to point diagonally away from the camera.
2. Use an orthographic camera, which always sees objects from the same parallel direction, no matter where they are in the world.
3. Use a separate camera just for this cube widget, which could be orthographic, or could just be positioned so its axis is closer to the cube. That lets you control the perspective of the cube independently from the rest of your scene rendering.
> 0 votes

---
Tags: unity, rotation, perspective, aspect-ratio
---


title: Storytelling in a DOOM style game

text:
# Question
Title: Storytelling in a DOOM style game
What if you have storytelling elements - nothing too complicated or convoluted, but you have a doom like game?

How can you convey the story through the medium?

I am saying specifically Doom like game, and not FPS, because for example, there will be no cutscenes

# Answer
> 3 votes
Environmental storytelling.

Use the environment details of your games to tell the story. You can do that:

* Verbally: Through voice lines from enemies or NPCs.
* Textually: By having written information on the level geometry. This doesn't necessarily mean long texts for the player to read. A poster or direction sign can tell the player a lot about what goes on in the game world.
* Visually: By integrating story detail into the look of the game environment. Architecture and aesthetics can communicate a lot about where and when the game takes place. Clutter can communicate what currently goes on in the world. You can even design individual places in a way that tells a story. Like placing dead bodies in poses which clearly tell the player how those people died. Or at least inspire their fantasy to fill in the gaps.
* Tactile: By having the player do things, which then affect the game environment. Free hostages, blow up structures, raise flags, etc.

One game series which does that really well is *Half Life*. Another game studio that is really good at environmental storytelling is Bethesda (*Skyrim*, *Fallout*). If you own any of those games, then I recommend to install them again and pay a lot of attention to how those games show you stories without outright telling them to you.

---
Tags: first-person-shooter, storyboard
---


# Question
Title: How to rotate a child game object everytime when parent rotates?
I have a GameObject called Gun, and a GameObject called Hand which is a child of other GameObject named Player.

When I pick up the gun, it becomes a child of the hand.

The problem is, when the player rotates (and so, Hand rotates too), the gun's not rotating, it stays at the same rotation.

Here's the Gun script:

```
using System.Collections.Generic;
using UnityEngine;

public class LaserGun : MonoBehaviour
{
    public GameObject Hand;
    public Transform LaserSpawnPoint;
    public Movement movement;
    public Rigidbody2D rb2D;
    public GameObject Laser;
    public bool IsInHand;

    public void Start()
    {
        Hand = GameObject.Find("Hand");

        movement = GameObject.Find("Player").GetComponent<Movement>();

        rb2D = this.GetComponent<Rigidbody2D>();
    }

    public void OnMouseDown()
    {
        this.transform.parent = GameObject.Find("Hand").transform;
        this.transform.position = Hand.transform.position;
        GetComponent<BoxCollider2D>().isTrigger = true;
        GetComponent<Rigidbody2D>().isKinematic = true;
        IsInHand = true;
    }

    public void Update()
    {
        if (Input.GetKeyDown(KeyCode.E) && IsInHand == true)
        {
            Instantiate(Laser, LaserSpawnPoint.position, transform.rotation);
        }

        if (Input.GetKeyDown(KeyCode.Q) && IsInHand == true)
        {
            this.transform.parent = null;
            GetComponent<BoxCollider2D>().isTrigger = false;
            GetComponent<Rigidbody2D>().isKinematic = false;
            IsInHand = false;
        }
    }
}

```

And here's the Player's movement script:

```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Movement : MonoBehaviour
{
    public float speed;
    public float jumpForce;
    public float moveInput;

    public GameObject Hand;
    public GameObject HeldObj;

    private Rigidbody2D rb;

    public bool facingRight = true;

    private bool isGrounded;
    public Transform groundCheck;
    public float checkRadius;
    public LayerMask whatIsGround;

    void Start()
    {
        rb = GetComponent<Rigidbody2D>();

        Hand.transform.rotation = this.transform.rotation;
    }

    void FixedUpdate()
    {
        isGrounded = Physics2D.OverlapCircle(groundCheck.position, checkRadius, whatIsGround);

        moveInput = Input.GetAxis("Horizontal");
        rb.velocity = new Vector2(moveInput * speed, rb.velocity.y);

        if (facingRight == false && moveInput > 0)
        {
            Flip();
            Hand.transform.Rotate(new Vector3(0, -180, 0));
        }
        else if (facingRight == true && moveInput < 0)
        {
            Flip();
            Hand.transform.Rotate(new Vector3(0, 180, 0));
        }
    }

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space) && isGrounded == true)
        {
            rb.velocity = Vector2.up * jumpForce;
        }
    }

    void Flip()
    {
        facingRight = !facingRight;
        Vector3 Scaler = transform.localScale;
        Scaler.x *= -1;
        transform.localScale = Scaler;
    }
}

```

Some info (might be useful)

* The game is 2D
* The "Hand" object is an empty game object
* There is no animator on player and the gun objects

I tried to upload the image of this but for some reason Stack does not let me do this.

Any help will be appreciated!

# Answer
It is a little difficult to determine from just your code what is the issue, because a lot of things can be causing the issue.

1. Is your Gun parented to the Player when picked up? I know your code says it does, but you may want to check in your Inspector when playing to see if it actually is, because other Components or snippets of code may be unparenting it.
2. An Animator may be affecting the positioning and rotation of your Gun or Player, and this may in turn be affecting your Gun and making it not rotate properly.
3. Is the Player a skinned mesh? If it has a skeleton, and your "Hand" object is a mesh, it may move weirdly. For skinned meshes, you will want to parent objects to the bones instead of the meshes when you want them to move with the body part.

I'm sorry my answer isn't more specific, but Unity has a lot of different moving parts, and I need more information to be able to pinpoint the issue more specifically for you.
> 0 votes

---
Tags: unity, c#, 2d, rotation
---


title: gesture influence each other

text:
# Question
Title: gesture influence each other
here is my two of touch function, the first is two finger touch the screen and move the camera; the 2st one is zoom in-out.

the problem is it often influence each other , when i use it.

like is use two finger move its will exclude a little bit zoom in..

how to fix it??

```
    void touchMve()
    {
        if (Input.touchCount == 2)
        {
            Touch Tozero = Input.GetTouch(0);
            Touch Toone = Input.GetTouch(1);
            if (Tozero .phase == TouchPhase.Moved && Toone.phase == TouchPhase.Moved)
            {
                transform.Translate(-(Tozero.deltaPosition.x + Toone .deltaPosition.x)/ 2000,
                    -(Tozero.deltaPosition.y + Toone .deltaPosition.y)/ 2000, 0);
            }
        }
    }

```

```
    void touchZoom()
    {
        if (Input.touchCount == 2)
        {
            Touch Tozero = Input.GetTouch(0);
            Touch Toone = Input.GetTouch(1);
            Vector2 Tozeroprevious =  Tozero.deltaPosition - Tozero.position;
            Vector2 Tooneprevious = Toone.deltaPosition - Toone.position;

            float oldTouchDistance = Vector2.Distance(Tozeroprevious, Tooneprevious);
            float CurrentTouchdistance = Vector2.Distance(Tozero.position, Toone.position);
            float Offset = oldTouchDistance - CurrentTouchdistance;
            if (Tozero.phase == TouchPhase.Moved && Toone.phase == TouchPhase.Moved)
            {
                transform.Translate(0, 0, - Offset / 1000);
             }
        }
    }

```

# Answer
I think it's more of a human error rather than a programming issue. We can't keep the distance between two fingers perfectly unchanged when moving the camera, right?

Though I have two ideas that may help you:

1. Don't zoom in if the distance change is small. Just write a simple if and check if the distance (in relation to their first position) is less than `X` or not
2. Let them choose. This one's way easier but will limit your user to do only one of them at a time. You can simply make a switch and let them choose what they want to do right now, moving or zooming?
> 0 votes

---
Tags: unity
---


title: Unity clipping volume not working

text:
# Question
Title: Unity clipping volume not working
I am trying to make a transparent clipping volume using shaders. I found this shader code that was supposed to hide everything within whatever volume it's applied to while drawing what's behind somewhere and applied it to a cube.

```
Shader "Custom/BufferStencil" {
  SubShader {
    Tags { "Queue"="Geometry+1" }
    Pass {
      Blend Zero One // keep the image behind it
    }
  }
  FallBack "Diffuse"
}

```

For some objects in the scene, this works. The part of them within the clipping volume disappears. However, I have a thin cube with a textured plane on top of it that I want to hide. The cube just has the default material applied to it. When I move the cube with this shader applied however, nothing changes. Why could this be? Keep in mind I'm not too experienced with Unity shaders. I'm at the very beginning of learning how to use them.

Thanks in advance.

# Answer
> 0 votes
The materials to be hidden have to have transparent materials applied to them. If the materials to be hidden have opaque materials, this shader will not work. After editing the material attributes for what I wanted to hide, it worked very well.

Edit: If you are worried about rendering cost, you can change the render queue of your opaque material in the inspector menu.

---
Tags: unity, shaders
---


title: Gap between two 3D objects in Unity

text:
# Question
Title: Gap between two 3D objects in Unity
Quick question related to Unity: if I have two objects (A and B) to create some tunnel, how can I make a constant gap? I thought of having A and B instantiated with a random value to start with; however, it will not be constant gap. So I was wondering what other ways are (as I'm reading now, there is Vector3.Distance method; but implementing it makes it a little bit more confusing). The idea is to have your player go through to this gap constant of object A and B.

Picture as an example: However, the gaps have inconsistencies because they are not clean. Sometimes there are really close together and the red ball cannot even go through (like the next image)

This is the code example that I have at this moment:

```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SpawnManager : MonoBehaviour
{
    public GameObject[] obstaclesPrefab;
    private float startDelay = 2;
    private float repeatRate = 2;
    private PlayerControl playerControllerScript;
    float gap = 4;
    // Start is called before the first frame update
    void Start()
    {
        playerControllerScript = GameObject.Find("Tomato").GetComponent<PlayerControl>();
        InvokeRepeating("SpawnObstacle", startDelay, repeatRate);
    }

    // Update is called once per frame
    void Update()
    {

    }
    void SpawnObstacle()
    {
        int obstaclesIndex = Random.Range(0, obstaclesPrefab.Length);
        float randomY = Random.Range(-1.0f, 2.0f);
        float randomY2 = Random.Range(-1.0f, 2.0f);
        Vector3 pipe = new Vector3(25, randomY * gap, -10);
        Vector3 pipe2 = new Vector3(25, randomY2 * gap, -10);
        float distance = Vector3.Distance(pipe2, pipe);
        if (playerControllerScript.gameOver == false)
        {
            Instantiate(obstaclesPrefab[obstaclesIndex], pipe2, obstaclesPrefab[obstaclesIndex].transform.rotation);
            Instantiate(obstaclesPrefab[obstaclesIndex], pipe, obstaclesPrefab[obstaclesIndex].transform.rotation);
        }
    }
}

```

I'm open to suggestions as I'm getting started with game development and learning too. Thank you for time and have a great day!

EDIT: Thank you DMGregory for such a simple solution and help. I was just tired and my brain was mush. This totally did the trick!

# Answer
Thank you DMGregory for such a simple solution and help. I was just tired and my brain was mush. This totally did the trick!

Code example:

```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SpawnManager : MonoBehaviour
{
    public GameObject[] obstaclesPrefab;
    private float startDelay = 2;
    private float repeatRate = 2;
    private PlayerControl playerControllerScript;
    float gap = 7.0f;
    // Start is called before the first frame update
    void Start()
    {
        playerControllerScript = GameObject.Find("Tomato").GetComponent<PlayerControl>();
        InvokeRepeating("SpawnObstacle", startDelay, repeatRate);
    }

    // Update is called once per frame
    void Update()
    {

    }
    void SpawnObstacle()
    {
        int obstaclesIndex = Random.Range(0, obstaclesPrefab.Length);
        float randomY = Random.Range(-1.5f, 2.5f);
        Vector3 randomHeight = new Vector3(25, randomY, -10); //CHANGED HERE
        Vector3 randomHeight2 = new Vector3(25, randomY + gap, -10); //CHANGED HERE (I'm adding gap, not multiplying it)
        float distance = Vector3.Distance(randomHeight, randomHeight2);
        if (playerControllerScript.gameOver == false)
        {
            Instantiate(obstaclesPrefab[obstaclesIndex], randomHeight, obstaclesPrefab[obstaclesIndex].transform.rotation);
            Instantiate(obstaclesPrefab[obstaclesIndex], randomHeight2, obstaclesPrefab[obstaclesIndex].transform.rotation);
        }
    }
}

```
> 0 votes

---
Tags: unity, c#, 3d, game-mechanics, transformation
---


# Question
Title: How to divide a Vector3 to recover a scale factor?
I have object I'm scaling by setting its localScale to (1, 1, 1) multiplied by a float `size`.

```
 transform.localScale = new Vector3(1, 1, 1) * size;

```

Now I need to get the size value back from the vector. How can I do that?

I tried to do this:

```
size = transform.localScale / Vector3(1, 1, 1)

```

But I get this error:

> Operator '/' cannot be applied to operands of type 'Vector3' and 'Vector3'

# Answer
Fun fact: there are only four possible division algebras over tuples of reals:

Any other division algebra must be isomorphic to one of these, by the Frobenius theorem.

Note that 3-vectors are not in the list! There is no complete and consistent way to define division over 3-dimensional vectors. In fact, William Rowan Hamilton was *looking* for a way to divide triples when he discovered quaternions.

So, vector division is not a useful way to think about this problem.

If your scale is only ever uniform, then you have the same value in all three components x, y, and z, so you can just pick one:

```
float size = transform.localScale.x;

```

If you can have non-uniform scale, then to digest three potentially different scale factors down into one, you need some way to average them, either taking their arithmetic mean:

```
float averageSize = (transform.localScale.x
                   + transform.localScale.y
                   + transform.localScale.z) / 3f;

```

(If some might be negative, you'd want to take the absolute value of each component before adding them up)

Or their geometric mean:

```
float volumeScale = transform.localScale.x
                  * transform.localScale.y
                  * transform.localScale.z;

float averageScale = Mathf.Pow(volumeScale, 1f/3f);

```

(This one works even with negatives, and the sign at the end tells you whether there's been a net reflection)

More generally, if you have some vector `V` that's been scaled by a scalar `a` to make a vector `S`, you can recover `a` from `S` like so:

```
float a = Vector3.Dot(S, V) / V.sqrMagnitude;

```

Why does this work? The dot product gives us the length of the two vectors times the cosine of the angle between them (cos 0° = 1), so that's `a ||v||²`. Dividing by the squared length of v gets us `a` again — including its sign (since cos 180° = -1).
> 3 votes

---
Tags: unity, c#, mathematics, linear-algebra
---


# Question
Title: Event Click Mouse Button to 3D TextMeshPro
Im create TextMeshPro from "Create -\> 3D Object -\>Text - TextMeshPro" How to receive mouse button click event for TextMeshPro? I tried via Physics.Raycast/Collider but it doesn't work. It's not "Create -\> UI -\>Text - TextMeshPro" though. I also tried to add GraphicRaycaster component to TextMeshPro as for UI element, but it doesn't work.I did not understand where to create EventSystem. I just added it as a component to TextMeshPro. Also tried to add Button Component to TextMeshPro.

```
public class Math : MonoBehaviour
{
    // Start is called before the first frame update
    GraphicRaycaster m_Raycaster;
    PointerEventData m_PointerEventData;
    void Start()
    {
        m_Raycaster = GameObject.Find("Solution").GetComponent<TextMeshPro>().GetComponent<GraphicRaycaster>();
        m_EventSystem = GameObject.Find("Solution").GetComponent<TextMeshPro>().GetComponent<EventSystem>();
        Solution = GameObject.Find("Solution").GetComponent<TextMeshPro>();
    }
    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            m_PointerEventData = new PointerEventData(null);
            m_PointerEventData.position = Input.mousePosition;
            List<RaycastResult> results = new List<RaycastResult>();
            m_Raycaster.Raycast(m_PointerEventData, results);
            foreach (RaycastResult result in results) //Results - null
            {
                Debug.Log("Hit " + result.gameObject.name); //not enter
            }
            Ray ray = GetComponent<Camera>().ScreenPointToRay(Input.mousePosition);
            RaycastHit hit;
            if (Physics.Raycast(ray, out hit))
            {
                if (hit.collider.gameObject.name == "Solution")
                {
                    Debug.Log("Hit " + hit.collider.gameObject.name); //not enter
                }
            }
        }

    }
}

```

# Answer
I don't know what I changed. It seems that nothing has changed. But the BoxCollider method just started working. Thanks to all who responded.
> 0 votes

---
Tags: unity, c#, scripting, text-mesh-pro
---


# Question
Title: Caret not visible with TMP_InputField created from script
I'm modding an Unity game. I don't have access to its source, to any Unity editor or assets. All I have is BepInEx and some C# scripting, plus whatever Visual Studio can decompile from dlls.

I create an `TMP_InputField` when the user presses Enter as follows:

```
var canvas = new GameObject("CommandConsoleCanvas");
var c = canvas.AddComponent<Canvas>();
c.renderMode = RenderMode.ScreenSpaceOverlay;

var inputField = new GameObject("CommandConsoleInput");
inputField.transform.parent = canvas.transform;

var inputFieldText = inputField.AddComponent<TMP_InputField>();
var txt = inputField.AddComponent<TextMeshProUGUI>();
inputFieldText.textComponent = txt;

inputFieldText.fontAsset = fontAsset;
inputFieldText.pointSize = 20;
inputFieldText.text = "example...";
inputFieldText.enabled = true;
inputFieldText.caretColor = Color.white;
inputFieldText.caretWidth = 4;
inputFieldText.selectionColor = Color.white;
inputFieldText.onFocusSelectAll = false;

var rect = inputField.GetComponent<RectTransform>();
rect.localPosition = new Vector3(0, 0, 0);
rect.sizeDelta = new Vector2(400, 25);

inputFieldText.Select();
inputFieldText.ActivateInputField();

```

This sort of works. I can see the text and type in. However, there is no caret and no indication of the current selection.

**How can I make the caret and current selection render?**

There must be some settings or components I'm missing but can't figure it out via Googling and looking at the API.

# Answer
Found the answer burried several pages deep in google search pointing to the unity forum.

Basically, one has to re-enable the component because the canvas is created via `OnEnable` that is probably executing too early before the other components have been setup. (Also the highlight starts working too but of course white on white is not good.)

```
inputFieldText.selectionColor = Color.gray;

inputFieldText.enabled = false;
inputFieldText.enabled = true;

```

Now it works for me as expected.
> 4 votes

---
Tags: unity, c#, input, text-mesh-pro
---


# Question
Title: "Invalid set index (on base: null instance)" error
I am trying to use a timer to change a variable in the parent node of the timer upon timeout.

```
func _on_DashTimer_timeout():
    get_node("root/Game/Level_1/Player").ACCELERATION = 10
    get_node("root/Game/Level_1/Player").MAX_SPEED = 50
    get_node("root/Game/Level_1/Player").velocity = get_node("root/Game/Level_1/Player").current_velocity

```

However, when I attempt to run it, it comes up with the error:

> Invalid set index 'ACCELERATION' (on base: null instance) with value of type 'int'

Anyone know how to fix this?

# Answer
> 2 votes
I realized I had to add a / before root. Hope this helps someone else who has this problem.

---
Tags: godot
---


# Question
Title: When should Flow Variables be used in Unity Visual Scripting?
There are six types of variables in Unity's visual scripting. I'm not 100% clear on the difference between Graph and Flow Variables.

Here's the most extensive description of them that I've seen:

https://docs.unity3d.com/Packages/com.unity.visualscripting@1.7/manual/vs-variables.html

Currently I use Object Variables if:

* The data in them is tied to a specific Object
* I need the data to be persistent, so I can access it later.

I use Graph Variables if:

* I don't need the variable's data to persist.

I use Flow variables if I say have a loop, and need to increment some numbers in the loop.

I'd like to use Flow variables as often as possible, as I assume they have a lower memory footprint (perhaps not true?). The way I think about it is: a Graph Variable are local to a graph, and a Flow variable is local to a smaller subsection of the graph (as defined in the screenshot). Is that the correct way to think about Flow variables?

# Answer
In general, the lifetime of `Flow variables` is an execution process of UVS, or within the runtime of an event trigger.

I think to understand this, the most important thing is to understand what `Flow` is. UVS is not open source, we can't know its specific implementation, but we can guess some.

In `Bolt.Flow.Runtime.dll` we can find:

```
namespace Bolt
{
    public sealed class Flow : IPoolable, IDisposable
    {
        ...
        public readonly VariableDeclarations variables;
        ...
        public MonoBehaviour coroutineRunner { get; }
        ...
        public GraphStack stack { get; }
        ...
    }
}

```

In `Bolt.Core.Runtime.dll` we can find:

```
namespace Bolt
{
    public class Variables : LudiqBehaviour, IAotStubbable
    {
        public static VariableDeclarations Saved { get; }
        public static VariableDeclarations Application { get; }
        public static VariableDeclarations ActiveScene { get; }
        public static VariableDeclarations Graph(GraphPointer pointer);
        public static VariableDeclarations GraphInstance(GraphPointer pointer);
        public static VariableDeclarations Object(Component component);
        public static VariableDeclarations Object(GameObject go);
        public static VariableDeclarations Scene(GameObject go);
        public static VariableDeclarations Scene(Scene? scene);
        public static VariableDeclarations Scene(Component component);
        ...
    }
}

```

So Variables is a static utility class for UVS to get/set all types of variables. With other APIs and documentation, we can roughly guess the structure of the UVS runtime.

The USV runtime is essentially an interpreter for blueprints that relies on the Unity lifecycle. The `Script Machine` mounted on a Gameobject is responsible for monitoring Unity and user-defined messages and starting a new `Flow` run. `Flow` starts execution from the entry node that receives the event, finds all required parameters, executes the node itself, and proceeds to the next node. If another `Gragh` is called during the process, it is pushed onto the `GraghStack` to preserve the context, and returns to the original gragh after execution. If there are no subsequent nodes to execute, this time the Flow ends. It all happens *within one frame*.

An event triggers the Graph to run until the operation is completed, this is the lifetime of a Flow, and it is also the lifetime of the `Flow variable`. So in general, it's roughly equivalent to "temp variables".

BTW, I personally do not recommend using `Graph Variables`, I didn't find the `VariableDeclarations` structure in Graph. In fact, in practice I found that Graph Variables do not follow the Graph instance, but its assets file. After unity exits running, the variables generated will be saved in the file. This is very counter-intuitive and can lead to unexpected bugs.

I don't know if they fixed the bug, or I don't know if it's a bug at all. I choose not to use it anyway :)
> 1 votes

---
Tags: unity
---


title: 'Partial data load' terminology

text:
# Question
Title: 'Partial data load' terminology
I am writing up my work and I'm trying to think of a word, or phrase, that better describes a 'partial load' of data.

In my case, I have one very large file that is "environment A". To improve the handling of my data (and to stop my PC crashing) I only load a small section of this environment at once. I do not split the data into different files.

Is there a term that more concisely describes this technique of data handling rather than a 'partial load'?

# Answer
> 1 votes
It seems that the accepted term is `streaming`. But this term is too broad, you need to add additional keywords to search, such as `game map streaming loading`. This is an example of streaming. It emphasizes a continuous, smooth loading process.

Personally I prefer `lazy loading`. It emphasizes loading only when necessary.

Or `progressive loading`. It comes from web front-end development, implying different loading priorities and providing placeholders.

---
Tags: terminology, loading, data, file-format
---


# Question
Title: Is it a good idea to detect collisions in 2D game on different thread?
I am writing simple tiled map based game using LWJGL and Kotlin. I am testing out different collision detection algorithms and avoid using out of box solutions for personal reasons.

I figured out that running some kind of update loop, checking the presence of collisions between some entity and all the colliding objects may be too heavy in long run.

I want to know if some kind of collision detecting coroutine will be an appropriate idea. Since there be only one such coroutine that will only update the parameters that are sent to render loop, I should not be facing too many problems with race conditions. However, I am not sure that modern 2d games use similar approaches.

# Answer
Probably not.

In a game, we usually don't want collisions to be processed *eventually* — we want them processed *now*. We have hard time constraints: we want to integrate all object motion forward one time step, detect and resolve collisions, all in time to render the next frame, so that we don't render two objects wedged halfway through each other while waiting for the detection and resolution thread to get back to us.

Similarly, ensuring the collision results are up-to-date this frame lets us begin playing impact sound effects immediately, so they don't sound delayed and disconnected from the objects' motion, as well as triggering gameplay state changes like dealing damage or spawning impact VFX.

So the usual "put it on its own thread and let it run asynchronously" strategy we might use for other processor-intensive work is not a great fit here. We'd need to almost immediately wait on the final results from that thread to do the next step of our gameplay updates anyway.

If the main thread is stuck waiting on these results before it can kick off rendering, then it might as well be the one computing those results. Just putting that work on another thread doesn't make it go faster, and you'd want to explore algorithmic optimizations instead.

That is, unless you have a large volume of other work that does not depend on collision info or object positions/orientations/velocities that you can schedule in between handing off to the collision-checking thread and retrieving the results. But often, *most* of the heavy work in a game depends on these kinds of transformation or movement properties. So if you have work that's the exception to this rule, it might make more sense to offload *that work* to the other thread, keeping the mainline dependency of object transformations simpler (and cache-resident).

Threading of bulk work in games is increasingly moving toward "job system" approaches, where instead of one long-lived thread devoted to each system/process, with queues or locks coordinating between them, we have a pool of general-purpose worker threads. As we process each system, we divide up its work into hundreds of work units to divide between the worker threads like a parallel-for, then wait on the results before farming out jobs for the next dependent system. This looks less like two threads running in parallel, and more like a braid or rope of sequential update phases that fans out wide for each phase and knots back together at dependency links between phases.

For instance, you could have a collision broadphase job that detects sectors of your world with potentially colliding objects, and divides them into islands. Then you can farm out each island to the worker thread pool to process, then collate the results for your subsequent gameplay update and rendering jobs.

Now you don't have one thread computing all your collisions before you can do the next step, but a group of threads each computing just a subset of your collisions, reducing the start-to-finish latency.

This strategy also scales better to hardware with different numbers of threads available, vs. having a single collision thread that runs just as slow on a 32-thread chip as on a 2-thread.
> 1 votes

---
Tags: opengl, 2d, collision-detection, kotlin
---


# Question
Title: How to calculate Lv(Xp), Xp(Lv) and NextLvXp(Lv) generically?
XP tables are common, but level tables are unfeasible and formulas are also possible. Are principles known that can help implement a defined progression through relationships between level, total xp, xp to the next level, and others?

No need to consider gross innovations like non-integer levels and XP.

# Answer
> 1 votes
I understand that when the progression is defined consequently the XP table is too, even using an algorithm. Most common is to store the values initial character level `Lv` and initial character total XP `TotalXp` to update and calculate other things using the elementary "conversion from level to total XP" algorithm/formula/table (you called it `Xp(Lv)`).

We may have means of at least

1. convert Lv into minimum total amount of XP to have at least the level Lv (you called "Xp tables" but I'm calling it `Xp(Lv)`, right?)
2. and have (or calculate) the level that corresponds to the current total XP, that is, Lv such that `Xp(Lv) ≤ TotalXp < Xp(Lv+1)` (you called `Lv(Xp)`)

because with these you can get more data, like

1. \\$Xp\_{\_{ToNextLv}}(Lv)=Xp(Lv+1)-Xp(Lv)\\$,
2. \\$Xp\_{\_{RemToNextLv}}(TotalXp)=Xp(Lv(TotalXp)+1)-TotalXp\\$ and
3. \\$Xp\_{\_{OwnToNextLv}}(TotalXp)=\frac{100\\%\*Xp\_{\_{RemToNextLv}}(TotalXp)}{Xp\_{\_{ToNextLv}}(Lv(TotalXp))}\\$.

I think it's convenient to divide this question in two types of `Lv(Xp)` finding problems, the more conveniently expressed by tables and the more by formulas (finding `Xp(Lv)` formula too). Let's look at some algorithms options that do this.

### Solving with tables

If you have a table of minimum Xp per level, you have `Xp(Lv)` and the points are expected to increase with level, so a mere binary lookup algorithm solves the `Xp(Lv) ≤ TotalXp < Xp(Lv+1)` problem. On the other hand, if the problem is that you think it will be a waste of processing, you can take advantage of the fact that the table is fixed and this allows for some simplifications.

For example, if you have a total, non-negative amount of experience points called `Xp` and the five levels Xp table `[ Lv1⟼0 , Lv2⟼10 , Lv3⟼70 , Lv4⟼250 , Lv5⟼700 ]`, you know that

```
if Xp<10:
    Lv = 1
elif Xp<70:
    Lv = 2
elif Xp<250:
    Lv = 3
elif Xp<700:
    Lv = 4
else:
    Lv = 5

```

but can compare up to four times (for dozens of levels can do dozens of times) and binary do it this way (for many dozens doesn't eight times).

```
if Xp<250:
    if Xp<70:
        if Xp<10:
            Lv = 1
        else:
            Lv = 2
    else:
        Lv = 3
else:
    if Xp<700:
        Lv = 4
    else:
        Lv = 5

```

Also, if we assume that an integer access of a table, a constant power-of-two division and some other arithmetic operations are faster than a comparison with a flow control, we can take advantage of reading the cache at later positions in what will work as a short "level table" that will guide binary search steps with more agile operations.

Using the example again and assuming Xp doesn't exceed 700, so not 999, not 1024... but the variables can hold more than ten thousand, then setting the limitation 1024 to make `0 ≤ Xp < 1024`, `0 ≤ X ≤ 1024` and `i ∈ ℤ` we can enjoy the implication

\\$ Xp\<X \implies \\$

\\$ Xp+(1024\*i-X)\<1024\*i \implies \\$

\\$ \frac{Xp+(1024\*i-X)}{1024} \< i \implies \\$

\\$ t = \lfloor \frac{Xp+(1024\*i-X)}{1024} \rfloor \< i \\$

and we have `t=i-1` when `Xp<X` and `t=i` when `Xp≥X`. Using table constants with `1024*i-X` to simulate comparison and `i` as greater "next table index" or "level in the end", why not do it?

```
T = [ 2*1024-250 , 4*1024-70 , 6*1024-700 , 2*1024-10 , 3*1024-70 , 4*1024-250 , 5*1024-700 ]
t = 0

// if Xp<250: t = 1
// else:      t = 2
t = ( Xp+T[t] )/1024

// if Xp<250:
//     if Xp<70:  t = 3
//     else:      t = 4
// else:
//     if Xp<700: t = 5
//     else:      t = 6
t = ( Xp+T[t] )/1024

// if Xp<250:
//     if Xp<70:
//         if Xp<10:  Lv = 1
//         else:      Lv = 2
//     else:          Lv = 3
// else:
//     if Xp<700:     Lv = 4
//     else:          Lv = 5
Lv = ( Xp+T[t] )/1024

```

I see that it is even possible to do with one cell less, unifying the four and five indices (the two distinguish levels 3 and 4) and decreasing the following indexes. Also, the variable `t` can be used instead of `Lv` itself and starts at zero.

```
T = [ 2*1024-250 , 4*1024-70 , 5*1024-700 , 2*1024-10 , 4*1024-250 , 5*1024-700 ]

// if Xp<250: Lv = 1
// else:      Lv = 2
Lv = ( Xp+T[0] )/1024

// if Xp<250:
//     if Xp<70:  Lv = 3
//     else:      Lv = 4
// else:
//     if Xp<700: Lv = 4
//     else:      Lv = 5
Lv = ( Xp+T[Lv] )/1024

// if Xp<250:
//     if Xp<70:
//         if Xp<10:  Lv = 1
//         else:      Lv = 2
//     else:          Lv = 3
// else:
//     if Xp<700:     Lv = 4
//     else:          Lv = 5
Lv = ( Xp+T[Lv] )/1024

```

The greater is `T[2]=5444`. When the case is overflow, you can subtract an index proportion from the cells affected by a formula and add the index correction to it or even apply it to the formula below. For example, the first formula uses `[ 2*1024-250 ]` (why not subtract `1024`, will be lower than thousand), second uses `[ 4*1024-70 , 5*1024-700 ]` (why not `-3*1024`) and third `[ 2*1024-10 , 4*1024-250 , 5*1024-700 ]` (why not `-1024`), then...

```
T = [ 1024-250 , 1024-70 , 2*1024-700 , 1024-10 , 3*1024-250 , 4*1024-700 ]
Lv = ( Xp+T[0] )/1024
Lv = ( Xp+T[1+Lv] )/1024
Lv = 1+( Xp+T[3+Lv] )/1024

```

So we have from an Xp table an extracted Lv table and a calculation procedure. It would be interesting to make an algorithm that assembles the table and possibly the sequence of constants per instruction from the restriction.

**Questioner edit**: taking the idea, one more option is to use `Xp<X ⟹ Xp-X<0` assuming an unsigned overflow/carry subtraction when the index/level is lower (otherwise higher) or `Xp<X ⟹ Xp+( 2³²-X )<2³² ⟹ Xp+uint(-X)<0` assuming an unsigned overflow/carry addition when the index/level is higher (if not lower). We should handle indices differently and maybe it supports billions of points. It can be `ushort & 2^16`, `ulong & 2^64`, etc.

```
T = [ uint(-700) , uint(-70) , uint(0) , uint(-10) , uint(-250) , uint(0) ]
Lv = AddWithCarry(0,0, AddWithCarry(Xp,T[0],0).carry ).sum
Lv = AddWithCarry(Lv,Lv, AddWithCarry(Xp,T[1+Lv],0).carry ).sum
Lv = 1+AddWithCarry(Lv,Lv, AddWithCarry(Xp,T[3+Lv],0).carry ).sum

```

The first "flow control" (`index=0`) isolates

* `Lv∈{1,2,3,4}` (`index=(1)+0`) and
* `Lv∈{5}` (`index=(1)+1`, it would support `Lv∈{5,6,7,8}` with one more slot in the table),

the second (`index∈{1,2}`) isolates

* `Lv∈{1,2}` (`index=(3)+0`) and
* `Lv∈{3,4}` (`index=(3)+1`) and
* `Lv∈{5}` (`index=(3)+2`, would `Lv∈{5,6}` with no larger table)

and the last (`index∈{3,4,5}`) get the level. It considers the processors standard instructions optimized using (like add with carry and mov with offset).

Note that to keep the indices doubling and thus branching using parity (carry) on each descent we have to separate as many lower levels as possible (power-of-two) in the first indices and the others in the last ones so that they don't grow more than necessary, otherwise it requires more operations (to result adjusting). It builds a table that looks like a `-Xp` full search tree except `uint(0)` is like `-∞` and its slots spreads like "unary tree" (because don't need to branch off, only have same depth).

### Solving with formulas

Tables can structure progression exactly but they take up space and formulas can be fast and accurate enough, so they are options too.

The XP table `[ Lv1⟼0 , Lv2⟼10 , Lv3⟼70 , Lv4⟼250 , Lv5⟼700 ]` example has `Lv(-∞)=...=Lv(8)=Lv(9)=1`, `Lv(10)=Lv(11)=...=Lv(68)=Lv(69)=2`, `Lv(70)=Lv(71)=...=Lv(248)=Lv(249)=3`, `Lv(250)=Lv(251)=...=Lv(698)=Lv(699)=4` and `Lv(700)=Lv(701)=...=Lv(∞)=5`. It happens when

\\$ Lv(Xp)=\lfloor f( clamp( 9 , Xp , 700 ) ) \rfloor \\$,

\\$ 1 \le f(9) \< 2 \\$,

\\$\left\\{ \begin{aligned} 2 \le f(10) \< 3 \\ 2 \le f(11) \< 3 \\ ... \\ 2 \le f(68) \< 3 \\ 2 \le f(69) \< 3 \end{aligned}\right.\\$

\\$\left\\{ \begin{aligned} 3 \le f(70) \< 4 \\ 3 \le f(71) \< 4 \\ ... \\ 3 \le f(248) \< 4 \\ 3 \le f(249) \< 4 \end{aligned}\right.\\$

\\$\left\\{ \begin{aligned} 4 \le f(250) \< 5 \\ 4 \le f(251) \< 5 \\ ... \\ 4 \le f(698) \< 5 \\ 4 \le f(699) \< 5 \end{aligned}\right.\\$

\\$ 5 \le f(700) \< 6 \\$

or something like it, so generically rounding is necessary to omit progress between level numbers, `f` must map to values that make correctly `Lv` formula (for each valid `Xp` we have `Lv(Xp)≤f(Xp)<Lv(Xp)+1 ⟹ Lv(Xp)=⌊f(Xp)⌋` or `Lv(Xp)-0.5<f(Xp)<Lv(Xp)+0.5 ⟹ Lv(Xp)=⌊f(Xp)⌉` or something like) and can clamp.

Watch out for rounding errors. If you make `Lv(Xp)=⌊f(Xp)⌋` and try `f(10)=2` but code result is `f(10)=1.999999999999999778` (minus one bit) then `Lv(10)≠2`. Since `Lv(9)=1` and `Lv(10)=2`, is better to assume that the level transition experience points is between 9 and 10 (possibly `f(9.5)=2` or `(f(9)+f(10))/2=2`).

The most common is to use easily invertible functions and truncation (the same as rounding down for non-negatives), because defining one formula like this makes the other one obvious. For example, if you decided that `Xp(Lv)=10*(Lv-1)³` then `Lv(Xp)=uint( cbrt(0.1*Xp) )+1` (or better yet `Lv(Xp)=uint( cbrt(0.1*Xp+0.05) )+1` to avoid rounding error).

Another more usual thing is to set a formula and accept the consequent progression, but you can set progression and try to find some sufficiently precise formula with curve fitting, regression, etc. If you want `Lv(9.5)=2`, `Lv(69.5)=3`, `Lv(249.5)=4` and `Lv(699.5)=5` then can find

\\$ Lv(Xp) = \lfloor f(clamp(9,Xp,700)) \rfloor \\$

such that, for example,

\\$ f(Xp) = c\_0+^3\sqrt{c\_1+(c\_2+c\_3 Xp)^3} \\$

\\$\left\\{ \begin{aligned} f(9.5) = 2 \\ f(69.5) = 3 \\ f(249.5) = 4 \\ f(699.5) = 5 \end{aligned}\right.\\$

because

\\$ f^{-1}(Lv) = k\_0+^3\sqrt{k\_1+(k\_2+k\_3 Lv)^3} \\$

\\$\left\\{ \begin{aligned} k\_0 &= -c\_2/c\_3 \\ k\_1 &= -c\_1/c\_3^3 \\ k\_2 &= -c\_0/c\_3 \\ k\_3 &= 1/c\_3 \end{aligned}\right.\\$

and the solution is `{ c0≈-4.18488 , c1≈562.35163 , c2≈-7.05762 , c3≈1/53.70418 , k0≈379.02365 , k1≈-87102824.71339 , k2≈224.74532, k3≈53.70418 }`. Assuming just that, we have

\\$f(0) = 1.76669\\$
\\$f(9) = 1.98843\\$
\\$f(10) = 2.01148\\$
\\$f(69) = 2.99399\\$
\\$f(70) = 3.00597\\$
\\$f(249) = 3.99918\\$
\\$f(250) = 4.00080\\$
\\$f(699) = 4.99607\\$
\\$f(700) = 5.00393\\$
\\$f(\infty) = \infty\\$

and the graph of `Lv(Xp)` and `f(Xp)` is below.

Don't need to restrict `Xp≥9` in level formula, you can see, but we must to take a look at the XP formula and inverse of `f`.

\\$f^{-1}(1) = -24.10491\\$
\\$f^{-1}(2) = 9.50000\\$
\\$f^{-1}(3) = 69.50000\\$
\\$f^{-1}(4) = 249.49997\\$
\\$f^{-1}(5) = 699.49999\\$
\\$f^{-1}(\infty) = \infty\\$

To get the correctly result, the rounding is up or `k0` must plus one (i.e. one is added to the function result) to use truncation. Even so, `f(1)` is very wrong. We can use

\\$ Xp(Lv) = clamp(0, \lfloor 1+f^{-1}(Lv) \rfloor ,700)\\$

and the plotting of `Xp(Lv)` and `f⁻¹(Lv)` is below.

Since `Xp(Lv)` is multiple of 10 we can use

\\$ Xp(Lv) = 10\*trunc(f^{-1}(Lv)) \\$

with domain `{1,2,3,4,5}` and constants `{ k0=37.5 , k1=-64156.5 , k2=13.3 , k3=6.6 }`.

\\$f^{-1}(1) = -0.82135\\$
\\$f^{-1}(2) = 1.78756\\$
\\$f^{-1}(3) = 7.17327\\$
\\$f^{-1}(4) = 25.83881\\$
\\$f^{-1}(5) = 70.24065\\$
\\$f^{-1}(\infty) = \infty\\$

Finally, if we don't get sufficiently accurate results we can adjust to make `Lv(Xp(Lv))=Lv` (and using some root-finding algorithms, possibly) if level function is exact. For example, if inverse of `f` is such that

\\$f^{-1}(1) = -1.2\\$
\\$f^{-1}(2) = 1.8\\$
\\$f^{-1}(3) = 6.8\\$
\\$f^{-1}(4) = 25.2\\$
\\$f^{-1}(5) = 69.8\\$
\\$f^{-1}(\infty) = \infty\\$

then truncation can be the correct value or its predecessor, so we can see if current `Xp(Lv)` result is such that `Lv(Xp(Lv))=Lv`, otherwise (`Lv(Xp(Lv))<Lv`) we threat as if truncation value is incremented.

\\$ Tmp\_{Xp} = Tmp\_{Xp}(Lv) = 10\*trunc(f^{-1}(Lv)) \\$
\\$ Xp(Lv) = \left\lbrace \begin{array}{ccc} Tmp\_{Xp} & Lv(Tmp\_{Xp}) = Lv \\ Tmp\_{Xp}+10 & otherwise \end{array}\right.\\$

# Answer
> 1 votes
> level tables are unfeasible

Why? When you have a level-to-exp table, then you also have a sorted exp-to-level table. Just fill it with the cumulative exp values, and not just the exp values to get from the previous to the next level. And if you don't want that, you can easily create that data at runtime. And it's already sorted, so if you want to derive the level from the exp, you just need to do a binary search.

I am a big fan of level tables, because even if your design document defines the exp curve by some complicated formula, a table that's hardcoded or read from a configuration file allows you to slightly fudge the numbers to make them more aesthetical. So instead of a level requiring 50,102 exp, you round that to 50,000 exp. It makes almost no difference gameplay-wise, but just looks a lot better in the UI and feels more accessible to the player.

---
Tags: mathematics, progression
---


# Question
Title: Character still plays death animation after respawning
My character dying animation works and when the character lies on the ground, text appears saying "Wasted". I added an object and it respawns.

The main problem is that although he respawns, the character still plays the death animation on the ground after respawning in the new location, as shown in the animation below:

```
using UnityEngine;
using DG.Tweening;
using UnityEngine.UI;
using UnityEngine.SceneManagement;

public class Health : MonoBehaviour {

 public float curHealth;
 public float maxHealth;
 public bool enemyDied = false;
 private Animator anim;
 public Slider healthBar;
 private ThirdPersonCharacter thirdPerson;
 private void Start()
 {
     curHealth = maxHealth;
     healthBar.minValue = 0;
     healthBar.value = curHealth;
     healthBar.maxValue = maxHealth;
     anim = GetComponent<Animator>();
     thirdPerson = GetComponent<ThirdPersonCharacter>();
 }
 void Update()
 {
     float hit = anim.GetFloat("hit");
     if (hit > 0)
     {
         hit -= Time.deltaTime * 3;
         anim.SetFloat("hit", hit);
     }
     if (curHealth < 1)
     {
         Physics.SyncTransforms();
         anim.SetBool("death", true);
     }
     if (Input.GetKeyUp(KeyCode.Space))
     {
         SendDamage(Random.Range(10, 20));
     }
 }
 public void SendDamage(float damageValue)
 {
     curHealth -= damageValue;
     healthBar.value = curHealth;
     if (curHealth <= 0)
     {
         enemyDied = true;
     }
     Invoke(nameof(Resurrect), 2f);
     anim.SetFloat("hit", 1);
 }
 public void Resurrect()
 {
     SpriteRenderer blackout = Camera.main.transform.GetComponentInChildren<SpriteRenderer>();
     Color orjinalRenkWasted = blackout.color;
     Color clrWhitealpha0 = new Color(1, 1, 1, 1);
     Color clr = new Color(0, 0, 0, 1);
     blackout.transform.GetChild(0).GetComponent<SpriteRenderer>().DOColor(clr, .5f).SetDelay(2f).OnStart(() =>
     {
         blackout.DOColor(clrWhitealpha0, .5f).SetDelay(.5f).OnComplete(() =>
         {
             Invoke(nameof(BringEverythingBack), 2f);
             blackout.transform.GetChild(0).GetComponent<SpriteRenderer>().DOColor(new Color(0, 0, 0, 0), .5f).SetDelay(2.5f).OnStart(() =>
             {
                 blackout.DOColor(orjinalRenkWasted, .25f);
             });
         });
     });
 }

 void BringEverythingBack()
 {
     transform.root.position = GameObject.FindGameObjectWithTag("Respawn").transform.position;
 }

```

# Answer
> 1 votes
In your `BringEverythingBack()` method, you should add code to do the following things:

* Force the state machine of the animator back to the default state of your animation controller with the `anim.Play(stateName)` method. You could also do this with transitions as DMGregory suggested in a comment on the question. But I would recommend to just use Play in this case. One reason is because later you might want to use the same method to respawn the character while they are in a completely different animation state. So you would have to create transitions from every possible state back to the default state. Also, the reason you usually use transitions is because they allow you to gradually blend from one animation to another. When the player respawns, you usually don't want to do that. You want them to appear in the default pose immediately. And that's exactly the behavior you get with Play.
* Clear the die-flag on the animation controller by setting `anim.SetBool("Die", false);`. Otherwise the animation controller will probably transition right back into the death-animation.
* Refill the character's health with `curHealth = maxHealth`, so they don't immediately die again.

---
Tags: unity, c#, animation
---


title: Cue ball direction after collision

text:
# Question
Title: Cue ball direction after collision
I am trying to figure out the velocity of ball A after collision, which is V2.A as seen in the figure. I know that the velocity of ball A is perpendicular to the line connecting centre of ball A and B when the collision occurs.

(Image taken from: http://www.real-world-physics-problems.com/physics-of-billiards.html)

The issue is, my V2.A is sometimes flipped in the opposite direction, and I can't seem to figure out the issue here. Here's my V2.A calculation

```
Vector2 diff = (b - a).normalized;
Vector2 perpendiular = Vector2.Perpendicular(diff);

```

# Answer
> 2 votes
See Vector2.Perpendicular:

> Returns the 2D vector perpendicular to this 2D vector. The result is always rotated 90-degrees in a **counter-clockwise direction** for a 2D coordinate system where the positive Y axis goes up.

In this case, just judge whether the unsigned angle between the velocity vector of ball A and the result vector is greater than 90 degrees:

```
Vector2 diff = (b - a).normalized;
Vector2 perpendiular = Vector2.Perpendicular(diff);
if (Vector2.Angle(directionOfA, perpendiular) > 90)
{
    perpendiular = -perpendiular;
}

```

# Answer
> 2 votes
You can also treat this as a vector projection.

```
Vector2 collisionAxis = (b - a).normalized;

// Get the component of the velocity vector pointing into B.
float parallelSpeed = Vector2.Dot(collisionAxis, velocityA);

// Subtract that component to leave only the portion perpendicular.
Vector2 remainingVelocity = velocityA - collisionAxis * parallelSpeed;

```

This method works without computing an angle or branching.

---
Tags: unity, physics, collision-resolution, linear-algebra
---


title: Rotate FPS Controller without Mouse

text:
# Question
Title: Rotate FPS Controller without Mouse
I'm trying to set up a game with portals in it. I've been struggling for a while now to rotate the Player. I've tried Quat.Slerp, Quat.AngleAxis, and Quat.Euler. But through rigorous testing I discovered that the MouseLook function in my FPS Controller script is the reason the Player isn't rotating. The player is being rotated, but half a frame later, the MouseLook script resets the Player's rotation.
How can I rotate the player without letting the MouseLook function of my FPS Controller script get in the way?

```
void MouseLook()
{   mouseX = Input.GetAxisRaw("Mouse X") * sensX * Time.deltaTime;
    mouseY = Input.GetAxisRaw("Mouse Y") * sensY * Time.deltaTime;

    yRot += mouseX;    xRot -= mouseY;
    xRot = Mathf.Clamp(xRot, -50f, 50f);
    transform.rotation = Quaternion.Euler(xRot, yRot, 0);
}

```

# Answer
These lines

> ```
> yRot += mouseX;
> xRot -= mouseY;
>
> ```

Are saying "Take the previous rotation values from mouse movement and add the latest mouse movement to them"

Which is then applied by this line:

> ```
> transform.rotation = Quaternion.Euler(xRot, yRot, 0);
>
> ```

The easiest option would be to rotate the player by changing `xRot` and `yRot`, so the next time `MouseLook()` is called, it's taking your manual rotation into account.

Failing that, you could either read the current rotation (might become complex if the player is ever non-vertical) or having another variable to track manual rotation separately from mouse rotation and sum the two together when setting `transform.rotation`
> 0 votes

# Answer
It looks to me like you want to update your FPS Controller script with a public method something like this:

```
public void RotateCameraToFace(Vector3 direction) {
    Vector3 d = direction.normalized;
    xRot = Mathf.Asin(-d.y);
    yRot = Mathf.Atan2(d.x, d.z);
}

```

This updates the internal angle-tracking variables so they'll produce an orientation that looks along `direction`.

If you have your desired orientation as a quaternion, you can call `controller.RotateCameraToFace(orientation * Vector3.forward)` to use this same code.

You could also try unpacking `xRot` and `yRot` from `orientation.eulerAngles`, though I wouldn't recommend it. You can get some awkward wrap-around cases when using computed Euler angles as input for another computation, so my standard practice is to compute the angles myself in a way I can control and verify has wrap-arounds handled in a way that works for my use case.
> 0 votes

---
Tags: unity, rotation, first-person-shooter
---


title: Scaling Weighted Loot Table

text:
# Question
Title: Scaling Weighted Loot Table
I'm working on an astroid mining game where there's the player controlled ship that can split astroids into smaller ore chunks to then collect and bring back to a base station for processing. I'd like to have a percent composition for these astroids that provides a weighted loot drop table for what ores each astroid drops when split by the player. In addition to this, I'd like to be able to shift the weights of the drops in the table based on the distance the player is from the base station. For example:

```
Near to Base Station
IRON - 0.80
SILVER - 0.15
GOLD - 0.05

Far from Base Station
IRON - 0.50
SILVER = 0.30
GOLD - 0.20

```

It'd be simple to create multiple drop tables with these values preset, however I'd like to interpolate the values and change them relative to the distance the player is from the base station. What would be a good approach to achieving this behavior?

# Answer
Sounds like you can do exactly what you said: dynamically make a new table by interpolating between the min & max tables.

Example:

```
double[] nearTable = new double[] { 0.80, 0.15, 0.05 };
double[] farTable = new double[] { 0.50, 0.30, 0.20 };

double minDist = 10;
double maxDist = 110;

double currDist = 60;

if (currDist < minDist)
    currDist = minDist;
if (currDist > maxDist)
    currDist = maxDist;

double percentage = (currDist - minDist) / (maxDist - minDist);

double[] table = new double[nearTable.Length];

for (int a = 0; a < table.Length; a++)
    table[a] = nearTable[a] + (farTable[a] - nearTable[a]) * percentage;

```
> 0 votes

---
Tags: game-design, algorithm
---


title: Align Relative Portal Camera Position

text:
# Question
Title: Align Relative Portal Camera Position
I've been having a bit of trouble with this small piece of code. To set my relative PortalCam position, I first take the *distance* and *angle* from the Portal and Player Cam. Then apply the *distance* and *rotation* to my OtherPortal to get the PortalCams position.

Desmos link to all the maths

```
float newX, newY, newZ;
float d;    // Distance between Portal and PlayerCam
float phi;  // Angle between Portal and PortalCam
            // Angle between Portals
float delta = Quaternion.Angle(portal.rotation, otherPortal.rotation);
d = Mathf.Sqrt( (playerCam.position.x - portal.position.x)^2 +
                (playerCam.position.z - portal.position.z)^2 );
if(playerCam.position.x >= portal.position.x)
    d = -d;
phi = Mathf.Atan( (playerCam.position.z - portal.position.z)
                / (playerCam.position.x - portal.position.x) );

newX = otherPortal.position.x - d*Mathf.Sin(phi - delta);
newY = playerCam.position.y + otherPortal.position.y - portal.position.y;
newZ = otherPortal.position.z + d*Mathf.Cos(phi - delta);
transform.position = new Vector3(newX, newY, newZ);

```

My problem is that, while this works perfectly when the portals are at 90degrees to each other. The code seems to fail when the portals are in-line.
Is there a mistake in my math? In my code? How can I best fix this bug?

# Answer
> 0 votes
Myself, I'd skip the manual math and use Unity's built-in transformation functions for this.

```
const Quaternion FLIP = Quaternion.Euler(0, 180, 0); // (0, 1, 0, 0)

void CrossPortals(Transform subject, Transform entrance, Transform exit) {
    // Map subject position into "entrance portal space" coordinates.
    Vector3 entrancePosition = entrance.InverseTransformPoint(subject.position);

    // Here I assume both portals face "outwards",
    // so "into" the entrance portal needs to be rotated
    // to map to "out" of the exit portal.
    Vector3 exitPosition = FLIP * entrancePosition;

    subject.position = exit.TransformPoint(exitPosition);

    // Order matters here (read from the end, back toward the beginning).
    Quaternion relativeRotation =
            // 3. Apply exit portal's orientation.
            exit.rotation
            // 2. Account for portals facing opposite directions.
            * FLIP
            // 1. Express orientation in entrance coordinates.
            * Quaternion.Inverse(entrance.rotation);

    subject.rotation = relativeRotation * subject.rotation;
}

```

---
Tags: unity, position, portals
---


# Question
Title: How to get my node to only execute _process_physics when the game is NOT paused and never in the editor?
I have implemented a simple "rocket" in 2D, it accepts UP and DOWN for acceleration and left/right for rotation. The implementation looks like this:

```
void Player::_physics_process(double delta)
{
    UpdateMotionFromInput(delta);
    set_velocity(motion);
    set_rotation(rotation);
    move_and_slide();
}

void Player::UpdateMotionFromInput(double delta)
{
    const Input* i = Input::get_singleton();

    double delta_v = 0;
    if (i->is_action_pressed("ui_up"))
        delta_v += acceleration * delta;
    if (i->is_action_pressed("ui_down"))
        delta_v -= acceleration * delta;
    if (i->is_action_pressed("ui_left"))
        angular_velocity -= angular_acceleration * delta;
    if (i->is_action_pressed("ui_right"))
        angular_velocity += angular_acceleration * delta;

    constexpr float pi_factor = 360.0f / 3.14f;

    rotation += angular_velocity * delta;
    angular_velocity -= SIGN(angular_velocity) * angular_dampening * delta;

    Vector2 newVec(0, -delta_v);
    motion = motion + newVec.rotated((float)(rotation));
}

```

Now the problem is, this still works even in the editor - if I press the arrows the rocket will start flying around my editor. There's a Process option in the node component, but that does not really work for me, for the given options, I am getting these results:

1. When paused, Disabled - doesn't do anything ever.
2. Inherit, Pausable, Always - always executes `_process_physics`

I want to process physics when the game is run, not when I'm in editor. How can I do that?

# Answer
> 3 votes
As you are aware, the Pause Mode lets you control when the code runs with respect to, well, the pause.

But that is not about whether the code runs in the editor... For that look for the property `editor_hint` of the `Engine` singleton. The getter is `is_editor_hint`, which will be `true` on the editor. You can check `editor_hint` during initialization, and then call `set_physics_process` with `true` or `false` if you want it to be able to run or not.

---
Tags: c++, godot
---


# Question
Title: World space inspector position not matching transform.position
I've seen questions like this that usually end up with the OP having confused localposition and world position. This is not the case.

My enemy is animated. He holds a gun. This gun has a child, called "shootpoint" which is where the bullet comes from.

When firing, I instantiate a empty gameobject at this shootpoint. Using the shootpoint's transform.position. The enemy is stood on the ground, so the shootpoint position is pretty low.

Here is the code that I am using to instantiate this.

```
GameObject g = new GameObject();
g.transform.position = bulletSpawnPoint.position;

```

This object (and the weapon's bullets) appear very high up. Far away from the position. Attached is a image, showing the point that the bullets (and the gameobject) are coming from. Selected, is where they should be coming from. They are instantiated in world space, using its transform.position. Here is a image.

Unity is bugged. I have no idea what to do now. How would I even fix this? Could it be the animator? Why doesn't it line up?

# Answer
Turns out, I fell for the classic "the object referenced is actually the prefab, and not the actual instantiated object" gag.

I did not actually state "hey, the current weapon is the actual instantiated one, not the prefab" after instantiating the weapon.
> 1 votes

---
Tags: unity
---


# Question
Title: How to identify classes with their namespace in the Unity editor?
It's always a good idea to separate code sections with namespaces and based on that you can have many classes with the same name.

The problem is that in Unity when you want to add a class as a component or somewhere else, it doesn't show namespace info. So probably devs make mistakes.

Is there a way around it or some editor extensions?

# Answer
Here's a cheeky workaround you can use.

First we define an empty struct, so it doesn't actually increase the memory allocation of our components:

```
[System.Serializable]
public struct NamespaceHint
{
}

```

Then we give it a `PropertyDrawer` (placed in a folder called "Editor") that prints out the fully-qualified name of the component it's attached to:

```
[CustomPropertyDrawer(typeof(NamespaceHint))]
public class NamespaceHintDrawer : PropertyDrawer
{
    public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
    {
        var t = property.serializedObject.targetObject.GetType();
        EditorGUI.LabelField(position, t.FullName);
    }
}

```

Then for any type that's ambiguous, we can add a little hint at the top of the inspector:

```
namespace Player
{
    public class Controller : MonoBehaviour
    {
        [SerializeField] NamespaceHint _ns;

        // ... other members...
    }
}

```

And now two identical components in different namespaces are distinguishable in the Inspector.

You could also do this manually with a `[Header("Player.Controller")]` attribute if you don't need it to automatically adapt to name changes.

Unfortunately, you still have to guess and check when selecting them from the Add Component menu:

To fix that, you can add an AddComponentMenu attribute to the top of your class to change its label/sorting in the add component menu:

```
[AddComponentMenu("Scripts/Player Controller")]
public class Controller : MonoBehaviour {
// ...

```

...but that one would need manual updates if you change your naming scheme.

---

But note how much better this looks and how much easier we can get it if we **just give classes unique names** to begin with:

```
namespace Player {
    public class PlayerController : MonoBehaviour {
    // ...

```

Boom. We can tell them apart in the inspector and component selection menu, and we don't need any extra boilerplate at the top of the script, so it's even less to type! The only downside is a slightly longer component name / more redundant-looking fully qualified name to reference in scripts: `Player.PlayerController`.
> 4 votes

---
Tags: unity, c#
---