# Question
Title: Accurately simulating the lots of dice rolls without loops?
OK so if your game rolls lots of dice you can just call a random number generator in a loop. But for any set of dice being rolled often enough you will get a distribution curve/histogram. So my question is there a nice simple calculation I can run that will give me a number that fits that distribution?

E.g. 2D6 - Score - % Probability

2 - 2.77%

3 - 5.55%

4 - 8.33%

5 - 11.11%

6 - 13.88%

7 - 16.66%

8 - 13.88%

9 - 11.11%

10 - 8.33%

11 - 5.55%

12 - 2.77%

So knowing the above you could roll a single d100 and work out an accurate 2D6 value. But once we start with 10D6, 50D6, 100D6, 1000D6 this could save a lot of processing time. So there must be a tutorial / method / algorithm that can do this fast? It is probably handy for stock markets, casinos, strategy games, dwarf fortress etc. What if you could simulate the outcomes of complete strategic battle that would take hours to play with a few calls to this function and some basic maths?

# Answer
As I mentioned in my comment above, I recommend you profile this before overcomplicating your code. A quick `for` loop summing dice is a lot easier to understand and modify than complicated math formulae and table-building/searching. Always profile first to make sure you're solving the important problems. ;)

That said, there are two main ways to sample sophisticated probability distributions in one fell swoop:

---

## 1. Cumulative Probability Distributions

There's a neat trick to sample from continuous probability distributions by using only a single uniform random input. It has to do with the cumulative distribution, the function that answers "What is the probability of getting a value *no greater* than x?"

This function is non-decreasing, starting at 0 and rising to 1 over its domain. An example for the sum of two six-sided dice is shown below:

If your cumulative distribution function has a convenient-to-calculate inverse (or you can approximate it with piecewise functions like Bézier curves), you can use this to sample from the original probability function.

The inverse function handles parcelling up the domain between 0 and 1 into intervals mapped to each output of the original random process, with the catchment area of each matching its original probability. (This is true infinitescimally for continuous distributions. For discrete distributions like dice rolls we need to apply careful rounding)

Here's an example of using this to emulate 2d6:

```
int SimRoll2d6()
{
    // Get a random input in the half-open interval [0, 1).
    float t = Random.Range(0f, 1f);
    float v;

    // Piecewise inverse calculated by hand. ;)
    if(t <= 0.5f)
    {
         v = (1f + sqrt(1f + 288f * t)) * 0.5f;
    }
    else
    {
         v = (25f - sqrt(289f - 288f * t)) * 0.5f;
    }

    return floor(v + 1);
}

```

Compare this to:

```
int NaiveRollNd6(int n)
{
    int sum = 0;
    for(int i = 0; i < n; i++)
       sum += Random.Range(1, 7); // I'm used to Range never returning its max
    return sum;
}

```

See what I mean about the difference in code clarity and flexibility? The naive way might be naive with its loops, but it's short and simple, immediately obvious about what it does, and easy to scale to different die sizes and numbers. Making changes to the cumulative distribution code requires some non-trivial math, and it would be easy to break and cause unexpected results without any obvious mistakes. (Which I hope I haven't made above)

So, before you do away with a clear loop, make absolutely certain that it's really a performance problem worth this kind of sacrifice.

---

## 2. The Alias Method

The cumulative distribution method works well when you can express the inverse of the cumulative distribution function as a simple math expression, but that's not always easy or even possible. A reliable alternative for discrete distributions is something called the Alias Method.

This lets you sample from any arbitrary discrete probability distribution by using just two independent, uniformly distributed random inputs.

It works by taking a distribution like the one below on the left (don't worry that the areas/weights don't sum to 1, for the Alias Method we care about *relative* weight) and converting it to a table like the one on the right where:

* There is one column for each outcome.
* Each column is split into at most two parts, each associated with one of the original outcomes.
* The relative area/weight of each outcome is preserved.

(Diagram based on images from this excellent article on sampling methods)

In code, we represent this with two tables (or a table of objects with two properties) representing the probability of choosing the alternate outcome from each column, and the identity (or "alias") of that alternate outcome. Then we can sample from the distribution like so:

```
int SampleFromTables(float[] probabiltyTable, int[] aliasTable)
{
    int column = Random.Range(0, probabilityTable.Length);
    float p = Random.Range(0f, 1f);
    if(p < probabilityTable[column])
    {
        return column;
    }
    else
    {
        return aliasTable[column];
    }
}

```

This involves a bit of set-up:

1. Compute the relative probabilities of every possible outcome (so if you're rolling 1000d6, we need to compute the number of ways to get every sum from 1000 to 6000)
2. Build a pair of tables with an entry for each outcome. The full method goes beyond the scope of this answer, so I highly recommend referring to this explanation of the Alias Method algorithm.
3. Store those tables and refer back to them each time you need a new random die roll from this distribution.

This is a space-time tradeoff. The precomputation step is somewhat exhaustive, and we need to set aside memory proportionate to the number of outcomes we have (though even for 1000d6, we're talking single-digit kilobytes, so nothing to lose sleep over), but in exchange our sampling is constant-time no matter how complex our distribution might be.

---

I hope one or the other of those methods may be of some use (or that I've convinced you that the naive method's simplicity is worth the time it takes to loop) ;)
> 17 votes

# Answer
The answer unfortunately is that this method would not result in an increase in performance.

I believe that there may be some misunderstanding in the question of how a random number is generated. Take the example below \[Java\]:

```
Random r = new Random();
int n = 20;
int min = 1; //arbitrary
int max = 6; //arbitrary
for(int i = 0; i < n; i++){
    int randomNumber = (r.nextInt(max - min + 1) + min)); //silly maths
    System.out.println("Here's a random number: " + randomNumber);
}

```

This code will loop 20 times printing out random numbers between 1 and 6 (inclusive). When we talk about the performance of this code, there is some time taken to create the Random object (which involves creating an array of pseudo-random integers based on the computer's internal clock at the time it was created), and then 20 constant time look-ups on each nextInt() call. Since each 'roll' is a constant time operation, this makes rolling very cheap time-wise. Also notice that the range of min to max doesn't matter (in other words, it's just as easy for a computer to roll a d6 as it is for it to roll a d10000). Speaking in terms of time complexity, the performance of the solution is simply O(n) where n is the number of dice.

Alternatively, we could approximate any number of d6 rolls with a single d100 (or d10000 for that matter) roll. Using this method, we first need to compute s \[number of faces to the dice\] * n \[number of dice\] percentages before we roll (technically it's s * n - n + 1 percentages, and we should be able to divide that roughly in half since it's symmetrical; notice that in your example for simulating a 2d6 roll, you calculated 11 percentages and 6 were unique). After rolling we can use a binary search to figure out which range our roll fell into. In terms of time complexity, this solution evaluates to an O(s\*n) solution, where s is the number of sides and n is the number of dice. As we can see, this is slower than the O(n) solution proposed in the previous paragraph.

Extrapolating from there, say you created both of these programs to simulate a 1000d20 roll. The first would simply roll 1,000 times. The second program would first need to determine 19,001 percentages (for the potential range of 1,000 to 20,000) before doing anything else. So unless you're on a weird system where memory look-ups are severally more expensive than floating-point operations, using a nextInt() call for each roll seems like the way to go.
> 0 votes

# Answer
If you want to store the dice combinations, the good news is that there is a solution, the bad is that our computers are somehow limited in regards to this kind of problems.

**The good news:**

There is a determistic approach of this problem:

1/ Compute all the combinations of your group of dice

2/ Determine the probability for each combination

3/ Search in this list for a result instead of throwing the dices

**The bad news:**

The number of combination with repetition is given by the following formulae

\\$\Gamma\_n^k={n+k-1 \choose k}=\frac{(n+k-1)!}{k!~(n-1)!}\\$

(from french wikipedia):

That means that, for example, with 150 dices, you have 698'526'906 combinations. Let's assume you store the probability as a 32 bit float, you will need 2,6 GB of memory, and you still have to add memory requirement for the indexes...

In computing terms, the combination number can be computed by convolutions, which is handy but doesn't solve the memory constraints.

In conclusion, for a high number of dices, I would advise throwing the dices and observe the result rather than precomputing the probabilities associated with each combination.

**Edit**

However, as you are only interested in the sum of dices, you can store the probabilities with much less resources.

You can calculate precise probabilities for each sum of dice using convolution.

The general formula is \\$F\_i(m) = \sum\_n F\_1(n) F\_{i-1}(m - n)\\$

Then starting from 1/6 form each result with 1 dice, you can construct all the correct probabilities for any number of dice.

Here is a rough java code I wrote for illustration (not really optimized) :

```
public class DiceProba {

private float[][] probas;
private int currentCalc;

public int getCurrentCalc() {
    return currentCalc;
}

public float[][] getProbas() {
    return probas;
}

public void calcProb(int faces, int diceNr) {

    if (diceNr < 0) {
        currentCalc = 0;
        return;
    }

    // Initialize
    float baseProba = 1.0f / ((float) faces);
    probas = new float[diceNr][];
    probas[0] = new float[faces + 1];
    probas[0][0] = 0.0f;
    for (int i = 1; i <= faces; ++i)
        probas[0][i] = baseProba;

    for (int i = 1; i < diceNr; ++i) {

        int maxValue = (i + 1) * faces + 1;
        probas[i] = new float[maxValue];

        for (int j = 0; j < maxValue; ++j) {

            probas[i][j] = 0;
            for (int k = 0; k <= j; ++k) {
                probas[i][j] += probability(faces, k, 0) * probability(faces, j - k, i - 1);
            }

        }

    }

    currentCalc = diceNr;

}

private float probability(int faces, int number, int diceNr) {

    if (number < 0 || number > ((diceNr + 1) * faces))
        return 0.0f;

    return probas[diceNr][number];

}

}

```

Call calcProb() with the parameters you want and then access the proba table for results (first index: 0 for 1 dice, 1 for two dices...).

I checked it with 1'000D6 on my laptop, it took 10 seconds to compute all probabilities from 1 to 1'000 dices and all possible sums of dices.

With precomputing and efficient storage, you could have quick answers for a high number of dices.

Hope it helps.
> 0 votes

---
Tags: mathematics, probability
---


title: Remove bullets from sprite Group

text:
# Question
Title: Remove bullets from sprite Group
I'm having an issue with removing objects from a sprite Group. What is happening is I have a bullet class and every time the user presses the player shoots a bullet. I have 'alive = bool' code and all works great so long as only one instance of bullet is in the list. If multiple are in the list however only the last one gets removed. Does anyone know how I can fix this?

```
elif event.key == pygame.K_SPACE:
                # Fire a bullet if the user clicks the mouse button
                bullet = Bullet()
                bullet.bullet = bullet
                # Set the bullet so it is where the player is
                bullet.rect.x = player.rect.x + 9
                bullet.rect.y = player.rect.y
                # Add the bullet to the lists
                bullet_list.add(bullet)
                all_sprites_list.add(bullet)
                print(len(bullet_list))

    if bullet.alive == False:
        bullet_list.remove(bullet)
        all_sprites_list.remove(bullet)

#In the class
# If the bullet goes off the screen remove it
    if self.rect.y < 200:
        self.alive = False

```

I have it set to 200 at the moment for testing purposes.

Any help or a better way of doing this would be very much appreciated. Thank you in advance.

# Answer
> 0 votes
You need to use a loop and remove all bullets from the lists where `alive == False`. How your code is set up right now, `bullet` will be the last bullet created (it's only assigned to when a new bullet is created), and no other bullet will be tested or removed from the list.

---
Tags: python, pygame
---


# Question
Title: Starting out with OpenGL when most tutorials are out of date
I'm sure there are already a bunch of questions like this asked, but the constant updating of the OpenGL library throws them all away, and in a month or two, the answers here will be worthless again.

I am ready to start programming in OpenGL using C++. I've got a working compiler (DevCpp; do NOT ask me to switch to VC++, and don't ask me why). Now I'm just looking for a solid tutorial on how to program with OpenGL. My assistant found the tutorial provided by NeHe Productions, but as I've come to find out, it's WAY OUT OF DATE! (although I did pull together a basic window to support an OpenGL canvas)

Then I went online, and found the OpenGL SuperBible, which apparently uses freeglut? But what I'd like to know is whether or not SuperBible 5th edition is up to date any longer. The suggestion to freeglut I found said the latest version was 2.6.0 but now it's 2.8.0!

* Is the OpenGL SuperBible still a good, and fairly up-to-date place to start?
* Is there a better place to go to learn OpenGL?
* Am I allowed to simply store freeglut in the DevCpp include directory (maybe in GL), or is there some important procedure?
* Are there any comments or suggestions that I didn't think to ask since I'm only just beginning?

---

@dreta cleared some things up for me, so now I have a better idea of what to ask:

I think I'd like to start out with OpenGL using a wrapper library instead of directly accessing OpenGL.
I just think that, for a beginner, it would be easier for me to program and get good results, while I don't yet have to understand all the grimy details (as @stephelton mentioned).

The problem is, I can't find any library that doesn't have undefined references to no longer supported functions. Freeglut sounds operational, but it still uses GLU.
Does anyone know what I can do?
Also, I tried compiling the first SuperBible's source, but I got errors since GLAPI is not being defined as a type, the error originating in the GLU library.

I'd like to use the SuperBible, but I don't know how to fix this.

# Answer
Our resident Nicol Bolas maintains an on-line book about modern graphics programming. It uses modern OpenGL, everything is introduced at an easy to consume pace, it's a good place to start. I've been using it to learn modern OpenGL and it's been doing me wonders in the past 2 months.

Beside that there are bits of knowledge here and there. The OpenGL wiki is quite well maintained. The code isn't "best practices" and sometimes there's ambiguity when it comes to OpenGL version, but outside of those rare occasion, it's a great resource.

If you want to learn about GLSL, there's the GLSL Core Tutorial from lighthouse3D. Though this is the only core knowledge i'd "trust" on the site, rest tends to be outdated.

Once you start to understand how modern OpenGL is done, you'll have an easy time looking for specific information, filtering out outdated code and most importantly reading the specification. You just have to start somewhere.

Most, if not all actually, of the OpenGL books availible are outdated. The new SuperBible is a freak of some sort and i wouldn't recommend it to anybody. The OpenGL Programming Guide for OpenGL 4.1 comes out September 16th, unfortunetly the 7th edition uses deprecated code, so you just have to wait, i sure am.

And ofcourse, you can always ask questions here.
> 19 votes

# Answer
It's been a while since this question was asked but I hope this will help people who have the same question as you.

I got started with OpenGL by reading a minibook on `arcsynthesis.org`. Not sure who wrote it. It looks like the site's registration has lapsed or something but you should be able to find it here: http://web.archive.org/web/20140209181347/http://www.arcsynthesis.org/gltut/. It uses OpenGL 3.3, so you will be using the modern pipeline and all the practices that entails, but you won't be exposed to tessellation or compute shaders.

Another site worth looking at is https://open.gl/. It seems to be VERY beginner focused and doesn't cover things nearly as in-depth as the above material, but it could be a good starting point for people who are just starting.

Remember to read the OpenGL wiki and google your function names if you need help. Some of the pages on the wiki are completely useless but others are quite helpful, both as a reference and as learning material.
> 1 votes

# Answer
These old tutorials are still very relevant to beginners. In fact, I would suggest starting there rather than with recent versions of OpenGL. More recent versions have discarded some of the easier methods of drawing geometry (namely immediate-mode drawing).

With recent versions, you have to prepare and send arrays of vertices and tell the video card how your vertices are arranged in the array you provide. These things are cumbersome to debug.

Some versions (namely OpenGL ES 2.x) require you to provide your own lighting equations (in the form of Fragment Shaders) and transform your own vertex data so that it ends up on the screen where you want it (Vertex Shaders). This is even harder to debug, and is no place for a beginner (in my opinion).

So I would actually suggest that you go back to those NeHe tutorials (etc) and start there. They may be "out of date" but they still work. When you start to understand what really happens in the rendering pipeline in OpenGL and get a feel for some of the mathematical concepts that make these things work, then you'll be ready to look into some of the more up-to-date methods of rendering in OpenGL.
> 0 votes

# Answer
As others have said, most books are either deprecated or too advanced. Nonetheless, I would recommend the 5th edition of the SuperBible but only to get a quick overview of what can be done in OpenGL and to get familiar with things like the view/projection etc.

Diving immediately in to modern OpenGL could possibly get you overwhelmed at first, so do consider learning to do some basic things in the now deprecated versions.

I'd also like to add a site with good tutorials I've found lately http://ogldev.atspace.co.uk/
> 0 votes

# Answer
arcsynthesis.org (the site mentioned in the accepted answer) seems to be down and out, unfortunately. (EDIT: it is available at this link!).

Anton Gerdelan's tutorials for OpenGL 4 are very readable and up to date as of mid-2014. The first few are free, the rest are available on amazon, where they have great reviews, for a small price. So far I've been pleased.

There are some more free tutorials for OpenGL 3.3+ at http://www.opengl-tutorial.org/. They date back to 2012, but may be good supplemental material for other sources.
> 0 votes

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


# Question
Title: Getting help on collaboration with Unity especially programmers
My team and I are currently creating a 3D tower defense game with Unity and are compromised of me a few animators modelers and programmers. However as I am still fairly new to Unity I have trouble figuring out ways to collaborate with them. I know not what practices or advice I could get on the front of developing this game. I was hoping someone here might have some insight as to how best to collaborate with all team members and what one might do to get a better flow of information and help or assistance when working on this project. We are all about an hour or more away from each other so we must work remotely to collaborate. Thank you in advance.

# Answer
It depends on many factors so this answer will have to be rather vague. There's also almost nothing Unity specific in your situation.

First off, there are several completely different ways to use Unity, and most of them are equally right. You will have to find a way all teammates agree with.

Regarding tools, source control is mandatory. If you know about source control, chose whatever people on the team are most familiar with. If you don't, use git. It will take the team a few days to get familiar with it, and they will screw up in the beginning, but this is the single most valuable tool you need for collaboration. Make sure you have a central repository where everyone checks in their code at least once a week (if you're doing this professionally full time: once a day), and which should always be working. Use Continuous Integration to make sure it ~~works~~ builds.

Beyond that you need regular team calls with a medium of your choice, could be WhatsApp, Skype, some fancy meeting software, or maybe even something totally crazy like landlines (if you can figure out how to do group calls with those). In these meeting the team needs to share what everyone's been working on, and what everyone is going to work on. Make sure people can use the same tool to contact each other whenever they want/need, and also provide a way to have collaborative whiteboard sessions - this can be done with whiteboard plugins on skype, or with teamviewer and paint, or in a million other ways.

Next, to share the vision of the product you may need a Wiki. Diagrams of how screens interact, paper drafts of GUI screens, description of the story, all that stuff goes there.

Last but not least you need to manage a shared todo list. Something like fogbugz, rally, or jira.

Now, for the slightly more Unity specific stuff, the programmers should use mock objects as prefabs, e.g. a cube for a tower, until the designers have the actual object ready, so the designers can simply replace the prefab and everything still works.

All the gritty details of how the people want to share the work, how much of the work should be done by the designers vs the programmers, and how much code the designers should touch depends 100% on your team members, so the team will figure that out during the team calls.
> 1 votes

---
Tags: unity, teamwork
---


# Question
Title: m_BoneMapping is undefined in OpenGL Step By Step Skeletal Animation Tutorial
I am new to this website I was following this specific tutorial on skeletal animation and I have a good idea on what it is, but when I was following his implementation he used a variable called "m\_BoneMapping" and which is undefined to me. What am I suppose to do?

# Answer
> 1 votes
It looks like that tutorial doesn't include all of the source code but I did find a link to it on the main page, here: http://ogldev.atspace.co.uk/

The Mesh class appears to have an m\_BoneMapping member, which the tutorial describes as the following:

> The m\_BoneMapping array maps a node name to the index that we generate and we use that index to as an entry into the m\_BoneInfo array where the final transformations are stored.

The tutorial describes the m\_BoneMapping as an array, but the source code suggests otherwise. It appears to be a `std::map<std::string, unsigned>` which maps a name (string) to an index (unsigned).

It is populated in the `void Mesh::LoadBones(uint MeshIndex, const aiMesh* pMesh, vector& Bones)` method, and used in `void Mesh::ReadNodeHeirarchy(float AnimationTime, const aiNode* pNode, const Matrix4f& ParentTransform)`

If you add that to your Mesh class it looks like it should all work out.

---
Tags: opengl, animation, skeletal-animation, assimp
---


# Question
Title: System function in entity component architecture
I started working with ECS and I am not completely sure that I understand it correctly. As I see it now - systems can implement logic for collision, movement, similar things like that. But would it be correct to dedicate a system for digging game logic only? It has a method for dig action, it also sets animation component to play "dig" animation and listens for event about animation completion after which it executes dig action. Am I doing it right?

# Answer
It really depends on the kind of game that you are making, but your approach might end up giving you troubles as you add more actions, animations and such as then you would have to actually tell what system has priority over the others to avoid running the dig animation when you're also being attacked, for example.

It's usually more convenient to split up your systems and components making them as generic as possible. So movement, animation, ai, health, gravity, physics are better suited for composing your entities.
> 0 votes

---
Tags: entity-system, artemis
---


# Question
Title: Alternative to entity system in a game engine?
I have been developing a game engine. I was wondering what I should use for a component system. I've read up on entity component systems, but what other alternatives are there? The idea of searching through a "master list" of all entities in the entire game world seems inefficient and slow. I need the most efficient one possible (3D and 2D, if that matters). Using object oriented programming (C++)

# Answer
> 5 votes
You will end with up keeping a list/array/database/dictionary/hastable (etc.) of all objects you have somehow, divided into chunks or not. That is the only way to track and store changes in your game on runtime.

But there is a choice you can make; which one do you care about: memory or CPU? If you care about memory, you should go with single master-list. If you care about CPU, you should go with divided lists like chunks/tagging/layering etc..

But please note that, if your game don't get big enough, these optimizations will be barely noticable for both developers and players.

# Answer
> 5 votes
Build a system where objects can be in multiple lists at once and build lists according to processing categories along with the master list.

This way you can run through the list that suits your purpose.

# Answer
> 4 votes
Divide your world up into chunks. Store a linked list of entities in each chunk. When an entity moves out of a chunk, move it from one list to another.

This allows you to pick out which chunks of entities to send to the player and which to unload more efficiently.

Linked lists are especially good for this because adding/removing elements is fast, as well as them being dynamic.

---
Tags: c++, entity-system
---


title: How do I ensure proper date formatting?

text:
# Question
Title: How do I ensure proper date formatting?
I'm trying to load a date in the form of a string. As there is always 4 possible date formats (x.x.xxxx, x.xx.xxxx, xx.x.xxxx, xx.xx.xxxx (day month year)) I had to take this into account and it is especially hard with the strings length of 8 as it is either xx.x or x.xx.

So I came up with this:

```
public void setDate(String CompleteDate, boolean loadOrNew){
  Date = CompleteDate;
  if(loadOrNew){
    int totalLength = Date.length();
    String sday = null;
    String smonth = null;
    String syear = null;
    if(totalLength == 9){
      sday = String.valueOf(Date.toCharArray(), 0, 2);
      smonth = String.valueOf(Date.toCharArray(), 3, 2);
      syear = String.valueOf(Date.toCharArray(), 6, 4);
    }else if(totalLength == 8){
      sday = String.valueOf(Date.toCharArray(), 0, 2);
      if(sday.contains(".")){
        smonth = String.valueOf(Date.toCharArray(), 2, 2);
      }else{
        smonth = String.valueOf(Date.toCharArray(),3, 1);
      }
      syear = String.valueOf(Date.toCharArray(), 5, 3);
    }else if(totalLength == 7){
      sday = String.valueOf(Date.toCharArray(), 0, 1);
      smonth = String.valueOf(Date.toCharArray(), 2, 1);
      syear = String.valueOf(Date.toCharArray(), 4, 4);
    }else{
      Toast.makeText(c, "Critical date format error occurred. Error G205", Toast.LENGTH_LONG).show();
    }
    sday.replace(".", "");
    smonth.replace(".", "");
    syear.replace(".", "");
    this.day = Integer.parseInt(sday);
    this.year = Integer.parseInt(syear);
    this.month = Integer.parseInt(smonth);
  }
  date.setText("Date: " + CompleteDate);
}

```

However it isn't correct as I get NumberFormatException with "1."

This means I somewhere messed up and the removing of the "." doesn't work. So I need help improving this so it works.

NOTE:

Some of this is android-specific, e.g. the Toast class and TextView class, but everything else is in standard Java.

`date` and `Date` isn't the same. `Date` is the `String`, `date` is the TextView(android).

# Answer
> 0 votes
The easiest way to do this is to use String.split to find out the different parts of the date. The following is pseudo-java but it should give you the idea.

```
String date = <YourDateStringHere>
String dateParts[] = date.split("\\.");
int day = dateParts[0].toInt();
int month = dateParts[1].toInt();
int year = dateParts[2].toInt();

```

Basically the idea is to split the string at each "." character and parse the data between each dot. You can also take different order formats (MM.DD.YYYY instead of DD.MM.YYYY) into account by just swapping some indices around. We use the sequence `"\\."` to match the single character "." because the `split` method wants a regexp pattern.

---
Tags: java
---


# Question
Title: Automapping of the noise texture onto 3D model
I want to apply kind of noise/dust texture to objects so it would look good, and make it without having UV mapping in models. This is because I want to have a possibility to apply this to any objects, despite them having some other textures already. Just to have a way to make anything look little dirty.

It doesn't have to seam well between faces as this is noise type texture. The priority is that the texture scale is preserved.

In the vertex shader I have vertex coordinates as well as normal, binormal and tangent. I thought about projecting 3d vertex coordinates onto a plane defined by the normal and getting 2d coordinates from there, then use them as UV. But either I can't get the equations right, or it's not going to work. I check results on a sphere and I always get places where texture is stretching.

Is there any way to achieve good results?

I'm using XNA/Monogame, C#, HLSL if this matters.

UPDATE: I have found this:

*Calculate Rotation Matrix to align Vector A to Vector B in 3d?* https://math.stackexchange.com/questions/180418/calculate-rotation-matrix-to-align-vector-a-to-vector-b-in-3d/897677#897677

And I thought this could work:

1. Find rotation matrix which would rotate plane normal to (0, 1, 0)
2. Use this matrix to rotate current vertex position.
3. Take (x, z) from the rotated position as (u, v).

However my math skills are not enough to make algorithms out if these equations. Would this work at all?

# Answer
You can use a small 3D texture for the noise and just use the model's vertex coordinates as texture coordinates.

https://msdn.microsoft.com/en-us/library/microsoft.xna.framework.graphics.texture3d.aspx
> 1 votes

---
Tags: c#, shaders, textures, hlsl, monogame
---


# Question
Title: Calculate edge loop from plane intersection
This is a fairly complex question, so please bear with me.

I'm attempting to calculate an edge loop based on the intersection of a plane with a mesh, bounded by a sphere.

Here is a mockup of what the expected result might look like:

The black lines represent the intersected mesh, the orange line the result. Blue and cyan lines are vertex and face normals, respectively. The sphere origin would be somewhere inside the mesh. The orange vertices and sphere origin would also be coincident with the plane. *Note that the edge loop is **not** part of the mesh*. This is *not* a mesh split - just a list of vertices forming a loop along it.

Faces included in the edge should be pointed toward the sphere origin side, and any islands should be ignored (greedy), as shown in this mock up:

In the event that a closed loop cannot be found, the function should return null or an empty array.

I'm working on this in Unity, so I will use its API to further illustrate. The signature I expect to use looks like this:

```
Vector3[] CalculateCorridorLoop(Vector3 planeNormal,
                                Vector3 origin,
                                float radius,
                                MeshFilter meshSource)

```

**So far...**

I've tried a few different approaches, but I'm now leaning toward a more brutal approach. To come up with those mockups I simply used Blender's knife tool, duplicated the edge loop, and then dissolved the edges on the mesh. If I could calculate an edge loop for every face intersecting the plane then project the edges and origin into 2D space using the plane, it simply becomes a problem of finding the outermost loop containing the origin, which is itself contained by the circle.

Of course I get the feeling I've spent so much time on this I've overthought it and missed something simpler - although even that doesn't seem very straightforward. I think I'd need to keep track of which edges belong to which triangles to keep track of which vertex goes with which loop.

I found this paper, Fast Algorithm To Split And Reconstruct Triangular Meshes, which also uses planes for splitting, but seems to integrate the vertices into the mesh as it goes - whereas I just want the resulting edge loops. Though it's entirely possible I'm reading it wrong.

# Answer
> 2 votes
Unity uses indexed meshes which will help (as long they are indexed properly and clean).

* Find a triangle that intersect the plane
* Mark it as scanned
* Find the two edges of that triangle that also intersect the plane
* Use one edge as the start and end of the loop
* Use the other edge to find the next triangle that intersect the plane, it is the one that will have two of the same vertices.
* Mark it as scanned
* Find the next edge intersecting the plane
* Repeat until you've returned to the start edge.

This gives you 1 ordered loop. Repeat with all the unscanned triangles to find all the loops.

Ignore the loops inside other loops using a 2D Point-In-Poly test projected on the cutting plane.

You may still end up with 2 or more loops. For example think of the ways you can slice a donut: You can get two loops outside of one another.

---
Tags: unity
---


# Question
Title: drawing a horizon / sky in OpenGL ES 2.0
I want to render a sky: My camera is at the origin, and I want there to be a white background for all world coordinates with z \< 0 (would normally be considered y \> 0, but I have a different coordinate system via glLookAt()).

I thought I may be able to do this in the fragment shader by multiplying the inverse MVP matrix with the corresponding clip space (?) coordinate (I compute that matrix on the CPU each frame by calling Matrix.invertM()). To get my vertices into the fragment shader, I use a varying variable (I wasn't sure if I could access gl\_Position in the fragment shader) and passed the position right through; not sure if my syntax is right (see below):

Vertex Shader:

```
attribute vec4 position;
varying vec4 vp;
void main() {
  gl_Position = position;
  vp = position;
}

```

Fragment Shader:

```
precision mediump float;
uniform mat4 inverseMatrix;
varying vec4 vp;
void main() {
  vec4 inversePosition = inverseMatrix * vp;
  if (inversePosition.z > 0.0) {
    gl_FragColor = vec4(0,0,0,1);
  } else {
    gl_FragColor = vec4(1,1,1,1);
  }
}

```

Question:

Does this approach seem sane? Should I use some other approach that doesn't involve multiplying each fragment coordinate with the inverse MVP matrix?

# Answer
> 1 votes
If you want things to be simple, another approach would be to set the clear color to the sky color at the beginning of your render pipeline. Then render a square with the soil color. It will be more efficient than the technique you are exploring.

Otherwise, I would recommend you to use a cubemap for the sky. Performance will still be good and you'll have the possibility to rotate the sky view along with the camera.

Hope it helps.

---
Tags: android, opengl-es2
---


# Question
Title: Cannot get mask with multiple textures to work
I am trying to render three textures: Background, Black/White Foreground Mask and Foreground.

I have used this OpenGL - mask with multiple textures, but I cannot get it to work. I only get the last rendered texture, in this case the Foreground Texture.

This is my code:

```
#include <GL/glew.h>
#include <GL/glfw.h>
#include <IL/il.h>
#include <IL/ilut.h>
#include <stdio.h>
#include <cstring>
#include <stdlib.h>

void DibujaCuadro(GLuint idtextura);

int main(){
    bool running = true;

    ilInit();
    glfwInit();

    if(!glfwOpenWindow(640,480,8,8,8,8,8,8,GLFW_WINDOW) ){
        glfwTerminate();
        return 0;
    }

    glfwSetWindowTitle("GLFW Application");
    glewInit();

    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glOrtho(0,640,0,480,-1,1);

    glMatrixMode(GL_MODELVIEW);
    glClearColor(0.0,0.0,0.5,1.0);

    ILuint idimg;
    ilGenImages(1,&idimg);
    ilBindImage(idimg);
    ILboolean imagen;
    ILint ilbpp;
    ILint ilancho;
    ILint ilalto;
    ILint ilformato;
    ILubyte *ildata;

    imagen = ilLoadImage("graficos/cfondo.png");

    if(imagen){
      imagen = ilConvertImage(IL_RGBA,IL_UNSIGNED_BYTE);
      if(!imagen)return GL_FALSE;
    }
    else return GL_FALSE;

    ilbpp     = ilGetInteger(IL_IMAGE_BPP);
    ilancho   = ilGetInteger(IL_IMAGE_WIDTH);
    ilalto    = ilGetInteger(IL_IMAGE_HEIGHT);
    ilformato = ilGetInteger(IL_IMAGE_FORMAT);
    ildata    = ilGetData();

    GLuint textura[3];

    glGenTextures(1,&textura[0]);
    glBindTexture(GL_TEXTURE_2D,textura[0]);
    glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
    glTexEnvf(GL_TEXTURE_ENV,GL_TEXTURE_ENV_MODE,GL_MODULATE);
    glTexImage2D(GL_TEXTURE_2D,0,ilbpp,ilancho,ilalto,0,ilformato,GL_UNSIGNED_BYTE,ildata);

    imagen = ilLoadImage("graficos/mascara.png");

    if(imagen){
      imagen = ilConvertImage(IL_RGBA,IL_UNSIGNED_BYTE);
      if(!imagen)return GL_FALSE;
    }
    else return GL_FALSE;

    ilbpp     = ilGetInteger(IL_IMAGE_BPP);
    ilancho   = ilGetInteger(IL_IMAGE_WIDTH);
    ilalto    = ilGetInteger(IL_IMAGE_HEIGHT);
    ilformato = ilGetInteger(IL_IMAGE_FORMAT);
    ildata    = ilGetData();

    glGenTextures(1,&textura[1]);
    glBindTexture(GL_TEXTURE_2D,textura[1]);
    glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
    glTexEnvf(GL_TEXTURE_ENV,GL_TEXTURE_ENV_MODE,GL_MODULATE);
    glTexImage2D(GL_TEXTURE_2D,0,ilbpp,ilancho,ilalto,0,ilformato,GL_UNSIGNED_BYTE,ildata);

    imagen = ilLoadImage("graficos/cfrente.png");

    if(imagen){
      imagen = ilConvertImage(IL_RGBA,IL_UNSIGNED_BYTE);
      if(!imagen)return GL_FALSE;
    }
    else return GL_FALSE;

    ilbpp     = ilGetInteger(IL_IMAGE_BPP);
    ilancho   = ilGetInteger(IL_IMAGE_WIDTH);
    ilalto    = ilGetInteger(IL_IMAGE_HEIGHT);
    ilformato = ilGetInteger(IL_IMAGE_FORMAT);
    ildata    = ilGetData();

    glGenTextures(1,&textura[2]);
    glBindTexture(GL_TEXTURE_2D,textura[2]);
    glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
    glTexEnvf(GL_TEXTURE_ENV,GL_TEXTURE_ENV_MODE,GL_MODULATE);
    glTexImage2D(GL_TEXTURE_2D,0,ilbpp,ilancho,ilalto,0,ilformato,GL_UNSIGNED_BYTE,ildata);

    while(running){
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        glEnable(GL_BLEND);

        glBlendFunc(GL_ONE,GL_ZERO);
        DibujaCuadro(textura[0]); //Background

        glBlendFuncSeparate(GL_ZERO,GL_ONE,GL_SRC_COLOR,GL_ZERO);
        DibujaCuadro(textura[1]); //Mask

        glBlendFunc(GL_DST_ALPHA,GL_ONE_MINUS_DST_ALPHA);
        DibujaCuadro(textura[2]); //Foreground

        glDisable(GL_BLEND);

        glfwSwapBuffers();

        running = !glfwGetKey(GLFW_KEY_ESC) && glfwGetWindowParam( GLFW_OPENED);
    }

    glDeleteTextures(1,&textura[0]);
    glDeleteTextures(1,&textura[1]);
    glDeleteTextures(1,&textura[2]);

    glfwTerminate();

    return 0;
}

void DibujaCuadro(GLuint idtextura){
  glLoadIdentity();
  glEnable(GL_TEXTURE_2D);
  glBindTexture(GL_TEXTURE_2D,idtextura);
  glBegin( GL_QUADS );
    glTexCoord2f(0.0,0.0);
    glVertex2f(-180.0f,110.0f);
    glTexCoord2f(0.0,1.0);
    glVertex2f(-180.0f,  0.0f);
    glTexCoord2f(1.0,1.0);
    glVertex2f( 820.0f,  0.0f);
    glTexCoord2f(1.0,0.0);
    glVertex2f( 820.0f,110.0f);
  glEnd();
  glDisable(GL_TEXTURE_2D);
}

```

Can anyone see what am I doing wrong?

Textures:

Background

Mask

Foreground

This is what I want to get.

# Answer
> 2 votes
It seems that your mask texture is alpha 1.0 everywhere. In order for this to work, your mask should have alpha set 1.0 for "HOLA" and alpha set to zero everywhere else.

Hope it helps!

# Answer
> 0 votes
On some graphic systems the window's back buffer has no alpha component. You should verify that it does have alpha bits by calling `GLint alpha_bits=0; glGetIntegerv(GL_ALPHA_BITS, &alpha_bits);` and check the value in alpha\_bits after the call.

If that is the case you will have to render to a frame buffer object (FBO) then copy this to the window's back buffer before calling `glfwSwapBuffers()`.

---
Tags: opengl, blending, glfw, masking
---


title: How to zoom and scroll in libGdx?

text:
# Question
Title: How to zoom and scroll in libGdx?
I am trying to both A.) Pinch zoom my game scene and B.) Move (scroll) my game scene but I have not found many examples. I learn more by examples than by reading API documentation (although I am willing to resort to that if there is no other way) and the lack of examples has put a damper on my game.

**How do I do these things?**

**A little background:**

I am developing a RPG for Android and one of the features in my game is the ability to purchase a game map for money that let's users see the location of enemies in the level and all of the obstacles. Since most Android devices are quite small 3.5" to 5" I thought it would be a good idea to let the user zoom into the map and then scroll around. I have omitted most of my game code.

**Relevant code**

I have

```
 //Irrelevant code omitted for clarity and in accordance with the help center
    public class MyGdxGame implements ApplicationListener
    {
Texture mapTexture;
SpriteBatch batch;

@Override
public void create(){
    mapTexture = new Texture(Gdx.files.internal("map.png"));
    batch = new SpriteBatch();
}

@Override
public void render(){
    Gdx.gl.glClearColor(1, 1, 1, 1);
    Gdx.glClear(GL20_GL_COLOR_BUFFER_BIT);
    batch.begin();
    batch.draw(0 , 0, Gdx.graphics.getWidth, Gdx.graphics.getHeight());
    batch.end();
}

@Override
public void dispose(){
}

//I want to zoom in to the map here
@Override
public void resize(int width, int height){
}

@Override
public void pause(){
}

@Override
public void resume(){
    }
}

```

# Answer
Here is the code that I used in my strategy game for zoom,pinch etc..

For handling the camera and setting the screen resolution based on the aspect ratio we have:

```
aspectRatio = (float)Gdx.graphics.getHeight() / (float)Gdx.graphics.getWidth();
height = width * aspectRatio;
camera = new OrthographicCamera(width,height);

camera.position.set(width / 2, height / 2, 0);
camera.viewportWidth = width / 2;
camera.viewportHeight = height / 2;
camera.update();

```

`handleInput()` function calls all the input events on keyboard and process them rest of inputs like pinch and zoom will be handled by implementation GestureDetector

To clamp the camera with in bounds we have:

```
 camera.position.x = MathUtils.clamp( camera.position.x, effectiveViewportWidth / 2f, width - effectiveViewportWidth / 2f);
 camera.position.y = MathUtils.clamp(camera.position.y, effectiveViewportHeight / 2f, height- effectiveViewportHeight / 2f);

```

---

```
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.input.GestureDetector;
import com.badlogic.gdx.input.GestureDetector.GestureListener;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.math.Vector3;

public class ScreenExample implements Screen, GestureListener {
    private SpriteBatch batch;
    private Texture texture;
    public OrthographicCamera camera;
    float elapsedTime = 0;
    float zoomFactor = (float) 0;
    Vector3 touchPosition;
    float width = 800, height, aspectRatio;

    public ScreenExample() {
        aspectRatio = (float) Gdx.graphics.getHeight() / (float) Gdx.graphics.getWidth();
        height = width * aspectRatio;
        camera = new OrthographicCamera(width, height);
        camera.position.set(width / 2, height / 2, 0);
        camera.viewportWidth = width / 2;
        camera.viewportHeight = height / 2;
        camera.update();

        texture = new Texture(Gdx.files.internal("background.png"));

    }

    @Override
    public void show() {

        camera.zoom = 2;

        touchPosition = new Vector3();

        Gdx.input.setInputProcessor(new GestureDetector(this));

    }

    @Override
    public void render(float delta) {
        handleInput();
        camera.update();

        Gdx.gl.glClearColor(0, 0, 0, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

        batch.setProjectionMatrix(camera.combined);

        batch.begin();
        batch.draw(texture, 0, 0, width, height);

        batch.end();

    }

    public void dispose() {
        batch.dispose();
        texture.dispose();
    }

    @Override
    public void resize(int width, int height) {

    }

    @Override
    public void pause() {

    }

    @Override
    public void resume() {

    }

    @Override
    public boolean touchDown(float x, float y, int pointer, int button) {
// TODO Auto-generated method stub
        touchPosition.set(x, y, 0);
        camera.unproject(touchPosition);

        return false;
    }

    @Override
    public boolean tap(float x, float y, int count, int button) {
// TODO Auto-generated method stub
        return false;
    }

    @Override
    public boolean longPress(float x, float y) {
// TODO Auto-generated method stub
        return false;
    }

    @Override
    public boolean fling(float velocityX, float velocityY, int button) {
// TODO Auto-generated method stub
        return false;
    }

    @Override
    public boolean pan(float x, float y, float deltaX, float deltaY) {
        // TODO Auto-generated method stub

        camera.translate(-deltaX, deltaY);

        return false;
    }

    private void handleInput() {
        if (Gdx.input.isKeyPressed(Input.Keys.A)) {
            camera.zoom += 0.02;
        }
        if (Gdx.input.isKeyPressed(Input.Keys.Q)) {
            camera.zoom -= 0.02;
        }
        if (Gdx.input.isKeyPressed(Input.Keys.LEFT)) {
            camera.translate(-3, 0, 0);
        }
        if (Gdx.input.isKeyPressed(Input.Keys.RIGHT)) {
            camera.translate(3, 0, 0);
        }
        if (Gdx.input.isKeyPressed(Input.Keys.DOWN)) {
            camera.translate(0, -3, 0);
        }
        if (Gdx.input.isKeyPressed(Input.Keys.UP)) {
            camera.translate(0, 3, 0);
        }
        int rotationSpeed = 1;
        if (Gdx.input.isKeyPressed(Input.Keys.W)) {
            camera.rotate(-rotationSpeed, 0, 0, 1);
        }
        if (Gdx.input.isKeyPressed(Input.Keys.E)) {
            camera.rotate(rotationSpeed, 0, 0, 1);
        }

        camera.zoom = MathUtils.clamp(camera.zoom, 1.5f, 1.8f);

        float effectiveViewportWidth = camera.viewportWidth * camera.zoom;
        float effectiveViewportHeight = camera.viewportHeight * camera.zoom;

        camera.position.x = MathUtils.clamp(camera.position.x, effectiveViewportWidth / 2f, width - effectiveViewportWidth / 2f);
        camera.position.y = MathUtils.clamp(camera.position.y, effectiveViewportHeight / 2f, height - effectiveViewportHeight / 2f);
    }

    @Override
    public boolean zoom(float initialDistance, float distance) {

        if (initialDistance >= distance) {
            camera.zoom += 0.02;
        } else {
            camera.zoom -= 0.02;
        }

        return false;
    }

    @Override
    public boolean pinch(Vector2 initialPointer1, Vector2 initialPointer2,
                         Vector2 pointer1, Vector2 pointer2) {

// TODO Auto-generated method stub
        return false;
    }

    @Override
    public boolean panStop(float x, float y, int pointer, int button) {
        // TODO Auto-generated method stub
        return false;
    }

    public void hide() {
        // TODO Auto-generated method stub

    }

```
> 1 votes

---
Tags: java, android, libgdx
---


title: Java Move towards point

text:
# Question
Title: Java Move towards point
Ive made this 'game' where you can fire an aibility (a fire ball for instance) from the player towards the mouse (to the point where the mouse was at the time of casting/fireing/shooting the ball), now Id like to know how I could implement it so that if it reaches its destination that it stops, and also how I could make it travel in the direction of the mouse but for a ciurtant distance only.

Here's the code for the fire ball thing:

```
life += 0.05f;
float dx = (mx - x);
float dy = ((Launcher.GAME_HEIGHT - my) - y);

double direct = Math.atan2(dy, dx);

xv = (float) (spd * Math.cos(direct));
yv = (float) (spd * Math.sin(direct));

x += xv;
y += yv;

```

Note: *xv* and *yv* are **velocities**, and *mx* and *my* are the **mouse x and y**

# Answer
> 1 votes
If your projectile has a consistent velocity throughout, here is how to make it stop exactly on the target when it reaches the target:

First measure the distance between the starting point of the projectile and the target.

```
float len = (float) Math.sqrt(Math.pow(dx-tx,2)+Math.pow(dy-ty,2));

```

Where `tx` and `ty` represent the position of the target.

You'll also need to keep track of the distance travelled, so just make a variable like `float t = 0`.

Then, whenever you update the position of the projectile, you'll need to add its `spd` value to `t`. When `t` exceeds `len`, you know the projectile must have gone through the target point.

```
void update(){

    projectileX += xv;
    projectileY += yv;

    t += spd;
    if (t >= len){

        // make the projectile stop moving.
        xv = 0;
        yv = 0;

        // since the projectile probably went
        // a little bit past the target, we
        // will have to "snap" the projectile
        // to the position of the target.
        projectileX = tx;
        projectileY = ty;

    }

}

```

---
Tags: java, slick
---


# Question
Title: I want to make a racing game.Can I have licensed cars without paying for licenses?
My idea was something similar to rFactor, but very easy to mod. There will be a step by step tutorial.

If I or somebody from the developers make the mods and publish them, do I still need licensing? Now it's just an idea, but I plan to make at least 1000-1500 cars from at least 150 manufacturers, and that would cost a fortune. A lot of the cars would be converted from other games like Forza or GT6 and others modeled by my team.

# Answer
> 5 votes
Usual disclaimer: I am not a lawyer and in this site questions about these issues have to be always taken as ideas, thoughts or experiences, never as technical advice.

That said, yes, if you or somebody from the developer team wants to use the names of the cars, the names of the car companies or the models of the cars, a license will be needed. Otherwise, you risk having to face legal problems. Never forget that when sued, just the time and resources you will have to spend in the legal struggle will be harmful no matter the result. But even worse, at the end, without the licenses, you likely will loose all the work you and your team have put a lot of effort into preparing.

For the sake of detailing, keep in mind that car names and car manufacturer names are trademarked, while the assets representing the cars (i.e. the car models) are copyrighted. Trademarking and copyrighting are two different things: "Video Games and the law: Copyright, Trademark and Intellectual Property".

Lastly, of course if modders came up with car models, then that is not necessarily a legal problem for you. I mean not necessarily, because you have also to be careful of not endorsing mods that infringe copyrights or trademarks, in order to be sure that you are safe from legal problems. Although the mods are not your responsability, if your game's website for instance holds tons of mods that are considered to be illegal due to infringing copyrights/trademarks, I doubt it won't give you trouble.

# Answer
> 4 votes
**I am not a lawyer, for actual legal advise consult an actual lawyer**.

No, you can not have licensed cars without a license, and you probably won't be able to get one regardless. Car licenses are expensive, hard to come by and fraught with extra requirements (ever wonder why you generally won't get a Ferrari in a game with destructible cars?).

Releasing a mod for your game that adds actual cars is also probably not legal, regardless of whether they are for sale or not. Even if it *is* legal, you'll go bankrupt before proving that in court should it come to that.

If you want you can make cars that look vaguely similar and have different names, that's generally sufficient, but again. Not a lawyer, not legal advice.

# Answer
> 2 votes
The names of cars and car manufacturers are trademarked. Using a trademark without permission opens you up to lawsuits. If you want to use trademarks of car manufacturers, you should contact their marketing departments to negotiate a deal.

When you release the base game with no trademarked content and leave it to the modding community to do so, you shift the legal responsibility to the modders. They are violating the trademarks, not you, so they should be the ones getting sued. But be careful about hosting or even endorsing mods which violate trademarks, or you might also be targeted.

# Answer
> 1 votes
If it's legal or not doesn't matter. Some car manufacturers will sue you if you don't have an agreement with them (a license). Defending yourself against such lawsuits with less than half a million USD per suit can only be done if you settle out of court and pay them.

Various examples of licenses exist, but one example is Blur, which had a license from Audi at one point, but later on something fell through, that's why the game is no longer being sold. While we don't know what exactly went wrong, they preferred to stop selling the game instead of pursuing other options.

The second idea of yours is far more problematic. Taking models from other games without permission is very blunt intellectual property theft. Even if you just steal parts of the game, it's very close to taking a game without copy protection and selling it as your own, which means massive legal trouble.

The only way this could somewhat work is the Kim Dotcom/Mega way: Make sure 3rd parties provide the models on their own, make sure you have absolutely no ties to these 3rd parties, remove any models some manufacturer or publisher complains about, and provide an easy way for the 3rd parties to add them again. Even then, you need to make many millions of profit, because even if what you do might be technically legal, just like in the Dotcom/Mega case police might still raid your home regardless what the law says, and you'll need a few millions for attorney fees or land in jail.

---
Tags: legal, modding, licensing, racing
---


# Question
Title: ECS: performance of many systems cycling on entities
I have been working with an ECS for my current game and I noticed that I came up with quite a few systems that go over lists of entities that sometimes overlap, so it's not unlikely that I loop on the same entity more than once as more than one system is processing that same entity.

Wouldn'it it be better to just iterate once over all th entities that should be updated instead? And if so, how would you do that? Redesign the systems so that a single system is in charge of more stuff on the same entities? Move the code from systems to an update() method on the components? Or am I just worrying about something that isn't really going to have a big impact on performances compared to other bottlenecks that could arise from taking a different approach?

# Answer
> 1 votes
It may appear inefficient on the surface but the reason that subsets of entities are iterated in this fashion is to make use of caching mechanics which could actually yield faster results than if you attempted some other alternative.

I also find it important that having separate behaviors split into their own systems and managing their own list of entities allows those systems to change over time with minimal impact to other behaviors. Despite the performance concerns, it does make replacing or changing a system much easier and all the while adheres to Single Responsibility Principle and Separation of Concerns.

---
Tags: entity-system, component-based, entity-component
---


# Question
Title: Libgdx fix small objects on android devices
I'm having issues with optimizing my game for android. I've basically created a simple menu with two buttons (see pictures below)! The size of the window is 720x480px ( in the Desktop Launcher ). My Problem is now the following: On my PC everything looks fine, but when launching my game on an android device, everything is "zoomed out" too much! This is obviously caused by the resolution (1440 x 2560 pixels). My question is now: How do I "scale" the screen correctly, so that it look identical with the desktop version?

Desktop  Android

CODE: `http://pastebin.com/HtMfd4Jz`

# Answer
What you have do is make UI Buttons and Text resolutions dependent on screen in which your game is running,Instead of entering fixed values like

```
button.height=100;
button.width=50;

```

Instead Give value like this.

```
button.height=Gdx.graphics.getheight()/4;
button.width=Gdx.graphics.getwidth()/8;

```

if you follow the above code you can run your game in any device the buttons will look the same with out zooming in or zooming out.

Here is a small code example with a single button,I am using scene2d for setting stage and adding actor button

* Create a class start that extends the Game class and call setScreen function to set screen to main menu
* MainMenu Class implements screen.It have stage that contains buttons that also have on/off state ,An input listener is added to button to handle touch inputs

> You can find button.pack and new.fnt files from here

**Start Class**

```
public class Start extends Game{
    public OrthographicCamera camera;
    public SpriteBatch batch;
    public BitmapFont font;

    @Override
    public void create() {

        camera=new OrthographicCamera(Constants.width,Constants.width*Constants.aspectRatio);
        batch=new SpriteBatch();

        setScreen(new MainMenu(this));

    }

}

```

**MainMenu Class**

```
public class MainMenu implements Screen{
    Start game;
     private Stage stage; //** stage holds the Button **//
        private BitmapFont font;
        private TextureAtlas buttonsAtlas; //** image of buttons **//
        private Skin buttonSkin; //** images are used as skins of the button **//
        private TextButton button;

public MainMenu(Start game)
{
    this.game=game;

}

    @Override
    public void show() {

    buttonsAtlas = new TextureAtlas("img/button/button.pack"); //**button atlas image **//
    buttonSkin = new Skin();
    buttonSkin.addRegions(buttonsAtlas); //** skins for on and off **//
    font = new BitmapFont(Gdx.files.internal("font/new.fnt"),false); //** font **//

    stage = new Stage();        //** window is stage **//
    stage.clear();
    Gdx.input.setInputProcessor(stage); //** stage is responsive **//

    TextButtonStyle style = new TextButtonStyle(); //** Button properties **//
    style.up = buttonSkin.getDrawable("buttonOff");
    style.down = buttonSkin.getDrawable("buttonOn");

    style.font = font;

    button = new TextButton("START", style);
    //** Button text and style **//
    button.setHeight(Gdx.graphics.getHeight()/3); //** Button Height **//
    button.setWidth(Gdx.graphics.getWidth()/4); //** Button Width **//

    button.setPosition(Gdx.graphics.getWidth()/2-button.getWidth()/2, Gdx.graphics.getHeight());

    button.addListener(new InputListener() {
        public boolean touchDown (InputEvent event, float x, float y, int pointer, int button) {
                Gdx.app.log("my app", "Pressed"); //** Usually used to start Game, etc. **//

                // TODO Auto-generated method stub

                return true;

        }

        public void touchUp (InputEvent event, float x, float y, int pointer, int button) {
                Gdx.app.log("my app", "Rggggggeleased");

          ///and level
                game.setScreen(new MyNextScreen(game));

                dispose();

        }
    });

    MoveToAction moveAction = new MoveToAction();//Add dynamic movement effects to button
    moveAction.setPosition(Gdx.graphics.getWidth()/2-button.getWidth()/2, Gdx.graphics.getHeight()/2+ Gdx.graphics.getHeight()/6);
    moveAction.setDuration(.5f);
    button.addAction(moveAction);

    stage.addActor(button);

}
@Override
public void render(float delta) {
    // TODO Auto-generated method stub
     Gdx.gl.glClearColor(1, 1, 1, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
        stage.act();
     game.batch.begin();
        stage.draw();
       game.batch.end();

}

@Override
public void resize(int width, int height) {
    // TODO Auto-generated method stub

}

@Override
public void pause() {
    // TODO Auto-generated method stub

}

@Override
public void resume() {
    // TODO Auto-generated method stub

}

@Override
public void hide() {
    // TODO Auto-generated method stub

}

@Override
public void dispose() {
    // TODO Auto-generated method stub

}

```

}
> 0 votes

---
Tags: android, libgdx, scale
---


# Question
Title: The best way to pass data between clients in a room
I am developing a backgammon game in Unity and tried to use Photon. But I could not find a step by step help for it and I also know that photon in real-time and it syncs data over 10 times per second. but I need to sync data after each moves.

Would you please show me the best way to do that.

# Answer
Take a look at Photon Turnbased instead of Photon Realtime. They have a step by step guide as well.

**Photon**

> Photon Turnbased offers everything that Realtime has but is geared towards games with less interaction between players (turnbased or not) and games that can be paused and picked up later on (asynchronously). It makes more use of Webhooks (e.g. to store a room's state) and WebRPCs.

Turnbased Intro: https://doc.photonengine.com/en/turnbased/current/getting-started/turnbased-intro

**Parse**

> The Parse platform provides a complete backend solution for your mobile application. Our goal is to totally eliminate the need for writing server code or maintaining servers.

Unity Guide: https://parse.com/docs/unity/guide
> 1 votes

---
Tags: unity, unity-networking
---


title: 3D Planetary gravity

text:
# Question
Title: 3D Planetary gravity
so i am making a thing in javascript and i want to have planetary gravity in my "universe".

But when i use an equation to calculate the acceleration by gravity i get **one number**. That is how fast the object accelerates in the direction of the other object, but how do i **convert a speed in one direction to a speed in the X**, **Y** and **Z** axis?

# Answer
> 1 votes
Gravity is additive. Calculate the gravity generated by planet A at point x. Then multiply by a unit vector pointing from x to A - that returns a vector, which gives the gravity a direction. Repeat for planet B, C, etc, then add the vectors.

Velocity is acceleration times time. Every frame, multiply the acceleration vector by the delta time, and add the result to the velocity vector. You can access x, y and z of the velocity vector directly.

A vector simply stores the x, y, and z components independently. A unit vector is a vector of length one - you make a unit vector by taking your vector and dividing each component by it's length, the length is `length = sqrt(x*x+y*y+z*z)`. You add vectors by adding the components independently. You multiply a vector by a constant like gravity by multiplying it's components independently.

---
Tags: physics, javascript, grid, axis
---


# Question
Title: Can I legally call ninja techniques "jutsus" in a game?
I'm making a game inspired by the anime *Naruto* and I want to use the word *jutsu*, used in the anime to mean ninja techniques. Can I do that?

Does the answer change if I change the techniques' specific names, but use the same concept of the hand seals?

# Answer
> 12 votes
The word "jutsu" is simply a Japanese word for "technique." The idea of ninja jutsus is very common in anime and manga, and definitely predates Naruto. As long as you aren't using a jutsu name copied directly from Naruto, you should be fine (and even some of the names are likely to be public domain, as they are mentioned in Japanese ninja folklore).

For example, the body substitution technique, "kawari no jutsu" pops up frequently in a wide variety of anime and manga whenever ninjas are mentioned. Similarly, I can probably name 5 or 6 animes that use the shadow-clone technique, "kagebunshin no jutsu."

# Answer
> -5 votes
Jutsu means technique so u can use it ..

---
Tags: legal
---


title: How to implement a job queue system?

text:
# Question
Title: How to implement a job queue system?
Essentially I'm trying to make a system which you can add a job to it then finds an AI which is idle and gives it that job to do, For an example look at Prison Architects job list system (image below).

I need to be able to add a job, removed them and look at all the jobs. The next job that this returns should be the oldest one in the list.

Initially I thought of using a queue as it already provides adding and removing but as it turns out I can only see the next item in that list (well at least thats the case with the standard C# implementation of it), meaning that if there is a certain requirement which isn't met I can't skip to the next task.

Is there a version of the queue that exposes all the items within the list or some other way of doing something similar? This will be coded in C# if that makes difference to the options available.

# Answer
The job queue system in Prison Architect is actually far more complex than a pure first-in-first-out queue. Actors prioritize their jobs:

* They only take jobs they are actually qualified for (example: any staff member can perform the "open staff door" job, but only guards can do the "open jail door" job)
* In many cases they prioritize jobs given by the player over jobs generated automatically
* They often prioritize jobs which are nearby over those which require some walking
* In other situations they prioritize the jobs which were generated first. It seems like distance and age are somehow valued against each other.
* Some jobs immediately spring to the front. For example, guards will stop doing what they do when they witness a prisoner misbehaving.

I could imagine that the developers started out with a simple FIFO queue for their job system, but then realized that it is far too inflexible to allow actors to behave as efficiently as the player would expect it. I would recommend you to just store all jobs unsorted in an `ArrayList` or similar unsorted data-structure. When an actor needs a new job, it iterates that whole datastructure and uses a rating function to assign an *own* priority rating to each job and pick the job with the highest score *for itself*.
> 5 votes

# Answer
If you're going to be adding and removing tasks dynamically, and they may have differing times, then you may want to look at a C# implementation of a Priority Queue.

It's a pretty basic data structure and implementations will be easy to find based on trees (usually red-black) or heaps.

Access to the next available is O(1) and insertions in most implementations will be O(log n) which is pretty fast indeed.
> 1 votes

# Answer
Use a `List<T>` instead. See How to add item to the beginning of `List<T>` for adding to front.

Not the most efficient but the Job Queue won't be the bottleneck in your game.

Alternatively, you can use a `LinkedList<T>` and wrap it in your own `JobQueue` class, here's a post showing how: Is there a better way to implement a remove method for a queue. This option is less cache performant but you can add/remove anywhere in the list.
> 0 votes

---
Tags: c#, ai
---


# Question
Title: Will SDL_DestroyRenderer() destroy every texture created with it?
The documentation on the SDL wiki states:

> Use this function to destroy the rendering context for a window and **free associated textures**

So does this mean that **every** texture I create will be freed (even those still used) or **only the ones that were destroyed manually** (by using `SDL_DestroyTexture()`)?

# Answer
> 7 votes
It means that all existing textures are freed. I checked the SDL source and inside the `SDL_DestroyRenderer` function they do this:

```
while (renderer->textures) {
    SDL_DestroyTexture(renderer->textures);
}

```

So **every** texture that was created with the renderer gets destroyed.

---
Tags: sdl2
---


# Question
Title: Code Logic's execution with respect to time Events
I have to show complete **24 hours cycle** in Unity3d Scene. **Where different kind of task will be executed in different Times.**

Suppose

* at 2pm I have to move a car,
* at 6pm An Aeroplane will land on airport
* at 07:07pm I have to open the door of Market's Buildings
* and so on different task/works execution at different timing.

Now, I have some basic animation e.g., car, Aeroplane and door etc.,. Now I am confuse that how to play and stop **my animation according to the time**. And time can also be changed manually using GUI. If currently 6pm (animation working) then user can switch to 8am to view 8am time's animation (or code execution). And **User can also fast the timing to view complete hours in a single minutes or in an hour**.

I can use **if/else** in **Update Events** but I guess this is not the **right way** to do and will be **very difficult** if I require to show significant number of works in different time duration (which means significant number of if/else statements). Just like below

```
void Update(){
if(time =1){
//logic
}
if(time =2){
//logic
}
if(time =3){
//logic
}
...//so on, tedious way
...//and also not possible if time require between the hours, suppose 06:06pm
}

```

What to do ? How to handle this?

# Answer
The way I'd approach this is to create a MonoBehaviour representing a daily event. We'd attach an instance to each object that needs to do something at a particular time.

This DailyEvent behaviour would expose to the Inspector:

* a start time
* an end time or duration (can be read implicitly from the animation, if using)
* some type of payload, like an animation to trigger or an event/message to send

You might have a few subclasses to specialize eg. DailyAnimationEvent vs DailyToggleEvent, or just handle them all in one class - that's up to your coding style.

Then I'd have a master DailyClock script that handles time of day. On startup, this script would find all DailyEvent instances in the scene and add them to an efficient lookup structure like an Interval Tree.

When the time changes, the DailyClock script is responsible for finding all DailyEvent intervals in its lookup structure overlapping the current moment, and telling them to trigger or update their animation playhead position. It also needs to find all formerly active DailyEvent intervals and deactivate them, for when the time seeks outside of a DailyEvent's interval.

Now all of the logic about when to trigger certain events lives in your data, rather than a big nest of if statements in code. This makes it easier to scale to bigger & smaller scenes, since you can reuse the same code with different scene objects.

This also keeps the timing information attached to the object that needs it, so you don't need to jump around your scene when editing the plane landing - the plane object has it all in one place - and if you delete an object its timing logic goes with it, rather than hanging around as unused cruft.
> 1 votes

# Answer
You could use `Time.timeScale` and your own time provider/clock to achieve this. You will need to store the animations in a list to be able to know their start time and also create the animations with descent play speed in mind. Update your clock according to your current play speed in your game loop. If the user steps in time just loop through the list of animations and set the animations normalized time if your clock is changed to a time where the animation should play. Use TimeScale to change playback speed or create your own time provider and control the animation playback yourself.

```
// pseudo code
void SetTime(float clock) {
    for each anim in anims {
        If(clock >= anim.start && clock < anim.end) {
            anim.normalizedTime = clock/anim.end;
            anim.Play();
        } else {
            anim.Stop();
        }
    }
}

```

http://docs.unity3d.com/ScriptReference/Time-timeScale.html
> 0 votes

---
Tags: unity, animation, events
---


# Question
Title: Unity 3D error when compiling to WebGL: Destination directory not found
When I try to compile my Unity project to WebGL in Development mode on Windows 8.1 (and with the latest version of Unity), I receive the following errors (the first one is truncated because it's really long; I can post it upon request).

> **`DirectoryNotFoundException`**: Destination directory not found: `Temp/StagingArea/Data/Resources`
> `System.IO.File.Copy` (`System.String sourceFileName`, `System.String destFileName`, Boolean overwrite)...
>
> Error building Player: **`DirectoryNotFoundException`**: Destination directory not found: `Temp/StagingArea/Data/Resources`

There's no output; the directory I'm attempting to build my project in is empty. A forum post somewhere suggested I run Unity in Administrator mode, but if that had worked I wouldn't be posting here for help.

# Answer
First of all make sure you can make a WebGL build with your currently installed Unity version. Create a new project with a new scene, add it to the build settings and make a WebGL build. If this does not work the problem is not project specific.

If it works try one of these possible solutions.

**Possible solution 1:**

> 1. Check your WebGL Build Settings
> 2. Make a fresh build (unique folder)

**Possible solution 2:**

> 1. BACKUP your project
> 2. Close Unity
> 3. Delete the folders -\> Library, Temp in the root of the project directory to force Unity to rebuild them on next launch.
> 4. BUILD

**Possible solution 3:**

> 1. Create a new Unity Project
> 2. Copy **OldProject/Assets** to **NewPoject/Assets**
> 3. Copy **OldProject/ProjectSettings** to **NewProject/ProjectSettings**
> 4. BUILD
> 2 votes

---
Tags: unity, webgl, bug, build-process
---


# Question
Title: Why does transform.forward appear to be void?
I have the following line of code from a project I'm working on:

```
this.transform.position += (keyMapping.Value * this.movementSpeed).Scale(this.transform.forward);

```

At a first glance, this line of code looks like it should work, yet, I get the following error when I try to run it:

```
error CS0019: Operator `+=' cannot be applied to operands of type `UnityEngine.Vector3' and `void'.

```

I'm stumped as to what might be causing this. How do I fix this?

# Answer
`Vector3.Scale` with one parameter input does not return a value so you will need to apply Scale as a separate step.

```
var movement = (keyMapping.Value * this.movementSpeed);
    movement.Scale(this.transform.forward);
transform.position += movement;

```

http://docs.unity3d.com/ScriptReference/Vector3.Scale.html
> 4 votes

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


# Question
Title: Storing player data for multiple players in libGDX
I'm working on a game (in libGDX) that would allow multiple player accounts. I need to store some simple user data (several key-value pairs). I think JSON is the best for my needs, but I'm wondering how this data should be organised. I'm thinking about two possibilities:

* single file for each player seems better design-wise, but I'm not sure if real-time file creation won't lead to issues
* one big file with player id as key and organised array of values - safer, but would require loading data for all players on initial read and each update (although there shouldn't be that many accounts on a single game instance). Also harder to maintain due to necessity of keeping values in proper order, etc.

Perhaps there are better ways to do it, that I didn't think about.

# Answer
> 1 votes
Storing all player profiles in a single file wouldn't be such a bad idea if it didn't mean you'd have to rewrite the file every time data was modified, even if just for a single profile. Having profiles stored in their own files, and perhaps in a player folder, would be a better option.

Here's some possible steps one could take to manage profile data:

1. Load all profiles when the profile selection screen is active.
2. Save the profile the player is playing on when they quit the game (or return to the main menu / profile selection screen).
3. Create a repeating task to perform step 2 perhaps every minute. The interval depends on your game and your design choices.
4. Create auto-save events that repeat step 2. Again, this depends on your game.
5. Save all profiles when the game exits.

File architecture if you want to support multiple players with multiple profiles:

```
Players
|-- Player 1
|   |-- Profile 1
|   |-- Profile 2
|   +-- Profile 3
+-- Player 2
    |-- Profile 1
    |-- Profile 2
    +-- Profile 3

```

---
Tags: libgdx, architecture
---


# Question
Title: MonoGame - Ordering Movement Key Presses
I'm looking for a way to retrieve the last key pressed even when other keys might be pressed for a top-down four-directional game. For example:

* `W` is pressed → Move up
* `D` is pressed → Move right
* `S` is pressed → Move down

The above I can get to work fine using a stack. When `S` is released, then we start moving right again, and when `D` is released, we go back to moving up. The issue arises when trying to release *(say `W`)* and then pressing `W` again to move up before `S` and `D` are released.

I've tried using arrays and lists to solve this problem (to use flags or remove a key from any point in the collection), but it results in whatever key is last in the if statements to check for the movement keys being given the priority.

Any help is greatly appreciated. If there's anything else I could provide please let me know.

**Edit - a more detailed example:**

* Player is currently standing still.
* User presses `W` to move the player up. This key is stored as the current movement key on a stack and as long as the key is pressed (checking per frame), the player will continue to move up.
* User presses `D` to move the player right. The `D` key is stored as the current movement key on the same stack `W` was stored on. `W` is not the current movement key anymore.
* User releases the `W` key - since this is stored on a stack, we know `W` was released but we cannot remove it from the stack (but we do know it is on the stack). I do not want to just keep adding the keys to the stack, thus the reason we check if the stack contains the key.
* User presses the `W` key again. Since `D` is still the current movement key, and since we weren't able to remove `W` from the stack, we cannot add it to the stack again.

# Answer
I'm not sure why but for some reason a solution I tried early on is working as I wanted it to now.

The implementation's psuedo-code is as follows:

```
// Initialize a list for movement keys and add the first element to be "No Key".
// For MonoGame, this is Keys.None.

/* In the update loop */
Check current keyboard state.
If (W key is pressed and the movement key list doesn't contain W)
    Add W to the list of movement keys.

// Repeat above for S, D, and A

If (W key is released and the movement key list contains W)
    Remove W from the list of movement keys.

// Repeat above for S, D, and A.

```

To get the current movement key, I just check movementKeyList\[movementKeyList.Count - 1\].

Incredibly simple and stupid and I'm a bit agitated that I missed something before to cause me this much trouble, but 'tis the life of programming. Thank you all who helped!
> 0 votes

# Answer
You want to know if the pressed keys have changed. If no new keys have been pressed or released you don't need to update the direction.

You could implement this:

1. Use a bitmask for the directions 1=up, 2=down, 4=left and 8=right. If the sum of the keys pressed is different than the sum you stored in the last frame, some logic needs to happen.
2. Now, clear the list of directions. Add directions to the list.
3. If the list is empty, the movement stops.
4. If the list contains only one element it can mean two things:

1. The player changes direction or
    2. The current direction is the only direction pressed.
5. If more than one element is in the list, remove the current direction (if that one is in the list).
6. The first in the list is the new direction.
7. We keep that direction until our 'change' is triggered because the bitvalue changed.

Now this is how it should work. Our bitvalue is 0. The player stands still.

The user presses `W` the bitvalue becomes 1, which is different from 0. We create a list thats contains only {`W`}. This becomes our new player direction. We store the bitvalue 1.

For a couple of frames the key pressed is `W` so the bitvalue of 1 is equal to the stored value. We keep going up.

The user now presses `W` and `D`. The bitvalue is 9 which is different than our stored 1. The list contains {`D`,`W`}. It is more than one element, so we remove the current direction `W`. The new direction is the first element in the list: `D` we also store value 9.

The bitvalue stays 9 for a couple of frames.

The user now releases `W`. The bitvalue is 8 which is different from 9. The only key pressed is `D` so we continue that direction. 8 is stored.

The user releases all keys. The bitvalue is 0 which is different from 8. The list is empty and the player stops. 0 is stored.

(Sorry no code example, I'm writing this on an ipad, typing code is a pita on the onscreen keyboard...)
> 1 votes

# Answer
If you are looking for the last key pressed, make four booleans and very simply change any boolean(based on what key is pressed) to true and rest to false. This way you can add a method for handling the booleans and then do the action. To do it after you released the new key pressed, you have to check that the keys arent pressed(dont know how to do that in C#). Also add two sets of four booleans one for what just got pressed(e.g. W) and what got pressed BEFORE you pressed W(e.g. D)
> 0 votes

---
Tags: c#, 2d, monogame, input
---


# Question
Title: Sending message to all players in room from Photon server?
I need to send a message to all players in the room from a Photon server. Sending the message from a player would introduce too much latency so I need the server to collect data and distribute messages at a rate of 16/s without a player's influence. Is there a way to do this?

# Answer
> 2 votes
```
if (PhotonNetwork.isMasterClient)
    photonView.RPC ("SendMessageRPC", PhotonTargets.All, "Hello there!");

[PunRPC]
void SendMessage (string message) {
    chatBox.AddMessage (message);
}

```

The above is basically how to send a message, with you needing to impliment a `GUI` or `UI` for a `chatBox` and a script that has a `public void` function that is called `AddMessage`, which adds the `string message` onto the big string of all the messages.

I'm not sure if there is a way to guarantee the speed of delivery, as all the client's (and if you're using a server, also that) devices and network speed is not the same.

---
Tags: unity, networking, multiplayer, server, photon
---


# Question
Title: How do I snap the Unity camera to a 2D, tile-based map?
I have a 2D, tile-based map. I want to be able to control the number of visible tiles on the screen vertically and horizontally, regardless of resolution. I want the player to be able to move the camera one tile width at a time until it hits the edge.

I do not understand how to manipulate the Unity camera in order to accomplish this. I have read the documentation, and Googled, but there is just something that is not clicking for me.

So, let's say I have a 100x100 map. A 32x24 portion of the map is shown at a resolution of 1024x768, each tile has a size of 1x1 Unity unit. The bottom-left of the visible area of the map starts at the bottom-left of the map (0, 0). The player then clicks the right arrow key and the map moves one tile to the right (1, 0).

How do I accomplish this, given that I am using the latest version of Unity in 2D mode?

# Answer
> 3 votes
Taken from Reddit, where I also posted the question. Full credit to /u/EmeraldScales.

> First, change the Orthographic Camera Size to the number of tiles you'll want to have displayed vertically. Since each tile is 1 Unity unit, what you put there will translate to how many tiles are displayed. It will be easier if you put an odd number there. If you put an even number, you will have to add some sort of offset, or you'll be displaying the bottom half of your top tiles and the upper half of your bottom tiles.
>
> For the horizontal limit, if you wish one, you'll have to put a black bar covering the tiles outside the range you wish to display. That is because the horizontal size of the orthographic camera changes with screen resolutions, so it likely won't translate nicely to a rounded number of tiles. A 10x10 plane that covers all tiles say 15 units away from the center should be placed 15 + (10/2) = 20 units to the left and another the right. Stick it to the camera.
>
> With this, changing the camera's X and Y position in full increments of 1 when the player presses a button should translate the camera exactly one tile on the desired direction.

I opted to alter the viewport rectangle of the camera, instead of the black bar solution /u/EmeraldScales had. The code I wrote to do so only works properly when the desired on-screen map size sticks to the 4:3 ratio, otherwise it shows portions of neighboring tiles. It adjusts the viewport to a 4:3 ratio, even when the screen isn't.

```
function resizeCamera() {
    PrevWidth = Screen.width;
    PrevHeight = Screen.height;

    var screenRatio : float = PrevWidth / PrevHeight;
    var relativeWidth = HardcodedRatioWidth / PrevWidth;
    var relativeHeight = HardcodedRatioHeight / PrevHeight;

    if(screenRatio < HardcodedRatioWidth / HardcodedRatioHeight) {
        var hAdjustment = relativeHeight / relativeWidth;
        var yAdjustment = (1 - hAdjustment) / 2;
        thisCamera.rect = Rect(0, yAdjustment, 1, hAdjustment);
    } else {
        var wAdjustment =  relativeWidth / relativeHeight;
        var xAdjustment = (1 - wAdjustment) / 2;
        thisCamera.rect = Rect(xAdjustment, 0, wAdjustment, 1);
    }
}

```

---
Tags: unity, camera, unityscript
---


title: Unity web player API?

text:
# Question
Title: Unity web player API?
Just curious about it. I only want to know that what graphics API does the Unity web player uses. Is that WEBGL? Or simply OPENGL? Or A custom one? Then how do the games get gpu acceleration?

# Answer
> 1 votes
There's the Unity Web Player, which is enabled by a Browser-Plugin, similar to Flash. The Web Player supports almost all features of the Unity-Engine, with the exception of some Plugins and Filesystem access.

In addition to this, there's also the possibility to export the game to HTML5/WebGL. It's possible that some features of your game won't work in some browsers when choosing this mode (Browser compatibility matrix). The advantage of WebGL is, that it works without any Plugins (given your Browser supports the required web-technologies, such as WebGL and Web Audio).

As to what API the different implementations use: If you're using the Unity Web Player, the API will be determined by the Web Player Plugin. It will use OpenGL or DirectX, depending on Platform. WebGL is also an abstract wrapper for the graphics API… most commonly it will use OpenGL, but some browsers use DirectX on Windows (also see this question on stackoverflow).

---
Tags: unity, graphics
---


title: How to destroy object after animation

text:
# Question
Title: How to destroy object after animation
I've made an object and when the player has pick it up, rise it up and stop it out of screen. But because you can see the shadow of that object, I will destroy it after the animation has played. But how can I do this whit Unity and C#?

Just destroy is just like this:

```
Destroy(gameobject);

```

and start an animation like this:

```
private Animator _anim;           // global variable
_anim = GetComponent<Animator>(); // in start() methode
_anim.SetTrigger("Picked");       // in other methode

```

# Answer
You could do this by checking the current state of the Animator. Add an additional state that your animation will transition to and then check if the animator reaches this state using `AnimatorStateInfo`.

Or you could just use `AnimationEvents`

The best way in my opinion is to wrap the functionality and **use a callback**. This way you could reuse the code as well.

```
animatorBox.Trigger("Picked", () => {
    Destroy(gameObject);
});

```
> 2 votes

# Answer
I've found also a way to do it:

```
// other code
anim.SetTrigger("Picked");
Destroy(gameObject, 2f);

```
> 0 votes

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


# Question
Title: Is it possible to fake momentum by tracking an objects last known positions?
Basically I am making a melee combat system. I want to be able to apply force based on where/how things are hit. I am NOT using physics simulations for this, which is why I cannot just rely on that. Instead, can I track the part of the sword that hits the target somehow, to work it's average momentum/direction of attack? I tried by just using the last frame position and the current frame position, but this doesn't give a great angle (as the sword rotates a lot, it always taps it towards the player, when really all the momentum is going directly left). Is there a formula for working this out? Or is it as something as simple as just totally up the directional changes each frame, with some kind of decay time.

# Answer
Why did you use 'post-processing' tag? Anyway:

I would start with why you want to do this with that kind of precision.

Just to compare, you could consider a simpler system such as "when hit, the enemy is knocked back/up at a 30-degree angle." This system is easy to implement and predictable for the player. So for example maybe the player knows how to try to set up an enemy to knock them into that pit or exploding barrel or man-eating plant's mouth or whatever.

Making a more realistic system that depends on the exact frame of impact might sound cool, but are you expecting the player to understand what's happening? Are you expecting them to utilize the differences as a mechanism of control? That second one is critical because now you're opening like 1-frame timing windows for the player to achieve some exact knockback direction.

In this most recent Ludum Dare I made a tennis/arkanoid mashup and it's fairly tricky to get the player feeling in control of the angle of a shot. If that's a key element of your game it will require a lot of focus and feedback... for example in my tennis game I have a fairly intense slo-mo moment for 8 frames when the player impacts the ball, so their eye can really observe and they feel the weight. Then I have a directional impact flash that lingers so they can observe an arrow that shows them the vector they achieved. The ball also takes on a temporary trails effect so they can see the movement off the racket for a moment. Still, only some players felt their aim was strong and a number never even realized how or to what extent they could control the angle of impact.

My point is that you will need to treat it carefully if you expect control of knockback direction based on momentum of an arcing sword to be important. If it's not important, perhaps you will be better off with something extremely simple and thus easily understandable, predictable, and reliable. If the simple system feels wrong in a few cases, you can always have a couple of simple checks, like do this if the enemy is standing, that if he is caught midair while jumping, or something.

Good luck!
> 1 votes

---
Tags: post-processing
---


# Question
Title: How to sync random incidents over network?
In my Photon powered game, I have a shotgun weapon and when a player fires a bullet, I call an RPC on other clients and it's bullets get direction from a random function, Random.Range, and on different clients it acts differently.

How can I sync this so in every client, the bullets behave the same, i.e. in this case they would have same directions?

I tried setting the same seed via Random.Seed but it didn't help.

# Answer
You'll need to create your own random number generator object and synchronize it on all clients.

Also make sure the order is deterministic even with lag if two clients shoot at roughly the same time the order of RNG polling might be reversed on some clients due to network lag if packets arrive in the wrong order.

The other option is to build an identical pseudo-random direction table on all clients and pass an index into the look-up table.
> 2 votes

---
Tags: unity, multiplayer, random, photon
---


title: Unity Singleton accross multiple scenes

text:
# Question
Title: Unity Singleton accross multiple scenes
I have a game where my code is designed to be on a single scene so I've implemented a singleton like that:

```
public class MonoSingleton<T> : MonoBehaviour where T : MonoBehaviour
{
private static bool _applicationIsQuitting;
private static readonly object Locker = new object ();
protected static T Instance;

public static T GetInstance {
    get {
        if (_applicationIsQuitting) {
            return null;
        }

        lock (Locker) {
            if (Instance == null) {
                Instance = (T)FindObjectOfType (typeof(T));

                if (FindObjectsOfType (typeof(T)).Length > 1) {
                    Debug.LogWarning ("More than one Singleton of type : " + typeof(T));
                    return Instance;
                }

                if (Instance == null) {
                    var singleton = new GameObject ();
                    Instance = singleton.AddComponent<T> ();
                    singleton.name = "(MonoSingleton) " + typeof(T);

                    DontDestroyOnLoad (singleton);

                    Debug.Log ("An instance of : " + typeof(T) + " is needed in the scene, so " + singleton +
                    " was create with DontDestroyOnLoad");

                    return Instance;
                }
                Debug.Log ("Using instance already created : " + Instance.gameObject.name);
                return Instance;
            }
            return Instance;
        }
    }
}

public void OnDestroy ()
{
    _applicationIsQuitting = true;
}

#region virtual methods

public virtual void Awake ()
{
        Debug.Log ("Awake".ColorMe (Color.green) + " instance of : " + typeof(T));
}
#endregion
}

```

But now with my game growing, I want to split it into mulitple scenes (easier to do now with Unity 5.3).

I mainly use singleton to manage UI. And for this i've a UI GameObject containing my script for current scenes. So on GameObject Awake it create a reference to my Scrit that i can call with script.GetInstance.

My problem is when i refresh a scene or i use a ui component that is already used in previous loaded scene my GetInstance return null. Is there any way to refresh instance reference in virtual Awake method ?

EDIT:

Obviously `OnDestroy()` set `_applicationIsQuitting` to `true`, so `GetInstance` return `null`. I've try to set it to `false` on `Awake()` but it doesn't change anything so I do that :

```
public static T SetInstance {
    set {
        Debug.Log (Prefix + ("Updating instance of : " + typeof(T)).ColorMe (Color.yellow));
        _applicationIsQuitting = false;
        Instance = value;
    }
}

```

and on each class when I awake i do the following :

```
public override void Awake ()
{
    base.Awake ();
    myScript.SetInstance = this;
}

```

I prefer to have separated getter and setter to provide myself mode readability.

# Answer
Problem is that `_applicationIsQuitting` is a static variable. You, probably, should set it in false on `Awake` call.
> 1 votes

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