# Question
Title: Direct3D 11 : Vsync to 60 fps not matter the monitor refresh rate
I am working with Direct3D 11 and I am trying to figure out how to make my game run at 60 fps. Currently I use :

```
swapChain->Present(1, 0);

```

To max the fps with Vsync. This only works because my monitor is 60hz though. As I understood it, the first parameter of Present is used to divide the current screen's refresh rate to obtain a certain fps. So I can get 60fps by setting this to 2 on a 120hz monitor or even 4 on future 240hz monitor and so on.

My problem is this : what do I do with 144hz monitors? Is there any way to get 60fps vsync on those monitors?

# Answer
> 2 votes
Vsync, like Sleep, is a terrible way of controlling frame rate, because (and also like Sleep) controlling frame rate is not it's primary purpose but a fortuitous side effect of it's primary purpose. Sleep is prone to different clock resolutions and vsync is prone to different refresh rates.

If you break it down, your problem is not that you want to vsync at 60fps; it's that you want to run at a fixed 60Hz timestep instead. So don't use vsync or Sleep for this, Fix Your Timestep instead: https://gafferongames.com/post/fix\_your\_timestep/

Afterwards, if you wish to reduce CPU usage use Sleep, if you wish to avoid screen tearing use vsync. But unfortunately there is no one solution that reliably does all three on all hardware.

---
Tags: c++, graphics, directx11
---


# Question
Title: How and when should I update events occuring after a while?
This question is not language specific but a more generic approach on how to deal with lazy updates for some game variables.

Let's say, for instance, that I want to implement a "*character age system*" for a game.

I guess that the "age" attribute does not need to be updated 60 times per second for each of my 10.000 or so RTS/MMO characters.

So, how to implement in the game loop the update of this "long term" variables that may have it value changed very sparsely?

At the moment, I would implement some global variables to accumulate the delta time between the frames until it reaches a certain value, then, it resets and updates that variables.

Is that correct? I mean, that's how things work? Or depending on the language/plataform you would set some timers, or events that trigger the update of these variables?

# Answer
Another approach for handling events on a larger time scale is using a Heap. In short, a Heap is a binary tree that always brings the largest or smallest item to the top.

If you maintain a min-heap (smallest at the top) of events, compared by the time the event is meant to occur (game time triggered + time until event), then on each update cycle you need only check the root the heap. If that event should occur, then trigger it, and check the next events in the heap. Trigger each if needed, remove all triggered events, and then restore the heap.

While many of the other answers are better for specific situations, this can be applied as a more general solution.
> 6 votes

# Answer
Store your birthday and **calculate your age on demand.**

When I buy alcohol the shopkeeper sometimes checks my ID to make sure I am not underage. However, my ID card doesn't have my actual age, and I don't have to update it every year. Instead, it shows my birthday, and the shopkeeper compares that date to the current date to calculate my actual age.

This is the same thing you can do in your game, but instead of birthday and the current date, it will probably be a game time counter. It's a common way to implement timed events.

Similarly, you can pre-calculate the result to make the comparison cheaper. For example, I always forget various anniversaries of family members because I'm an imperfect human being. Instead, I calculate the next anniversary and mark it in a calendar. Then I can check the calendar every day, and see if there's an anniversary. You too can do this for your game, if your timed events have expensive calculations.
> 7 votes

# Answer
**Non-Real-Time Variables**

Some variables don't need to be calculated real-time, those will include a lot of stuff, from deadlines to stuff like age and from how many players are in the game to how many gold you have in your bag. Even some variables that seem to be updated real-time are actually just updated when they need to be (see hit points example down below).

**Calculate On Demand**

Your gold, for example, is only ever updated when you spend it or get more added to it. The number of players in a server is only ever updated if a person joins or leaves the server.

The age of a player's character should only ever be updated if it is shown on the screen, in other words, when the player opens his character sheet. So, if a player wants to see his updated age, he will have to close and re-open the character sheet if it's already open.

Even stuff like hit points or mana need only ever be updated if they're changed. In games that do not have regeneration, it would be a waste to update the hit points every frame. Even in games that do have regeneration, it's still a waste to update it every frame, every second would be more than enough.

This is all to avoid heavy CPU usage.

**Delegate To The Client**

As an example, in a game like FarmVille, there are many timers and many times more players and it's impossible to do all the timers real time on the server side. So, the server sends when the timer will end to the player' computer (the client). The client will handle the calculations, and when the timer ends, it will send a request to the server and the server will either approve it or reject it. Usually rejection means the client's timer ended too soon and the server will most likely send a new timer value or delay the action if it's just a few seconds.
> 3 votes

---
Tags: game-loop
---


title: Save game feature in SDL 2?

text:
# Question
Title: Save game feature in SDL 2?
I am making a 2D action-adventure platformer video game using the C++ computer programming language and the Simple DirectMedia Layer 2.0 (SDL 2.0.5) development library.

So far I have created over 50 levels, added enemies (with A.I.), assigned controls, animations, and of course, added the player.

As you know one of the most important features of a video game is the game save feature, in which the game software actually stores the data in the computer memory.

Is there any way to add this feature to my game using SDL 2? If so, please answer in detail with the nessecary code.

Thank you. You have been the most helpful.

Here are the items I'm using:

* Microsoft Windows 10 (O.S.)
* Microsoft Visual Studio Community 2017 (I.D.E.)
    + VSX 17 C/C++ Compiler (Compiler)
    + C++ (Programming Language)
    + Simple DirectMedia Layer 2 (Version 2.0.5) (Development Library)

Thanks again.

# Answer
> 3 votes
You can either write your own save format and save file reader & writer, or use an existing parser like an XML or JSON one. You can store the save data in a `GameSave` class at runtime either as a tree of the file format you chose, or inside direct member variables. I myself us the latter, as then it's easier to save data (while reading becomes a bit more tricky). It also abstracts setting of the save data with the writing of the save data.

```
class GameSave
{
public:
    GameSave() { }
    GameSave(const std::string& filename)
    {
        // Load save data...
    }

    void Write(const std::string& filename)
    {
        // Write save data...
    }

    std::string CurrentLevel;
    std::vector<std::pair<std::string, int>> Inventory;

    // More save data...
protected:
private:
}

```

Here's a very basic example of what your save class could look like. The details or writing and loading and the filename management depends on if you want to support multiple saves or not, and if you want to predefine a few save slots or allow the player to chooce their own filenames etc.

So, when the player saves the game, you need to write the required data to the file. This can be done in a few ways: you could ask each object to save its own data to the file, or you could have a parent object (like your level / gamestate) save the required data. Since your data needs seem quite small, I'd go with the latter option and write something along the lines of:

```
void GameplayState::SaveGame()
{
    GameSave save;

    save.CurrentLevel = m_Level->GetName();
    Player* player = m_Level->FindPlayerEntity()->GetLevel();
    save.PlayerLevel = player->GetLevel();
    for (InventoryItem* item : player->GetInventory()->GetItems())
        save.Inventory.push_back(std::make_pair(item->Name, item->Amount));

    save.KilledEnemyCount = GameStatManager::KilledEnemyCount;

    save.Write(AskPlayerForSaveSelection());
}

```

Finally, to continue from a save, you just have to load the data in and pass it to the correct owners. This could be done by passing the whole `GameSave` around, or simply by passing the required members of the save to the constructors/methods.

```
void GameplayState::Continue(GameSave* save)
{
    // Use save data:
    m_Level = new Level(save->CurrentLevel);
    m_Level->CreatePlayer(save->PlayerLevel, save->Inventory);
}

```

This is the basic high-level architecture of a basic game save setup that I've found that worked well enough for me, when the data that I need to save is quite small and can be handled as such. Were you need more data and more dynamic data, then you'd have to start assigning unique identifiers to objects and allowing each object to save/load its own data.

---
Tags: c++, windows, sdl2, savegame
---


title: Implementing a scrolling UI in Libgdx

text:
# Question
Title: Implementing a scrolling UI in Libgdx
I am using the LibGDX framework. I'm not using Scene2D but I want to implement my own "scrolling UI". This is only what I could think of (see image below):

I will make the 2nd camera look at very far coordinates (and draw the UI stuff there) and have it (within the blue box) receive its own input. But I think this is not possible with LibGDX, since if you set the size of the camera you are like setting how big it views the world and not how big the viewport is. I mean you can't set the size of the camera of something like 50px width and height and have it place on the center. If you setPosition, you are setting it to where it looks at and not where it is placed in the 2D space. I'm trying to explain it clearly and I hope it is clear.

# Answer
> 0 votes
Since you are using 2 cameras for each separate area you can split the input for each area using an input multiplexer. Now you can have one input processor for the main camera and one for the UI. Then its simply a case of responding to mouse drag events in the UI processor and if the event is not in the UI area you return false in the input processor method to signify that this processor did not process the event and it needs to be passed to the next input processor(main camera input processor) in the multiplexer chain.

**Example**

```
import com.badlogic.gdx.InputProcessor;

public class UIInputProcessor implements InputProcessor{

    @Override
    public boolean touchDragged(int screenX, int screenY, int pointer) {
        if(screenX >= 50 && screenX <= 100
                && screenY >= 50 && screenY <= 150 ){
            // I assume the sreen UI window is 50px x 100px with its lower left corner at 50,50

            //TODO respond to UI events

            return true; // this event has been processed so respond true so events do not get passed to next input processor
        }

        return false;
    }

    //.. some events removed for clarity

}

```

**Main Input Processor**

```
import com.badlogic.gdx.InputProcessor;

public class MainInputProcessor implements InputProcessor{

    @Override
    public boolean keyDown(int keycode) {
        //  input events for main area
        return false;
    }

    //.. some events removed for clarity

    @Override
    public boolean scrolled(int amount) {
    //  input events for main area
        return false;
    }

}

```

**Game/Screen Class**

Using 2 normal InputProcessors

```
  MyProcessor = new InputMultiplexer(new UIInputMuliplexer(), new MainInputProcessor());

```

Or if you use scene2d stage

```
MyProcessor = new InputMultiplexer(MyStage, new MainInputProcessor());

```

**Camera** Now you need to make 2 cameras. One for the main area and one for UI

This example is adapted from How to implement 2 cameras in a unique stage using LibGDX

```
mainCamera = new OrthographicCamera(GAME_WIDTH,GAME_HEIGHT);
mainCamera.position.set(GAME_WIDTH /2, GAME_HEIGHT /2, 0);
mainCamera.update();

secondCamera = new OrthographicCamera(UI_WIDTH,UI_HEIGHT);
secondCamera.position.set(UI_WIDTH /2,UI_HEIGHT /2, 0);
secondCamera.update();

```

In your render method you would add

```
//For the main cam
Gdx.gl.glViewport(0,0,GAME_WIDTH, GAME_HEIGHT); // set viewport to full screen
batch.setProjectionMatrix(mainCamera.combined);
batch.begin();
    // draw main screen items
batch.end();

//For the UI cam
Gdx.gl.glViewport(100,100,300, 400); // set smaller region for UI
batch.setProjectionMatrix(secondCamera.combined);
batch.begin();
    // draw UI items
batch.end();

```

The important bit being the glViewport which sets which part of the screen to draw to.

---
Tags: libgdx, camera, ui-design, scrolling
---


# Question
Title: Will the inclusion of LGBT characters in my game detract from possible sales?
As we all know, the inclusion of LGBT characters has been a mighty controversial topic in recent film and literature (Beauty and the Beast probably being the premier example). Some love it with *every fiber of their being*, while others *absolutely detest the very thought of it*. Now, keep in mind that ***I am not here to start a political firestorm*** nor am I here to preach my own personal beliefs regarding this, I'm simply asking the question: *will the inclusion of LGBT characters decrease potential sales?*

In our game, a pseudo-'90s JRPG, one of our main story writers added two consuls (of a civilization with heavy Roman influence, but with different laws), both female, married. Originally hailing from an area in which LGBT relationships are looked down upon, I was quick to note that it may be *too much controversy*, but it truly depends on where you live—for him it was almost completely normal.

As I see it, we have three choices.

* We can keep the characters just as they are.
* We can keep the characters, but only imply their relationship.
* We can alter the relationship entirely, changing one to a male.

Right now, our main goal is to satisfy the general public while still strongly appealing to those who actually played JRPG's such as *Dragon Quest* or *Final Fantasy* back in the day. Which of these three options should we choose to best enhance our sales, or, if it's not up there, what is the wisest way to go about doing this? ***I am looking for facts and data if possible and/or applicable***.

EDIT: Our target audience is Everyone! Like we said, we’re aiming to *satisfy the general public* while still appealing to those who played JRPG’s back in the ‘90s.

EDIT II: Wow. Every almost answer here contained a *wealth* of information, and I'd like to formally thank all that contributed. I will be using the information from just about all of these answers, and I'm sure may others facing this issue may as well.

EDIT III: If you have comments that aren’t answers or you’d like to further discuss this, please refer to the official chat room as opposed to commenting. Thanks!

# Answer
> 68 votes
I come from a place in the Internet most people deem to be horrible in every single way. While I generally don't agree with most of the stuff said in that website, I can provide some insight on what happens around there when a pro-LGBT game is released.

* A small but very vocal group of (probable) trolls will complain about it, no matter the way they are depicted, under the argument that it's "degenerate", "pozzed" and a thousand other descriptors usually containing the word "cuck" in them. They swear they won't ever buy the game because of these small details, and will generally attempt to derail any serious discussion about the game, but they are a really tiny percentage of the population that just happens to invade any threads made about games like these.
* Some users, the less sarcastical version of the above, will automatically qualify whether it's cute or "degenerate" exclusively depending on whether the game was made in Japan or not. It's as dumb as arbitrary, but they are somewhat grounded in reality considering the vast majority of Japanese depictions of LGBT people is very different from the vast majority of their western counterparts.
* Some users will only care about whether the girls and the relationship are cute and whether it comes of as preachy or not.
* Some users will only care about whether the game presents this plot point as preachy or very "in your face". Probably the biggest demographic around these places.

Some research on Gamergate and its slow declive into the alt-right should give some light on the above positions, but the general idea is, they are tired of games being marketed on their "progressiveness", which usually tends to overinflate their scores in game journalism sites even though the games are not that good (in the case of Gone Home, some people don't even consider it a game, yet it managed to score a 10/10 in many reviews, which didn't sit well with many gamers). This resulted in an influx of games with progressive values being thrown in your face in the most preachy and obnoxious way possible just to achieve "brownie points" in attempts to replicate the success of previous games who did this, something they didn't like because it went against their beliefs and political stances. This may seem inmature, but nobody likes to feel like the games they are playing are going directly against them, so it is kind of logical to expect such an outcome.

Thing is, these gamers are very wary of these topics because they feel "stiff" and "fake", as in, so shoehorned it becomes obvious the devs are trying to virtue signal in hopes their game gets noticed by the games journalism crowd. Most of the LGBT character depictions shown on many recent games seem to default to the "accepted" representations of their gender or sexuality (how many characters would describe "strong independent lesbian woman who needs no man, is snarky towards everyone, always looks angry and has short hair", despite that description being very specific?), so many of these characters end up having the same personalities, same background and sometimes even same questlines, which to these people smells like mass produced token LGBT. The queer characters are often presented as borderline Mary Sue saints who could do no wrong, but are always wronged by (most of the time, and I think this is your game's case as well) white cishet males just because they are hateful mysoginistic beings or something like that, even when they are not. Queer people are still people after all, so they should probably have as many flaws as the non-queer people, and you should contemplate that into writing them as actual characters and not "that lesbian couple" in that game.

But people will always find a way to complain. This is a "damned if you do, damned if you don't" situation in which incorporating LGBT characters or not, making them flawed or not, making it an extremely secondary trait or their whole personality, making them evil or good, making them stereotypical or not, will result in outrage from certain demographics. My advice is, just do whatever you think will be best for your game without thinking of sales, reviews or prohibitions, because there are not enough cotton gloves in the world to tackle these topics without offending anyone.

If all you want to know is whether this will boost sales or not, it all depends on your target. As people mentioned before, do you want this game not o be 18 or not? Do you plan on translating it to Russian and selling it there? Do you want to target hardcore gamers who most often than not despise preachy politics in their games? If the answer to any of these is "yes", you may want to just leave it as heavily implied at best. Do you want to target fans of JRPG, who are very likely to like Japanese media in general? As stupid as it seems, your best bet is sexualizing them (people will get mad about this, but if they are outside of your target demographic, it doesn't really matter). Otherwise, if you want to target a more casual (not in a bad sense, not even as in people who only play Candy Crush on their phones - still "core" gamers, just not as fixated on videogames that take a lot of effort to play) or modern demographic, such as the people who played and liked Life is Strange, Gone Home, or Dragon Age: Inquisition, making them blatantly gay could even boost your sales.

**EDIT:** I remember Dofus had two NPC, a major and her secretary, named Mayor Cantille and Lou Bricante (yes, that's probably a sexual pun; game is full of them), who were very explicitly implicitly closet lesbians for each other. People talked a bit about this, but nobody seemed to care because it was cute and both girls were cute. Villagers would often gossip about it for comedic purposes. It wasn't given much relevance, and it was always treated in a very lighthearted tone -like the rest of the game-, so it simply happened to be a very secondary side story that was consistent with the setting, so I guess people simply accepted it; which brings me to the point that, if it is not a relevant plot point, just mention it in passing just like you would comment on any plot point of little relevancy.

I guess your case with the consul could be similar, but keep in mind that, depending on how directly based on Roman society the society in your game is, some people could complain about lack of realism (yeah, even if otherwise your game contains dragons and magic crystals). While ancient Rome didn't really treat homosexual relationships much differently to heterosexual relationships, they did treat women, and whoever they deemed to fulfill the role of the woman in a relationship, as inferior. I am unsure how would have ancient Rome reacted to a masculine lesbian consul, considering information on lesbians in ancient Rome is scarce, but chances are she would have stood no chance against other male politicians.

To avoid these complaints, either try to show (don't just tell!) in which ways this society distanced itself from our ancient Rome, and try to justify how could this happen, and of course, what could the possible reactions to this be, or just treat it in a consistent manner (if it isn't something people usually accept, why would they be telling anyone but people they utterly trust?).

Part of why people disliked the transsexual character in Baldur's Gate: Siege of Dragonspear is because they were out of place. It's already weird enough to bump into a stranger and casually start talking about stuff, so don't make it any weirder by talking about personal stuff most people have no bussiness knowing. This, combined by the fact that it just comes out of the blue (shoehorning), that the universe has genderbending magic that's apparently not in play here (inconsistency), that the topic isn't relevant at all to the plot or worldbuilding at al (virtue signaling at its finest), and that it's one of the only dialogues that doesn't let you any agency at all on how to react to this (which comes out as inconsistent, preachy and gives the impression Mizhena is above other characters just because she is trans) made several people, including trans people themselves, angry about the inclusion of just a token LGBT character for the sake of having a token LGBT character, above the normal rules of the world and dialog mechanics.

# Answer
> 118 votes
It's not as easy as saying: *"Lesbian couple in the game = ± x% copies sold"*.

Just like with most things in game development, it's not the idea which matters, but the execution. When you write LGBT characters into your game, there are many things which can go wrong:

* You can portray them as ridiculous clichés, offending LGBT people and LGBT allies. A common mistake is to write a homosexual character completely around their sexuality. Remember that sexuality is just one of many aspects of a well-rounded character.
* You can overuse them as a vessel to hammer down some sociopolitical message which doesn't fit into your overall narrative. Don't get me wrong. Having some message in your work is usually a good thing. But coming over as too preachy can be bad and offend those people who disagree with the message. See also Weaving VERY IMPORTANT OPINIONS into a story without murdering it on Writers Stackexchange.
* It might not fit into the story. Ancient Rome was a very patriarchal culture. There were no female consuls and no lesbian marriages. You aren't writing *how* close your fictional culture is to its ancient roman inspiration. The closer you are to the original, the more anachronistic these characters will feel to the player. If you just want to write them in because you want to have a lesbian couple with a position of authority and not because they actually work in the setting and the story, it will likely be detrimental.

But there are also many things which can go very **right**. Video game writing was always suffering from overusing shallow stock characters. Just recently have we discovered that the medium can tell much deeper stories with much more complex characters than we thought. If you want to contribute to this development, then daring to add more diversity to your cast of characters is a first step.

For further watching I recommend this video by Extra Credits: Sexual Diversity - How a Queer Character Made Persona 4 Great.

# Answer
> 40 votes
I have some numbers, though they're for a web game, which might not apply to your market.

Back in 2012, I wrote a game called Farm & Grow. It featured little people wandering around a farm and occasionally one of them would get married. The game made no distinction regarding gender; I was writing for a game jam and didn't really have time, but also having no gendering appealed to me. The first character was named after the players Kongregate id, if they had one.

There were a few players who became extremely upset because they married a man. They posted their outrage in the game comments, personal messages and bug reports. A moderator has removed them now. 22 Kongregate users were added to my mute list.

I inspected the high scores for 22 users who I muted. 19 had researched the entire tech tree; effectively completing the game. *Turns out most homophobic bigots claiming they are greatly offended will play your game anyway.*

Assuming that the 3 complaining players who didn't complete the tech tree did so because they quit the game in outrage:

Most players don't write comments. I had 241670 gameplays and nearly 1200 comments (including the deleted ones). So 1 commenter per 200 players, perhaps. Multiply that by 3 gives approx 600 players who were so outraged about same-gender marriage that they quit the game, or about 0.25%.

A sample of 3 players is too small to base any decisions on. However I feel that you lose an insignificant number of players by including LBGT content.

I used mochi analytics in addition to the Kongregate api; 90% of my players were from America, 8% from Europe, and 2% from the rest of the world.

Edit - this isn't a valid statistical analysis, because of the small sample size and sampling bias (among other flaws). Interpret the numbers as you will, but this is anecdotal evidence, not proof.

# Answer
> 30 votes
There's no such thing as bad PR. While not universally true, it certainly does apply to indy games with a rather low projected number of sales. This kind of controversy is the best thing that could happen to you, because it's free advertising, spreading the name of your game. Which is also the sole reason that Beauty and the Beast story you linked exists.

But realistically, you're probably too late to create controversy. After Baldur's Gate and Mass Effect, nobody cares about LGBT characters in RPGs anymore, unless they're horribly written.

Regarding numbers, you're out of luck. Sales numbers are difficult to compare, and you're asking about a very specific feature in a very specific genre of games, when the gaming industry to date still can't even quantify something comparatively far simpler like the lost/gained sales due DRM vs DRM-free.

P.S: There is an exception! If for some reason your game gets banned from one of your main target markets due to LGBT characters, that's obviously rather bad for sales. I heard Russia and some other countries are rather strict on homosexuality, but I don't know if they ban games that include it.

# Answer
> 23 votes
**Games sell because they're good, not because they have X or Y**

Your game sales will most likely have nothing to do with the sexual orientation of your characters. What will matter to the players is how developed the characters are and how realistic they feel.

If you make a character that is *(insert some stereotypical LGBT character here)* then you will most likely hurt your sales. Not because you included someone from the LGBT community, but because you did not give enough thought to the character.

**Character development is more important than what the characters symbolize**

* Your characters need to have needs and wants, not just be a certain type of person.
* They need to have individual stories, history, stuff they like or hate because of what they lived through or how they think about the world they're living in.
* They need to have room for development and not to be set in stone. If they're *that kind of character* then they will become boring sooner or later. If they change as your story goes on, e.g. the high priestess is killed by a demon so the newbie priest in your party now hates demons with a passion, then they will be more interesting.
* You also need to be able to advertise this to the outside world, to the people who have never heard about your game, without giving away too much but giving enough to get them interested, or hook them with a juicy bait.

If you manage to get half of this right, you will have a decent game. If you manage to get all of it right, you will have a gem.

# Answer
> 5 votes
There is a very highly rated point-and-click game from 2000 called "The Longest Journey." Two minor characters are lesbians, and one of them talks at length about their relationship--not graphically, but still. It's kind of amusing because the one who does most of the talking has a beautiful voice and a British accent, and she's the femme. When the partner is finally introduced, she has short hair, a manly voice with a different (Southern U.S.?) accent, and is wearing overalls, from what I remember.

Anyway, the point is that I'm straight and didn't find it offensive or forced. Their little story was pretty funny and added some color and realism to the game. That was 17 years ago, and the LBGT content didn't seem to hurt the game's popularity. Ultimately, it probably depends on the skill of your writers.

# Answer
> 3 votes
So, I'm actually queer, and the question about weather including LGBT stuff in your game will affect sales put a really bad taste in my mouth.

My opinion is that you should. I have an obvious bias here.

I can't give you hard numbers, but I can tell you that including LGBT stuff in your game will get you at least a few die-hard fans. I've seen hundreds of posts in the queer circles I hang out in about how important it was for queer people, especially kids, to see representation in media.

For me, that important representation was the movie Heathers. I've watched it at least 5 times (I've lost count at this point), and I will happily recommend it to anyone. Aside from being one of the only movies I know of with a bisexual lead, it's also a great social commentary, the predecessor to the runaway success Mean Girls... I could go on for days.

As a non-personal example, here's a lovingly compiled list of lesbian movies.

Now, these people probably won't boost sales much in the first few days after launch, but they will most definitely increase your long-term sales. A week or a month or a year after launch, a person like me, starved for content that includes queer characters and themes, will buy your game based on a friend's recommendation. It will end up in lists of queer games. It will get talked about on the hundreds of queer communities across the web.

Note that this is REGARDLESS OF QUALITY, by the way. A better game will have better sales after launch, but there are always people willing to try a game or a movie or whatever regardless of its reviews because it has LGBT/queer stuff in it.

Also, check out Life is Strange and its community for a good example of all of this.

# Answer
> 2 votes
Everyone is pussyfooting around the answer and posting some ridiculous opinion pieces when the answer is extremely simple: **yes, it will detract from possible sales.**

There are entire COUNTRIES which will ban such a game on basis of it "promoting homosexuality". There are entire cultures where users would be shamed for playing such a game, or literally put in risk of gruesome death if it was found out they were playing a game where a character is gay.

And most importantly, just because you include some gay characters will not make your game sell better. Gamers don't care about social causes in their games, they care whether the game is good or not. So you can only lose, never really win.

# Answer
> 2 votes
To a certain extent, yes, it will affect sales of your games. Even if you do it right, by depicting the characters as not only human, but also fallible, and not *always* a victim, and keep such themes in proportion to the intended primary themes of the game, you will, if your game receives any press at all, encounter some games journalist who will blow the entire character out of proportion. This may shift public perception of your game towards a "LGBT romance" theme, with several effects:

1. You may pick up customers who purchase the game thinking LGBT themes are stronger in the title than they actually are, who may be disappointed by the relatively narrow span of attention received: They just bought an LGBT game, after all, and it ended up being a JRPG!
2. You may lose potential customers who simply aren't interested in romance subplots in their games in general. They don't want to buy a romance game, after all, they just want a good old-fashioned JRPG like those of their youth, after all.
3. You may lose conservative customers who do not wish to fund what they perceive as propaganda.
4. You may lose more moderate conservative customers. Even if such a customer *would* ordinarily be okay with moderate and realistic LGBT themes in a title they're playing for themselves (say an M-rated title like Skyrim or a Bioware title), you should keep in mind the particular niche you're targeting: if you're genuinely trying to aim toward a **nostalgia** theme, part of the fun of nostalgia is sharing what you played as a kid with your own children, and by adding LGBT themes in the title you will put those adults in a situation where they *cannot* in good conscience share that experience with a child---nullifying the very purpose of your title to this class of customer!
5. You may pick up sales from those who will never play your title, but purchase it as a means of advancing their vision of social justice.

All in all, I see very little advantage in placing LGBT themes in your title. Those customers gained via point (1) will likely be disappointed, yielding short-term benefit but little in the long-term, whereas you will likely lose some customers due to (2) and (4), and may permanently lose a subset of customers via (3). About the only measurable advantage is that controversy is free advertising, and you may, if you are lucky, end up inundated with social justice sales (5). But it's a tremendously risky strategy, and essentially costs you the soul of your game.

Alternatively, simply place the content with enough subtlety that neither journalist nor child will detect it; to avoid detection by the former, one may simply place such themes after the tutorial, but avoiding detection by the latter may require some exemplary writing talent.

# Answer
> 0 votes
One of the problems of LBGT games (or propaganda, for some games) is: People don't care unless they are pissed or angry.

For example, let's say Overwatch, where one of the characters is lesbian just because the authors want to. It's not vital to the story or relevant, it's just forced for please some specific group. In Overwatch exists a gorilla, is it gay? Is it straight? Who cares! It's the same with the rest of characters may be some has some straight story but it's not something relevant.

So, unless you are doing a social game, then you must be subtlety and elegant, not about the LBGT character but about everything that is not relevant.

For example, a good example is Utena (an anime), is the main character lesbian? I don't know, but I'm ok with whether she is or not.

Anyways, gays in JRPG aren't a novelty idea at least for the Japanese version of the games such as Chrono Trigger, Final Fantasy and such.

# Answer
> 0 votes
Well, I presume you could include a setup option that includes/excludes possibly controversial features, perhaps with defaults guided by the player's age, or (better yet), oriented by actions taken by the player while playing.

Such an option would allow you to opt out of taking sides, which might be what you really want, as you'd not want to enter the any particular reality distortion field (RDF). If anything, as a game designer, your task is to exploit the players own RDF.

*But I am presenting this technical option to show you a mirror, so you can see that it comes down to what you (really) want with the game. Try make the best game! That LGBT reality distortion field could be a very effective ingredient of an excellent game, a force, while at the same time teaching about preaching, without taking sides*.

Experiencing reality, that's what games are for ;)

# Answer
> 0 votes
What ever you do, people will find problems with it.

I would say that the question of How is way more important than the what or if. You can go for content that is not political and do very well. Just put it in there without the rethoric from politico-ideological groups. The few that will find it wrong or dislike it will not alter your game sales. If anything, they will help you. if the content is trying to preach something, many moderate people will dislike it. That will be bad for business.

Oh, and if it is Lesbian content with no political bullshit, you will win over even the childish trolls that would hate it.

The only ¨sin¨ would be to put male on male content as the main part of the game, as something players can not avoid or choose. Thisi s just how guys are...

# Answer
> 0 votes
In my opinion, I don't think most people "hate" LGBT characters, there is a very vocal minority angry about LGBT characters in games, or even when games choose women protagonist over male, or things like that.

What I don't like is when devs use LGBT characters as a selling point, as if they need to put them as a diversity token. One example of that is a transgender NPC in *Mass Effect Andromeda*. She basically tells you "Oh, hey there! I'm a girl but I used to be a dude: my name was Dave!" and, as far I know, dead names for trans people is like a big deal.

In the other hand, you have Tracer, I really liked how Blizz managed her homosexuality since they just put her with her girlfriend there, she was not there like "Hey, my name is Tracer and I have a girlfriend. YES, I'M LESBIAN".

So, if you ask me, I don't think most people mind LGBT characters, there is a vocal minority hating them because they think there is some kind of LGBT conspiracy to destroy straight people, so don't be afraid of making your characters whatever you like.

# Answer
> 0 votes
The inclusion of LGBT characters will not harm your sales so much as *botched* inclusions of LGBT characters. The only massive brouhaha regarding this topic is that a number of developers seem to use this as an excuse to break the rules of good writing (in a lazy, not artistic way).

To illustrate my point, I'm going to look at two characters from the Borderlands series, who are LGBT but were handled vastly differently by their creators. Tiny Tina is one of Borderlands's most loved characters. She's a sadistic 13 year old demolitions expert who uses lots of 'ghetto slang' that would stereotypically be associated with African Americans (the character is white) and mixes this with stereotypical little girl behaviours too.

Her mixture of childishness and sociopathy is the main source of humour in scenes and missions where she is involved. Despite this she can also be sweet and caring, and have some genuinely deep moments. The fact that she is LGBT is given away only in fairly natural comments that you might expect an immature person to make, which again fits into her nature. This is good character writing, LGBT or not.

Contrast this with Janey Springs from Borderlands: The Pre-Sequel. From what this game gives us, Janey is a lesbian mechanic who, at the beginning of the game, somehow gets stranded even though she should have access to a quick-travel station (these are actually part of the series's canon, and not just gameplay elements), and her partner is eaten. That's it.

This wouldn't be an issue if the game didnt spend such a long time hammering the point in that she is a lesbian or even if she acted the remotest bit upset about her partner being eaten, but the game wants you to focus less on that and more on the fact that she is a lesbian. This is amplified further if you play as Athena, where she will hit on your character repeatedly despite Athena actively blowing her off at times. It most certainly doesn't help that the game makes another Borderlands classic character completely break character and talk about the immaturity of referring to the 'friendzone' (This character's entire personality is immature masculinity, and is also the source of humour for most of his scenes). This is what you get for the first 30 minutes of the game after the intro mission, and it's a drag to the point where I wanted to turn off the game.

# Answer
> -1 votes
This is an opinion based answer, but as I don't believe anyone here has direct research information about this topic, here I go anyway.

I would start at looking at the two groups you are interested in.

* Those who would buy a game because of the LGBT characters
* Those who would buy your game if not for the LGBT characters

First off, your game has only two female married characters. You do not say how essential these characters are for the overall story, but my impression is that they are minor characters. So how could this affect sales?

**first off, who would buy the game because of the LGBT characters**

As a gay man myself, I might feel like I had an extra reason to buy a game, if I felt that it had characters that I could relate to. But I can't see how I could even know about two minor(?) characters before actually playing it. It might make me more inclined to buy a sequel though. Other things, like a good story, and exciting gameplay would be more important, though I always enjoy feeling included. When it comes to lesbians, I would be completely indifferent if it came to sexual depictions or romance, but it would work if it revolved around the small daily efforts one has to endure, due to being a minority. Male on male romance would be awesome though, but even then it had to be characters I could in other ways relate to. Demographically, people's sexuality are about 4% in the direction of same sex. There are countless studies about this number, varying in great difference. I take my numbers from pornhub statistics, which I believe is the most likely to be accurate. LGBT demographics are evenly distributed all over the world, and also gamers. You could also argue that female on female sex traditionally sells well among my straight male counterparts.

**Secondly, who would not buy the game because of the LGBT characters.**

Here again, there are a lot of factors. For instance, is this a game meant for children, or adults? If it is meant for primarily children, you could risk that it would get an unnatural adults-only rating in Russia, depending on the significance and graphic content of the two women. The beauty and the beast was not banned in Russia, it was only set to have an 18 year age limit. If the game is meant for adults, I believe they would, like me, not even know about the characters before they bought the game. Some might be offended by them, which is more likely to happen on a personal basis, and maybe affect sales of sequels. Any kind of organized outrage in media or similar would probably not happen, unless the characters were significant.

**Lastly, who would not care**

Most people who did not time travel directly from 1990 or before. We have all seen the inclusion of LGBT characters in countless mainstream games and tv-shows. It is fortunately not shocking to most people that gays exist anymore. The most popular TV-shows all have LGBT characters, at least as long as the cast is big enough. This includes The Walking Dead, Game of Thrones, Modern Family and countless others. They all include several both minor and major characters, both toned down, and flamboyant. The thing they have in common, is great writing, and great stories.

In ultra religious countries, like Saudi Arabia, I do think it could lead to the game being totally banned. But then again, so could depiction of alcohol, non-covered women in general, or any other religion besides Islam.

If I in any way thought that my story would be better because of LGBT characters, I would definitely include them. If sales are the most important thing about your game, there might be a few demographic issues to watch out for. The likeliness of sales being affected by two minor characters is probably unnoticable, unless you have a very specific target demographic that frowns upon even small amounts of LGBT content.

---
Tags: rpg, sales, character-development
---


# Question
Title: Direct3D 11 : Pixel shader and Vertex shader getting set at every draw call
I'm working on my own (much tinier) version of Monogame. Right now I've been able to draw triangles to the screen with custom shaders using Direct3D 11. The problem is that I can't get it to be as perfomant as Monogame. I did some graphics debugging and noticed something :

The above picture is my implementation and the other is Monogame. For some reason the pixel shader, vertex shader and constant buffers are assigned at every draw call. I don't understand why this is happening since in my code I only ever set those parameter once an then draw a buffer containing 2 triangles 1000 times (as a performance test).

# Answer
> -1 votes
It turns out that the lack of performance was due to the lack of depth buffer.

---
Tags: shaders, graphics, directx11
---


# Question
Title: Update and merge Unity coordinate systems multiplayer - Hololens
**Project Summary**

Creating a multiplayer HoloLens app that allows players to spawn and move objects around the local space they share.

**Problem**

I am able to connect to the other HoloLens and see the other player in the correct location but, for some reason the objects that I spawn I offset. I determined that the offset was based off of where the application started off. When developing in HoloLens the device always starts at (0,0,0). However, once the client has connected to the host and imported their world anchor the client's coordinate system is never updated event though the anchor is in the same physical location. This creates a problem because if the client is offset by 180 degrees everything that the host does is offset by the same amount when moving an object if that makes sense.

**Moving toward a solution**

After doing a lot of research I found this pertaining to sharing and HoloLens:

> "After a GameObject is locked via the LockObject call, it will have a WorldAnchor which will keep it in the same physical position in the world, but it may be at a different location in the Unity coordinate space than other users."

I found this on Microsoft's website here

https://developer.microsoft.com/en-us/windows/mixed-reality/shared\_experiences\_in\_unity

**Question**

So obviously my question is basically, is there a way to update the x,y,z coordinates of (0,0,0) during runtime?

# Answer
In my object controller script, I added a command that gets the position based off of the shared anchor which is in the correct position for both players. My code looks a little bit like this. I hope this helps anyone else that comes across this problem.

```
/// The position relative to the shared world anchor.
[SyncVar]
private Vector3 localPosition;

///The transform of the shared world anchor
Transform sharedAnchorTrans;

/// The rotation relative to the shared world anchor.
[SyncVar]
private Quaternion localRotation;

void Start()
{
    //Get the instance of your anchor in the world this will be different
    sharedAnchorTrans = SharedCollection.Instance.gameObject.transform;

    // I set this to be the child of an object with an anchor so that I do not have to
    // have one on this object because it takes up a lot of processing power to have
    // multiple anchors.
    transform.SetParent(SharedCollection.Instance.transform, false);
}

private void Update()
{
    if (receivedAuthority)
    {
        Vector3 objDir = transform.forward;
        Vector3 objPos = transform.position + objDir * .01f;

        localPosition = sharedAnchorTrans.InverseTransformPoint(objPos);
        // localRotation = transform.localRotation;
        CmdTransform(localPosition);
    }
    else if(!receivedAuthority)
    {
        transform.localPosition = localPosition;
        // transform.localRotation = localRotation;
    }
}

public override void OnStartAuthority()
{
    receivedAuthority = true;
}

public override void OnStopAuthority()
{
    receivedAuthority = false;
}

[Command]
public void CmdTransform(Vector3 position)
{
    if (!isLocalPlayer)
    {
      localPosition = position;
      //localRotation = rotation;
    }
}

```
> 0 votes

---
Tags: unity, coordinates, unet, hololens
---


# Question
Title: How to devise an algorithm for a person being on a walk?
The game is an isometric RPG. The map is tile based.

I'm creating a town for this game. And I want one of the characters to roam the town randomly, because she is on a walk with her children.

I tagged the tiles she can go on. And I created a simplistic algorithm that I, in my naiveness, thought would be enough. Here it is:

If the character is blocked out and can't move in any direction she waits 1s before checking this again. If she can move in only one of the 4 directions, she moves that direction. If there is more than one possibility: If she can go forward, she always has 50% chance of going forward; if she can go both to her left and to her right there is an equal chance she chooses either of those two directions; and finally, if she can turn back, that chance is 2x smaller than turning to her left and 2x smaller than turning to her right. So, if she can choose from all 4 directions, she will have 50% chance to go forward, 20% chance to go to her left, 20% chance to go to her right, and 10% chance to go back. Repeat the above every step.

This algorithm fails beautifully. The character mostly moves randomly in one place. If she gets on a square she almost can't leave it.

I thought the solution would be to increase the chance of her moving forward. So I made the chance to go forward 5 times bigger than doing anything else. But this proved to hardly improve things.

COuld you give me some hints, point me to the correct direction? Or at least tell me that this is not worth it and I should instead resort to giving her a predefined path? (Are there no algorithms to make a character roam a given set of walkable tiles?)

# Answer
> 6 votes
People walking through a town usually have a destination. So when you want your NPCs wander behavior to look natural, they should also have one. It doesn't need to be a *logical* destination. Any destination will do to give a cursory observer the impression that this is a mentally sane pedestrian. (You could of course go the extra mile and give your NPCs a plausible daily routine or even a goal-oriented action planning AI, but it seems to me like this is currently far beyond your scope)

So just pick a random destination and calculate the shortest path to it. Then have the NPC follow that path. When the path is blocked, recalculate the path. When the NPC reached the destination, or the destination is unreachable, pick a new random destination and repeat.

In order to do that, you will have to implement a path finding algorithm. One algorithm which is very simple to implement and "good enough" when you don't calculate too many routes per second is Dijkstra's Algorithm. A more efficient algorithm which is slightly more complex (but still quite easy) is A\*. There are many more route finding algorithms, but these are the two most famous ones which should belong to the standard repertoire of every game programmer.

---
Tags: algorithm, procedural-generation, random
---


# Question
Title: How should I parse user input in a text adventure game?
Parsing user commands in a text adventure is a spectrum from Adventure's simple "go north" to some mind-bogglingly clever ones in hhgttg.

I seem to remember reading nice how-tos in computer magazines back in the 80s, but now I find almost nothing on the 'net except a brief Wikipedia ref.

How would *you* do it?

---

**Update**: I went with the simplest approach possible in my Ludum Dare entry.

# Answer
Did you search in the interactive fiction community? They still write parsers and some try to push the envelope by implementing new techniques such as natural language processing.

See for example this link for articles describing approaches used:

http://ifwiki.org/index.php/Past\_raif\_topics:\_Development:\_part\_2#Parsing
> 10 votes

# Answer
The term you want is 'natural language processing', or NLP. However, bear in mind that formal methods are designed to try and understand real world texts, whereas you only usually need something that works for a limited subset of your natural language.

Typically you can start out with a simple grammar and vocabulary, then write a parser for it. A grammar might be something simple like this:

```
sentence = verb [preposition] object
verb = "get" | "go" | "look" | "examine"
preposition = "above" | "below"
object = ["the"] [adjective] noun
adjective = "big" | "green"
noun = "north" | "south" | "east" | "west" | "house" | "dog"

```

The above is a variant on Backus-Naur form, the standard way of representing grammars. Anyway, you can use a parser generator to generate code to parse this grammar, or write your own fairly easily if your language has decent string handling. (Look up 'recursive descent parsers', which use one function for each line of the grammar.)

Once parsed, you can work out if the sentence makes sense - "go north" may make sense, but "get the green north" does not. You can solve this in 2 ways; make the grammar more formal (eg. have different types of verbs only valid with certain types of noun) or check the nouns against the verb afterwards. The first way can help you to give out better error messages to the player, but you always need to do the second to some degree anyway, as you always need to check context - eg. "take the green key" is grammatically correct and syntactically correct, but you still need to check that the green key is present.

Eventually your program ends up with a validated command with all the various parts checked; then it's just a case of calling the right function with the arguments to perform the action.
> 11 votes

# Answer
The state of the art for making text adventures today is using Inform 7. Inform 7 source reads "like English," in the same way that Inform-based games let you "write English." For example, from Emily Short's *Bronze*:

> A thing has some text called scent. The scent of a thing is usually "nothing".
> The block smelling rule is not listed in any rulebook.
> Carry out smelling something:
> say "From \[the noun\] you smell \[scent of the noun\]."
> Instead of smelling a room:
> if a scented thing can be touched by the player, say "You smell \[the list of scented things which can be touched by the player\].";
> otherwise say "The place is blissfully odorless."

The Inform 7 parser is closely integrated with the Inform 7 IDE, and the entire source code is not available for study yet:
> 6 votes

# Answer
The two best current sources for learning to create a text adventure parser are (as was mentioned) the IF community and the mud community. If you search the major forums for those (Intfiction.org/forum, the newsgroup rec.arts.int-fiction, Mud Connector, Mudbytes, Mudlab, Top Mud Sites) you'll find some answers, but if you're just looking for articles I would recommend Richard Bartle's explanation of the parser in MUD II:

http://www.mud.co.uk/richard/commpars.htm

And this explanation on rec.arts.int-fiction:

http://groups.google.com/group/rec.arts.int-fiction/msg/f545963efb72ec7b?dmode=source

No disrespect meant to the other answers, but creating a CF grammar or using BNF is not the solution for this problem. That's not to say it couldn't be a solution for a different problem, that is, creating a more advanced natural language parser, but that's the subject of considerable research and not IMO in the scope of a text adventure.
> 6 votes

# Answer
In my first-year at university we made an adventure game in Prolog, and for the user input we had to use *definite clause grammar* or DCG. See http://www.amzi.com/manuals/amzi/pro/ref\_dcg.htm#DCGCommandLanguage for an example of using it as a command language. It seemed like a principled (it was uni after all) and flexible approach at the time.
> 4 votes

# Answer
You need to define a domain specific language that is all the sentences which are correct in your game. To this end you have to define a grammar for your language (vocabulary and syntax). The type of grammar you need is a Context Free Grammar and there are tools which automatically generate a parser starting from a synthetic description of the grammar such as ANTLR (www.antlr.org). The parser only checks whether a sentence is correct or not and produce an Abstract Syntax Tree (AST) of the sentence which is a navigable representation of the sentence where each word has the role you specified in the grammar. By navigating the AST you have to add the code that assess what is the semantics each word takes when playing that role with respect to the other words in the sentence and verify whether the semantics is correct.

For instance the sentence 'The stone eats the man' is syntactically correct but not necessarily semantically correct (unless in your world stones, maybe magic stones, can eat men).

If also the semantics is correct then you can, for instance, change the world according to it. This could change the context and thus the same sentence could no longer be semantically correct (for instance there could be no man to eat)
> 1 votes

# Answer
I used the Tads3 (www.tads3.org) engine for some of the text adventures I wrote. It's more for computer programmers though but a very powerful language. If you're a programmer Tads3 will be tons easier to code things faster than Inform7, which I've used before as well. The problem with Inform7 for programmers is as famous as "guess the verb" is for players of text adventures in that if you don't write your sentences VERY carefully you're going to break the game. If you have the patience to do it you can easily write up a parser in Java using the Tokenizer class. Example I wrote using a global JTextArea and a global String\[\] array. It strips out unwanted characters except leaves A-Z and 0-9 as well as the question mark (for a "help" command shortcut):

```
// put these as global variables just after your main class definition
public static String[] parsed = new String[100];
// outputArea should be a non-editable JTextArea to display our results
JTextArea outputArea = new JTextArea();
/*
 * parserArea is the JTextBox used to grab input
 * and be sure to MAKE sure somewhere to add a
 * java.awt.event.KeyListener on it somewhere where
 * you initialize all your variables and setup the
 * constraints settings for your JTextBox's.
 * The KeyListener method should listen for the ENTER key
 * being pressed and then call our parseText() method below.
 */
JTextArea parserArea = new JTextArea();

public void parseText(){
    String s0 = parserArea.getText();// parserArea is our global JTextBox
    s0 = s0.replace(',',' ');
    s0 = s0.replaceAll("[^a-zA-Z0-9? ]","");
    // reset parserArea back to a clean starting state
    parserArea.setCaretPosition(0);
    parserArea.setText("");
    // erase what had been parsed before and also make sure no nulls found
    for(int i=0;i < parsed.length; i++){
      parsed[i] = "";
    }
    // split the string s0 to array words by breaking them up between spaces
    StringTokenizer tok = new StringTokenizer(s0, " ");
    // use tokenizer tok and dump the tokens into array: parsed[]
    int iCount = 0;
    if(tok.countTokens() > 0){
      while(tok.hasMoreElements()){
        try{
          parsed[iCount] = tok.nextElement().toString();
          if(parsed[iCount] != null && parsed[iCount].length()>1){
            // if a word ENDS in ? then strip it off
            parsed[iCount] = parsed[iCount].replaceAll("[^a-zA-Z0-9 ]","");
           }
        }catch(Exception e){
          e.printStackTrace();
        }
          iCount++;
        }

      /*
       * handle simple help or ? command.
       * parsed[0] is our first word... parsed[1] the second, etc.
       * we can use iCount from above as needed to see how many...
       * ...words got found.
       */
      if(parsed[0].equalsIgnoreCase("?") ||
        parsed[0].equalsIgnoreCase("help")){
          outputArea.setText("");// erase the output "screen"
          outputArea.append("\nPut help code in here...\n");
        }
      }

      // handle other noun and verb checks of parsed[] array in here...

    }// end of if(tok.countTokens() > 0)...

}// end of public void parseText() method

```

...I left out the main class definition and variable initialize() method, etc. because it's assumed if you know Java you already know how to set that up. The main class for this should probably extend JFrame and in your public static void main() method just create an instance of it. Hopefully some of this code helps.

EDITED - Okay, so now what you'd do next is create an Actions class and scan for an action (i.e. "get lamp" or "drop sword"). To make it simpler you'd have to have a RoomScan object or method to scan everything visible in scope and scan for only those objects on that action. The object itself handles the action handling and by default you should have an Item class handle all known actions in a default way, which can be over-ridden. Now, if for example, an item you want to "get" is held by a non-player character, the default response for getting that item held by its owner should be something like "The won't let you have it." Now you'd have to create a ton of default action responses to this in the Item or Thing class. This is basically coming from a Tads3 perspective on over all design. Because in Tads3 each item has its own default action handling routine on it which the parser calls if an action on it is initialized. So... I'm just telling you, Tads3 already has all this in place, so it's VERY easy to code in a text adventure in that language. But if you want to do it from scratch, like in Java (above), then I personally would handle it much the same way Tads3 was designed. In that way, you can override default actions handling routines on different objects themselves, so for example if you want to "get lamp" and the butler is holding it, it could trigger a response in the "get" action method of default for Item or Object and tell you that "The butler refuses to hand over the brass lamp." I mean... once you've been a programmer long enough like I have, then this is all VERY easy stuff. I'm over 50 years old and been doing this since I was age 7. My father was a Hewlett Packard instructor in the '70's so I learned a TON from him initially on computer programming. I'm also in the US Army Reserves as basically a server administrator now. Um... yeah, so don't give up. It's not that hard once you really break it down to what you want your program to do. Sometimes trial and error is the best way to go on this sort of stuff. Just test it and see and don't ever give up. Okay? Coding is an art. It can be done in many different ways. Don't let one way or the other seem to block you into a corner on design.
> 1 votes

---
Tags: input, text-based, interactive-fiction
---


# Question
Title: which one should use Transform or Nullable Vector3?
We know Vector3 is a struct and for this reason it can't be null. Let's suppose that I want to rotate to a enemy position, if I use a Vector3 I can't be sure if there was an enemy or not and maybe I will be looking at Vector3.zero. A solution for this problem is use the enemy transform (and not the position) and do a null check, but another option is make a nullable Vector3, but I'm not sure which use, what should I take in account to take a decision?

# Answer
> Let's suppose that I want to rotate to a enemy position, if I use a Vector3 I can't be sure if there was an enemy or not

This should be an impossible case. To ensure it's impossible, design your interface accordingly. You should be writing this function:

```
Quaternion findRotationToFace(Character subject, Character target)

```

This function takes the `subject` character (could be the player) and computes the rotation necessary to face the `target` character (could be an enemy), returning that rotation as a quaternion. Or any other rotation representation you prefer, such as a `Transform`, if that's really what you want.

Then there's no ambiguity: this function *must have* two characters to work, and if you don't have a second character you can't call it. So in higher-level code you can write:

```
if (enemy != null) {
  // An enemy exists for the player to look at, so face it:
  Quaternion rotation = findRotationToFace(player, enemy);
  player.rotateBy(rotation);
} else {
   // No enemies right now.
   player.twiddleThumbs();
}

```

---

To answer your broader question of when to use a nullable thing versus not, there's three primary things you'll want to consider:

* Nullability adds complexity; it means the null case must be checked for. Ideally, one would prefer simple interfaces over complex ones, so if you can avoid scenarios where null data can be passed or returned, that's often better. In other words, use nullability when you *have* to.
* Examples of cases where you might "*have*" to have a null are scenarios where all valid values of some type are "correct" outputs. For example, the classic function `int stringToInteger(string input)` function: there is no sentinel value like 0 or -1 you can choose to represent the case where `input` contains "hello" instead of a number, so a `Nullable<int>` might be a good choice for a return value (ignoring the other possibilities for communicating errors, like throwing exceptions).
* For C#/Unity specifically: remember that reference types exist on the heap and thus create garbage for the collector to process. For C# games, it's usually preferable to minimize the amount of incidental, temporary garbage so that you minimize the tendency of the GC to run its gen0 phase on junk, pushing things you do really need to have on the heap into later, more expensive-to-collect generations. `Nullable<T>` is itself a value type and thus not afflicted with this, but other nullable things are generally reference types, so this does apply to those.

The tl;dr is that you should usually use non-nullable types when you can, but nullable ones when you have to.
> 0 votes

---
Tags: unity
---


# Question
Title: How can I calculate an octree node's depth from its location code?
The article *Advanced Octrees 2: node representations* states:

> The AABB (axis-aligned bounding box) of the node can be stored explicitly as before, or it can be computed from the node’s tree depth stored implicitly inside the locational code. To derive the tree depth at a node from its locational code a flag bit is required to indicate the end of the locational code. Without such a flag it wouldn’t be possible to distinguish e.g. between 001 and 000 001. By using a 1 bit to mark the end of the sequence 1 001 can be easily distinguished from 1 000 001. Using such a flag is equivalent to setting the locational code of the Octree root to 1.

The book *Real-Time Collision Detection, Volume 1* by Christer Ericson states:

> The size of a node can be explicitly stored or it can be derived from the "depth" of the locational code. In the latter case, a sentinel bit is required in the locational code to be able to distinguish, say, 011 and 000000011, turning these into 1011 and 1000000011, respectively.

Both offer the following algorithm for computing the depth of a node:

```
int node_depth(unsigned int key) {
    for (int d = 0; key; ++d) {
        if (key == 1) { return d; }
        key >>=3;
    }
    assert(false);
}

```

How and why does this work?

The location code is a 32 bit word. That is, `... 011` and `... 000 011` might be equal, depending on what the remaining bits of the first location code are. using a sentinel, one has `... xx1 011` and `... xx1 000 011` and now they are different location codes.

What I don't understand is how can I get the depth of the nodes from the location codes and how does the sentinel help me with that.

Going back to the example above, `... xx1 011` and `... xx1 000 011`, these words could be `... 000 001 011` and `... 000 001 000 011`, respectively. Both cases have the sentinel bit, but since `001` (and any other `xx1` combination) is a valid triple, all triples are valid, and there is no way for me to tell what the depth of the nodes is.

The only solution I've found is to store the depth of the node next to the location code, but that article and the book seem to indicate that the depth can be derived from the location code somehow.

# Answer
It might be helpful to think of the `key` variable as a stack that you're trying to count the depth of. Every iteration, you add 1 to the depth, return if the stack is empty, then pop 3 bits off the stack.

The sentinel bit just marks where the stack ends.

An example (imagine lots more zeros to the left):

```
... 001 000 010 111 # pop 111
... 000 001 001 010 # pop 010
... 000 000 001 001 # pop 001
... 000 000 000 001 # done (because the stack == 1)

```

Since the `key == 1` check is only `true` when the bits are exactly `000 000 … 001`, it doesn't matter that a `001` was also encountered in the middle of the sequence.

It doesn't actually matter what value the sentinel bit is, as long as it's not `000`. You could have a "sentinel seven" by putting `111` at that point and checking for `key == 7` instead.

So why not a `000` "sentinel zero"? Because if the location code starts with a bunch of zeros, you wouldn't be able to distinguish the "bottom of the stack" from the zeros that the bit shift keeps introducing:

```
... 000 000 001 010 # pop 010
... 000 000 000 001 # pop 001
... 000 000 000 000 # pop 000
... 000 000 000 000 # pop 000
... 000 000 000 000 # pop 000
... 000 000 000 000 # pop 000
... 000 000 000 000 # pop 000
... 000 000 000 000 # When do we stop?

```
> 3 votes

# Answer
Given the locational code c of a node, its depth in the Octree can be computed as log2(c)/3
> -1 votes

---
Tags: algorithm, octree
---


# Question
Title: Scale VBO magnitudes based on aspect ratio
On my screen I have drawn a box. When I adjust my screen size (to a non 1:1 aspect ratio) I get a rectangle. This is obviously something wrong with my projection matrix.

I am attempting to keep everything in my engine scaled from 0-\>1 to make it simple to define assets and have them look good on any size screen.

I would like to make my internal VBO sizes scale with the window's aspect ratio. In this example I have one asset that I define as having a width and height of "0.01" which is 1/100th the screen size.

I create the following VBO with this...

```
    GLuint VAO, VBO, EBO;
    GLfloat verts[] = {
            width, height, 0.0f,
            width,   0.0f, 0.0f,
             0.0f,   0.0f, 0.0f,
             0.0f, height, 0.0f
    };
    GLuint idxs[] = {
            0, 1, 3,
            1, 2, 3
    };

    glGenVertexArrays(1, &VAO);
    glGenBuffers(1, &VBO);
    glGenBuffers(1, &EBO);

    glBindVertexArray(VAO);

    glBindBuffer(GL_ARRAY_BUFFER, VBO);
    glBufferData(GL_ARRAY_BUFFER, sizeof(verts), verts, GL_STATIC_DRAW);

    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(idxs), idxs, GL_STATIC_DRAW);

    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), NULL);
    glEnableVertexAttribArray(0);

    glBindBuffer(GL_ARRAY_BUFFER, 0);
    glBindVertexArray(0);

```

I'm using an ortho matrix from (0, 1, 0, 1, 0, 1), I'm correclty doing my PVM multiplication in my shader, and I've correctly translated my matrix.

My boxes are still rectangles and I believe that this is because my original "1/100th" screen size is different from my new screen's width and height. How do I correctly scale my width and height that I've given to my VBO?

Edit: PS you can find all of the important pieces of code in my git repo (https://github.com/gravypod/solid-snake/). I'd link directly to the right section but StackExchange seems to have a karma based limit...

# Answer
> 1 votes
You need to recalculate your projection matrix whenever the screen aspect ratio changes.

1/100th of the screen width and height is still exactly 1/100th of the screen width and height when the viewport is rectangular but now that will be a rectangle.

What you need to do to keep your coordinate units square is decide if you want to shrink to square or expand to square (or something in between) and which direction and then generate a projection matrix that will have a different width scale than height scale.

So for example, when your screen is 16:9 your ortho matrix range could be (-0.388888889, 1.388888889, 0, 1, 0, 1) = shrink, or (0, 1, 0.21875, 0.78125, 0, 1) = expand to keep everything square.

You take the aspect ratio (eg: 16:9) which is **width/height** and apply that to either the X range or the inverse of it (eg: 9:16) to the Y range of your ortho matrix.

---
Tags: vbo, aspect-ratio
---


# Question
Title: How can I call two functions in a sequence with onclick?
I'm learning Unity.

I have two functions, one that transitions to a new scene and the other one is the button animation.

I add both functions to the onclick of a given button. I assume it calls both functions at the same time and executes the transition without running the animation.

I want the button to run the animation first (I'm using DOTWEEN) and once it's done to execute the transition.

# Answer
Unity generally does not execute "two funtions at the same time", because the game logic is single-threaded. What likely happens is that the function which *starts* the button animation is executed. The actual animation happens in a coroutine which would be processed throughout future updates.

Then the scene change function is executed. The scene change also interrupts the tweening coroutine, which means it is never finished.

What you actually want to do is start the tween coroutine and then do the scene change when the tween coroutine finished. The Unity UI system doesn't know about the tween you are doing, so it can't know when it will be finished. That unfortunately means that you can't cleanly separate these two functionalities (animation and scene-change) because the second depends on the first being completed.

To do something when a DOTWEEN tween is finished, pass it as a callback method to the `OnComplete` method of your Tweener. More about this in the DOTWEEN documentation under "Chained Callbacks".
> 1 votes

# Answer
You can simply animate button using Button Transition.by default, unity is selected with Color Tint, change it from Color Tint to Animation and then you can use OnClick to translate new scene.

you can do simple animation for the button in Unity animation

Using Unity animation is better than DoTween and it's easy for small animations.
> 0 votes

---
Tags: unity
---


# Question
Title: AI not pathing correctly with pathfinding
I have implemented A\* pathfinding to use in a game that im making for a project. The issue is that the AI that's using the pathfinding does not seem to wanna follow the path correctly. as displayed in the picture

blue dots = AI's path

yellow dots = path to take according to the pathfinding

red dots = impassable wall

As you can see the AI completly ignores the path to follow according to the pathfinding. I have been twisting my head multiple times around and have been unable to figure out the issue.

Below is the code where the pathfinding is used by the AI and shows all the states it cant be in. Position and rotation is applied later down in the code which is not shown here.

```
if (_pathState == SEARCHING)
        {
            if (glm::length(enemy->getPosition() - player->getPosition()) < 10.0f)
            {
                _isAtGoal = true;
                _pathState = ATTACKING;
            }

            _pathFinding->findPath(enemy->getPosition(), player->getPosition(), map);
            _isAtGoal = false;
            if (_pathFinding->foundGoal)
            {
                _targetPos = player->getPosition();
                _pathState = FOUND_GOAL;
            }
        }
        if (_pathState == FOUND_GOAL)
        {
            if (!_isAtGoal)
            {
                glm::vec3 targetDistance = _pathFinding->nextPathPos(enemy->getPosition(), getRadius()) - enemy->getPosition();
                angle = glm::degrees(atan2(targetDistance.x, targetDistance.z));
                rotation = glm::angleAxis(glm::radians(angle), glm::vec3(0, 1, 0));
                _velocityX += 0.1f * cosf(angle);
                _velocityZ -= 0.1f * sinf(angle);

                /*if (glm::length(_targetPos - enemy->getPosition()) < 10.0f)
                {
                    _pathFinding->intializedStartGoal = false;
                    _pathFinding->foundGoal = false;
                    _pathFinding->clearPathToGoal();
                    _pathState = SEARCHING;
                }

                if (glm::length(_targetPos - player->getPosition()) > 10.0f)
                {
                    _pathFinding->intializedStartGoal = false;
                    _pathFinding->foundGoal = false;
                    _pathFinding->clearPathToGoal();
                    _pathState = SEARCHING;
                }*/

                if (glm::length(enemy->getPosition() - player->getPosition()) < 1.0f)
                {
                    _isAtGoal = true;
                    _pathState = ATTACKING;
                }
            }
        }
        if (_pathState == ATTACKING)
        {
            if (glm::length(enemy->getPosition() - player->getPosition()) > 10.0f)
            {
                _pathFinding->intializedStartGoal = false;
                _pathFinding->foundGoal = false;
                _pathFinding->clearPathToGoal();
                _pathState = SEARCHING;
            }
            else
            {
                glm::vec3 playerDir = enemy->getPosition() - player->getPosition();
                angle = glm::degrees(atan2(playerDir.x, playerDir.z));
                rotation = glm::angleAxis(glm::radians(angle), glm::vec3(0, 1, 0));
            }
        }

```

The tutorial that I followed when implementing the pathfinding is from here:

https://www.youtube.com/watch?annotation\_id=annotation\_654919&feature=iv&src\_vid=-A2HYXj186c&v=NJOf\_MYGrYs

And my pathfinding is pretty much as follows. My own suspicion is that the radius is whats causing the problem, since the radius is just a set number that I didn't put any thought into when I set it.

# Answer
> 1 votes
I found the issue, apperantly the angle calculation was incorrect along with the distance calculation in nextPathPos. The pathfinding works beautifully now.

---
Tags: c++, 3d, ai, path-finding
---


title: Shadow Shimmering When Moving Objects

text:
# Question
Title: Shadow Shimmering When Moving Objects
I am having a shadow shimmering in my scene when using a shadow mapping technique. I know that there is a lot of posts over the internet dealing with this subject but my issue is slightly different.

I know that the problem comes from sub-texel issue when moving the camera BUT my scene is using a different technique as the camera and the light sources are stable and the objects inside the scene is moving Relative To Eye concept (RTE). The issue is when implementing cascaded shadow mapping and variance shadow mapping as stated in DirectX examples, everything goes well except that the shadows are shimmering (flickering). The shimmering is coming from the objects that are moving, not the camera. So when I try to solve the problem with adjusting the sub-texel problem with the camera movement it didn't solve the problem as the camera is stable but the objects are not.

# Answer
The easiest way to overcome this would be blurring your shadows. This is obviously not a perfect solution, but might be worth trying it out, it might just solve your problem.

Now, there are multiple way of implementing soft shadows. The most straighforward way is to sample your shadow maps multiple times, and interpolate the shadow comparison results. This is called percentage closer filtering (PCF). This is trivial with a comparison sampler, because the sampling result is already a filtered comparison value. You can use a jittered shadow sampling kernel or sample neighborhood shadow map texels in a regular grid.

You could also be blurring your shadows in a full screen pass.

You can blur the shadow maps themselves before the comparison if you are using Variance shadow mapping technique.

You could do a temporal filtering for shadow maps maybe with an offset shadow projection matrix and blending with the previous frame's shadow map. I haven't seen this technique being applied to shadow maps yet, but this is widely popular these days for anti aliasing.
> 1 votes

---
Tags: 3d, directx, shadows, shadow-mapping
---


# Question
Title: Merging custom c++ engine with Unreal Engine
I have my own custom C++ game engine with networking, game logic (most important) suitable for type of games I am working with etc.

I find it harder and harder to keep up with other engines in case of graphical part.

I wonder if **it's possible to merge my C++ engine with Unreal Engine?** And if so, what would be the best practice for it?

What I mean is to keep my already established game logic and data modules and use UE to render meshes ordered by game logic (I can easily detach the rendering part of my engine, because it's closed into few abstract interfaces that I can implement again with calls to another API or custom code), as well as do some simple physics (the type of games I do do not require too much of physics simulations). That way I could benefit from both UE rendering superior and my engine's tailored game logic module.

I know it's possible to extend UE with custom plug-ins, but I'm not sure it would be the best approach for me.

# Answer
> 3 votes
Yes, it's possible, but it's likely going to be *far* more work than you're thinking and in the end you'll likely be left with very little of your engine. So it's probably not the best idea.

Unreal is a tightly-integrated package, it's not designed to be used piecemeal, and it's very hard to decouple its various major subsystems from eachother. The component you want to use, the rendering engine, is going to depend on or talk with the core object model and garbage collection, the asset serialization system, the physics layer, the editor for building materials (and in turn the rest of the editor infrastructure), et cetera.

You'd be better off taking your existing gameplay code you want to keep, and adapting that to Unreal (not everything in Unreal has to be done with Blueprints, you can write native C++ just fine, directly or via plugins, as you've noted). You will need to adapt that gameplay logic to work within the framework of Unreal (e.g., `AActor` instead of your own existing game object/entity system, and so on), so you'll be abandoning almost all of your "engine" code except perhaps systems that Unreal provides no analogue for.

This will still be a fairly significant effort, potentially (depending on the size of your gameplay code base). It's up to you to decide if the perceived gain in graphics functionality is worth the cost.

Remember that good graphics involves good art, as well, and art that is tailored to the way the graphics code works. It's possible your existing art will need to be re-authored because it's flat-out incompatible or because it just doesn't look good within Unreal's lighting/rendering models, et cetera. Keep in mind that overheard as well.

I am very skeptical this will be a net win for you.

---
Tags: c++, architecture, unreal-4
---


title: error, how to remove BOX2D

text:
# Question
Title: error, how to remove BOX2D
I got an error, when I launch fireball too swiftly, I guess, my fireball does not really remove well. So that's why I got crush.. Can you guys check my update method, and please give me some idea?

And one more thing I want know is what `!world.isLocked()` means...

```
public class FireBall extends Sprite {

    PlayScreen screen;
    World world;
    Array<TextureRegion> frames;
    Animation fireAnimation;
    float stateTime;
    float firetiem;
  public static  boolean destroyed;
    boolean setToDestroy;
    boolean fireRight;

   public static Body b2body;
    public FireBall(PlayScreen screen, float x, float y, boolean fireRight){
        this.world = screen.getWorld();
        this.fireRight = fireRight;
        this.screen = screen;
        destroyed = false;
        frames = new Array<TextureRegion>();
        for(int i = 0; i < 4; i++){
            frames.add(new TextureRegion(screen.getAtlas().findRegion("fireball"), i * 8, 0, 8, 8));
        }
        fireAnimation = new Animation(0.2f, frames);
        setRegion((TextureRegion)fireAnimation.getKeyFrame(0));
        setBounds(x, y, 6 / MarioBros.PPM, 6 / MarioBros.PPM);
        defineFireBall();
    }

    public void defineFireBall(){
        BodyDef bdef = new BodyDef();
        bdef.position.set(fireRight ? getX() + 12 /MarioBros.PPM   :  getX() - 12 /MarioBros.PPM, getY());
        bdef.type = BodyDef.BodyType.DynamicBody;
        if(!world.isLocked())
        b2body = world.createBody(bdef);//?

        FixtureDef fdef = new FixtureDef();
        CircleShape shape = new CircleShape();
        shape.setRadius(3 / MarioBros.PPM);
        fdef.filter.categoryBits = MarioBros.FIREBALL_BIT;
        fdef.filter.maskBits =  MarioBros.GROUND_BIT | MarioBros.ENEMY_HEAD_BIT|
                MarioBros.COIN_BIT |
                MarioBros.BRICK_BIT |
                MarioBros.ENEMY_BIT|
                MarioBros.OBJECT_BIT;

        fdef.shape = shape;
        fdef.restitution = 1;
        fdef.friction = 0;
        b2body.setLinearVelocity(new Vector2(fireRight ? 2 : -2, 2.5f));
        b2body.createFixture(fdef).setUserData(this);

    }

    public void update(float dt){
        stateTime += dt;

        setRegion((TextureRegion) fireAnimation.getKeyFrame(stateTime, true));
        setPosition(b2body.getPosition().x - getWidth() / 2, b2body.getPosition().y - getHeight() / 2);

        if((stateTime > 0.5f &&  !destroyed)) {
            System.out.println("remove");
            world.destroyBody(b2body);
            destroyed = true;
            stateTime=0;
            }

        if(b2body.getLinearVelocity().y > 2f)
            b2body.setLinearVelocity(b2body.getLinearVelocity().x, 2f);

        }

    public boolean isDestroyed(){
        return destroyed;
    }}

```

# Answer
It looks like you're accessing your `Body` **after** it has been destroyed, that is not allowed.

Try returning immediately from the `update` method if `destroyed` is set, and make sure destroying the `Body` is the **last** thing that happens in that method.

```
public void update(float dt){
    if(destroyed)
      return;
    stateTime += dt;

    setRegion((TextureRegion) fireAnimation.getKeyFrame(stateTime, true));
    setPosition(b2body.getPosition().x - getWidth() / 2, b2body.getPosition().y - getHeight() / 2);

    if(b2body.getLinearVelocity().y > 2f)
        b2body.setLinearVelocity(b2body.getLinearVelocity().x, 2f);

if((stateTime > 0.5f &&  !destroyed)) {
        System.out.println("remove");
        world.destroyBody(b2body);
        destroyed = true;
        stateTime=0;
        }
    }

```
> 1 votes

---
Tags: libgdx, box2d
---


# Question
Title: Unity: Failed to build APK. See console for details
i am getting this error whenever i am trying to build a project. i looked at so many solutions but this one just doesn't go away.

This is the error:

```
CommandInvokationFailure: Failed to build apk.
C:\Program Files\Java\jdk-9\bin\java.exe -Xmx2048M -Dcom.android.sdkmanager.toolsdir="C:/Users/Mohit/AppData/Local/Android/sdk\tools" -Dfile.encoding=UTF8 -jar "C:\Program Files\Unity\Editor\Data\PlaybackEngines\AndroidPlayer/Tools\sdktools.jar" -

stderr[
Exception in thread "main" java.lang.reflect.InvocationTargetException
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:564)
    at SDKMain.main(SDKMain.java:130)
Caused by: java.lang.NoClassDefFoundError: sun/misc/BASE64Encoder
    at com.android.sdklib.internal.build.SignedJarBuilder.<init>(SignedJarBuilder.java:177)
    at com.android.sdklib.build.ApkBuilder.init(ApkBuilder.java:446)
    at com.android.sdklib.build.ApkBuilder.<init>(ApkBuilder.java:422)
    at com.android.sdklib.build.ApkBuilder.<init>(ApkBuilder.java:362)
    at UnityApkBuilder.<init>(UnityApkBuilder.java:214)
    at UnityApkBuilder.main(UnityApkBuilder.java:34)
    ... 5 more
Caused by: java.lang.ClassNotFoundException: sun.misc.BASE64Encoder
    at java.base/java.net.URLClassLoader.findClass(URLClassLoader.java:466)
    at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:563)
    at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:496)
    ... 11 more
]
stdout[

]
exit code: 1
UnityEditor.Android.Command.Run (System.Diagnostics.ProcessStartInfo psi, UnityEditor.Android.WaitingForProcessToExit waitingForProcessToExit, System.String errorMsg)
UnityEditor.Android.AndroidSDKTools.RunCommandInternal (System.String javaExe, System.String sdkToolsDir, System.String[] sdkToolCommand, Int32 memoryMB, System.String workingdir, UnityEditor.Android.WaitingForProcessToExit waitingForProcessToExit, System.String errorMsg)
UnityEditor.Android.AndroidSDKTools.RunCommandSafe (System.String javaExe, System.String sdkToolsDir, System.String[] sdkToolCommand, Int32 memoryMB, System.String workingdir, UnityEditor.Android.WaitingForProcessToExit waitingForProcessToExit, System.String errorMsg)
UnityEditor.HostView:OnGUI()

```

what i have tried so far:

1) downgrading android sdk 2) moving zipalign file from build-tools to tools folder 3) setting up keystore

# Answer
> 2 votes
Make sure you are using jdk 8 and unity is pointing to the right location

---
Tags: unity, exceptions
---


# Question
Title: How can I make actions that effect the position of another player appear responsive when my game server is authoritative?
* You are playing as Lucio in Overwatch. You boop another player and they immediately get booped away. It feels really responsive. But the server hasn't actually registered the boop yet. By the time your command reaches the server, that player might be in a different location and the result of your boop might be completely different. If we needed to wait for a server confirmation, we wouldn't see our boop for, say, 200ms. (assuming 200ms RTT.)
* You are driving around in PUBG and see another player. You drive your car in to a player who is running around on foot. They appear to immediately die or at least get bumped away by the impact. You hit the player where you saw him but he is actually somewhere else on the server (you may have actually missed him!). If our game does not respond immediately, we would see the other player clip in to your car as they continue running, then, say, 200ms later they would die or get knocked around (again assuming a RTT of 200ms)

How are situations like these resolved? It seems like the result is simulated locally (prediction) but the outcomes could be so drastic that an incorrect prediction could result in a lot of confusion. (Running over a player who isn't actually in your way, booping a player to your left off a cliff, but they are actually in front of you and won't fall down the cliff)

# Answer
The usual solution is for the client to assume at first that the server will agree with it and correct afterwards when it does not.

So when you "boop" another player, both tell the server you are "booping" it and calculate their trajectory according to the client's currently assumed world-state. When the server then says 200ms later: "uhm, actually, you did not boop actor 1703 to `100.0002`:`23.00124` but to `100.0003`:`23.00126`", you have the client correct that afterwards. Either immediately (with a notable jump) or have the actor "rubber-band" slowly to their intended position over multiple frames.
> 3 votes

---
Tags: multiplayer
---


# Question
Title: Unity 2D graphical glitch cuts sprite diagonally
While making a game in unity, we found a graphical glitch that only happens on one of our mobile devices (a htc) where the screen will be oddly sliced by a triangle as shown in this image;

I've searched online but found no problem. We're using unity 2D, it only does it on the HTC but we have no idea why. The background is a 3D quad with a texture wrapped around it (so we can make it move with the character when the character is running, without having one large background). Any help would be greatly appreciated. Thanks

# Answer
> 5 votes
This is a camera culling issue. Had the exact same thing happen to me. More than likely, you need to adjust the Canvas that character is on, so that it is closer to the z-index range of your Camera.

# Answer
> 1 votes
I had this painful clueless issue before. But I did resolve it. Probably your camera is at z:-10 and everything other is at z:0. Try to bring camera closer to object like set camera's Z to -1.

# Answer
> 1 votes
don't keep your background and your image in the same position . keep them far away from each other .

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