title: What is realism?

text:
# Question
Title: What is realism?
Beyond the obvious *something that seams real*, realism in games is a hard feature to hit.

In some cases, things that are completely impossible in real life are seen as realistic by gamers. For instance, in some FPS you can survive being hit by a fair amount of bullets when in real life one is enough, Newton-defying car drifts, etc.

So, in some cases, reductions of life-like actions or consequences implies a bigger sense of *realism*.

The root of this pseudo-philosophical question lies in:
I am going to create a engine for battles in an online (browser-based) strategic game. Browser-based means that the battle would not be seen. And i do not know how to approach this realism issue.

# Answer
This is a common area of confusion amongst both game developers and players. Like many such confusions, its root cause is *sloppy thinking*. Video game worlds do not, in fact, attempt to mirror reality. Instead, they present their own limited worlds which are loosely based upon some facet of the reality with which you and I are familiar.

When people talk about *realism* in games, what they're really talking about is *mimesis*, which is (loosely speaking) the degree to which the presented world maintains *internal continuity*, within the boundaries set by the player's understanding of the game's fictional world. (I like to think of mimesis as "the degree to which something behaves like itself". Which is glib, but gives the gist of the idea)

To take an example from Roger Giner-Sorolla's essay Crimes Against Mimesis (which was written in reference to interactive fiction), the following would be a violation:

> \>look
> This is a tidy, well-appointed kitchen. On the table you see a chainsaw.

The chainsaw doesn't fit what we'd expect to find in a kitchen, and so it breaks the player's belief in the reality of the situation; or in other words, it breaks *mimesis*. (Randomly strewn coloured keys often had exactly this problem, in the FPS games being made in the 1990s)

By contrast, if the same scene was written:

> \>look
> This is a tidy, well-appointed kitchen. On the table you see breakfast: six fried eggs, a foot-high stack of pancakes and about a pound of fried bacon. A huge checked flannel shirt is draped across the chair, and on the other end of the table you see a chainsaw.

Now the player can fit the presence of a chainsaw into the reality of the game world; it no longer breaks mimesis, because we've given the player a plausible explanation for how and why the chainsaw came to be where it is.

This is the challenge in creating a game. It's presenting a consistent world where everything that's present is reasonable, and doesn't pull the player out of the world. It's fine to make things bigger or more exciting or not work using the same physics as the real world, as long as they work using the same physics as the game world. It's when established rules within your game world have bizarre exceptions that you break mimesis, and that people start complaining about a "lack of realism".
> 20 votes

# Answer
Instead of realism, think *immersion*. The game must feel real to the player, but *feeling real* is not the same thing as being *realistic*. What's meant is that the game world and it's setup must be plausable (or at least semi-plausable), internally self-consistent, and deducable.

Take an old classic for example - let's say Doom. Everybody knows Doom. OK, we're on a moon of Mars (which just happens to have full gravity, breathable air and what looks like forested mountains in the background), demons from hell are running loose, and you're the only survivor. Most definitely not realistic, but within the rules of the game world that it sets up for itself, it works, and - yes - it was acclaimed for being "realistic" back in it's day.

For your specific example, don't get too hung up on the problem of being realistic. What you want instead is to set up a scenario in which the players feel as though all the wild, crazy and fun stuff you're going to throw at them may actually be happening somewhere, even if that particular somewhere may have completely different laws of reality.

So, how do we model a browser-based battle simulator? Well how do people normally get to witness battles they can't see? One way is through news reports I guess, which can contain all manner of outlandish exaggerations, propaganda and lies. And perfectly suited to a browser-based setup too. That might be a good start.

Another thing to do is take some inspiration from something similar that already works. Let's look at Nation States \- a browser-based political simulator. You pick some starting parameters, every day you get issues, you make decisions and these decisions influence the country you're managing. Lots of room for ideas in there.
> 7 votes

# Answer
I believe that Extra Credits just had an episode dedicated to this very topic which in my opinion was very enlightening.

http://penny-arcade.com/patv/episode/the-uncanny-valley
> 1 votes

# Answer
I think by "realism" you really mean **I believe it**. In other words, I "buy into" this game world. The game world and how it works *makes sense* to me and I can work within it. My disbelief in the fact this game world is not real is "suspended". A good definition of "suspension of disbelief":

> The temporary acceptance as believable of events or characters that would ordinarily be seen as incredible. This is usually to allow an audience to appreciate works of literature or drama that are exploring unusual ideas.

So the game world is self-consistent and has rules that it itself doesn't break. Abstract game worlds, like Rez, even though they don't have much relation to reality at all, are playable because they have consistent rules that you can learn, and so take control of the player and move him through the self-consistent game world.
> 1 votes

---
Tags: game-design, browser-based-games
---


# Question
Title: Solving the riddle on distributing a python built game?
So, I've done the research, and i've done the try/catch process of almost getting things to work. . . almost.

I've read this chart: https://spreadsheets.google.com/pub?key=tZ42hjaRunvkObFq0bKxVdg&output=html and i've read this post: How can I distribute a native executable for a Python program?

I'm at that point where I'm looking for either just using an installer that can run a python installer, then run the installers for all the dependencies (modules) or just copy paste the modules into the proper python directories.

So my question is: Do you have any experience with this? If so, what are your success/fail stories? Would you want to build everything into an Exe with something like pyinstaller, or just use a custom installer that would require more time to learn (like: http://www.actualinstaller.com/)?

# Answer
> 2 votes
I GOT IT WORKING!! I'm going to put all the info here that you need to know, as it's incredibly simple once you get it working.

First i'll explain my directory setup:

So i have: src\game\main.py. in source, i have a music, graphics, game and data folder. I have all my .py files in the game folder, and the others are self explanatory. Also inside the source folder is a RGB.py (RGB is the name of my game) and ALL THIS DOES is execute main.py in the game folder. So it looks something like this: graphics\> (images) games\>main.py, stuff.py, etc.py src\>music\> (music) data\> (log files and other stuff) RGB.py

Now, PyInstaller 2.0 lets you use a .spec file, which you will HAVE to use to get this to work. I'll show mine, then explain it:

```
`# -*- mode: python -*-

import os
import glob
import sys

base_path = 'C:\\RGB\\dist\\RGBpy'
sys.path.append('C:\\RGB\\dist\\RGBpy')
a = Analysis([os.path.join(base_path, 'RGB.py')],
             pathex=['C:\\RGB'],
             hiddenimports=['_codecs', 'encodings', 'encodings.aliases', 'encodings.codecs',
             'encodings.encodings', 'encodings.__builtin__', 'encodings.utf_8'],
             hookspath=None)
pyz = PYZ(a.pure)
exe = EXE(pyz,
          a.scripts,
          exclude_binaries=1,
          name=os.path.join('build\\pyi.win32\\RGB', 'RGB.exe'),
          debug=False,
          strip=None,
          upx=True,
          console=True )

pygame_files = [
    ('freesansbold.ttf', os.path.join(base_path, 'data', 'freesansbold.ttf'), 'DATA'),
]

game_files = []
with file(os.path.join(base_path, 'MANIFEST.in')) as f:
    for line in f.readlines():
        if line.startswith('include'):
            rest = line.split(' ')[1]
            base, pattern = os.path.split(rest)
            if base:
                for item in glob.glob(os.path.join(base_path, base, '*.*')):
                    _, name = os.path.split(item)
                    game_files.append((
                        os.path.join(base, name),
                        item,
                        'DATA'
                    ))
coll = COLLECT(exe,
               a.binaries,
               a.zipfiles,
               a.datas + pygame_files + game_files,
               strip=None,
               upx=True,
               name=os.path.join('dist', 'RGB'))`

```

Now, your .tff file is likely to not be detected, so thats where the pygame\_files list comes in. My .tff file is in the data folder, so the 'data' you see is there for that. Ignore the 'DATA' in all caps.

The C:\RGB\dist\RGBpy you see is where my RGB.py is located and all the folders. I just renamed \src to \RGBpy. The location doesn't matter as long as the driver .py file (RGB.py) is in that location, along with everything else that you'll probably want imported.

Next is game\_files, this is used as a workaround for manifest.in, which wouldn't work for me, but it might work for you, my manifest.in file is just a .txt file with .in on the end and it has

```
exclude .hgignore
include graphics/*.*
include music/*.*
include game/*.*
include data/*.*
include *.py
include *.txt

```

which should be pretty self explanatory.

Additional details include a pathex which is where the .exe will be unloaded. Which, when combined with `name=os.path.join('dist', 'RGB')`, you get the .exe in RGB\dist\RGB.

The rest should be pretty self explanatory. To properly run it, save the MANIFEST.in in both the pysintaller main directory AND besides your driver.py (RGB.py) and .spec in the pysintaller dir. Then execute the following in windows command: python pyinstaller .spec. If python isn't added to your system path: https://stackoverflow.com/questions/4621255/how-do-i-run-a-python-program-in-the-command-prompt-in-windows-7.

ONE FINAL RULE THAT I MUST WARN YOU OF!! .pyc files. Pyinstaller will choose those of the exist. remove them before running pyinstaller!! It'll force your file imports to be static, causing all kinds of issues! That was my major roadblock several times. DELETE YOUR .PYC FILES!!

And that is all there is to it!! Good luck!!

(credit goes to paul paterson of perpetualpyramid.com for helping)

# Answer
> 1 votes
You can just use py2exe. Congats.

# Answer
> 1 votes
As mentioned on your links, pyInstaller has been a great tool so far because it attends what users usually want on a program: simplicity. With pyInstaller, you can put everything - compiled code and libraries - on a single file, and options like an icon to your executable. It's also multiplatform, which is a bonus these days. In fact, pyInstaller has many options for building your application, so you got the freedom to choose what's best for you.

---
Tags: python, pygame, distribution, installer
---


title: texture won't move OpenGL ES 2.0

text:
# Question
Title: texture won't move OpenGL ES 2.0
I want be able to move my texture in GLSL I have set my texture to wrap S and wrap T but not sure why it wont move

my fragment shader looks like this at the moment

```
uniform sampler2D  n_mapTex;
uniform sampler2D  n_mapTex2;

varying mediump vec2  TexCoord;
varying mediump vec2  TexCoord2;

//This gets updated within the main code
uniform mediump float vTime;

void main()
{

    gl_FragColor =  texture2D(n_mapTex, vec2(TexCoord.x + vTime, TexCoord.y + vTime));
}

```

within my code I have a made a function to calculate FPS and I use the delta time of that function to pass into the fragment shader

```
void OGLESIntroducingPVRTools::timer(){
/*This method records to the time to start rendering a frame and hold that value
in another variable we then start to count again.  To get delta time we subtact
the current time from the previous time this will give us in milliseconds how
long it took for a frame to render.  We then divide this by 1000 this converts
it from ms per frame to FPS*/

FrameCount++;

p_Time = c_Time;
c_Time = PVRShellGetTime();

elapsed = c_Time / 1000.0f;
DT = ((float)(c_Time - p_Time)) / 1000.0f;

fCount += DT;

if(fCount >= 1.0f) //if time is over 1 second reset counters and recount
{
    FPS = FrameCount;
    FrameCount = 0;
    fCount = 0;
}

```

}

and in my renderscene method which updates I have this code to pass the value to the uniform within the fragment shader

```
glUniform1i(glGetUniformLocation(m_ShaderProgram.uiId, "vTime"), DT);

```

# Answer
`vTime` is a `float`, but you're passing it as an `int`, since you're using `glUniform1i()`. Adding integer values to your texcoords has no effect.

Use `glUniform1f()` instead.
> 1 votes

---
Tags: animation, opengl-es, glsl, opengl-es2
---


title: Shadowmap moving with camera

text:
# Question
Title: Shadowmap moving with camera
I am trying to shadowmap a large terrain, I position my light that it is always at the position of the player and looking at the player, the problem is that the shadows now move with the player, I tried to set the position to 0 1000 500 and look at the player always and its a good improvement however the player moves out of the light there are now no shadows :(

How am I supposed to make the light so it covers the entire terrain and everything has shadows all the time without the shadow moving effect?

I am really stuck right now, do I need to somehow calculate scene bounds? would that help at all?

# Answer
It'd be helpful if we knew what API or engine you're using.

If your shadows are from the Sun, you should be using a directional light, not a point or spot light. This means using an orthographic projection matrix when rendering to your shadowmap, as explained here: http://www.opengl-tutorial.org/intermediate-tutorials/tutorial-16-shadow-mapping/

If your terrain is very large, you may want to confine your shadowmap to a small region centered on the player. This is done through via the view and projection matrices used to render to the shadowmap. If you take this approach, you will encounter a "swimming" artifact discussed here: http://www.gamedev.net/topic/462238-swimming-shadow-edges-can-they-be-eliminated/
> 2 votes

---
Tags: shadow-mapping
---


title: texture movement stutters

text:
# Question
Title: texture movement stutters
Hey I at the moment I have got my texture to move however it stutters as I increment by 0.001 every second. My animation is done via FPS if that make sense and here is some code

```
FrameCount++;

p_Time = c_Time;
c_Time = PVRShellGetTime();

elapsed = c_Time / 1000.0f;
DT = ((float)(c_Time - p_Time)) / 1000.0f;

fCount += DT;

if(fCount >= 1.0f) //if time is over 1 second reset counters and recount
{
    FPS = FrameCount;
    FrameCount = 0;
    fCount = 0;
    move += 0.001;
    glUniform1f(m_ShaderProgram.auiLoc[eTime], move);
}

```

My problem is I want it to move more seamlessly and not sure how to achieve this and thought I would get some ideas from you.

Oh and here is my vertex and fragment shader

Vert

```
    attribute highp   vec3  inVertex;
attribute mediump vec3  inNormal;
attribute mediump vec2  inTexCoord;
attribute mediump vec3  inTangent;

uniform highp   mat4  MVPMatrix;
uniform mediump vec3  EyePos;
uniform mediump float Time;

varying mediump vec3  EyeDir;
varying mediump vec2  TexCoord;
varying mediump vec2  TexCoord2;
varying mediump float vTime;

void main()
{
    // Transform position
    gl_Position = MVPMatrix * vec4(inVertex,1.0);

    /*mediump vec2 waterCoord = inTexCoord;
    TexCoord = waterCoord.xy * waterSX;
    TexCoord += watermovementX;*/
    TexCoord = inTexCoord;
    vTime = Time;
}

```

and here is my frag

```
    uniform sampler2D  n_mapTex;
uniform sampler2D  n_mapTex2;

varying mediump vec2  TexCoord;
varying mediump vec2  TexCoord2;
varying mediump float vTime;

void main()
{
    gl_FragColor =  texture2D(n_mapTex, vec2(TexCoord.x + vTime, TexCoord.y + vTime));
}

```

Thanks

# Answer
> 2 votes
As you already have a delta time in seconds, and also the 'speed' of the texture in whatever units you use per second, then you simply need to move the texture by the speed (0.001) multiplied by the delta in seconds. Say if you have a delta of 0.5 seconds, the movement would be 0.0005, which is what you want.

To implement it in your program, change

```
if(fCount >= 1.0f) //if time is over 1 second reset counters and recount
{
    FPS = FrameCount;
    FrameCount = 0;
    fCount = 0;
    move += 0.001;
    glUniform1f(m_ShaderProgram.auiLoc[eTime], move);
}

```

to

```
if(fCount >= 1.0f) //if time is over 1 second reset counters and recount
{
    FPS = FrameCount;
    FrameCount = 0;
    fCount = 0;
    glUniform1f(m_ShaderProgram.auiLoc[eTime], move);
}
move += 0.001 * DT

```

This technique is invaluable in developing games which cope with changing framerates, because your objects will always move the same distance *per second* rather than *per frame*, which means you no longer need to assume a constant framerate.

EDIT: As you mentioned the 0.001 was supposed to be per frame, you can simply swap 0.001 in the code for what ever per-second value you desire.

---
Tags: opengl-es, glsl, opengl-es2
---


title: how to restart in java japplet?

text:
# Question
Title: how to restart in java japplet?
how to restart a game? problem with my code is that when it restarts it double the enemy. so there are 10 enemies and lets say player dies than user restart and now there are 20 enemies and so on.....

in start method i am create 10 enemies and storing in arraylist

```
public void start()
{
for(int i = 0; i < 10; i++){
    enemyObject = new Enemy(10*i,10);
    enemyStore.add(enemyObject);    //store in array
   }
}

```

in here i am making enemy move, collision etc and if enemy is dead than i am remooving it from arraylist

```
public void actionPerformed(ActionEvent e)
{
    for(int i = 0; i < enemyStore.size(); i++){
        enemyObject = (Enemy)enemyStore.get(i);
            if(!enemyObject.getDead()){               //if enemy is not died
                //make enemy move, collision etc... here
                                ....
            }
        else{           //remove enemy and create another one
            enemyStore.remove(i);
            enemyObject = new Enemy(10*i, 10); //create enemy
            enemyStore.add(enemyObject);                                               //store in array
        }
    }
}

```

in paint method paint enemy

```
public class Display extends JPanel
{
    public void paintComponent(Graphics g){
super.paintComponent(g);

for(int i = 0; i < enemyStore.size(); i++){      //PAINT ENEMY
    enemyObject = (Enemy)enemyStore.get(i);
    enemyObject.paint(g);
        }
   }
}

```

in there if player dies than remove all enemies in arraylist and restart

```
public void mouseClicked(MouseEvent e)
{
if(playerObject.getDead()){
    if(e.getX() > bx && e.getX() < bx + bw) {
        if(e.getY() > by && e.getY() < by + bh){
            for(int i = 0; i < enemyStore2.size(); i++){
                enemyStore2.remove(i);
            }
            start();
         }
     }
  }

```

}

# Answer
> 2 votes
if you remove an object at index `i` then all subsequent objects are shifted; in your loops you always skip over the next object (you could in your actionperformed function just use `enemyStore.set(i,enemyObject )` instead of removing and re-adding

in your last code block you are clearing `enemyStore2` and not `enemyStore` (note the 2 at the end

one last note: ArrayList has a clear function which is more efficient than looping and removing and actually works properly

---
Tags: game-loop
---


title: Program closes without Exception

text:
# Question
Title: Program closes without Exception
I'm using XNA 3.1 ( .NET 3.5 ) and my program closes without any warning, errors, or code instructing it to do so. I looked in the output, and there aren't any obscure messages outside of telling me that certain modules had been loaded and the program was optimized. FURTHERMORE, this doesn't occur on my own personal computer. It only happens on my school computers and my mom's laptop which makes me wonder if there's a hardware issue ( ? ). The schools run Windows XP, and the laptop runs Windows 7. Both of them have the full SDK installed, so it's not a dependency problem. Does anybody have any advice for this?

Sometimes it will run for 2 seconds. Other times it will run for about 10. Sometimes if I rebuild it enough times, it runs and doesn't crash ( or rather, the "countdown" was severely extended somehow. I don't really know. )

( I would post code, but since I have absolutely no clue where my code is doing stuff wrong, that's kind of a challenge ).

# Answer
> 3 votes
This kind of rapid exit is sometimes from calling a driver with invalid data, or for abilities it just can't do.

Assuming that you're in visual studio, find the Debug-Exceptions menu and temporarily turn on all the system ones.

Also also, **check all function returns** because, just because. Be paranoid whenever calling the system. While you're doing that, check all device caps to verify that the hardware you're running on has features that your code expects.

And finally, try using the debug version of DirectX/D3D (which gives a ton of extra console status output).

---
Tags: xna, c#, xna3.1
---


# Question
Title: Simulated Economic Factors Based on Supply and Demand in MMO Resource Trading Game
I'm working on a gam (naturally), and the primary activity for the player is to buy and sell commodities at various marketplaces.

Each commodity has the following properties:

Base Price: if all things were otherwise equal, this would be the measure of value for the commodity Supply Factor: when a player sells one unit of this commodity in a market, the "supply" goes up by this factor Demand Factor: when a player purchases one unit of this commodity in a market, the "demand" goes up by this factor.

Within each market, the commodities are given the following local properties: Local Supply Local Demand

To keep things "simple", I have these values generated randomly with the equivalent of a 3d6, so Supply and Demand can be anywhere from 3-18.

The price for one unit of a commodity in a particular market is calculated like so:

Price = BasePrice * (LocalDemand+DemandFactor\*UnitsDemanded) / (LocalSupply+SupplyFactor\*UnitsSupplied)

In this way, player purchases will drive the price up, and player sales will drive the price down.

Now comes the problem, and I'll use a concrete example as it is not entirely obvious from just looking at the formula.

We have commodity X with a base price of 100, and local demand and local supply both of 10, and a supply and demand factor each of 1.

So, desiring to purchase a single unit, I calculate the price:

Price = 100 * (10+1\*0) / (10+1\*0) = 100

And I purchase the unit, which drives up the price to:

Price = 100 * (10+1\*1) / (10+1\*0) = 110

And if the player then sells the commodity at that price, he immediately profits 10.

This is no good.

So, my first pass at this solution is to calculate the price based on what the supply or demand WILL BE after the purchase is over, which works after a fashion, but consider that in the example above, the purchase of 1 unit will be 110, whereas the purchase of 10 units will have a unit price of:

(100 * (10+1\*10) / (10+1\*0)) = 200 (total of 2000 to buy 10 units)

So, naturally this is unfair, and so the player would get the best price for purchasing one unit at a time.

And I don't want the player to have to do that, so I want to calculate the price one unit at a time.

This in itself is relatively easy, just loop through the units I want to purchase, and add it up.

Unfortunately, it doesn't exactly take care of the fractional units.

I might not have mentioned that you can own fractional units of commodities. You can.

Another thing to compound the issue is that the "currency" is simply another commodity, which can itself have supply, demand, supply factor, demand factor, sales, purchases, and so on.

So purchasing is a two step problem.

First, for a particular number of units of a commodity, determine the "value" of them in a way that ensure that buying and then immediately selling is a losing proposition.

Second, for a particular "value", determine the number of units that would need to be "sold" in order to make up that value.

Another wrinkle: it should not be advantageous to purchase fractional units. The price for buying half a unit, and then buying another half a unit should not be better or worse than buying one whole unit at one time.

# Answer
> 2 votes
When computing the price for the units that the player is trading, don't use the final number of units left after the transaction. Instead, use the arithmetic mean of the two quantities, before and after the transaction.

For example: if the player wants to purchase 1 unit out of 10 available units, use the price of the commodity as it would be at 9.5 units available. If the player instead wants to do two transactions of 0.5 units each, you'd first pay him at 9.75 price and then at 9.25 price, thus giving him the same amount of currency.

This should also solve the issue of buying, immediately selling and thus generating a profit, since in both instances you would sell for an average number of units, which would be equal in both instances. In our previous example the player would buy 1 unit out of 10 at the price of 9.5 units, then sell that unit back at the price of 9.5 units, therefore gaining just as much currency as he lost.

Another advantage to this approach is that you should no longer need that loop you mentioned.

# Answer
> 5 votes
TokPhobia's answer contains the seed of a good idea, but the arithmetic average he recommends only gives the right answer if the price is a linear function of the amount of available units.

If the price is a *non*-linear function of availability, the correct price can instead be obtained by integrating the per-unit price from the amount available before the transaction to the amount available afterwards. Indeed, this is basically what your loop-and-add-up solution is doing, except that you're approximating the integral with a finite sum, which introduces some inaccuracy.

You *could* try to address the problem by using a better numerical integration method, but there's an easier solution: instead of trying to calculate the integral based on the spot price function, *define the spot price in terms of the integral.*

Specifically, start by defining a function `P(x)` which gives the total cost of buying the *entire local supply of the product* when that supply consists of `x` units (excluding seller profits, transaction costs, etc.). You can make that function look like *anything you want*, as long as it's monotone increasing. Typically, you'd also want to make sure it's concave, i.e. that the marginal cost of a single unit goes down as the amount of units available increases.

(In particular, note that, for all the calculations below, adding a constant value to `P(x)` doesn't actually change the results. Thus if, say, buying the last few units would be disproportionately expensive, it might be numerically more convenient to replace `P(x)` with the function `Q(x) = P(x) - P(c)`, where `c` is e.g. the "typical" amount of the product available. Essentially, `Q(x)` then gives the cost/profit of bringing the local supply from `x` to `c` units.)

Then, if the current locally available amount of the product is `x`, and the player wants to buy `y` units, the total cost of the purchase should be `P(x) - P(x-y)` (times the seller's markup, plus any fixed transaction costs), while if they want to *sell* `y` units, they amount of money they should receive is `P(x+y) - P(x)` (minus markup and transaction costs again, of course; even virtual vendors have to eat, don't they?).

If you want to quote a per-unit spot price to your players, you can just approximate it with `P(x) - P(x-1)`, i.e. the price of buying one unit of the product. I would, however, recommend that you also allow your virtual merchants to offer direct quotes for buying/selling `y` items, so that your players can know in advance how much they'd be paying.

Of course, the function `P(x)` can change over time, or between different locations; indeed, it *should*, if you want your players to have meaningful trading opportunities. Also, naturally, the local availability `x` should more or less gradually return to its "typical" value in the absence of player trading, to simulate the actions of unseen local traders.

# Answer
> 0 votes
If you simply delay the price adjustment until a later time then any immediate "gaming the system" will be thwarted. You can argue that players will figure this out and still game the system for profit... but that's what trading is... gaming the system for profit.

In multi-player game usually the inherent market price is kept at a constant and low value to stabilize the economy and give a baseline "meager living wage" if no one live participates. Live players then set the real value via their trading strategies.

Since you don't have live players in this game and assuming that you want the markets to feel fluid then I suggest following what I described above, but substitute "AI traders" for the live players. Build a bunch of trading strategies and set them loose on the market, let the player go against their algorithms.

This obviously is not a direct answer to your original math question, if you're looking for that please follow @TokPhobia and try his answer.

---
Tags: mathematics
---


# Question
Title: Breakout style ball-paddle bounce, error at corner
I am trying to make a breakout game where you have a paddle and a ball bounces around breaking bricks. The problem is that if the ball touches the corner of player it goes inside of player. I change the `dx`, `-dx`, `dy`, `-dy`, etc. in order to change the ball position so it looks like it bounces off of the player or window.

Here I check collision between ball and window. `x`,`y`,`dx`,`dy` are ball position and speed.

```
public void BallWCollision()
{
    //dx, dy is ball speed

    if(x <= 0){   //if ball goes right of screen
      dx = -dx;
    }
    else if(x >= Main.WINDOW_WIDTH){  //if ball goes left of screen
      dx = -dx;
    }

    if(y <= 0){    //if ball goes top of screen
      dy = -dy;
    }
    else if(y >= Main.WINDOW_HEIGHT){  //if ball goes bottom of screen
      dy = -dy;
    }
}

```

Here I check collision between player and ball. If the ball touches the player then change ball `dy`.

```
public void playerBallCollision(Ball b)
{
    if(player.getBounds().intersects(b.getBounds())){  //if player and ball touch each other
      b.setDy(-b.getDy());
    }
}

```

# Answer
> 4 votes
There are many specific circumstances related to your code (that you haven't posted). For instance, do you update position before or after checking for collisions? Do you always apply changes to position, or are they sometimes skipped? Do you apply any extra position change in order to resolve a collision? When your ball gets "inside" player, is it still moving in the `x` direction? After changing direction, are you certain your ball will not bounce a second time?

That last one is most important. If a ball strikes the corner of your paddle, then simply changing the sign of `dy` probably won't resolve the collision. The ball could be too far along in the `y` direction to move out of the paddle before the next update. So on that next update, it will collide again, and it will reverse direction again. This process will repeat indefinitely.

What you need to do is not simply change direction of motion, but guarantee that the collision is resolved. You may have to separately detect a region of collision, where a corner is different from the front, is different from the side, etc. For the case of the corner, you may only need to reverse both `dx` and `dy`. You may need to arbitrarily move the ball out of collision with the paddle. It all depends on your specific implementation.

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


# Question
Title: Should I negate a variable or use absolute value?
this is how i was chaning ball postion

```
if(...) //if ball goes to left of screen
  dx = -dx
if(...) //if ball goes right of screen
  dx = -dx;

```

i found some people using math.abs to move ball postion.

```
if(...)  //if ball goes to left of screen
    dx = Math.abs(dx);
if(...) //if ball goes right of screen
    dx = -Math.abs(dx);

```

which is better? if 2nd one than plz explain why.

# Answer
> 3 votes
Neither is better. They are different functions. Their appropriateness is determined by what you are trying to do.

```
//negate a variable
dx = -dx;

//force a variable to be positive or negative
dx = Math.Abs(dx);
dx = -Math.Abs(dx);

```

# Answer
> 3 votes
Depending on the circumstances in some physics engines it may happen that two objects that overlap in one frame, and has their collision resolved, still overlap in the next frame. If they therefore have their collision resolved again it will typically reverse the original collision, resulting in the objects getting stuck together as they spend every second frame moving towards one another and every other frame moving equally away from one another.

The `abs` code is a simple fix for this, ensuring that the collision will only happen if the ball is moving towards the wall.

---
Tags: mathematics, collision-resolution, linear-algebra
---


# Question
Title: Differences between Overlap and Intersection testing?
I have heard of techniques such as *overlap testing* and *intersection testing* for collision detection and collision resolution.

I looked up on the two techniques, but I don't see what differences they have. On every frame, the overlap testing will check to see if it overlaps another object by looking if any vertices is inside another object's bounding volume. The intersection testing on the other hand casts a line from its centre point to check for intersection. But since it's only a line, it may not be as accurate. So it has to cast many lines continuously from all over its edges in its moving direction and, hence, is more costly. Is this true and is the only difference between the two techniques?

Otherwise, what are the differences between the two techniques? Also, are there any differences in terms of collision resolution between the 2 techniques/

# Answer
The terms overlap testing and intersection testing are largely synonyms. Neither does without context signify a specific method. Collision detection could also be said to be a synonym, but therm might in some cases be bit broader.

I'd describe these terms as the art of determining whether or not two figures in any place occupy the same space. Depending on the context this may also include finding the bounds of that space or finding the point where they first touched.

Collision resolution is what comes after collision detection, it is the art of determining how the collision should influence the objects. Usually this means changing the velocities and spin of the objects according to Newtonian rules of physics, but it could also mean breaking the objects or applying some alternate physics rules that fit the gameplay better.
> 1 votes

---
Tags: collision-detection, collision-resolution
---


title: Game programming books?

text:
# Question
Title: Game programming books?
I need a book that's beneficial for me and not something that contains what i have already read.

I have a strong maths,physics background and I have good c++ programming skills

and i want to start game programming in 2d because after a lot of research on net people recommend not to jump in 3d directly.

Also I don't want to study from online tutorials like those in SFML because there is lot of knowledge scattered on the net but what i want to study from a good book because in the book all knowledge is in one place

I have also done research that books like Beginning 2d game programming by Charles Kelly,Game Engine Architechture,Game Coding Complete,Advanced 2d game development by Jonathan Harbour are all good **But I can Only Buy one** at the moment and i already know c++,physics and maths pretty well (dont know graphics though) so which one is the right one for me. So please guide me Thank You

# Answer
> 0 votes
I only know Game Engine Architecture and Game Coding Complete. Both aim for 3d game development. But the core concepts (event handling etc.) are applicable to 2d game as well.

I recommend Game Coding Complete. Shaffry has a ton of experience developing games. He also explains the concepts really well and has C++ code examples.

Game Engine Architecture feels a bit incomplete as it only explains subsystems required for a game. Well worth a read though.

I could be wrong, but from your question I think you don't know how to start game development.

Just pick a library for drawing 2d graphics and start coding.

Start coding a main game loop, load and draw a sprite, capture user input and apply it on screen. Then you want to look up entities and component system etc.

Research stuff as you encounter it. One of the books is a good starter.

Hope that helps.

---
Tags: software-engineering, graphics-programming
---


# Question
Title: How to combine tap and long hold gesture recognizers?
I have a game in which the player moves around a sprite by tapping on various sections of the screen (left, right, up, down). So far, each tap moves the sprite one tile (I use a tile system for movement, among other things), so to move the sprite a long distance the player has to tap in the direction they want for a while. **Is there a way to combine a tap gesture recognizer and a long hold gesture recognizer so that if the player taps once, the sprite moves one tile in the direction tapped and if the player holds, the player moves in that direction until the player stops holding**?

Here's my code for a single direction just as an example of what I have:

```
-(void)handleRightTap {

    self.player.direction = RIGHT;
    float currentSpriteX = self.playerSprite.center.x;
    float currentSpriteY = self.playerSprite.center.y;

    //If the animation is not already happening and the destination is accessible...
    if(!self.isAnimating && self.toTile.isWalkable) {
        self.isAnimating = YES;

        //If the player has reached the edge of the screen...
        if([self checkIfPlayerHasReachedEndForPoint:toPoint]) {
            self.isAnimating = NO;
            return;
        }
        CABasicAnimation *moveAnimation = [CABasicAnimation animation];
        moveAnimation.toValue = [NSValue valueWithCGPoint:CGPointMake(currentSpriteX + TILE_WIDTH, currentSpriteY)];
        [moveAnimation setDelegate:self];
        [moveAnimation setFillMode:kCAFillModeForwards];
        [moveAnimation setRemovedOnCompletion:NO];
        [moveAnimation setDuration:MOVE_ANIMATION_DURATION];
        [self.playerSprite.layer addAnimation:moveAnimation forKey:@"position"];
    }
}

```

# Answer
The way to deal with this is to set a timer once the person taps the phone. The most user friendly scenario that you'd implement would look something like this:

1. When you detect a tap, set a timer (`t = timeToRepeat`)
2. On each frame, decrease the timer by dt
3. If the timer reaches zero, move the sprite a tile and reset the timer
4. If the user releases their finger before the first cycle of the timer, move the sprite one tile

Obviously the amount of time that you set your timer to will determine how fast your sprite moves. There are a few variations on this theme depending on the kind of behavior you want as well. For example, you can move the sprite once immediately upon detecting a tap and ignore step #4.
> 2 votes

# Answer
Measure the time between the user started to touch the screen and until he release it. If the measured time is below a certain threshold ( 1 sec?! ) it's a tap, otherwise it's a long hold.
> 1 votes

---
Tags: ios, movement, objective-c, gestures
---


# Question
Title: XNA/MonoGame and Game Studio/MonoDevelop
First off, I have a bit of programming experience in Java and have always programmed using ViM (even though I recently moved to Sublime Text 2) and I'm trying to learn C# and the MonoGame framework. My question is whether or not I REALLY need MonoDevelop.

So, do I really need Visual Studio/MonoDevelop to develop games in C# and MonoGame?

# Answer
You can build XNA projects outside of the IDE (debugging them effectively is another matter entirely), just like any other C# project. Using the MSBuild system.

The specific thing that you need to know about for XNA is the Content Pipeline that you need to process your content. You can build content projects outside of the IDE, but to set them up you would have to edit the `.contentproj` file by hand (it's XML). The values for that file are exposed nicely through the IDE (using reflection). Figuring out what to set them to yourself will be an exercise in frustration.

Also, I don't think XNA Game Studio will install without Visual Studio also being installed. I don't think there's any other "within the EULA" method of getting the DLLs necessary to run the content pipeline.

So, in the interest of sanity and practicality, you should probably at least install Visual Studio, even if you insist on not using it. Although, once you've got it installed - you should give it a proper go - it's rather excellent. For XNA you probably want VC# 2010 Express.

I haven't checked on MonoGame for a while, but last time I looked you needed to use the XNA Content Pipeline to build a few kinds of content, like fonts. I have heard that they're working on their own content pipeline solution - not sure how far along that is coming. But otherwise the situation should be similar to XNA.
> 3 votes

---
Tags: xna, monogame, editors, ide
---


# Question
Title: Follow behavior with randomization factor
I'm trying to make enemy follow player as in picture below, the code below is code for following player with steering behavior ( i'm not sure it steering works tho but it does follow player ), how would i code something like in the picture below to make the following more randomized but still going in direction of where player is.

```
Vector2f velocity,steering,desiredVel;
velocity = new Vector2f(player.getX() - getX(), player.getY() - getY());
velocity.normalise();
velocity.scale( maxVelocity);

// unsure what to do with random numbers yet
Random rand = new Random();
int randy = (rand.nextInt(101) -50);
int randx = (rand.nextInt(101)-50);

desiredVel = new Vector2f(player.getX() - getX() +randx, player.getY() - getY() +randy);
desiredVel.normalise();
desiredVel.scale( maxVelocity);

steering = desiredVel.sub(velocity);

steering = truncate(steering,maxForce);

steering.scale(1 / mass);

velocity = truncate(velocity.add(steering) ,maxSpeed);
this.velocity = velocity;

position.add(velocity);

```

# Answer
> 3 votes
This is a simple mixing of two different steering behaviors. Following and wandering.

You can find information about implementing both in this GDC paper from '99.

Start with implementing both independently. Then apply both at the same time, with a blending factor. You'll have to modify the blending value depending on how much you want to wander vs how direct you want the steering to be.

If you want the regular pauses, you can add a random duration for the path following to run and another random duration for it to pause.

---
Tags: java, game-mechanics, slick
---


title: bump mapping with 2 normal maps

text:
# Question
Title: bump mapping with 2 normal maps
I was wondering if its actually possible to do bump mapping with 2 normal maps... I have tried doing it this way however I get a function overload on max and dot.

```
uniform sampler2D  n_mapTex;
uniform sampler2D  n_mapTex2;
uniform sampler2D  refTex;

varying mediump vec2  TexCoord;
varying mediump float vTime;

void main()
{
    mediump vec4 wave = texture2D(n_mapTex, TexCoord - vTime);
    mediump vec4 wave2 = texture2D(n_mapTex2, TexCoord + vTime);
    mediump vec4 bump = mix(wave2, wave, 0.5);
    //this extracts the normals from the combined normal maps
    mediump vec4 normal = normalize(bump.xyzw * 2.0 - 1.0);
    //determines light position
    mediump vec3 lightPos = normalize(vec3(0.0, 1.0, 3.0));

    mediump float diffuse = max(dot(normal, lightPos),0.0);
    gl_FragColor = mix(texture2D(refTex, TexCoord), bump, 0.5);
}

```

# Answer
I'm not really sure what exactly you hope to achieve, the proposition sounds sketchy.

In any case, I'm pretty sure you get your error for trying to calculate the dot product between a `vec4` and a `vec3`. The mathematical dot product is only defined for vectors with the same number of dimensions, most programming languages mirror this.
> 1 votes

---
Tags: opengl-es, glsl, opengl-es2
---


title: Box2D physics editor for complex bodies

text:
# Question
Title: Box2D physics editor for complex bodies
Is there any editor out there that would allow me to define complex entities, with joins connecting their multiple bodies, instead of regular single body entities? For example, an editor that would allow me to 'define' a car as having a main body with two circles as wheels, connected through joints.

**Clarification:**

I realize I haven't been clear enough about what I need. I'd like to make my engine data-driven, so all entities (and therefore their Box2D bodies) should be defined externally, not in code.

I'm looking for a program like Code 'N' Web's PhysicsEditor, except that one only handles single body entities, no joints or anything like that. Like PhysicsEditor, the program should be configurable so that I can save the data in whatever format I want to. Does anyone know of any such software?

# Answer
> 6 votes
You may be interested in Physics Body Editor. That's an open-source tool handling bodies with multiple fixtures.

A big update is in progress, and next revision will support complex dynamic objects made of multiple rigid bodies linked with custom joints, as well as a scripting support for directly testing your bodies.

Hope you'll like it ;)

# Answer
> 5 votes
R.U.B.E. is fantastic: https://www.iforce2d.net/rube/

Its just does what it should and is not restricted to specific game engines like levelhelper..

# Answer
> 3 votes
The Box2D website does list 3 editors that could be useful to you. http://www.box2d.org/links.html

One of the links is dead however. I was only able to check this one out: http://www.brainblitz.org/BoxCAD/

There is an option to dump to code that I tried, and it does in fact give you the Box2D code of whatever you built on screen. Looks pretty decent.

# Answer
> 0 votes
LevelHelper (www.levelhelper.org) has support for Box2D joints. Here's a tutorial to get your started: http://www.levelhelper.org/?tag=cocos2d

# Answer
> 0 votes
I use level director (www.retrofitproductions.com/level-director) and PhysicsEditor by codeandweb.

Physics Editor will allow you to apply the physic properties and body shapes to each object and Level Director will allow you to import them and then setup the complex bodies and joints as needed. Once done, Level Director allows you to export the data in pretty much any format you desire via a template.

---
Tags: physics, box2d, editors
---


title: Client send rate for network games

text:
# Question
Title: Client send rate for network games
As I understand for a client server model, it's common practise to send input to the server and then the server applies the input to update the state of the game. The server then sends updates to clients regularly. The client in the meantime does prediction, before it receives the "true" state.

My question is how often to send input. Surely it should be sent every frame otherwise some input (during frames which are not sent) will not be processed by the server. Will this be too heavy for the network. What is common practise?

# Answer
Sending data to the server can usually happen at a higher rate to data coming from the server.

That's because the main bandwidth restriction is usually on the server's outgoing connection to all the clients, and also because the client generally needs to send much less data that it receives.

However, this will vary based on what sort of game it is, and how the networking code is implemented.

If it doesn't get sent every frame, the client should accumulate all the data in a buffer and send it in a batch at whatever rate is appropriate. The main advantage of batching it up is to avoid the overhead from the UDP packet headers (~32 bytes each IIRC).

Also note that on most frames nothing will have changed for the client, so there's probably no need to send any data in that case.
> 2 votes

---
Tags: networking, input, server, client
---


# Question
Title: Physics engine recommendation which can simulate pool game correctly?
I'm making a pool-game like game. This game requires correct (or very accurate) reflective bounces. I tried *Box2D* and *Bullet Physics*, but they both have this problem.

If there is a wall on top of this image, red line is expected course of a real ball in a pool-game. But the engines often shows green line course. Especially,

1. This happens after a slowly moving ball hits the wall.
2. Sometimes a rapidly moving ball get slower suddenly.

I'm finding a physics engine which can simulate pool-game accurately as much as possible without these problems. Can I get some recommendations? Now I'm digging *Newton Game Dynamics*, but I am not sure the engine will show what I want. I'm considering the *PhysX* engine as a next trial, and have to make my own if nothing works. But it's obvious it'll take very long time, so I wish I won't do that. I'll be very appreciated if you save my time. And of course, solution with Box2D / Bullet Physics are also welcomed.

I am working with C/C++/Objective+C on iOS.

---

I attach my configuration with Box2D.

# Walls

* static box shape
* linear/angular damping = 0.1
* restitution = 1.0
* friction = 100
* density = 10
* bullet = false
* fixed rotation = false
* inertial scale = 1.0

# Balls

* dynamic sphere shape
* linear/angular damping = 0.1
* restitution = 1.0
* friction = 100
* density = 20
* bullet = true
* fixed rotation = false
* inertial scale = 1.0

# Answer
> 8 votes
Several solutions.

1. For Box2D, set `b2_velocityThreshold` in `b2Settings.h` file. In my case, I set it to `0.0f` and it worked! Mass, friction, damping were NOT problem. Check this discussion thread for more details. http://www.box2d.org/forum/viewtopic.php?f=3&t=6906&p=30782#p30782
2. Using other physics engine. *Newton Game Dynamics* configured performing this correctly by default. However using Newton dynamics in iOS is possible but it's somewhat harder than others. I used several days configuring it for iOS.

I'm also asking on BulletPhysics forums. I'll update this when I got a solution.

-- (edit) --

There are some threshold attributes in Bullet, however I couldn't find exactly same thing with `b2_velocityThreshold`.

This looks similar, but didn't work well.

```
btRigidBody->setContactProcessingThreshold(0.0f)

```

# Answer
> 6 votes
Box2D will do what you want but you have to set the restitution (bounce) constants for the wall and ball fixtures. For a pool game you probably want to start with perfect restitution and high friction but linear and angular damping, and tweak from there.

# Answer
> 4 votes
Physics engines have a bounce threshold. I don't know how to do it in either of those engines, but the threshold being set too high will cause it to ignore impacts under a certain velocity. Lower the bounce threshold and it will bounce at lower speeds.

I know you asked for a different physics engine, but all physics engines I know of use bounce thresholds to keep objects from jittering when they're sitting on top of each other. So suggesting a good physics engine will be counterproductive as any good physics engine will have this effect.

# Answer
> 0 votes
I had this problem and for me the solution was providing perfect restitution.

So for me that is sqrt of 0.5 for all objects. Because sqrt(r1\*r1 + r2\*r2) == 1 in perfect situation.

---
Tags: physics
---


title: XNA Camera Positioning All Wrong

text:
# Question
Title: XNA Camera Positioning All Wrong
I've been working in 3DSMax for years now and decided to give XNA 4.0 a try. I've got the majority of it working, however the camera is being a pain to me and I can't discern what's gone wrong. I followed tutorials up to this point and am branching out into newer things.

Basically for this setup, I have a 'grid' in 3D space (all have a Y-component of 0) with spheres located here and there along the grid (spheres are FBX models from 3DS). What I'm trying to do is write a quick move command that'll move the camera above and behind one of the objects and then look at it. By using the keyboard, I can scroll through the list of objects and the camera should immediately jump to the specified position. However, in practice, the camera ends up in strange places, doesn't look where it's supposed to, and I'm not even sure it's actually moving!

The location of the objects is stored within a class object as a Vector2 (hence the Y/Z swap below), as they are all on the same plane (no Y-axis used). The following code, in theory, should return the position of the camera, and it's target, based on that class object's position in the world. m\_vPosition is a Vector2 that defines the location of the object. That vector is defined at creation-time and is in the Translation Matrix for the object.

```
    public void GetCameraHoverLocation(out Vector3 p_vPos, out Vector3 p_vLook)
    {
        p_vPos = new Vector3(0, 0, 0);
        p_vLook = new Vector3(0, 0, 0);
        // Position should be above and behind
        p_vPos.X = m_vPosition.X;
        p_vPos.Y = 1;
        p_vPos.Z = m_vPosition.Y + 10;

        p_vLook.X = m_vPosition.X;
        p_vLook.Y = 0;
        p_vLook.Z = m_vPosition.Y;
    }

```

The code to move the camera into position is:

```
    public void SetCameraPosition(Vector3 p_vPos, Vector3 p_vLookAt)
    {
        m_mViewMatrix = Matrix.CreateLookAt(p_vPos, p_vLookAt, Vector3.Up);
        m_vCameraPos = p_vPos;
        m_vCameraView = p_vLookAt;
    }

```

The Position and LookAt are stored for later usage. The ViewMatrix is then given to the shader and bob's your uncle. However, again, the positioning of the camera is alllll wrong. I'm thinking it might be a complete misunderstanding of the Matrix.CreateLookAt function, but it works as written if I don't bother moving it (up to this point that is). Can anyone point me in the right direction on this one? I'm used to the way 3DS does things with cameras (vector for location, vector for target), so that might be polluting my thought process.

# Answer
This was a myriad of problems gone awry. I rewrote my Camera class using another tutorial insight (http://www.madgamedev.com/post/2010/09/05/Article-Simple-3D-Camera-in-XNA.aspx) that helped point out my problems. While the way I had it setup was, in theory, correct, the way in which I was handling it was erroneous. In addition there was an additional cascade issue when I was calculating the Matrix for the position of my models. They were being multiplied a few too many times, so while my target was correct, the actual location physically in the world was wrong. I implemented the design setup in the above link and fixed my location bug, and darn, it looks quite nice now.
> 0 votes

---
Tags: xna-4.0, camera, matrix, transformation
---


# Question
Title: Set texture of a LHSprite that is loaded from LevelHelper
How do i set the image/texture of an LHSprite that is loaded into xCode using levelHelper & spriteHelper?

I am using sprite sheets. So i tried to load the image the old fashioned way using CCSpriteFrameCache, but unfortunately it isnt recognizing the .pshs file :( Any Help would be great!

# Answer
I have figured it out, I just added another animation which consists of 1 frame, then when i need it, i play the animation:

```
[mySprite stopAnimation]; //Stops CurrentAnimation
[mySprite prepareAnimationNamed:@"jumpAnimation" fromSHScene:@"Jungle"];
[mySprite playAnimation];

```
> 0 votes

---
Tags: iphone, ios, cocos2d-iphone, objective-c
---


# Question
Title: Is Free2Play w/ cash shop "non-commercial"?
I'm new to game development and considered using the Unreal Development Kid for a test game. The website states it is free for non-commercial use. I know that games that can be obtained free of charge are considered non-commercial.

However, my mind came up with the question: **What are free-to-play games with cash-shops categorized as?** Not saying I'm planning to embed one in my test game, that would be just non-sense.

A quick Google search couldn't come up with any answer, especially since I'm unsure of what to search.

# Answer
# No.

From the faq link I put on @eBusiness's answer, in reference to what money requires the 25% royalty while using a comercial license:

> ...includes, but is not limited to, revenue earned from: sales, advertisements, sponsorships, endorsements, subscription fees, microtransactions, in-game item or service sales, rentals, pay-to-play, services you sell or are remunerated for in connection with the use of your application and amounts a third party pays You to develop or use the application.

You need a commercial license for in-game sales.
> 9 votes

# Answer
Non-commercial:

> ...refers to an activity or entity that does not in some sense involve commerce.

An in-game shop involves commerce.

If you make money directly from the game, it's a commercial game.
> 5 votes

# Answer
First of all, read the terms of free use for the desired product, they will usually contain a much more specific phrasing.

It is hard to define a strict definition for what is commercial and what is non-commercial, a prominent borderline case is a good given out for free to promote a commercial product. It is still commercial, but what if the good doesn't mention the promoted product? Perhaps it only bears the company name. What if the advertising is distributed along with but the product itself bear no marks of advertising?

You will almost never see words like commercial in legalese without a preceding strict definition of the word, since using a word without a strict definition makes for weak ambiguous contracts.

### Unreal Development Kit

I'd be surprised if the UDK allowed freemium games without a paid license.
> 5 votes

---
Tags: udk, legal
---


# Question
Title: How to seamlessly texture a cube in OpenGL
I have been following this site as an intro to OpenGL.

After going through the model obj loading tutorial, I wanted to create my own .obj (a cube) as well as my own texture. Following this blender tutorial I created and textured the cube, and exported the .obj and .dds which I am loading in the OpenGL tutorial program.

My issue is that in both cases, the original tutorial .obj/.dds and my own custom one created with blender, the texture for each face of the cube has a slight black edge around it.

I can't figure out how to change this, so that I have a "seamless" texture around the cube, with no black or white edges.

I'm not sure if this is something that needs to be adjusted in Blender, or in the c++ application. Any help would be appreciated!

# Answer
I'm pretty sure that's just happening because your UV map is spilling over into the black area of the texture. If you just bring your UVs in a bit it should work.

Or you could just do it the lazy way (like me) and paint along the borders of the white/black area to make it impossible to read any background pixels, EG:
> 1 votes

---
Tags: c++, opengl, textures, blender
---


# Question
Title: How to detect when a character is walking on an item in Java?
To detect if a character is on an item on the floor, I can check every item on the map and do a collision check, and repeat the process every iteration.

Is there another way to do it, without checking *every* item?

I'm using Java, maybe the language offers a smart way to do this.

# Answer
A common way to do this is to divide the game world into tiles (which is something you may want to do for other reasons too) and have each tile store a list of the items in it. That way, you only have to check the items that are in the same tile as the character (or possibly in an adjacent tile, if the items and/or the character can overlap several tiles).

If you have a large world with items scattered sparsely in it, you may also try fancier spatial subdivision techniques like quadtrees. In any case, the principle is the same: divide the world into chunks, assign each item or character into a chunk based on their location, and only check for collisions between things in the same or in adjacent chunks.
> 2 votes

---
Tags: java, collision-detection
---


# Question
Title: OSX Based Equivalents for Stacking Normal Maps?
I've been looking for an OSX based alternative to the Windows based xNormal and NVIDIA textures tools for stacking normal maps in photoshop.

Can anyone recommend something, whether it's a standalone package or photoshop plugin?

# Answer
> 1 votes
It was suggested that I try out nDo, which looks like it might do what I want. It's a PS plugin that works in both Windows and OSX so here's hoping :)

---
Tags: textures, normal-mapping, plugin
---


# Question
Title: What revenue models can I use for a non-commercial game
I don't have any budget to buy commercial licenses but the libraries I use offer non-commercial free licenses.

How far can I go in regard to monetizing my game without it being considered commercial ? Donations? Do ads count? Optional items purchase?

For example, fmod states in their free license:

> This license cannot be used for commercial services, where the executable containing fmod is not sold, but the data is.

What if only some data (optional) is sold?

Thank you.

# Answer
> 2 votes
com·mer·cial \[kuh-mur-shuhl\] –adjective 1. of, pertaining to, or characteristic of commerce. 2. engaged in commerce. 3. **prepared, done, or acting with sole or chief emphasis on salability, profit, or success**: a commercial product;

I am not a lawyer, and the comment that Chewy made about consulting a professional stands as very reasonable.

Since you asked here though, my opinion is that if you use the software on someone's behalf, and they compensate you to do so by any means then you have acted commercially.

For this discussion, I'd suggest that sales, ad revenue, donations, software in trade or any promises of future considerations all constitute acting commercially.

If you're looking to take a project out of the basement and start generating income from it, then the authors who have aided you by writing libraries deserve to be compensated. If you've developed this program with the intention of selling it, then the clock's been ticking on this day.

# Answer
> 6 votes
From http://www.fmod.org/index.php/sales :

> If your title is not intended for commercial gain and does not include the FMOD library for resale, license or other commercial distribution, then use of FMOD is free.

If you are pursuing revenue models, then your title is clearly intended for commercial gain, and you do not meet the criteria to use the FMOD non-commercial license. You would need to purchase either the Commercial or the Casual licenses.

In general, you should contact the copyright holder over these types of conditionally-free licenses, to verify that your planned usage is okay with them. But in this specific case, it seems pretty clear to me that what you're trying to do is not allowed by FMOD's non-commercial license terms.

But you should really be asking them, not us. FMOD has a team which handles licensing terms and interactions with developers. You can reach them at sales@fmod.org.

# Answer
> 3 votes
If you're monetizing your game, via ads or in-game purchases, it will be considered commercial. I'd suggest using a library that allows commercial usage, there are plenty of free open-source libraries that fit the bill.

# Answer
> 2 votes
The title of this question is an oxymoron. Any revenue **means** your product is *commercial*. If you don't want to pay licensing, **you need to stick to free alternatives**. OpenAL is not that much harder to use than FMod and it is free. There are plenty of free libraries like SDL that can help with a lot of the startup work.

It sounds like you're trying to "get around" *licensing*, which you just can't do. Either license the product or use one of the (many available) free alternatives.

---
Tags: legal, monetization, licensing, revenue
---


# Question
Title: Legal issues concerning using superheroes in games
Before proceeding on with the idea of developing a mobile game that involves superhero characters from both Marvel/DC Comics, I am taking a serious dip into looking into things from a legal point of view. As what I have observed so far that all the games of this genre are under the banner of warner bros. or some other concerning production company.

I need to know whether it is legal to use the names/images/weapons/sounds/themes or any other specific association of a given character in a game?

If not, then what is the right way of going about to make one? Should I need some sort of permission/license to make one?

What if the game developed is kept free? Will that give us a safe passage to walk on?

# Answer
IANAL, and it would potentially be different in different countries, but some guidelines:

1. Anything that references trademarked and/or copyrighted content (and everything is copyrighted at the moment of creation by its creator) should not be used without explicit permission from the trademark/copyright owner.
2. When in doubt about trademark or copyright status, assume trademarks and copyright exist, see 1. on how to proceed.
3. Commercial status of either the original or the derived work are irrelevant to this.
4. Don't assume a "fair use" claim on your part will be valid. Such systems are far from universal in IP law and where they do exist can be interpreted to be extremely restrictive.
> 7 votes

# Answer
@jwenting Has a very valid point on restrictions of use. But you also asked about licensing and creation.

Any copyrighted work or trademark can be licensed, if the copyright owner agrees to. (He may have his own plan for a game or may think you will not build a quality game and devalue his brand.) As a default and especially in your case you need to go to the copyright holder. (the name after the ©)

In the case of music and movies there are royalty collection agencies. But these are only for so called "mechanical royalties", such as verbatim playback. So if you want music in your game, you can contact the your local royalty collection agency and they will license it to you for a reasonable fee. Note, specify where you want to license it, for example "for worldwide distribution", since they either may not be able to grant that license or apply different fees.

Also a word about fair use. In your case, fair use may apply if you make a comedy or satire of something. Here is a quick primer on the issue: Fair Use School But note that this only applies to copyright, not trademarks and most characters in comics are trademarked. But you can work around this by using funny alteration of the make, so Super Man it not ok to use, but Supper Man is... (Supper Man, the hero that feeds the homeless ^\_^)

Finally a word about plagiarism. This is a difficult subject, since the comic books did copy many characters from each other; then again they had many legal fights too. Basically you can not make a super man clone, buy just swamping the names of things. So you can not have Ulta Man for the plant Zipton that exploded on his birth. You need to have a story, character and setting that is unique.
> 3 votes

---
Tags: legal, mobile, marketing, character
---


title: 3D Graphics Engine for Ruby on Rails

text:
# Question
Title: 3D Graphics Engine for Ruby on Rails
I've had a good few months of experience with Ruby on Rails, creating my own CMS system, a social network and even a VOIP enabled answering phone machine. I'm also an established 3D modeller, and what I really, really want to do is create a 3D game that's executed in the browser.

I'm not talking Crysis: Online or CoD: Online, or even Doom. Nothing too graphically/RAM intensive. Not a shooter. I simply want to create a simple puzzle solving, hidden object game that can be accessed in the browser.

Maybe something along the lines of the Myst III+ games.

http://www.youtube.com/watch?v=turE\_nFwXhM

Technically, they're very simple games, but by placing the camera inside a 3D sphere with its inner surface textured with an appropriately-distorted 2D rendering, they pull the player into thinking they're exploring a 'fully' 3D world.

They're not realtime, and I genuinely think this could be done online. Maybe some bandwidth issues with these high-res images, but by hiding loading screens behind doors that take a while to open, I think a seamless experience could be achieved.

So, is there a simple 3D engine for ruby? Open source, with a great community?

Apologies if you think I'm rambling, I've rambled in the hope that it'll give you a good feel for my technical requirements :)

# Answer
I think you are mixing up what the purpose of Ruby on Rails is for, and what the purpose of a game platform is for.

Ruby on Rails is for serving up and managing a web server, web-based content, and so forth - built very strongly around the whole idea of Model View Controller. And it ALL runs on the web server.

But a game engine is something that runs on on the player's machine. Which Ruby on Rails doesn't do.

What you can do though is use Ruby on Rails to manage the back end of your game. It can manage login authentication, keep track of player scores, leader boards, achievements, multiplayer matching, etc. I use it a lot professionally, and it's a great system for web servers and web services. At work we use it to serve up XML, JSON as well as special markup to the little touch screen front panel of some web-enabled printers.

As to what you use for the game engine, if you are looking for 3D, check out something like Unity 3D. It's free unless you're out to go for high end features and go commercial.

So don't lose hope in Ruby on Rails - it can be great for what you need to do on the back end of the game. But look into something else for the front end part.
> 1 votes

---
Tags: 3d, ruby
---


title: OpenGL - question about glColorPointer

text:
# Question
Title: OpenGL - question about glColorPointer
So, I'm just starting out with LWJGL, and my current task is to render two colored cubes on the screen. I can render them, however, I'm looking for some advice on the most efficient way to specify the colors. Currently, I'm doing this:

```
// specify vertices and colors
vertexData.put(new float[] { -0.5f, -0.5f, 0, 0.5f, -0.5f, 0, -0.5f,  0.5f, 0, 0.5f,  0.5f,  0, // 1st cube vertices
                             -1.0f, -2.5f, 0,    0, -2.5f, 0, -1.0f, -1.5f, 0,    0, -1.5f,  0 }); // 2nd cube vertices
colorData.put(new float[] { 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, // colors for 1st cube
                            1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1 } ); // colors for 2nd

```

In the render loop:

```
glVertexPointer(vertexBufSize, GL_FLOAT, 0, 0L);
glColorPointer(colorBufSize, GL_FLOAT, 0, 0L);
...
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); // 1st cube
glDrawArrays(GL_TRIANGLE_STRIP, 4, 4); // 2nd cube

```

This works, but I can't help but think that since I'm specifying the *exact* same color values for both cubes, I'm wasting memory. I was hoping to just have one set of vertex colors that could be applied to each cube that gets drawn. Can it be done? If so, what is the best way to do it?

Thanks

# Answer
Why don't split the vertex array into two arrays, each one for a separate cube, then you can share the color array between these two vertex arrays, like these:

```
firstCubeVertexData.put(new float[] { -0.5f, -0.5f, 0, 0.5f, -0.5f, 0, -0.5f,  0.5f, 0, 0.5f,  0.5f,  0});// 1st cube vertices
secondCubeVertexData.put(new float[] {-1.0f, -2.5f, 0,    0, -2.5f, 0, -1.0f, -1.5f, 0,    0, -1.5f,  0 }); // 2nd cube vertices
colorData.put(new float[] { 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1}); // color data

```

when you render, do:

```
glColorPointer(colorBufSize, GL_FLOAT, 0, 0L);
glVertexPointer(firstVertexBufSize, GL_FLOAT, 0, 0L);
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); // 1st cube
glVertexPointer(secondVertexBufSize, GL_FLOAT, 0, 0L);
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); // second cube

```
> 1 votes

# Answer
Don't worry too much about "wasting memory" - the key to good performance with OpenGL is not so much how much memory you use, but rather using the API properly and in the way it was designed to be used.

This means that sometimes you need to burn a little extra memory and this can seem counter-intuitive, particularly if you have a background/culture that emphasises frugality.

In this case you can certainly do what has been suggested in the other answer (i.e. share the same glColorPointer for each cube) but this is actually going to work against you longer term.

* You need to partially respecify vertex format and layout each time you draw anything which may lead to performance loss (you'll particularly feel this when you move to VBOs).
* You're unable to interleave your vertex data which will lead to performance loss.
* You're unable to index your vertex data, which will also lead to performance loss.

In the trivial case where you're just drawing a couple of cubes none of this is going to matter so much. As scene complexity and vertex counts build up, you're really going to be hurt badly by it, and this single initial focus on not "wasting memory" will prevent you from hitting anywhere near your potential max performance. You may even run as slowly as 10% of what you would otherwise be capable of.

The moral of the story is that coding stuff to run on a CPU is not the same as coding stuff to run on a GPU. If you take a programming mentality that is evolved around the former (and that has an emphasis on ultra-frugality derived from a time when limited storage was most likely to be your primary bottleneck) and try to apply it to the latter, you'll have a very high risk of being burned. That's not an absolute rule of course; I'm not saying that it's OK to needlessly use extra memory all over the place; I am however saying that what looks like "wasting memory" from one perspective may well turn out to be just "using a relatively small amount of extra memory in exchange for gaining a relatively large amount of extra performance" from the other.
> 1 votes

---
Tags: opengl
---


title: Picking 3D with OpenGL ES 2

text:
# Question
Title: Picking 3D with OpenGL ES 2
I'm trying to implement picking in my framework but I don't understand how I can do this.

**I'm working with:**

* OpenGL ES 2.
* GLM mathematic library.

**What I have understand, picking can be made with two methods:**

* Draw scene with one color per polygon, and read pixel under mouse.
* Ray projection in 3D and finally calculate geometry \<-\> ray intersection.

**My architecture:**

* A Geometry class with indices/vertices/texture coords/colors data.
* A Scene class with a Mesh array (using a geometry).
* A Transformable class with Matrix computed with rotation/position/scale.
* A Camera class with methods like getViewport/….

**What I have:**

*My ray calculation:*

```
void Ray::createFromEvent( const Camera& camera )
{
    glm::mat4 model         = camera.getMatrix();
    glm::mat4 projection    = camera.getProjectionMatrix();
    glm::vec4 viewPort      = camera.getViewport();

    this->origin = glm::unProject(  glm::vec3( x, y, camera.getMinDistance() ),
                                    model,
                                    projection,
                                    viewPort );

    this->direction = glm::unProject(   glm::vec3( x, y, camera.getMaxDistance() ),
                                        model,
                                        projection,
                                        viewPort );
}

```

So, my questions are:

* How can I calculate intersection with my scene geometries?
* It's better to calculate if point is inside a bounding box or ray traversing a bounding box?
* How can I compute bounding box with Transformable matrix (rotation, scale, …)?

(I am on mobile so I am limited by hardware performance.)

Thanks!

# Answer
> 1 votes
> How can I calculate intersection with my scene geometries?

it varies depending on your performance needs and scene size, there are different approaches the easiest one is checking ray intersection with all bounding volumes containing geometry in the scene, however this may not be good enough if your scene is huge, or you have limited computational power. Other approaches usually use Hierarchical scene structure hence eliminating most of the intersection possibilities, two examples are using K-d trees or bounding volume hierarchies (each one has its own Pros. and Cons.). good resource for this is the book "Real Time Rendering" and its companion website http://www.realtimerendering.com/.

> It's better to calculate if point is inside a bounding box or ray traversing a bounding box?

Well a ray has a starting point, and direction you can test if the origin is in the bounding box, but "usually" this will be a redundant step since most well known tests cover this already. One method for testing Ray AABB and OBB is called SLABS Method and is well covered in real time rendering.

> How can I compute bounding box with Transformable matrix (rotation, scale, …)?

AABB is Axis Aligned hence cannot be rotated, so you need to use Oriented Bounding Boxes (OBB) you can check a lot of details about intersections tests and bounding volumes here http://www.realtimerendering.com/intersections.html

---
Tags: opengl, mathematics, picking, glm
---


# Question
Title: How are the following 3D effects mocked in Myst 4? (link)
Superficially, I thought 'all' that would be required to make a myst style game would be to place the camera inside a 3D sphere, with the sphere's inner surface textured with an appropriately-distorted (to account for the concave nature of the sphere), 2D rendering of a 3D world.

The only thing that I can't really work out is how are some elements of the game alive and moving?

In this video, the sea waves are moving: http://www.youtube.com/watch?v=ju0lACSm7Us

In this one we have some pretty cool particle effects involving clouds, as well as lighting, thought I think the lightning is pre-rendered: http://www.youtube.com/watch?v=\_CidCIDHFL4

I doubt these effects are actually 3D; I think they are 2D looping movie files. However I could be wrong.

To clarify, how do you think they've achieved such gorgeous 3D effects regarding the **water**, **clouds** and **lightning**?

Are they looping movies? How are these movies presented to the user and integrated so well?

# Answer
> 2 votes
One way to make such an effect is UV animation.

The UV is a texture coordinates, as XYZ is the objects coordinates, what is done here is simple. Given the following texture with the mention that it needs to have an alpha channel so that we can exclude the blue color and leave just the clouds, it is going to be applied to a quad

Let the upper left corner be (0,0) in texture coordinates be the starting poing. What it is being done: **a step X is taken and the starting point of the UV texture is incremented at each frame/update giving the illusion of animation.**

To achieve different effects, different textures are "displaced", for the clouds the diffuse texture, for the water the normal texture given it is a flat quad with only reflection.

For the lightning it's just a simple texture with alpha and perhaps some additional calculations being done in the fragment shader.

---
Tags: 3d, animation
---


# Question
Title: adding space between each bricks in breakOut
i am trying to create breakout. code below loop though my 2d array(map) and creates bricks. the problem is that i want to add 10 pixels space between each bricks. i was thinking to add x\*titleWidth+x+10 in side blockobject but it moves all of the bricks and there is no space in between. any ideas?

```
for (int y = 0; y < map01.length; y++){  //row
for (int x = 0; x < map01[y].length; x++){ // cols
    if(map01[y][x] == 2){  //Bricks
        blockObject = new Block(x*tileWidth+x, y*tileHeight+y, tileWidth, tileHeight);
    }
}

```

}

# Answer
> 1 votes
If you want to add a transparent border to each block, then you need to increase the space needed for each block:

```
x * (tileWidth + 10) + x

```

This probably won't be exactly the look you want, but it'll point you in the right direction :)

# Answer
> -1 votes
Which view are you working in? I could probably get it to work in XNA, if I knew a bit more about your code.

---
Tags: mathematics, software-engineering
---


# Question
Title: Why spritebatch.Draw shows blank output?
In my code below, I think it's correctly done. But idk, the image called by \_bg is does not shown up. The screen only show White. Weirdly, there is 0 error message when I run it.

(The RenderTarget2D is for default-ing my view into landscape mode)

```
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace GameName2
{
    /// <summary>
    /// This is the main type for your game
    /// </summary>
    public class Game1 : Game
    {
        GraphicsDeviceManager _graphics;
        SpriteBatch _spriteBatch;
        Texture2D _bg;

        public Game1()
        {
            _graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
        }

        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            // TODO: Add your initialization logic here

            base.Initialize();
        }

        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            _spriteBatch = new SpriteBatch(GraphicsDevice);

            _bg = Content.Load<Texture2D>(@"background");
            // TODO: use this.Content to load your game content here
        }

        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// all content.
        /// </summary>
        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
        }

        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {
            // TODO: Add your update logic here

            base.Update(gameTime);
        }

        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.White);

            // TODO: Add your drawing code here
            _spriteBatch.Begin();
            _spriteBatch.Draw(_bg,
                new Rectangle(0, 0, Window.ClientBounds.Width, Window.ClientBounds.Height),
                null,
                Color.White,
                0,
                Vector2.Zero,
                SpriteEffects.None,
                0);
            _spriteBatch.End();

            base.Draw(gameTime);

        }
    }
}

```

I use xnb file. And I put it in Content folder in the project. I've set 'Content' and 'Copy if newer' to the file property.

This is the .png file I use before converted into xnb:

Or maybe the problem is in my .png file?

Any idea?

# Answer
You should be using *GraphicsDevice.Viewport* instead of *Window.ClientBounds* when working with your SpriteBatch.
> 1 votes

---
Tags: xna-4.0, xna-content-pipeline, monogame, windows-phone-8
---


# Question
Title: Playing different particle effects in Unity on the same ParticleSystem
The question really sums it up: What is the best way to use one particle system for playing different particle effects?

The scenario: GameObject is picked up and it starts playing a simple indicator particle effect. If the GameObject is placed on a special platform it will play another particle effect.

I have very little experience with particle systems - how would you do this?

# Answer
Attach two GameObjects to one parent, each with a ParticleSystem, and just activate/deactivate them as needed.
> 4 votes

# Answer
It depends on a situation. If you have only two different particle systems that you want to use, Nevermind's answer with two different child object is definetly the best. However, if you want to use a lot of different particle systems (for example, if you making an RPG with a lot of spell effects), you may want to instantiate/destroy (or better, take from object pool and put back there) particular particle systems each time for each such event.
> 1 votes

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


title: Specifying 3D objects in a game

text:
# Question
Title: Specifying 3D objects in a game
I have hands on experience in OpenGLES 2.0 , OpenGL and wish to apply the same in a 3D game development in Android. My idea is to develop a Combat game having fighter planes. I am trying to create a 3D mesh for plane. Right now I am creating a model by myself so that I can keep the polycount low.Here z-axis is my reference i.e. the object is symmetric about z-axis. But when I apply rotation the depth test causes the components to look incorrect. Using z-axis as reference will make my ModelView matrix less expensive in terms of computation. How does one typically specify 3D objects in games ? Is .obj a good alternative ?

Also if you guys can provide some basic tutorials that will be great.

# Answer
> How does one typically specify 3D objects in games ? Is .obj a good alternative ?

.obj is one of the easiest 3D formats to parse if you're doing it yourself. You can also export it from just about any modeling software. (I recommend Blender, but whatever you do, definitely don't do it yourself in code).

However, it sounds like you might be just starting out with this stuff, in which case I recommend you find and use a game engine (maybe start here) rather than trying to figure things out on your own. These problems have been solved a million times by thousands of other people, so why not use their work to your advantage?

Just an interesting side-note here:

> Using z-axis as reference will make my ModelView matrix less expensive in terms of computation.

I doubt that. It's generally more expensive for the graphics card to do an early-out test that checks for special cases (like z-axis aligned matrices) than it is to just do the multiplication. This is because GPUs are heavily parallel and pipelined, to the point where basically every time you do a branch, both paths are actually executed, and the "wrong" branch path just gets discarded.

At any rate, even if there were a performance benefit, it would not be noticeable at all, even with a very advanced profiler.

My advice is, don't worry about performance until it becomes an issue. Pre-mature optimization is a common trap developers fall into.

Anyway that's my two cents. Good luck!
> 0 votes

---
Tags: game-design, game-mechanics, opengl-es2
---


# Question
Title: Realtime fisheye to cubic or spherical panorama transformations with OpenGL or pixelshaders
I'd like to transform a sequence of circular fisheye-images to cubic or spherical panorama images to be used in a panorama-viewer based on OpenGL. The viewer-part is nemas problemas but the transform from fisheye to panorama is not my usual cup of tea. I was kind of expecting a google would solve this, but so far I have come up with next to nothing. What would the preferred method be? OpenGL or pixelshaders?

The image sequence is coming from a camera so it has to be done in realtime (or as fast as possible). I have used PanoTools for Photoshop before so I know a little about the process, but not much about the math behind. Any kind soul out there who could get me started? Any resources that could be useful? This can't be something new but I guess it's not that common either. Anyway it's a fun project ... =)

Update:

Found this awesome online shader-laboratory: https://www.shadertoy.com

Just too bad I can't add my own image-inputs here...

# Answer
Since you're going to have a real-time panorama viewer anyway, it seems to me you could configure your panorama viewer to view the fisheye images directly. There is no need to convert them to a cubemap or lat-long format first.

A panorama viewer works by drawing a mesh of some shape (e.g. a cube or sphere) around the camera, and setting up texture coordinates on the mesh such that the image gets wrapped around the mesh in the same mapping used to generate the original image. So viewing fisheye images with it is just a matter of coding up the right mapping. I would suggest building a reasonably tessellated hemisphere and mapping spherical coordinates on the hemisphere to polar coordinates around the center of the 2D fisheye image. No pixel shaders will be needed, just standard texture mapping.

You will need the right mapping between the radial coordinate of the fisheye image and the polar angle of the sphere. Unfortunately, there is no standard fisheye mapping - there are several variations that are all called "fisheye". Wikipedia describes some. The docs for your lens might say what kind of mapping it uses, or you might just have to experiment a bit until things look right.
> 2 votes

# Answer
The image you provided even simplifies the whole thing.

What you are looking for is called polar to rectangular coordinates transformation. It's very simple.

You can find some reference here : http://www.cliffsnotes.com/study\_guide/Polar-Coordinates.topicArticleId-11658,articleId-11630.html

No point in me going over the topic again as it's avaialable everywhere :)
> -1 votes

---
Tags: opengl, transformation, fragment-shader, skybox
---


# Question
Title: Creating shattering effects without having to use actual physics?
For certain effects like glass shattering and falling objects cracking to reveal their inner contents, are there any tricks or ways to implement these fracture physics without having to use actual physics simulation? Also, what are the trade-offs if I don't use real physics simulations?

Since the effects don't really require exact simulation, an actual physics simulation may be too expensive and wasteful.

# Answer
I assume by "real" physics you really mean "realistic" physics. In almost every game that includes physics, unless it is a key feature of the game, the developers will take shortcuts to reduce processing time.

Quick answer: fake it with an animation.

Little longer answer: Reduce the number of pieces you process. You'd be surprised by how much time you save by processing half the number of pieces. Also having the objects pre-broken, meaning the interaction with the user doesn't determine where in the object the fracture is, will reduce processing time.

Trade offs for faking:

1. Doesn't look real
2. Not very dynamic
3. I'm sure there's others

Trade offs for reducing number of pieces:

1. If you are using realistic physics the player may not even notice.
2. Still can be dynamic.
3. Simulated physics.
> 5 votes

# Answer
In X Men 2, Magneto shatters his glass prison with several marble sized metal balls, youtube.

In the DVD commentary the designers explian how they did the breaking effect. It was too computationally intensive to fully simulate it, instead they had an artist determine where the breaks would be (and where they'd look good). Then they scripted when the pieces would detach, the falling glass shards were physically simulated.
> 2 votes

---
Tags: physics, simulations
---


# Question
Title: How do I go about creating the "Watcher" component?
Last weekend, I spent several hours writing a basic entity component model, in JavaScript. I was largely referencing the Ash Actionscript game engine. I successfully worked out how the systems, components, nodes, and entities all link up, but one thing that eludes me is how to implement the "watcher" that checks the entities for their components, creates nodes for them, adds those nodes to the various systems automatically, and watches for any changes in the components on an entity. I was a bit confused by the way it works, in Ash, and all of the posts and tutorials on the subject that I have read seem to forgo the details of that part of the implementation.

Right now, I currently have the following:

* Entity, which is assigned components.
* Engine, which keeps a track of the systems and entities.
* Node, which contains references to the components in an entity that we want the system to modify (I am currently creating these, manually, and adding it to the system).
* Component, which contains the data to be modified by the system.
* System, which operates on the nodes, which in turn change the data in the entity.
* I also have various other classes, dedicated to holding lists of the various objects.

How do I go about creating the "Watcher" component?

# Answer
> 1 votes
I think simplicity is key when designing these systems. What I do is associate a bitmask with each entity where each component type corresponds to a bit; the bit is switched on if the entity contains a component of that type. I give the entity/component manager a couple of helper functions to change the bitmask when adding and removing components.

If you associate each system with a component bitmask as well, it is trivial to build the set of entities to be processed by a given system. You can then do one of two things:

1. Make each system loop through all entities each frame, skipping those that do not satisfy the system's component requirements.
2. Each frame, check the entities which have been modified and loop through all the systems, registering the entity with each system that is able to use it.

To store the components, I use a struct-of-arrays approach where each component type is an array (possibly with another layer of indirection) and each entity is an index into all the component pools. All the systems have access to this data, and accessing components is as easy as `world.type[entity]`.

# Answer
> 0 votes
It's difficult to figure out exactly what you need, but it seems like you want to use something similar to the Observer Pattern or the Publish-Subscribe Pattern.

Basically your entities would become observers/subscribers and your "watcher" would be the subject/publisher.

---
Tags: entity-system
---


# Question
Title: How to detect a touch on transparent area of an image in a (libgdx) stage?
Can some one please help to detect a touch on an image which I am using as an actor in a stage. The image is actually a long diagnol brush which has plenty of transparent area. The problem is when I touche the transparent area of the brush image it is also triggering the clicklistener of the image. I need the click listener should only be called when the finger actually touched the visible image not the area which is empty.

I am using libgdx-0.9.4 libraries. Here is my simple piece of code.

```
import com.badlogic.gdx.scenes.scene2d.ui.Image;
import com.badlogic.gdx.scenes.scene2d.ui.ClickListener;

Image brushImg = new Image(ImageCache.getTexture("brush"));
brushImg.width = mStage.width()*0.75f;
brushImg.height = mStage.height()*0.75f;

brushImg.setClickListener(new ClickListener() {

@Override
public void click(Actor actor, float x, float y) {
    SoundFactory.play("brush");
}

```

# Answer
> 7 votes
If you'll keep the Pixmap object you'll be able to check for the alpha component in the relative location. Try the following code:

```
final Pixmap pixmap = new Pixmap(Gdx.files.internal("brush"));
Image brushImg = new Image(pixmap);
brushImg.width = mStage.width()*0.75f;
brushImg.height = mStage.height()*0.75f;

brushImg.setClickListener(new ClickListener() {

@Override
public void click(Actor actor, float x, float y) {
   int imageX = (int)(x/0.75f); // relative pointer location
   int imageY = pixmap.getHeight() - (int)(y/0.75f); // relative pointer location
   int pixel = pixmap.getPixel(imageX, imageY);
   if ((pixel & 0x000000ff) != 0) {
      // Hit
   }
}});

```

# Answer
> 1 votes
I've no idea if this is an efficient way of doing things with libgdx, but you could use a rotated, transparent `Button` that would cover the solid part of your brush, and set you click listener on it.

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