title: LibGdx Positioning the camera

text:
# Question
Title: LibGdx Positioning the camera
I've been following some tutorials about libGdx and I've tried to create a 2d platformer but I've got stuck at how would be the right way to make the camera not go out of the screen when the player moves :( The camera follows the player when it moves on the x coordinate position but if i go near where the map ends the camera will go out of the screen and i'm not sure how to solve that

Here is the main code of the game:

```
public PlayScreen(SuperShooter game){
        this.game = game;
        atlas = new TextureAtlas("Diz_Pack.atlas");
        gamecam = new OrthographicCamera();
        gamePort = new StretchViewport(SuperShooter.V_WIDTH / SuperShooter.PPM, SuperShooter.V_HEIGHT / SuperShooter.PPM, gamecam);

        hud = new Hud(game.batch);
        mapLoader = new TmxMapLoader();
        map = mapLoader.load("Level1WithObjects2.tmx");
        renderer = new OrthogonalTiledMapRenderer(map, 1/SuperShooter.PPM);
        //initailly set our gamecam to be centered correctly at the start of
        gamecam.position.set(gamePort.getWorldWidth()/2 , gamePort.getWorldHeight()/2, 0);

        world = new World(new Vector2(0,-10), true);

        new B2WorldCreator(world, map);

        controller = new Controller(game);

        // b2dr = new Box2DDebugRenderer();
        player = new John(world, this);

        world.setContactListener(new WorldContactListener());

    }

public void update(float dt){
        handleInput(dt);
        world.step(1/60f, 6, 2); // in order for box2d to execute our physics simulation we need to tell it how many times to calculate per second
        player.update(dt);
        gamecam.position.x = player.b2body.getPosition().x;
        gamecam.update();
        renderer.setView(gamecam);
    }

public void render(float delta) {

        update(delta);
        Gdx.gl.glClearColor(1, 1, 1, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
        renderer.render();
        //render our Box2dDebugLines
        //b2dr.render(world, gamecam.combined);

        game.batch.setProjectionMatrix(gamecam.combined);
        game.batch.begin();
        player.draw(game.batch);
        game.batch.end();

        game.batch.setProjectionMatrix(hud.stage.getCamera().combined);  //you have something that can draw to the screen via gpu like the spritebatch. And you have a camera.
        //you gotta tell the spritebatch where we are / where the camera is looking, because on screen shall be what the camera is looking at.
        hud.stage.draw();
        controller.draw();

    }

```

The camera is at first set on the left bottom of the screen but then, while the game updates it's placed on the x position of the player and that's why it looks like that:( do you guys know how should it be done to show only the map when the player moves? should i position the camera in front of the player or something like that?

Help would be appreciated! thanks

# Answer
I haven't ever used LibGDX, but what you'll have to do is find the width of the camera viewport, and limit the x position of the camera like this pseudocode:

```
camera.x = min((levelWidth / 2) + levelPosition.x - (camera.viewportWidth / 2), camera.x);

```

Essentially, we find the smaller number with the `min` function, which will limit our `camera.x` value to the x position of where the camera can be and not show any of the outside of the level. The `OrthographicCamera` class from LibGDX provides the `viewportWidth` value, so you only need to make sure you know where your level object is located and how wide it is.

That code with prevent you from having the camera go too far to the right, to prevent it going to far too the left, use an implementation similar to:

```
camera.x = max(-(levelWidth / 2) + levelPosition.x + (camera.viewportWidth / 2), camera.x);

```

This does a similar thing to the original, it just ensures that the camera's left bound never goes further left than the leftmost point on the level. Both of these snippets assume that the position of the level is in its center. If the level is at (0, 0), then the `levelPosition.x` can be omitted completely:

```
camera.x = min((levelWidth / 2) - (camera.viewportWidth / 2), camera.x);
camera.x = max(-(levelWidth / 2) + (camera.viewportWidth / 2), camera.x);

```
> 0 votes

---
Tags: libgdx, camera, movement
---


title: Using multiple shaders in OpenGL3.3

text:
# Question
Title: Using multiple shaders in OpenGL3.3
guys, I got a question on how to use multiple shaders in my app. The app is simple: I have a 3D scene, say, simple game and I want to show some 2D GUI in the scene. I was following this tutorial on how to add font rendering to my scene. One difference is that I am using Java and `lwjgl`, but everything is implemented as in the tutorial.

So I have 2 sets of shaders (2 programs). 1st that handles the 3D models and scene at all. I added the second set of shaders, I just copied them from the tutorial. Here are they:

vertex:

```
#version 330
in vec2 position;
in vec2 texcoord;
out vec2 TexCoords;
uniform mat4 projection;

void main() {
    gl_Position = projection * vec4(position, 0.0, 1.0);
    TexCoords = texcoord;
}

```

and fragment:

```
#version 330
in vec2 TexCoords;
out vec4 color;

uniform sampler2D text;
uniform vec3 textColor;

void main() {
    vec4 sampled = vec4(1.0, 1.0, 1.0, texture(text, TexCoords).r);
    color = vec4(textColor, 1.0) * sampled;
}

```

I compile shaders, link them into a separate programs. (so I have `modelProgram` and `fontProgram`). However, when I run my application, I see errors in the console (however, the application runs fine):

```
WARNING: Output of vertex shader 'TexCoords' not read by fragment shader
ERROR: Input of fragment shader 'vNormal' not written by vertex shader
ERROR: Input of fragment shader 'vTexCoord' not written by vertex shader
ERROR: Input of fragment shader 'vPosition' not written by vertex shader

```

As you can see `TexCoords` is an `out` variable in `font.vs.glsl` and the other 3 are `in` variables in `model.fs.glsl`. So they belong to the other set of shaders, other program.

My question is why this happen? It looks like the pipeline tries to combine one program with another, although the application runs smoothly.

The other problem I have is that I do not see any text rendered. I don't know whether this is caused by this or it happens because something else. Any help will be appreciated!

Thank you

# Answer
Make sure that you're doing `glUseProgram(0);` and then `glUseProgram(SHADER_PROGRAM_ID);` (The first of those is likely unnecessary, but it's always a good idea to be over-explicit when in doubt) If you're doing that, be sure that you're loading the correct files into the shader. You might be initializing a shader with the source code from one of the wrong shaders, while the other is the correct one.
> 0 votes

---
Tags: opengl, java, glsl, lwjgl
---


title: Does bad AI lead to more sales?

text:
# Question
Title: Does bad AI lead to more sales?
Games like HL2 and FEAR are legendary for having excellent AI. Recent titles (as of 2018) leave much to be desired. With improvements in our understanding of probability related state machines, and general machine learning (or AI as it's called sometimes) improves, it generally feels many commercial titles forego the development of good AI. Anecdotally, I have personally experienced in recent titles (where the AI is dumb as per say - far cry, wildlands, etc.). I feel having dumb AI may sell games more (giving a more accomplished feeling, pushing players towards multiplayer, etc.). So, let me pose the question, does any research show that bad AI leads to more sales?

# Answer
Bad is highly subjective & requires some context. In an FPS for instance, the an AI that never misses a shot would have optimal scores, but arguably wouldn't be very fun.

Academic research in this areas has some significant difficulties. First, there's very little publicly available data about the sales of games. Second, companies rarely report such things when they don't reflect favorably on themselves. This sort of biased small pool of data is problematic for conducting rigorous statistical research.

That being said, there is some research that draws conclusions about player perception of AI & the experiences provided by games. In particular, "What You See Is Not What You Get: Player Perception of AI Opponents" by Baylor Wetzel and Kyle Anderson in *Game AI Pro 3* draws the following conclusions:

* Players are not particularly good at estimating AI difficulty
* News is mixed regarding whether or not its worth investing time to develop complicated AIs
* Perceived difficulty correlated highly with realism but the correlation between actual difficulty & realism was not equally high
* Players were not particularly good at detecting cheating
    + AIs that did cheated routinely went undetected
    + Players readily accused AIs cheating when they did not
* Players were not good at inferring even basic AI strategies
* Players will project / invent stories onto AIs & see motivations, biases, cheating & desires where no exist
> 6 votes

# Answer
I'd wager to say that AI is one of those aspects which contribute very little to game sales because it is an aspect which is very difficult to use for marketing.

The easiest aspects to advertise are graphics and aesthetics. A single screenshot is enough to tell the customer at first glance "this game looks awesome".

The text description of your game is a good way to impress with the amount of content, because you can simply express it in numbers (100 levels, 10 different environments, 200 side-missions, over 80 hours of playtime...).

A trailer is a good way to give the player an impression about how the gameplay feels like. You can use it to highlight some unusual game mechanics (although not every game mechanic can be presented well in just a few seconds of screentime). It can also be used to give a glimpse of the soundscape.

But how do you market a good AI? Whether an AI is fun to play against or not is something you only notice after several hours of gameplay. It might be worth writing about in a longer review article. You could show a few interesting tidbits in a more documentation-oriented trailer. But unless your AI does something truly innovative and extraordinary, then those won't be particular interesting.

So if you design your game for maximum marketability, then AI is one of those aspects where you get the least return of investment for your development budget.

And yes, **developing good AI is expensive**. The better your AI, the more complex its programming becomes. More complex programming means more obscure interactions between different game features which means more corner cases for bugs to hide in. So your testing effort increases exponentially with the complexity of your AI. A complex AI is also really annoying for the level designers. The level designer might say "I want a huge battle to take place in this location, so I design it as the perfect battle arena with lots of interesting cover and tactical opportunities and put some enemies in it". But then the AI decides "Having a battle here would be strategically unwise, I will relocate and fight the player in this bland and boring environment instead". So you need to keep testing all the levels you designed to make sure that the AI still behaves the way the level designers intended.
> 4 votes

# Answer
**Addendum**: When Difficult Is Fun - Challenging vs. Punishing Games - Extra Credits.

---

## What is good A.I.?

If we can agree on bad A.I. is one that accomplishes nothing. Then the problem is defining good A.I. because that will depend on what is the objective of A.I.

Often times, the objective is not to beat the players. *Usually, we are not making games expecting players to pay to be defeated, and if we were, we would just make the game unfair.*

Instead, the objectives of A.I. in games are to keep the game:

* Interesting.
* Believable.
* Fun.

Usually, game are more successful when A.I. can simulate the skills of a regular human player – instead the best human player. I will remind you that human players are not perfect. In fact, a human player will not have full knowledge of the environment, will have limited reaction time, can be tricked or deceived, can be emotional and irrational, and has a tendency to fall to routines.

In addition, you can usually go without one of these - depending the genre. For example in a crowd-combat fighting game, the A.I. can get away with dumb agents - for the most part - because you kill them right away anyway. Other games will have easily exploitable A.I. – Some streamers may like that, and thus, provide a kind of publicity - but that is not a good fit for every genre or setting.

---

## You have a budget

Well, you have a few budgets (a monetary one, the time to the deadline, and the work per frame), and you have to decide on what to spend them.

You will find that A.I. will be at the bottom of the priorities. Visuals, audio, UX, and writing usually come first. That is without talking about all the underlying technology, such as proper logging, networking, and so on.

I want to make a point about writing: It is much cheaper and much more effective. Spending some extra time in thinking what the NPCs do - when they are not talking to you - and what their relationships are, and some extra time in the history of items, and some extra time in writing more than two lines in narrative, dialogs, flavor text, and lore... will go a long way in selling the world as bigger and alive.

Futhermore, if you can tie good writing to a simple A.I. it becomes much more effective. For example, if your enemies express their state and actions in dialog and animation (think, for example, in classic Metal Gear, how the enemies express they noticed something or are searching for the player) it makes the NPCs seem smarter.

---

**Should you aim to have a bad A.I. as an attempt to sell more?** No, you should not. You should set reasonable and viable goals for your A.I. and make A.I. that is good at those goals. *Even if the goal is to make the NPCs seem stupid. Because, I assure you, that is a thing. It can even be part of the lore of the world. In fact, you will learn to see that as be good A.I. once you accept that the objective is not to beat the player.*

**Addendum**: A.I. should be able to beat the player. I want to say that it is better if it feels fair to the player. When I say that the objective is not to beat the player, I do not mean that A.I. should try to not beat the player... instead that you are not designing A.I. with the objective to beat the player.

---

## On making better A.I.

Making A.I. is hard. In particular making A.I. effective in beating the player - which, as I said, should not be your objective - is hard. At least if you want to go beyond planning algorithms and state machines, which can be very predictable.

For example, you can write planning algorithms that adapt to usual player behavior. It can even anticipate the player if you model the player behavior, which can be done with influence maps and similar technologies. *Even that will be predictable, players will learn that if they keep doing X, the A.I will eventually do Y, and that can lead to exploitablity.*

To break predictability, adding random to the algorithm goes a long way.

If that is what you consider “bad” A.I. you probably want some form of modern machine learning; you can try something like NEAT, and I would suggest finding an existing solution so you do not worry about implementation details. Then you probably will NOT have it run in real time because training agents takes time. Thus, the main use in games is to train agents to play the game and ship the trained agent.

**Note**: See What is the difference between artificial intelligence and machine learning?.

Even if you were to train the agents during gameplay, you should start with decent agents, because if you start from scratch, it means the player will encounter dumb A.I.

As a consequence, usually the improvements during gameplay are not significant enough (in particular, if the player kills each enemy mere instants after it appears on screen). Meaning that this is often a waste of resources.

Futhermore, if the improvements during gamplay were effective, remember your difficulty curve. An A.I. that improve out of your control will make it hard to design for it and keep a good difficulty curve, leading to player frustration.

Ah, and generational machine learning - while results in improvements in the long run - can have dumber offerings. In addition, if you have seen anything about adversarial machine learning approaches, you know that even well trained A.I. can be exploitable.

*I repeat, making A.I. is hard.*

---

**A.I in F.E.A.R?** It is basically goal oriented planning with smart objects. A lot of the work is in the objects, not the agents. It is not much different than what you find in The Sims. In fact, we could argue that compared to The Sims, the A.I. in F.E.A.R is "bad" because the agents have less knowledge. Also, **there is no machine learning in F.E.A.R.** See Assaulting F.E.A.R.’s AI: 29 Tricks to Arm Your Game.

---

## Will bad A.I sell more?

> Truth resists simplicity

-- John Green.

Terrible A.I. will not sell. Because terrible A.I. results in NPC who stand in place and do nothing.

I believe there is a sweet spot where bad A.I. can sell. *In particular, if you have a funky world, where dumb enemies make sense, or you are going for the comedic effect.*

In general, good A.I. will sell better. Except good does not mean good at beating the player. *A good difficulty curve is more important that A.I. effective at beating the player.* Instead good and making the game interesting, believable and fun.

You can do plenty of other things that you can improve – aside from A.I. - that will be more effective for marketing. Although, that does not mean you should go for bad A.I.

**Addendum on studies**: Give me a metric on which we can quantify how "bad" A.I. is, and then we can talk about research on bad A.I. leading to **more sales**. Hmm... after controlling for all other variables of course... to isolate the effects of A.I. in sales we will also have to quantify visuals, audio, etc. I haven't found any study on game A.I. influencing **sales** (I find a lot on using A.I. for sale force automation) - I do not claim to have searched exhaustively - but won't be surprised if there aren't, in particular considering that a lot of game development happens without involment from academia.
> 2 votes

# Answer
## Biology/Psychology

Seeing the other answers, I may twist this question to biology rather than CS. While I work in the field of AI, this is much more about mammalian psychology when it comes to games (which seems to be semi-universal among the species.)

While I can't find the studies myself very well, here's a clip of Jordan Petersen taking about Games. https://www.youtube.com/watch?v=JI9n2yC14fU Around 1:40 he starts on the rat game. This is crucial to your question. *Note: Whatever your thoughts on his views or arguments in general, this is unrelated. I simply couldn't find the study myself*

The point of this is that studies are now showing that mammals play games in general, and that they only continue playing if they win an "ok" percent of the time (~33% for the rats.) If the AI is so difficult that it's impossible for the human (such as a good Chess AI against your average player); the human will stop playing.

If, instead, the human sees a challenge but can beat it, they are likely to continue. You need a glimmer of hope. *Side note: while this is hardly academic wording; the more "casual" the player, the bigger the glimmer of hope needs to be*

**Why AIs are difficult** What makes this difficult is what I just pointed out; people need different levels of difficulty based on how tenacious they are; which also means different approaches based on the game type.

Chess is simple: reduce the search space and (by virtue of choosing a random move among equal moves) introduce randomness; which is why Chess AIs are successful for casual and professional players. FPS is a bit harder; in general the AIs tend to work the same but they increase/decrease the amount of opponents and the damage scaling.

---

## "Bad AIs" and Human Competition

The thing about more recent "Bad AIs" are more likely a trend of the increasing requirement of having multiplayer (or being ONLY a multiplayer game.) Players will naturally be able to beat some people and lose to others, and a skill-ranking system helps to sort them into buckets of satisfying difficulty.

AIs, thusly, are only really required for time-filling or for story-driven content; which is taking a backseat in the last decade by comparison to previous decades. Why build a convincing AI when you can generally get the result of an enjoyable game by pitting players against players?

---

The **TL;DR** version of my post: While this is an indirect answer; humans who want to beat things will often only continue playing if it's possible and rewarding. This tends to be easier by simply adding multiplayer than spending countless debugging and development hours making a convincing Ai.
> 1 votes

# Answer
Truthfully, 'bad AI' can be very loosely branded. The AI may not be a very difficult opponent, it may be very simple, or the AI writers were just plain lazy. I am going to go off of the simplicity side of it.

The reason why some games with simple AIs sell better is because we, as humans, want to understand things. If I were to write a several-thousand line file for the AI of an enemy, it would use a lot of random and conditionals, therefore making it complex. The patrons to my game who are not that good and win by learning the enemy's patterns will not be happy. They would be confused by all of the options that the AI has. This goes to negative reviews, and causes less game sales.

However, the simple AI found in games such as Mario, such as the goombas, makes it very easy for the average Joe to complete the levels. He can more easily understand how the AI works, how to avoid the enemy, and eventually kill it.
> 0 votes

---
Tags: game-design, ai, marketing
---


# Question
Title: Is my skill tree possible, balanced, or even a good idea?
Like most people, I have an idea for a game. I have a particular concept I want to create with a particular set of mechanics I want to implement.

What I need help with is the underlaying player statistics, how they effect what the player can do, and how I can enable a player endless expansion down a particular path that improves only a small sub-set of those statistics.

The entire game will be turn based. The concept is to explore and learn about the world you're in. Books, scripts, notes-on-napkins will lead you to secrets and dungeons. There are no quests to do this for you. You have to read, study and venture forth.

The base stats will decide how effective you are in combat as well as other areas of exploration and general existence in the world.

It could be important to mention that combat in my system isn't realtime or even in the control of the player. The player decides to enter a dangerous area of the map and the computer decides if they get into combat. The computer also rolls some dice and applies modifiers based stats, and finally decides who is the winner. You may die, you may be able to flee. I haven't decided yet.

At this moment in time, I'm considering the following (classic) player stats:

* Strength
* Stamina
* Intelligence
* Wisdom
* Agility
* Intuition

I'm considering the following three class types:

* Combat
* Magic
* Stealth

Class types have two base statistics behind them:

* Combat: Strength and Stamina
* Magic: Intelligence and Wisdom
* Stealth: Agility and Intuition

Somewhat obvious, I guess. Moving further into the mechanics, I had the following progression system in mind:

* Levels 1-50 are about learning the game and its mechanics
* Advancing to level 50 is fast and is also the cap
* After level 50, you gain Guild Wars 2 style "Mastery" points which allow you to enhance specialisations
* The end-game is about horizontal progression and mastering your class type, but more importantly, it's about lore and finding it

The idea behind Specialisations is you invest Mastery into them and they force your character down a particular path: combat, magic, or stealth. They also lock you out of the other paths, so you can't mix and match. You have to think about what it is you want to do and whether you can do it based on your understanding of the area you're going into.

The idea behind locking a player down a particular path (which can be unlocked and reassigned, but with research, effort and work) is I want to make it difficult for players to simply construct a "super character" that can take on everything and everyone. Think about how easy it is to become a super mage in Skyrim that can blow everything up... boring!

I want a world in which a very powerful mage is useless against certain monsters simply because of the magic resistance and shear strength that monster has: it forces the player to respec' and rethink before walking into any situation.

To summarise, my thoughts so far are:

* Base stats effect everything the player does
* Equipment can effect the base stats as well as potions and the other classic stuff
* Specialisations effect only two stats and lock out other specialisations
* Mastery points go on and on, but the "leveling" curve gets harder and harder quit quickly
* Mastery and leveling up a particular specialisation enables the player enter new parts of the world (which is massive, by the way) and continue exploring, but not without first researching what's there (and respeccing as a result)

Am I looking at a dead end here, or is this possible? I'm brand new to game development and really enjoy the mechanics behind games. Am I describing a classic setup here, perhaps? Or something close to one?

I would welcome and greatly appreciate all feedback. I'd even welcome a preexisting system I can copy/paste into my world and just use ;-)

Thanks again.

EDIT: Thanks for the great replies and questions. I think I'm getting this a bit backwards and will, instead, focus on my location and movment, then overlay combat when the time comes :-)

# Answer
> 6 votes
Of course it's good for you to have this tree, but what I see from this is that you are aiming too high! As a beginner developer you might just get stuck. Trust me it happened to me many times and I have only finished one small game. I didn't read the whole thing, but I ran trough it and I can really say it's too much for a beginner. So if you want to get ALL this done, what you have to do is cut it down a lot and get the BASIC IDEA of all this. After you create the basic small prototype, then you will be able to expand it. First make the game playable and then expand it to this. So instead of doing all this to make it playable, make sure it's playable when you make just a part of all this! Good luck!

# Answer
> 3 votes
Often games tend to prefer single class focus, as you described for your end game, however from a user perspective consider this:

---

Warrior beats stealth beats mage beats warrior

---

I'm playing your game as a Stealth character. I spent the last 4 hours quickly leveling up. Each level granted new information, so the majority of the time spent playing was interrupted with learning some new aspect. I muscled through it, learning this new ruleset, and finally done!

Now that I'm at max level, fully invested in my class, thinking I've finally "got there" turns up I get absolutely murdered by a group of "Warriors." Nothing I had learned worked against them. Now I can't progress without relearning a whole new skill tree? But I don't want to respec to a Mage!

---

So I've outlined a potential use case where your design would disappoint. That doesn't mean everyone will feel that way, however I think we should always try to consider each possibility we can.

I propose that while you structure your skill tree allow the player to not just be rock paper scissor, but rather One of something and Half of another. That way at LEAST they have the potential to survive a deadly encounter with their nemesis by using their minor skillset intelligently.

You can handle your desire for "Respec" differently by allowing more advanced combat tactics to be skill based, similar to diablo 3. being able to quickly prepare your skills to enhance situational tactics can give you that "No one build destroys everything" aspect without making it unapproachable.

First time posting an answer here, hope it helps.

# Answer
> 2 votes
All of this is definitely possible, in fact it sounds somewhat similar to the leveling system in DDO (Dungeons & Dragons Online). As Joza100 said though, this is a lot for a beginner, and you should really just get the bare-bones game working first, then layer features on after. Kind of like making a cake, then adding frosting and fondant after the base cake is good.

# Answer
> 1 votes
I like the idea of forcing a player to respect and think things through.

Pardon my long answer, but it details examples, and also your q was long.

Anyways,

**You can do a rock paper scissors setup.** E.g. Mage beats thief, thief beats warrior, warrior beats mage. So a warrior would only wanna venture in mage towns to fight mages in this example, since they'll have an easier time there.

**Give players options to choose from. I.e. some options work well in certain situations, other options work better in other situations.** Players have to assess the situation and pick a good option. I.e. randomly picking one won't work.

With six stats instead of only three, players can have more options and variety.

E.g. A warrior who puts all their points into strength and none into stamina can deal lots of damage, but thieves with high agility can just dodge their attacks until the warrior gets tired, and then the thief wins.

But such warriors can fight powerful mages that take too long to cast powerful spells.

They decided their fate by choosing what to master!

But maybe more stamina allows a warrior to stand a chance vs an agile thief. But with some intuition, thieves know how to counter a warrior that only knows how to swing their sword horizontally. Thief knows how to roll under and attack.

**Six stats can lead to more options and thus more thinking, which engages players and makes these types of games fun.**

Another idea: Only if your strength is 20 points high will certain strong NPCs share tales and strategies of intense battles with you. But a powerful mage or thief won't tell you their advanced strategies.

**How do you balance the game? Is 20 points strength fair? or broken? "Broken" means cheap. What about 15 strength? or 25? You'll probably find this out through testing your game, so make a playable prototype!**

**Note: there's super-fair balancing, e.g. no hard-counters. Or there's balancing where some classes hard-counter others, which can be more exciting to watch, but sometimes unfair in some matchups.**

**You're not looking at a dead end. You're looking at lots of possibilities!** League Of Legends has 140 characters! Imagine the options there! I think Magic the Gathering has a bazillion possibilities, too. meta-game and matchups are keywords, too. These things go hand in hand with competitive pvp games.

Check this out for how to make players think: How can I make text-based combat more engaging?

Good luck!

**\*P.S. If you copy and paste someone's code or something, you'll get their permission or follow their license, right? Don't get into any legal trouble.**

There's very permissive open source licenses (e.g. MIT license, X11) that are free with few or no strings attached.

And the less permissive ones (i.e. "copyleft" e.g. GNU, GPL) that are also free, but with a few certain strings attached.

P.P.S. anything (applicable) is automatically copyrighted as soon as it exists. Registering for a (c) is just extra safety measure.\*

**P.P.P.S. I'm not a lawyer. Ask them for legal advice. Don't take my advice word for word.**

# Answer
> 0 votes
*Ahem* If I were creating the game, I would only make three changes:

1. Change the level cap to about 200, which they should reach in about 1.3 playthroughs if they do not grind.
2. Rock - Paper - Scissors: Yes, I know this has already been mentioned, but this works very well. Be creative with it too!
3. Ease the players into the system - Do not start the players off with anything more complex then the very basic options for combat, and slowly introduce the rest.

Also, tweak the system in the beta testing to get the best responses from testers.

---
Tags: game-design, rpg, turn-based, statistics, combat
---


# Question
Title: Why I'm getting exception ArgumentException: Scene to unload is invalid ? Should I change to UnloadScene without async?
The script is attached to a button in the Inspector to the On Click: The script is attached to both StartGame and StartGameButton:

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

public class LoadSceneOnClick : MonoBehaviour
{
    public void ActivatePlayer()
    {
        SceneManager.UnloadSceneAsync(0);
    }
}

```

The exception is on the line:

```
SceneManager.UnloadSceneAsync(0);

```

---

```
ArgumentException: Scene to unload is invalid
UnityEngine.SceneManagement.SceneManager.UnloadSceneAsync (Int32 sceneBuildIndex) (at C:/buildslave/unity/build/artifacts/generated/common/runtime/SceneManagerBindings.gen.cs:196)
LoadSceneOnClick.ActivatePlayer () (at Assets/My Scripts/Scenes/LoadSceneOnClick.cs:10)
UnityEngine.Events.InvokableCall.Invoke () (at C:/buildslave/unity/build/Runtime/Export/UnityEvent.cs:165)
UnityEngine.Events.UnityEvent.Invoke () (at C:/buildslave/unity/build/Runtime/Export/UnityEvent_0.cs:58)
UnityEngine.UI.Button.Press () (at C:/buildslave/unity/build/Extensions/guisystem/UnityEngine.UI/UI/Core/Button.cs:36)
UnityEngine.UI.Button.OnPointerClick (UnityEngine.EventSystems.PointerEventData eventData) (at C:/buildslave/unity/build/Extensions/guisystem/UnityEngine.UI/UI/Core/Button.cs:45)
UnityEngine.EventSystems.ExecuteEvents.Execute (IPointerClickHandler handler, UnityEngine.EventSystems.BaseEventData eventData) (at C:/buildslave/unity/build/Extensions/guisystem/UnityEngine.UI/EventSystem/ExecuteEvents.cs:50)
UnityEngine.EventSystems.ExecuteEvents.Execute[IPointerClickHandler] (UnityEngine.GameObject target, UnityEngine.EventSystems.BaseEventData eventData, UnityEngine.EventSystems.EventFunction`1 functor) (at C:/buildslave/unity/build/Extensions/guisystem/UnityEngine.UI/EventSystem/ExecuteEvents.cs:261)
UnityEngine.EventSystems.EventSystem:Update()

```

# Answer
> 2 votes
You're getting the error because there's no scene with the build index 0. If you're certain a scene does exist, then you can either:

Pass its name instead: `SceneManager.UnloadSceneAsync("MyScene");`

You could also pass the scene as an object: `SceneManager.UnloadSceneAsync(SceneManager.GetActiveScene());`.

Or, if you really want to use the index, pass: `SceneManager.UnloadSceneAsync(SceneManager.GetActiveScene().buildIndex);`

`UnloadScene()` is obsolete and should not be used.

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


# Question
Title: Unreal Engine 4.15 Error C++ | ERROR: UBT ERROR: Failed to produce item UE4Editor-ProjectName.dll
I've already tried installing the Windows 8.1 SDK, but that did not work. Any Help? I'm running on windows 10 using visual studio 2017. I got this error when I created the project.

Error Log:

```
The project could not be compiled. Would you like to open it in Visual Studio?

Running C:/Program Files/Epic Games/UE_4.15/Engine/Binaries/DotNET/UnrealBuildTool.exe ThisIsGoingToWork Development Win64 -project="C:/Users/AaronX/Documents/Unreal Projects/ThisIsGoingToWork/ThisIsGoingToWork.uproject" -editorrecompile -progress -NoHotReloadFromIDE
Performing full C++ include scan (building a new target)
Creating makefile for ThisIsGoingToWork (no existing makefile)
@progress push 5%
Parsing headers for ThisIsGoingToWorkEditor
  Running UnrealHeaderTool "C:\Users\AaronX\Documents\Unreal Projects\ThisIsGoingToWork\ThisIsGoingToWork.uproject" "C:\Users\AaronX\Documents\Unreal Projects\ThisIsGoingToWork\Intermediate\Build\Win64\ThisIsGoingToWorkEditor\Development\ThisIsGoingToWorkEditor.uhtmanifest" -LogCmds="loginit warning, logexit warning, logdatabase error" -Unattended -WarningsAsErrors -installed
Reflection code generated for ThisIsGoingToWorkEditor in 8.3515565 seconds
@progress pop
Performing 9 actions (3 in parallel)
[2/9] Resource ModuleVersionResource.rc.inl
[3/9] Resource PCLaunch.rc
PCH.ThisIsGoingToWork.cpp
ThisIsGoingToWorkGameMode.cpp
ThisIsGoingToWorkCharacter.cpp
ThisIsGoingToWork.cpp
ThisIsGoingToWork.generated.cpp
[8/9] Link UE4Editor-ThisIsGoingToWork.dll
[9/9] Link UE4Editor-ThisIsGoingToWork.lib
   Creating library C:\Users\AaronX\Documents\Unreal Projects\ThisIsGoingToWork\Intermediate\Build\Win64\UE4Editor\Development\UE4Editor-ThisIsGoingToWork.lib and object C:\Users\AaronX\Documents\Unreal Projects\ThisIsGoingToWork\Intermediate\Build\Win64\UE4Editor\Development\UE4Editor-ThisIsGoingToWork.exp
   Creating library C:\Users\AaronX\Documents\Unreal Projects\ThisIsGoingToWork\Intermediate\Build\Win64\UE4Editor\Development\UE4Editor-ThisIsGoingToWork.suppressed.lib and object C:\Users\AaronX\Documents\Unreal Projects\ThisIsGoingToWork\Intermediate\Build\Win64\UE4Editor\Development\UE4Editor-ThisIsGoingToWork.suppressed.exp
ThisIsGoingToWorkGameMode.cpp.obj : error LNK2001: unresolved external symbol "public: virtual bool __cdecl AGameModeBase::SetPause(class APlayerController *,class TBaseDelegate<bool>)" (?SetPause@AGameModeBase@@UEAA_NPEAVAPlayerController@@V?$TBaseDelegate@_N$$$V@@@Z)
ThisIsGoingToWork.generated.cpp.obj : error LNK2001: unresolved external symbol "public: virtual bool __cdecl AGameModeBase::SetPause(class APlayerController *,class TBaseDelegate<bool>)" (?SetPause@AGameModeBase@@UEAA_NPEAVAPlayerController@@V?$TBaseDelegate@_N$$$V@@@Z)
C:\Users\AaronX\Documents\Unreal Projects\ThisIsGoingToWork\Binaries\Win64\UE4Editor-ThisIsGoingToWork.dll : fatal error LNK1120: 1 unresolved externals
ERROR: UBT ERROR: Failed to produce item: C:\Users\AaronX\Documents\Unreal Projects\ThisIsGoingToWork\Binaries\Win64\UE4Editor-ThisIsGoingToWork.dll
Total build time: 92.21 seconds (Local executor: 0.00 seconds)

```

# Answer
> 1 votes
You can see that your project *compiles*, because it gets to this point in the log:

```
Link UE4Editor-ThisIsGoingToWork.lib

```

This indicates all the source files that go into `ThisIsGoingToWork.lib`, which is the main module of your UE4 game in this scenario, have successfully compiled and the linker is now being invoked to join them all together.

During the link, you get this error:

```
error LNK2001: unresolved external symbol "public: virtual bool __cdecl AGameModeBase::SetPause(class APlayerController *,class TBaseDelegate)"

```

This means the linker couldn't find a *definition* for a symbol called `AGameModeBase::SetPause`. This symbol *should* be provided by UE's engine module. It consequently appears as if you are not linking the Engine module; make sure your projects `.Build.cs` file refers to the `Engine` module in the appropriate dependency section.

# Answer
> 0 votes
If the other answers don't work for you, try mine.

I spent almost half day to search for the solution to this. Finally, I found something useful:

You can refer to these two links above. Both the same, either one will be fine.

For convenience, I copied it:

> This is a known issue with changing to 4.12 and using tasks. It can be resolved by simply adding “GameplayTasks” to the PublicDependencyModuleNames section inside your ‘ProjectName’.Build.cs For example:
>
> PublicDependencyModuleNames.AddRange(new string\[\] { “Core”, “CoreUObject”, “Engine”, “InputCore”, “AIModule”, “GameplayTasks” });\*
>
> YourProjectName.Build.cs PublicDependencyModuleNames GameplayTasks
>
> Add GameplayTasks to PublicDependencyModuleNames of the YourProjectName.Build.cs file~.

Different modules you use, Differ the Add.

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


title: Rendering multiple objects in OpenGL

text:
# Question
Title: Rendering multiple objects in OpenGL
I am using advanced OpenDL methods (VBO, VBA, ...) to render over screen. Currently I abstracted vbo, vba, index buffer, texture, and shader to a class called 'Object2D'.

I tried to render two objects on screen. I saw that when the same shader is applied to both objects it works fine; but if the two objects are rendered with two different shader script, only the one rendered last is visible to screen.

Here is `Object2D::render()`:

```
void Render()
{
    if(check_status())
    {
        sh.bind(); //shader
        vb.Bind(); //vertex buffer
        ib.Bind(); //index buffer
        tex.bind(); //texture buffer
        glDrawElements(GL_TRIANGLES,6,GL_UNSIGNED_INT,NULL);
    }
    else{}
    //sh.unbind();
}

```

And here is the drawing function (assume the two 2D objects are `obj` and `box`):

```
void display()
{
    glClear(GL_COLOR_BUFFER_BIT); //refresh/..
    box.sh.setUniformMat4x4("m_projection",GL_FALSE,1,&m_PROJ[0][0]);
    box.Render();
    obj.sh.setUniformMat4x4("projection_matrix",GL_FALSE,1,&m_PROJ[0][0]);
    obj.sh.setUniformMat4x4("view_matrix",GL_FALSE,1,&view_transform[0][0]);
    obj.Render();
    glFlush();
}

```

And this is the shader binded to `box`:

```
#shader vertex
#version 330 core

layout(location = 0) in vec4 positions;
uniform mat4 m_projection;
void main(void)
{
    gl_Position=m_projection*positions;
}

#shader fragment
#version 330 core

layout(location=0) out vec4 color;

void main(void)
{
    color=vec4(1.0,0.4,0.3,1.0);
}

```

and this shader is binded to obj:

```
#shader vertex
#version 330 core

layout(location = 0) in vec4 positions;
layout(location=0) in vec2 texture_coodrinate;
out vec4 p;
out vec2 TexCoord;
uniform mat4 projection_matrix;
uniform mat4 view_matrix;

void main(void)
{
    gl_Position=projection_matrix*view_matrix*positions; //modelvi
    p=projection_matrix*view_matrix*positions;;
    TexCoord=texture_coodrinate;
}

#shader fragment
#version 330 core

layout(location=0) out vec4 color;
in vec4 p;
in vec2 TexCoord;
uniform vec4 U_color;
uniform sampler2D tex_;

void main(void)
{
    ;
    U_color;
    color=texture(tex_,TexCoord);
}

```

My problems are:

* Two of the objects aren't being rendered if until and unless both the shaders are same
* Unbinding the shader result in no rendering?

# Answer
Before setting up uniforms, you should bind the shader as well (with `glUseProgram`, i guess that's what the `.bind()` method does in your case). See GLSL common mistakes.
> 0 votes

---
Tags: opengl
---


# Question
Title: Adjusting collision hitbox size with Pygame
So I coded a 2d sidescrolling platform, everything is fine except this:

As you can see, the sprite is standing at the platform when her feet is not in the platform anymore. I want to adjust the collision hitbox size so that when her feet is not on the platform, she falls to the ground.

Below is the code for sprite initiation:

```
    class Player(pygame.sprite.Sprite):

    #Initiating the player (23 / 5)
    #because there is only one character right now, it will have no case for character selection (23 / 5)
    def __init__(self):
         super().__init__()

         #width and height of character (23 / 5)
         width = 80
         height = 120

         #character sprite goes here (23 / 5)
         self.image = pygame.image.load("Malahayati.jpg").convert_alpha()
         self.image = pygame.transform.scale(self.image,(width,height))

         #hitbox (23 / 5)
         self.rect = self.image.get_rect()

         #character speed (23 / 5)
         self.vx = 0
         self.vy = 0

         #references to the list of sprite we bumped against (24 / 5)
         self.level = None

         #current state: 0 is idle, 1 is moving right, 2 is moving left, 3 is dashing
         self.status = 0

         #character status (24 / 5)
         self.rank = 1
         self.health = 220
         self.attack = 50
         self.defense = 20
         self.speed = 52.5
         self.exp = 0
         self.jumpspeed = 125

```

# Answer
First of all, you have to give your sprites a second Rect attribute, the scaled `hitbox` which will be used for the collision detection. You have to do that because the `self.rect.topleft` coordinates are used as the blit position and if you shrink the Rect, it will be smaller but only fill the upper left area of the image. (The darker area represents the scaled Rect and the brighter area the image.)

```
 ________
|░░░░░   |
|░░░░░   |
|░░░░░   |
|        |
|________|

```

So create the `hitbox` either by scaling the original Rect with the `inflate` method or create a new one with the desired size. I also give my sprites a `pos` attribute (a `pygame.math.Vector2`) which represents the actual center position of the sprites. When the pos is updated in the `update` method, you have to assign it to the `center` of the rect and the hitbox as well in order to move them.

Then define a custom collision detection function which will be passed as the `collided` argument to `pygame.sprite.spritecollide` or `groupcollide`. In this function you can use the `colliderect` method of the `hitbox` Rect to check if it collides with the rect (or `hitbox`) of the other sprite.

In your case you also need to shift the hitbox because the weapon of the character is so large. You can do this by defining a vector (called `offset` here) which you have to add to the `self.hitbox` every update. When the character and its image are flipped, you also have to invert the `self.offset` vector.

Here's a minimal, complete example. The images are blue and gray (with the hitboxes centered at the blue area), the hitboxes red and the outer rects (`self.rect` for the blitting) are green. Press `F` to flip the player sprite.

```
import pygame as pg
from pygame.math import Vector2

pg.init()
IMAGE = pg.Surface((70, 110))
IMAGE.fill((0, 80, 180))
pg.draw.rect(IMAGE, (160, 160, 160), (0, 0, 20, 110))

class Entity(pg.sprite.Sprite):

    def __init__(self, pos, *groups):
        super().__init__(*groups)
        self.image = IMAGE
        self.rect = self.image.get_rect(center=pos)
        # A deflated copy of the rect as the hitbox.
        self.hitbox = self.rect.inflate(-40, -20)
        self.vel = Vector2(0, 0)
        self.pos = Vector2(pos)  # Actual center position.
        self.offset = Vector2(10, 0)

    def update(self):
        self.pos += self.vel
        self.rect.center = self.pos
        # Add the offset to the pos to center the hitbox
        # at the blue part of the image.
        self.hitbox.center = self.pos + self.offset

    def flip(self):
        # Check which side the sprite is facing.
        if self.offset.x > 0:
            self.image = pg.transform.flip(IMAGE, True, False)
        else:
            self.image = IMAGE
        self.offset = -self.offset  # Invert the offset.

# This callback function is passed as the `collided`argument
# to pygame.sprite.spritecollide or groupcollide.
def collided(sprite, other):
    """Check if the hitboxes of the two sprites collide."""
    return sprite.hitbox.colliderect(other.hitbox)

def main():
    screen = pg.display.set_mode((640, 480))
    clock = pg.time.Clock()
    all_sprites = pg.sprite.Group()
    player = Entity((300, 200), all_sprites)
    player.flip()
    enemies = pg.sprite.Group(
        Entity((100, 250), all_sprites),
        Entity((400, 300), all_sprites),
        )

    done = False

    while not done:
        for event in pg.event.get():
            if event.type == pg.QUIT:
                done = True
            elif event.type == pg.MOUSEMOTION:
                player.pos = event.pos
            elif event.type == pg.KEYDOWN:
                if event.key == pg.K_f:
                    player.flip()

        all_sprites.update()
        # Pass the custom collided callback function to spritecollide.
        collided_sprites = pg.sprite.spritecollide(player, enemies, False, collided)
        for sp in collided_sprites:
            print('Collision', sp)

        screen.fill((30, 30, 30))

        all_sprites.draw(screen)
        for sprite in all_sprites:
            # Draw rects and hitboxes.
            pg.draw.rect(screen, (0, 230, 0), sprite.rect, 2)
            pg.draw.rect(screen, (250, 30, 0), sprite.hitbox, 2)

        pg.display.flip()
        clock.tick(30)

if __name__ == '__main__':
    main()
    pg.quit()

```

---

Alternatively, you could give your sprite two offset vector attributes and add the current offset to the `rect.topleft` position when you blit the sprite. However, that means the sprite group's `draw` method can't be used anymore and you have to blit the sprites in a `for` loop. On the other hand, you wouldn't need the `hitbox` and the `collided` callback function anymore.

```
import pygame as pg
from pygame.math import Vector2

pg.init()
IMAGE = pg.Surface((70, 110))
IMAGE.fill((0, 80, 180))
pg.draw.rect(IMAGE, (160, 160, 160), (0, 0, 20, 110))
IMAGE_FLIPPED = pg.transform.flip(IMAGE, True, False)

class Entity(pg.sprite.Sprite):

    def __init__(self, pos, *groups):
        super().__init__(*groups)
        self.image = IMAGE
        self.rect = self.image.get_rect(center=pos).inflate(-40, -20)
        self.vel = Vector2(0, 0)
        self.pos = Vector2(pos)  # Actual center position.
        self.offset_right = Vector2(-30, -10)
        self.offset_left = Vector2(-10, -10)
        self.offset = self.offset_right

    def update(self):
        self.pos += self.vel
        self.rect.center = self.pos

    def flip(self):
        # Check which side the sprite is facing.
        if self.offset.x <= -30:
            # Swap the image and the offset vector.
            self.image = IMAGE_FLIPPED
            self.offset = self.offset_left
        else:
            self.image = IMAGE
            self.offset = self.offset_right

def main():
    screen = pg.display.set_mode((640, 480))
    clock = pg.time.Clock()
    all_sprites = pg.sprite.Group()
    player = Entity((300, 200), all_sprites)
    player.flip()
    enemies = pg.sprite.Group(
        Entity((100, 250), all_sprites),
        Entity((400, 300), all_sprites),
        )
    # Define blit as a local variable to increase the performance.
    blit = screen.blit

    done = False

    while not done:
        for event in pg.event.get():
            if event.type == pg.QUIT:
                done = True
            elif event.type == pg.MOUSEMOTION:
                player.pos = event.pos
            elif event.type == pg.KEYDOWN:
                if event.key == pg.K_f:
                    player.flip()

        all_sprites.update()
        collided_sprites = pg.sprite.spritecollide(player, enemies, False)
        for sp in collided_sprites:
            print('Collision with id', id(sp))

        screen.fill((30, 30, 30))

        for sprite in all_sprites:
            # Add the current offset to the blit position.
            blit(sprite.image, sprite.rect.topleft+sprite.offset)
            pg.draw.rect(screen, (250, 30, 0), sprite.rect, 2)

        pg.display.flip()
        clock.tick(30)

if __name__ == '__main__':
    main()
    pg.quit()

```
> 0 votes

# Answer
The hitbox is set up in this line:

```
self.rect = self.image.get_rect()

```

Documentation gives the following constructor: `Rect(left, top, width, height)` https://www.pygame.org/docs/ref/rect.html

So you need to change the above line to this (replacing `characterWidth` with the new narrower width, and `offset` to the width of the whitespace to the left of the character's feet):

```
self.rect = pygame.Rect(self.image.get_rect().left + offset, self.image.get_rect().top, characterWidth, self.image.get_rect().height)

```

It looks like the whitespace is *almost* (but not exactly) half the width of the sprite, so here's a working example you can play around with until it looks right (change the two 40s, but ensure the two values always add up to 80):

```
self.rect = pygame.Rect(self.image.get_rect().left + 40, self.image.get_rect().top, 40, self.image.get_rect().height)

```
> 0 votes

---
Tags: pygame
---


# Question
Title: Is there a maximum value of sample for Anti Aliasing in Unity?
In Quality settings, there is Antialiasing option with 2~8x sample range. I can change the sample by script like this:

```
QualitySettings.antiAliasing = myAAValue;

```

However is there a maximum value? In Unity Editor, minimum is 2 and maximum is 8.

# Answer
8 is the maximum supported value. See the Unity Manual on the AntiAliasing option:

> AntiAliasing - This sets the level of antialiasing that will be used. The options are 2x, 4x and 8x multi-sampling.

Note that when setting via script, `antiAliasing` is an int, so if you set a higher unsupported value it should default to the highest supported number less than the indicated number. See Unity's `QualitySettings.antialising` documentation that mentions this behavior:

> **QualitySettings.antiAliasing**
>
> `public static int antiAliasing;`
>
> Set The AA Filtering option.
>
> Anti-aliasing value indicates the number of samples per pixel. If unsupported by the hardware or rendering API, the greatest supported number of samples less than the indicated number is used.
> 2 votes

---
Tags: unity, antialiasing, multisampling
---


# Question
Title: How to make one-axis tileable simplex noise?
I made a program that uses perlin noise to generate a height map. It worked very good. Later I changed it to use simplex noise.

What I want to achieve now is that the left edge fits in the right edge, so I want to make it tileable.

I did some research and found this: https://gamedev.stackexchange.com/a/23639/116727. This formula makes it tileable on every edge but I only want it to be tileable on the left and right edges. Then I found this website: http://www.jgallant.com/procedurally-generating-wrapping-world-maps-in-unity-csharp-part-2/#wrap1. It was just what I needed, with a formula that only tiles on one axis. I the tried to implement it, but I could not get it to work.

Here is my implementation:

```
//Noise range
double x1 = 0, x2 = 1;
double y1 = 0, y2 = 1;
double dx = x2 - x1;
double dy = y2 - y1;

//Sample noise at smaller intervals
double s = x / xsize;
double t = y / ysize;

// Calculate our 3D coordinates
double nx = x1 + Math.Cos(s * 2 * Math.PI) * dx / (2 * Math.PI);
double ny = y1 + Math.Sin(t * 2 * Math.PI) * dy / (2 * Math.PI);
double nz = t;

float PerlinValue = (float)SimpNoise.Evaluate(nx, ny, nz); //* 2 - 1;

map[x, y] = PerlinValue;

```

This is the result that I get:

What am I doing wrong? How can I fix this?

# Answer
Your `x / xsize` and `y / ysize` use integer division and return incorrect values because of that.
> 1 votes

---
Tags: c#, heightmap, simplex-noise
---


# Question
Title: OpenGL Outlining Cubes in a Greedy Meshed Mesh
So I've managed to get myself a greedy meshing algorithm implemented for a little voxel game I'm developing to teach myself LWJGL/OpenGL, and it's going great. The thing is, I don't plan on using textures (to truly fit into the *voxel* theme), and I was wondering how I could go about outlining each individual voxel (there can be multiple per quad). Here's the code I've come up with so far in my fragment shader:

```
float epsilon = 0.025f;
float xx = fract(mvVertexPos.x);
float yy = fract(mvVertexPos.y);
float zz = fract(mvVertexPos.z);
bool nearX = (xx >= -epsilon && xx <= epsilon);
bool nearY = (yy >= -epsilon && yy <= epsilon);
bool nearZ = (zz >= -epsilon && zz <= epsilon);
if ((nearX && !nearY && !nearZ) || (!nearX && nearY && !nearZ) || (!nearX && !nearY && nearZ)) {
    fragColor -= vec4(0.3, 0.3, 0.3, 0.0);
}

```

In this sample, `mvVertexPos` is the position of the vertex from the vertex shader transformed by the model matrix:

```
vec4 mvPos = modelMatrix * vec4(vert, 1.0);
mvVertexPos = mvPos.xyz;

```

This method, however, leads to a mesh that looks like this:

When it looks like this without that part of the shader:

And I am trying to make it looks similar to less (not black, but darkened around the edges, just pretend I outlined all the voxels, that's laziness on my part):

I have also ensured that it's not me just duplicated meshes and overlapping them in the world, so that weirdness is a result of my lack of shader experience.

The chunks of terrain will always have the edges of the cubic voxels fall on whole numbers (negative and positive). Essentially, this would be a shader that darkens the frag colors near whole numbers in the world.

Thanks in advance for your help :)

Update: It would appear that the problems stem from the fract calls in these lines:

```
float xx = fract(vertWorldPos.x);
float yy = fract(vertWorldPos.y);
float zz = fract(vertWorldPos.z);

```

Drawing the colors like this: `fragColor = vec4(xx, yy, zz, 1.0);` yields this unexpected behavior:

Note: I also changed the `fract(mvVertexPos.-)` calls to `fract(vertWorldPos.-)` because `mvVertexPos` has been transformed by the matrix, while `vertWorldPos` has not.

# Answer
Ok, I finally got it to work using this annoying-looking method:

```
float epsilona = 0.025;
float epsilonb = 0.0001;

float xx = fract(mvVertexPos.x);
float yy = fract(mvVertexPos.y);
float zz = fract(mvVertexPos.z);
bool nearX = (xx >= -epsilona && xx <= epsilona);
bool nearY = (yy >= -epsilona && yy <= epsilona);
bool nearZ = (zz >= -epsilona && zz <= epsilona);
bool overX = (xx >= -epsilonb && xx <= epsilonb);
bool overY = (yy >= -epsilonb && yy <= epsilonb);
bool overZ = (zz >= -epsilonb && zz <= epsilonb);
if ((nearX && !overX) || (nearY && !overY) || (nearZ && !overZ)) {
    fragColor = vec4(color * vec3(0.3, 0.3, 0.3), 1.0);
}

```

Here's what it looks like (there's some weird glitches when far away, but I can fix those by looking at the transformed z-values and not draw then they're far enough away:
> 2 votes

---
Tags: opengl, shaders, lwjgl, voxels, fragment-shader
---


# Question
Title: Unity 2018 NavmeshBuilder.BuildNavMeshAsync
I am trying to test out the new Navmesh tools as of Unity 2018.1

So i have a simple scene with a plane:

Then i have the following script:

```
    public class SpawnObject : MonoBehaviour
{
    public GameObject ObjectToSpawn;
    // Update is called once per frame
    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            RaycastHit hit;
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);

            if (Physics.Raycast(ray, out hit))
            {
                if (hit.transform.name == "floor")
                {
                    Instantiate(ObjectToSpawn, hit.point, Quaternion.identity);
                    NavMeshBuilder.BuildNavMeshAsync();
                }
            }
        }
    }
}

```

This spawns a prefab and then i attempt to update the navmesh however nothing really happens:

The cube I am spawning has the following properties:

Can anyone tell me what I am doing wrong?

# Answer
> 1 votes
It looks like your object is not marked as nav mesh static and is not a nav mesh obstacle.

Either change the static flags on the prefab (press the down arrow next to the “static” checkbox) or add a nav mesh obstacle component.

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


# Question
Title: Decomposing a concave mesh into a set of convex meshes
I'd like to be able to decompose a concave mesh into a set of convex meshes for 2 reasons:

1. Transparent rendering
2. Physics shapes

Is there an algorithm that takes a set of triangles (concave) as input and outputs a number of sets of triangles (convex)? I'd like it to not fill in the holes between parts of the original mesh.

I've already come across a small idea: find all the concave edges, and split the meshes along the edge loops. Am I on the right track? How could I implement this?

# Answer
I'd say you are on the right track, but coming up with an optimal and/or efficient algorithm is another matter: it's a difficult problem. However, unless your interest is academic, a good-enough solution may suffice.

First, if you are not interested in coming up with your own solution, CGAL contains an algorithm for convex polyhedra decomposition already: http://doc.cgal.org/latest/Convex\_decomposition\_3/index.html

Now for the method; like many problems in 3D, it's often helpful to consider the 2D problem which is easier to understand. For 2D, the task is to identify reflex vertices, and split the polygon into two by creating a new edge (and possibly new vertices) from that reflex vertex, and continuing until you are left with no reflex vertices (and hence all-convex polygons).

Polygon Decomposition by J. Mark Keil contains the following algorithm (in unoptimised form):

```
diags = decomp(poly)
    min, tmp : EdgeList
    ndiags : Integer
    for each reflex vertex i
        for every other vertex j
            if i can see j
                left = the polygon given by vertices i to j
                right = the polygon given by vertices j to i
                tmp = decomp(left) + decomp(right)
                if(tmp.size < ndiags)
                    min = tmp
                    ndiags = tmp.size
                    min += the diagonal i to j
    return min

```

Basically it exhaustively compares all possible partitions, and returns the one with the least diagonals produced. In this sense it is somewhat brute-force and optimal as well.

If you want "nicer looking" decompositions, that is ones that produce more compact shapes rather than elongated ones, you could also consider this one produced by Mark Bayazit, which is greedy (hence much faster) and looks nicer but has a few shortcomings. It basically works by trying to connect reflex vertices to the best one opposite to it, typically to another reflex vertex:

One of the shortcomings is that it ignores "better" decompositions by creating Steiner points (points that do not exist on an existing edge):

The problem in 3D can be similar; instead of reflex vertices, you identify "notch edges". A naive implementation would be to identify notch edges, and perform plane cuts on the polyhedron repeatedly until all polyhedra are convex. Check out "Convex Partitions of Polyhedra: a Lower Bound and Worst-Case Optimal Algorithm" by Bernard Chazelle for more details.

Note that this approach could produce worst case an exponential number of sub-polyhedra. This is because you could have degenerate cases like this:

But if you have a non-trivial mesh (think bumpy surface), you'll get poor results anyway. It's very likely that you'll want to do a lot of simplification beforehand, if you ever need to use this for complex meshes.
> 12 votes

# Answer
Computing an exact convex decomposition of a surface S is an NP-hard problem and usually produces a high number of clusters. To overcome these limitations, the exact convexity constraint may be relaxed and an approximate convex decomposition of S is instead computed. Here, the goal is to determine a partition of the mesh triangles with a minimal number of clusters, while ensuring that each cluster has a concavity lower than a user defined threshold.

Check out the following approximate convex decomposition libraries: https://code.google.com/p/v-hacd/ http://sourceforge.net/projects/hacd/
> 7 votes

# Answer
Here is some code that could help you. It is in java so you'll have to convert it to c++.

Here also is another article that can help you
> 0 votes

---
Tags: c++, algorithm, geometry
---


# Question
Title: TMX crashes in Tablet 10″ Android 7.0 with Andengine
I've developed a video game that has worked fine so far. When testing it in a Samsung Galxy A6 tablet (10" resolution with Android 7.0), I get the following error and the map won't load:

> Blockquote 12-09 12:49:20.940: E/AndroidRuntime(9369): Process: cam.main, PID: 9369 12-09 12:49:20.940: E/AndroidRuntime(9369): java.lang.NullPointerException: Attempt to read from field 'org.anddev.andengine.opengl.texture.region.TextureRegion org.anddev.andengine.entity.layer.tiled.tmx.TMXTile.mTextureRegion' on a null object reference 12-09 12:49:20.940: E/AndroidRuntime(9369): at org.anddev.andengine.entity.layer.tiled.tmx.TMXLayer.drawVertices(TMXLayer.java:220) 12-09 12:49:20.940: E/AndroidRuntime(9369): at org.anddev.andengine.entity.shape.Shape.doDraw(Shape.java:102) 12-09 12:49:20.940: E/AndroidRuntime(9369): at org.anddev.andengine.entity.Entity.onManagedDraw(Entity.java:991) 12-09 12:49:20.940: E/AndroidRuntime(9369): at org.anddev.andengine.entity.shape.Shape.onManagedDraw(Shape.java:120) 12-09 12:49:20.940: E/AndroidRuntime(9369): at org.anddev.andengine.entity.Entity.onDraw(Entity.java:875) 12-09 12:49:20.940: E/AndroidRuntime(9369): at org.anddev.andengine.entity.Entity.onManagedDrawChildren(Entity.java:1008) 12-09 12:49:20.940: E/AndroidRuntime(9369): at org.anddev.andengine.entity.Entity.onDrawChildren(Entity.java:1000) 12-09 12:49:20.940: E/AndroidRuntime(9369): at org.anddev.andengine.entity.Entity.onManagedDraw(Entity.java:993) 12-09 12:49:20.940: E/AndroidRuntime(9369): at org.anddev.andengine.entity.scene.Scene.onManagedDraw(Scene.java:233) 12-09 12:49:20.940: E/AndroidRuntime(9369): at org.anddev.andengine.entity.Entity.onDraw(Entity.java:875) 12-09 12:49:20.940: E/AndroidRuntime(9369): at org.anddev.andengine.engine.Engine.onDrawScene(Engine.java:517) 12-09 12:49:20.940: E/AndroidRuntime(9369): at org.anddev.andengine.engine.Engine.onDrawFrame(Engine.java:509) 12-09 12:49:20.940: E/AndroidRuntime(9369): at org.anddev.andengine.opengl.view.RenderSurfaceView$Renderer.onDrawFrame(RenderSurfaceView.java:154) 12-09 12:49:20.940: E/AndroidRuntime(9369): at org.anddev.andengine.opengl.view.GLSurfaceView$GLThread.guardedRun(GLSurfaceView.java:617) 12-09 12:49:20.940: E/AndroidRuntime(9369): at org.anddev.andengine.opengl.view.GLSurfaceView$GLThread.run(GLSurfaceView.java:549) 12-09 12:49:21.531: E/ApplicationPackageManager(4011): checkSettingsForIconTray value : 0

Rest of screens that are Android native work well. Please help!

# Answer
> 0 votes
After losing my faith in Andengine in particular and in game development in general, I found a solution for a problem that seemed to be happening not in Tablets only but **in any device with Android 7 and higher.**

By exporting the tmx files to .xml instead of GZIP compressed everything works well. Almost magic.

---
Tags: android, andengine
---


# Question
Title: How can I increment the position of the X and Y depending on its value?
How can I increment the position of the X and Y depending on its value

Here's my code :

```
#region BIG EYE ROAD
    for (int col = 0; col < table.GetLength(0); col++)
    {
        for (int row = 0; row < table.GetLength(1); row++)
        {
            if (table[moveCol, moveRow] == null)
            {
                col0 = table[colIndex1, row];
                col1 = table[colIndex2, row];

                if (col0 != null)
                {
                    sum1 += 1;
                }

                if (col1 != null)
                {
                    sum2 += 1;
                }
                counter1++;
            }
            else
            {
                if (counter1 == 0)
                {
                    data1 = table[firstTableCol, firstTableRow];
                    data2 = table[secondTableCol, secondTableRow];
                    data3 = table[thirdTableCol, thirdTableRow];
                    data4 = table[fourthTableCol, fourthTableRow];

                }
                else
                {
                    if (moveRow > 1)
                    {
                        firstTableRow = moveRow;
                        secondTableRow = moveRow - 1;
                        thirdTableRow = moveRow;
                        fourthTableRow = moveRow - 1;
                    }

                    else if (moveRow == 1)
                    {
                        firstTableRow = 1;
                        secondTableRow = 0;
                        thirdTableRow = 1;
                        fourthTableRow = 0;
                    }

                    if (moveCol > 1)
                    {
                        firstTableCol = moveCol;
                        secondTableCol = moveCol;
                        thirdTableCol = moveCol - 1;
                        fourthTableCol = moveCol - 1;
                    }

                    data1 = table[firstTableCol, firstTableRow];
                    data2 = table[secondTableCol, secondTableRow];
                    data3 = table[thirdTableCol, thirdTableRow];
                    data4 = table[fourthTableCol, fourthTableRow];

                }
                if (data1 != null && data2 != null && data3 != null && data4 != null)
                {
                    redBead();
                }
                else if (data1 != null && data2 != null && data3 == null && data4 == null)
                {
                    redBead();
                }
                else
                {
                    blueBead();
                }

                if (moveRow + 1 < table.GetLength(1))
                {
                    moveRow++;
                }
            }
        }

        if (sum1 == sum2)
        {
            redBead();
        }
        else
        {
            blueBead();
        }
        //reset
        sum1 = 0;
        sum2 = 0;

        if (colIndex1 + 1 < table.GetLength(0) && colIndex2 + 1 < table.GetLength(0))
        {
            colIndex1++;
            colIndex2++;
        }
        else
        {
            //nothing to do
        }

        if (moveCol + 1 < table.GetLength(0))
        {
            moveCol += 1;
        }
        if (moveRow + 1 < table.GetLength(1))
        {
            moveRow = 1;
        }

        #endregion
    }
}
void blueBead()
{
    p = Instantiate(big_eye_gameobject) as GameObject;
    p.transform.SetParent(pos_big_eye_road);
    p.transform.localScale = Vector3.one;

    img = (RawImage)p.GetComponent<RawImage>();

    img.texture = NewTexture[0];
    p.SetActive(true);

    p.transform.localPosition = new Vector3(bigEyeXIndex * 56, bigEyeXIndex * -45, 0f);
}

void redBead()
{
    p = Instantiate(big_eye_gameobject) as GameObject;
    p.transform.SetParent(pos_big_eye_road);
    p.transform.localScale = Vector3.one;

    img = (RawImage)p.GetComponent<RawImage>();

    img.texture = NewTexture[1];
    p.SetActive(true);

    p.transform.localPosition = new Vector3(bigEyeXIndex * 56, bigEyeXIndex * -45, 0f);
}

```

What I am trying to do here: I have this variables called `int bigEyeXIndex = 0;` and `int bigEyeYIndex = 0;` . So everytime that my value is different and not the same it will increment my X and Y axis for example like this

But what is happening to me right now is like this

# Answer
> 1 votes
Got it .

```
  enum beadColor
{
    BLUE,
    RED,
    NONE,
}

void OnBeadIncreased(beadColor color)
{
    if (color == previous)
    {
        bigEyeYIndex++;
    }
    else
    {
        bigEyeXIndex++;
        bigEyeYIndex = 0;
    }

    if (previous == beadColor.NONE)
    {
        bigEyeXIndex = 0;
        bigEyeYIndex = 0;
    }

    previous = color;
}

```

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


# Question
Title: Why when loading a scene it's taking too much time?
I have two scenes in the Hierarchy when running the game. And this script attached to empty GameObject:

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

public class LoadScenes : MonoBehaviour
{
    // Use this for initialization
    void Start()
    {
        if (!SceneManager.GetSceneByName("The Space Station").IsValid())
        {
            SceneManager.LoadScene(1, LoadSceneMode.Additive);
            StartCoroutine(WaitForSceneLoad(SceneManager.GetSceneByName("The Space Station")));
        }
    }

    public IEnumerator WaitForSceneLoad(Scene scene)
    {
        while (!scene.isLoaded)
        {
            yield return null;
        }
        SceneManager.SetActiveScene(SceneManager.GetSceneByBuildIndex(1));
    }
}

```

But it's taking like 3-4 seconds until it's getting to the line:

```
SceneManager.SetActiveScene(SceneManager.GetSceneByBuildIndex(1));

```

# Answer
Scene loading always depends on resource (prefabs, game objects, audios, textures, etc.) usage. If scene has a lot of objects in it, or scripts instantiate objects in awake or start methods, scene loading will take much more time.

Async Object Management in Unity3D Forum.

LoadSceneAsync Unity3D Docs.
> 1 votes

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


# Question
Title: Xna/Monogame How to get an object to decelerate
So I've written a statement for releasing the ball based on a certain speed and for it to move in the direction of the mouse, like so:

```
            MouseX = stateOfTheMouse.X;
            MouseY = stateOfTheMouse.Y;
            difference = Vector2.Subtract(position, new Vector2(MouseX, MouseY));
            direction = Vector2.Normalize(difference);
            velocity.X -= ((float)(usedSpeed / 2));
            velocity.Y -= ((float)(usedSpeed / 2));

```

Then in my updateI call this

```
            position += velocity * direction;

```

I assign usedSpeed as an integer with the press of a NumPad key 1-5 each on reflects the speed amount hence NumPad1 = speed of 1, etc.

Therefore, how would I make the velocity decelerate and slow down to a complete stop?

# Answer
> 2 votes
You can decelerate your object by multiplying its velocity with value smaller than 1 and greater than 0, the smaller the value, the faster it decelerates. For example:

```
public readonly float Friction = 0.98f;
/* ... */

public void Update(GameTime gameTime)
{
    /* your code here */

    velocity *= Friction; // Here we go
}

```

# Answer
> 0 votes
In your update method, just reduce the velocity (increase if negative, otherwise decrease)

```
var resistence = -0.05f; // change this
if (velocity.X != 0)
{
    if (velocity.X < 0) { velocity.X += resistance; }

    if (velocity.X > 0 )
    {
        velocity.X -= resistance;
    }
}

if (this.vel.Y != 0)
{
    if (this.vel.Y < 0) { this.vel.Y += resistance; }

    if (this.vel.Y > 0 && tempY == this.vel.Y)
    {
        this.vel.Y -= resistance;
    }
}

```

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


# Question
Title: Why my keyPressed method stops reacting to any key i press after i hold (W/A/S/D) for 1 or 2 seconds?
```
public class Testing extends JPanel{

    public void Action() {
        Timer t = new Timer();
        t.schedule(new TimerTask() {

            public void run() {
                if(move2==true) {
                    switch(direction2) {
                    case 1 : x-=2;
                    break;
                    case 2 : x+=2;
                    break;
                    case 3 : y-=2;
                    break;
                    case 4 : y+=2;
                    }
                }
                repaint();
            }

        }, 10, 20);
    }

    public void paint(Graphics g)
    {
        g.clearRect(0, 0, 526, 690);
        g.drawLine(x, y, x, y-30);
        g.drawLine(x+1, y, x+1, y-30);
        g.drawLine(x-1, y, x-1, y-30);

    }
    static boolean move2 = false;
    static int x = 200;
    static int y = 100;
    static int direction2 = 0;
    public static void main(String[] args) {
    JFrame f = new JFrame();
    Testing t = new Testing();
    f.setVisible(true);
    f.setSize(526,690);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.setLocationRelativeTo(null);
    f.setFocusable(true);
    f.add(t);
    t.Action();
    f.addKeyListener(new KeyListener() {

        public void keyTyped(KeyEvent e) {

        }
        public void keyPressed(KeyEvent e) {
            System.out.println("did");
            switch(e.getKeyCode()) {
            case KeyEvent.VK_A:
                move2 = true;
                direction2 = 1;

                break;
            case KeyEvent.VK_D:

                move2 = true;
                direction2 = 2;
                break;
            case KeyEvent.VK_W:

                move2 = true;
                direction2 = 3;
                break;
            case KeyEvent.VK_S:

                move2 = true;
                direction2 = 4;
                break;
            }

        }

        public void keyReleased(KeyEvent e) {
            switch(e.getKeyCode()){
            case KeyEvent.VK_A:move2 = false;
            break;
            case KeyEvent.VK_D:move2=false;
            break;
            case KeyEvent.VK_W:move2=false;
            break;
            case KeyEvent.VK_S:move2=false;
            }
        }
    });
    }

}

```

# Answer
> 1 votes
The problem is not your code it is rather your Keyboard...

...most modern keyboards don't support enough key presses, aka as `N-Key-Rollover` (http://blog.controlspace.org/2010/08/n-key-rollover-what-it-is-and-how-to.html) so your event are 'swallowed'

***N-key rollover relates to the ability of a keyboard to correctly recognize multiple key presses at once (in the case, the ability to press as many keys as you want)...***

---
Tags: java, jframe
---


# Question
Title: adding virtual-joystick relative layout to a surfaceview in Android
The problem: I have my main class which extends surfaceview that contains the gameloop and I want it to use the virtual joystick found here (https://github.com/controlwear/virtual-joystick-demo) but I have been unsuccessful in getting the joysticks to appear alongside the game. I either do

```
setLayout(R.layout.layout) //OR
setLayout(game)

```

I am very new to Android Programming and I've looked into the manuals available to me but I am having trouble finding a solution to merge the two layouts. Do I have to do two seperate layout views? And how would I do that?

What I've tried doing in the Activity class, right now giving me an error (Cannot add a null child view to a ViewGroup)

```
public class GalaxyMonkeysActivity extends Activity {

Game game;

@Override
protected void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);

    // get the screen resolution
    Display display = getWindowManager().getDefaultDisplay();
    Point size = new Point();
    display.getSize(size);

    game = new Game(this, size);

    RelativeLayout layout = new RelativeLayout(getApplicationContext());
    View right = findViewById(R.id.joystickView_right);
    View left = findViewById(R.id.joystickView_left);
    layout.addView(right);
    layout.addView(left);
    layout.addView(game);

    setContentView(R.layout.layout);

```

and in my game class which extends surfaceview

```
 if (state == STATE.GAME) {

                JoystickView joystickLeft = (JoystickView) findViewById(R.id.joystickView_left);
                joystickLeft.setOnMoveListener(new JoystickView.OnMoveListener() {
                    @Override
                    public void onMove(int angle, int strength) {
                        for (int i = 0; i < handler.object.size(); i++) {
                            int mx = (int) Math.cos(angle);
                            int my = (int) Math.sin(angle);
                            GameObject tempObject = handler.object.get(i);

                            if (tempObject.getId() == ID.Player) {
                                handler.addObject(new Bullet((int) tempObject.x + 16,
                                        (int) tempObject.y + 24, ID.Bullet, handler, mx, my, screenX, screenY, getContext()));
                            }
                        }
                    }
                });

                JoystickView joystickRight = (JoystickView) findViewById(R.id.joystickView_right);
                joystickRight.setOnMoveListener(new JoystickView.OnMoveListener() {
                    @Override
                    public void onMove(int angle, int strength) {
                        for (int i = 0; i < handler.object.size(); i++) {
                            GameObject tempObject = handler.object.get(i);

                            if (tempObject.getId() == ID.Player) {
                                if (angle > 45 && angle < 135)
                                    handler.setUp(true);
                                if (angle > 135 && angle < 225)
                                    handler.setLeft(true);
                                if (angle > 225 && angle < 305)
                                    handler.setDown(true);
                                if (angle > 305 && angle < 45)
                                    handler.setRight(true);

                            }

                        }
                    }
                });

```

and in my layout.xml

```
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp"
tools:context="com.theGalaxyMonkey.GalaxyMonkeysActivity"
android:background="@drawable/back"
android:id="@+id/main_layout">

<io.github.controlwear.virtual.joystick.android.JoystickView xmlns:custom="http://schemas.android.com/apk/res-auto"
    android:id="@+id/joystickView_left"
    android:layout_width="166dp"
    android:layout_height="148dp"
    android:layout_alignParentBottom="true"
    android:layout_alignParentStart="true"
    android:background="@drawable/joystick_background"
    custom:JV_buttonImage="@drawable/pink_ball"
    custom:JV_fixedCenter="true" />

<io.github.controlwear.virtual.joystick.android.JoystickView xmlns:custom="http://schemas.android.com/apk/res-auto"
    android:id="@+id/joystickView_right"
    android:layout_width="154dp"
    android:layout_height="205dp"
    android:layout_alignParentBottom="true"
    android:layout_alignParentEnd="true"
    custom:JV_backgroundColor="#009688"
    custom:JV_borderColor="#00796B"
    custom:JV_borderWidth="8dp"
    custom:JV_buttonColor="#FF6E40" />

```

I've also tried:

```
    setContentView(R.layout.layout);
    addContentView(game, new RelativeLayout.LayoutParams(size.x, size.y));

```

which this plays the game, however, it isn't effective as the joysticks are underneath a layer of the main menu background.

# Answer
one simple solution would be to add your game view to the `layout.xml` directly:

```
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://sche...>

<io.github.controlwear.virtual.joystick.android.JoystickView... /> <!-- left -->
<io.github.controlwear.virtual.joystick.android.JoystickView.../> <!-- right -->
<your.game.package.Game .../> <!-- your Game view extends SurfaceView -->

```

(please excuse that i've shortened the xml)

after you've done that your activity should be done by simply calling `setContentView(R.layout.layout);` \- you can skip the part, where you manually/programmatically add views to the layout.

Hints on your errors: if you try to get a view with `findViewById` **before** you have created the view (by calling `setContentView(R.layout.layout);`) the method will return `null` (see View Api) and `null`cannot be added to a `Layout`...
> 0 votes

---
Tags: java, android, view
---


# Question
Title: Java Swing KeyBindings do not recognize input in a weird way
I am new to programming, so forgive me if I make silly mistakes.

I want to make a game, and I started by making the player, and that's where I'm stuck at. I'm trying to use Keybindings (InputMap and ActionMap of a JComponent) to make the player move, but something really odd is happening. When I hold "A" to make the player move to the left, that's what he does. But if I then press "D" to make him move right, he just stands still. Then, if I release and press "D" again, it does move. This happens with all of my keyboards, and I had a similar problem when using a KeyListener.

This seems like a problem with another class, like the Player class, but it isn't: When the situation i described occurs, the AbstractActions I created aren't being called! And that was the same with the KeyPressed() method when I was using a KeyListener.

This is my class for managing keyboard-input:

```
import java.awt.event.ActionEvent;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JLabel;
import javax.swing.KeyStroke;

public class KeyManager {

private JLabel keyManager;

private Action leftTrue, leftFalse, rightTrue, rightFalse;

public boolean left = false, right = false, up = false, down = false;

public KeyManager() {
    initActions();

    keyManager = new JLabel();
    System.out.println("called");

    keyManager.getInputMap(JLabel.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("D"), "pressed_D");
    keyManager.getInputMap(JLabel.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("released D"), "released_D");
    keyManager.getInputMap(JLabel.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("A"), "pressed_A");
    keyManager.getInputMap(JLabel.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("released A"), "released_A");

    keyManager.getActionMap().put("pressed_D", rightTrue);
    keyManager.getActionMap().put("pressed_A", leftTrue);
    keyManager.getActionMap().put("released_D", rightFalse);
    keyManager.getActionMap().put("released_A", leftFalse);
}

public JLabel getKeyManager() {
    return keyManager;
}

private void initActions() {

    leftTrue = new AbstractAction() {

        private static final long serialVersionUID = 1L;

        @Override
        public void actionPerformed(ActionEvent e) {
            System.out.println("pressed a");
            left = true;

        }

    };
    leftFalse = new AbstractAction() {

        private static final long serialVersionUID = 2L;

        @Override
        public void actionPerformed(ActionEvent e) {
            System.out.println("released a");
            left = false;

        }

    };
    rightTrue = new AbstractAction() {

        private static final long serialVersionUID = 3L;

        @Override
        public void actionPerformed(ActionEvent e) {
            System.out.println("pressed d");
            right = true;

        }

    };
    rightFalse = new AbstractAction() {

        private static final long serialVersionUID = 4L;

        @Override
        public void actionPerformed(ActionEvent e) {
            System.out.println("released d");
            right = false;

        }

    };

}

}

```

The JLabel object is added to my JFrame in another class

I don't feel like my explanation of the problem made much sense, so here's a video of what's happening:

https://www.dropbox.com/s/7bs6r1kt6z489rf/JavaHelp.mov?dl=0

Does someone know how to fix this? :(

# Answer
> 0 votes
uhm i've postet an answer to a very similar question, it's about `N-key rollover`...

i'm really sorry to post a 'link-only' answer, but have a look at this question from this forum =)

---
Tags: java, input
---


title: Unity Quaternion.LookRotation meaning

text:
# Question
Title: Unity Quaternion.LookRotation meaning
I've gone through Unity's documentation for **Quaternion.LookRotation**, but I didn't get the full understanding of how it works.

1. What is the meaning of **Creates a rotation with the specified forward and upwards directions?**
2. And if I have to rotate my object in X axis I have to modify both X and Z axis`Vector3 lookAt = new Vector3(relativePos.x, 0, relativePos.z);
transform.rotation = Quaternion.LookRotation(lookAt);`, why can't I only just modify the X axis directly to rotate?

# Answer
`Quaternion.LookRotation(forward, up)` constructs an orientation quaternion that...

* rotates an object's local z+ axis (0, 0, 1) — the blue arrow on its local translation gizmo — to point *exactly* in the worldspace direction you pass as `forward`. It makes the object "look" in that direction.
* rotates an object's local y+ axis (0, 1, 0) — the green arrow on its local translation gizmo — to point *as close as possible to* the worldspace direction you pass as `up` (or to world up if you skip this parameter). This controls the twist or roll about that forward axis.

By specifying a `forward` direction of the form `(x, 0, z)`, you're ensuring that the resulting rotation will look along the XZ plane. ie. it will be a yaw rotation about the y axis, with no pitch / x-axis rotation upward or downward.
> 5 votes

# Answer
I am not sure what you mean with "modify the X axis". If you intend to do `transform.rotation.x = value`, then you are going to fail, because quaternions are not that simple. There is a reason why the documentation says "Don't modify this directly unless you know quaternions inside out.". You should only modify the individual fields of a Quaternion when you actually understand the math behind them. And very few developers actually understand it, so don't feel bad when your head starts to hurt. Just accept that quaternions are magic and get on with your life.

Or maybe you are thinking about rotating a Quaternion with `transform.rotation *= Quaternion.Euler(x, 0.0f, 0.0f);`. Now you are on the right track. But when you want one object to rotate so that it faces a certain point, then you have to calculate the values for `x` yourself. And if your knowledge of trigonometry isn't the freshest, you might have to think a few minutes about how to calculate that correctly.

That's why there is a convenient method just for this common use-case.

If you just want one object to rotate in a way that it faces a different game object, you use `Quaternion.LookRotation(position);`. Now you might wonder why you need the additional "upwards" vector. Note that when you are looking from the perspective of the object, then there are three ways to rotate it:

* pitch
* yaw
* roll

You usually want to change only *pitch* and *yaw* and keep the *roll* the way it is. But sometimes in order to do that you need to tell the engine the difference between pitching, yawing and rolling. That's what the `upward`-vector is for. Note that this is an optional argument. You can omit it. The engine will then assume you mean upwards in world-space. But sometimes you want to use a different upward-axis. The `upward` parameter allows you to do that if you want to.

For a possible use-case, consider a space ship with turrets attached on the top and on the sides. You want all those turrets to be able to track enemy fighters in a hemisphere oriented relative to their mounting-point. The best way to do that is obviously by using `Quaternion.LookRotation(enemy.transform.position - turret.transform.position)`. But you still want all the guns to stay level relative to the hull of the space ship and not rotate around the barrel-axis. This is additionally complicated by the fact that the ship *itself* is able to rotate. So you need to tell `LookRotation` which way is up for that specific turret.
> 3 votes

---
Tags: unity, c#, rotation, quaternion
---


# Question
Title: VSSetConstantBuffers1 does not appear to be working
I'm experiencing something very strange here when using VSSetConstantBuffers1.

I have a projection * world matrix that I'm sending to a constant buffer to rotate a triangle on an axis. When I do this, I follow this pattern:

Frame #1

* Set offset to 0, count is always at 64 (4 * float4)
* Map Constant Buffer using Discard.
* Write matrix to constant buffer
* Unmap
* Call VSSetConstantBuffers1(0, 1, new \[\]{ cbuffer }, new \[\]{offset }, new \[\]{ count })
* Draw

Frame #2

* Set offset to 64, count remains same.
* Map constant buffer using NoOverwrite
* Write matrix.
* Unmap
* Call VSSetConstantBuffers1(0, 1, new \[\]{ cbuffer }, new \[\]{offset }, new \[\]{ count })
* Draw

Etc... When I fill the constant buffer completely, I reset offset to 0, and start again by using discard on my map.

Now here's my problem: Nothing shows up on the screen. Well, that's not 100% true, the very first frame, where offset = 0 and count = 64, that shows up perfectly. The next frame, and subsequent frames do not.

I used the Visual Studio 2017 graphics debugger to confirm that my constant buffer did indeed have data in it. And it did, and the values were correct.

It's really weird. I should be mapping the constant buffer to the next matrix element with my 2nd call to VSSetConstantBuffers1, but it doesn't actually look like it's going anywhere near that element.

Also, I tried forcing it to just use the 0, and 64 offset/count and only updating that portion of the buffer, and it works just fine.

I've tried my best to dig up info about constant buffer offset/count, but it's pretty sparse out there (my own searches on this site gave me 0 for VSSetConstantBuffers1, same with GameDev.net). What little I did scrounge up on Nvidia's website, makes it appear as though this pattern should work.

Since my hardware might come into question here, I have a GeForce 1080 GTX running on Windows 10 (latest update), and according to the D3D11.1 options, it does indeed support constant buffer offsets, and my feature level is at max.

Anyone have any ideas? Given the lack of info, I'm guessing the offset/count versions of constant buffers aren't too popular?

# Answer
> 0 votes
So, thanks to some people on GameDev.Net, and a review of the documentation, I realized that my offset/count assumptions were incorrect.

I had assumed it was aligned to 16 bytes per element for the offset/count, when in reality, it's 16 elements (256 bytes). So instead of a count of 64, it should have been 16, and the same with the offset on the next frame.

---
Tags: c#, directx11, sharpdx, visual-studio
---


# Question
Title: Nvidia High Performance Processor Setting leads to graphical bug (Seizure Warning) with current lighting system, drawing completely in the shader code
I followed the Lighting tutorial on learnopenGL, modifying some of the code to work in a 2D game engine. Everything was looking great and my team got our game done and the lights were quite simple for our designers to use. However we ran into a rare bug. as shown here: https://www.youtube.com/watch?v=to0mMP5I0cs one team member was able to recreate the bug by switching his Nvidia settings to use the "High Performance Processor" as opposed to "Integrated Graphics". Otherwise everything renders properly. The bug doesn't appear when there are no lights and everything is rendered in its full color. We have gone through alot of Ideas already but they haven't worked and now I am at a loss. Does anyone have any ideas about what is going on?

# Answer
Always make sure you initialize your variables. Apparently some cards and drivers automatically initialize vec3 to (0,0,0), but others don't. That was what was going on here. Garbage values causing different colors at each fragment. By Initializing my resulting color vec3 to (0,0,0) at the beginning the problem is fixed.
> 3 votes

---
Tags: opengl, c++, nvidia
---