# Question
Title: stencil shadows - doom 3 engine - precision errors - shadow cracks - why?
I am testing the limits of the Doom 3 engine - in regards to maximum map size.

I noticed some stencil shadow precision errors that become more pronounced when objects get further and further away from the map origin.

at position: -10901 -18214 -11204

at position: -10802 -26483 -19383

at position: -10802 -34683 -27540

I believe these errors have been referred to as "shadow cracks" but I am not positive what these artifacts have been previously called.

Nearly all of the artifacts appear along the bounds of the lights/shadows - which can be seen here:

Has anyone seen this type of graphical artifact before with stencil shadows? What are they called? What is the cause?

More examples:

This is the vanilla Doom 3 Engine as found here: https://github.com/TTimo/doom3.gpl

I noticed while testing the r\_useOptimizedShadows cvar (which handles the shadow volumes of the worldspawn geometry) that the artifact disappeared. Then I worked my way to this function:

```
R_LinkLightSurf( &vLight->globalShadows, tri, NULL, light, NULL, vLight->scissorRect, true /* FIXME? */ );

```

which I changed to this:

```
R_LinkLightSurf( &vLight->globalShadows, tri, NULL, light, NULL, vLight->scissorRect, false /* FIXME? */ );

```

That gets rid of the artifacts - but now it assumes that we are never inside shadow volumes of the worldspawn geometry. So whenever we do go inside a shadow volume, that shadow volume is not rendered properly.

# Answer
I did finally figure out a solution - actually a few different solutions. I did **not** figure out the actual cause of the artifact from a graphics programming perspective - but I did find some solutions.

As I previously stated in my question, it appeared that the artifact was only occurring on the pre-computed shadow volumes of the worldspawn static geometry (which is basically geometry that the engine knows is never going to move so it pre-calculates ahead-of-time the shadow volumes and other things with a command entered in the console called "dmap"). I did not figure out why it was only on the shadows of the static worldspawn geometry and not on any of the ASE or LWO models.

Now, the thing that I noticed was that there is actually a plethora of parameters that can be used with the dmap command - one of these parameters is called "shadowOpt" - which must stand for shadow optimization level. This parameter sets an enum - there appear to be a few different shadow optimization levels:

```
typedef enum {
    SO_NONE,            // 0 // NOTE: I haven't tried this one yet - should test this one.
    SO_MERGE_SURFACES,  // 1 // NOTE: this was the original default one - it causes some artifacts - the ones I have been trying to fix.
    SO_CULL_OCCLUDED,   // 2 // NOTE: this one works the best - takes a bit longer - but it has alot of unnecessary print statements that could probably be removed.
    SO_CLIP_OCCLUDERS,  // 3 // NOTE: I haven't tried this one yet - but it is not used anywhere.
    SO_CLIP_SILS,       // 4 // NOTE: I haven't tried this one yet - should test this one.
    SO_SIL_OPTIMIZE     // 5 // NOTE: this one doesn't seem to work well at all - and it takes an extrememly long amount of time - was probably an expirimental version.
} shadowOptLevel_t;

```

I have had success with option 2 - "SO\_CULL\_OCCLUDED". It fixes all the artifacts - it takes a bit longer to run - but I believe a lot of this time is spent printing large amounts of information to the console - these prints could probably be reduced or done away with.

One the of the places that gave me some clues was the comment here in tr\_stencilshadow.cpp:

```
// if we are running from dmap, perform the (very) expensive shadow optimizations
// to remove internal sil edges and optimize the caps
if ( callOptimizer ) {

```

Now, the problem with only doing this "extra" shadow optimization during "dmap" is that if any of these lights are ever moved (which is always possible depending on the type of project you are doing) - it will then default back to the "un-optimized" real time shadow volume creation process (for the moved light) and the artifacts will reappear for that light. So the only way to guarantee that these artifacts will not appear is to always run the very expensive optimization process for these static worldspawn shadows. It is in fact very expensive so this would be an absolute last resort if you can't figure out a proper graphics solution. (if you do, make sure to post your solution here.)

I would recommend for anyone creating large maps for the vanilla Doom 3 engine - and using worldspawn geometry - that they create a cvar that they can change depending on their needs for the real-time creation of the optimized shadow volumes. I called my cvar r\_useExpensiveShadowOptimizations - which appears to be an oxymoron. For example:

```
// if we are running from dmap, perform the (very) expensive shadow optimizations
// to remove internal sil edges and optimize the caps
if ( callOptimizer || r_useExpensiveShadowOptimizations.GetBool() ) {

```

I also recommend that depending on how large your maps are(and assuming the lights will not move), that you increase the static shadow volume optimization level with the "shadowOpt" parameter for dmap.

So basically all of the things you need to have a large map and not have shadow artifacts are there for you, you just need to decide which ones you will need to use. Doing it in real time is extremely expensive and should only be done as a last resort if you can't find a proper graphics solution. Doing it in DMAP makes perfect sense as it solves the problem and only takes a few more seconds for the map to compile.
> 3 votes

# Answer
It could very well be a floating pointer precision error, since Doom used `float`s for the rendering (mainly an OpenGL limitation). However, fiddling around `tr_stencilshadow.cpp`, I've noticed this comment which might be related to the issue (inside `PointsOrdered()` function):

```
// vectors that wind up getting an equal hash value will
// potentially cause a misorder, which can show as a couple
// crack pixels in a shadow

....

// in the very rare case that these might be equal, all that would
// happen is an oportunity for a tiny rasterization shadow crack

```

So there it is. It might also be a known limitation of the way the shadow rendering was implemented. Quite frankly, the code is very messy and hard to read, so I can't tell you for sure. You might try mailing the devs to get more info.
> 2 votes

---
Tags: opengl, shadows
---


# Question
Title: How do reflections work for large flat surfaces?
I understand how reflections work for objects. A cubemap would be rendered around a certain point in 3D space, usually at the center of the object that the reflection is to be applied to, and that is the surrounding world it reflections.

But this leads to the question, what about large flat surfaces like floors and walls? If you're only rendering the cubemap from a single point in 3D space, reflections only work for a small area around this. If you walk down the hall and look at the same floor, the reflections would make no sense at all.

How are large, flat surfaces reflected?

# Answer
> 5 votes
For large flat surfaces (water, floors, etc) there is this approach:

1. Scale everything (geometry, camera, lights, etc) upside-down across reflection plane;
2. Clip geometry left above the reflection plane;
3. Render to texture;
4. Render everything as usual except the reflective plane surface;
5. Render reflective plane with reflections texture applied to it (blending/shading/distorting it as needed).

If you don't need any shader effects, it is also viable to just render the upside-down geometry stenciled by visible reflective plane area.

Here's a diagram of how it works (from this excellent GLSL tutorial):

# Answer
> 2 votes
A reflected image is placed on the mirror by first rendering the reflection image using a reflected camera on the other side of the mirror, and then combining the reflection image with the scene image.

The steps of this procedure are as follows:

```
Reflect the camera to the other side of the mirror surface.
Modify the scene model by removing the reflecting surface and other surfaces that block the view of the reflected camera.
Render the reflection image.
Convert the reflection image into a reflection texture map.
Apply a suitable shader to the reflecting surface; this shader uses the reflection texture to simulate the reflections.

```

refer the below link for more details https://renderman.pixar.com/resources/RPS\_13.5/prman\_technical\_rendering/AppNotes/appnote.6.html

# Answer
> 1 votes
I'm not much of a programmer, but since I did lots of researches around the kind of elements you find in background (as I'm having a blast at making video game backgrounds), I had to understand the behavior of the cubemap reflections.

On the basic, the cubemap reflection all work in a single way : the render processor (camera) is able to render up to a circular 180x180 degrees of a 360x360 cubemap. So, if you see the cubemap from a single point of view, you can see up to 5 of the 6 maps from which the cubemap is made of.

That said, there are 3 kinds of cubemap reflections : Predetermined cubemap reflection (mapped) // Real-time Light procedural // Real-time Procedural projection : and each have a different way of working, giving results and being managed.

The predetermined cubemap reflection is pretty much the same thing as a skybox on which a mask is applied which is calculated from the specular value of the material's map. On your example of a large flat surface, this would end up as a big view of the reflected cubemap over the part that have a high amount of specular. On a large surface without any area with low specular value, it would look like a reflection of a picture. (Not really good) This is commonly used on things like windows to simulate cloud/sky reflection in them.

Real-time light procedural is a process on which a initial cubemap is used which act as a kind of specular color, but on which an additional additive layer is added based on the projected lights around its surface. This is the actual best way of simulating heavily transparent glass and metals. There are no "real" reflection as every light reflected are calculated from a single ray projection (which is done naturally from the light in 3D scene) So, for example, if you uses a light with a mask over it, the mask won't appear on the reflecting surface. On the given example of a huge flat surface, it would look good as long as there are no lights too close to it (from the camera view). Otherwise, the light "projected" will seems too bright.

Real-time procedural reflection is actually the thing which is closer to the real mirror reflection. It's a reflection process that involve an additional render process (hidden camera) which project what its seeing onto the meshes with the material. There are 3 main problem with this system. Problem #1 is that you need 1 different material per meshes and, so, 1 generated hidden camera. Otherwise, you'll end up with the same reflection point of view on all the meshes). Problem #2 is the it's highly costy on the performance. #3 is that the reflection might be of poor quality or not include any camera filter you might be using like Anti-aliasing, blur, dynamic fog, etc. Best example of this one is for water and mirror reflections.

Those are 3 different ways of using the cubemap reflection and have different uses.

For your example of a huge hall with the reflective floor, those are the final result you'll end up with :

With the simple cubemap reflection : you'll have a view similar as if the floor was made of glass with a skybox under it. Big issue is if you have multiple room with the same floor. This would require multiple cubemap reflection materials.

With the Real-time Light procedural, you'll have a view as if the floor was made of metal, plastic or any materials that doesn't reflect much detail, yet have a high amount of light reflected. Unlike the regular specular channel, this one actually apply spot-like light effects on the meshes faces. Since there are no "reflected object" and since the light projected are procedural, you can use the material multiple time without any change nor adjustment.

For a Real-time Procedural projection, you get high fidelity result. The amount of material using this process should be reduced to a minimal. For example, the game Watchdog from Ubisoft make uses of it for things like the streets' water ( http://media1.gameinformer.com/imagefeed/featured/E32012/Ubisoft/watchdogs/WatchDogs1.jpg ) In this screenshot, you can see the reflection of the city which is created in real-time based on the point of view of the camera. While it look awesome, you might also notice that nothing else uses the same kind of reflection. Simply put, it's because it's actually a procedural (Substance Designer) layer on the material which project the pixels shown from a hidden secondary camera which is created from the collision of a raycast shot by the camera in real-time. (In other words, having that reflection is similar, in CPU and GPU, as having 2 player playing on the same screen)

Might not be what you wanted to know (or too much), but I hope this will help you understand how vaste the cubemap reflection is and how it works.

---
Tags: 3d, cubemap, reflection-rendering
---


# Question
Title: How do I make a pop-up window with Scene2D?
I have a main-menu screen with a logo and a bunch of buttons. When the Login-button is pressed, I pop up a dialogue asking for a username and password.

This works fine, other than the "popping up". At the moment the new the dialogue box just shifts everything about, but I'd want to position it *over* the current scene.

I'm just learning Scene2D.

# Answer
> 11 votes
Dialog is better suited for modal pop-up windows, and it includes a "button" and "content" table already in the window (as the docs say). You can grab these tables with getButtonTable() or getContentTable().

The dialog makes it easy to work with pop up windows. For example, here is a confirmation dialog:

```
Dialog dialog = new Dialog("Warning", skin, "dialog") {
    public void result(Object obj) {
        System.out.println("result "+obj);
    }
};
dialog.text("Are you sure you want to quit?");
dialog.button("Yes", true); //sends "true" as the result
dialog.button("No", false);  //sends "false" as the result
dialog.key(Keys.Enter, true); //sends "true" when the ENTER key is pressed
dialog.show();

```

You can use other objects for, say, Yes/No/Cancel options.

# Answer
> 0 votes
Right well, since no one has replied, I will post my solution.

When adding Actors to the Stage, rather than doing:

```
stage.add(actor);

```

Which adds a Cell with the given Actor in it, I done the following:

```
stage.addActor(actor);

```

I was then free to overlap actors and move/scale/rotate them via tweening. The only probably I currently see with this is the absolute positioning of Widgets.

In order to position them you have to call:

```
actor.setPosition(x, y);

```

So it could be a little difficult when dealing with Android devices of different aspect ratios and resolutions.

---
Tags: java, libgdx, menu, scene2d
---


# Question
Title: How to take a screenshot with java from directX
I'm looking for a way to take a screenshot with a Java application of any running directX game. I use the following code

```
Robot robot = new Robot();
GraphicsConfiguration config = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDefaultConfiguration();
BufferedImage screenshot = robot.createScreenCapture(config.getBounds());
ImageIO.write(screenshot,"png", file);

```

This one works perfectly anywhere but in directX games. I'm not that familiar with Java and even less with DirectX, I'm just trying to adjust this code. I googled very much, but everything just leads to the same code I already have.

Do you know of another way to take a screenshot of DirectX games?

Thanks.

# Answer
> 2 votes
Try doing this:-

```
try {
                Robot bot = new Robot();
                bot.keyPress(KeyEvent.VK_F6);
                bot.delay(50);
                bot.keyRelease(KeyEvent.VK_F6);
            } catch (AWTException ex) {
                Logger.getLogger(main.class.getName()).log(Level.SEVERE, null, ex);
            }

```

---
Tags: java, directx, screenshot
---


# Question
Title: How to detect when two bitmaps intersect in Android
I made two bitmaps based off of two ImageViews using this code:

```
playerimage.buildDrawingCache();
Bitmap bplay1 = playerimage.getDrawingCache();
brickimg.buildDrawingCache();
Bitmap bbrick1 = brickimg.getDrawingCache();

```

I tried getting the height and width of each bitmap for collision detection, but it made the app crash. This is what I used for it:

```
int w1 = bplay1.getWidth();
int h1 = bplay1.getHeight();
int w2 = bbrick1.getWidth();
int h2 = bbrick1.getHeight();

```

Is there a different way to get the coordinates of a bitmap to test collision detection?

# Answer
> 2 votes
You should be able to use Rect.intersects(Rect, Rect), like this example:

```
Rect myViewRect = new Rect();
myView.getHitRect(myViewRect);

Rect otherViewRect1 = new Rect();
otherView1.getHitRect(otherViewRect1);

Rect otherViewRect2 = new Rect();
otherView2.getHitRect(otherViewRect2);

if (Rect.intersects(myViewRect, otherViewRect1)) {
  // Intersects otherView1
}

if (Rect.intersects(myViewRect, otherViewRect2)) {
  // Intersects otherView2
}

```

---
Tags: android
---


# Question
Title: Do I need to copyright my game before releasing it on the Android Play store?
I am developing a game on Android and I was wondering if I have to copyright it before putting it on the store (so no one can steal the idea)?

# Answer
> 8 votes
While this depends on the country in which you are publishing, as not all countries will have the same copyright laws/regulations, copyright is implicit. There is nothing to register specifically to mark it as copyright unlike a patent which has to be applied for.

The difficulty comes in asserting your copyright. In the event that someone does infringe your copyright it's always good to have proof of when your implicit copyright protection took place. However the date of first publication on a store will suffice and any records of development, i.e. dates on your source repository.

Keep in mind a few things though. Copyright will essentially protect you against people taking your game and either using the assets from it or hijacking it via a straight clone. However, game mechanics and general ideas are not generally enforceable via copyright laws. They may be via patent law, but even then it's probably unlikely.

This is too your advantage. If this weren't the case, think how empty the games market would be. Only one company would be able to produce FPS games without paying a license fee to the copyright holder.

So long story short, if you want to have a market advantage, be the first to publish and market the hell out of it. Don't worry about people stealing the idea. If it's a good one, they will anyway and there isn't much you can do about that.

# Answer
> 1 votes
You need to go through steps and be careful at few steps as well while publishing app on play store. Refer this link for more details:

http://developer.android.com/tools/publishing/publishing\_overview.html

---
Tags: android, copyright
---


# Question
Title: Different kinds of collision detection in Android
Are there any other ways to detect collision between two objects besides the bounding rectangle method and downloading another class to put into Android?

# Answer
> 2 votes
Android does not limit your options when it comes to collision detection.

Here is a nice article about SAT collision detection: http://www.codeproject.com/Articles/15573/D-Polygon-Collision-Detection

That implementation also has the nice feature of being tunneling free. That is, if two object with very high speed intersect each others paths in such a way that they will overlap in the current frame, it will still detect it as an collision.

I think you need to rephrase your question. Are you going to do 3d collision detection, is the performance important, are there any special properties of your polygons (eg, maybe they are concave instead of convex?)

What is it that you want to do with collision detection?

# Answer
> 2 votes
Refer the below site for some guidance:

http://www.kilobolt.com/day-4-collision-detection-part-1.html

It explains bounding shapes that will be used to check for collision. In the case of our robot, we will be using four bounding rectangles. I will suggest to give more specific requirement so that I can update my answer more helpfully.

---
Tags: android, collision-detection
---


# Question
Title: Making a Collision Detection for ImageViews
I'm trying to make a collision detection system for two ImageViews, but I can't seem to figure it out. I've tried doing several things from StackOverflow and other places, but they don't work. One ImageView stays still and the other moves toward it (it's animated, not a sprite). They don't do anything when the collide, though. Do I need to make them sprites or drawables on a canvas or something?

# Answer
> 3 votes
Get information (dimensions, coordinates) of two imageviews, then use rectangle intersection condition. Assume that two rectangles A, B with coordinate of top-left and buttom-right as follow:

```
Rectangle A: (Xa1, Ya1) ; (Xa2, Ya2)
Rectangle B: (Xb1, Yb1) ; (Xb2, Yb2)

```

Overlap condition:

((Xb1 - Xa2)*(Xb2 - Xa1) \<= 0) && ((Yb1 - Ya2)*(Yb2 - Ya2) \<= 0)

Refer the below site for some guidance:

http://www.kilobolt.com/day-4-collision-detection-part-1.html

It explains bounding shapes that will be used to check for collision. In the case of our robot, we will be using four bounding rectangles.

---
Tags: android, collision-detection, image
---


title: Steering in top-down racer with Libgdx

text:
# Question
Title: Steering in top-down racer with Libgdx
I'm a beginner in game development and as a little project I thought I should try to do a top-down racer game much like the good old Slicks n Slide.

I've seen several tutorials and questions about steering and car physics but most is more complicated than what I need and uses box2d with wheels turning and so on.

I want it to keep simple and only want three buttons. Accelerate, turn left and turn right. And my "car" is for now just a circle :-)

My question is how to do the steering. If someone can explain it simple to me I would be very thankful. I know I need to use sin and cos to get the steering angle but I haven't figured out how.

# Answer
For a very minimalistic car you won't need anything other than two values: `velocity` and `direction`. Both values can be just a floating point number.

When steering left/right, adjust the `direction`, which could be as simple as being the angle the car is facing. Accelerating or breaking will modify the `velocity`.

```
if (key_left)
    direction -= 0.001;
else if (key_right)
    direction += 0.001;

if (key_up)
    velocity += 0.001;
else if (key_down)
    velocity -= 0.001;

```

To move the car, you'd use simple trigonometry:

```
pos.x += velocity * cos(direction);
pos.y += velocity * sin(direction);

```

Of course you can modify this further, e.g. only adjusting `direction` based on `velocity` (so you can't turn while standing still). In addition, you'll most likely want to add some friction as well:

```
velocity *= 0.99;

```
> 1 votes

---
Tags: libgdx, steering-behaviors
---


title: Slide to reveal in AndEngine

text:
# Question
Title: Slide to reveal in AndEngine
I was designing the game in that i want to cover the scene with black layer and i want user to see it when he slide the image. Is there any functionality in AndEngine for something like slide to unlock.

# Answer
> 1 votes
There are only a very few GUI elements in AndEngine. You will have to implement it yourself. Take a look at `SurfaceGestureDetector` for the slide gesture.

---
Tags: andengine, gestures
---


# Question
Title: How do we detect keypresses in a sequence?
```
using UnityEngine;
using System.Collections;

public class TrollingRowlandMK2 : MonoBehaviour {

    int cheat_progress = 0;
    float cheat_delay = 0.0f;

void detect() {if(cheat_progress == 0 && Input.GetKeyDown("1")){
            ++cheat_progress; cheat_delay = 1.0f; Debug.Log ("1 pressed");
    } else if(cheat_progress == 1 && Input.GetKeyDown("2")){
        ++cheat_progress; cheat_delay = 1.0f;
    } else if(cheat_progress == 2 && Input.GetKeyDown("3")){
        ++cheat_progress; cheat_delay = 1.0f;
    } else if(cheat_progress == 3 && Input.GetKeyDown("4")){
        ++cheat_progress; cheat_delay = 1.0f;
    } else if(cheat_progress == 4 && Input.GetKeyDown("5")){
        ++cheat_progress; cheat_delay = 1.0f;
    } else if(cheat_progress == 5 && Input.GetKeyDown("6")){
        ++cheat_progress; cheat_delay = 1.0f;
    } else if(cheat_progress == 6 && Input.GetKeyDown("7")){
        ++cheat_progress; cheat_delay = 1.0f;
    } else if(cheat_progress == 7 && Input.GetKeyDown("8")){
        ++cheat_progress; cheat_delay = 1.0f;
    } else if(cheat_progress == 8 && Input.GetKeyDown("9")){
        ++cheat_progress; cheat_delay = 1.0f;
    } else if(cheat_progress == 9 && Input.GetKeyDown("0")){
        cheat_progress = 0;
        //Some cheats here
        Application.LoadLevel(3);

    }
    /*if(cheat_delay > 0.0f){
        cheat_delay -= Time.deltaTime;
        if(cheat_delay <= 0.0f){
            cheat_delay = 0.0f;
                cheat_progress = 0;}*/
        }
    }

```

We're trying to detect the keypresses and change the level, like a cheat code, but even when we debug, it doesn't seem to be detecting the keypresses.

# Answer
Chaining `Input.KeyDown()` and using a progress counter is a very rigid approach. You will find it difficult to modify or extend.

You may find `Input.inputString` more adaptable. On each frame it will hold the ascii value of any keys pressed since the last frame. It could be used like this:

```
public string cheatCode = "1234567890";
public float timeoutDuration = 1.0f;

private string userInput = "";
private float timeoutTime = 0.0f;

public void Update() {
    if(Input.inputString.Length > 0) {
        timeoutTime = Time.time + timeoutDuration;
        userInput += Input.inputString;
        if(userInput.Contains(cheatCode)) {
            //activate cheat
        }
    }
    else if((Time.time > timeoutTime) && (userInput.Length > 0)) {
        userInput = "";
    }
}

```
> 2 votes

---
Tags: unity
---


# Question
Title: How to draw a diagonal fade-in and fade-out?
How to draw a diagonal fade-in/fade-out in 2D using MonoGame draw API?

For a simple (non-directional) fade-in/out drawing the background with alpha variation do the tricks, but what is the standard way to fade-in/fade-out directionally in 2D?

(The background is a texture, not a unicolored background)

# Answer
> 2 votes
Creating an horizontal or vertical gradient is very simple. Anything else is going to be a little more complicated.

If you are looking to strictly create an horizontal or vertical gradient, you can do it as follows. This will create a RenderTarget for a horizontal gradient:

```
//create a blank 1x1 white texture
Texture2D BlankTexture = new Texture2D(GraphicsDevice, 1, 1, false, SurfaceFormat.Color);
Color[] color = new Color[1];
color[0] = Color.White;
BlankTexture.SetData(color);

//Set gradient colors
Color ColorA = Color.Blue;
Color ColorB = Color.Red;

//Create a rendertarget for horizontal gradient
Render = new RenderTarget2D(GraphicsDevice, 1, GraphicsDevice.Viewport.Height);

//Draw horizontal gradient
GraphicsDevice.SetRenderTarget(Render);
SpriteBatch.Begin();

for (int i = 0; i < Render.Height; i++)
    SpriteBatch.Draw(BlankTexture, new Rectangle(0, i, GraphicsDevice.Viewport.Width, 1), Color.Lerp(ColorA, ColorB, i / (float)Render.Height));

SpriteBatch.End();
GraphicsDevice.SetRenderTarget(null);

```

Then you can draw this across your screen, by stretching it along your viewport to create a smooth gradient effect:

```
SpriteBatch.Begin();
SpriteBatch.Draw(Render, new Rectangle(0, 0, GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height), Color.White);
SpriteBatch.End();

```

---
Tags: c#, 2d, monogame, graphic-effects
---


title: Enemy clones don't target player

text:
# Question
Title: Enemy clones don't target player
In a small game that I'm making enemies multiply when you kill them, however when clones are instantiated they don't chase the player like the original prefabs do (example: http://gfycat.com/VastActualElver)

Here is relevant part of my code:

```
 #pragma strict
    var moveSpeed : int = 3;

    var player : Transform;
    var MaxDist = 10;
    var MinDist = 1;

    function Update () {
        if(curhealth <= 0){
            Dead();
        }
        transform.LookAt(player);
        if(Vector3.Distance(transform.position, player.position) >= MinDist){
            transform.position += transform.forward * moveSpeed * Time.deltaTime;
        }
    }

function Dead () {
    Destroy(gameObject);
    var posx = Random.Range(-10, 10);
    var posz = Random.Range(-10, 10);
    Instantiate(enemys, Vector3(posx, 0.5, posz), transform.rotation);
}

```

What am I missing?

# Answer
> 3 votes
You are not setting the Player transform of your clones, most likely.

If I had to guess, you drag and drop the Player object onto your prefabs that are in your scene. This effectively maps your player onto your Transform object. However, if you clone the enemy, the object is a new instance, and the player transform is not initialized.

Example on how to set player transform in code:

```
player = GameObject.Find("PlayerObject").transform;

```

---
Tags: unity, javascript
---


# Question
Title: Where does my .sav file default to in XNA 4.0 when using the StorageDevice class?
I am using the StorageDevice class built into XNA and am looking to delete my save file from the solution in my XNA game. I never specify where the save file is to save, and can't find the default location on MSDN documentation. I am developing this game for the pc, and never prompt the user to select a save device. Where can I find the save file so that I may delete it?

# Answer
> 2 votes
Some high level details on storage in XNA can be found on this MSDN page.

The paragraph with the most relevance to your question would be:

> User storage is in the My Documents folder of the user who is currently logged in, in the SavedGames folder. A subfolder is created for each game according to the titleName passed to the BeginOpenContainer method. When no PlayerIndex is specified, content is saved in the AllPlayers folder. When a PlayerIndex is specified, the content is saved in the Player1, Player2, Player3, or Player4 folder, depending on which PlayerIndex was passed to BeginShowSelector.

The saved game file should be located within the SavedGames sub folder found within MyDocuments. You should find a folder hierarchy similar to that of the parameters you passed into your storage function calls.

---
Tags: xna, pc
---


# Question
Title: Texture is black when manually building mipmap
I am trying to manually build a mipmap from a series of images. For the sake of brevity, let's assume the file containing the images I want (from 256x256 to 32x32) have paths `file_1...4`.

What I do to load the texture is:

```
GLuint textureID;
glGenTextures(1,&textureID);
glBindTexture(GL_TEXTURE_2D, textureID);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 4);

for i from 1 to 4
    unsigned char* image =  stbi_load_from_file(file_i, &width, &height, &comp, 3);
    glTexImage2D(GL_TEXTURE_2D, (i-1), GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, image);
    stbi_free_image(image);

```

When I go and try to use this created texture in a render all I got is a black result. Using singularly each texture works properly, so I excluded they're malformed. What can it be?

# Answer
The only apparent error in your code is that you seem to specifying 4 mip-levels, from level 0 to level 3, however, you set `GL_TEXTURE_MAX_LEVEL` to 4. The max level is the zero-based index of the last mip-level, so in this case, it should be 3:

```
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 3);

```
> 5 votes

---
Tags: opengl, textures, mipmaps
---


# Question
Title: OpenGL / Soil Image Loading Difficulties
# The Problem

I am attempting to load and display an image in OpenGL using the SOIL library. I originally started with lodePNG but I had difficulties getting the image to display so I assumed it was just a library issue and decided to switch to SOIL, however, as I am having the same issue now I believe it must be something that I am doing wrong somewhere in my own code.

So, the exact issue is that I seem to be able to load a texture correctly: the width and height attributes get set to the appropriate value, and if I just dump the data it loads to console it seems to have actually grabbed the appropriate data (Screenshots later on). The problem comes when I try to render it, I believe my shader and loading code to be correct, however I only get a black square upon rendering. I have been working on this for a couple of days now, trying lots of iterations and have even seperated out all of my framework code and have a completely barren example now that just loads up OpenGL and needed libraries and tries to render.

I am seriously at a loss as to what I am doing wrong, I am using GL\_TEXTURE1 as my active texture but I originally started with GL\_TEXTURE0 so I don't think that would be the problem.
Beyond that I can't think of anything that I am glaringly doing wrong; console output from Bitmap.cpp DOES output correct data (the image to display is 64x64) and when I dump the char\* it outputs a large amount of data that was loaded into it.

# EDIT

I managed to fix it, I honestly can't believe I missed this but when I switched from lodePNG to SOIL I never added the 4 lines that set the attributes of the images. Adding these lines fixed everything right up and made it render

```
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);

```

# Bitmap.cpp

```
GLuint BitmapLoader::Load(std::string path) {
    glEnable(GL_TEXTURE_2D);

    GLuint texture_id;
    glGenTextures(1, &texture_id);

    glActiveTexture(GL_TEXTURE0);
    glBindTexture(GL_TEXTURE_2D, texture_id);

    image = SOIL_load_image(path.c_str(), &width, &height, 0, SOIL_LOAD_RGBA);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, image);

    std::cout << "Width: " << width << ", Height: " << height << std::endl;
    std::cout << "Image ID: " << texture_id << std::endl;
    std::cout << "Image Data: " << image << std::endl;

    SOIL_free_image_data(image);

    if (texture_id == -1) {
        return -1;
    }

    return texture_id;
}

```

# Answer
I'm not sure if I should just delete the question since I solved it on my own or if I should leave it up for others to see in case they have the same problem. For now I am going to add my edit to this as an answer but if I should just delete the entire question let me know! I'm relatively new to Stack Exchange and am not really sure.

The problem with the texture loading was that I was not setting the attributes of the image upon load, setting these 4 parameters seemed to fix everything up and now causes it to render correctly.

```
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);

```

# Bitmap.cpp (Full Version)

```
GLuint BitmapLoader::Load(std::string path) {
    glEnable(GL_TEXTURE_2D);

    GLuint texture_id;
    glGenTextures(1, &texture_id);

    glActiveTexture(GL_TEXTURE0);
    glBindTexture(GL_TEXTURE_2D, texture_id);

    image = SOIL_load_image(path.c_str(), &width, &height, 0, SOIL_LOAD_RGBA);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, image);

    std::cout << "Width: " << width << ", Height: " << height << std::endl;
    std::cout << "Image ID: " << texture_id << std::endl;
    std::cout << "Image Data: " << image << std::endl;

    SOIL_free_image_data(image);

    if (texture_id == -1) {
        return -1;
    }

    return texture_id;
}

```
> 3 votes

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


# Question
Title: How to properly do top-down aRPG melee attacks?
I'm reposting this from my own thread in Reddit's Gamedev community since there were too few responses.

I've been looking for some info on that, but I mostly find articles on the *design* of such systems, which are very useful, but not helpful from the coder's point of view. My main idea is similar to what the 2D Zelda games used to do but with more directional freedom. In Zelda, you can only face one of the cardinal directions and attack the enemy there.
My idea is to have the same but with any direction, since we now have analog sticks, or even mice. I'm pretty sure this has been done before, and a few Flash games come to mind, such as the Zombie Apocalypse game Dead Frontier (which is now done on Unity3D, but was Flash back when I played it)

I'm working with Unity3D (although I'm making a 2D game), and I'm not completely happy with where I'm going.

The above image is my current hacky solution for a Melee hit check. The green triangle is the player, the faint green circle is a trigger that checks if there are enemies in this trigger, and the red boxy thing is an enemy.

When the player presses the "melee attack" button, it picks one of the enemies in the trigger (by order of the first one to enter the trigger) and causes damage.

Among a few things I've added are: slow down the player's movement during an attack, so that they can't "run n' slash" through an entire level, and also limit how many attacks the player can do per second. An attack cannot start if the previous one hasn't finished yet.

This is looking a bit crude, though. I just kind of hacked it together and it doesn't feel as natural as in other games I've played.

Here's my hacky Melee Attack script in my prototype (it uses a few magic numbers, such as the attack duration):

```
void Update()
{
 //other logic
    if (Input.GetMouseButtonDown (0) && sec <= 0)
    {
        attackDuration = 0.5f; //setting how long the attack takes from start to finish
    }
    if (attackDuration > 0)
    {
        attackDuration -= Time.deltaTime;
        if (attackDuration <= 0.25f && !done) //cause the damage when the attack is halfway done
        {
            if(EnemiesInRange.Count > 0)
            {
                Enemy target = ((GameObject)EnemiesInRange[0]).GetComponent<Enemy>();
                target.health -= 10;
                if (target.health <= 0)
                {
                    EnemiesInRange.Remove(target.gameObject); //if the enemy dies, it's no longer a valid target.
                }

            }
            done = true;
        }
    }
    else
    {
        done = false;
        sec = 0; //attack over, reset it to zero (to avoid stuff like -0,001)
    }
//other logic
}

```

Meanwhile, in the CharacterMovement.cs script:

```
void Update()
{
//other logic
    if(gameObject.GetComponent<MeleeAttack>().sec <= 0)
    {
        lookAtMouse();
        transform.Translate(new Vector3(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"), 0) * baseSpeed, Space.World);
    }
    else
    {
        transform.Translate(new Vector3(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"), 0) * (baseSpeed*0.25f), Space.World);
    }
//other logic
}

```

What I'm doing here is stopping the player to change their facing during the attack as well as slowing the movement down to 1/4 the base speed.

Anyway, any advice? How could I make attacking and moving feel more natural? What about the hit mechanics themselves?

My biggest gripe right now is: **I don't think "Pick an enemy in a small circular area ahead of the player" is really good.** What should I do?

# Answer
To help you with collision : There are ways to check for pixels changing color(being drawn over eachother) but I don't use that. I give all object in the game a Bounds Property. The Bounds is a Rectangle that is at the position of the object(enemy/character). Rectangles have a method .Intersects that allows you to see if two rectangle are intersecting. When moving I use a velocity variable that takes the games ellapsed time * the character's movement speed. When I choose attack I check to see if the characters bounds + his Melee Range are intersecting with the enemy's bounds.

It would look something like this :

```
gameTime = this.GameTime;
velocity = (float)(gameTime.TotalEllapsedTime.MilleSeconds);

Character.Bounds = new Rectangle(Character.Position.X, Character.Position.Y,Character.Widht, Character.Height);

characterMeleeBounds = new Rectangle(Character.Position.X + HeroMeleeRange, Character.Position.Y + HeroMeleeRange,Character.Width + HeroMeleeRange, Character.Height + HeroMeleeRange);

if (characterMeleeBounds.Intersects(Enemy.Bounds)){

//Enemy is hit

}

```

The limitations of this is that it is limited to a Rectangle, or a collection of Rectangles if you were to make a List to make up an abstract shape. You would then have to loop through the rectangles to see if any of them have intersected with the object.
> 0 votes

# Answer
> Anyway, any advice? How could I make attacking and moving feel more natural? What about the hit mechanics themselves?
>
> My biggest gripe right now is: I don't think "Pick an enemy in a small circular area ahead of the player" is really good. What should I do?

You could have the hit detection and movement restrictions match your attack animations. If the hit detection matches the shown position of the weapon as it moves during an attack, the visual experience will synch with the game effect, and the player can learn how to place themselves to choose which target to try to hit.

You and playtesters can play with it a bit, and tweak it to remove movements that don't look or seem right.
> 0 votes

---
Tags: 2d, unity, combat
---


title: Oblique launch within a game

text:
# Question
Title: Oblique launch within a game
I'm creating a simple game in python that will follow the same logic of DDTank and Worms. The graph is formed by characters. The buildings that will be destroyed are formed by '\*', players are '@' and the projectile I still did not think the character. For now I did the part that draws the buildings with a random height.

But I was thinking the logic of launching projectiles. I learned in physics classes some formulas for oblique launch. So wanted to know if these formulas would fit in a computer program or I would have to invent another logic?

Formulas:

```
vx = v0 . cos ?
x = vx * t
v0y = v0 * sen ?
y = v0y * t + g * t² / 2

```

# Answer
> 2 votes
Although you can use this type of equasions they are quite unhandy. These are derived from intigration where a fragment of time known as delta time or even dt limits to zero. They are most precise but usually unfit for physics engine due to the complexity of finding the time at which the object or projectile will collide. The complexity grows with more dynamic objects and once those dynamic object may appear at any time the system simply becomes unmaintainable. In other words I highly recommend you not to use them...

So what it is best to do is create a fixed delta time which is most commenly the duration of your frame or 1/FPS seconds.

The eqasions are then as easy as:

```
position = position + speed * dt

speed = speed + force * dt

```

Then on each frame you would call for each projectile to move in which you would compute both, the new speed and the new position. After you have moved the projectiles you should check for crashes and handle them if any.

Note that all of those parameters I used are vectors except the `dt`. The gravity in your case would be a constant force vector of (0,G).

To add a bit on your specific case: if the user input would be an `angle` at which the projectile would be launched and its absolute speed `aSpeed` then all you needed to do in the begining is to determine the `speed`:

speedX = aSpeed * cos(angle) speedY = aSpeed * sin(angle)

Then if for instance your gravity acceleration is 10 (m/(s\*s)) and your FPS is 10 you would in each frame call:

```
speedY = speedY - 10 * 1/10

positionX = positionX + speedX * 1/10

positionY = positionY + speedY * 1/10

```

---
Tags: physics, graphics, python, logic
---


# Question
Title: XNA - DrawIndexedPrimitives or DrawUserIndexedPrimitives?
When rendering primitives in XNA, does it matter if I use `DrawIndexedPrimitives()` versus `DrawUserIndexedPrimitives()`? RB Whitaker uses the former, while Reimer's uses the latter.

From what I can tell, the *intent* is that if you're using a premade type that ships with XNA (such as `VertexPositionNormalTexture`), you should use the normal draw primitives function, while if you create a custom struct which satisfies `IVertexType` and/or `VertexDeclaration`, you should use the DrawUserPrimitives instead.

However, XNA places no such restriction on how they're used, and I am wondering why it wasn't just all rolled into one generic function to begin with.

# Answer
`DrawUserIndexedPrimitives()` takes your vertices and indices from RAM, sends them to buffers on the GPU, then draws them. That means the data is sent to the gpu every time you call this function.

`DrawIndexedPrimitives()` requires you to create and set both a vertex and index buffer before calling it, and the data will stay on the gpu until those buffers are disposed. (See MSDN's example.)

So the latter takes a few extra lines to get working, but will perform at least as well as the former in every situation I can think of, and a *lot* better in most situations. This is true even if the vertex data changes every frame, because of dynamic buffers.

If you're only going to draw something once, then the User function is just easier to use. Otherwise, I would avoid it.
> 2 votes

---
Tags: xna, 3d
---


# Question
Title: How to implement a hint-system for nearby matches (in a Match-3 puzzle game)?
Taking *Candy Crush* as an example:

In a Match-3 game, how would you figure out which nearby tiles are 1 move away from creating a match?

Do you basically have to do it by trial-and-error on every single possible moves (behind-the-scenes) to see which resulting matches it would create?

# Answer
One way would indeed be to try out the four possible moves for every tile (or rather the ones that have recently moved) and check for matches, then store them as hints. You wouldn't need to do this as often as you might think (especially if you only do it for tiles that have moved); you would only need to swap every tile twice since the one next to it would overlap its two other swaps. Like this:

Another way would be to check the surrounding tiles without simulating anything in the background. The best way to do that would be as follows.

Say you have a tile that just moved (center). Focus only on its color and the tiles that are occupied in this diagram:

Here are all possible matches for the four possible moves (6 blue, 6 red, 4 green):

However, you don't need to check for all of these. What you have is a decision tree; all you need to check are if the orange ones match your center tile. If they do, then you proceed to check the secondary ones. Here's a diagram that connects the orange tiles to their secondary tiles (notice how you only need to do four checks for the green matches and not 8 since the other 4 are the same):

Depending on what kind of data structure you store tile data in, these checks can be extremely fast to the point where you don't really need to do any significant optimization. I personally can't think of any other shortcuts.
> 3 votes

---
Tags: algorithm, tiles, puzzle, patterns, movement-prediction
---


# Question
Title: How should IDs be assigned in an entity component system?
I haven't actually implemented this system yet. I'm trying to work through the major conceptual hurdles before I actually start writing code, and the proper way to generate IDs is a little confusing to me. Should I just give each entity an integer ID in the order that it's created? Use the C# guid? What is the proper way to assign IDs in such a way that there won't be issues later on?

# Answer
The sole constraint of an identifier in an entity component system is that the generated identifier be unique. That's the only criteria. If it's unique, it's good.

Any method which satisfies this one constraint is a proper way to assign IDs.

* *guid?* Fine.
* *integer from an incrementing counter?* Provided the counter isn't going to overflow during play, that's fine too.
* *random integer?* Provided the integer is big enough, this is the same as a guid, so is fine. If you're generating smaller random numbers, you'll probably eventually randomly generate a duplicate ID, so that wouldn't be ideal.
* *current time as returned by a high-resolution timer?* Sure, if you're certain that you're not going to generate more than one id per whatever resolution the timer's using.
* *hashed string?* See the comment above about random integers; same deal here.

Doesn't matter. Do any of the above, or do some other method that I haven't thought of. As long as whatever method you pick generates unique identifiers, that's all that matters.

Ignore folks who argue about which method is faster. This is just generating unique identifiers; it will almost definitely not be a factor in your game's execution time. Trying to optimise this sort of thing for speed is a total waste of effort until you have profiler results which prove otherwise. And in that case, the only thing you'd have to change is this one function which generates the identifier. It wouldn't be a major change to switch from one mechanism to another.

So do whatever you're comfortable with, and don't stress about it.
> 11 votes

# Answer
I don't think there is a proper way. You might want to let the user assign his own identificators on creation, if he wants, it's what Ember does, it then lets you retrieve entities by it. Artemis probably uses consecutive integers, reusing them if they're freed when an entity is destroyed, because it uses an array implementation.

Personally i use the consecutive integer approach, because inside of the manager i store entities in an array and i want to be able to quickly access an entity by its index. Reusing identificators means that you don't have to use lists because you don't shift the array when removing an entity. Also, for me in code identifying entities comes down to `entity1.id() != entity2.id()`, not `entity1.id() == 'player'`.

It depends on your needs. If you're using an array approach, then the algorithm is simple, pop an id from the id stack, or if the stack is empty, assign the next integer. When destroying an entity, push the id to the stack. If you're using lists and just want a unique identifier then you don't even need this, unless you're worried that somebody might create four billion entities.
> 4 votes

# Answer
Our ES implementation basically uses an unsigned integer to assign a unique ID to each entity that gets created. The entity ID is essentially an index offset to various subsystem vectors where component data is stored. When an entity is destroyed at the end of the frame, those IDs are placed into a free list and simply reused later.

In other simulations & in networked games, I've often resorted to some 64-bit ID which we referred to internally as a GUID that identified a few characteristics about the entity by simply doing some bitwise math.

As for editor friendly names or possibly encounter-specific names that make scripting easy, we generally associate a TagComponent to those entities. It allows us to query entities by some human readable name such as "General of Death" or some system-defined name such as "Target", "Player", "TargetTarget", "Leader", etc.
> 3 votes

# Answer
A little late to the party here but thought I'd add a few suggestions and reasoning behind each which should be considered when considering these or other suggested answers mentioned in this thread. I've faced the same question and the answer always seems to be to decide which trade-offs best suit my particular situation. My suggestions are based on c# design choices, however the reasoning is pretty much transferable to any language you'll be developing games in.

---

**1. 32-bit Signed Integer IDs**

By far the most lightweight ID type. Comparisons are fast and are easily orderable (if required). They're light enough for being passed around in function calls when needed without taking a noticeable performance hit.

Signed 32-bit integers provide a wide enough range of possible values for most gaming needs. If used for static (unchanging) IDs, this should be fine as I cant think of a single game that uses anywhere near 2.1 billion different types of entities!

If using for instance IDs, again you should be fine as 2.1 billion+ possible ID values is an enormous amount. The only time this may become a consideration is if you are talking about an online game and the game server stays up without restarts for a very very long time, in which case you'll have to monitor this and see how long you can go without needing to reset the count (by restarting the server) to avoid overflowing.

The one thing to be cautious of if using 32-bit signed integers is thread-safety. Do not assume that just because a type is static that it's threadsafe or you will be bound for problems. To successfully use an incremental 32-bit integer design, you must also implement a properly designed locking system to ensure thread safety. Due to this, you also have to be aware of any overhead involved in repeated locking as if designed poorly, this cause a big performance hit.

---

**2. 32-bit Unsigned Integer IDs**

Very similar to the above but with a few gotchas. In .NET, unsigned integers are not CLS compliant and needs to be considered if planning to allow/use libraries from other .net languages.

In some databases unsigned integers are not supported at all (strange but true). This is something to consider if these are static id's that need to be stored in a database.

The odds of needing 4.2 billion+ range in possible ID values is incredibly rare even for the largest of games but still a viable consideration for IDs.

---

**3. GUID IDs**

GUID values are 128-bit so they're a bit larger than 32-bit integers so their memory footprint is a bit bigger in comparison.

As for uniqueness, this will give you complete and utter uniqueness for each ID created. Someones bound to chime in that GUIDs are not guaranteed to be unique as per definition, but this is only true over the context of an insanely huge timeframe, well beyond the lifetime of anygame, or developer for that matter. Plain and simple, these will be unique for your requirements, even across machines.

Another benefit to GUID IDs is that you will not have to worry about thread safety during creation. Yet another bonus of GUID IDs is that they can be created in-place within the constructor of the type if desired. Doing this means that the Entity Manager is not burdened with managing ID generation and no unnecessary overhead is incurred during from locking, etc.

Performing comparison of GUID values is obviously slower than comparing integer values but it's still surprisingly fast and shouldn't be an issue in most, if any systems. Ordering these may be a major burden however but there shouldn't be any need for ordering if being used for the proper purpose (i.e.: Instance IDs). On that note though, I would suggest that anywhere you need to store these outside of the object themselves where searching must be performed against other IDs (object maps, etc) they should be stored in a dictionary. Storing in an array or a list will be absolutely horrible performance do to the search algorithm used where as in a dictionary, due to the internal structuring and search algorithm used, will be blazing fast regardless of the 128-bit size.

I should also not that the equality comparison of GUID values in .NET is actually even faster for GUIDs that are not equal than those that are equal. It may seem scary at first when thinking of GUID comparisons as when we view the human-readable form it looks like a big, messy string, but internally it is a sequence of various integral types and is treated as such when comparing values against others.

---

**4. String IDs**

The heaviest memory footprint of this list for multiple reasons. I do generally advise against using string values as IDs if at all possible unless you fully understand the inner workings of strings and how to make optimal use of them.

String values do provide the largest possible range of values and most flexibility. Names can be randomly generated, strategically assigned, and can be made very meaningful. One attractive use-case could be fully qualified names i.e.: (Player.SomeGuy, or Creature.Humanoid.SomeBadGuy, etc). That is an attractive feature with a lot of possibility.

Due to the way strings are handled in the .NET framework (via the string intern table), the way you implement and manage these IDs is really what will decide how good or bad it performs. String equality comparison can be relatively fast if handled properly but many things such as size, storage methods, etc become factors. Explicitly choosing the comparison type will be in your best interest when comparing string values. I prefer case-sensitive ordinal comparison personally but some may wish to be culture-sensitive in certain scenarios. This will be a design choice based on your requirements.

Generating string ID values could get tricky if required to be done automatically and of course, thread safety will something you will have to accommodate in your implementation.

---

There's a fair bit to take into consideration when deciding which route you will go with ID types but the above break-down gives some strong points to consider when choosing. My personal preferences are as follows:

* **signed 32-bit integer** IDs for static ID values that will be persisted in databases, etc.
* **signed 64-bit integer** IDs for static ID values that will be persisted in databases when I want to provide some sort of sub-identifiers within the ID itself for use with bit-masking to speed up searches/ordering, etc. An example would be: player entity types may have a bit-mask of 0x0100000000000000 and creature entity types may have a mask of 0x0200000000000000, just as an example as it can go even further in-depth than that.
* **GUID** IDs for instance IDs since these values aren't persisted, easily generated in-place without worrying about threadsafety and the likeliness of me needed to perform any sort of ordering on instance IDs is slim to none as it's usually just simply equality comparison (Equal or Not Equal).

Just my 2 cents on the issue anyway but feedback is always welcome :)
> 3 votes

# Answer
You could also use a dictionary (map, hasmap, etc).

It would be just as easy as using an array approach, but more flexible since shifting and all that is handled for you.

You just need an IdManager class, an instance of which would be a member of your EntityManager class. The IdManager should have a public method called `GetId()`, which would always return a unique string of n characters. You would also need a private method `NextId()`, which would be called from `GetId()` to compute the new unique ID.

```
GetId()
{
    old_id = current_id_; //Store the current id so it doesn't get changed.
    NextId(); //Advance to the next ID, just like counting.

    return old_id;
}

```

Now, when you're adding an entity just do `entities[idm.GetId()] = some_entity;`.

Most of the problems raised in that AltDevBlog article Darcy posted don't really apply here: we're not letting anyone name entities, strings are just numbers here.

If you're using C++ you might not need strings at all, as integers work as keys too.
> 0 votes

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


title: Mouse click movement

text:
# Question
Title: Mouse click movement
I need to make realistic human movement (3D) using mouse click.

1. Get mouse click point using `Raycast`.
2. Smoothly `Slerp` to `LookRotation`.
3. Move `transform.forward`.

Everything works fine, except I have problem with circular movement (close radius).

1. Example If **dont** move `transform.forward` while `Slerp` to `LookRotation` or `MoveTowards` instead of `transform.forward` it will be spinning like whirligig on circular movement.
2. Example If **do** move `transform.forward` while while `Slerp` to `LookRotation` it will distort trajectory of straight direct movement.

Is there any solution to move circular realistic (not spin like whirligig) and move straight direct when needed (not distort trajectory)?

I need straight movement from first example and circular movement from second.

```
        if (Input.GetMouseButtonDown(1))
        {
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);

            RaycastHit[] hits = Physics.RaycastAll(ray);

            foreach (RaycastHit hit in hits)
            {
                if (hit.transform.tag == "Ground")
                {
                    DestinationPosition = new Vector3(hit.point.x, transform.position.y, hit.point.z);

                    DestinationRotation = Quaternion.LookRotation(DestinationPosition - transform.position);

                    break;
                }
            }
        }

        if (Vector3.Distance(transform.position, DestinationPosition) > 1)
        {
            transform.rotation = Quaternion.Slerp(transform.rotation, DestinationRotation, RotationSpeed * Time.deltaTime);

            transform.position += transform.forward * MovementSpeed * Time.deltaTime;

            //transform.position = Vector3.MoveTowards(transform.position, DestinationPosition, MovementSpeed * Time.deltaTime);

            animation.CrossFade("run");
        }
        else
        {
            animation.CrossFade("idle");
        }

```

# Answer
> 2 votes
When facing this problem I found that I wanted the character to move forward at a velocity roughly proportional to how close they are to facing the target.

When facing away from our target we "turn on the spot" (Red), when facing directly towards it we walk straight towards it (Green), when somewhere in between we will may walk slowly while turning (Blue & Purple).

How best to implement this, and the values to use for thresholds, will depend on the other systems already in place.

One approach with Unity that would allow for easy fine tuning would be to use an AnimationCurve.

```
public AnimationCurve speedAngleCurve;
public float maxSpeed;

private float getTargetSpeed(Vector3 targetPosition) {
    Vector3 targetDirection = targetPosition - transform.position;
    float offsetAngle = Vector3.Angle(transform.forward, targetDirection);
    float normalizedAngle = offsetAngle / 180.0f;
    return speedAngleCurve.Evaluate(normalizedAngle) * maxSpeed;
}

```

This would allow a developer to rapidly modify behaviour using the Inspector and the Curve Editor.

---
Tags: unity, 3d, mathematics, rotation, movement
---


# Question
Title: Random Placement of Objects on a Tilemap
I have read many topics on random world generation on this site and others, and I roughly understand most of it. What I can't see is how to randomly place objects on the generated tile map I get. Say I want to generate a forest. How would I go about doing this? I have tried studying other people's code. I delved into Notch's Minicraft to look at how it generates its random worlds.

I have identified this part of the code that generates trees for example.

```
for (int i = 0; i < w * h / 400; i++) {
        int x = random.nextInt(w);
        int y = random.nextInt(h);
        for (int j = 0; j < 200; j++) {
            int xx = x + random.nextInt(15) - random.nextInt(15);
            int yy = y + random.nextInt(15) - random.nextInt(15);
            if (xx >= 0 && yy >= 0 && xx < w && yy < h) {
                if (map[xx + yy * w] == Tile.grass.id) {
                    map[xx + yy * w] = Tile.tree.id;
                }
            }
        }
    }

```

However, this just confuses me. I need to be able to see how this code translates into spread out trees. There is also code for generating the desert.

```
for (int i = 0; i < w * h / 2800; i++) {
        int xs = random.nextInt(w);
        int ys = random.nextInt(h);
        for (int k = 0; k < 10; k++) {
            int x = xs + random.nextInt(21) - 10;
            int y = ys + random.nextInt(21) - 10;
            for (int j = 0; j < 100; j++) {
                int xo = x + random.nextInt(5) - random.nextInt(5);
                int yo = y + random.nextInt(5) - random.nextInt(5);
                for (int yy = yo - 1; yy <= yo + 1; yy++)
                    for (int xx = xo - 1; xx <= xo + 1; xx++)
                        if (xx >= 0 && yy >= 0 && xx < w && yy < h) {
                            if (map[xx + yy * w] == Tile.grass.id) {
                                map[xx + yy * w] = Tile.sand.id;
                            }
                        }
            }
        }
    }

```

Is this just way over my head or is there some kind of algorithm that I'm missing here?

# Answer
> 6 votes
Both of those pieces of code appear to pick a random location (xx,yy in the first example and x,y in the second), then try to change grass to something else near that location.

There are lots of other algorithms, although most are more complicated than the ones you posted. I can't answer whether they're over your head; I don't know what's in your head ;-)

I usually like to use noise functions. I have written a tutorial on noise functions. I also like to start with the simplest possible thing, and change it only if it's not satisfactory.

**Pink Noise**

The first question you have is about placing forests, deserts, grasslands, etc.

You can use some sort of random noise to generate attributes that determine whether some land is grass, forest, desert, etc.

For example, you could use Perlin Noise to generate a value from 0.0 to 1.0, and then decide that the range 0.0–0.3 is desert, 0.3–0.7 is grass, and 0.7–1.0 is forest. That's fairly simple, once you have a Perlin Noise library.

A more involved approach would be to generate "realistic" attributes such as temperature and moisture using a noise function, and then use those attributes to decide whether something is a forest. You might decide that forests occur when moisture is between 0.2 and 0.8, and temperature is between 15°C and 30°C. See Whittaker Diagrams for more on this; it gives you different types of forests and other areas.

Another approach would be to generate those attributes using something other than a noise function. For example, in this project I used “distance from coast” to generate elevation, which then turned into temperature. I used “distance from river” to generate moisture. I then used temperature and moisture to look up the biomes on the Whittaker diagram.

These systems typically follow “pink noise”. There are large areas with one type of biome or another. There's a small amount of variation within these areas.

**Blue Noise**

The second question you may have is to place *objects* such as trees in a forest zone, or rocks in a desert zone. “Blue noise” is used when you want semi-even *spacing* of objects.

The simplest approach is to go through each tile in the forest zone and place a tree with some probability. Something like: `if random() < 0.3` then place tree. It's really simple, and it's worth starting with this. However, it often yields clumps of trees that you may not want.

To fix clumping, you can pick a random point and place your tree if it's in a forest zone and there are no other trees within a certain radius. See this article for an explanation and sample code.

There are more complicated approaches, using things like Wang Tiles. I liked the video from this project. However, I haven't tried implementing it.

---
Tags: game-design, tiles, game-mechanics, procedural-generation, random
---


title: Forcing a game to use Direct3D WARP

text:
# Question
Title: Forcing a game to use Direct3D WARP
I am making a study for a research project that involves measuring the performance and quality impact of rendering 3d games using a software rasterizer (like WARP).

I wonder if there is a way to force games to use WARP. Maybe something easier would be to just use games that support using warp or the reference rasterizer. Are there any relatively new game (no more than 8 years old) that supports that? I don't remember seeing that option in games in a long time.

If there is no tool or setting to do that, I was thinking I could use something like Detours (http://research.microsoft.com/en-us/projects/detours/) or EasyHook (http://easyhook.codeplex.com/), and perform binary rewriting on the code. For DirectX 10 games I think it should be enough to intercept the CreateDevice call and change the device. For DirectX9 games is it enough to change the D3D9CreateDevice for a D3D10CreateDevice? I tried with samples from the SDK and it seems it is not the case. Any suggestions on what to do there?

# Answer
There is a way to force a game to use WARP without disabling Display Driver, Just install the direct X SDK. http://www.microsoft.com/en-us/download/details.aspx?id=6812 Go to C:/windows/system32 Run dxcpl.exe In "Scope" click "Edit list" Add The Path To Your Application Go to your game / application directory And Launch It.
> 5 votes

# Answer
Install a build of Windows 8 and disable your video card in device manager. The whole system will then be running using the 'Microsoft Basic Display Adapter' - which is WARP.
> 1 votes

---
Tags: directx, software-rendering
---


# Question
Title: How do I make A* agents avoid other agents?
I'm implementing a multi agent A\* algorithm on a tile map. Agents move only in the X and Y axes. I avoid collisions between them by checking where the others are when calculating paths.

It works fine except the situation where agents have to pass the same tile from different directions. In situations like this, an optimal solution would be for one agent to wait for the other to pass:

Also, if there's no northern corridor, then pathfinding fails.

How could I implement such an algorithm?

# Answer
You can start by letting the pathfinding fail. On failure, choose a random time in the future to re-try pathfinding. Some low level networking protocols work that way, and quite well. What you have to do is build paths one at a time, and mark as used all the tiles an agent will pass through. When further paths fail the random timer to restart will help spread out the new path searches and break up looping failures.

The second part of your problem could be handled by returning two paths. The first path is the regular return, even if it fails from a block. The second path is a path that completely ignores all the agents. You can then use the knowledge gained from these two paths to decide whether waiting or taking the long way would be better. The heuristic for that decision will take some work, but it's better than not trying anything at all.

In the very bad case where your agents are getting blocked a lot by single width corridors like this you may have to add safe spots to stand where agents can quickly path to and wait for their real path to open up (so the agent doesn't just wait and block a corridor).
> 18 votes

# Answer
Rather than solving your problem, here's a way to take the lemons and make lemonade.

Many years ago a friend of mine was working on a very well-known FPS which had precisely the problem you describe: a constrained area would have a number of AI characters who had particular desired positions, and the path-finding algorithm was constantly bumping them into each other. In particular, the player would, say, throw a grenade into a small room full of enemies, and the AI characters in the area would each try to run to their exit, but run into each other, and end up pausing, turning around, hitting someone else, turning around, and so on. This looks very unrealistic.

Attempts to build a better pathfinding algorithm that could run successfully given the tight computational budget failed. So instead of solving the pathfinding problem, my friend added a very cheap check to the AI: if an AI has bumped into another AI twice in a short time period, stop trying to find the exit and instead take cover. So now what happens is, the PC lobs the grenade and sees a bunch of enemies run for the exits. Those that hit each other, turn around, and it looks like they realize they can't get out, so they duck and cover their heads right before they blow up. This is both realistic-looking and highly satisfying to the player.

Is there some similar way you can turn the disadvantage of your collision-producing algorithm and turn it into an advantage?
> 19 votes

# Answer
I usually find it best to augment A\* pathing with other forms of path finding for other localized scenarios; unit avoidance is usually one of them, especially in a world where there are multiple agents moving simultaneously and thus creating dynamic blockers).

Generally, an edge-following technique can work for this. When you are following a path an encounter a blocker that wasn't part of the original path computation, you basically pick a direction (clockwise or counterclockwise) and try to traverse the blocker by travelling around it in that direction. If you can't, you wait for the blocker to resolve itself (although this can result in a deadlock).

You can also implement the ability for units to path co-operatively; that is, a unit can ask another unit to move aside slightly so it can "squeeze past" the blocking unit. This doesn't work well in a tile-based game where you are restricted to tile-based movement, though, because you can still deadlock in single-width corridors like your example. In that case you can provide for the units to ask eachother to "switch places," which results in resolution most of the time. Occasionally this leads to units leapfrogging eachother, though.

"Unit avoidance" is a fairly common topic when discussing pathfinding in games, there are a lot of hits out there for it. In particular you may want to check out this question on the "flow field" pathfinding used in Supreme Commander 2. RTSs usually run into this problem a *lot* and solve it in all sorts of interesting ways.
> 3 votes

# Answer
If you have a turn based/tick based movement system than you could create a 3D graph where each transition moves the agent into how the map would look in the future. Then have each agent claim the tiles they would be on in that point in the future and mark them as inaccessible. Each agent then has an extra option of "ẅaiting" to the next tick as a 3rd way to transition through the graph. This will be harder on your system but should give you better results than waiting randomly. Even better if you allow 2 agents to communicate bt having one of them send a message of "I want to pass you" if it's shortest path passes through that agent, the reaction could then be to check if the agent is waiting during that time and if it is then letting it move to a tile that does not cross the path of the other agent (else repath that agent).
> 2 votes

# Answer
When using an algorithm like A\* you have the greatest latitude in working with the cost heuristic.

In this particular case you could adjust the heuristic to increase the cost of movements that take an agent close to another agent, the problem there is you would likely end up with both trying to take the upper route, and you could end up with them oscillating back and forth between paths as they close on each other depending on the exact timing.

Another possibility is to track agents intended routes and adjust costs upward along other agents intended paths. This effectively allows agents to coordinate with each other to a limited extent. The main issue here is if all the routes are blocked out path finding may keep failing for whichever agent moves last.

In the case where there is only one path, then path finding will either fail or they will advance on each other until they deadlock.

If neither of those are good enough then you need to start keeping track of time when calculating your cost as well. The cost for the second agent should be the amount of time it takes for the first agent to get clear plus the normal traversal cost, in that way your agent would be able to decided correctly when to wait versus taking the other path.

Taking timing into accord can be significantly more effort, so most people settle for tweaking the level layout and cost values until things are good enough.
> 0 votes

# Answer
Normally I would adivse you to use steering behaviours to solve problems like this during path-following. And you still might to take a lot at those to get inspiration for grouping behaviour. But unfortunatley it is not really directly applicable for simple tile based movement.

Since you already have a working collision avoidance for most situations, lets focus on this particular one. I guess you are re-doing the pathfinding each time an agent wants to move, or else I can't see how they react to others moving during their move. Secondly I guess those agents are friendly to each other.

You suggest one agent waiting for the other one and I would advise you to do exactly that. Give the agents a way to access the paths of the others, search for the first tile of your own path that is not part of the other path and go there. Problems with this technique may be:

1. How do you decide if there is another acceptable way around the other agent or not? You dont want to wait for the other agent if there is space enough to go around him. A pathfinding failure when considering the other agent is a clear sign of the situation you want to fix, but in the example you brought up there wont be a pathfinding failure. But you can - with a little bit of calculation - decide if the alternative path A\* gives you just goes around the other agent in a small circle, or uses a totally different path like the northern corridor.
2. I don't know how far an agent can travel during one round/operation, but if that is not far enough, or if all agents are moving parallel, both agents would decide to wait on the other end of the path. This can be fixed by signalizing the other agent that you free up his path.
> 0 votes

# Answer
One of the possible solutions would be to disable unit collision in such tight spots.

For example in the Starcraft game, workers (SCVs, Probes, Drones) don't collide with each other when mining crystals.
> 0 votes

---
Tags: collision-detection, ai, path-finding
---


# Question
Title: What are good solutions for serialization in C++?
I'm curious what solutions game developers have come up with for serializing the different types of data that they deal with for their games. Do you guys use some monolithic GameObject hierarchy that houses a serialization interface for derived types, use sort of custom RTTI-based solution, perform explicit stream serialization for certain classes, or use some of the open source solutions (boost::serialization, s11n, etc).

# Answer
Protocol buffers from Google can be a pretty good approach for serializing c++ objects. You may have to make some intermediated objects as part of the serialization process, but it also works across many platforms and languages.
> 9 votes

# Answer
We in our game simply use boost.serilization, it's easy to use and very fast, but it's in my opinion just useful for savegames. If you try creating characters, i recommend you something XML'ish or JSON based things, because they are easy to read and editable even if you don't have the editor.
> 10 votes

# Answer
I rather like JSON for serialization. It is pretty simple to parse and there are free libraries available such as http://jsoncpp.sourceforge.net/ I've never been a fan of boost or RTTI in C++. Tinyxml also work well for xml serialization and deserialization. http://www.grinninglizard.com/tinyxml/ Ultimately I don't want to have to spend any more time than I have to for serialization.
> 3 votes

# Answer
> Google FlatBuffers is an efficient cross platform serialization library for C++, with support for Java and Go. It was created at Google specifically for game development and other performance-critical applications.
>
> It is available as open source under the Apache license, v2.
> 2 votes

# Answer
Message pack is a great alternative too! (http://msgpack.org)
> 2 votes

# Answer
XDS was designed just for this purpose, it gives you the benefits of XML during development and the benefits of a compact binary representation at distribution time.
> 1 votes

# Answer
If you are on a Linux platform, you can directly use `json.h` library for serialization. Here is sample code I have come across. Source: Json Serializer

```
//============================================================================
// Name        : JsonTest.cpp
// Author      : Manis Kumar Khedawat
//============================================================================

#include <iostream>
#include <json/json.h>

using namespace std;

struct objStruct{
    string str;
    int n1;
    int n2;
};

typedef objStruct obj;

void serializeToJson(json_object *jObj,obj* pObj)
{
    /*
    string str;
    int n1;
    int n2;
    */

    // Create json object for every member in struct Obj.

    json_object *jstr = json_object_new_string (pObj->str.c_str());
    json_object *jn1 =json_object_new_int(pObj->n1);
    json_object *jn2 =json_object_new_int(pObj->n2);

    // Add all above created object into jObj

    json_object_object_add(jObj,"str",jstr);
    json_object_object_add(jObj,"n1",jn1);
    json_object_object_add(jObj,"n2",jn2);

    // pObj is Serialzed into jObj
}

void deSerializeToJson(json_object *jObj,obj* pObj)
{
    /*
    string str;
    int n1;
    int n2;
    */

    // Get every member as different json obj from jObj
    json_object *jstr = json_object_object_get (jObj,"str");
    json_object *jn1 =json_object_object_get(jObj,"n1");
    json_object *jn2 =json_object_object_get(jObj,"n2");

    pObj->str=json_object_get_string(jstr);
    pObj->n1=json_object_get_int(jn1);
    pObj->n2=json_object_get_int(jn2);

    // jObj is DeSerialzed into pObj
}

int main() {
    // Lets Create an Object which we will serialze into Json
    obj obj1;
    obj1.n1=3;
    obj1.n2=6;
    obj1.str="This is String";

    // Create a json Object
    json_object* jObj=json_object_new_object();

    // To serialize into Json Object
    // Please Keep in mind , we are passing address of object (pointer) & not object
    serializeToJson(jObj,&obj1);

    obj obj2;
    // To serialize into Json Object
    // Please Keep in mind , we are passing address of object (pointer) & not object
    deSerializeToJson(jObj,&obj2);

    cout<<"String str == "<<obj2.str<<endl;
    cout<<"n1 & n2 : "<<obj2.n1<<" "<<obj2.n2<<endl;

    return 0;
}

```
> 1 votes

# Answer
Both jsonCpp and Protocol buffers are good options. To my knowledge both are only going to allow you to serial tree structures out of the box (please correct me if I am wrong). boost::serialization can handle arbitrary graphs, but doesn't have a nice text format like json (I think there is an xml format)

Personally I think the approach for json serialization that Dojo has taken is the best
http://docs.dojocampus.org/dojox/json/ref

I made my own version of it in c++ using jsoncpp, that also will deserialize typed objects (I have sort of big factory for all my types). It allows me to make a scene from a collection of json files that can be referenced anyway I please.
> 0 votes

---
Tags: c++, serialization
---


title: Smooth anmiation with LibGDX

text:
# Question
Title: Smooth anmiation with LibGDX
I want to move a enemy from its current position toward the mouse position in LibGDX. **x, y** \- enemy position **saveX, saveY** \- position where my enemy need to go(or mouse position saved at specific time) **xSize, ySize** \- enemy size.

```
protected Vector2 makeVec(float saveX, float saveY){
    Vector2 v = new Vector2(saveX - x, saveY - y);
    return v.nor();
}

public void update(float dt){
    test += dt;
    dtTime += dt;
    if(cont){
        vec = makeVec(saveX, saveY);
        x += vec.x * speed
        y += vec.y * speed;
        cont = cont();
    }
}

```

But for some reasons my enemy movement animation is not smooth. What's wrong?

# Answer
> 1 votes
The distance moved does not take the delta time into account, so if you get updates coming at an irregular interval you'll get jerky motion.

Scale your `speed` by the elapsed time, `dt`;

```
public void update(float dt){
    if(cont == true){
        vec = makeVec();
        x += vec.x * speed * dt;
        y += vec.y * speed * dt;
    }
}

```

This might mean you'll want to increase the speed.

---
Tags: java, libgdx, movement, vector
---


# Question
Title: What is the speed difference between cross platform HTML5 games and native mobile games?
Microsoft is advertising and promoting cross platform HTML5 game development. I am thinking of creating a simple 2D side scroller game and I am trying to decide what engine should I use for creating it. I am trying to understand if there is a big difference between developping once in Unity and exporting to different platforms or simply develop it once in HTML5 in Visual Studio and publish it everywhere. What are the drawbacks and benefits for each? Is there any speed/lag difference? any tips are useful

# Answer
> 2 votes
The difference between html5 games and native games is a vast discussion, one that im not going to be able to answer in just one post.

So the closest thing i can come to a straight answer is : **It depends on the game.**

This stems from that both technologies are fairly new, and growing exponentially. As far as I know, no game studio have tried making the same game on both platforms, or at least not with publicly displaying the results.

And with HTML5 growing stronger each time i hear about it, and Unity playing with fully integrating WebGL in their engine, you can be assured that great things are in the horizon.

But one thing seems to be set at the moment:

* **HTML5 games** seems to be faster to build in, but have some hard cielings in terms of memory and scene handling.
* **Native games** have much more direct control of what is being allocated, deallocated and used, but suffer greatly in that it takes longer time to develop.

I guess "which platform to use" can not be answered for all games. Are you building a turn based trading game, I would definitely suggest to start in HTML5, at least for prototyping. Making a multiplayer fastpaced first person shooter, I would suggest that you go straight to native, since the range of network handling can be much more detailed and lag would cost a lot in the game experience.

But since HTML5 for the most part is faster to craft in, I would recommend building a prototype in HTML5 and show it to some developers. That should give you some solid feedback in what the client needs to carry, and which approach would be the smartest.

You might also find this discussion interesting : HTML5 mobile game development vs. native game apps

**In your case:**

A simple sidescroller would be good for both platforms. I would try and weigh puzzlesolving vs action on a scale to figure out which option to pick.

In my experience, input lag has been an issue with some HTML5, especially on certain mobile devices. So if you are strong on action (especially actions that involve combos or fast reactions) the "safest" would be to go native.

But if you just want to make the game, and have people playing it as early as possible (and hopefully grow it from there) I would recommend building it in HTML5.

But in the end, it's all about the user experience.

---
Tags: unity, android, ios, html5, windows-phone-8
---


# Question
Title: Why does changing texture change it for both objects?
I have two identical objects in my Unity scene. When I change the texture of one, the texture is changed on the other, almost as though the first one is a prefab. Why is this happening and how can I treat them independently?

Steps taken:

* Import .obj file and two .png files
* Drag object into scene
* Look at the object in the hierarchy (where the list of all objects in the scene is)
* It has a child called pSphere1
* pSphere1 has a mesh renderer with 2 materials on it - RedGold and pSphere1Mat
* It also has two components controlling each of these materials
* In those control components, I can select a shader from the dropdown and I can also select a texture.
* For either one of them, if I change the texture say to PolkaDots, both objects have their materials changed, instead of only the one I am working on.

# Answer
> 2 votes
If you modify a material, it affects the objects that are using it. You need to duplicate that material, modify its texture and reassign it to the target object.

---
Tags: unity, textures, materials
---


title: UV map data structure

text:
# Question
Title: UV map data structure
I've received a few instructions on what kind of usage UV maps allows, and currently try to understand how it works. However, I can't figure out what kind of *data* there is inside a UV map.

Googling around, I found... almost nothing. Maybe this simple example. That was totally unexpected. Is it non standard, with as many possibilities as software vendors ?

Anyway, if that is the case, I'm nonetheless interesting in understanding what *kind* of data can be found inside an UV map save file, in order to properly complement my understanding of the process, and try to figure out what kind of post-processing would be possible.

# Answer
> 3 votes
An UV map is usually literally 2 extra floats per vertex, one for the U, and one for the V, how they are stored is dependent on the model format used and not really relevant to how you *use* them.

How they are used in modern applications is typically completely defined in the fragment shader, a common use is to take the UV values and use them as the coordinates from which you sample an image and use that as the base color for the model at that point on the triangle.

What you *can* do with them is practically unlimited, it's just 2 extra floats and you can interpret them any way you like in a fragment shader.

As UnholySheep pointed out, it is also possible to change, or even create them in different shaders, for example a geometry shader for particles could emit a quad with appropriately offset UV values from a particle atlas, meaning you'd only need to upload 1 set of XYZ/UV values per particle you want rendered.

---
Tags: uv-mapping
---


title: Store values or calculate values

text:
# Question
Title: Store values or calculate values
We're talking about fairly anal levels of optimisation here that I wouldn't really worry about in anything other than mobile games. Let's say for example you were drawing a texture to the screen in a fairly constant position and the position of that texture could easily be calculated or stored.

I'd be interested to know what professional game developers default to in the first instance when writing code. Which of the two options below would to achieve higher performance in a majority of situations. My main development language is Java.

So option 1 is something like:

```
constructor {
  x = container.left + offset.x;
  y = container.bottom + offset.y;
}

paint {
  draw(texture, x, y);
}

```

And option 2 is something like

```
paint {
  draw(texture, container.left + offset.x, container.bottom + offset.y);
}

```

With option one the advantage is obviously that the values are pre-calculated. The disadvantages being you're using more RAM and as such there's an increased risk that the data you need wont be in the CPU cache. You also need to make sure the position is recalculated every time there's any movement.

With option two less RAM is used and therefore it's more likely data will be in the CPU cache, but there's the overhead of the calculation. We also don't need to worry about recalculation when there's movement.

# Answer
> 8 votes
The real implications in performance here depend 100% on the platform used.

Say you have written code as in option 2.

When using a statically compiled language such as C++ the compiler will presumable not notice that `container.left + offset.x` is constant for as long as the object lives and it will not optimize it. When using a language that uses Just-In-Time compilation the code can be optimised at run-time when the compiler sees that the code is on the hot path and it can deduce (thanks to more information being available) that the value is constant. Allowing it to trade memory for speed. If the Jitter will actually make this decisions depends on a very complex set of rules. Here is an interesting article about the optimisations the JIT-compiler can make. Though I am still looking for the definitive source on this from Microsoft.

That being said, these kind of performance questions are almost never worth thinking about. The only real applications that benefit from these performance 'enhancements' are micro-controllers. If you're ever worried about performance use a profiler. I've been writing performance intensive code for many years and I find I can still be surprised by what part of the code is on the hot-path, and actually slowing things down.

First worry on writing code, then worry about the algorithmic complexity of the code on the hot-path, if that is still not enough dive in, trade memory for speed, investigate cache-misses and inspect the generated assembly.

# Answer
> 2 votes
The only way to know for sure is to try both ways, as they can both be faster than each other in different circumstances. The first can be faster because less computation is done, the second can be faster because data is smaller which normally helps avoid costly cache misses. It depends totally on the context. Put another way, I could construct one benchmark that would show the first to be faster, and another benchmark to show the second is faster.

Personally, I default to the second way since it's easier to read (assuming the 'real' program 1 would have the constructor and paint method placed further apart in source). In cases where profiling hasn't been done and seems unlikely to make a large impact either way, I'll always pick the option that's most readable.

---
Tags: performance, optimization
---


title: How to deal with tags in a component

text:
# Question
Title: How to deal with tags in a component
I have a component called "ReflectOffCollision". This component should obviously not need to be aware of specific details about the game such as tags. The problem is, I want to apply this script to an object that reflects off of only some collisions.

I could check the tag of the collision, but this will destroy the generality of the component. It will only work on collisions with this tag. I could have the script take a white list or black list of tags, but this is awkward to do.

My other option is to inherit from the component and make a more specific version. This seems like overkill, though.

How should I deal with tags in components? I see this problem anywhere that there are collisions. Am I using tags incorrectly, or misunderstanding them?

# Answer
> 1 votes
There are a few ways to achieve this. First, you can use layers and modify the collision matrix so that it won't interact with non-collidable objects. Second, objects you want to collide can contain a common component to mark them as collidable.

Let's say it's Reflectable. At run-time, you can determine whether the object is collidable or not with this:

```
if(collision.gameObject.GetComponent<Reflectable>()!=null)
    collide();

```

---
Tags: unity, component-based
---