# Question
Title: How can I prevent small numerical advantages from dominating the balance of an encounter?
I've been tinkering for some time with a game and I'm having a fair amount of trouble with something:

I have two characters, each of whom have attributes (about ten) in a range (between 1 and 20). I want to use these attributes to generate a 'roll' such that the higher roll wins that particular encounter. It's worth noting that the two characters are *not* damaging/defending each other. They're both rolling to see if they pass what I guess we could call a skill check. They're both rolling to pass/fail against a common value. They do not interact with one another.

However, when one of the characters has even a small numerical advantage, any formula I've come up with results in the ever-so-slightly superior one winning a huge majority of the time. This is undesirable.

I've tried weighting the 'most relevant' attribute for the test at 80% and the sum of the other attributes at 20%. I also tried comparing averages to produce a relative difference and using that to boost the weaker character. Both approaches resulted in the significant advantages I'm trying to remove (for example, if I run the encounter 5,000 times, it quite regularly produces one side winning all 5,000).

Adding a "luck" component only matters, it seems, if it's weighted somehow in favour of the lesser character, and I haven't hit a good balance there.

What approaches can I take to blunt the impact of a small numerical advantage but still preserve and increase that advantage as the relative gap in attributes increases?

---

Per the request, here are the specifics I have so far. Some things I haven't figured out yet so they remain generalities:

At the moment, the roll is generated as

```
0.8 * (mainAttribute) + 0.2 (1/3 * subAttA + 1/3 * subAttB * 1/3 subAttC)

```

At present, this produces numbers in the neighborhood of 4.0. Attributes are randomly generated between specified ranges. The current test uses one character with attributes from 2 to 4, and the opponent between 3 and 5. Predictably, this produce averages close to 3 and 4 respectively.

With this one-point advantage, I'd like to see the stronger of the two win in the area of 55% to 60% of the time, with this scaling up to winning about 80% of the time with an average attribute advantage of 5 or 6, 90% at advantages of 7 or 8, leaving some room for an unlikely win when the gap grows larger. I'd prefer not to ever have guaranteed wins, but perhaps things becoming very unlikely - to the tune of winning 99.5% or 99.6% of the time when the gap gets very large.

The current formula produces a non-random number. Randomness comes from the selection of which attributes are relevant. Not *all* of the attributes are used for each roll. It's possible for the one with the overall weaker attributes to be stronger in the areas relevant to that roll, and steal a win. But, predictably, it happens rarely.

My next attempt was to weigh their relative strengths, by taking an average of all of each's stats, dividing them against each other, and using that value to give a small boost to the lesser character. This smoothed things out a little, but still had a pronounced tendency to produce things like 5,000 wins for one guy out of 5,000 tries.

# Answer
The problem with your approach is that you decide the result of the combat the moment you decide on the main stat. When you have 4 main stats, and the fighter is only better in one of them, their win-chance is always 1 in 4, no matter how large the differences actually are. When you want more fine-grained results, you need more fine-grained randomness.

First of all, I think you can keep your random pick for the main attribute and you can also keep your formula if you want to. It is the number which represents how much of an edge this combatant has in this specific encounter. For the rest of this post, I will refer to this as just `power`.

A method which I used in quite a lot of games and which served me quite well when it comes to a duel between two *things* with a certain `power`, is to roll a random floating-point number between `0` and `power` for both and see who rolled higher. Here is a list of the expected results of this method. The percentages are not calculated but generated experimentally by running 100000 fights per combination and iteration count and counting who won how often:

```
PowerA | PowerB | Win chance of A
  9    |   1    |    94.5%
  8    |   2    |    87.5%
  7    |   3    |    78.6%
  6    |   4    |    66.6%
  5    |   5    |    50.0%
  4    |   6    |    33.3%
  3    |   7    |    21.5%
  2    |   8    |    12.5%
  1    |   9    |    5.5%

```

The nice thing about this algorithm is that it scales no matter how large the numbers are you are dealing with. The chance of 0.3 vs 0.7 is the same as that of 3 vs 7, 300 vs. 700 or 3,000,000,000 vs. 7,000,000,000.

When this is still too unpredictable for your taste, you can make the combat more predictable by rolling multiple random numbers for each combatant and add them up. Due to the law of large numbers, many random events will even out and result in more predictable results. Here is a table with different number of iterations.

```
| A | B | Iterations
|   |   |       1 |     2 |     3 |     4 |     5 |     6 |     7 |     8 |     9 |
-----------------------------------------------------------------------------------
| 9 | 1 |   94.5% | 99.3% | 99.9% |100.0% |100.0% |100.0% |100.0% |100.0% |100.0% |
| 8 | 2 |   87.4% | 96.3% | 98.8% | 99.5% | 99.8% |100.0% |100.0% |100.0% |100.0% |
| 7 | 3 |   78.7% | 89.2% | 94.0% | 96.6% | 97.8% | 98.9% | 99.2% | 99.6% | 99.7% |
| 6 | 4 |   66.8% | 74.3% | 79.2% | 82.9% | 85.7% | 88.0% | 89.9% | 91.2% | 92.5% |
| 5 | 5 |   50.0% | 50.0% | 50.0% | 50.0% | 50.0% | 50.0% | 50.0% | 50.0% | 50.0% |
| 4 | 6 |   33.6% | 25.6% | 20.9% | 17.1% | 14.7% | 12.0% | 10.2% |  8.9% |  7.5% |
| 3 | 7 |   21.4% | 10.7% |  6.0% |  3.5% |  2.0% |  1.2% |  0.7% |  0.4% |  0.3% |
| 2 | 8 |   12.7% |  3.7% |  1.2% |  0.4% |  0.1% |  0.1% |  0.0% |  0.0% |  0.0% |
| 1 | 9 |    5.5% |  0.7% |  0.1% |  0.0% |  0.0% |  0.0% |  0.0% |  0.0% |  0.0% |

```

The results of 100% and 0% in the above table are an illusion due to rounding differences. Unless the `power` of a combatant is exactly 0 there is always the possibility that they win. It just didn't happen in the above test, so you can expect it to be below 1:100000.

You might also notice some slight irregularities which can be attributed to mood swings of java.lang.Random and might not appear when you run the code again with a different seed.

The program I used to generate this table (Java).

```
public class Main {

    private static Random random = new Random();
    private static final int SAMPLES = 100000;

    public static void main(String[] args) {
        for (int i = 1; i < 10; i++) {
            double powerA = 10.0 - i;
            double powerB = i;
            System.out.print("| ");
            System.out.print((int)powerA);
            System.out.print(" | ");
            System.out.print((int)powerB);
            System.out.print(" |   ");

            for (int iterations = 1; iterations < 10; iterations++) {
                int wins = 0;
                for (int j = 0; j < SAMPLES; j++) {
                    if (fight(powerA, powerB, iterations)) wins++;
                }
                System.out.print(String.format("%2.1f", 100.0 * (double)wins / (double)SAMPLES));
                System.out.print("% | ");
            }
            System.out.print("\n");
        }
    }

    private static boolean fight(double powerA, double powerB, int iterations) {
        double sumA = 0.0f;
        double sumB = 0.0f;
        for (int i = 0; i < iterations; i++) {
            sumA += random.nextDouble() * powerA;
            sumB += random.nextDouble() * powerB;

        }
        return sumA > sumB;
    }
}

```

If you would like to use this code in your game, it is licensed under the WTF Public License Version 2 as published by Sam Hocevar.
> 36 votes

# Answer
Your mistake is using a "dice based" approach. You're on a computer you can use any system you like. Make a table that turns a difference in values into a %age chance to win and then you can set the values to absolutely anything you like, e.g.

```
Difference (A-B) | %chance A wins
-----------------|---------------
+5 or greater    | 100%
+4               | 95%
+3               | 85%
+2               | 70%
+1               | 55%
0                | 50%

```

(You only need do half the table, simply always choose A as the one with the higher stat)

Obviously, these numbers are just an example, you can make it follow whatever distribution pleases you.
> 13 votes

# Answer
This is a pretty deep question, honestly, from a game mechanics standpoint. But there are a few things that might help.

First, this is why most games have a separate component for hit and damage, where there's a "roll" to see if you hit for damage, then a "roll" against a damage table or range for the given character. This also leads to some standard archetypes across genres, where you might have smaller, quicker characters that have fewer hitpoints but deal more damage (glass cannon mages, certain types of rogues) and larger, armored characters that hit for less damage (tanks, warriors).

This leads to a natural balance where the smaller character might be fragile, but avoids being hit as often due to an agility-type ability, and also evens the playing field by doing more damage (a spell, or a poison effect that does damage over time). The tank might be slower and get hit more often, but often has a huge well of health or hitpoints to sustain, however tends to do less damage per hit (or damage per second).

The background for these is why many games continually go through balancing of weapons and classes and stats. World or Warcraft, Destiny, Diablo, Battlefield: any type of game in any genre often goes through balancing and tuning over time.

This may not be a direct answer, but you did ask for general ideas. So, let's also evaluate the play system.

How do those attributes function? If all else is equal (no archetype, no armor or better weapons or whatnot), then any slight gain is absolutely likely to throw things heavily in favor of one side. While adding facets to combat complicates any system, it also allows for more flexibility.
> 5 votes

# Answer
There's two big things.

First, remember you are on a computer. You can make any system you want. No need to limit yourself to a d20 roll, though this is easy to comprehend for players. Things like rolling 6 d6 dice are easy on a computer and they give far less random results.

Second, looking at other systems like D&D it is obvious that they simply throttle down the effect of attributes a great deal. Instead of having your base stat add 80% of its value to the rule, scale it down and make its addition more subtle. In D&D for example if you have 18 dexterity you get just 4 as a bonus to your armor class.

So in short numerically all you need to do is scale down your domain to fit your range better. But qualitatively I would think looking at other systems and coming up with things that seem less mathematic would make for a more satisfying system for the player.
> 2 votes

# Answer
How about this: Add a constant, e.g. 1000, to all attributes concerned. Then the relative difference becomes very small.
> 1 votes

# Answer
**Know your numbers**

Adding a bit to Philipp's answer, namely that rand\[x\] compared to rand\[y\] may not always produce what one expects. Below a table where we compare A to B. Both A and B have the values 1...10. We compare in two ways (note: rand() in this case generates integers, ie. rolls):

1. rand\[A\] \> rand\[B\]
2. rand\[A\] ≥ rand\[B\] (ie. greater or equal to)

Additionally we compare

3. rand\[A\*1000000\] \> rand\[B\*1000000\]
(in this case it is irrelevant whether it is \> or ≥ as they are so close). These big figures are within parenthesis.

Cells hold %'s. Each result is holds 1 million iterations (made using Dyalog APL).

```
┌────────────┬────────────┬────────────┬────────────┬────────────┬────────────┬────────────┬────────────┬────────────┬────────────┬────────────┐
│ A↓      B→ │ 1 (1000000)│ 2 (2000000)│ 3 (3000000)│ 4 (4000000)│ 5 (5000000)│ 6 (6000000)│ 7 (7000000)│ 8 (8000000)│ 9 (9000000)│10(10000000)│
├────────────┼────────────┼────────────┼────────────┼────────────┼────────────┼────────────┼────────────┼────────────┼────────────┼────────────┤
│ 1 (1000000)│ >0(50) ≥100│  >0(25) ≥50│  >0(17) ≥33│  >0(13) ≥25│  >0(10) ≥20│   >0(8) ≥17│   >0(7) ≥14│   >0(6) ≥13│   >0(6) ≥11│   >0(5) ≥10│
├────────────┼────────────┼────────────┼────────────┼────────────┼────────────┼────────────┼────────────┼────────────┼────────────┼────────────┤
│ 2 (2000000)│>50(75) ≥100│ >25(50) ≥75│ >17(33) ≥50│ >12(25) ≥38│ >10(20) ≥30│  >8(17) ≥25│  >7(14) ≥21│  >6(13) ≥19│  >6(11) ≥17│  >5(10) ≥15│
├────────────┼────────────┼────────────┼────────────┼────────────┼────────────┼────────────┼────────────┼────────────┼────────────┼────────────┤
│ 3 (3000000)│>67(83) ≥100│ >50(67) ≥83│ >33(50) ≥67│ >25(37) ≥50│ >20(30) ≥40│ >17(25) ≥33│ >14(21) ≥29│ >12(19) ≥25│ >11(17) ≥22│ >10(15) ≥20│
├────────────┼────────────┼────────────┼────────────┼────────────┼────────────┼────────────┼────────────┼────────────┼────────────┼────────────┤
│ 4 (4000000)│>75(87) ≥100│ >62(75) ≥88│ >50(62) ≥75│ >37(50) ≥63│ >30(40) ≥50│ >25(33) ≥42│ >21(29) ≥36│ >19(25) ≥31│ >17(22) ≥28│ >15(20) ≥25│
├────────────┼────────────┼────────────┼────────────┼────────────┼────────────┼────────────┼────────────┼────────────┼────────────┼────────────┤
│ 5 (5000000)│>80(90) ≥100│ >70(80) ≥90│ >60(70) ≥80│ >50(60) ≥70│ >40(50) ≥60│ >33(42) ≥50│ >29(36) ≥43│ >25(31) ≥38│ >22(28) ≥33│ >20(25) ≥30│
├────────────┼────────────┼────────────┼────────────┼────────────┼────────────┼────────────┼────────────┼────────────┼────────────┼────────────┤
│ 6 (6000000)│>83(92) ≥100│ >75(83) ≥92│ >67(75) ≥83│ >58(67) ≥75│ >50(58) ≥67│ >42(50) ≥58│ >36(43) ≥50│ >31(38) ≥44│ >28(33) ≥39│ >25(30) ≥35│
├────────────┼────────────┼────────────┼────────────┼────────────┼────────────┼────────────┼────────────┼────────────┼────────────┼────────────┤
│ 7 (7000000)│>86(93) ≥100│ >79(86) ≥93│ >71(79) ≥86│ >64(71) ≥79│ >57(64) ≥71│ >50(57) ≥64│ >43(50) ≥57│ >38(44) ≥50│ >33(39) ≥44│ >30(35) ≥40│
├────────────┼────────────┼────────────┼────────────┼────────────┼────────────┼────────────┼────────────┼────────────┼────────────┼────────────┤
│ 8 (8000000)│>88(94) ≥100│ >81(87) ≥94│ >75(81) ≥87│ >69(75) ≥81│ >63(69) ≥75│ >56(62) ≥69│ >50(56) ≥62│ >44(50) ≥56│ >39(44) ≥50│ >35(40) ≥45│
├────────────┼────────────┼────────────┼────────────┼────────────┼────────────┼────────────┼────────────┼────────────┼────────────┼────────────┤
│ 9 (9000000)│>89(94) ≥100│ >83(89) ≥94│ >78(83) ≥89│ >72(78) ≥83│ >67(72) ≥78│ >61(67) ≥72│ >55(61) ≥67│ >50(56) ≥61│ >44(50) ≥56│ >40(45) ≥50│
├────────────┼────────────┼────────────┼────────────┼────────────┼────────────┼────────────┼────────────┼────────────┼────────────┼────────────┤
│10(10000000)│>90(95) ≥100│ >85(90) ≥95│ >80(85) ≥90│ >75(80) ≥85│ >70(75) ≥80│ >65(70) ≥75│ >60(65) ≥70│ >55(60) ≥65│ >50(55) ≥60│ >45(50) ≥55│
└────────────┴────────────┴────────────┴────────────┴────────────┴────────────┴────────────┴────────────┴────────────┴────────────┴────────────┘

```

If looking at A=2 and B=3 (and 1 million tests):

* rand(2) is bigger than rand(3) in 17 % of the cases
* rand(2000000) is bigger than rand(3000000) in 33 % of the cases (notice scaling ./.. integer rounding)
* rand(2) is bigger than or equal to rand(3) in 50 % of the cases
* (rand(2000000) is also bigger than or equal to rand(3000000) in 50 % of the cases)

Surprises might be that:

* rand(2) \> rand(3) in only 17 % of the cases
* rand(10) \> rand(10) in 45 % of the cases
* rand(6) \> rand(5) every other time

I might in fact solve this Q differently, by simply hand-typing a 10x10 table with nice, desired percentages (maybe one wants irregularity as well?). Then if needed interpolate between two values, to get an exact percentage, say it is of some reason 53. Then it is easy to generate a 53%-probability hit, a 0 or 1, by simply executing a rand(100) and testing if it is smaller or equal to 53 :-).

That is along the line Jack Aidley mentions.
> 1 votes

# Answer
The traditional approach that several answers have implicitly referenced but nobody has actually spelled out is that the task requires a fixed die roll, and add an ability modifier derived from your stats.

For example, if two players follow the procedure:

* Roll a 14 sided die
* Add their modifier to the die roll

and repeat until one side beats the other, then you get numbers in your range: here are the odds of victory with a given numerical advantage to their modifier:

```
0   50%
1   57%
2   64%
3   70%
4   76%
5   81%
6   85%
7   89%
8   92%
9   95%
10  97%

```
> 0 votes

# Answer
The characters do not challenge each other for supremacy. They challenge a requirement. What if both pass the requirement. Who wins? I'm surprised you haven't challenged the logic enough that you've even went to calculation with it.

Either way, here are two things that might do you some good.

**Win chance case with advantage:**

IF pass bar/skill check is a roll of 10. A Rolls 40. B Rolls 42. IF only one has to win. Starting from an equal A 50% Win/ B 50% Win . You can add % to win chance based on amount of advantage. Roll B has (42-40)/40 = 5% advantage in terms of roll. Adding it directly makes B's win chance 55%. Or you can determine a custom win chance per advantage percent. Say for every 100% advantage you add 10% chance to win. So if A Rolls 10 and B rolls 20. Then A wins 40% and B Wins 60% of the cases.

**Fair randomness concept:**

Doing a standard 30% chance to win you may end-up winning 38 checks out of 100.

Some people want an extra step in fairness and make sure that a 30% chance always wins exactly 30 out of 100 encounters and suffice with the randomness of not knowing which encounters in the sequence are a win and which are a loss.

This is particularly useful for well calculated game economies. Because a random stat of 70% chance to win. Say 70% chance for a mob to drop 5 gold. The mobs may end up dropping the gold 81 times out of 100. Which throws off income/expense flows off balance. And depending on how many entities/instances use such rolls inflation and/or shortages are inevitably created. Of course many folks don't even have a rough estimate of full input/expense rundowns of their economy. A lot of people suffice with doing "most" economy points. And leave some generation variables that are not calculated and stack discrepancy overtime even with fair randomness.

Inflation and shortages aren't a problem on their own. You can manage non-fair randomness and even unforeseen variables if your economy is setup to respond adequately to inflation and shortage.

Why bother with this as the **law of large numbers** evens things out in the long run?

Not every environment can retain its design behavior while counting on things to even out later on...
> 0 votes

---
Tags: mathematics, game-design, balance
---


# Question
Title: How to handle RTS Click-And-Move in 3D Space?
How can I handle the click-and-move in a complete 3D space? It is easy to handle on a 2D plane by a simple raycast, but this is not the case in 3D since there is no end-plane for a raycast to get an end-point.

I have two ideas in mind:

1. Do raycast, then allow player to select distance on the ray by another input (mousewhell, for example).
2. Instead of complete 3D, have multiple "layers of height", so player can change the height layer before ordering the move.

What are your thoughts?

# Answer
> 4 votes
Breaking movement in two steps is an outdated approach.

**Mouse movement for the horizontal plane. Mouse wheel for vertical plane.**

Homeworld did a fine job, but mouse wheels weren't so widely deployed yet so they didn't go with that.

You can still have modifier keys to switch mouse movement between the modes but moving the mouse and scrolling can be done simultaneously thus is the most efficient method for the hardware. In homeworld you set the planes in sequence one after the other which slows you down. Not to mention you are only slowed down in moving to empty space. Moving to object automated the trajectory.

**The other ways to do it simultaneously are two hands on the keyboard or twin stick controls.**

If your fluidity of movement depends on speed, doing and extra step can kill your flow. Homeworld fits its system because it doesn't matter if you waste an extra second or two in issuing your move order, and you can be sure they factored that consideration when they built the pacing.

P.S. Zooming placement:

If zooming isn't a central mechanic and you don't need to keep it as robust as possible it can be offloaded.

Handle zooming the same way the original "Black and White" game did. Zoom by mouse movement + Mouse button hold (where the button is just the function modifier between map move and map zoom). The gametesters I've used all agree it "feels" to be the best zoom. I would recommend holding both mouse 1 and mouse 2 while for the zoom mode (exactly as B&W did) - but technically one of them would suffice if you don't have a conflict.

I've often recommended to people to install the game to try it. Add the keyboard usability and its the most useful and comfortable mechanic to date I've seen for large map navigation.

Now, this of course is not common default and you have to damn well make sure it is explained to your users at least a few times. But once people get it they are very comfortable with it. Besides you are teaching folks navigation in 3d. You are bound to venture out of the 2d controls comfort zone any way.

If your mouse is too overloaded with controls you can always use a modifier keyboard key or middle mouse button. Optimal configuration would really depend on your game flow.

# Answer
> 11 votes
Break movement into two steps

1. Select a position on a 2D X/Z plane located at the entity's current Y position.
2. Set the offset (up or down) from that plane.

This is similar to how Homeworld, one of the first 3D space RTS games handled movement. Works really well.

Breaking movement into two steps provides the most control, simply because the mouse is a 2D input device. It can only provide a position on one plane at a time. The same could be achieved by binding two keys on the keyboard to be the up/down in the Y axis.

Alternatively, you could use the right mouse button to toggle the mode. For example, left click starts the move command and moves the target on the X/Z plane, holding the right mouse button switches to altering the Y axis position.

# Answer
> 2 votes
Do what EVE online does: Don't allow click-and-move! Note

What they do is that they create objects in space, and allow you to right-click on them (raycast or what-not), and select one of different options:

* Go to object (with different speeds)
* Rotate about object (at different radii)

This allows you to only move to relevant places.

---

Note *(They might have changed that lately, though. Haven't played for a while.)*

---
Tags: game-design, unity, raycasting, rts
---


# Question
Title: What do you call the camera movement type in starcraft?
Yeah, that's it, I cannot figure it out for the life of me.

What I'm curious about can be seen in this YouTube video (at 3:58).

# Answer
StarCraft uses a top-down camera.

Generally camera types are named based on their projection method and constraints they place on viewing the world. A top-down camera is generally called such because it always sits above the action, looking down.

The way you interact with the camera's constraints is usually less of a factor in what we call them.

StarCraft's technique of moving the camera when you get close to the screen edges is called... "moving the camera when you get close to the screen edges," or some variation on that. It does not have a standard, de-facto or otherwise, name.
> 1 votes

---
Tags: camera, terminology
---


# Question
Title: What should developers do when they receive conflicting feedback about their game?
I've been working my first mobile game (I have done a lot of web and PC games before).

I wanted the idea to be simple but fun. The thing is, I received feedback from friends and family and I have heard a lot of contradictory opinions about my game. Some would say that the game is addictive, challenging and fun, while other didn't see it as a fun game and said it was boring or not really good enough.

Now that I have these two opposite opinions I don't know if my game is good or not.

What opinion should I listen to, and how am I supposed to know if the game is fun or not when people's opinions are mixed?

# Answer
This is something you simply must get used to when you create any creative work.

Not everyone will like your work. Not everyone *must* like your work. There are plenty of world-renowned artists who receive plenty of negative feedback and are still widely successful. It doesn't matter, because that negative feedback comes from people their work isn't made for.

When you receive negative feedback, first consider if it is even relevant:

* Is the feedback relevant to *your target demographic*? For example "There is not enough sex and blood in your game" is not relevant feedback when your target demographic is 8-12 year old children.
* Is the feedback relevant to *your vision of the game*? For example, when you want to create a very dark and depressing game, then "It's not colorful and cheerful enough" is not relevant feedback.

(although such irrelevant feedback might give you a hint that maybe your presentation gave the player a different expectation than you intended)

Still, negative feedback can be a great source to improve your work. Do not dismiss feedback as irrelevant too early just to protect your feelings. It is often worth looking at *why* the player feels that the game is lacking in certain regards.

* **"it was boring"**: Why did the player feel the game was boring?
    + Was there something in particular about the game they didn't like?
    + Were they over- or underchallenged?
    + Did the game not have enough depth? Or was the game's depth not presented to them in an accessible manner (bad tutorial, bad complexity progression, bad ui)?
    + Did they feel the game forced them to do something they didn't like?
    + Did they miss some incentive or motivation to keep them engaged?
* **"not really good enough"** What wasn't good enough about the game?
    + The graphics?
    + The aesthetics? (yes, that's a difference).
    + The sound design?
    + The presentation?
    + The controls?
    + The gameplay?
    + The pacing?
    + The amount of content?

When the test player can't or won't answer any of these questions, then their feedback is not useful because you can't derive any directions from them regarding what you need to work on.

By the way: Asking friends and family about your game might be convenient, but might not always get you honest feedback, because people you know might not want to hurt your feelings by giving you negative feedback. While positive feedback is always encouraging, it's the negative feedback which is most helpful to you as a game designer (if it is relevant).
> 60 votes

# Answer
Remember the Edsel - giving people what they think they want is not necessarily going to make a good product.

This is why I feel it's important that you, personally, have a real passion for whatever it is you are doing. That way you are qualified to be the ultimate authority in what the right direction is and sorting out varying criticism will not be much of a burden.

So if you are a big fan of RPGs from the 80s and 90s and get lots of comments that people think the game is too hard, you are probably on the right track for making a great homage to the era.

If you simply look at things as a demographics game then you will get Hollywood-style pandering, least common denominator mixed up nonsense that doesn't really appeal to anyone in particular.

So the key here is to have a strong vision and stay true to it...and of course to have a market for this in the first place. You have to be careful if your vision is very outside the usual and make sure that a market actually exists.

For example Julian Gallop was the original maker of XCom, and he made a followup game in a similar vein. But instead of the simple turn-based system that people enjoyed he came up with a very complex phase based system that never really caught on with the fans of his old work.

If you have a vision there is a basic market for, and you stick with it AND you have the ability to bring it to market then you will succeed, feedback or no feedback. If you don't then your project has failed before it's even begun.
> 3 votes

# Answer
Farmville became one of the most successful games besides people writing articles about it how it is boring, rather than fun. If a game is polarizing the audience, that counts in it's favor.

If some people find a game addicting then work on making the game even better for them. Of course you have to make sure that those friends are giving you honest opinion and don't simply say your game is fun because that's what you want to hear.

If you try to get your games liked by everyone, it's likely that nobody will get passionate about it.
> 1 votes

# Answer
All the previous answers here have been great! But I want to add one thing: What's the demographic of the people who like/dislike your game? This is another thing you'll have to find out when you create and design software and video-games.

You may want to ask yourself some questions. Here are a few examples:

* Are the people that liked your game younger or older?
* Are the people that liked your game into casual or challenging "hardcore" gameplay?
* Do the people that liked your game enjoy playing video-games in general or do they not play video games often?

You can then decide if you want to make the game more accessible to people who don't fit within the answers to these questions; people who don't fit within the current "demographic." Or, if you are happy, then you may decide to focus on these people to make sure that they have the best possible experience. That's not to say that you can't focus on making the game more accessible too, but it *will* be more difficult the satisfy the needs of **everybody**.

An example of a game that focuses on it's core audience would be "Dwarf Fortress." It's difficult for beginners to pick-up but, as far as I can tell from feedback, they seem to \*really\* enjoy it.

An example of a game that focuses on accessibility would be something like "Minecraft." It's on every platform imaginable, it's moddable and there is a wide audience but it never becomes 'difficult' without user mods or tweaks.

Now, there are games that are easy to pick up and difficult to master but you'll find that most of these games are online-based and the multiplayer is a core mechanic, like *Dota* or *Counter Strike*. The other players make the game challenging but these games have ranking systems so new players aren't mixed with people who have *"played every game in the series for 700+ hours and know the in-game maps better than the plans for their home."*

Here's a couple excellent videos on the subject. You should check out the *Extra Credits* YouTube channel as they have **loads** of videos based entirely on video-game design.

Have fun making games! (And remember, when it stops becoming fun/rewarding, you're doing something wrong. If you are stuck on a coding problem or a more fundamental-philosophical problem like this one, then feel free to ask the community!)
> 1 votes

# Answer
**The feedback management handbook (composed by input from several people in the office):**

> Feedback is not to be ignored and not to be entirely listened to.
>
> Water is one of the most important substances on this planet. Half of you is water. You can die of thirst. Yet you can drown. Consuming enough will kill you - it is toxic, regardless of how low.
>
> Feedback management is about everyone's feelings but yours.
>
> People are not all articulate. You don't know what they mean - ASK for specs.
>
> Negative or positive feedback can both vary in terms of usefulness. Asking people for relevance is half the job. "Your game is great" is equally useful to "Your game sucks" in terms of what to expand on.
>
> Most of us fail on feelings. Once you manage your feelings and start looking for value, the only thing you have to do is allign feedback with your goal. This means that if a homicidal maniac comes and rudely tells you 2+3 is 5 and your own calculation was wrong - you take that correction and you move on. Anything else you can derrive from such a case is toxic and serves no other purpose than to upset you. Whether your player was polite or nasty is a waste of your time. If you can't handle people's words in text format on the internet don't even start doing this - we have content management positions for people of not so flexible mental fortitude.
>
> Even so folks that hate you are on average more honest about things than people who like you. They don't have to refine what they say based on common courtesy - they can just spit it all out in raw form at your face.
>
> Conflicted feedback is either produced by design flaw. Setting people to expect something other than what they will get (including allowing people to think they have no idea what to expect, which sets you up at even lower rates of fullfilling their expectations). Or is irrelevant to your goal - people expecting things that were never the goal, were never even hinted at. Unless you decide to change your goal, such feedback has to be declined. If they took the time to give it to you, at least you can say, "Yes I see, its not something we are going to do"
>
> Overall: Your customer will rarely if ever see the process from your side of things.
>
> Your job is to grab a pile of dirt and sort out the gold bits and gemstones in it. The essence of this job is deriving technicality out of sensation. Yes it would have been easier if you just scooped it and used it as is - but alas it isn't.
>
> This isn't the firm grooming you to be rough and tough. If getting your hands dirty upsets you - it mostly affects you. The longer it affects you the more it leaks into your job satisfaction, the more it leaks into your job performance and like it or not - its a free market, we can't keep you when folks around you constantly outperform you because they can handle their feeling within the occassionally hostile world. If capitalism has proven anything is that you don't have to like people to do meaningfull transactions with them. Of course we are all human here, so you have discretion to dispense with the most awful of individuals you come across. Just make sure that doesn't happen to be everyone who disagrees with you.
>
> This politics has has allowed us to grow our company by 30+% from a single forum post starting with "You idiots.... cursing ... and more cursing ... **very valuable feedback** and again plenty of cursing..." It is why the post is in a picture frame above Jake's desk. While the bitterness might have irritated him at the time, he and others sure are enjoying the pay raise to this very day. This wouldn't have been possible if the moderator lost his cool and didn't even bother to finish reading the post. Trust me when i say that I would mandate ignoring every polite customer from the feedback systems if every obnoxious one helped us grow our revenue by 1%.
>
> (You might have noticed the less than good use of language and spelling, it is allowed to remain as a symbol of the purpose of this document)

You will also notice the lack of specifics elements such as in the main answer. The document accepts that if you were hired, you know the "pillars of gaming" so to speak. So you don't have to be told what the variety of main components in games are.

A lot of great value we have found is not from the users themselves but by merely communicating with them requiring us to set ourselves to think in directions we haven't so far. Considering the handbook you can guess that some of those communications were distant from "civil" discourse by a long stretch.
> 1 votes

# Answer
Design your game in what is important to the direction of the vision of it, understand that sometimes people not liking an element of your game may actually confirm that you are going in the direction you seek for your game.

You have to understand that people may dislike it because of their own personal biases or what image of it they have built up in their own head. Sometimes people will dislike elements of your game because it doesn't suit their tastes or sometimes it suits their tastes and is executed poorly. It is your job as a designer to decide what the direction of the game will be, what will it feel like to play, what emotional response do you want from your players? What do you want them to walk away thinking about your game?

Players who are hardcore Counter Strike: GO players may not be so interested in a title like Firewatch or The Witness, that said, you could also be wrong about that assumption and they might personally enjoy the difference in style despite the evidence of what sells and their previous behavior.

Your audiences will be varied, and age and sex are not nearly as telling indicators of audiences as you'd think they would be, don't work on faulty assumptions of your audience, try to test your game with as many different people as possible and be weary of poor criticism.

**Good criticism will tell you in detail what they felt while playing your game and why they didn't like it or why they felt it was out of place or ripped them out of the overall world of the game.**

**Bad criticism will blame your game for not being Halo or not having the production quality of a AAA title (that said, if you are in a AAA studio, this is a valid criticism). Bad criticism will compare your game to something that it was never intended to be and pretend that it's falling short of some valid criterion. It doesn't make sense to complain that a horror game made someone feel hopeless and scared and judging the game bad because the player felt negative emotions. It doesn't make sense to judge The Witness because you can't carry a Colt 1911 while solving puzzles in a bright beautiful landscape.**
> 0 votes

---
Tags: game-design, user-experience
---


# Question
Title: Replace PolygonCollider2D with MeshCollider at runtime
I am using a PolygonCollider2D to load in points for a MeshCollider at runtime, but am having issues switching between the two at runtime using good coding practices.

This is a simplified version of the current code:

```
Awake(){
    PolygonCollider2D polyCollider = this.gameObject.GetComponent<PolygonCollider2D>();
    //save vectors
    Vector3[] v3 = new Vector3[polyCollider.points.Length];
    for (int i = 0; i < polyCollider.points.Length; i++)
    {
        v3[i] = new Vector3(polyCollider .points[i].x, polyCollider .points[i].y, 0);
    }
    //destroy collider
    DestroyImmediate(collider);
    meshCollider = this.gameObject.AddComponent<MeshCollider>();
    meshCollider.sharedMesh.vertices = v3;
}

```

Other than the bad naming, how can I substitute DestroyImmediate(collider) with Destory(collider) while still having it behave correctly. I would be willing to move the mesh collider declaration to a different function to delay its assignment.

# Answer
> 1 votes
I'm not sure filling `sharedMesh.vertices` will be enough to convert your `PolygonCollider2D` into a `MeshCollider`.

From my (not long enough and too basic) tests, when you try to create a `MeshCollider` and only give it vertices it doesn't work. Your `MeshCollider` will need vertices but also **triangles**.

After getting the polygon points you might have to compute all the triangles to recompose the shape.

# Answer
> 1 votes
The solution to this is to use a Coroutine that waits for the variable to be destroyed. This guarantees that it will be able to make the MeshCollider. Here is a piece of sample code that could be used to implement a similar solution.

```
Vector3[] v3
IEnumerator Start(){
    PolygonCollider2D polyCollider = this.gameObject.GetComponent<PolygonCollider2D>();
    //save vectors
    v3 = new Vector3[polyCollider.points.Length];
    for (int i = 0; i < polyCollider.points.Length; i++)
    {
        v3[i] = new Vector3(polyCollider .points[i].x, polyCollider .points[i].y, 0);
    }
    //destroy collider
    DestroyImmediate(collider);

    yield return StartCoroutine(genearteMeshCollider());
}

IEnumerator genearteMeshCollider()
{
    yield return new WaitUntil(() => this.polygonCollider == null);
    meshCollider = this.gameObject.AddComponent<MeshCollider>();
    meshCollider.sharedMesh.vertices = v3;
    setIndecies(meshCollider.sharedMesh.vertices);
}

```

This code needed to be moved to Start because IEnmerators cannot be on the Awake function.

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


# Question
Title: How move sprite in Java 2d (swing) with keyboard?
I'm practicing some simple techniques with Java swing games, to learn the basics. Right now I'm practicing how to move a sprite... but it's not working! whhyyyy

Here is what I've come up with so far (**Main class**):

```
public class GraphicsPracticeDrawing extends JPanel implements Runnable{

private CoinSprite coin2;
private Thread animate;

private final int DELAY = 25;

public GraphicsPracticeDrawing(){
    setBackground(Color.BLACK);
    this.addKeyListener(new InputHandler());

    Initialize();
    animate = new Thread(this);
    animate.start();
}

public void Initialize(){
    coin2 = new CoinSprite("images/coin.gif", 25, 25);
}

public void paintComponent(Graphics g){
    super.paintComponent(g);

    Graphics2D g2d = (Graphics2D)g;
    g2d.drawImage(coin2.getImage(), coin2.getX(), coin2.getY(), null);
}

@Override
public void run() {
    long beforeTime, timeDiff, sleep;

    beforeTime = System.currentTimeMillis();

    while(true){
        coin2.move2(); //move the 2nd coin based on the inputHandler
        repaint();

        timeDiff = System.currentTimeMillis() - beforeTime;
        sleep = DELAY - timeDiff;

        if(sleep < 0)
            sleep = 2;

        try{
            Thread.sleep(sleep);
        } catch(InterruptedException e){
            System.out.println("Animation interrupted!");
        }

        beforeTime = System.currentTimeMillis();
    }
}

/*
 * create a inner class to handle key inputs via the CoinSprite class
 */
private class InputHandler extends KeyAdapter{
    public void keyPressed(KeyEvent e) {
        coin2.keyPressed(e);
    }
    public void keyReleased(KeyEvent e) {
        coin2.keyReleased(e);
    }
}

```

}

and for my **CoinSprite class**:

```
public class CoinSprite {

private BufferedImage img;
private int speedKeyX, speedKeyY;

public CoinSprite(){ }

public CoinSprite(String fileLoc, int x, int y){
    try{
        this.img = ImageIO.read(new File(fileLoc));
    } catch (IOException e){
        System.out.println("Can't load file!");
    }

    this.x = x;
    this.y = y;
}

/*
 * move the sprite based on key inputs
 */
public void move2() {
    this.x += this.speedKeyX;
    this.y += this.speedKeyY;
}

public void keyPressed(KeyEvent e) {
    if(e.getKeyCode() == KeyEvent.VK_LEFT) {
        speedKeyX = -1; //when move is, called change the speed
    }
    if(e.getKeyCode() == KeyEvent.VK_RIGHT) {
        speedKeyX = 1;
    }
}

public void keyReleased(KeyEvent e) {
    if(e.getKeyCode() == KeyEvent.VK_LEFT){
        speedKeyX = 0;
    }
    if(e.getKeyCode() == KeyEvent.VK_RIGHT){
        speedKeyX = 0;
    }
}

//GETTERS
public BufferedImage getImage(){ return this.img; }
public int getX(){ return this.x; }
public int getY(){ return this.y; }

//SETTERS
public void setX(int x){ this.x = x; }
public void setY(int y){ this.y = y; }

```

}

When I run the game and press left and right the sprite wont move! I don't know why...

# Answer
I found the issue, I needed to set my JPanel to focusable() in order to handle input.

In my constructor I added:

```
this.setFocusable(true);

```

and everything works fine.
> 2 votes

# Answer
```
public void run() {
    long beforeTime, timeDiff, sleep;

    beforeTime = System.currentTimeMillis();

    while(true){
        coin2.move2(); //move the 2nd coin based on the inputHandler
        repaint();

        timeDiff = System.currentTimeMillis() - beforeTime;
        sleep = DELAY - timeDiff;

        if(sleep < 0)
            sleep = 2;

        try{
            Thread.sleep(sleep);
        } catch(InterruptedException e){
            System.out.println("Animation interrupted!");
        }

        beforeTime = System.currentTimeMillis();
    }
}

/*
 * create a inner class to handle key inputs via the CoinSprite class
 */
private class InputHandler extends KeyAdapter{
    public void keyPressed(KeyEvent e) {
        coin2.keyPressed(e);
    }
    public void keyReleased(KeyEvent e) {
        coin2.keyReleased(e);
    }
}

public class CoinSprite {

private BufferedImage img;
private int speedKeyX, speedKeyY;

public CoinSprite(){ }

public CoinSprite(String fileLoc, int x, int y){
    try{
        this.img = ImageIO.read(new File(fileLoc));
    } catch (IOException e){
        System.out.println("Can't load file!");
    }

    this.x = x;
    this.y = y;
}

/*
 * move the sprite based on key inputs
 */
public void move2() {
    this.x += this.speedKeyX;
    this.y += this.speedKeyY;
}

public void keyPressed(KeyEvent e) {
    if(e.getKeyCode() == KeyEvent.VK_LEFT) {
        speedKeyX = -1; //when move is, called change the speed
    }
    if(e.getKeyCode() == KeyEvent.VK_RIGHT) {
        speedKeyX = 1;
    }
}

public void keyReleased(KeyEvent e) {
    if(e.getKeyCode() == KeyEvent.VK_LEFT){
        speedKeyX = 0;
    }
    if(e.getKeyCode() == KeyEvent.VK_RIGHT){
        speedKeyX = 0;
    }
}

//GETTERS
public BufferedImage getImage(){ return this.img; }
public int getX(){ return this.x; }
public int getY(){ return this.y; }

//SETTERS
public void setX(int x){ this.x = x; }
public void setY(int y){ this.y = y; }

this.setFocusable(true);

```
> 0 votes

---
Tags: 2d, java, input
---


# Question
Title: What keys should I use for a four-player game with one keyboard?
I'm planning on making a multiplayer game for up to four people on a single machine. We want to have all input coming from players using the same keyboard (or multiple keyboards connected to the same computer). What keys should I use for each player?

Each player will be able to move around at a minimum, which will require four directional keys. They might potentially have one extra action they can take, which would require a fifth key.

WASD and the Arrow Keys are somewhat obvious options for a single player game, but what other sets of keys should I use?

I'm mainly interested in what positions of keys to use, rather than the letters, so just answer using the QWERTY keyboard layout. Potentially we can let people map this to their own preference for the other keyboard users.

I'm aware that many keyboards limit the number of keys that can be pressed simultaneously, however for this particular game we will be controlling the hardware and using multiple keyboards. It would be nice to have a set of keys that would work on a single keyboard if that keyboard didn't have that input limit (although it might be difficult fitting everyone's hand)

# Answer
> 5 votes
Just as a heads up, most keyboards have a finite limit of keys that can be pressed. For example, I have an *Asus Transformer Book* and you can only press around ~5 keys at a time. Some keyboards also won't allow more than a few keys pressed if shift or control is being pressed. (Like my *Transformer Book*...) And yes, most of the time, this is hardware limited, so you wouldn't be able to interface with any drivers in order to remove the limit. The limit is usually unintentional or is there to drive costs down on budget keyboards. It may not be possible to have a high number of keys pressed simultaneously with certain designs/layouts.

Hardware limitations aside, I'm not so sure that having four hands on the same keyboard at the same time is very... ergonomic. Not only would it be cramped, selecting the correct keys to use would be a nightmare, and I suppose that is why you asked the question.

If you're looking for multiplayer support, why don't you do something with Xbox controllers? A-lot of successful desktop games support multiplayer XInput without extensive Keyboard/Mouse support, but that's drifting away from your original question.

You would need 16 available keys in order to have 4 people playing the same game locally.

What about `WASD` `TFGH` `IJKL` `↑ ↓ ← →`?

You could use *Home, Delete, End and Start* or the numpad instead of arrow keys and you should refrain from using punctuation, syntax or symbols as they are differ by region, not by layout. (i.e. US QWERTY and UK QWERTY)

**Edit:** With most laptop keyboards, using *Home, Delete, End and Start* or using the numpad is not a feasible option. Compact keyboards tend to "squish" these keys on the edge of the board or at the top beside the function keys. Some keyboard manufacturers even decide to omit these features completely, so I wouldn't recommend adding those keys as the defaults.

Another note; Make sure that you allow the user to change the keys for themselves as they would be able to decide on their situation and their needs and, chances are that they wouldn't be happy with the default settings or their keyboard wouldn't be compatible for four players anyway.

Anyway, what ever you decide to choose, all the best with your project! ^\_^

# Answer
> 2 votes
As others have pointed out, you can't be sure the player has a keyboard with anti-ghosting so this simply wont be possible on most non-gaming keyboards.

Regardless, I think the best solution would be to let the players decide when the game starts. Everyone positions their hands where they're comfortable then each player is prompted, one by one, to press their up, down, left, and then right keys. It's an extra step in the game flow but avoids plenty of confusion and I'm sure after doing it once or twice, people would be able to do it very quickly (and there's always the option of saving their choices).

# Answer
> 1 votes
Depends on the player's keyboard hardware. You cannot make a set that will work for sure on everyone's computer.

Make sure your game design does not encourage the players to hold more than one key, as you'll run into the limit on the number of keys that can be reported at a time.

# Answer
> 1 votes
Have you considered supporting gamepad controllers? For inspiration the game Duel (https://github.com/odanek/duel6r) supports 4 positions on keyboard + others on gamepads.

And for completeness - numpad keys can be used too to give you more room around the keyboard.

# Answer
> -1 votes
WASD and Arrow Keys are good options for two players. According to Wikipedia, IJKL is a common option, so that could be used for the third player.

If the keyboard has a number pad, you can use that for the fourth player. Otherwise, GVBM is the most spaced set of letters in the WASD shape.

For the fifth key for each player, you could potentially use a letter next to each of the players, such as X for with WASD, Ctrl with the Arrow Keys, M with IJKL, and Space for GVBM.

---
Tags: multiplayer, input, keyboard
---


title: Add UVs back into a model

text:
# Question
Title: Add UVs back into a model
I built a 3D model in Autodesk 123d design, then exported it as an stl. When I convert it into an obj, however, there were no UVs in it.

Is there a way I can add the UVs back into the model using a program like blender?

**Cheers!**

# Answer
> 1 votes
STL doesn't export coords so there isn't a work around. Unless the program exports directly to obj (I'm guessing it doesn't hence the workaround) or you can export the coords in another format, you're stuck having to redo the unwrap yourself.

https://en.wikipedia.org/wiki/STL\_(file\_format)

*"STL files describe only the surface geometry of a three-dimensional object without any representation of color, texture or other common CAD model attributes"*

---
Tags: 3d, models, blender, uv-mapping
---


# Question
Title: Texture mapping artifacts on certain surfaces
I am currently working on a 3d game engine, but am complete stumped on a problem involving texture rendering. Here is the rundown.

My game engine renders meshes of the OBJ wavefront type. I have created a OBJ mesh parser that simply looks through all the vertice/normal/texture indexes(Line by Line) and loads the corresponding data into the right places without altering it.

Mesh Parser Code: (NOTE pseudo codeish)

MY VERTEX STRUCTURE: struct VERTEX { D3DXVECTOR3 Pos; D3DXVECTOR3 Normal; D3DXVECTOR2 TexCoords; };

```
    if (line[i]->c_str()[0] == 'v' && line[i]->c_str()[1] == ' ') {

        float tmpx = 0;
        float tmpy = 0;
        float tmpz = 0;

        sscanf(line[i]->c_str(), "v %f %f %f", &tmpx, &tmpy, &tmpz);

        D3DXVECTOR3 myVec = {tmpx, tmpy, tmpz };

        vertices.push_back(myVec);

    }
    else if (line[i]->c_str()[0] == 'v' && line[i]->c_str()[1] == 't') {

        float tmpx = 0;
        float tmpy = 0;

        sscanf(line[i]->c_str(), "vt %f %f", &tmpx, &tmpy);

        D3DXVECTOR2 myTexCoords = { tmpx, tmpy };

        texCoords.push_back(myTexCoords);
    }
    else if (line[i]->c_str()[0] == 'v' && line[i]->c_str()[1] == 'n') {

        float tmpx = 0;
        float tmpy = 0;
        float tmpz = 0;

        sscanf(line[i]->c_str(), "vn %f %f %f", &tmpx, &tmpy, &tmpz);

        D3DXVECTOR3 myNorm = { tmpx, tmpy, tmpz };

        normals.push_back(myNorm);

    }

            sscanf(line[i]->c_str(), "f %d/%d/%d %d/%d/%d %d/%d/%d %d/%d/%d",
            &tmpindices1, &tmpTexCoordsIndex1, &tmpNormalsIndex1,
            &tmpindices2, &tmpTexCoordsIndex2, &tmpNormalsIndex2,
            &tmpindices3, &tmpTexCoordsIndex3, &tmpNormalsIndex3,
            &tmpindices4, &tmpTexCoordsIndex4, &tmpNormalsIndex4);

            verticeIndex.push_back(tmpindices1 - 1);
            verticeIndex.push_back(tmpindices2 - 1);
            verticeIndex.push_back(tmpindices3 - 1);
            verticeIndex.push_back(tmpindices4 - 1);

            texCoordsIndex.push_back(tmpTexCoordsIndex1 - 1);
            texCoordsIndex.push_back(tmpTexCoordsIndex2 - 1);
            texCoordsIndex.push_back(tmpTexCoordsIndex3 - 1);
            texCoordsIndex.push_back(tmpTexCoordsIndex4 - 1);

            normalsIndex.push_back(tmpNormalsIndex1 - 1);
            normalsIndex.push_back(tmpNormalsIndex2 - 1);
            normalsIndex.push_back(tmpNormalsIndex3 - 1);
            normalsIndex.push_back(tmpNormalsIndex4 - 1);

for (int i = 0; i < texCoordsIndex.size(); i++) {
    ModelToFill.Vertices[i].TexCoords = texCoords.at(texCoordsIndex.at(i));
}

for (int i = 0; i < normalsIndex.size(); i++) {
    ModelToFill.Vertices[i].Normal = normals.at(normalsIndex.at(i));
}

for (int i = 0; i < vertices.size(); i++) {
    ModelToFill.Vertices[i].Pos = vertices.at(i);
}

for (int i = 0; i < verticeIndex.size(); i++) {
    ModelToFill.Indices[i] = verticeIndex.at(i);
}

```

But now when my renderer renders the mesh it looks like this:

As You can see the texture coordinates are all messed up, (for some surfaces). The Bottom, Leftmost and back are messed up but the front and top are fine.

Now I should mention that my mesh is exported from blender with materials, and the mesh is also triangulated. Before importing I also performed the smart UV unwrap.

Finally, I should mention that the parts of the mesh which are not texture mapped correctly vary depending on the mesh.

MY QUESTION though quite general: What is the most probable cause of this issue, the mesh parser, form of blender mesh exporting, or renderer.

# Answer
You need to be careful, wavefront files and gpu does not works the same, in the file, you can have a missmatch of indices between position, texcoord and normal because they can be reuse differently. Extreme example, a cube with a texture per face only need 8 point values, 4 texcoord values and 6 normal values.

Now, on the GPU, a vertex need to be a full tuple, it means for our cube, that you need to split points for divergent texcoord and normal, and you ends with 24 vertex.

EDIT: tips for building a proper vertex buffer and index buffer from a wavefront file

use `std::map<std::tuple<int,int,int>,int> remap;`, the key is the triplet position/uv/normal, the value is an increasing counter, starting at 0, and that you increment every time you that a new triplet.

Once you insert every triplet, counter is your number of unique vertex. you can now create a vertex buffer of that many values, and fill it by reversing the `std::map`, the value become the vertex offset, the key is the vertex attribut indices.

You do the same for the index buffer, you use the triplet as a key to retrieve the final vertex index.
> 0 votes

---
Tags: 3d, textures, directx, directx11
---


title: Combining skydome and fog

text:
# Question
Title: Combining skydome and fog
I am developing a 3D game in DarkBASIC Professional, and I have a theoretical problem with the combination of skydomes and fog in general. My question is not specific to a programming language, so I am not refering to code.

**What I want to achive**

1. The player can see a night sky with stars
2. The sky should rotate slowly
3. Trees will block the light of the stars
4. Trees will be dark when far away and colorful when player is near (normal shader work).
5. A tree at the horizont should not "pop up" randomly when it enters the skydome. It should slowly fade, as the player comes near.

---

**Techniques I use**

1. Instead of a skybox, I have choosen a skydome with a night-sky-texture. This texture scrolls.
2. DarkBASIC has a "fog" feature. If enabled, I can choose a fog color and a fog distance. Things like trees will slowly fade and vanish into this fog color and will be completely faded when they reach the fog distance. I am using black colored "fog" for the night scene, so that the trees far away will vanish in the dark night.
3. DarkBASIC's "fog" and "ambient light" features automatically shade the trees, so that far away trees are dark, and trees close to the camera, colorful.
4. The skydome will always enclosure the camera. It will automatically move when the camera moves. (Note: Since the landscape is very big, I couldn't choose a giant skydome that covers the whole level, because the rendering of the texture on a giant skydome requires too much rendering time (at least for DarkBASIC's engine).)

---

I have tried several things now, and I am don't know what to do to fulfill all requirements.

**Version 1**

What I did:

* I am using black fog with a fog distance of 1000.

Pro:

* Trees are perfectly faded horizontally and vertically and no tree "pops up" at the horizont

Contra:

* There is no skydome, so the sky is just 100% black, without any stars.

---

**Version 2**

What I did:

* I am using a sky sphere with diameter 300
* I am using black fog with fog distance 1000

Pro:

* Since I am using the fog feature, trees will slowly fade to black when the camera diverges from them.
* The sky can be seen completely (also at the horizont) because the sky sphere is smaller than the fog distance

Contra:

* The trees are taller than 300, and therefore poke through the skydome! So I only see half trees... (Note: I cannot increase the value "300", because otherwise the skydome will be shaded too much by the fog, which would result in a extremely low star light.)
* Since the skydome is smaller than the fog distance, trees will "pop up" at the sky, once they come close (and pass the skydome)

---

**Version 3**

What I did:

* I set black fog with a distance of 1000
* The skydome is an ellipsis with height 300 and width 1200.

Pro:

* The sky can be seen when the camera looks up (because the skydome does not exceed the fog distance)
* Trees at the horizont are faded and do not "pop up"

Contra:

* The trees are taller than 300, and therefore poke through the skydome! So I only see half trees... (Note: I cannot increase the value "300", because otherwise the skydome will be shaded too much by the fog, which would result in a extremely low star light.)
* The sky at the horizont is black and no stars can be seen. (But this is not a big deal in my opinion, since there will be always things at the horizont which block star light)

---

**What I actually need**

I think I need something like an "elliptic fog". A fog that will shade objects at the horizont stronger than objects above the player (sky). But such a thing does not exist in DarkBASIC.

So I am trying to find out a good solution using the standard techniques fog, ambient light and skydomes to achive my goal. Do you have a solution for me?

# Answer
> -1 votes
You're stuck in a bit of a predicament using an older engine like DarkBasic. The problem as you've already described yourself, is that you can't afford to make the skydome bigger. The reason the trees are popping, you already know, is that they are clipping through the geometry of the skydome. If you cannot make the skydome bigger, there's not much you can do to get rid of the problem. I'm not a programmer so I'm not sure what the limitations are with the engine, but one approach might be to create a pixel depth fade on the skydome material. This is a technique that's used by modern game engines (unreal 4) to give a faded edge around meshes that protrude through the mesh they are intersecting with. They use it most commonly on water meshes where you have rocks jutting out of the water and they don't want the intersection to look sharp. This won't eliminate the problem because the trees will still be intersecting with the skydome, but it will fade the point of intersection around the trees so it might look less terrible.

Another alternative would be to make the stars using a different method. You could try using a particle system (not likely in DarkBasic) or you could make a custom star mesh for the stars that's not a sphere.

The other more obvious alternative now that I think of it is to change the shape of your skydome to be elliptical instead of trying to create elliptical fog.

---
Tags: 3d, shaders, skybox, sky, fog
---


# Question
Title: How can I fix the face/normal direction of my 3d mesh in blender/UE4?
So I am playing around with UE4 to make some concept art for a game. I extracted the model I wanted to use from the game's files and imported it into blender. It's a tank with 4 parts: the hull, the suspension, the turret, and the cannon. The suspension and cannon work as intended, but there is something wrong with the way the hull and turret are rendered. Here I have linked 3 photos of what is happening: https://i.stack.imgur.com/OJ6pQ.jpg

The first screenshot is what the model looks like when rendered in blender (internal and cycles both look like this).

The second screenshot is the model in blender's 3d preview. Looks completely normal.

The third screenshot is what the model looks like in UE4 with textures and normals applied. The outside of the hull and turret meshes are see-through, so only the inside faces on the backside of the mesh are visible.

I have already looked through google and can't find anything to help me. By default the normal direction for the faces (not the vertices) are flipped inside out. Also if I tick "backface culling" blender removes the front faces of the mesh instead of the back faces (should be the other way around). Which means somehow the faces of the 3d mesh are flipped inside out and I need help getting them the way they should be. I have already tried flipping as well as re-calculating the normals (with the "make normals consistent" box ticked) and neither fix the problem. Would really appreciate some help with this. Will upload the model if I have to, but it's not mine so it might be considered copyright infringement.

EDIT: I'm not sure if this matters, but the hull and turret need to be mirrored in blender to match up with the orientation of the cannon/suspension. By defualt they're flipped in the wrong direction. This doesn't seem like a coincidence.

# Answer
> 1 votes
Double click on the Normal texture inside UE4 and expand the Texture rollout. Below the X-axis and Y-axis Tilting Method drop downs you'll see a check box for "Flip Green Channel". Tick this off and hit save. If this Doesn't fix the problem for you, then the issue isn't with your normal map but with the mesh normals. If this is the case then inside Blender you need to select the normals in question and use the Flip Direction button within the Shading rollout under the heading Normals.

https://blender.stackexchange.com/questions/29132/how-do-i-flip-normals-on-this-model

---
Tags: 3d, blender, unreal-4, normals
---


# Question
Title: How do I draw a name above monsters head?
My player HUD works perfect, but when I move, the monster name moves with me instead of getting attached to the monster.

Player has a HUD and I'm using `Scene2D.ui` to pull it off and works great.

I use unit scale, that's why I got 2 camera. One for UI stuff and other for game.

```
 public void update(float deltaTime) {
    // update creatures
    world.getPlayer().onThink(deltaTime);
    for (Monster monster : world.getMonsters()) {
        monster.onThink(deltaTime);
    }

    // update camera to the player
    camera.position.set(world.getPlayer().getPosition(), 0);
    camera.update();
}

@Override
public void render(float deltaTime) {
    // clear screen
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

    // seprate update logic
    update(deltaTime);

    // set camera to what we see
    worldRenderer.renderer.setView(camera);
    worldRenderer.renderer.render();

    // draw world
    game.spriteBatch.setProjectionMatrix(camera.combined);
    worldRenderer.render();

    // monster UI
    game.spriteBatch.setProjectionMatrix(uiCam.combined);
    for (Monster monster : world.getMonsters()) {
        uiCam.project(uiPosition.set(monster.getPosition().x, monster.getPosition().y, 0));
    }

    game.spriteBatch.begin();
    Assets.font.draw(game.spriteBatch, "Firefox", uiPosition.x / 2, uiPosition.y / 2);
    game.spriteBatch.end();

    // Player Hud
    game.spriteBatch.setProjectionMatrix(hud.stage.getCamera().combined);
    hud.stage.draw();
}

```

I'll appricate all kind of suggestions! If i could use Scene2D.ui for monsters aswell, would be great.

Cheers.

# Answer
> 0 votes
If you want the text to show up above the monster's head, you'll have to add at least the monster's sprite's height to the base Y of the font, something like:

```
Assets.font.draw(spriteBatch, "Monster", position.x, position.y + getFrame().getHeight());

```

Secondly, if you put the font rendering code before the sprite/texture rendering code, the font will be overlapped by the sprite, so I'd consider changing the order of the render lines to something like:

```
public void render(SpriteBatch spriteBatch) {
    spriteBatch.draw(getFrame(), position.x, position.y, width * world.unitScale, height * world.unitScale);
    Assets.font.draw(spriteBatch, "Monster", position.x, position.y);
    Assets.font.getData().setScale(1 * world.unitScale, 1 * world.unitScale);
}

```

This will make the font overlap the sprite, though I'd consider putting the name rendering code in a separate loop all together, otherwise monster sprites standing above your sprite but "under" the name tag will sometimes overlap it, but this is a design decision.

---
Tags: libgdx
---


# Question
Title: How to hide a post-processed mesh outline when/where the mesh is hidden
I'm working on setting up an active outline in my 3d engine, a highlight effect for selected 3d characters or scenery in the screen. After working with the stencil buffer and getting some unsatisfactory results (issues with concave shapes, outline thickness due to distance from camera, and inconsistencies between my desktop and laptop), I switched to edge detection and frame buffer sampling and got an outline I'm pretty satisfied with.

However, I am not able to hide the outline when the selected mesh is behind another mesh. This makes sense given my process, since I simply render 2d shader outline from a frame buffer after rendering the rest of the scene.

Two screen captures of my results are below. The first is a "good" outline, the second is where the outline is seen over a mesh that blocks the outline source.

The rendering process runs like this: 1) Draw only the alpha of the highlighted mesh, capturing a black silhouette in a frame buffer (framebuffer1).

2) Pass the texture from framebuffer1 to a second shader that performs the edge detection. Capture edge in framebuffer2.

3) Render the entire scene.

4) Render the texture from framebuffer2 on top of the scene.

I have a few ideas on how to accomplish and am hoping to get feedback on their validity, or on simpler or better methods.

First, I've thought of rendering the entire scene to a frame buffer and storing the visible silhouette of the highlighted mesh in the alpha channel (all white save where the highlighted mesh is visible). I would then perform the edge detection on the alpha channel, render the scene frame buffer and then render the edge on top. Resulting in something like this:

To accomplish this, I thought of setting a define only during the render pass of the highlighted object that would draw all black in the alpha for any visible pixels.

My second idea is to use the current render process outlined above, but also store the X, Y and Z coordinates in the R, G and B channels of framebuffer1 when rendering the silhouette of the selected mesh. Edge detections would be performed and stored in framebuffer2, but I would pass on the RGB/XYZ values from the edges of the alpha to the silhouette. Then, when rendering the scene, I would test if the coordinate is within the edge stored in framebuffer2. If so, I would then test the depth of the current fragment to determine if it is in front of or behind the coordinates extracted from the RGB channels (converted to camera space). If the fragment is in front of the depth coordinates, the fragment would be rendered normally. If the fragment is behind, it would be rendered as the solid outline color. This seems like a more convoluted and error prone method...I haven't fully grasped packing and unpacking floats in OpenGL yet, but my feeling is I may run into floating point precision issues when trying to store the XYZ coordinates in the RGB channels.

I'm using LibGDX for this project and would like to support WebGL and OpenGL ES, so none of the solutions involving geometry shaders or newer GLSL functions are available to me. If anyone could comment on my proposed approaches or propose something better I'd really appreciate it.

# Answer
1) in a frame buffer object, you can run a laplacian shader in the GPU to obtain the contour.

2) you have to use the final depth buffer when you draw your object in the FBO, that way you will draw only the visible part of your object in the FBO, and the laplacian will contour only the visible part.
> 0 votes

# Answer
I hope I can make this clear, but basically you need to make a stencil of both objects as if they are both selected, then only keep the areas in the bounding box of the item you actually want to highlight.

So basically you make one stencil buffer of both objects selected (or all objects that occlude the object, really...but I would not worry about those cases unless it actually comes up a lot - if it's that occluded people are not going to expect this much help), then and it with a stencil of the bounding box for your object.

That should get the effect you are looking for.

Alternatively you can just leave the 'bad' result and I don't think most people will care too much, though this depends on your data/game and especially the size of the objects.
> 0 votes

# Answer
I would render the entire scene into a stencil buffer with the desired outlined object to set a bit and for anything else to discard/remove the bit.

Then get rid of edge detection, you don't need that, instead you can just scale the buffer up a little bit. So each object just grows slightly.

From there you're stencil buffer can have the outline you need. It's all about making sure that the other objects you're rendering are turning off the bits in your stencil buffer.
> -1 votes

---
Tags: opengl, opengl-es, webgl, selection, outline
---


title: Image Not Loading Crafty.js

text:
# Question
Title: Image Not Loading Crafty.js
I am experimenting with Crafty.js, and I have called .image() on an entity, and the image is not loading. When I look through the web inspector, I can see that the cloud entity exists, and that the cloud image is found, but it is not showing up. What is the proper way to load an image on an entity, and what is wrong with my code?

mainCrafty.js:

```
Crafty.e('myCloud, 2D, DOM, Image')        // cloud
        .attr({x: 300, y: 10, w: 45, h: 30})
        .image('images/cloud.png');

```

Here is the directory structure:

```
index.html
images/
   cloud.png
scripts/
   crafty.js
   mainCrafty.js

```

# Answer
> 0 votes
It turns out that the image was to large for the size I wanted it to be, so I was only seeing the corner of it (which was blank).

---
Tags: javascript, crafty
---


title: Raycasting from vertices is not working

text:
# Question
Title: Raycasting from vertices is not working
I have two perpendicular planes in xz and yz like this

I want to find the projection of the vertices of plane 2 on plane 1 using raycasting.The rays are hitting the plane but the log is showing zeros. why?

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

//[ExecuteInEditMode()]
public class PlaneManipulation : MonoBehaviour {
    Ray ray;
    RaycastHit hit;

    Mesh mesh;
    private Vector3[] vertices;
    public float rayLength;

    public LayerMask planeLayer;

    void ChangeMesh() {
        mesh = GetComponent<MeshFilter>().sharedMesh;
        vertices = mesh.vertices;
        //using only the first row of the vertices from the plane
        for (int i = 0; i < 11; i++)
        {
            Vector3 vert = transform.TransformPoint(vertices[i]);

            Physics.Linecast(vert, Vector3.up, out hit,planeLayer);

            Debug.DrawRay(vert, Vector3.up);

            Debug.Log("hitPoint = " + hit.point);

            //vert.y = hit.point.y;
            //vertices[i].y = hit.point.y;
            //vertices[i] = transform.InverseTransformPoint(vert);
        }

        mesh.vertices = vertices;
        mesh.RecalculateNormals();
        mesh.RecalculateBounds();
    }

    void Update() {

        ChangeMesh();
    }
}

```

# Answer
You're not raycasting, you're **linecasting**:

```
Physics.Linecast(vert, Vector3.up, out hit,planeLayer);

             origin | destination | hit info | layer mask

```

The second argument here is the end of the line you want to check along, *not* the direction of the line. So you're checking for an intersection along the line from your vertex to the point (0, 1, 0) in world space - probably not what you intend.

Check the docs on Linecast versus Raycast to confirm.

I think what you mean to write is:

```
Physics.Raycast (vert, Vector3.up, out hit, Mathf.Infinity, planeLayer);

              origin | direction | hit info | max distance | layer mask

```

I've labelled the arguments here because implicit conversion between layer masks and numbers makes it easy to accidentally get the wrong override without any errors or warnings.
> 2 votes

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


title: PlayerCenteredScores in LeaderBoards

text:
# Question
Title: PlayerCenteredScores in LeaderBoards
```
Games.Leaderboards.loadPlayerCenteredScores(mGoogleApiClient,leaderboardId, LeaderboardVariant.TIME_SPAN_ALL_TIME, LeaderboardVariant.COLLECTION_PUBLIC, 5).setResultCallback(new ResultCallback<Leaderboards.LoadScoresResult>()
{
    public void onResult(Leaderboards.LoadScoresResult arg0) {
    // TODO Auto-generated method stub

       int size = arg0.getScores().getCount();
        Log.e("ACHGOD", "SIZE="+Integer.toString(size));

        for (int i = 0; i < 3; i++) {
            LeaderboardScore lbs = arg0.getScores().get(i);
            // String name = lbs.getScoreHolderDisplayName();
            String score = lbs.getDisplayScore();
            Log.e("ACHGOD", "SCORE="+score);
            //Uri urlimage = lbs.getScoreHolderHiResImageUri();
        }
        // arg0.getScores().close();
        arg0.getScores().release();
    }
});

```

I am getting the integer score value here. But, I could not find any proper documentation regarding the score value, which I get.

Is it the high score? Or, is it the last submitted score? I am looking to get the highest score made by the currently logged-in user from the leaderboard.

Thanks in advance.

# Answer
> 1 votes
The documentation isn't clear about the ordering of the scores. When the documentation doesn't guarantee any kind of order, guarantee it yourself.

I suggest you simply iterate through the list, keeping track of the largest (for O(N) time).

---
Tags: android, libgdx, leaderboards, google-play-services
---


title: Phaser BitmapData Pick Color and Paint

text:
# Question
Title: Phaser BitmapData Pick Color and Paint
Hi guys,

Could anyone kindly shows me a little bit of code about pick and paint color to the sprite?

here is my code that I have played around, but I still cannot find out and achieve it.

Thanks you in advance for your time and consideration.

```
preload: function() {
    this.game.load.image('test', 'test.png');
},

create: function() {

    this.color1 = this.drawRec('rgb(141,243,160)', 20, 20);
    this.color2 = this.drawRec('#6bd4e0', 100, 20);
    this.color3 = this.drawRec('#cb6be0', 20, 100);
    this.color4 = this.drawRec('#8df3a0', 100, 100);
    this.square = this.game.make.bitmapData();
    this.square.load('test');
    this.square.addToWorld(this.game.world.centerX, this.game.world.centerY, 0.5, 0.5);

    this.game.input.onDown.add(this.pickColor, this);
},

drawRec: function(color, x, y) {
    this.bmd = this.game.make.bitmapData(100, 100);
    this.bmd.ctx.beginPath();
    this.bmd.ctx.rect(0,0,50,50);
    this.bmd.ctx.fillStyle = color;
    this.bmd.ctx.fill();
    this.sprite = this.game.add.sprite(x, y, this.bmd);
},

pickColor: function(pointer, x, y) {
    console.log(this.bmd.getPixelRGB(x,y));
}

```

# Answer
3 issues:

* In the `drawRect` funtion `x` and `y` doesn't have the pointers values. You should use `pointer.x` and `pointer.y`
* Each time you call the `drawRec` function you are creating a new bitmapData, storing it in this.bmd. So in the `console.log(this.bmd.getPixelRGB(x,y));` you will get the information of the las square created. You should create a unique bitmapData and add the squeres to it.
* As the phaser docs says: "If you have drawn anything to the BitmapData since it was created you must call BitmapData.update to refresh the array buffer".

So your code should looks something like this:

```
preload: function() {
    this.game.load.image('test', 'test.png');
},

create: function() {
    this.bmd = this.game.make.bitmapData(500, 500);
    this.color1 = this.drawRec('rgb(141,243,160)', 20, 20);
    this.color2 = this.drawRec('#6bd4e0', 100, 20);
    this.color3 = this.drawRec('#cb6be0', 20, 100);
    this.color4 = this.drawRec('#8df3a0', 100, 100);
    this.square = this.game.make.bitmapData();
    this.square.load('test');
    this.square.addToWorld(this.game.world.centerX, this.game.world.centerY, 0.5, 0.5);

    this.game.input.onDown.add(this.pickColor, this);
},

drawRec: function(color, x, y, id) {
    this.bmd.ctx.beginPath();
    this.bmd.ctx.rect(x,y,50,50);
    this.bmd.ctx.fillStyle = color;
    this.bmd.ctx.fill();
    this.sprite = this.game.add.sprite(0, 0, this.bmd);
},

pickColor: function(pointer) {
    this.bmd.update();
    console.log(this.bmd.getPixelRGB(pointer.x,pointer.y));
}

```
> 0 votes

# Answer
@jolmos, sorry for disturbing you again bro.

I would like ask you a little bit more of this code about the dynamic click of button colors.

```
drawColor: function() {
    this.colorGroup = this.game.add.group();
    var arrayColor = [
        'rgb(86,160,211)', 'rgb(156,141,195)', 'rgb(26,80,120)', 'rgb(233,119,175)',
        'rgb(141,243,160)', 'rgb(167,64,150)', 'rgb(243,115,33)', 'rgb(94,220,255)'
    ];
    var padding = 10;
    var i=0;
    this.colorGroup.x = 20;
    this.colorGroup.y = 100;
    for(var row=0; row<4; row++) {
        for(var col=0; col<2; col++) {
            this.bmd = this.game.add.bitmapData(50, 50);
            this.bmd.ctx.beginPath();
            this.bmd.ctx.rect(0, 0, 50, 50);
            this.bmd.ctx.fillStyle = arrayColor[i];
            this.bmd.ctx.fill();
            this.buttonColor = this.game.add.button((padding+50)*col, (padding+50)*row, this.bmd, this.btnColor, this);
            this.buttonColor.name = 'color'+i;
            this.colorGroup.add(this.buttonColor);
            i++;
        }
    }
},

btnColor: function(button) {
    this.bmd.update();
    console.log(button.name);
    var test = this.bmd.getPixelRGB(button.x,button.y);
    console.log(test); // I cannot get the different colors of the button. Whats wrong?
},

```
> 0 votes

---
Tags: color, phaser
---


title: OpenGL: Properly attach Texture

text:
# Question
Title: OpenGL: Properly attach Texture
## Problem:

Been trying for hours to set a simple png of a cross hair as a texture (so I could later stick in the middle of the view like a normal cross hair), without luck.

I'm coding in Java with JOGL.

P.S Also need to make the background of the texture transparent. But that's another problem.

## Code:

```
public void display(GLAutoDrawable gLDrawable) {
    final GL2 gl = gLDrawable.getGL().getGL2();
    gl.glClear(GL2.GL_COLOR_BUFFER_BIT | GL2.GL_DEPTH_BUFFER_BIT);
    gl.glLoadIdentity();  // Reset The View
    gl.glTranslatef(0.0f, 0.0f, -5.0f);

    gl.glTexParameteri ( GL2.GL_TEXTURE_2D,GL2.GL_TEXTURE_WRAP_T, GL2.GL_REPEAT );
    gl.glTexParameteri( GL2.GL_TEXTURE_2D,GL2.GL_TEXTURE_WRAP_S, GL2.GL_REPEAT );
    texture.bind(gl);

    gl.glBegin(GL2.GL_QUADS);
    // Front Face
    gl.glTexCoord2d(0, 0);
    gl.glVertex3d(0, 0, 0);
    gl.glTexCoord2d(0, 1);
    gl.glVertex3d(0, 1, 0);
    gl.glTexCoord2d(1, 1);
    gl.glVertex3d(1, 1, 0);
    gl.glTexCoord2d(1, 0);
    gl.glVertex3d(1, 0, 0);
    gl.glEnd();
}

public void init(GLAutoDrawable drawable) {
    final GL2 gl = drawable.getGL().getGL2();
    gl.glShadeModel(GL2.GL_SMOOTH);              // Enable Smooth Shading
    gl.glClearColor(0.0f, 0.0f, 0.0f, 0.5f);    // Black Background
    gl.glClearDepth(1.0f);                      // Depth Buffer Setup
    gl.glEnable(GL2.GL_DEPTH_TEST);              // Enables Depth Testing
    gl.glDepthFunc(GL2.GL_LEQUAL);               // The Type Of Depth Testing To Do
    // Really Nice Perspective Calculations
    gl.glHint(GL2.GL_PERSPECTIVE_CORRECTION_HINT, GL2.GL_NICEST);
    gl.glEnable(GL2.GL_TEXTURE_2D);
    gl.glEnable(GL2.GL_BLEND);
    try {
        String filename = "resources/misc/crosshair.png";
        texture=TextureIO.newTexture(new File( filename ),true);
    } catch (IOException e) {
        e.printStackTrace();
        throw new RuntimeException(e);
    }
    gl.glTexParameteri(GL2.GL_TEXTURE_2D, GL2.GL_TEXTURE_MIN_FILTER, GL2.GL_LINEAR);
    gl.glTexParameteri(GL2.GL_TEXTURE_2D, GL2.GL_TEXTURE_MAG_FILTER, GL2.GL_LINEAR);
}

```

## Result:

## Original png:

## Edit

Changed code above according to comments, here's the new result:

## Another Edit

Had to add this line after glBlend, everything works after that:

```
gl.glBlendFunc(GL2.GL_SRC_ALPHA, GL2.GL_ONE_MINUS_SRC_ALPHA);

```

# Answer
SurvivalMachine nailed one of your problems (you can see that the texture is repeated twice).

Your other problem (the texture is a big blob instead of a crosshair) is because you don't use transparency : some of the completely transparent pixels of your texture have a green color value (that's a common sight with optimized PNGs).

Just enable blending with `gl.glEnable(GL.GL_BLEND);`, and you'll have proper color blending in the transparent areas.
> 2 votes

# Answer
Maybe there's more problems, but at least this looks incorrect:

```
gl.glTexCoord2f(2f, 1.0f);

```

Your texture is repeated horizontally 2 times because its wrap mode is **repeat** and the coordinates you set are over `1` (in this case `2f`). To fix this, replace `2f` with `1f`:

```
gl.glTexCoord2f(1f, 1.0f);

```
> 1 votes

---
Tags: opengl, c++, java, graphics, jogl
---


# Question
Title: How to find the optimum path, on a road, for a car?
For the moment I have an AI car, that follows points (let's call this Waypoints), that I built by myself.

Of course, it's not optimal because of my poor human hand, and car knowledge.

After this drawing, I put waypoints (about 80) on this red line, and my car is able to follow it (and dodge other cars, but that's another story).

But... It's not perfect: I read some articles, but I don't know how to implement the generation of the perfect path..

http://www.drivingfast.net/techniques/racing-line.htm (speaking about an 'Apex', but I don't know how to find this particular point)
"Searching for the Optimal Racing Line Using Genetic Algorithms" (too complicated for my little game)

# Answer
You're looking for two important properties here. The path must obviously be continuous (can't jump) but also the direction must be continuous (turning around a corner takes time). Since it's a racing game, there's also a third constraint: the turn radius probably should be larger at high speeds. However, you can probably fake that one.

The common techniques to calculate paths like this are splines / Bezier curves
> 1 votes

# Answer
Technique generally used on AAA games to find the best possible path for a given car (because car settings are often all different) is to run an AI that will improve its driving technique. After thousands (millions?) of runs, comparing the last one to the currently best one, the AI will be able to determine the best possible path for this given car setting.
> 2 votes

---
Tags: car, path
---


# Question
Title: LibGDX - Tilemap Wall Collision Detection Issues
I cribbed some code from another web tutorial (SuperKoalio - https://github.com/libgdx/libgdx/blob/master/tests/gdx-tests/src/com/badlogic/gdx/tests/superkoalio/SuperKoalio.java) about detecting a collision between my player, and tiles within a tilemap layer called "walls". The game is an RPG (Gauntlet) style game. The collision detection generally works but occasionally, the player will pass through a wall and appear much further away on the map, or suddenly outside the bounds of the map. It's almost like there are gaps.

The code I have used appears to check the tiles immediately to the left and right of the player, and then performs another check on the tiles above and below the player. I think the idea is fundamentally okay, except that this doesnt take into consideration diagonal movement, which I believe might be causing the player to pass through walls.

The code inside my detection routine is as follows:

```
public void checkCollisions(float delta) {
    ////////////////////////////////////////////////////////////////
    //collision detection - X
    int startX, startY, endX, endY;
    startX  = (int) (position.x);
    endX    = (int) (position.x + 1);
    startY  = (int) (position.y);
    endY    = (int) (position.y);

    playerRect = rectPool.obtain();
    playerRect.set(position.x, position.y, 1.0f, 1.0f);

    getWalls(startX, startY, endX, endY, walls);

    for (Rectangle wall : walls)
    {
        //Rectangle rectangle = rectangleObject.getRectangle();
        if (playerRect.overlaps(wall) && velocity.x != 0) {
            velocity.x = 0;
            if(facingDir == 3) {
                position.x = wall.x+1.1f;
            } else if(facingDir == 4) {
                position.x = wall.x-1.1f;
            }

            break;

        }
        // collision happened
        //break;
    }

    playerRect.x = position.x;

    // if the player is moving upwards, check the tiles to the top of it's
    // top bounding box edge, otherwise check the ones to the bottom
    if (velocity.y > 0)
    {
        startY = (int) (position.y);
        endY = (int) (position.y + 1.1f);
    }
    else
    {
        startY = endY = (int) (position.y);
    }

    startX = (int) (position.x);
    endX = (int) (position.x + 1);

    getWalls(startX, startY, endX, endY, walls);

    //playerRect.y = velocity.y;

    for (Rectangle wall : walls)
    {
        if (playerRect.overlaps(wall) && velocity.y != 0)
        {
            velocity.y = 0;
            //velocity.x = 0;
            if(facingDir == 1) {
                position.y = wall.y - 1.1f;
            } else if(facingDir == 2) {
                position.y = wall.y + 1.1f;
            }
            break;
        }
        break;
    }

    playerRect.y = position.y;

    rectPool.free(playerRect);

    velocity.x = 0;
    velocity.y = 0;

}

```

And the "getWalls()" method which loads the walls layer is as follows:

```
/**
 * Get the walls of the map for collision detection between the player and the walls, so that
 * the player cannot pass through.
 * @param startX
 * @param startY
 * @param endX
 * @param endY
 * @param walls
 */
private void getWalls(int startX, int startY, int endX, int endY, Array<Rectangle> walls)
{
    TiledMapTileLayer layer = (TiledMapTileLayer) MapRenderer.map.getLayers().get("walls");
    layer.setVisible(false);
    rectPool.freeAll(walls);
    walls.clear();

    for (int y = startY; y <= endY; y++)
    {
        for (int x = startX; x <= endX; x++)
        {
            TiledMapTileLayer.Cell cell = layer.getCell(x, y);
            if (cell != null)
            {
                Rectangle rect = rectPool.obtain();
                rect.set(x, y, 1, 1);
                walls.add(rect);
            }
        }
    }
}

```

Does anyone have any ideas as to why this routine is not very robust?

I really want to be able to achieve this as simply and effectively as possible. The same technique would also need to be applied to enemies, to stop them from also passing through walls.

Surely there must be a better and more reliable way of doing this, or is it just that there are faults/gaps in my code - for example if I it a wall in a diagonal direction?

Regards

James

# Answer
In your update loop:

* You first handle the input from the user and move him accordingly.
* Then, you check for collisions with the walls and identify which wall/walls collide with the player. To improve the efficiency of that, instead of checking every single wall in your game, you can check only the walls close to your player and check if there is a collision with those walls. To do that, you will also have to consider how fast the player is moving.
* Lastly, if there is a collision, your player should now be inside 1 or more walls. So, using the position and size of the wall/walls that the user collided with (you calculated those walls in the previous step), you need to move your player right on the edges of those walls so that the player, just barely, no longer collides with them. To do that, you will also have to consider the player's position before and after the input was handled and move the player towards the opposite direction.
> 1 votes

# Answer
I think that you have error in your collision testing function. Maybe it has to be like this:

```
foreach (Rectangle wall in walls)
    {

   /* your code here */

    }

```

In your original code you are not testing all the walls from the list generated by getWalls() procedure.
> 0 votes

---
Tags: collision-detection, libgdx, tiled
---


# Question
Title: How do games like Street Fighter compensate for bad frame rates?
I know fighting games like Street Fighter like to run and are capped to a standard 60 fps. All their combos, animations, chains, etc... are based on frames. So, how do they compensate for slowdowns when the game can't catch up the needed frame rate?

It doesn't seem an easy task like just scale the used frame count data used in the different systems of the game because of the discrete nature of frames.

Any tip on this?

# Answer
Most games separate the *visual* framerate from the *physical* framerate. The gameplay itself is always calcualted with a fixed number of frames per second, but the drawing only happens when there is time left. That means the game might run at 60 fps internally but only show you 20 of those frames on the screen.

This works quite well because in most games the physics are just a tiny fraction of the overall calculation load. The bottleneck are almost always the graphics. This is especially true for 1 vs. 1 fighting games where you have just two objects in the scene which have any notable mechanics (the fighters). Compare that to an open-world game with potentially hundreds to thousands of moving objects in a scene, all potentially with complicated physics. And even in those games the bottleneck are usually *still* the graphics.

Another approach is to have all game mechanical calculations take the time since the last frame into account, so the speed of the game is not influenced by the framerate (the delta-time approach). This is the recommended approach used by Unity.

When you would like to use Unity but still work with a fixed physics framerate, implement your game mechanics in `FixedUpdate` instead of `Update`. But keep in mind that the `Input` class unfortunately only gets updated in `Update` which is called once per render-frame. So complex input sequences during render lags might not get recognized correctly. Solution: Don't have bad framerates :)
> 1 votes

---
Tags: unity, frame-rate
---


# Question
Title: Unity2D - collide with objects while moving to a position
How do I get my character to collide with other objects while moving to a position?

All I've managed to do is change the position, it only collides if the character is not moving, it's like he is moving behind.

```
void Update () {

    foreach(Touch touch in Input.touches)
    {

        if (touch.phase == TouchPhase.Began)
        {
            worldCoordinates = Camera.main.ScreenToWorldPoint(touch.position);
            posi.x = worldCoordinates.x;
            posi.y = worldCoordinates.y;
            //transform.position = Vector3.MoveTowards(transform.position, posi, speed);
            //transform.Translate(0,32.4,0);
            //rb.MovePosition(posi);
        }
    }
}

```

# Answer
> 1 votes
First of all, all your physics related stuff should be done in `FixedUpdate` method and not in `Update` method.

`Update` is called every frame, while `FixedUpdate` is called at fixed interval. When you ask Physics movement computation in `FixedUpdate` Unity will predict the new position in `Update` until it'll be able to compute the actual position in the next `FixedUpdate` (ie: it explains why fast moving objects are usually not stopped by walls. Because the FixedUpdate happens too soon or too late to compute the collision).

Also, if you want to move a `GameObject` that has a `RigidBody` attached don't move it using its `Transform`, do it using its `RigidBody`.

So instead of setting `transform.position` use directly `rb.MovePosition`. This will teleport your gameObject from its current position to the desired position every `FixedUpdate`. If it's not smooth enough, you can Lerp between the two positions in the `Update` method.

# Answer
> 0 votes
In addition to @lvictorino answer, maybe what you're looking for is in fact the `AddForce` method.

I'm not exactly familiar on how it could work with Unity, but roughly, what you could do is

```
// Rough pseudocode
difference = touchPosition -  objectPosition

distance = difference.lenght
direction = difference.normalize

radiusForMaxForce = 50 // tweak this value, above that distance maxForce will be used as-is,
                       // otherwise it will be scaled down
maxForce = 25 // tweak this value according to your needs

if distance > radiusForMaxForce
  distance = radiusForMaxForce

forceRatio = distance / radiusForMaxForce

thrust = forceRatio * maxForce
forceVector = direction * thrust

rb.AddForce(forceVector)

```

If your target game object encounters other rigid body, the physics simulation should be respected: free bodies will be pushed around, and there is not going to be inter-penetration.

---
Tags: c#, collision-detection, unity, rigidbody
---


# Question
Title: Prefab Instantiates into scene, but when I store a reference to the instance it's null
I am instantiating and parenting two objects - the first is a Unity primitive and the second is a prefab cube (literally nothing but a cube made into a prefab). The direct instantiation of the primitive works great, but when I try to instantiate the prefab I get ***NullReferenceException:Object reference not set to an instance of an object***

Below is my script:

```
    Vector3 myPosition = new Vector3 (x, Rotator_Prefab.transform.position.y , z);
    GameObject ball = GameObject.CreatePrimitive (PrimitiveType.Sphere);
    ball.transform.parent = gameObject.transform; // no problems and gameObject.name gives me the right parent

    GameObject prefab = Instantiate (Rotator_Prefab, myPosition, Quaternion.identity) as GameObject;
    prefab.transform.parent = gameObject.transform; // this gives me an error

```

The error is coming from the prefab still being null after being instantiated. Still it shows up in the scene. Would anyone have any ideas ? \- Thank you!

Update: Where the prefab is coming from

# Answer
> 0 votes
In the end, keeping the code from the question and changing the public field of the Prefab to type ***GameObject*** (not Transform) did the trick.

(I did not need to use Resources.Load("*PATH*");)

I hope this saves someone some time

# Answer
> 1 votes
For what I've seen in the comments your prefab is null because there is nothing assigned at runtime.

Drag n dropping stuff in the inspector of your script is ignored by the engine at scene load. Once your script is assigned as component to a gameObject in your hiearchy then public slots will appear and you should do there your drag n drop.

Otherwise you can dynamically load via script doing

```
Rotator_Prefab = Resources.Load<Gameobject>(*your prefab path*);

```

**After you edit** I should specify that your variable must be of type GameObject to instantiate it correctly.

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