title: Destructible Enviroments

text:
# Question
Title: Destructible Enviroments
I've got my own game engine, now rendering and animating, MD2 MD3 and MD5 models now. I feel i am only just starting to get comfortable with opengl.

I'm currently writing code to render Quake 3 maps now too but, i would love to know how games like red faction allowed for destructible environments. Not quite sure, where to start with this. If i render a map do i have to turn the map into constitute components where by a physics engine controls every brick in the map or something maybe someone could tell me where i should look or read would be great. Thanks.

# Answer
> 1 votes
This is a wery Advanced and complex subject, But there is (Luckily) some resource on how to achive this. I cant say with a straight arm which one is the best. My best suggestion for you is to read some article about it and later try something out, see if it works and if you can get it in a manageable state.

And the best idea on how i would do it is to have a geometry shader spliting a specific mesh and restiching it after it's been destroyed. This of course comes with bad memory consumptions since you are probably going to need a copy of the orginal mesh and then a second one for each destruted object. But there is always stuff to improve.

And here are the good links :
DICE This is basicly how my idea also would be. DICE DESTRUCTION
A Good read on a White paper : White paper

# Answer
> 12 votes
There are many many ways of doing this in games and simulations in general. No one technique will ever be the best as they all have their place.

In general, destructible material goes along with the subject of soft body simulation.

I will assume from here that you have some form of rigid body physics engine which can detect collisions and resolve forces.

## Precomputed Fractures

Take a mesh and slice it up into nice pieces before even running the game. Connect them with joints in your physics engine and split those joints dynamically based on the item used to fracture the object.

Don't use the joined mesh until you have to. Use the un-fractured version until it's hit with a certain impact/weapon then quickly swap the models, break the joints and let the physics engine take over.

This gives you great control over what can break and how it can break. Truly dynamic fracturing could cause unexpected results and in certain circumstances prevent the game from continuing. Imagine if a pillar broke only just enough to block the exit and the player had no more rockets.

To give it the appearance of being dynamic simply use a mix bag of variants. The physics engine will make the pieces move nicely based on impact point and weapon used anyway.

## Material Point Method

You can fill your object with a cloud of particles and then augment your mesh based on how these particles move internally. This is often used in soft body or fluid simulations and allows for things to bend, dent, melt etc.

The particles should be bonded together and, when appropriate, these bonds should be broken. When they are the mesh should be split between these bonds.

The way in which things break can be defined through the bonds being used between the particles. Tougher materials like metal can have stronger bonds. Also, you can use different bond definitions with the same object to have it act differently based on the material it's supposed to be made of.

This is an all-round technique, but it's especially good for natural soft things like organic materials. The main issue is the computational load it adds resolving all those particles.

## Voronoi

Voronoi fracturing is probably the one I like best. This is simply a technique for splitting the mesh in an interesting way.

It looks nice for structural environments and seems fairly straight forward. This technique will help define fracture lines alone which new polys should be added to the mesh.

The advantage to the example in the link is the decomposition into convex shapes. Convex shapes are required for some physics systems, especially those based on the separation of axis theorem.

## Finite Element Method

FEM is basically about breaking the problem down into small pieces. In this way the particle method above falls into this category, and is considered an "FEM based particle method".

Commonly in FEM the object is represented by a simplified triangular mesh cage which is used as a deformer for the main object mesh. The triangles are dealt with in a fairly individual way to determine how forces work upon them before working out how they impart force onto adjacent triangles.

One difficult part here is how you describe the material used in each triangle. This will determine how the triangle responds to various forces/effects and can make the difference between the simulation seeming real and looking terrible.

This method you will find all over the place and is used in high detail for modelling complex simulations for use in engineering. A common example is modelling how an impact affects a car and those inside it, so various designs can be tested before a working prototype is put through crash testing.

This is mostly a technique for breaking your problem down into managable sets and it's expandable to simulate many physical phenomenon, such as heat transfer or fluid movement. You should be able to find many articles, and probably sample code, around the place, but here is a place to start.

## Conclusion

This is a massive topic and will require a lot of research before picking the method you like for your purpose. My main advice is to remember that we are making games, not simulation software, so whichever method you use in the end, make sure it looks good, plays well, remains stable/bug free and, above all, is really good fun.

# Answer
> 0 votes
I'm doing something similar.

What I'v done until now is to have

* a procedurally generated terrain
* a structure of the world which could fit my needs (a 3d matrix or an octree)
* function to modify the base structure (i.e. a dig() function which for example removes a quantum of cells from the world structure)

If you never dealt with procedural generation of terrain, you should indeed read some arcticle, because it is a very broad subject. You should choose algorithms depending on your needs of preformance/precision/speed/etc. Basically you have to choose an algorithm for pseudo randomly generate the structure and then another one to render it.

I will link you something I found of interest which could help you out as I have a little more time to re-arrange things. By the while you could start reading something more generic about procedural geenration of terrain. Then I will link documentation I refered to about `Perlin/Simplex` noyse algorithms for pseudo random generation and `Marching Cubes` and `Marching Tetrahedra` algorithm for rendering (for which you could start looking by yourself)

Try to read this about Simplex noise

Try this about Marching Cubes

---
Tags: destructables
---


# Question
Title: When should rendering be performed during a frame?
When working with OpenGL or DirectX, should draw calls be done all at once, at the end of the update loop, or is it better to have draw calls occur during the update loop rather than just at the end?

# Answer
You should strive to ensure your *updating logic* (that is, the logic of your actual game) is decoupled from your *rendering logic*. This is the single responsibility principle, a key tenet of good engineering design. This will make your interfaces more resilient to change and maintainable in the long run, and that should be a high priority.

That said, you can still keep to the SRP and have a system where you interleave update and render operations for your objects. At a very high-level, in pseudo-code, this might look like:

```
foreach(object in the game) {
  object->update();
  render_description = create_description_of(object);
  renderer->draw(render_description);
}

```

Now, whether or not you *should* do this is a different question. Certainly, if you game and its render needs are simple enough and you prefer this style for some reason, you can create a game that way. But as the complexity of a project scales, you can run into some issues:

* Since you are performing heterogenous operations, this approach does not lend itself well to splitting across multiple threads to take advantage of the corewise-scaling that modern CPUs provide. Concurrency is the way of the future and you should design systems to at least allow for the possibility of utilizing it in the future.
* While you are not tightly binding the update and render APIs, you are tightly binding their processing order. This can be problematic if your rendering needs are more complex, such as requiring multiple passes (where you generally would want everything rendered from pass one before you start on pass two), or simply different processing order for render objects (for example, transparent objects should be rendered after opaque ones and in depth-based order).

While you can work around the above (and the host of other smaller irritations, such as an increased difficult in keeping update and render timesteps distinct), it starts to make your code and the logical flow of your program more confusing, for a very minor potential benefit (it's possible you could achieve better CPU and GPU load balancing this way if you issue non-waiting render calls; but again, there are other solutions to that).

For this reason, most games prefer to do all their logic updates in one batch, followed by any and all rendering operations required.
> 4 votes

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


# Question
Title: How can I create my own GameTime for timing things in my game?
I have a `Game` class and a `GameComponent` class. I want to perform operations inside the `GameComponent` class which depend on calling `gameTime.ElapsedGameTime.TotalSeconds`, but I've noticed that that value is always 0.

At the moment I am initializing `gameTime` inside the `GameComponent` class by doing `new GameTime();`

I had the thought that somehow I should take the `gameTime` variable of my `Game` class, but I was not able to find a way to do so. I had always used `Update(Gametime gameTime)` and `Draw(Gametime gameTime)` methods in the past, which automatically gave me a game time object.

Now, that I need to deal directly with `gameTime` to run my own timing information, I see that it is a little tricky because I don't understand how it works properly. How can I create a timer for my own use?

# Answer
`GameTime` is not a timer. It's an object representing timing information sampled at one particular point in time (from something that *is* a timer).

If you need a timer, consider using the `Stopwatch` class. Using a `Stopwatch` is very straightforward:

```
var timer = new Stopwatch();
timer.Start();

... do things, read the value of timer.Elapsed or whatever...

timer.Stop();

```

`Stopwatch` also support resetting the elapsed time, pausing, and so on. The `Elapsed` property returns a `TimeSpan` which you can use to initialize a `GameTime` object if you really want.
> 1 votes

---
Tags: c#, xna-4.0
---


# Question
Title: Retrieve variable from another class and send to another scene in Unity
Sorry for asking a noob question, but I have never used c# in Unity, only unityscript.

Basically I have a `public int score` variable stored in `Players` Class.

I need to retrieve it in the following method:

```
void OnTriggerEnter(Collider c)
{
    if(c.tag == "PlayerCollision")
    {
        if(!c.gameObject.transform.parent.gameObject.GetComponent<Player>().isDead)
        {
            Debug.Log("Hit");
            //Load next scene
        }
    }
}

```

How can I retrieve the `score` variable in this method below and send the variable to the next scene? (In unity script I had to do something like `Application.LoadLevel(1);` after of course building the scene as levels. Thanks

# Answer
I think the simplest way would be to make the variable `static`. Eg.

```
public static int score

```

Then you could access it any time using `Players.score`. There are other approaches such as singletons, but I think that would be overkill.

If you have several variables like this, you could decouple them into a helper class and access them all from there.
> 0 votes

# Answer
Set the script to an object and set this in the script:

void Awake () { DontDestroyOnLoad (transform.gameObject); }

Your object pass all scenes and you can give their variables these values you need in the other scenes.
> 1 votes

---
Tags: c#, unity, scene, unityscript
---


# Question
Title: theoretical solution for "drawing" with mask
So am trying to create a make-up game and i need to have a basic drawing solution, and so far i have made a good progress with the help of the DepthMask solution
My approach was like this : suppose we want to edit the eyelash color (texture)

1-in the beginning there is an eyelash object at a layer named old 2-after choosing the new color that we will draw with, a new game object is created under the first eyelash, which mean it's invisible for the moment 3-then when we start drawing, we are actually creating little circles above the old eye lash, these circles contain the depthMask shader which effect the old eyeLash and give the impression that we are drawing with the new color

So far, everything is going great, my problem is that i cannot use this approach to use a 3rd color, suppose the player want to create an eyelash with mixed color, how can i do that with the previous solution ? or is it impossible to do ?

**EDIT:** I already thought about adding new layers with each new color, and it works, but since unity is limited to 31 layers, this solution can never be a good one.

I really hope someone can answer this, and if you know a better way to do it then please don't hesitate to tell me.

**EDIT2:** After a couple of hours, i've reached a pretty cool result, and i think that this can be the good way to reach my goal, this script allow to replace a specific pixel in a material texture with another chosen texture (target texture must be in the same size, and readable)

```
// the texture that i will paint with
public Texture2D targetTexture ;
//temporary texture
Texture2D tmpTexture;

void Start ()
{
        //setting temp texture width and height
        tmpTexture = new Texture2D (targetTexture.width, targetTexture.height);

        for (int y =0; y<tmpTexture.height; y++) {
                for (int x = 0; x<tmpTexture.width; x++) {
                        //filling the temporary texture with the target texture
                        tmpTexture.SetPixel (x, y, targetTexture.GetPixel (x, y));
                }
        }
        //Apply
        tmpTexture.Apply ();
        //change the object main texture
        renderer.material.mainTexture = tmpTexture;

}

```

Now i think that the problem will only be, "*how to know which pixel i should replace based on mouse position over the object ?*"

Thank you very much and have a great day.

# Answer
> 1 votes
To achieve this effect you just have to verify which pixels are affected by a brush stroke and play a little with them in a post processing fragment shader with alpha blending enabled.

***Brush stroke:***

For smoothness, the brush strokes can be simulated by a spline generated using the mouse positions reported while doing the stroke.

***Rendering***

After updating the brush stroke, do the usual rendering of the scene using the current person face state.

***Post processing***

* Acquire the sampled points in the spline and use them as centers for circles. You can as well get other points in the spline with better displacement to ensure a good distribution.
* For each pixel verify if it is inside the radius of any circle.
* If this is true, assign an alpha value for that pixel and use usual alpha blending with the current scene texture generated before post processing. This step will mix the colours of the brush and the face.

---
Tags: unity, masking
---


# Question
Title: Update and Render logic with interpolation
I am working with C and SDL2 and just wanted some insight as to how to properly apply interpolation to the rendering.

**EDIT** \- some clarification, `update()` `input()` and `render()` are just hypothetical stubs, the real code is messy and long as I learn SDL2.

```
while (!quit) {
    current = SDL_GetTicks();
    elapsed = current - previous;
    previous = current;
    lag += elapsed;

    input();

    while (lag >= ms_per_update)
    {
        update();
        lag -= ms_per_update;
    }

    interpolation = (float)lag / (float)ms_per_update;

    printf("Interploation: %f\r\n", interpolation);

    render(interpolation);
}

```

This is something that has always kind of baffled me -

lets say that in `update()` if `SPACE` pressed we start a jump animation and movement. So `sprite.y += 2` to move it.

Where does that movement of one pixel happen? Does it happen in `update()`?

If the movement happens in `update()` then how do i properly apply the interpolation in `render()` since my item has already been moved (during the update)?

* Lets say i have a bullet at (x=10, y=10)
* It's velocity is 10 pixels per update.
* use clicks button to shoot
* first update bullet is moved to (x=20, y=10)
* render(interpolation) // lets say it is 0.5) // lots of on screen lag from awesome effects
* second update bullet is moved to (x=30, y=10)
* third update bullet is moved to (x=40, y=10)
* render(interpolation) // lets say it is .09 from lots of lag

How is the interpolation value applied to the bullet so that it appears to pass smoothly across the screen. **What information is known during render to apply the interpolation?** Would a struct containing the origin point, current velocity (or amount moved since last render), and current location suffice?

# Answer
> 2 votes
Basically, you have to store the two most recent "snapshots" produced by the update step. These snapshots have all the information needed to render the scene, such as the positions and rotations of all your sprites.

To properly interpolate, the rendering system time lags behind real time by the interval of an update, so if your game updates at 50Hz, the rendering system is behind 20ms. This ensures that the rendering time lies between the snapshots.

To render the scene, you interpolate between the snapshots. Be wary that objects that are orbiting something extremely quickly will be rendered incorrectly if you interpolate between their positions and not their polar coordinates relative to the center of their orbit. You could also integrate acceleration and velocity to more accurately interpolate, but if you're going to go this far you might as well just run your update step more often.

---
Tags: sdl, c, interpolation
---


# Question
Title: Why aren't resources such as Pixmap disposed on finalization in LibGDX?
I've been looking at the LibGDX framework, and certain classes such as Pixmap require to be disposed manually when you are no longer using them (call the dispose method).

I'm wondering, since this is Java, why did they not choose to dispose the resources on Pixmap finalization? That is, override the `finalize` method to automatically call `dispose`. If an object is finalized, then that means that the Garbage Collector determined no hard references to it, so clearly no one is using the Pixmap and it is fine to dispose it.

What particular advantages are there to calling it manually rather than use the finalization method?

# Answer
You may want to read up on this SO question to get some background information. That is:

* Java GC is nondeterministic
* You cannot force the GC to run at a certain point, only give it hints to run (which it may ignore)

In libGDX (if not gamedev in general), this is bad for two reasons:

* GC may sometimes run for a long time, causing a noticeable pause in the game
* You may have limited memory resources, especially on mobile platforms, so you want to force some deallocations to occur at specific points

For these reasons, it's in your interest to avoid long GC runs during gameplay, which means controlling when you deallocate expensive resources such as those encapsulated by Pixmap, for example deallocating during loading screens.
> 3 votes

# Answer
LibGDX avoids a problem with android wherein the OpenGL context can simply vanish over the course of running the app. If that happens, video-memory assets are lost. LibGDX fixes this problem by keeping the original objects in normal ram. That doubles the memory cost, but it allows the video memory to be repopulated from the other copy.

But in order to keep those assets in memory, they must not be disposed of randomly by the GC. That's why the responsibility falls to the API user to dispose them manually.
> 1 votes

---
Tags: java, libgdx, design-patterns, memory-efficiency
---


# Question
Title: Universal Tween Engine: are accessor hierarchies possible?
Background: I'm using Universal Tween Engine, which allows generic accessors to be implemented to permit tweening of arbitrary atttributes.

I have a hierarchy of game entity classes that share a common base class (say, Entity). I've implemented a TweenAccessor on Entity for basic attribute tweening (position, color, rotation, etc). I'd also like subclasses of Entity to be able to implement their own, more specialized tweens, in addition to having access to Entity's base set of tweens. However, it seems that when I register a class and a subclass accessor, the base class' accessor is never called during tweening.

For example, assume base class Entity and subclass Bullet:

```
Tween.registerAccessor(Entity.class, new EntityAccessor());
Tween.registerAccessor(Bullet.class, new BulletAccessor());

```

Attempting to do any of the tweens defined in EntityAccessor will not be called -- BulletAccessor will always be used instead. Is there any way to configure Universal Tween Engine to work in such a hierarchical fashion?

# Answer
Although it's a little awkward, I ended up having subclasses' accessors compose the parent accessor as a member and have getValues/setValues fall back onto it if no tween is found.

```
public class BulletAccessor implements TweenAccessor<Bullet> {

    private EntityAccessor entityAccessor;

    // Special care needs to be taken to ensure these values don't
    // overlap with any of the parents' or their tween accessors.
    public static final int SOME_PROPERTY = 50;
    public static final int ANOTHER_PROPERTY = 51;

    public BulletAccessor() {
        entityAccessor = new EntityAccessor();
    }

    @Override
    public int getValues(Bullet bullet, int type, float[] values) {
        switch(type) {
            case SOME_PROPERTY:
                // ...
                return 2;
            case ANOTHER_PROPERTY:
                // ...
                return 1;
            default:
                return entityAccessor.getValues(bullet, type, values);
        }
    }

    @Override
    public void setValues(Mob mob, int type, float[] values) {
        switch(type) {
            case SOME_PROPERTY:
                // ...
                break;
            case ANOTHER_PROPERTY:
                // ...
                break;
            default:
                entityAccessor.setValues(bullet, type, values);
                break;
        }
    }
}

```
> 0 votes

---
Tags: java, libgdx
---


# Question
Title: Multiple resolutions for Unity 2D Android game
I'm trying to target as many devices as possible by providing a consistent experience. So I'm trying to make sure the aspect ratio fits each device it's played on.

After reading some forums and tutorials related to this topic I found that to create a game which runs without creating any black bars on the sides, I have to use multiple resolutions. So my question is how to use multiple resolutions in Unity 2D?

# Answer
> 4 votes
Asset resolutions and aspect ratios are two different problems. I don't have any experience with Unity, but this is a platform agnostic problem.

\< Disclaimer \> This is my approach - it might not be the best but it works fine for me. \< /Disclaimer \>

---

**Asset size/resolution handling:**

Have a few sets of predefined resolutions (for example: mobile, tablet, desktop and retina size).

Then you have two options:

* include the right assets when building for the specific platform
* include everything but load what you need based on the screen resolution

The first approach requires customizing the build/package process but it gives a significantly smaller file size. The second doesn't require any modifications to the build/package process but requires runtime logic to decide which asset to load and gives a bigger size. I would recommend the first one.

---

**Aspect Ratio**

This heavily depends on the type of game you're actually making. For a competitive game, you every player should see the same because you don't want to give advantage to users with a certain aspect ratio. The best way to achieve this is to take the most "extreme" ratio supported and model everything according to it. Usually, you lock either the horizontal or the vertical axis and fill the other with something visually appealing but non interactive. On a side scrolling example:

* you decide that 16:9 is the most extreme resolution you support
* lock the horizontal axis so it always fills the length of the device
* on devices which have more vertical space (for example, 4:3) fill the top, bottom or both with extra non-interactive graphics

---
Tags: 2d, unity, graphics, resolution
---


# Question
Title: How do I find two points at an angle on opposite sides of a circle?
With reference to my previous question:

I'm using micklh's answer, which works perfectly. However, it calculates the gradient based on two points, a *starting point* and an *ending point*. I want to **change that** such that I can give it a *center point*, an *angle in degrees*, and a *length*.

If you look at the picture from the other question:

You can sort of discern where the center point is, the x,y of starting/ending locations become the dots based on the length of the gradient.

I assume I would have to:

1. Take the center location
2. Apply the angle + length
3. Gives me my ending x,y
4. Take the center location
5. Calculate the reverse angle
6. Apply the reverse angle + length
7. Gives me my starting x,y
8. Plug these starting/ending positions to the answer from the other question.

Am I correct? How would I do those steps?

# Answer
You might want to briefly refresh your trigonometry (maybe by reading the overview at Wikipedia) if you're stuck.

Your problem looks like this:

Keeping that picture in mind, we can take essentially the same steps you described, but in a more mathematical form:

As **inputs**, you have a centre point `p0` (red) and an `angle` (blue) and a `length` (orange).
As **outputs**, you want two points `p1` and `p2` (in black), representing the points that are `length/2` away from `p0` on its directly opposite sides.

The gray circle is just for emphasis that trigonometry applies.

Basic trigonometry says that to get the `x` value of the orange vector (`p0` to `p1`), we can do `r * sin(a)` and for its `y`, do `r * cos(a)`.

Hence to find `p1`, add the orange vector to `p0`. For `p2`, *subtract* the orange vector from `p0`.

You can then use `p1` and `p2` to draw your gradient.
> 3 votes

---
Tags: xna, c#, mathematics, color, trigonometry
---


# Question
Title: How to import .fbx MODEL into Unity Project?
I created new Project in Unity. I downloaded .fbx file from internet, it looks like as give in image. How can I import .fbx into Unity Project. I am beginner and this is my first Unity Project.

Thanks

# Answer
> 5 votes
Simply drag the .fbx file to the project assets folder.

---
Tags: unity, fbx
---


title: How do I maintain an online users list?

text:
# Question
Title: How do I maintain an online users list?
In a multiplayer JavaScript game client, is it a good idea to poll the server periodically to refresh online user list, or keep track of joined/left users? Is there a better option?

# Answer
A combination of both strategies would likely yield the best results. Just keeping track of when user join/leave might not account for situations where the user is unexpectedly disconnected. A periodic poll would likely have to happen too often to get reasonably updated list of players joining and leaving.

So, update the list when a player joins or leaves and poll less periodically.
> 6 votes

# Answer
It depends is network traffic efficiency really important to you. If it is not you might have three actions in your server:

* connect - which will add user to a server list
* disconnect - which will delete user for a server list
* poll - which will periodically check all users alive status (simple ping with client app)

More complex but also better way is to use timers. Every user will have a separate timer when he joins. When the timer runs out, server will poll for his status.

* if he is alive server reset timer
* if he is not responding server will delete him from user list

It won\`t generate as big lag as polling all users at once.

**Edit:**

actions for the client

* connect
* disconnect
* "ping" response

In other words, you are not polling server at all until server will ask you for alive status.
> 0 votes

---
Tags: javascript, multiplayer, online, client
---


# Question
Title: How to vectorize a raster image edges into SVG paths?
I'm having a lot of trouble figuring out how to convert a 2D list of points into an SVG Path representing a political map border. I have completed all parts of a 2D terrain generator, including climate simulation, rivers, lakes, rainfall, temperature, biomes, and finally territories. This last part is where the problem lies. The entire script is written in Python.

I have a list of territories, which are represented as dicts with several properties. One of which is Color, used as an ID and to output a pretty map. Another is a list of Pixels, list of Borders, and list of Neighbors. Pixels refers to all points in the territory. Territories can be thought of a polygons. They have Border pixels, which are defined as any outside (meaning not part of the Pixels list) pixel not belonging to this territory (whether it be a River, Ocean, or Unowned pixel). I also keep a list of neighboring territories.

Now, I can't store an array of ~3000 coordinates in a database efficiently when I only really need the border. I aim to draw only the world map with the borders of each territory drawn in a layer above. So I need to convert the border to an SVG Path string.

The Borders list is unordered when the generator finishes. For each border pixel, I go clockwise around the pixel and look for another, and progressively create a SVG Path string. **I can't seem to efficiently parse the borders without getting stuck**. Another problem is that there may be "lakes" in the middle of the Territory, and Borders are added around those as well. These don't have to be included in the path string.

Territories can also wrap around horizontally (like Google Maps for instance), splitting the territory in two.

So the final result of my algorithm would ideally be an LIST of SVG Paths, each representing individual parts of the territory polygons.

**But, how do I do this efficiently? Is there another way to efficiently store a list of potentially thousands of coordinates representing the shape of the territory?**

Each white line that sticks out from the coastline is a river. You can also see a lake in the middle of the lower green territory.

PS: I was unsure of a title, if a mod would like to change it.

# Answer
> 3 votes
### The question

I have an image with multiple regions, that I need to efficiently convert to vector graphics.

### The problem

This is a common non trivial problem in image processing -prepare to get your hands dirty-. I can categorize it as an image segmentation problem. The extra step you want to make is to convert it into vector graphics which is also non-trivial.

My solution is a variation of common techniques, but it's an algorithm that I just came up with, so don't expect 100% correct results. I hope it will put you on the right track..

### The solution

**1-** At first we should detect regions and their edges (connected components).

This can be done using a region growing algorithm. Start with random points taken accross the image -or in your case from each already known region-.

Grow each point neighbors across all directions, if the pixel is within color range add them to the region. When the region reaches an edge with (given that it has a distinctive color, white for example in your image add that pixel to the region.

This way you have each region and it's edge. Since you said you already know about the regions you can only use this to add the edges for each region's list.

For different approach you may want to check this wiki page.

Three things to keep in mind when doing this step:

1. You should copy each region's pixel to a seperate image, this will make dealing with each region in the later steps more
2. *you don't need a fully colored image, you can get away with grayscale.*
3. A lot of the region growing can be optimized by removing the recursion but that's not easy.

**2-** Build a bounding box for each region.

Make sure the in the first step to keep track of the min and max pixel position.

One you detected the region build a box using min and max. This box will contain each region and it's white edges. This is an important step what we have done here and the first step is to isolate each connected component. So we can study each region separately.

**How to detect the lakes ?**

Using the bouding boxes. If a bounding box is contained in another then it's a lake.

*I can see this step might have some edge cases, you can divide the box more. For more accuracy. more on that in the next step*

**3-** Vectorization.

This is in my opinion the hardest part. Now we have each region and its edges bounded in a box. What you can do is subdivide the box into a grid and sort each edge pixels for each grid block counter clock wise. Once you sorted them you can convert each pixel to a point and connect them. In order to connect separate curves in every grid block, just connect it with the neighbor grid block.

### Bonus Fun Fact

Because of digital image representation, images lose most visual information once the signal is digitized, your brain rocks, it will fill the information for you. Notice this image under the black arrow, you can zoom the image to specifically get my point.

Who else other than your brain can know that those 5 pixels are actually a car, see!

---
Tags: procedural-generation, maps, terrain, image-processing
---


# Question
Title: Are there any games that contain a machine learning AI?
Can anybody here give a reference to commercial AAA games that implement a machine learning AI?

# Answer
> 13 votes
The most common approach is to train the AI off-line or pre-release, and to ship that final result. As such the game arguably doesn't contain a machine-learning AI.

This is because machine learning can traditionally take many hours of training to produce a usable result, and as it's by definition emergent, it's probably a good idea to put any result through a full QA pass to make sure there aren't any exploitable edge cases.

For the above reasons, and because gameplay changes and balancing even late on might mean that the AI has to be retrained and retested, not many studios use this approach.

# Answer
> 8 votes
Forza's Drivatars are an example of learning AI in a shipped game. They watch your driving to learn how to copy your style. There's lots of information in that link.

# Answer
> 4 votes
The only game I knew that I think may use machine-learning is **Tekken 5: Dark Resurrection** for psp. in that dojo mode game AI could learn how you play with each one of characters and it created a **ghost** of you playing that specific character. later you could fight with yourself or give your shadow to your friend and let him to fight against your shadow.

# Answer
> 1 votes
I don't know if it counts as a AAA title, but Darkwind uses genetic algorithms to train AI drivers. There's also a newer paper about using player behaviour to modify pathfinding in complex terrain, which you can read here.

# Answer
> 0 votes
It's not a AAA title, but more of a research game, you create a squad and then train it by manipulating the enviourment, the ai is based on neural net's and the learning is done through GA. NERO

# Answer
> 0 votes
Galactic Civilizations 3 will use a networked approach to AI Machine Learning. Player tactics and strategy will be uploaded to the company servers for analysis. From the Gal3 website faq (http://www.galciv3.com/game/faq):

"Q: : Will the game require a network connection to play?

A: No. However, some of the AI learning mechanisms will require access to the Metaverse in order to perform analysis on player strategies. This will be optional and able to be disabled by the player but does require an Internet connection."

No details on if this is real time, delayed or used in game updates, but the GalCiv games have always been noted (in reviews) for the solid AI.

---
Tags: ai
---


title: Particle movement in three Dimensions

text:
# Question
Title: Particle movement in three Dimensions
I have created a particle system which movement is controlled by a flow field over perlin noise - Available here.

I would be very thankful for any ideas and tips how to control their movement on the Z-plane (noise is 3d), as my 3d knowledge is still very poor.

How to describe the movement controlled by noise value in the third dimension? I guess the displacement has to be described by a vector directing the movement and added to current possition, but how to determine the z component?

3d example video is available here

# Answer
In your code, you always set z portion of each particle position to 0. Same thing that you've done for x and y do now for z and you are all set, I guess. That means most of all - create third instance of SimplexNoise and use it to calcualte z position in your animation() function.

Then add something like FirstPersonControls.js so viewer can actually enjoy third dimension.
> 1 votes

---
Tags: 3d, movement, particles, perlin-noise, three.js
---


# Question
Title: How to swap the position of two sprites?
I'm making a game like Candy Crush with Cocos2D in Android. I've made the sprites but I want to swap to sprites by touch .

How to swap the position of two sprites?

# Answer
To do this, all that you need to write is something like this, a simple swap function:

```
class Point
{

private int x, y;

procedure swapPositions(Point a)
{
   Point temp = a;

   a.x = x;
   x = temp.x;

   a.y = y;
   y = temp.y;
}

}

```

Note: this is pseudo-code and it will not work if you try to use it. You must write your own, with this concept, and fit it into your current game's build.
> 2 votes

---
Tags: java, android, cocos2d
---


# Question
Title: What are some good (retro) symbols for magic/mana/energy?
Much like a heart is used a lot for health and lives in old retro games...

**...what would be a good icon to use for Energy, Mana and/or Magic points?**

# Answer
> 21 votes
I don't know of any particular icons, but I think the most important thing to keep in mind is that **players associate the colour blue with magic**. Thus, I don't think the icon actually matters, as long as you follow the basic convention of **red for health, blue for magic and green (or the less-used yellow) for a third metric** (usually stamina, but can be other things like in the case of *Eternal Darkness: Sanity's Requiem* where green stood for sanity).

Typical shapes include orbs, crystals, potions or runes.

Hope this helps!

# Answer
> 9 votes
Magic and stuff. Orbs, staffs, scepters and green/purples came to my mind. Here's Some of it:

* A basic orb :

* Some Zelda style rupee (You could modify it to a suitable color)

* Basic staffs and scepters :

* Some potion :

And also green and purple fire.

# Answer
> 1 votes
Purple or green stars could work for magic. For energy, maybe some yellow lightning bolts. And for food (mana), you could use any food item and pixelate it. I would be able to give more advice as far as shapes if you could tell me the theme of your game :)

# Answer
> 0 votes
I would suggest for mana a retro crystal like in the background of this pokemon game:

---
Tags: art, gui
---


# Question
Title: How do I show a Quit button on Desktop but don't show it on Android with libgdx?
So I would like to display a Quit button on the Desktop main menu screen, but I wouldn't want to have it on Android too. What is the correct approach to achieve this? Do I have to check the `ApplicationType` of the app each time I want to display something different on the two platforms, or is there a more general approach maybe?

The same question is valid for text for example. Say, on Desktop it should say "Click to continue" whilst on Android - "Tap to continue".

To mention that both projects (Desktop and Android) share the same main project, since they have been created using the gdx-setup-ui tool.

Thank you.

# Answer
> 2 votes
Another thought:

You pass a resource provider to the constructor of your ApplicationListener, and get your string values (or other resources) from it.

You wind up with one abstract class in the core project for the resources that do not change, and a derived class in each of the platform projects for the resources that do change.

In this way, you only do this at the start of the app, and the rest of the game is completely oblivious to the difference, which is what I think you are looking for.

# Answer
> 3 votes
To add in platform specific code, you may check the application type with libgdx.

https://stackoverflow.com/a/15891372/1620568

`Application.ApplicationType` will return one of the following results:

* Android
* Applet
* Desktop
* iOS
* WebGL

http://libgdx.badlogicgames.com/nightlies/docs/api/com/badlogic/gdx/Application.html#getType%28%29

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


# Question
Title: Tricks in game mechanics to avoid dealing with network lag compensation?
Implementing network lag compensation is hard, how to avoid it?

Maybe it's possible to use tricks and build game mechanics in such a way that lag would be percieved as a non critical or even as a natural part of game?

What are those technics and is there any existing games (MMORPG, Strategies, ...) that uses such technics?

UPDATE:

Turn based games don't require lag compensation, but it would be interesting to see approaches for real-time (or just an impression of real-time, the important part - user shouldn't be blocked and forced to wait).

The main reason for me to avoid lag compensation is simplicity.

# Answer
> 17 votes
It's common for the client to implement some sort of feedback to let the player know immediately that their chosen action has been registered, eg.:

* interface sound (eg. button click)
* in-world sound (eg. a character saying, "At once, commander")
* animation (eg. begin swinging a sword)

These can take place while the information is travelling to the server so the player doesn't realise that their action has not started yet. As long as the server replies promptly and the action does begin soon, the player may not notice the delay.

These tricks work in games where player inputs are fairly infrequent and therefore the amount of time you spend waiting for an input to take effect is a relatively small proportion of the total time spent playing. Therefore, you would want to find ways to structure the game so that the player makes fewer inputs. This probably means making player actions more abstract and having the game implement the low level behaviour. Examples:

* replace steering mechanics with pathing mechanics
* replace aiming mechanics with target selection mechanics
* replace round-by-round combat instructions with more tactical or strategic plans
* replace real time/continuous gameplay with discrete/turn-based systems

# Answer
> 7 votes
Random thoughts:

1. cheat: **use rockets**. Rockets explode in a radius, hiding any weirdness.
2. cheat: **predetermine the outcome** and force the condition to happen visually
3. cheat: **attacks take time**, hide latency in the atk+anim+result discontinuity
4. cheat: **disconnect local feedback** from the networking stuff
5. cheat: **lots of VFX** or screen activity that covers any weirdness.
6. use an **action-reaction design** that requires resolution before continuing

So yeah, cheat a lot.

# Answer
> 4 votes
The answer is quite simple - just build games that don't have time critical sections. You're looking to avoid implementing these types of interpolations for a specific reason I take it, which means you're not concerned about twitchy and fast gameplay. This is perfectly accetpable for a lot of games, including Civilization (which is a strategy game). However, understand this is NOT acceptable for a **REAL TIME** strategy game where you need to be passing a lot of data over the network at variable timings. If you'd like to design a game around a very high latency network, consider the following:

1. **Build turn based games.** In these types of games, real-time input of the state isn't needed and the other player can simply push the state of the game into their client when it's their turn. This reduces pressure on the network and allows delays upwards of even a few seconds if one so desires. **Civilization** is a turned based game which is very popular, and in the strategy vein.
2. **Keep the other players decisions impact to a minimum.** If your game is strategic and can't play turn based, consider reducing the impact of delayed packets. Can the client does most of the simulation? An example is a strategy game that is played alone for a while and then after say, 16 minutes, is simulated against another player (perhaps a combat game where players send in troops every x interval and report back every y interval.

I hope this helps at least a bit; without knowing your exact game ideas it's difficult. I assume you have your reasons for wanting to create your game around such a pattern (simplicity, saving on bandwidth, reduced network complexity)

# Answer
> 4 votes
You could also make lag be part of your gameplay for "realism" sake. Say your players are meant to control some robots from a distance, you could force the lag to be at least 500ms or 1s (you'd have to implement some dynamic lag padding system).

# Answer
> 0 votes
It is also a nice trick to simply hide the actions of players. A lot of FPS games do exactly this. They do not show any visuals of most of the bullets only sounds are played and you get the outcome in the form of damage dealt to players.

I have played some FPS games where high accuracy weapons (snipers and such) had very clear visual effects, and you could actually see that the other player shot behind you, but because of lag compensation you were killed.

---
Tags: networking, mmo, rpg, rts, lag
---


# Question
Title: Procedurally Generated Structures over large quantitys of chunks in 3D Terrain Generator
I am creating large scale worlds using 16\*16\*16 voxel chunks which are stacked up to 32\*32\*32 in dimensions and I have hit a bit of a Bump in the road so to speak.

I want to create large structures that span 20+\*20+\*20+ chunks in volume which are created from procedurally generated structures as well as using templates for some of the content. Now I have an issue. The visual render range is up to 32\*32\*32 chunks and while I have up to maybe 40\*40\*40 chunks held in memory at a time when possible.

The structures can be anything like towns, dungeons and roads. I was thinking something like perlin worms for roads and just lay them over the terrain in the x,z and then analyze the path for bridges etc..

The structures and collection of structures need to be pre-generated before the player is within visual range or work more like perlin noise does for heightmaps (best solution). (to avoid the players seeing the generator at work). They also need to be consistent with the world seed every time.

I have thought about this a bit and have 3 possible solutions.

1) Generate the structures based on a point of origin for the structure generator. This causes several issues though as even if I generate from the center of the structure, the structures can easily cross into the potential visual range of the player.

2) Pre-Generate "unreachable" chunks and then page them in and out in order to generate the structures using the above method. This also seems rather unnecessary.

3) I had an idea for dungeon generation in which I generate point clouds/nodes for rooms.

Steps:

a) When the generator finds a "node" it creates an x, y and z size to create a box basing it from the originator point of the room\** (centre or corner of the room) and the room type.

\**x,y,z relative to 0,0,0 worldspace calculated like so new Vector3((chunkX\*16)+voxelX,(chunkY\*16)+voxelY,(chunkZ\*16)+voxelZ)

b) Once a room size is calculated, check for overlaps and if one is found do one of several things. If the room overlap is high up lower it down till either the roof or the floor are flush. If the roof is flush build a stairs up to the room and remove the walls that intersect.

b) Look Down, North and East for a room maybe with a small cone and attempt to create a hallway between them.

This would probably work somewhat, especially if the center of the dungeon is the main hall/boss room.

This would be different for towns, cities, and surface dungeons. Still seems a little choppy though. Any ideas?

All methods need to analyze the terrain in large quantities for a valid location to spawn the structures.

I was hoping somebody might have a more organic solution or even just a simpler solution that doesn't require me to "Look" so far ahead.

Thank you in advance.

# Answer
It looks to me that there are two different points in your question:

1. What would be the best way to pre-generate structures before the player is within visual range in a voxelized scenario?
2. Is your reasoning for generating 3d dungeons ok?

The first question has many implications. One of them is addressed by the link suggested by Thorinll (how to manage structures larger than your chosen voxel chunk size).

But you seem to be particularly interested in finding a method for generating things at a safe distance from player and also being able to repeat the generation process easily again.

As mentioned in your own question, it's all related to your pseudo-random noise (PRN) generator. Any PRN can be repeated, because they are deterministic. Moreover, an adequate PRN should also give you the necessary coherence \[1\] so you can partially generate structures at one moment, generating the rest of them later.

What you don't seem to consider is that you don't need to pre-generate all your structure to position it in a safe distance from player. I.e.: You don't need to generate all dungeon rooms to figure it out how big it is, you could just determine its bounding box before hand.

Neither you seem to be dealing with infinitely large structures, so I guess you could consider your PRN space equivalent to world space and use a point lattice \[2\] to determine if there's a structure in a given world point or not. You should only take care to choose an interval (between your points) large enough so that you can fit the biggest of your structures without colliding to another.

You could also "play" with the coherence of your noise to make sure that the parts (rooms) of a structure are never (or very much unlikely) unrelated. For that you just have to map a range of numbers to the types of rooms adequately. For example, if you map \[0.0, 0.25) =\> kitchen, \[0.25, 0.5) =\> living room, \[0.5, 0.75) =\> bedroom, \[0.75, 1.0\] =\> bathroom, it would be unlikely or even impossible to have a kitchen beside a bathroom, because it would be unlikely or impossible to find a 0.0 besides a 0.75.

Also, you could trigger your generation routine whenever the player moves from intervals on this lattice. You could start "loading" your strutures' metadata to RAM at a certain distance from player, just like you would do with paged terrains.

This way there should never be a structure popping from out of nowhere, crossing "(...) into the (...) visual range of the player".

On your question about your method for generating a 3d dungeon, I think have done something similar to it on this game:

http://www.ludumdare.com/compo/ludum-dare-28/?action=preview&uid=30821

But, although the game is "2.5D", the level generation is in 2D. I just had a few room shapes which I was randomly attempting to fit along each other following a very simple heuristic. Despite the fact that it was very unoptimized, it ran fast enough to generate reasonably big levels.

\[1\] http://libnoise.sourceforge.net/glossary/index.html#coherentnoise

\[2\] http://mathworld.wolfram.com/PointLattice.html
> 1 votes

---
Tags: c#, procedural-generation, terrain
---


# Question
Title: How can I track both current and maximum values for a given statistic?
In my design I have several cases where I need to track both a max value and a current value (examples include Hit Points or Movement Points). I could track these as separate variables:

```
int HitPointsMax;
int HitPointsCurrent;

```

or as a struct:

```
public struct HitPoints {
  public int Max;
  public int Current;
}

```

So my question: **Is one of these preferable over the other, and why?**

Is there some element of efficiency? A best-practice? Is there a better option?

# Answer
> 3 votes
In the *vast majority* of cases, your best bet is with **loose values** like this:

```
int hitPointsMax;
int hitPointsCurrent;

```

This is by far the easiest thing to think about and to modify. The "structure" (including putting the values close together in memory for performance) should be provided by whatever class (eg: `Player`) they reside in. Leave the `Player` class to be responsible for managing how the two variables relate.

This way, if the way hitpoints work changes (eg: "now player can boost their HP past its capacity", or "monsters max HP is defined by monster type lookup and doesn't change") then you haven't locked yourself into some complex structure - possibly that other code depends on - that you have to pick apart later.

---

Now, that being said, what if you've got lots of this functionality spread across your codebase, and you're finding you're getting lots of duplicated code:

The *first* thing to consider is the possibility that your (for example) `Player` and `Monster` classes should inherit from some common class like `Lifeform` or `Actor` (or be composed with that class or whatever).

If that doesn't solve the problem, if you've genuinely got identical hitpoint handling or stat-with-a-maximum handling in many disparate places, and especially if you're passing the values (current and max) around a lot as a "unit", *then* you might consider turning them into a specific struct.

If hitpoint handling is somehow "special" - perhaps you will have hitpoint-specific methods - then you may want to do this:

```
public struct HitPoints { public int max; public int current; }

```

Otherwise, if you've got stats like "hit points" and "armour points" and "movement points", with identical functionality, do something like:

```
public struct StatWithMax { public int max; public int current; }

```

And then create variables for each one:

```
StatWithMax hitPoints;
StatWithMax movementPoints;

```

(Your struct should probably start with simple public variables like that, and then add in additional functionality as it is needed.)

---

Bottom line: **It's all a matter of taste.** The overall goal should generally be to minimise the amount of coding work in the long term. Sometimes you will want to make something extremely simple and flexible; other times you'll want to impose some extra structure to reduce duplication and save work later on.

Obviously, in this particular case, the difference is insignificant. But the principles are important.

(Take a look at this lecture for some more thinking on the topic.)

# Answer
> 3 votes
You should probably generalize when you can to prevent code duplication. For instance (pseudo code):

```
class BoundedVal<class T> {

    // Normal val can be used for attributes like defense or attack
    // that are temporarily buff/debuffed
    T min, max, normal_val, val;
    void inc_val(T amount){
        val = min(max, val + amount);
    }

    void dec_val(T amount){
        val = max(min, val - amount);
        if (val == min) event_on_min();
    }
     // You can add some event too
    void event_on_min(){
        // do stuff (if ran out of xyz)
    }
}

```

This way you handle, hp, mana, stamina and what not. Since C# does not support templates to the extent c++ does and does not allow arithmetic operators to be used with unspecified types, you will want to use a specific type where I wrote T. I would use double for flexibility unless you need fine-grained control on very large integers.

To learn more about this subject:

https://stackoverflow.com/questions/756954/arithmetic-operator-overloading-for-a-generic-class-in-c-sharp

# Answer
> 0 votes
Arguably there are benefits to the structure. Grouping related data, and in low level languages elements of structures are kept adjacent in memory so faster access (though this is largely an "academic" performance increase - unlikely to be noticeable).

I think any efficiency would be negligible and in terms of best practice I'm sure that is completely subjective - there isn't a de facto method.

In the end it's up to you and whatever you're happiest with.

# Answer
> -1 votes
Either way would work just fine.

However, the way that I like to do it is to just have one variable with a value of the max hit points (5 in this case).

Then just subtract from that variable. And test whether it is equal to zero.

Initialization

```
int HitPoints = 5;

```

When hit is detected

```
--HitPoints;
if (HitPoints <= 0)
{
    // Do what you want to do when hit points are used up
}

```

However, there may be certain cases where you would want to store the MaxHitPoints variable anyway so either way is good.

---
Tags: c#, game-state
---


title: Invert Alpha on Image

text:
# Question
Title: Invert Alpha on Image
I'm making a lighting system right now, and the last part I have to do is to invert the alpha channel on the final light map. My previous code that used to work was

```
DataBufferByte buf = (DataBufferByte)lightmap.getRaster().getDataBuffer();
    byte[] values = buf.getData();
    for(int i = 0; i < values.length; i += 4) values[i] = (byte)(values[i] ^ 0xff);

```

But this code threw this "java.lang.ClassCastException: java.awt.image.DataBufferInt cannot be cast to java.awt.image.DataBufferByte" on the first line. So, I changed it to

```
DataBufferInt buf = (DataBufferInt)lightmap.getRaster().getDataBuffer();
    int[] values = buf.getData();
    for(int i = 0; i < values.length; i += 4) values[i] = (int)(values[i] ^ 0xff);

```

but this doesn't actually invert the alpha, but seems to invert the color between the hue and black? I know that this works

```
for(int i = 0; i < lightmap.getWidth(); i++) {
        for(int j = 0; j < lightmap.getHeight(); j++) {
            lightmap.setRGB(i,j,(lightmap.getRGB(i, j) ^ 0xFF000000));
        }
    }

```

But testing this, it brings my framerate down to 15 fps.

So I guess my question is this: Either how can I fix this, or is there a fast way to invert the alpha values of a bufferedimage?

# Answer
> 2 votes
I inverted color in java before and for each channel in the byte array I would subtract the existing value from 255 a bit like so

```
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(img, "jpg", baos);
baos.flush();
byte[] imageBytes = baos.toByteArray();
baos.close();
for(int i = 0; i < bytes.length/3; i++)
{
   //red
   imageBytes[i*4] = (255-imageBytes[i]);
   //green
   imageBytes[(i*4)+1] = (255-imageBytes[(i*4)+1]);
   //Blue
   imageBytes[(i*4)+2] = (255-imageBytes[(i*4)+2]);
}

```

So for an ARGB I would find which order the Alpha comes in assuming its the first byte in order then your code would read

```
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(img, "jpg", baos);
baos.flush();
byte[] imageBytes = baos.toByteArray();
baos.close();
for(int i = 0; i < bytes.length/4; i++)
{
   //alpha
   imageBytes[i*4] = (255-imageBytes[i*4]);
   //red
   //imageBytes[(i*4)+1] = (255-imageBytes[(i*4)+1]);
   //green
   //imageBytes[(i*4)+2] = (255-imageBytes[(i*4)+2]);
   //Blue
   //imageBytes[(i*4)+3] = (255-imageBytes[(i*4)+3]);
}

```

you would divide bytes.length by 3 for an RGB image and by 4 for an ARGB in the for loop you can then convert to them back to DataBufferByte with

```
buf.setData(imageBytes);

```

assuming `DataBufferByte` works the way I think it does. not hugely familiar with it. I commented the other channels so yo can see what I mean but they aren't needed.

I found this incredibly fast on slow machines as I was able to load and parse an image 512x512 then save it in under a second. I also read somewhere that iterating backwards through an array in java is faster. http://www.mkyong.com/java/reverse-loop-versus-forward-loop-in-performance-java/ I would also note that an ARGB image needs to be png or bmp not jpg like in my example.

---
Tags: java, graphics-programming
---


# Question
Title: 2d metaballs with shader to give blobs of water effect?
I want to simulate blobs of water in a 2d game in Unity3d. One possible way of doing it is to use 3d metaballs moving in a 2d plane though this is very processor intensive. Do you think it would be possible to make 2d metaballs, so I end up with a 2d meshes something like in the picture (In this case its 2 metaballs in conjunction) and then apply some kind of shader to make it look like they are bulging out and refracting the texture behind them like drops of water? I ask because I dont have much experience with shaders and am not sure what is possible.

# Answer
> 4 votes
ilmale's answer is very comprehensive for 3D.

For the 2D case, a trick I've used in the past is to render a bunch of blobs with feathered edges using additive blending. (This example I had kicking around used rounded squares, but any shape works. The soft edges let them merge smoothly together when they get close.)

This creates something like a height field. Then in a second pass you threshold this field to generate your blob contours. You can use finite differences to extract normals from the field for shading & refraction.

This gets the visual effect, but the exact countours live only in the raster data on the GPU side. If you need to know where the boundaries of the metaball surface are for gameplay, you may want to use an analytical approach instead (although the two techniques could also be combined, as long as the implementations agree on where the contour goes).

# Answer
> 3 votes
If you want to draw 2d drop of water a solution is to draw sphere normals and then blur the normal buffer. Then use the buffer to calculate the refraction.

This technique is briefly explained here (in 3d):

http://developer.download.nvidia.com/presentations/2010/gdc/Direct3D\_Effects.pdf

---
Tags: unity, shaders, water
---


# Question
Title: How control probability of win-lose in tile-matching games?
In a random puzzle game, such as a match-three game, how can you control the probability of a winnable starting condition?

# Answer
> 2 votes
You could generate your puzzle by starting with a solved puzzle and then backtrack to an unsolved puzzle by generating a series of random legal player moves which lead to that state.

This is like starting with an already solved rubiks cube, making a couple of random moves, and giving it to a player to solve. You then know that there is at least one solution: repeating the same moves you made in the opposite order. But there could be other solutions, maybe even a better one.

This strategy can be transfered to most other puzzle games which are solved by a series of deterministic moves. The advantage of this method is that you can easily control the difficulty by choosing the number of moves you make.

# Answer
> 1 votes
You basically need to create a solver. The solver can randomly attempt to win. You can calculate the percentage of chance to win. In order to create a winnable stage you need to add new tiles in a way that reverses the move of the player. Meaning that if you add a combination that can be eliminated you simply pick a position to put it and the move the existing tiles in these rows up to accommodate the new pieces.

# Answer
> 0 votes
Computing probability implies that some random process occurs. Here is not clear which random process you are refering to. Taking for example a match-tree game, once you have a initial condition there is no more randomness involved: a board may be eighter solveable or not. You may ask "what is the probability of a random board to be solveable", but this is not under your control.

Said that you can control the "difficulty" of board but you have to define what you mean for "difficulty", this kind of metric is strictly bound to the specific game you are modelling and the choice you make for metric is one of the main factors that determine the (in)success of your game.

---
Tags: algorithm, random
---


# Question
Title: Why does my game display the wrong "required Android version" on Google Play?
I'm porting a Unity game to Android, and I've set up the "Minimum API Level" in the Player settings to "2.3.3 (API level 10)".

However, on the store, it says "Requires Android: 1.6 and up".

On the Google Developer Console I didn't find this setting, so I guess the store is just trying to "guess" it examining the application, and failing.

Did I miss something?

# Answer
> 12 votes
You have probably published your APK as Alpha or Beta. This is a known bug and Google Play store will incorrectly show "Requires Android: 1.6 and up". When you deploy your APK as production, it will show the correct number.

You can check your apk's minSdkVersion by the command-line tool `aapt` (inside sdk/platform-tools)

`aapt d badging game.apk`

or

`aapt l -a game.apk`

But you should put the correct setting to your manifest in any case:

```
<uses-sdk android:minSdkVersion="A" android:targetSdkVersion="B" />

```

# Answer
> 2 votes
Okay. Instead of editing it directly like Lestat tried, how about trying to set it programmatically, with the help of Unity.

```
PlayerSettings.Android.minSdkVersion = AndroidApiLevel10;

```

Documentation for minSdkVersion

# Answer
> 1 votes
That is defined in the Android Manifest file:

```
<uses-sdk android:minSdkVersion="10" android:targetSdkVersion="19" />

```

# Answer
> 0 votes
It is possible that you and/or your IDE (if you're using one) may have missed something. It's likely that there are elements in your project that are causing this.

Check for anything that may have been introduced in a later API. Also be sure your project is targeting the correct API level.

---
Tags: android, unity, google-play
---


# Question
Title: How do you calculate a gradient value within multiple colors (gradient stops)
In WPF/Silverlight XAML you can have a brush with multiple gradient stops at different points along the color line.

I was able to replicate this behavior with two colors, a single color lerp, from this answer to my previous question: Code to generate a color gradient within a texture using a diagonal line

How do I do the same thing in that question, but with multiple color steps even at different widths from each other.

# Answer
You do the same thing, only multiple times between the starting point and end point of each color.

Here is some pseudo code (copied from other question) and modified:

```
int counter = 0;
Color ca[N]; // put in somecolors here
float color_precentage[N]; // put in desired percentage

for(int x=0;x<width;x++) {
    for(int y=0;y<height;y++) {
        // but we need vectors from (-1, -1) to (1, 1)
        // instead of pixels from (0, 0) to (width, height)
        float u = (x / (float)width)  * 2.0f - 1.0f;
        float v = (y / (float)height) * 2.0f - 1.0f;
        float here =  u * rx + v * ry;
        float lerp = (start - here) / (start - end);

        // Make sure we stay in range
        for(counter = 0; counter < color_percentage.Count && color_precentage[counter] < lerp; counter++);
        counter--;

        counter = Math.Max(counter, 0);
        counter = Math.Min(counter, color_precentage.Count - 2);

        float new_lerp = (color_precentage[counter] - lerp) / (color_precentage[counter] - color_precentage[counter + 1]);
        SetPixel(x,y, Color.Lerp(ca[counter], ca[counter + 1], new_lerp));
    }
}

```
> 2 votes

---
Tags: xna, c#, graphics, color
---


title: Game states vs calling new activities

text:
# Question
Title: Game states vs calling new activities
I am trying to decide what the best method is to call "level complete-screen" and "game over-screen" in my real-time android 2d game. Currently I am using game-states and only updating my game when its in `gamestate==GAMEPLAY`, but this sometimes makes resetting some stuff awkward. Another method I have tried is calling a new activity during real-time using context, like this:

```
public void startMenu() {
    final Context context = this.getContext();
    ((Activity) context).runOnUiThread(new Runnable() {
        public void run() {
            thread.setRunning(false);
            try {
                thread.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            // Context context = getContext();
            Intent intent = new Intent("nielsen.happy.activities.MENU");
            intent.putExtra("level", level);
            ((Activity) context).startActivity(intent);
        }
    });

```

This method calls another activity during real-time from a View-class. But it seems a bit clumsy and forced. Just want to know if there is a preferred way to call these screens in real-time games?

# Answer
I would need to see a video of the game first to give a specific answer. I personally would implement functionality to pause and reset the game and also to transition to the next stage. In most cases I would not pause the game in stage complete / game over state and simply display a sprite with the relevant text. Then I would either transition to a new level or reset as needed.

I don't think you really need to use this hack / work around and instead ask about the problems that stem from your attempt to pause the game.

Alternatively you could put focus on completing the game and ignore code smell. If the game is fun and it works, it really does not matter how clean and tidy the code is unless you wish to extend it or use code from it in other games.
> 2 votes

---
Tags: java, 2d, android, game-mechanics
---


title: xna 2.5d gravity system

text:
# Question
Title: xna 2.5d gravity system
i currently developing a game using the xna API.

now the game i am developing is 2.5d.

by 2.5d i mean the character or object can move left and right and a up and down(not just by jumping) that it would look like there is depth to the level.

try to think something like little fighter 2 where you can also walk up and down.

now i need to develop a gravity system,so far i used the idea that i draw a shadow on the ground of the level,and it follows the object or character and when the character jumps,he moves parabolic like in the real world(using very simple physics).

the gravity system detects landing if the position of it's shadow is the position of the character( or the position of the character is below the position of the shadow). is there a better way to simulate gravity in this 2.5d approach?

# Answer
> 0 votes
I tend to define a separate jump offset, which you then manipulate with the players + shadows position when you render.

That way you don't need to compare positions with the shadow and player position (as they could be offsetted at some other point in your game). You just check if the jump offset is \<= 0 length.

When it comes to the physics themselves I'd just create a velocity that adds itself to the jump offset over time and a gravity that subtracts from the offset over time. And then do a ye olde if(jumpoffset \< 0) jumpoffset = 0;

That way you get the parabolic movement, simply by setting the velocity to some value you feel fits your game. :)

---
Tags: game-design, xna-4.0
---


title: How to optimize the distance function?

text:
# Question
Title: How to optimize the distance function?
While developing a reasonably simple RTS-like game, I noticed my distance calculations were causing an impact in performance.

At all times, there are distance checks to know if a unit is in range to its target, if the projectile has reached its target, if the player has run over a pickup, general collision, etc. The list goes on, and checking for distance between two points is used a lot.

My question is exactly about that. I want to know what alternatives game developers have for checking distances, other than the usual sqrt(x\*x + y\*y) approach, which is fairly time consuming if we are performing it thousands of times per frame.

I'd like to point out I am aware of the manhattan distances and squared distance comparisons (by skipping the sqrt bottleneck). Anything else?

# Answer
TL;DR; Your problem is not with performing the distance function. Your problem is performing the distance function so many times. In other words you need an algorithmic optimization rather than a mathematical one.

\[EDIT\] I am deleting the first section of my answer, because people are hating it. The question title was asking for alternative distance functions before the edit.

~~You are using a distance function where you are calculating square root everytime. Yet, you can simply replace that without using the square root at all and calculate the distance squared instead. This will save you a lot of precious cycles.~~

> ~~Distance^2 = x\*x + y\*y;~~

~~this is actually a common trick. But you need to adjust your calculations accordingly. It can also be used as initial check before calculating the actual distance.~~  ~~So for example instead of calculating the actual distance between two points/spheres for an intersection test we can calculate the Distance Squared instead and compare with radius squared instead of radius.~~

**Edit, well after @Byte56 pointed out that I didn't read the question, and that you were aware of the squared distance optimization.**

Well in your case, unfortunately we are in computer graphics almost exclusively dealing with Euclidean Space, and distance is exactly defined as `Sqrt of Vector dot itself` in euclidean space.

Distance squared is the best approximation you are going to get (in terms of performance), I can't see anything beating 2 multiplications, one addition, and an assignment.

> So you say I can't optimize the distance function what should I do ?

Your problem is not with performing the distance function. Your problem is performing the distance function so many times. **In other words you need an algorithmic optimization rather than a mathematical one.**

The point is, instead of checking player intersection with each object in the scene, each frame. You can easily use spatial coherency to your advantage, and only check the objects that are near the player (that are most likely to hit/intersect.

This can be easily done by actually storing those spatial info in a spatial partitioning data structure. For a simple game I would suggest a Grid because it's basically easy to implement and fits dynamic scene nicely.

Every cell/box contains a list of object that the bounding box of the grid enclose. And it's easy to track the player position in those cells. And for the distance calculations, you only check the player distance with those objects inside the same or neighbor cells instead of everything in the scene.

A more complicated approach is to use BSP or Octrees.
> 28 votes

# Answer
If you need something that stays linear over any distance (unlike `distance^2`) and yet appears vaguely circular (unlike the squarish Chebyshev and diamond-like Manhattan distances), you can average the latter two techniques to get an octagonally-shaped distance approximation:

```
dx = abs(x1 - x0)
dy = abs(y1 - y0)

dist = 0.5 * (dx + dy + max(dx, dy))

```

Here is a visualization (contour plot) of the function, thanks to Wolfram Alpha:

And here is a plot of its error function when compared to the euclidean distance (radians, first quadrant only):

As you can see, the error ranges from 0% on the axes to approximately +12% in the lobes. By modifying the coefficients a bit we can get it down to +/-4%:

```
dist = 0.4 * (dx + dy) + 0.56 * max(dx, dy)

```

## Update

Using the above coefficients, the maximum error will be within +/-4%, but the average error will still be +1.3%. Optimized for zero average error, you can use:

```
dist = 0.394 * (dx + dy) + 0.554 * max(dx, dy)

```

which gives errors between -5% and +3% and an average error of +0.043%

---

While searching the web for a name for this algorithm, I found this similar octagonal approximation:

```
dist = 1007/1024 * max(dx, dy) + 441/1024 * min(dx, dy)

```

Note that this is essentially equivalent (though the exponents are different - these ones give a -1.5% to 7.5% error, but it can be massaged to +/-4%) because `max(dx, dy) + min(dx, dy) == dx + dy`. Using this form, the `min` and `max` calls can be factored out in favor of:

```
if (dy > dx)
    swap(dx, dy)

dist = 1007/1024 * dx + 441/1024 * dy

```

Is this going to be faster than my version? Who knows... depends on the compiler and how it optimizes each for the target platform. My guess is it'd be pretty difficult to see any difference.
> 32 votes

# Answer
Sometimes this question can arise not because of the cost of performing distance calculations, but because of the **number of times** the calculation is being made.

In a large game world with **many actors**, it is **not scalable** to keep checking the distance between one actor and all the others. As more players, NPCs and projectiles enter the world, the number of comparisons that need to be made will **grow quadratically** with `O(N^2)`.

One way to reduce that growth is to use a good data structure to quickly discard unwanted actors from consideration.

We are looking for a way to efficiently iterate all the actors that **might** be in range, whilst **excluding the majority** of actors which are definitely out-of-range.

If your actors are fairly evenly spread across the world space, then a **grid** of buckets should be a suitable structure (as the accepted answer suggests). By keeping references to actors in a coarse grid, you need only check a few of the nearby buckets to cover all the actors which could be in range, ignoring the rest. When an actor moves, you may need to move him from his old bucket to a new one.

For actors which are less evenly spread, a **quadtree** may do better for a two-dimensional world, or an **octree** for a three-dimensional world. These are more general purpose structures that can efficiently partition large areas of empty space, and small areas containing lots of actors. For *static* actors there is **binary space partitioning** (BSP), which is very fast to search but unsuitable to update in realtime. BSPs partition the space using planes to repeatedly cut it in half, and can be applied to any number of dimensions.

Of course there are overheads to keeping your actors in such a structure, especially when they are moving between partitions. But in a large world with many actors but small ranges of interest, the savings should be far greater than the costs.

Consideration of how the expense of an algorithm grows as it receives more data is called **computational complexity** is crucial for scalable software design. Sometimes simply choosing the correct **data structure** is enough. Costs are usually described using Big O notation.

(I realise this is not a direct answer to the question, but it may be useful for some readers. My apologies if I have wasted your time!)
> 22 votes

# Answer
How about the Chebyshev distance? For points p, q it is defined as follows:

So for points (2, 4) and (8, 5), the Chebyshev distance is 6, as |2-8| \> |4-5|.

Furthermore, let E be the Euclidean distance and C be the Chebyshev distance. Then:

The upper bound probably isn't much use since you'd have to calculate the square root, but the lower bound could be helpful - whenever the Chebyshev distance is large enough to be out of range, the Euclidean distance must be too, saving you from having to calculate it.

The trade-off, of course, is that if the Chebyshev distance is within range, you'll have to calculate the Euclidean distance anyway, wasting time. Only one way to find out if it'll be a net win!
> 4 votes

# Answer
Efforts were made in the past to optimize `sqrt`. Although it no longer applies to today's machines, here is an example from the Quake source code, which uses the magic number `0x5f3759df`:

```
float Q_rsqrt( float number )
{
  long i;
  float x2, y;
  const float threehalfs = 1.5F;

  x2 = number * 0.5F;
  y  = number;
  i  = * ( long * ) &y;  // evil floating point bit level hacking
  i  = 0x5f3759df - ( i >> 1 ); // what the hell?
  y  = * ( float * ) &i;
  y  = y * ( threehalfs - ( x2 * y * y ) ); // 1st iteration
  // y  = y * ( threehalfs - ( x2 * y * y ) ); // 2nd iteration (optional)
  // ...
  return y;
}

```

A detailed explanation of what's going on here can be found on Wikipedia.

In short, it is a few iterations of Newton's method (a numerical algorithm which iteratively improves an estimate), with the magic number used to provide a reasonable initial estimate.

As Travis points out, this kind of optimization is no longer useful on modern architectures. And even if it was, it could only provide a constant rate speedup to your bottleneck, whilst algorithmic redesign might achieve better results.
> 3 votes

# Answer
A very simple local optimization is to simply to check a single dimension first.

That is :

```
distance ( x1, y1 , x1, y2) > fabs (x2 - x1)

```

So just checking `fabs (x2 - x1)` as a first filter may give an appreciable gain. How much will depend on the size of the world versus the relevant ranges.

Furthermore, you can use this as an alternative to the spatial partitioning data structure.

If all relevant objects are sorted in a list in x coordinate order, then nearby objects must be nearby in the list. Even if the list becomes out of order due to not being fully maintained as objects move, then given known bounds of speed you can still reduce the section of the list to be searched for nearby objects.
> 2 votes

---
Tags: collision-detection, mathematics, performance, optimization
---


# Question
Title: What coding issues can be significant in damaging the performance of a game?
I have just finished a 2D game in Java that I've been working on for a while.

I found that on some computers it runs fine, and on others (which are not particularly slow in general), the game runs a little slower, and with minor interruptions every second or so. Not completely smooth.

Since I am a beginner to making games, and probably since I didn't plan everything about the game in advance, the code of the game is rather long, clumsy and probably inefficient.

I want to improve this in my next projects. So my question is - In general, **what would be the main causes for a common 2D game to slow down on a computer**?

What should I pay the most attention to, next time, in order to design an *efficient* game?

* Making a small amount of classes? (Even if the classes are small ones?)
* Avoiding repetition of code? (Even small sections of code, such as short `if` statements).
* Avoiding too many threads running?
* Anything else?

Obviously, all of the above are recommended for an efficient program.

But I'd like to know, what in a game's code, could be ***especially*** significant for making an efficient application, and what would be less important and will not save significant amounts of memory.

**Any advice would be welcome - could be regarding game design, or regarding more specific coding issues.**

*I don't know if this matters, but please note that I'm talking mainly about real-time games, using a 'game-loop' that constantly updates the game and the dispaly.*

Thank you

# Answer
> 2 votes
In my experience, there are some things that greatly affect the performance or my games, and some that do not, as much.

**Most Significant:**

* Running lengthy code all of the time. This can be avoided, at least partly, by checking if any given code needs to be run that frame:

if change == True: do code

else:don't
* With concern for repetition of code, it is always good to make a method or function for it, depending on the programming language.
* Also, you want to find the edge cases, like DMGregory said, and improve their efficiency, or at least do something to make the framerate smoother. Smoother frames look much better than jittery ones, even if they have a slightly less overall framerate.

**Less Significant**

* The more threads that there are, or background processes, or anything else that takes processor time, the less processor use will be allocated to the game
* Your engine: sometimes code that is built into engines is bulky, and has things that you don't need, which you can disable. This will usually save processor time, also.

---
Tags: performance, memory-efficiency
---


# Question
Title: How can I handle different keyboard layouts?
Let's say I have a game that uses WASD controls on a QWERTY layout. Trying to use these controls on, say, a Dvorak layout is not ideal (equivalent to `<A:H` on QWERTY). Obviously, I'd want to use the same physical keys as QWERTY would use (`,aoe` on DVORAK).

I've come up with a few possible solutions:

* Force the user to use QWERTY
    + obviously not ideal, especially for international users
* Change shortcuts based on keyboard layout (WASD -\> ,aoe)
    + forces me to make layout maps for each supported layout (automatable)
    + easiest for the user if there are more shortcuts than just WASD
* Force the user to define shortcuts themselves
    + More flexible
    + Annoying if there are lots of shortcuts
    + Can be used in conjunction with the second option
* Use hardware keycodes
    + consistent across keyboards?

How is this type of thing usually handled?

# Answer
Listen for scan codes. How this is done depends on your OS, which you did not list. On Windows, you can get the scancode for a given virtual key code from WM\_KEYDOWN and friends by using MapVirtualKey. Scan codes are based on the physical key and are unaffected by layout.

Have a quick read of http://www.altdevblogaday.com/2011/10/02/i-never-managed-to-go-left-on-first-try/.

So yes, as Nicol Bolas said, you can and should let users work around it. But just making it work right out of the box is not hard and your users will appreciate it.

Note that you are (probably) handling character input wrong, like the vast majority of game developers. Make sure that for text, you always use WM\_CHAR (or the equivalent on other OSes) rather than using WM\_KEYDOWN for text input. It is completely wrong to assume that when the 'a' key is pressed that you should input an 'a' to a text input control, due to the use of Dead Keys on some layouts. You can also support IME (or OS equivalent) for East Asian markets which have far more characters than can reasonably fit on a keyboard, and need special UI to type. Handling IME in a game is a pain (handling it at all is a pain), but worth it in my opinion to increase the appeal of your product to a much, much larger set of markets. Again, WM\_KEYDOWN is never to be used for text, ever.
> 10 votes

# Answer
You should *always* give the player the ability to change their key assignments. That is how it is "usually handled": let the player change them. Some players will set their keyboard to QWERTY when they play games because that's what most games expect. Some will leave them set to their current keyboard and rely on the ability to change the keys.
> 6 votes

# Answer
In the case you can't listen for scan codes (like for example when developing a flash game) you can make a key binding which works for as many layouts as possible. Most keyboard layouts are very similar, with just a few exceptions.

The keyboard layouts following ISO 9995 (that's most) are arranged like this:

Basically the black keys are safe to use.
> 3 votes

# Answer
Most big budget games (those with an international distributor) will work out of the box, using ZQSD instead of WASD for azerty layouts. A decent game will also introduce the layout in the first level, others will let the player discover it through the customisation screen. The implementation strategy can be detected by asking the OS to switch layouts. Either the game uses scancodes (positions) internally, and maps them to keycodes (symbols) when showing configuration dialogs and prompts; or it uses keycodes internally, and detects the layout at startup or on first launch.

The first strategy (scancodes internally) is more robust, but does require a bit of care to prevent the abstraction from leaking through. Remember to remap scancodes to keycodes when presenting keys to the user (in tutorials, prompts and customisation dialogs). You will still need to look at keycodes when taking text input (letting a player type their name for example). If you need to handle more text than that, look at using the platform's text input support, which is outside the purview of a game engine (handles dead keys, capslock, copy-pasting, advanced input methods…).

When porting a game that never used scancodes (which is not the case with a decent engine, since scancodes are also closer to the hardware and faster), the other strategy might be more practical. You can map scancodes to keycodes using SDL2 functions SDL\_GetKeyFromScancode and SDL\_GetScancodeFromKey, or platform-specific equivalents. If you also use the SDL2 event loop, those functions will remain accurate across layout switches. Avoid functions like GetKeyboardLayout() on Windows; there is no guarantee that you'll be able to find the layout in a known list.
> 3 votes

---
Tags: keyboard
---


# Question
Title: Live capturing from Unity-like application
I need such thing for non-game application:

A city-like 3D scene, containing a few people. People walk, run, stand, ... May be cars also.

Around the scene some cameras are located. And I need them to live stream 2D views to my application. I do not want to capture screen, because I will use lots of such cameras simultaneously.

May be Unity has such feature or something else?

# Answer
You can place cameras in the scene to cicling these cams and capture the video with a other program like Fraps, and saves of scripting time
> 0 votes

---
Tags: camera, streaming
---


# Question
Title: Where can I post job listings or browse through resumes?
\[Hypothetically\] I'm at a smaller company and looking for a place to get the word out about our available openings. Alternately, I'm looking for a place to browse through resumes of people looking for jobs. What are some services I can use to find the people I need?

**Answer Format**

* One URL per answer
* Costs (if applicable)
* Specializations (if any)
* Experiences using the service

# Answer
> 12 votes
## Gamasutra Jobs

This is the canonical place to go if you want to hire a game developer, or become one.

**Cost:**

Recruitment pricing on this page. It appears job postings are free.

**Specialization:**

Game development. "The game industry leader in career resources"

# Answer
> 5 votes
## StackOverflow Careers

FAQ here.

**Costs:**

* 1 year filing: $19 or free for students
* 30 day job listing: $350
* Hiring manager: test drive free, to view candidates and make contact subscriptions are $500 for one week, $1000 for one month, $3000 for 6 months, $5000 for one year
* 90 day money back guarantee if you are dissatisfied

**Specializations:** "professional software developers looking for great places to work" (developers who browse Stack Overflow)

I have no experiences using it, sorry.

# Answer
> 2 votes
Another place you can post job ads is the IGDA boards but they're usually local in nature. On the other hand there are usually freelancers there as well.

# Answer
> 2 votes
Game Industry Grunts

http://gameindustrygrunts.com/

The idea of this site is that it is free for everyone, so non-rich companies, and rich companies that want post entry-level jobs can post there.

# Answer
> 1 votes
## Game Job Hunter

**Cost:**

* Basic job ads - Free
* Spotlight job ads links on home page - $50/week
* Header banner ad, appears on all pages (728x90, jpg or gif) - $250/week
* Skyscraper ad, appears on all pages (120x600, jpg or gif) - $200/week

# Answer
> 1 votes
# Mobile Gaming Jobs

**Costs**: 199 per job. Discounts on multiple jobs and longer terms.

**Specialization**: Focuses on mobile game development only and powers the job listings on several large developer focused sites.

# Answer
> -2 votes
## Microsoft Students 2 Business

(global site, USA site)

**Costs:** Free for students. Maybe free for recruiters?

**Specializations:** students in IT majors (computer science, information technology, etc.)

My only experience was to promote it to fellow students, as my school's Microsoft Student Partner. I personally found it to have a very limited selection of job openings.

---
Tags: hiring, jobs, human-resources
---


title: Lighting Objects with Textures - OpenGL

text:
# Question
Title: Lighting Objects with Textures - OpenGL
I'm trying to get lighting effects on a textured object; I'm using .obj and .mtl files to define them. No matter what I try my object is either invisible, unlit (plain texture), or completely white.

I defined my mtl by having my texture mapped to diffusion (that is, map\_Kd texture.png). I found that if I don't set both a Ka and Kd (in addition to the texture) the object is invisible. Also, it seems that the actual ambient values don't change anything - they could be 0 and transparent, as long as they're defined.

If I set my material to have white ambient, diffuse, and specular, then the object is 100% white, no matter what I do with my light source. This is also after I set it to gl\_separate\_specular\_color, as before that, I just got the plain texture. I tried making sure I had a normal defined for at least one face of the model, with no luck. I'm trying to have my texture be dominant, with a little bit of specular lighting on it.

What am I doing wrong? Is the lighting "working" but the all white means I haven't set my shininess properly? Is it being infinitely reflective or something?

Note: I'm using OpenTK and working in C#.

# Answer
> 3 votes
I figured out that my problem was twofold. One, I didn't have enough normals defined. Two, I was using flat shading. With only one normal to go on, all the faces were using the same normal for shading, hence they all reflected light in exactly the same way. So my model was a uniform color. Adding more normals and using smooth shading made it look nice.

# Answer
> 1 votes
I don't know if the above method works for you, but I had the same problem; I found that I had not specified the normals of the object. So to solve it, just specify the normals before drawing the textures. For example:

```
//specify normals

//front face of cube

glNormal3f(0.0, 0.0, 1.0);

glVertex3f(-1.0, 1.0, 1.0);

glVertex3f(1.0, 1.0, 1.0);

glVertex3f(1.0, -1.0, 1.0);

glVertex3f(-1.0, -1.0, 1.0);

```

Hopefully this will solve the problem for anyone (I tried every other method that I could find, but only this method worked).

---
Tags: opengl, models, lighting
---


# Question
Title: How should I organize Lua scripts so that some entities do not have access to functions they shouldn't?
For my game in C++ I'm using different objects (like player, enemy, et cetera) which will have to be controlled by a Lua script. My problem is that if I were to write a function in my player script, all my other scripts will have access to it as well, and I don't want that.

I can think of three basic solutions:

* For every iteration clear the entire state and re-register everything
* Determine out what functions a script registers and remove them
* Have every gameobject running it's own Lua state

Is there a good way to do this, keeping runtime performance in mind?

# Answer
> 2 votes
You can give each script it's own Evironment. This is the table that is otherwise usually thought of as the global scope. With this, each function that you declare in your script will be confined to that script unless you expose and subsequently explicitly use a name to access the global table, e.g. `_G.myfunc = function foo() end`.

This is sometimes called "sandboxing," thought that term may be a bit misleading since it doesn't fully isolate the scripts.

See https://stackoverflow.com/questions/11013727/sandboxing-embedded-lua-in-5-2-set-envirenment-for-functions-from-lua-file for some code samples.

It's not necessarily a bad idea to use a separate coroutine (state) for each player object, though. This has advantages if you're trying to use more coroutines or a state machine inside the player object. A fully separated top-level `lua_State` is deinitely overkill.

---
Tags: c++, lua
---


# Question
Title: What does it mean to cross a scalar with a vector in a 2D plane?
At the moment, I'm following this page to create a physics engine.

As per that page, I need to cross angular velocity by a distance vector to get relative torque and such, but I'm not sure how (in a 2D plane), you can cross a scalar(angular velocity), and a vector(such as the distance vector). I've assumed so far that you multiply the magnitude, but obviously this isn't correct, as I continue the debugging of my flimsy code. What am I missing?

# Answer
The cross product is not defined between a vector and a scalar, so it means nothing (it would be a malformed operation, or perhaps a mis-interpretion of a simple vector scaling operation).

In the link you provided, angular velocity is a *vector* when it is used in the equation that involves its presence as an operand of the cross product:

> Here we are regarding the angular velocity as a *3 dimensional vector* perpendicular to the plane, so that the *cross product is calculated as*

(Emphasis mine.)

This is in the section "Physics of Collision for Rigid Bodies in 2 Dimensions."
> 3 votes

---
Tags: mathematics, physics, vector
---