# Question
Title: How can I check if a player-drawn line follows a path?
I want to draw an invisible path that the user must follow. I've stored that path as points. When a player draws a line, how can I test if it follows the path I've stored?

Here's an example for tracing the letter A.

```
if((traitSprite.getX()<=Invisible.X  && traitSprite.getX()>=Invisible.X )){...}

```

(`traitSprite` is a sprite.)

# Answer
Here's a vector-based solution. I haven't tried it, but it seems fine conceptually.

# Theory

I gather you've stored the shape as line segments. Here's the letter A represented with three line segments.

I've assumed that paths in the user's drawing are stored as lists of points.

We can "inflate" those line segments to allow an error margin when checking for **nearness**: whether the user's drawn path is near the correct lines error margin.

However, that alone is not enough. We also have to check for **coverage**: whether the user's drawing "covers" a large fraction of the shape. These drawings are bad, because even though they fit within the error margin, they're missing some part of the letter:

If we check both of those things, we can approximate if the player's drawing is good.

# Implementation

**Checking nearness** just means for each user path point, finding the distance between that and every line making up the letter, taking the lowest and checking it's less than the error margin.

**Checking coverage** is more complicated, but you can get a very good approximation with vector math if for each line segment, you find the nearest user-drawn path (green) and project its parts (dark green) onto that line segment (black), then check for how well the projected vectors (blue) cover it:

To project a vector `a` onto another vector `b`, do

```
projection = dotProduct(a, b) / lengthSquared(b) * b

```

where `dotProduct` computes the dot product of the two vectors and `lengthSquared` is what it sounds like. Essentially, this finds the scalar value of how much `a` goes in `b`'s direction and multiplies `b` by that to get a vector in the same direction. (Metanet Software's collision detection tutorial A has a nice visualisation of this in *Appendix A* § *projection*.)

The direction of the projected vector might not actually be important. If you just sum together the lengths of the projected vectors and compare them to the total length of the line segment, that will tell you what fraction of it is covered. (Except in odd cases—see §*Limitations* below).

In the above image, the path would cover about half of the segment. You could pick any tolerance value you want.

# Limitations

## Curved letters

Line segments are sub-ideal: Many letters are curved! How do you represent a ‘P’ or an ‘O’?

You could use many line segments (maybe with a larger error margin).

You also *could* start using Bézier curves instead of lines for a closer fit, but note that finding the closest point on a Bézier is *much* more complex—as are many other measurement operations.

## Mismatches

Overly relaxed tolerance margins for distance from the lines and coverage of the letter could have unintended consequences.

For example, the player might have been trying to draw an ‘H’ here.

## Loops and overlaps

Loops or overlaps in the player-drawn path could result in some parts of the drawing being counted twice when projecting them onto the nearest line segment.

This could be worked around by doing fancier processing on the projected vectors, perhaps storing exactly where the projected vector would be (store the direction of the projection too, and the closest point on the line segment to the point on the player-drawn line), then rejecting new ones that overlap it.

If the player drew a single path and it was processed starting at the end marked with the blue circle, the green parts of that path would be accepted and the red ones rejected, because their projection would overlap with some parts processed before.

The implementation has many technical subtleties that would probably belong in a different question.

## Unpredictably adventurous players

A player might draw something weird that still passes.

Although you could call that a feature! :)
> 12 votes

# Answer
tl;dr I suggest making the players' brush paint a visible (or invisible) 2d plane. Diff the users' painted image with the origin (the desired silhouette or 2d model). If you want to increase accuracy then make the guiding lines and brush more narrow, to allow more room for error, make brush and design thicker.

Otherwise, you could measure the distance of each (x, y) the users click / touch on from the spline by calculating point to segment distance. Then you can average the distances to compose a measure of accuracy and efficiency. It will require more work to get a meaningful measure of completion and realize how effectively the user performed.

---

Consideration: I suggest not doing so (checking directly if a line follows a path). This is possibly a bad idea. It seems you want the user to fill a silhouette. The path itself is a (skeletal) spline representing the silhouette.

If you simply make the players' brush apply a pulpy monochrome mass of pixel to the 2d plane, you can run a process in the background that checks how many pixels are inside the silhouette and how many of them are outside. This can easily result in % of success, where how much % of the pattern is filled is one statistics of interest and another is how much % is outside the borders of the model. If you check for sub-segment distances it's not very clear of accurate the users' work is.
> 2 votes

# Answer
The best solution not use graphics at all, do it with math!

You can easy understand how much every point (user painted) far from segment https://stackoverflow.com/questions/849211/shortest-distance-between-a-point-and-a-line-segment

That you can calculate average error, so measure how much user is correct.
> 1 votes

---
Tags: libgdx, algorithm, vector, hand-drawn
---


# Question
Title: LibGDX camera position shifted on movement
I'm programming a game with LibGDX and Box2D and I want my camera to follow my player. But as I zoom in (because Box2Ds metric system, using camera.zoom = x) the camera is shifted when the player moves (the camera follows the player):

*Shifted View*

*Normal View*

That only happens when the player moves, so there can't be a problem with the coordinates. My Question is how to remove this shifting as the player moves.

Here's some of my code:

*Render Loop (excerpt):*

```
@Override
public void render(float delta) {
    //set the camera position to player's position
    cam.position.set(player_body.getWorldCenter().x, player_body.getWorldCenter().y, 0);
    cam.update();

    world.step(Gdx.graphics.getDeltaTime(), 6, 2);
    world.clearForces();

    handleInput();

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

    batch.setProjectionMatrix(cam.combined);

    debugRenderer.render(world, cam.combined);

}

```

*Make the player move:*

```
if (Gdx.input.isKeyPressed(Keys.W)) {
    player_body.setLinearVelocity(transX, transY);
    player.setMoving(true);
}

```

# Answer
> 1 votes
Okay, I found an answer. You need to set the camera's position directly after calling world.step() and then it works without shifting.

```
world.step(...);
camera.position.set(...);
camera.update();

```

(Original Answer)

---
Tags: libgdx, box2d, camera, perspective, jbox2d
---


# Question
Title: What is the purpose for drawing vertices and shapes in OpenGL (or DX), if a game is using sprites?
Something I do not understand. All the tutorials on OpenGL, DirectX, or other, always show you how to draw a shape and then change its vertices, move it around and so on. But all the games I know of, tutorials on creating, etc., always have sprites and sprites alone.

What is the reason for drawing triangles and squares for games? I never see it used, only pre-made graphics.

edit: based upon answers so far, is the purpose of drawing shapes to "bound" a sprite? So if I have a character, on a platformer like Mario, Mario has a shape around him and that shape's location is used to detect collisions, etc.?

edit: Maybe a small example?

# Answer
Because 3D libraries like OpenGL and DirectX draw everything using triangles, including sprites.

You put a texture (image) on triangles, put two triangles side by side to make a square and that's how you draw a "sprite" with OpenGL or Direct3D.

The sprites are drawn using triangles, its not for collisions, its simply for drawing them.
> 4 votes

# Answer
You can achieve certain effects with shapes that would be more difficult with sprites. For example if you want a circle line or a pathway to be drawn in certain amount of time, or an image shattering to several pieces. These are that came to my mind at the moment, but obviously, you can think up anything.
> 0 votes

---
Tags: sprites, graphics-programming
---


# Question
Title: Looking for Bezier curve OpenGL open source implemention
well in short im looking for something like this as open source.
https://www.youtube.com/watch?v=Cut3\_A0Xm3Y

i need to implement especially the Bezier curve editing in my app in open gl . any ideas where i can find such open source implementation ? ( can be c++ or java )

# Answer
To draw a bezier curve using OpenGL or Direct3D you need to sub-divide the bezier into line segments. If you do this with enough sub-divisions it will look like a smooth curve.

Interpolation functions:

```
vec2 Lerp(vec2 a, vec2 b, float i) {
    return a + (b - a) * i;
}

vec2 Bezier4(vec2 a, vec2 b, vec2 c, vec2 d, float i) {
    return Lerp(Lerp(a, b, i), Lerp(c, d, i), i);
}

```

Then you generate a series of points on the bezier curve and draw connected lines between them:

```
vec2 bezier[4] = { bezier control points };

int resolution = 8;
vec2 points[resolution];

for(int n=0; n < resolution; ++n){
    float i = (float)n / (float)(resolution-1);

    points[n] = Bezier4(bezier[0], bezier[1] bezier[2] bezier[3], i);
}

DrawConnectLines(points, resolution);

```

You can increase the resolution to make the curve approximation smoother.
> 3 votes

---
Tags: opengl, open-source, curves
---


# Question
Title: Render model with meshes with materials and/or textures
I'm making a model class that is using Assimp in the background. I want my models' meshes to be able to have a material and an optional texture on top of that.

Right now I'm doing it like this: for each mesh, I store postion, normal, and texCoord for each vertex in that mesh. If the mesh doesn't have a texture, I just add vec2(0.0, 0.0) to the texCoord-array. I needed to add blank values for the meshes that doesn't have textures so the offset for the meshes that has textures would be correct.

At first I thought this would work. To draw the meshes I use the same shader-program for both the meshes without textures and the ones with textures. But since no texture will be bound when I render the ones without textures, it will sample tex-colors from nothing (?), and flickering occurs.

So my question is, what would be a good way to solve this? Is it possible to have two shader-programs and switch between them depending on if the model has a texture?

# Answer
You could very well have two separate shaders. A nice way to do this would be to create a **Material** object that would contain pointers to some shader and *maybe* a texture (resources should be stored inside a ResourceManager or something similar).

But if that's too much work you could always use a special texture that always exists for objects with missing textures.
> 0 votes

---
Tags: opengl, textures, glsl, materials
---


# Question
Title: Libgdx drawing semi-transparent circle on pixmap
I am currently working on an android game using libgdx and would like to add a joystick to its interface. For this I use the built-in touchpad class. Untill now I have used external images for rendering the background and joystick. Now, I would like to dynamically draw the background of the joystick. This would make it possible to make the background of the joystick semi-transparent and to change the color of the background dynamically.

To do this, I implemented the following:

```
public class Joystick{
    private Touchpad touchpad;
    private static TouchpadStyle touchpadStyle;
    private Skin touchpadSkin;

    public Joystick(GameWorld world, GuiComponent gui) {
        touchpadSkin = new Skin();
        touchpadSkin.add("touchKnob", new Texture("data/touchKnob.png"));

        touchpadStyle = new TouchpadStyle();
        touchpadStyle.knob = touchpadSkin.getDrawable("touchKnob");;

        Pixmap background = new Pixmap(200, 200, Format.RGBA8888);
        background.setColor(1, 1, 1, .6f);
        background.fillCircle(100, 100, 100);
        touchpadStyle.background = new TextureRegionDrawable(new TextureRegion(new Texture(background)));

        touchpad = new Touchpad(10, touchpadStyle);
        touchpad.setBounds(15, 15, 200, 200);

        gui.inputStage.addActor(touchpad);
    }
}

```

As you can see, this code provides a joystick with a semi-transparent background: Joystick with semi-transparent background

However, this background has some inexplicable lines that are not transparent. Does anybody know what causes this? I thought it could have something to do with the format of the pixmap, but after trying with some other formats, there was not much improvement.

# Answer
> 2 votes
To get rid of the lines, you need to set `Pixmap.setBlending(Blending.NONE);` before you draw the circle.

---
Tags: libgdx, gui, alpha-blending
---


# Question
Title: Slick2D re-starting particle system/emitter
I am trying to use a particle system/emitter in Slick2D to produce a thrust jet from a space ship. I can get the emitter running continuously without any problem, however I can't get it to run for a fixed duration when I press the thrust key (which I need to do so that it only emits particles when the thrust is active). Note I can get the emitter to run for a fixed duration once when the program starts, but can't get the emitter to restart afterwards. I have variously tried (all attached to the thrust key press):

* disabling/re-enabling the configurable emitter
* resetting the particle system
* resetting the configurable emitter
* resetting the State of the configurable emitter
* replaying the configurable emitter
* running 2 separate emitters and re-adding these to the particle system when turning the jet on

... which either do nothing (no particles) or give a short burst of particles at the start of the program (for the initial emitter length if emitter length is enabled), but then do nothing whenever I press the thrust key. The last option (running 2 emitters) causes the particle system to run out of particles after about 10 seconds.

Is there a way to stop and restart a particle emitter that will give the effect that I want?

Just to cover any initial questions, I have read and re-read the javadocs (which are, as ever, reductive and unhelpful) and have read what I can find on the internet (mainly FrumsNL videos on youtube, which mention but don't cover this case) as well as doing my own trials as per the list above.

Any help gratefully received.

# Answer
> 0 votes
Solved it.

The second line below fixes the problem (I included the first for clarity). By default, if the emitter completes its cycle it is removed from the ParticleSystem. Disabling automatic removal means that you can restart the emitter.

(From my shipflame class)

```
system = new ParticleSystem(image, 10000);
system.setRemoveCompletedEmitters(false);

```

I have then just disabled or enabled the length option (which gives a fixed duration to a particle burst if enabled) depending on whether thrust is engaged or not, i.e. if thrust on then disable length, otherwise enable it (I have this set to 10ms in the xml config file). This gives nice, organic puffs of thrust when I 'feather' the thrust control, which is exactly what I wanted.

(From my ship class)

```
if (this.thrustOn
        && this.engineOn) {
    shipflame.getEmitter().length.setEnabled(false);
    this.applyThrust();
} else {
    shipflame.getEmitter().length.setEnabled(true);
}

```

For future reference, I had a look at the Slick2D code and resetState() calls replay() and replay() also calls reset(). So, if you want to restart the particle burst use resetState() since that covers all the bases.

---
Tags: java, slick, particles
---


# Question
Title: Yet another libGDX resolution independance question
I am developping a Android smartphone game in LibGDX, and I am encountering issues about resolution managing. Most notably, I have no clue how to handle that in LibGDX. For now, I am developping based on my Nexus 5 screen, but it will certainly not (down)scale well to devices with lower density screens.

On the web, most data are about LibGDX \< 1.0.0 and is totally irrelevant. The few things I have found talks about the Viewport classes, but it is poorly explained ; the game is either horribly stretch or way too small on high-definition devices.

At this point, I have understood that I need to define a "virtual screen" of some unit (lets say meters) and then place my elements based on this unit. But there is no fragment of clue on how to do that the right way in LibGDX ; when using Scene2D, for example, buttons are totally misshaped, with letters out of the box, buttons clearly overstretched and such, or ultra small based on the Viewport class used.

In the same way, using multiple asset size is not clear ; how to load them based on pixel density, how to force them to be there at the good size ? Etc... This stuff can make anyone crazy at start.

What I want to know is : is there somewhere some good, updated to recent libGDX, demos, examples or tutorial to the proper way to handle resolution, screen ratio and such in recent libGDX ? The libGDX viewport example, while a good start, are still unclear to me, and don't show the multiple asset size thing.

Thanks for any help, it is highly needed.

# Answer
Unfortunately, there is no magic: the only good way is to implement resolution independence yourself. While libgdx may be of some help, it's not going to solve your every problem.

For my NoThree puzzle game (see profile for link), I drew my graphics in Inkscape and I exported several resolutions (144x144, 72x72, 48x48) for each texture (the font is also packed in several sizes).

At loadtime, depending on the resolution, you should select the size you need:

```
int [] sizes = { 48, 72, 144 };
int size = 144;
for (int i = sizes.length - 1; i >= 0; --i) {
    if (sizes[i] * 10 > Math.min(Gdx.graphics.getHeight(), Gdx.graphics.getWidth())) {
        size = sizes[i];
    }
}

```

After this, you load the texture of size "size". The example above is for when you need about 10 sprites to fit the screen. You should choose font size similarly. You also want to make sure the textures are antialiased.

In the resize() method, I calculate the actual sizes and positions of all graphic elements. Here's an example:

```
    float pad = Math.min(width, height) / 32.0f;
    // have this amount of space between graphic elements (in pixels)
    if (landscape) {
        boardSize = Math.min(height - 2.0f * pad, width - 4 * pad - 2 * textWidth);
        // calculate the size of the game board (in pixels) making sure
        // the board fits in the screen along with the side text/buttons/etc
    } else {
        boardSize = Math.min(height - 6.0f * pad - 6.0f * textHeight, width);
    }

    if (landscape) {
        float startX = (width - boardSize) / 2;
        float startY = height - pad - boardSize;
        gameBoard.setPosition(startX, startY); // set the position of the game board
    } else {
        ...
    }

```

In render(), I would then simply call gameBoard.draw(). The gameBoard itself is an Actor that renders/keeps track of the game world.

To summarise, load textures of appropriate size (depending on the size of the screen and how many elements you need to fit on that screen), in resize() recompute the actual positions/sizes of the graphic elements and in render simply call their draw method.
> 5 votes

# Answer
I'm studying this book, and here what I learned so far:

You need to set a OrthographicCamera passing width and height of your screen, If you want pixel-perfect manipulation, pass the screen resolution, but for your problem you could just pass a size in 'meters'

```
camera = new OrthographicCamera(5.0f, 5.0f);

```

In your render method, you need to update the camera and set a projectionMatrix

```
camera.position.x = x;
camera.position.y = y;
camera.zoom = zoom;
camera.update();
batch.setProjectionMatrix(camera.combined);

```

Then you can draw everything on the screen based in this generic 'meter'

```
public class Rock extends AbstractGameObject{
    private void init(){
        dimension.set(1,1.5f); // in 'meters'
        regEdge = Assets.instance.rock.edge;
        regMiddle = Assets.instance.rock.middle;

        // initial size
        setLenght(1); // in 'meter' too
    }
}

```

and the draw method

```
    batch.draw(
                reg.getTexture(),
                position.x + relX, position.y + relY,
                origin.x, origin.y,
                dimension.x / 4, dimension.y,
                scale.x, scale.y,
                rotation,
                reg.getRegionX(), reg.getRegionY(),
                reg.getRegionWidth(), reg.getRegionHeight(),
                false, false
                );

```

The code and explanation and the explanation is oversimplified due my own limitations, but I hope it can be somewhat useful
> 3 votes

# Answer
I'm still rookie about **libgdx** and I currently started to port my android game to iOS via libgdx. In the android version I have drawable folders (assets) for different screen densities and resolutions and the loading of the proper ones works automatically (android knows which folder to access based on the device specs).

What I read everywhere for libgdx is that people use **Viewports** and **Camera** to handle different resolutions. This maybe a good case for most games, but it seems like overhead to implement for my game which fits entirely on the device screen (it's a card game).

I decided to give up Viewport and Camera and try to implement the android scheme with direct batch drawing on the screen. So what I currently try to do is this:

1) have 4 folders with different quality assets: **mdpi**, **hdpi**, **xhdpi**, **xxhdpi**. I borrowed the names from android.

```
assets/mdpi/ is for resolutions like >= 320x480
assets/hdpi/ >= 480x800
assets/xhdpi/ >= 720x1280
assets/xxhdpi/ >= 1080x1920

```

I still haven't decided what to do for tablets, but it will be something similar.

2) when game is starting make a simple check for these resolutions (if,else,switch) and manually load the corresponding textures

3) directly draw things on screen with **batch** and calucalations based on the real pixel dimensions of the textures and the real pixel dimensions of the screen. For example, if I want to center an image on screen I will calculate it's coordinates like this:

```
TextureRegion myImage = myAtlas.findRegion('myImage');
int myImageX = (Gdx.graphics.getWidth() - myImage.getRegionWidth()) / 2;
int myImageY = (Gdx.graphics.getHeight() - myImage.getRegionHeight()) / 2;

```

4) a nice consequence of not using Viewport and Camera and doing things directly with screen pixel coordinates is that all libgdx event coordinates (touch, mouse, etc.) can be used directly to tell what object is clicked and there is no need to unproject, project and translate coordinates in any way. This seems like a benefit as it's more simple to think about positions, because there are no separate coordinate systems to switch between, and constantly keep converting and imagining in your mind what should happen and when it will happen on screen.

I realise that this is super simple solution that may not prove viable in the future. However for the moment while I still learn about the framework, I decided to give it a try and see if it may prove worthy for my game.

These are some links that may be useful in regard to android and ios:

http://www.iosres.com/

http://developer.android.com/guide/practices/screens\_support.html
> 1 votes

---
Tags: android, libgdx, resolution
---


# Question
Title: How can I make A* finish faster when the destination is impassable?
I am making a simple tile-based 2D game, which uses the A\* ("A star") pathfinding algorithm. I've got all working right, but I have a performance problem with the search. Simply put, when I click an impassable tile, the algorithm apparently goes through the entire map to find a route to the impassable tile—even if I'm standing next to it.

How can I circumvent this? I guess I could reduce the pathfinding to the screen area, but maybe I am missing something obvious here?

# Answer
Some ideas on avoiding searches that result in failed paths altogether:

### Island ID

One of the cheapest ways to effectively finish A\* searches faster is to do no searches at all. If the areas are truly impassible by all agents, flood fill each area with a unique **Island ID** on load (or in the pipeline). When pathfinding check if the **Island ID** of the origin of the path matches the **Island ID** of the destination. If they do not match there is no point doing the search - the two points are on distinct, unconnected islands. This only helps if there are truly impassable nodes for all agents.

### Limit upper bound

I limit the upper bound of the maximum number of nodes that can be searched. This helps impassable searches from running forever, but it does mean some passable searches that are very long can be lost. This number needs to be tuned, and it doesn't really *solve* the problem, but it mitigates the costs associated with long searches.

If what you are finding is that it is taking **too long** then the following techniques are useful:

### Make it Asynchronous & Limit Iterations

Let the search run in a separate thread or a bit each frame so the game doesn't stall out waiting for the search. Display animation of character scratching head or stamping feet, or whatever is appropriate while waiting for the search to end. To do this effectively, I would keep the State of the search as a separate object and allow for multiple states to exist. When a path is requested, grab a free state object and add it to the queue of active state objects. In your pathfinding update, pull the active item off the front of the queue and run A\* until it either A. completes or B. some limit of iterations is run. If complete, put the state object back into the list of free state objects. If it hasn't completed, put it at the end of the 'active searches' and move onto the next one. This has the benefit of preventing long searches for agents, such as those that are impassible, from blocking shorter, passable searches for other agents.

### Choose the Right Data Structures

Make sure you use the right data structures. Here's how my StateObject works. All of my nodes are pre-allocated to a finite number - say 1024 or 2048 - for performance reasons. I use a node pool that speeds up the allocation of nodes and it also allows me to store indices instead of pointers in my data structures which are u16s (or u8 if I have a 255 max nodes, which I do on some games). For my pathfinding I use a priority queue for the open list, storing pointers to Node objects. It is implemented as a binary heap, and I sort the floating point values as integers since they are always positive and my platform has slow floating point compares. I use a hashtable for my closed map to keep track of the nodes I have visited. It stores NodeIDs, not Nodes, to save on cache sizes. The hashtable is a linear probe table and has the same size as the nodepool, and is allocated only once, when the StateObject is created.

### Cache What You Can

When you first visit a node and calculate the distance to the destination, cache that in the node stored in the State Object. If you revisit the node use the cached result instead of calculating it again. In my case it helps not having to do a square root on revisited nodes. You may find there are other values you can precalculate and cache.

Further areas you could investigate: use two-way pathfinding to search from either end. I have not done this but as others have noted this might help, but is not without it's caveats. The other thing on my list to try is hierarchical pathfinding, or clustering path finding. There is an interesting description in the HavokAI documentation Here describing their clustering concept, which is different than the HPA\* implementations described here.

Good luck, and let us know what you find.
> 48 votes

# Answer
AStar is a *complete* planning algorithm, meaning if there exists a path to the node, AStar is guaranteed to find it. Consequently, it *must* check every path out of the start node before it can decide the goal node is unreachable. This is very undesirable when you have too many nodes.

Ways to mitigate this:

* If you know *a priori* that a node is unreachable (e.g. it has no neighbors or it is marked `UnPassable`), return `No Path` without ever calling AStar.
* Limit the *number of nodes* AStar will expand before terminating. Check the open set. If it ever gets too big, terminate and return `No Path`. However, this will limit AStar's completeness; so it can only plan paths of a maximum length.
* Limit the *time* AStar takes to find a path. If it runs out of time, exit and return `No Path`. This limits the completeness like the previous strategy, but scales with the computer's speed. Note that for many games this is undesirable, because players with faster or slower computers will experience the game differently.
> 25 votes

# Answer
4. Run a dual A\* search from the target node in reverse as well **at the same time in the same loop** and abort both searches as soon as one is found unsolvable

If the target has only 6 tiles accessible around it and the origin has 1002 tiles accessible the search will stop at 6 (dual) iterations.

As soon as one search finds the other's visited nodes you can also limit the search scope to the other's visited nodes and finish faster.
> 21 votes

# Answer
Assuming the issue is the destination is unreachable. And that the navigation mesh isn't dynamic. The easiest way to do this is have a much sparser navigation graph (sparse enough that a full run through is relatively quick) and only use the detailed graph if the pathing is possible.
> 12 votes

# Answer
**Use multiple algorithms with different characteristics**

A\* has some fine characteristics. In particular, it always finds the shortest path, if one exist. Unfortunately, you have found some bad characteristics as well. In this case, it must exhaustively search for all possible paths before admitting no solution exists.

The "flaw" you are discovering in A\* is that it is unaware of topology. You may have a 2-D world, but it doesn't know this. For all it knows, in the far corner of your world is a staircase which brings it right under the world to its destination.

Consider creating a second algorithm which is aware of topology. As a first pass, you might fill the world with "nodes" every 10 or 100 spaces, and then maintain a graph of connectivity between these nodes. This algorithm would pathfind by finding accessable nodes near the start and end, then trying to find a path between them on the graph, if one exists.

One easy way to do this would be to assign each tile to a node. It is trivial to show that you only need to assign one node to each tile (you can never have access to two nodes which are not connected in the graph). Then the graph edges are defined to be anywhere two tiles with different nodes are adjacent.

This graph has a disadvantage: it does not find the optimum path. It merely finds *a* path. However, it has now shown you that A\* can find an optimum path.

It also provides a heuristic to improve your underestimates needed to make A\* function, because you now know more about your landscape. You are less likely to have to fully explore a dead end before finding out that you needed to step back to go forward.
> 4 votes

# Answer
Some more ideas in addition to the answers above:

6. Cache results of A\* search. Save the path data from cell A to cell B and reuse if possible. This is more applicable in static maps and you will have to do more work with dynamic maps.
7. Cache the neighbours of each cell. A\* implementation need to expand each node and add its neighbours to the open set to search. If this neighbours is calculated each time rather than cached then it could dramatically slow down the search. And if you havnt already done so, use a priority queue for A\*.
> 2 votes

# Answer
If your map is static you can just have each separate section have there own code and check this first before running A\*. This can be done upon map creation or even coded in the map.

Impassable tiles should have a flag and when moving to a tile like that you could opt not to run A\* or pick a tile next to it that is reachable.

If you have dynamic maps that change frequently you are pretty much out of luck. You have to way your decision making your algorithm stop before completion or do checks on sections get closed off frequently.
> 1 votes

# Answer
> How can I make A\* more quickly conclude that a node is impassable?

Profile your `Node.IsPassable()` function, figure out the slowest parts, speed them up.

When deciding whether a node is passable, put the most likely situations at the top, so that most of the time the function returns right away without bothering to check the more obscure possibilities.

But this is for making it faster to check a single node. You can profile to see how much time is spent on querying nodes, but sounds like your problem is that too many nodes are being checked.

> when I click an impassable tile, the algorithm apparently goes through the entire map to find a route to the impassable tile

If the destination tile itself is impassable, the algorithm shouldn't check any tiles at all. Before even starting to do pathfinding, it should query the destination tile to check if it's possible, and if not, return a no path result.

If you mean that the destination itself is passable, but is encircled by impassable tiles, such that there is no path, then it is normal for A\* to check the whole map. How else would it know there's no path?

If the latter is the case, you can speed it up by doing a bidirectional search - that way the search starting from the destination can quickly find that there is no path and stop the search. See this example, surround the destination with walls and compare bidirectional vs. single direction.
> 1 votes

# Answer
### Do the path-finding backwards.

If only your map doesn't have big continuous areas of unreachable tiles then this will work. Rather than searching the entire reachable map, the path-finding will only search the enclosed unreachable area.
> 0 votes

# Answer
To check for the longest distance in a graph between two nodes:

(assuming all edges have the same weight)

1. Run BFS from any vertex `v`.
2. Use the results to select a vertex furthest away from `v`, we'll call it `d`.
3. Run BFS from `u`.
4. Find the vertex furthest away from `u`,we'll call it `w`.
5. The distance between `u` and `w` is the longest distance in the graph.

Proof:

```
                D1                            D2
(v)---------------------------r_1-----------------------------(u)
                               |
                            R  | (note it might be that r1=r2)
                D3             |              D4
(x)---------------------------r_2-----------------------------(y)

```
* Lets say the distance between `y` and `x` is greater!
* Then according to this `D2 + R < D3`
* Then `D2 < R + D3`
* Then the distance between `v` and `x` is greater than that of `v` and `u`?
* Then `u` wouldn't have been picked in the first phase.

Credit to prof. Shlomi Rubinstein

If you are using weighted edges, you can accomplish the same thing in polynomial time by running Dijkstra instead of BFS to find the furthest vertex.

Please note I'm assuming it's a connected graph. I am also assuming it's undirected.

---

A\* is not really useful for a simple 2d tile based game because if I understand correctly, assuming the creatures move in 4 directions, BFS will achieve the same results. Even if creatures can move in 8 directions, lazy BFS that prefers nodes closer to the target will still achieve the same results. A\* is a modification Dijkstra which is far more computationally expensive then using BFS.

BFS = O(|V|) supposedly O(|V| + |E|) but not really in the case of a top down map. A\* = O(|V|log|V|)

If we have a map with just 32 x 32 tiles, BFS will cost at most 1024 and a true A\* could cost you a whopping 10,000. This is the difference between 0.5 seconds and 5 seconds, possibly more if you take the cache into account. So make sure your A\* behaves like a lazy BFS that prefers tiles that are closer to the desired target.

A\* is useful for navigation maps were the cost of edges is important in the decision making process. In a simple overhead tile based games, the cost of edges is probably not an important consideration. Event if it is, (different tiles cost differently), you can run a modified version of BFS that postpones and penalizes paths that pass through tiles that slow the character down.

So yeah BFS \> A\* in many cases when it comes to tiles.
> 0 votes

# Answer
If the areas that the player are connected (no teleports etc.) and the unreachable areas are generally not very well connected, you can simply do the A\* starting from the node you want to reach. That way you can still find any possible route to the destination and A\* will stop searching quickly for unreachable areas.
> 0 votes

# Answer
> when I click an **impassable tile**, the algorithm apparently goes through the entire map to find a route to the impassable tile — even if I'm standing next to it.

Other answers are great, but I have to point at the obvious - You should not run the pathfinding to an impassable tile at all.

This should be an early exit from the algo:

```
if not IsPassable(A) or not IsPasable(B) then
    return('NoWayExists');

```
> 0 votes

---
Tags: algorithm, performance, path-finding
---


title: Rotating towards a point in Box2D

text:
# Question
Title: Rotating towards a point in Box2D
I'm using Box2d as my physics engine and I'm trying to solve what would normally be a simple problem but what has become a nightmare for me and preventing me from finishing my app. (6 months work)

I've tried implementing this: (Example of implementation below) http://box2d.org/forum/viewtopic.php?f=18&t=7306 but it's got three problems. 1: When reaching the top angle it stops and goes the other way. (Example in logs) 2: Limited speed, some objects need turn fast. 3: Large objects with moving joints spaz out rocking all over the place.

I have a desired angle and I want my body to rotate at different speeds (depending on turn speed setting as I want large slow turn objects).

Problems with current code. 1: Large object with a moving joint either spin very fast or rock constantly. 2: The rock effect exists on everything.

**Edit** This is within a game loop, so have access to delta.

**Code 1: Box2D attempt:**

```
//Testing speed.
float tempSpeed = MathUtils.PI;

float currentAngle = getBody().getAngle() % MathUtils.PI2;

float nextAngle = getBody().getAngle() + (getBody().getAngularVelocity() * update);
float totalRotation = getDesiredAngle() - nextAngle;

//Assuming this tries to prevent the switch angle problem but limits the speed??
while ( totalRotation < -MathUtils.PI * tempSpeed ) totalRotation += MathUtils.PI2 * tempSpeed;
while ( totalRotation >  MathUtils.PI * tempSpeed ) totalRotation -= MathUtils.PI2 * tempSpeed;

float desiredAngularVelocity = totalRotation;
float change = 1f * tempSpeed; //allow 1 degree rotation per time step
desiredAngularVelocity = Math.min(change, Math.max(-change, desiredAngularVelocity));
float impulse = getBody().getInertia() * desiredAngularVelocity;
getBody().applyAngularImpulse(impulse, true);

//Below shows an example of the top angle being switched.
if(getFocus()){
    Functions.log("currentAngle: " + getBody().getAngle() + " | nextAngle: " + nextAngle + " | totalRotation: " + totalRotation + " | desiredAngularVelocity: " + desiredAngularVelocity);
}
/*
Log: nextAngle: -0.1850999 | totalRotation: 6.400846 | desiredAngularVelocity: 3.1415927
Log: nextAngle: -0.02812685 | totalRotation: 6.2195992 | desiredAngularVelocity: 3.1415927

Example of top angle being reached and switching back.

Log: nextAngle: 0.21522963 | totalRotation: 5.948592 | desiredAngularVelocity: 3.1415927
Log: nextAngle: 0.45278195 | totalRotation: 5.6859627 | desiredAngularVelocity: 3.1415927
 */

```

**Code 2: My warped attempt**

```
//Keep the angle within range.
float currentAngle = getBody().getAngle() % 6.283185f;

//Get the next angle. Use angle in next time step
float nextAngle = currentAngle + (getBody().getAngularVelocity() * update);

float totalRotationAngle = getDesiredAngle() - nextAngle;

//Keep the total rotation within range, so we don't spin all the way around when reaching the other side.

while (totalRotationAngle < -MathUtils.PI) {
    totalRotationAngle += (MathUtils.PI2);
}
while (totalRotationAngle > MathUtils.PI) {
    totalRotationAngle -= (MathUtils.PI2);
}

//Do some other stuff.
float desiredAngularVelocity = totalRotationAngle * getRotationSpeed();

//Inertia is the amount of force required to rotate the object, without it it rotates really fast.
//If we introduce it, we get more realistic results but the horrible rock.
//float torque = (getBody().getInertia() * (desiredAngularVelocity * this.turnSpeed)) * update;

//Need inertia otherwise it can spins things right out the way.

//float turnSpeed = (this.turnSpeed * (4f * (getDesiredAngle())));

float torque = (desiredAngularVelocity * (this.turnSpeed));
torque *= (getBody().getInertia());
torque *= update;

//Apply torque.
getBody().applyTorque(torque, false);

```

# Answer
I think you want method 1, not method 2. I assume you a constant turn rate towards the desired heading? In that case, torque, being angular force, is not what you'd want to use here. (You'd need infinite torque to get the initial immediate start, and then infinite torque to stop immediately at the target direction) so the first method is more accurate.

There's a couple places where your variables don't seem to have the right units. It may help to write out (on paper) what units each of your variables is and check the units with dimensional analysis.

The following two lines of code clamp totalRotation/tempSpeed to \[-π, π\]. Assuming `tempSpeed` is your maximum angular velocity, this doesn't make much sense to me. I think you should remove the tempSpeed parts, and thus the logic is that "total rotation" needs to be in that range.

```
//Assuming this tries to prevent the switch angle problem but limits the speed??
while ( totalRotation < -MathUtils.PI * tempSpeed ) totalRotation += MathUtils.PI2 * tempSpeed;
while ( totalRotation >  MathUtils.PI * tempSpeed ) totalRotation -= MathUtils.PI2 * tempSpeed;

// should be:
while (totalRotation < -MathUtils.PI) totalRotation += MathUtils.PI2;
while (.. etc ..)

```

The following two lines seem wrong to me as well -- your desiredAngularVelocity is angular velocity (unit: 1/time), and not a rotation (radians are unitless), you need to divide by a time variable. Also, the change variable has some you're not allowing 1 degree rotation per timestep, you're allowing 180 degrees rotation per unit time (i.e, second).

```
float desiredAngularVelocity = totalRotation;
float change = 1f * tempSpeed; //allow 1 degree rotation per time step

// should be:
float desiredAngularVelocity = totalRotation / timedelta;
float change = tempSpeed * delta; // allow 180 degree rotation per second

```

With these changes, it should remove the wobbling, which was caused by an incorrect impulse calculation that always overshot the desired value.
> 1 votes

---
Tags: libgdx, box2d, jbox2d
---


title: Storing walls that are between tiles

text:
# Question
Title: Storing walls that are between tiles
I am writing isometric engine in c++. I decided to take a more realistic approach and make walls occupy space between two tiles, not a single whole tile, as shown in the picture below (just like in The Sims).

My problem is that I have no idea how to store the tile map related data in something that is not grid. In this situation I guess I will need to make it A\* friendly, so there will be nodes and edges between tiles not divided by walls. Here is another picture showing what I want to achieve:

**So here is the question(s):**

How should I:

* store the whole map, both tiles and walls
* optimize it for rendering
* use it for A\* and other algorithms rather straightforward to implement on a simple grid but now using walls (edges) to determine visibility, collision etc.?

# Answer
> 9 votes
I start with coordinate systems — the coordinates for grid locations are (x,y) but as Krom mentioned in a different answer, for walls there can be up to two walls for each grid location. That leads to a second coordinate system, for *edges between tiles*. In this article I used West and South so the edges can be (x,y,West) or (x,y,South), but you can pick two as long as you're consistent.

These two coordinate systems (grid tiles and edges) are related. You'll want to ask: which *four* edges surround a tile?

For pathfinding, A\* wants to know which tiles are neighbors (B) of the current tile (A). Instead of returning all four adjacent tiles, you can check the four edges. You include tile B as a neighbor only if there's no wall between A and B.

Instead of storing two walls for each tile, as Krom suggests, I usually keep the walls in a separate data structure: a *set* of edge coordinates. When A\* wants to know whether B is a neighbor of A, I will check whether that edge is in the set. If it is, then I don't return B.

You probably don't need this for A\*, but for other things you'll probably want to know for any edge, which *two* tiles are connected to it:

See the “Algorithms” section of the page for the calculations for these two operations.

Also note: for some types of maps, you'll actually want to store *four* edges per grid tile, so that you can support one-way moves.

# Answer
> 4 votes
In each tile you can store walls it has on North and East. That way each tile needs to store only 2 more booleans (or ints, if you want to store wall type). Downside is that tiles along South and West edges cannot have walls on South and West unless you add a one more row of hidden tiles that will have them.

# Answer
> 2 votes
In each tile, it could store the neighbours (or connectivity) that it has access to. Perhaps as a bitmap. The walls are where the two adjacent tiles are not connected. This is very friendly with A\*.

The second approach is to store the connectivity of tile as a enumeration. For example, a fully open tile is 0, a tile with wall to north and rest open is 1, a tile with wall to south and rest open is 2, and so on until you covered all possible combinations.

# Answer
> 1 votes
Hopefully this C# is okay for you - my c++ is very rusty:

```
abstract class MapFeature
{
    public void Draw();
    public bool IsWall();
}
enum Direction
{
    North, South, East, West
}
class Wall : MapFeature
{
    public bool IsWall() { return true; }
    public Tile Front, Back; // Tiles on either side of the wall, otherwise null.

    #region Implementation of MapFeature

    public void Draw()
    {
        // Wall specific drawing code...
    }

    #endregion
}
class Tile : MapFeature
{
    public bool IsWall() { return false; }

    public MapFeature North, South, East, West; // Tiles/Walls on each side, otherwise null

    public bool CanGo(Direction direction)
    {
        switch (direction)
        {
            case Direction.North:
                return !North.IsWall();
            case Direction.South:
                return !South.IsWall();
            case Direction.East:
                return !East.IsWall();
            case Direction.West:
                return !West.IsWall();
            default:
                throw new ArgumentOutOfRangeException("direction");
        }
    }

    #region Implementation of MapFeature

    public void Draw()
    {
        // Tile specific drawing code...
    }

    #endregion
}

```

You can add wall-specific information to the Wall class, Tile specific information to the Tile class, and further refine conditions in the "CanGo" method. For example, when a wall is actually a locked door - say, a Door class.

In order to draw this, you would start with some arbitrary tile - say the tile in the middle of the current camera position. Then move toward and to the left of the camera according to the size of the tiles. Then do a breadth-first traversal of the IMapFeature nodes, drawing each wall/tile in the order encountered.

A\* will work on this structure, though you would obviously need some modifications to handle something like locked doors.

If you wanted to, you could also maintain a spatial index of the tiles, which would implicitly include the walls, in order to find out which tiles were within camera bounds.

You'd still only need to pick a starting tile and a distance to traverse based on tile size.

---
Tags: tiles, tilemap, grid
---


title: How to Render an xml tile grid in java

text:
# Question
Title: How to Render an xml tile grid in java
So i decided to write my games data files in xml since a lot of people recommend it security wise for an online game, but how exactly does one render an xml tile grid in java?

format will be as follows:

```
<Data>
   <Tile X="1" Y="1" Value="12"></Tile>
</Data>

```

# Answer
> 2 votes
XML is just a data storage (or transfer) format. The XML file itself has nothing to do with rendering tilemaps. You actually need to have the data in memory in a better format suited for rendering tile maps.

I think you should tackle the problem from another direction. Rather than trying to figure out how to render XML data as tile map, you should just learn to render tile maps, and then save that data in a XML file.

---
Tags: java, xml
---


title: LWJGL Stencil shadow problem

text:
# Question
Title: LWJGL Stencil shadow problem
I've a problem with shadow (Stencil). So when i draw the shadow they looks good, but when the object to draw is underground his shadow is wrongly rendered. My game is do with LWJGL/GL11.

Normal render: over http://web-survival-machines.crystal-serv.com/shadow%20problem%201.jpg Bad renders: over http://web-survival-machines.crystal-serv.com/shadow%20problem%202.jpg over http://web-survival-machines.crystal-serv.com/shadow%20problem%203.jpg

the light is on the right of the scene.

code used to render:

```
public void render(){
    TimeLogic.updateMSTimer(); TimeLogic.updateDelta();
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);

    glLight(GL_LIGHT0, GL_POSITION, BufferUtils.arrayToBufferFloat(lightPos));

    //-----

    glEnable(GL_STENCIL_TEST);
    glStencilFunc(GL_ALWAYS, 1, ~0);
    glStencilOp (GL_KEEP, GL_KEEP, GL_REPLACE);
    drawScene();
    /*do->
    glPushMatrix();
        glTranslatef(0,(float)(Math.sin((float)(Sys.getTime())*0.002f))*2+1, 0);
        sphere.draw(1, 70, 20);
    glPopMatrix();

    SimpleEntities.drawBox(50, 0.25f, 50);
    */

    //-----

    glDisable(GL_STENCIL_TEST);

    glDisable(GL_DEPTH_TEST);
    glEnable(GL_STENCIL_TEST);
    glStencilFunc(GL_EQUAL, 1, ~0);
    glStencilOp(GL_KEEP,GL_KEEP,GL_ZERO);

    glEnable(GL_BLEND);//Turn blending on
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    glDisable(GL_LIGHTING);//Turn off light to draw shadow without normals
    glColor4f(0.0f,0.0f,0.0f,0.5f);//Exsisting color (on plane) is modulated with 50% black

    //-----

    //Draw shadow of objects on the floor
    glEnable(GL_DEPTH_TEST);

    drawSceneShadow();
    /*do->
    glPushMatrix();
        glTranslatef(0, 0.0005f, 0);
        glMultMatrix(BufferUtils.arrayToBufferFloat(shadow_floor));
        drawSphere();
    glPopMatrix();
    */
    //-----

    //Restore original mode
    glDisable(GL_BLEND);
    glDisable(GL_STENCIL_TEST);
    glEnable(GL_DEPTH_TEST);
    glEnable(GL_LIGHTING);

    //-----

    updateCam();//check keys and do a gluLookAt();

    Display.update();
    Display.sync(GameInfo.FPS);//--> 60FPS

    TimeLogic.showFPS();

    if(Keyboard.isKeyDown(Keyboard.KEY_ESCAPE)){
        //pauseMenuShow = true;
        //showPauseMenu();
        render = false;
        Display.destroy();
    }
}

```

SimpleEntities.drawBox function:

```
public static void drawBox(float x, float y, float z){
    // cut the quad in parts for light reflection

    float cutx = 0;
    for(float i=0;i<x;i+=cutSize){
        cutx++;
    }
    float cuty = 0;
    for(float i=0;i<y;i+=cutSize){
        cuty++;
    }
    float cutz = 0;
    for(float i=0;i<z;i+=cutSize){
        cutz++;
    }
    //-------------------------
    glPushMatrix();
    glScalef(x,y,z);
    glBegin (GL_QUADS);

    //glColor3f(1, 1, 0);
    //face 1
    glNormal3f(-1, 1,-1);
    glVertex3f(-1, 1,-1); glVertex3f( 1, 1,-1);
    glVertex3f( 1,-1,-1); glVertex3f(-1,-1,-1);
    //face 2 bottom
    glNormal3f(-1,-1,-1);
    glVertex3f(-1,-1,-1); glVertex3f( 1,-1,-1);
    glVertex3f( 1,-1, 1); glVertex3f(-1,-1, 1);
    // face 3
    glNormal3f( 1,-1, 1);
    glVertex3f( 1,-1, 1); glVertex3f( 1,-1,-1);
    glVertex3f( 1, 1,-1); glVertex3f( 1, 1, 1);

    //face 4 top
    //--> x;z
    //System.out.println("number of part:\nx:"+cutx+"\ny:"+cuty+"\nz:"+cutz+"\n-----------------------");
    boolean first = true;
    for(float ix=0;ix<cutx;ix++){
        for(float iz=0;iz<cutz;iz++){
            /*
            glColor3f(30, 30, 30);
            if(first){
                glColor3f(255, 0, 0);
                first = false;
            }
            if(ix+1 == cutx && iz+1 == cutz){
                glColor3f(0, 255, 0);
                first = false;
            }
            */
            //-1 ==> i/cutx*2-1
            //1  ==> i/(cutx+1)*2-1
            /*
            System.out.println("-------------------------");
            System.out.println("iz="+iz);
            System.out.println("cutz="+cutz);
            System.out.println("=>"+iz+"/"+cutz+"*2-1");
            System.out.println("=>"+div+"*2-1");
            System.out.println("=>"+(div*2)+"-1");
            System.out.println("=>"+(div*2-1));
            System.out.println("-------------------------");
            */
            //System.out.println("-1 => "+iz+"/"+cutz+"*2-1 = "+n1);
            //System.out.println("1  => ("+iz+"/"+cutz+"+1)*2-1 = "+(iz/(cutz+1)*2-1));
            //float milis = (float)Math.sin(((double)System.currentTimeMillis())/5000);

            float overx = (ix+1)/cutx-0.5f;
            float underx = ix/cutx-0.5f;
            float overz = (iz+1)/cutz-0.5f;
            float underz = iz/cutz-0.5f;

            /*
            float overx = (ix+1)/cutx;
            float underx = ix/cutx;
            float overz = (iz+1)/cutz;
            float underz = iz/cutz;
            */
            glNormal3f(overx*2, 1, underz*2);
            glVertex3f(overx*2, 1, underz*2); glVertex3f(underx*2, 1, underz*2);
            glVertex3f(underx*2, 1, overz*2); glVertex3f(overx*2, 1, overz*2);
        }
    }
    //glNormal3f( 1, 1,-1);
    //glVertex3f( 1, 1,-1); glVertex3f(-1, 1,-1);
    //glVertex3f(-1, 1, 1); glVertex3f( 1, 1, 1);
    //face 5
    glNormal3f(-1, 1, 1);
    glVertex3f(-1, 1, 1); glVertex3f(-1, 1,-1);
    glVertex3f(-1,-1,-1); glVertex3f(-1,-1, 1);
    //face 6
    glNormal3f( 1,-1, 1);
    glVertex3f( 1,-1, 1); glVertex3f( 1, 1, 1);
    glVertex3f(-1, 1, 1); glVertex3f(-1,-1, 1);
    glEnd();
    glPopMatrix();
}

```

Can someone help me to resolve this bug ? thanks !

Sorry for my bad english --'

# Answer
> 1 votes
You are drawing the shadow using a cone from the light source which extends above the object causing the wrong shadow when the object is below ground.

You need to draw volumetric shadows by extending the shadow-casting object in the direction opposite to the light source, capped at the object.

Google "Volumetric Shadows" or "Shadow volume".

http://en.wikipedia.org/wiki/Shadow\_volume

Notice that the shadow volumes don't extend toward the light, only away from it (light cap).

Chapter 9. Efficient Shadow Volume Rendering

---
Tags: lwjgl, shadows
---


# Question
Title: Can someone explain to me how setting shader parameters aren't a bottleneck?
I am trying to understand this. So I have a bunch of models that need to be rendered. Each model most likely has various "sub meshes" with their own diffuse, specular, etc textures. So for each of these models I have to loop through set the diffuse, specular, etc and then a draw call. Now lets say I do this a couple times for each model, and I have 100 models in a scene. Since my C++ code that sets these per model parameters is called by the CPU, doesn't it have to bus all that data to the GPU a ridiculous amount of times. Even if it doesn't and the GPU is caching, wouldn't the CPU still need to make several inquires to make sure the correct resources are cached? I am asking because I have a, single, high res model I am rendering and once textures are applied I drop from 1000 FPS to 70. This model has about 20 different textures, and isn't something that will be used in a game, solely using it to stress test and locate bottlenecks. Thanks!

# Answer
Look into "Shader Constants Buffers" on DirectX and "Uniform Buffers" on OpenGL. These allow sending shader parameters all at once to the GPU and possibly reusing them every frames without having to resend them over the bus.
> 0 votes

# Answer
It isn't entirely clear what you are asking. Setting shader parameters **IS** a bottleneck - that's why engines batch by material - textures, parameters, lights, etc. While CPUs and GPUs are efficient, in order to get the most out of rendering performance you have to think about these things.
> 2 votes

---
Tags: c++, directx, hlsl
---


# Question
Title: How to detect if players alter game files and stop them from entering the game server
as the question says.

how can i check if a player modifies a file such as maps or spells in my rpg games that will be located as "/cache/spells", "/cache/maps" or "/cache/entities" and you get the point.

all the files are going to be written in .xml if that matters and the game will be an online game made in java. not a browser game btw

# Answer
> 0 votes
The client can use the files to reduce network latency but everything must be confirmed by the server.

For example, if the client's map has been modified to remove a wall and the client tells the server "I move from Point A to Point B" on the other side of the wall that has been removed, the server rejects the move and sends back a packet "you're at Point A".

The modified client will see itself starting to walk through the (deleted) wall and pop back to its original position just before the wall.

Every other clients will only see the confirmed moves from the server and won't see the modified client going through the wall.

Same applies for spell costs and effects.

Server has to confirm and will resynchronize everything, canceling out any client-side modifications.

The client can spawn a fireball graphic locally but the damage to the enemy will only occur once the server confirms it and the amount is decided by the server, not the client.

Essentially, you do not need to detect client-side modifications as they are rendered inconsequential and will cause more trouble for the attempted cheat than anyone else.

---
Tags: java, data
---


# Question
Title: How can I find the minimal texture size so the texture requires no pixel interpolation when transformed by a given matrix?
Given a rectangle with width **x** and height **y**, and a transformation matrix **T**: How can I estimate the minimal resolution of the texture (that is, its width and height) such the interpolation of additional pixels won't be needed?

*Simple example*: If `x = 200px`, `y = 150px` and `T` is a 2× scale matrix, then the required resolution is 400×300.

How can I do this for more complex cases, such as perspective projection?

# Answer
To calculate perspective projection divide by w.

```
vec4 result = vec4(x, y, z, 1) * perspective_view_model_matrix;
result /= w;

```

You are then left with the (x,y) in screen space (-1 to 1).

Multiply this by 1/2 screen width,height and you get pixel coordinates.

You then need to take the corresponding vertex UVs, multiply by the texture size and you get texel coordinates.

What you need to do next is calculate the polygon (triangle) **pixel area** and the polygon (triangle) **texel area**, divide one by the other and you get the texel-to-pixel ratio (or the other way around).

This will give you an approximation of how big/small the texture is relative to screen size.

It will work even rotated as long as the polygons are facing the screen and have uniform scaling otherwise you'll get an average as some texels will be more stretched than others.
> 1 votes

---
Tags: mathematics, textures, algorithm, matrix, interpolation
---


title: Artefacts when drawing textures

text:
# Question
Title: Artefacts when drawing textures
I am working on a level-based android game. The level is constructed of many blocks, all drawn with the same texture. Until now I didn't have any problems with drawing the different textures next to each other. However, when I draw a translucent rectangle over the level (in order to show a pause screen on top of it for example), I get artefacts on the places where the textures overlap. To be more clear I included a screenshot that clearly shows my issue: the regions where the textures of the different level blocks overlap do not have the same transparency as the rest of the rectangle.

As you can see, only when drawing the translucent rectangle on top of the level, the overlap is visible.

# Answer
This issue happens with some MSAA or CSAA implementations.

Try disabling anti-aliasing and see if it goes away.

If that is the case you might need to force multi-sampling resolve before rendering your transparency.

The other solution would be to force some overlap of your tiles.
> 2 votes

---
Tags: libgdx, transparency, alpha-blending
---


# Question
Title: Unity: Object is underneath another object but shouldn't be
I have a simple collision detection program. The red object is controlled by the user and the yellow object is always moving up and down:

However, when the objects are supposed to collide, the red object ends up being underneath the yellow object. I wrote code that should destroy the red object on collision. This is a 2D game project, so I'm not sure how that works. They both have *0* set value for *Order In Layer* field.

Movement code for red object:

```
using UnityEngine;
using System.Collections;

public class Movement : MonoBehaviour {

    // Use this for initialization
    void Start () {

    }

    // Update is called once per frame
    void Update () {
        //GetKeyDown checks if a button is clicked, but GetKey checks if a button is held down.

        //LEFT
        if (Input.GetKey (KeyCode.LeftArrow))
        {
            transform.Translate(-1 * Vector2.right);
        }

        //RIGHT
        if (Input.GetKey (KeyCode.RightArrow))
        {
            transform.Translate(Vector2.right);
        }

        //UP
        if (Input.GetKey(KeyCode.UpArrow))
        {
            transform.Translate(Vector2.up);
        }

        //DOWN
        if (Input.GetKey(KeyCode.DownArrow))
        {
            transform.Translate(-1 * Vector2.up);
        }
    }
}

```

Movement code for yellow object (contains collision event):

```
using UnityEngine;
using System.Collections;

public class EnemyMovement : MonoBehaviour {

    private bool moveUp;

    // Use this for initialization
    void Start () {
        moveUp = true;
    }

    // Update is called once per frame
    void Update () {

        if(transform.position.y == 30)
        {
            moveUp = false;
        }
        else if(transform.position.y == -30)
        {
            moveUp = true;
        }

        if (moveUp)
        {
            transform.Translate (Vector2.up);
        }
        else
        {
            transform.Translate (-1 * Vector2.up);
        }
    }

    void OnCollisionEnter (Collision col)
    {
        if(col.gameObject.name == "player_character")
        {
            Destroy(col.gameObject);
        }
    }
}

```

Also, I'm a complete newbie with Unity, so sorry if I'm asking something that should be obvious.

# Answer
> 1 votes
For Physics2D the method needs to be called **OnCollisionEnter2D** and both gameobject needs to have a Collider like BoxCollider2D or CircleCollider2D

```
public class EnemyMovement : MonoBehaviour
{
    void OnCollisionEnter2D (Collision2D col)
    {
        if(col.gameObject.name == "player_character")
        {
            Destroy(col.gameObject);
        }
    }
}

```

For **Layer Ordering** you are already found the correct property *Order In Layer*. The red object needs to have a higher number i.e. 1 then the yellow object.

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


title: Encoding Float to RG/RGBA and Blending

text:
# Question
Title: Encoding Float to RG/RGBA and Blending
Encoding a float value inside a RG or RGBA texture is very interesting and useful but it is also become quite useless when you use blending as the result and the values might be altered because of face overlapping. Is there a way to avoid such issues ?

here is an example of a bad result when encoding depth on the red and green channels and just decoding it again in a post-process effect.

# Answer
> 1 votes
Disable blending when rendering your depth texture.

Or use an actual depth texture as depth buffer in a frame buffer object then use that depth texture in later passes with a sampler.

---
Tags: opengl, shaders, directx, glsl, hlsl
---


# Question
Title: Alternatives to map of strings in regard to performance
I would like to start my first question here with a subjective question. I think it qualifies as constructive.

To introduce the situation: I have a 2D tiled map. I also had different arrays of graphics (one array for tile graphics, one array for GUI graphics, multiple arrays for different kinds of entities that can be placed onto the map).

Because I have not liked these many arrays I wanted to refactor so that I have *one* data structure to hold all my graphics. The thing is now that a number of graphics belong together

* A map tile has several graphics for different views, i.e. angles you can watch from.
* An animation has multiple frames and is also view-dependant.
* There are entities with have multiple states and therefore different graphics.
    + These states I can also use for GUI elements (button normal, hovered, pressed).

To consolidate all these requirements I thought of

```
std::unordered_map<std::string, const GraphicSet*>

```

as the holder of all the graphics

```
// with ...
class GraphicSet : private std::unordered_map<GraphicSetKey, Animation*, ...>

class Animation : private std::vector<const IGraphic*>

typedef const std::string GraphicSetKeyState;
typedef const std::string GraphicSetKeyView;
typedef std::pair<GraphicSetKeyState, GraphicSetKeyView> GraphicSetKey;

// ...and IGraphic as the very graphic

```

. I knew that using standard library container is slower than arrays in memory but tried it anyway. And indeed it is too slow. According to `callgrind` rendering a single frame is nearly 85% slower than before. This is unacceptable.

I do not want to badmouth the standard library because if I would implement my own container it would be as bad. The problem - `callgrind` reveals this as well - are the strings I am using. For every tile I want to draw the program creates a string uses the whole mechanism hashing and so on just to get me the graphic I desire.

---

Now we are getting to the question:
What data structure / technique would you suggest? (please read on)

My next idea is to partially fall back to my graphics arrays. But instead of several arrays I want to do one big array and map these views and state at compile time to indexes.

One issue I yet have in mind: My goal eventually is to be open for extensions. I want everything to be configurable so for example modifying the entities and the graphics of the game is possible by editing a config file.

With strings this is pretty easy by simply adding a new key to the map. If however I use fixed indexes at compile time this will be a very big problem in the future.

How can I keep it performant but also flexible for the future?

# Answer
AFAIK standard procedure is to have resources stored in a map-like structure with strings as keys, since it's extensible as you've seen. However, for the core game elements (especially the performance-critical ones), the resources will be explicitly linked instead of involving a key-lookup, thus skipping the lookup overhead.

For example, you might have a `Pony` that you render by drawing a `Sprite`. Initially you might lookup the sprite by using the string `"pink_pony_sprite"` then rendering it, every frame, but to make this more efficient, your pony will hold a reference to the sprite directly. Your pony might look something like this then:

```
class Pony {
public:
    Pony(const std::string& name, const Sprite& sprite);
    void Render(Renderer& r) { r.render(_sprite); }
private:
    const Sprite& _sprite;
};

// Construction:
Pony p{"Speckles", bigSpriteMap["pink_pony_sprite"]};

```

This setup has the following advantages:

* Extensible (you can easily add, or change what sprite to use for your ponies)
* Reusable assets (multiple ponies can use the same sprite)
* Efficient (only one map lookup, during construction)
> 3 votes

---
Tags: c++, graphics, performance
---


# Question
Title: How do I modify the health of an entity after it has been created?
Is there any way to add or remove health after an entity has been created?

For example, I'd like to have a mob regenerate "hearts" when some event happens.

# Answer
There are two ways. Using MCP obfuscation mappings, the first and proper way to do so is with:

```
EntityLiving.attackEntityFrom(DamageSource, damageDealt);

```

You need to specify where the damage came from in the first parameter though, so the simpler one is to simply use:

```
EntityLiving.setEntityHealth(health);

```

Use this with getHealth so you can do stuff like `entity.setEntityHealth(entity.getHealth() - 1);`
> 7 votes

# Answer
Use this JSON Code:

```
{HealF:0,Attributes:[{Name:"generic.maxHealth",Base:0}]}

```

, use

```
/entitydata @e[type=MOBNAME] JSON

```

or use

```
/summon MOBNAME ~ ~ ~ JSON

```

to summon the mob or change the mobs health. Change the two 0's in the JSON code to whatever health you want that mobs health to be, but the format is set in half hearts, so you may want to double the number (So 100 full hearts would be 200 as the number in the JSON). This is completely vanilla, and uses no external resources.
> 0 votes

# Answer
Use MCedit to give mobs more/less heath. Or you could give it something like 5 seconds before it gets a regeneration effect. If you havn't got MCEdit look it up on youtube and download it :)
> -1 votes

---
Tags: minecraft-modding
---


title: XNA/Monogame inverting a BoundingBox

text:
# Question
Title: XNA/Monogame inverting a BoundingBox
I have a box that is drawn around my game that I want to check collisions with. Currently my `BoundingBox` is made in a way that whatever is **inside** the box is colliding with it:

```
BoundingBox bb = new BoundingBox(new Vector3(position.X - 0.1f, position.Y - 0.1f, position.Z - width - 0.1f), new Vector3(position.X + width + 0.1f, position.Y + width + 0.1f, position.Z + 0.1f));

```

(Note: the `+0.1f` is added so that it doesn't cause collision when an object is touching it, only when it passed through)

What I want is the inverse. I want a `BoundingBox` around this box so that only objects **outside** of the box will cause collision.

Is there an easy way of doing this or am I supposed to make different BoundingBoxes around this existing one? Thanks

# Answer
`BoundingBox` provides several `Contains` (MSDN) methods that return `ContainmentType` (MSDN).

To test if an object is *outside* your bounding box, test for `ContainmentType.Disjoint`.
> 3 votes

# Answer
You need to invert the logic of the test not the box itself. The bounding box can only describe a box. Whether that is a rectangular solid in space or a rectangular hole in infinite space is up to the test performed.
> 2 votes

---
Tags: xna, c#, collision-detection, monogame, bounding-boxes
---


# Question
Title: Unity3D: Disable player input but not character movement?
I'm trying to code a dash/air dash for a 2D platformer. In my character controller's `FixedUpdate()`, I have various `if` statements that cause certain actions when a button is pressed.

To disable player input while the dash was happening, I tried putting `Dash()` in an `IEnumerator` with a simple test code like this:

```
IEnumerator Dash() {
    if (player.GetAxis("Horizontal") < 0)
        {
            thePlayer.GetComponent<HeroController>().enabled = false;
            yield return new WaitForSeconds(0.5f);
            move = move * 2;
            thePlayer.GetComponent<HeroController>().enabled = true;
    }
}

```

But since the character's physics are inside the character controller, both the player's input and the character's movements are stopped when the controller is disabled. How can I disable inputs while still allowing the character to dash?

# Answer
> 2 votes
You could make a bool that, if true, checks for all input. If false, you essentially turn off all input.

```
bool DoInputs = true;
IEnumerator Dash() {
  if (DoInputs)
    if (player.GetAxis("Horizontal") < 0)
        {
            thePlayer.GetComponent<HeroController>().enabled = false;
            yield return new WaitForSeconds(0.5f);
            move = move * 2;
            thePlayer.GetComponent<HeroController>().enabled = true;
    }
}
```

If you'd like to keep detecting the axis, simply store it in a variable and set this variable to the input only if the bool is true.

```
    bool DoInputs = true;
    float AxisH;
    IEnumerator Dash() {
      if (DoInputs)
              AxisH = player.GetAxis("Horizontal");

        if (AxisH < 0)
            {
                thePlayer.GetComponent<HeroController>().enabled = false;
                yield return new WaitForSeconds(0.5f);
                move = move * 2;
                thePlayer.GetComponent<HeroController>().enabled = true;
        }
    }
```

That will keep the character moving while not affecting it with input. Hope one of these suits your style. Cheers.

---
Tags: unity
---


title: Drawing a missile relative to the ship

text:
# Question
Title: Drawing a missile relative to the ship
I'm drawing my ship by the following code and wanted to draw a missile at the tip of the ship, so that when I click spacebar it fires that missile. I don't know if what I'm doing is correct or not. Is that the "correct" way to do the job of drawing a missile then firing it by a space bar? or there is a "better" way? Is the transformation correct here, I mean writing hard coded values and just stick the missile at the tip of the ship by trial and error?

```
void Ship::Draw( )
{

    gl::pushMatrices();
    gl::translate(Vec2f(m_Pos.x,m_Pos.y));
    gl::rotate(Vec3f(0,0,m_Angle));

    gl::color(ci::Color(1,0,0));

    gl::drawLine(Vec2f(-43,-52),Vec2f(59,1));
    m_Bullet.Draw(59,-8);
    gl::drawLine(Vec2f(-14,-34),Vec2f(-14,38));
    gl::drawLine(Vec2f(59,1),Vec2f(-43,54));
    gl::popMatrices();

}
void Bullet::Draw(int x, int y)
{
    gl::pushMatrices();
    gl::translate(x,y);
    gl::drawSolidRect(Rectf(0,0,16,16));
    gl::popMatrices();
}

```

# Answer
> 0 votes
I am not certain if I exactly understand this question, and I do not know OpenGL. That being said, my interpretetion here is that you are trying to draw the missile dependant on the ship's position, similarely to determining where to create a bullet object from a gun, when it is not directly in its center, and is offset either a direct amount from the center on one axis, or on both. (further changing this when set object rotates).

First, I am personally a fan using variables over hard-coded (magic, perhaps) numbers. First, allows easier modification if you change it, and, well, I think might be easier to work with, but your choice. For exampple, let's say each logic frame, you incriment the ship's position. If you suddenly decide to change the speed from, say, 3 to 4, using hard-coded numbers you need to change all of them. Or, you could have them all use speed, and just change the value of speed. This might be useful if said variables change during runtime, something which hard coded numbers cannot, but perhaps a runtime transformation works just as well.

As per positioning it, I know you can find the translation on each axis given a speed and direction, where the speed is length of the hypothesis and direction is an angle, where you can then use trigenometry to determine the actual incriments. Using this, you could, say, find a point relative from the ship where you want the missile, and position it accordingly.

Is this what you were looking for?

# Answer
> 0 votes
To get the position, assume you have a vec3 that hold the position of the ship. All what you have to do is to set the position of the bullet to that vec3 of the player.

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


# Question
Title: Reference keyboard keys as "justPressed", "pressed", and "justReleased" with SDL in C++
I'm teaching myself 3D graphics with OpenGL and SDL in C++. I'm at a point where I need to be able to query states of individual keys, like so:

```
if (InputManager::justPressed(SDLK_UP)) {}
if (InputManager::pressed(SDLK_UP)) {}
if (InputManager::justReleased(SDLK_UP) {}

```

I'm not sure if I should be using SDL\_GetKeyboardState or bool arrays for SDL\_Keycode/SDL\_Scancode, using states seems to me to be the more correct way. I've implemented this previously using states in C# with XNA (see that here). But I've been unsuccessful trying to replicate that with SDL.

**Method 1 - Using SDL\_GetKeyboardState**

```
// InputManager stores
Uint8* _curKeys, _oldKeys;

void InputManager::init() {
    _curKeys = SDL_GetKeyboardState(NULL);
    _oldKeys = new Uint8[sizeof(_curKeys)/sizeof(Uint8)];
}

void InputManager::update() {
    memcpy(_oldKeys, _curKeys, sizeof(_curKeys)/sizeof(Uint8)); // this seems to work
    std::copy(std::begin(_curKeys), std::end(_oldKeys), std::begin(_curKeys));
}

bool InputManager::pressed(SDL_Keycode code) {
    return _curKeys[code];
}

bool InputManager::justPressed(SDL_Keycode code) {
    return _curKeys[code] && !_oldKeys[code];
}

bool InputManager::justReleased(SDL_Keycode code) {
    return !_curKeys[code] && _oldKeys[code];
}

```

In the main loop I update the InputManager instance by copying the current keyboard state and updating the current state. Since I'm relatively new to C++ I'm unsure of exactly the best way to copy the values from \_curKeys to \_oldKeys without using a for-loop. I can't just set \_oldKeys=\_curKeys because that just makes \_oldKeys point to \_curKeys. But memcpy seemed to work.

With this implementation justReleased is constantly true, no matter what key is pressed, and justPressed and pressed are always false.

**Method 2 -Array of bools**

```
// SDL_PollEvent() loop
case SDL_KEYDOWN: InputManager::keyDown(//event keycode);
case SDL_KEYUP: InputManager::keyUp(//event keycode);

```

The keyDown and keyUp functions just set keyArray\[keycode\] to true and false. In the InputManager update function I once again duplicate of the array, simulating "states". But with this implementation all three functions are always false.

**Anyway**

I hope that this question wasn't too incoherent, I tried to explain it as best as I could. I've found some forums where people had similar problems, the criticism always was that this kind of functionality isn't needed. I would disagree, a good use case for this would be, for example, a charge-up weapon in a game. At justPressed you start the charge, increment a charge counter while pressed is true, and at justReleased you fire the weapon.

If anyone has any pointers for me (no pun intended :P) that would be awesome.

# Answer
`sizeof(_curKeys)/sizeof(Uint8)` does not give you the size of the array, because it's just a pointer from compiler's point of view.

Instead of passing NULL as an argument to `SDL_GetKeyboardState();`, pass a pointer to an integer and the function will write the length of the array to that integer. See documentation. Use that value for both allocating \_oldKeys and memcpying the data.
> 2 votes

---
Tags: opengl, c++, sdl, input, keyboard
---


# Question
Title: Mouse position to grid position not working
I have a function which converts my mouse position to grid position in the game but it is not working properly... its slightly off.

I have two functions - one which converts from grid to screen position (this particular one, works fine) and the code is:

```
function mapToScreen(gridX,gridY,screen) {
    var grid = 64;
    var x  = (gridX - gridY) * (grid/2);
        x -= screen.offsetX; //camera scroll offset X axis
        x -= grid/2; //centre of the iso tile on X axis

    var y = (gridX + gridY) * (grid/4);
        y -= screen.offsetY; //camera scroll offset Y axis
        y -= grid/4; //centre of the iso tile on Y axis
    return [x,y];
}

```

So my function to do the opposite looks like this:

```
function screenToMap(pixelX,pixelY,screen) {
    var grid = 64;
    pixelX += screen.offsetX;
    pixelX += grid/2;
    pixelY += screen.offsetY;
    pixelY += grid/4;

    var gridX = Math.floor((pixelX / (grid/2)  + pixelY / (grid/4)) /2);
    var gridY = Math.floor((pixelY / (grid/4)  -(pixelX / (grid/2))) /2);

    return [gridX, gridY];
}

```

The problem is as shown below in the image, it doesn't return the correct number. The first corner tile should be `[0,0]`.

Also notice the co-ordinate doesn't change correctly with the tile border. I don't know how to solve that either.

# Answer
Did some testing and I think your only mistake is in adding the offsets rather than subtracting them. Other than that it's been working for me, although you could simplify those equations quite a bit to get rid of all those divisions.

---

While trying, I've written this example code on JSFiddle. I omitted drawing the grid, but you should see a moving "tile" when moving your cursor over the screen rectangle.

**Here are my conversion functions:**

*From screen to grid:*

```
var grid_x = Math.floor((screen_x - offset_x + 2 * (screen_y - offset_y)) / grid) + 2;
var grid_y = Math.floor((2 * (screen_y - offset_y) - (screen_x - offset_x)) / grid) + 1;

```

*From grid to screen:*

```
var tile_x = (grid_x - grid_y - 2) * grid / 2 + offset_x;
var tile_y = (grid_x + grid_y - 4) * grid / 4 + offset_y;

```

The actual offsets might need some adjustment, based on how you'd like to originate your tiles etc.

As a bonus, I've left your own screen to grid conversion in there, so just uncomment it to see it working (all I did was subtracting offsets rather than adding them up). Although keep in mind the offsets aren't 100% correct when using your formula in the example.
> 2 votes

---
Tags: javascript, camera, isometric, coordinates, mouse
---


# Question
Title: How can I create a large space background that repeats, in an unnoticeable way
How can I create a large space background that repeats for an rts game. I want to have complex nebulae and dust fields also, but since the units will have lots of space to explore I can't have a 120000px by 1200000px jpeg, so I want to have the image repeat, but not have change lines between segments.

I'm using this with Babylon framework by Microsoft for web GL canvas

# Answer
> 19 votes
1. Use parallax scrolling. Have multiple background layers which scroll with different fractions of the speed of the main viewpoint. The lower the layer, the slower it scrolls. This isn't just a great way to provide an illusion of depth, it also makes the backgrounds look less repetitive because the objects on the different layers will appear in different compositions due to the layers not being in sync.
2. create your backgrounds procedurally. Instead of one huge background graphic, have multiple different smaller elements and place all of them multiple times randomly all over the game world.

And by the way: Don't use JPEG when you can avoid it. It's a lossy format which loses more quality every time you modify and save it, it is heavily optimized for photography and doesn't support transparency. Use a lossless format with alpha channel like PNG. The only good reason would be when your source image is only available in JPEG (NASA published a lot of nice astronomy pictures which are all in the public domain) and you want to do no modification whatsoever on them.

# Answer
> 7 votes
A way to build an infinite background for a 2D game is the following:

1. Using a graphics editor software (like iDraw for Mac) create an image **A** that represents a portion of your background. This image should have a limited size.
2. Duplicate A and mirror it on the Y axis, this is **B**
3. Now paste (horizontally) togheter A and B, this is **AB**.
4. Finally import the image **AB** in your game and repeat it horizontally via code as many times as you want.

Hope this helps.

# Answer
> 5 votes
Layers work well.

Here's some maths:

Suppose you have a railway track that's been poorly made such that the like `__ __` notice the gap between them. When the wheel rolls over them it makes a small notch (tiny notch).

If the track length is `l` and the wheel has radius `r` then `2pi r` is the circumfrence of the wheel, `ration=l/(2pi r)` if the ratio is say 10.25 then the wheel will get a notch in it every quarter as it rides a long.

This is the easiest way I can think of to explain covering spaces.

So suppose you have two images, if one has this quarter ratio you'll get a 4-phase pattern, it'll repeat after 4 tiles. Suppose you have 1 main background and 2 overlays, with m and n phases. Then the pattern will repeat after m\*n tiles.

While it wont matter much the pattern will look best if the numbers are co-prime, that is the greatest common divisor is 1. For example suppose we have something of phase 6 and something of phase 4, every other phase these will "line up" in a sense.

You can use this technique (especially with particles and stuff) to create a lot of "unique" stuff with very little effort.

Back to the train wheel, if the ratio is irrational, then the notches will cover the the wheel! But this doesn't really matter.

# Answer
> 5 votes
Here is another idea which seems to be missing:

In case of long distance backgrounds, like sky boxes, Parallax layers doesn't really feel good. Think of the stars for example, when walking on earth, or even better through out the night, all the stars move together, though we know they are hundreds or thoughts light year away from each other. The thing is they are way too far away for us to notice their distances. All that said we still want a very big texture (say 120k\*120k), to be drawn with our limited computational power (which can handle 8k\*8k at most). Like using multiple parallax layers, you should create different textures, each with different kinds of details. For example one represents galaxies, another one is a bunch of stars, etc. But this time instead of moving them with different speeds, they should differ in their sizes. Here is an example: Consider using 3 textures, one is 2048\*2048, another one is 729\*729 and the third one is 625\*625. Since these numbers are coprime with each other, When combining these 3 textures in 3 layers, one should move lcm(2048,729,625) = 764M pixels from the origin to see same thing being drawn, which kinda feels like infinity. In fact you can add other layers or change size of each texture and you'll always end up with a result as big as least common multiple of texture sizes.

# Answer
> 4 votes
This seems to be a job for a procedural pixel shader.

The advantages over using an image are:

* You don't need to provide huge bitmaps
* It is procedural, so it doesn't have to repeat a fixed image (it can vary infinitely)
* If you want a paralax effect, you can simulate thousands of planes, which would be impractical using images
* You can do very advance effects, like dynamic lighting
* Most of the processing is made by your GPU, leaving the CPU free for other parts of your game

A simple web search bring this shader up http://casual-effects.blogspot.com.au/2013/08/starfield-shader.html which looks like what you're looking for.

I'm not an expert on WebGL, but according to this page, it looks like it uses the regular GLSL language (this is the C-Like language used by graphic cards to program shaders). This means you will probably have little to no changes to do to make it work.

You may however try to start with a more basic shader to understand how it works.

This blog page lists all the steps to implement a shader in WebGL. That seems a good place to start.

Another good place to find wonderful shader examples is https://www.shadertoy.com/

# Answer
> 2 votes
You can cut your big jpeg in a small segments and place them (visible part) , you don't even need store it in a memory all the time.

And like a old games some 'tiles' can repeat. Thats was common solution for NES console, thats was even supported by hardware.

---
Tags: image
---


# Question
Title: Is it possible to store diffuse and normal maps in the same texture area and preserve SRGB/linear space?
Usually, one would want to upload texture data to OpenGL with `GL_SRGB*` for the *`internalformat`* of a texture, and `GL_RGB*` (or some other linear format) for normal data or specular highlight maps. We can minimize context switches by using a texture array, but that forces *all* textures to have the same *`internalformat`*. Is there a way to store all needed textures in a single texture array, but preserve colour spaces? Or should I convert from SRGB to linear space when uploading texture data?

# Answer
I think the only way to achieve this is by building a texture array and then using a *view* into the array, casting into a different *`internalformat`*.
> 0 votes

---
Tags: opengl, color, srgb
---


# Question
Title: Unity access method from separate script
I'm learning Unity3D and I'm practising accessing game object scripts from other objects. For the most part I've got it down, but I've run into a weird issue causing a NullPointerException.

I've set up a GameObject, with the following script attached to it:

```
using UnityEngine;
using System.Collections;

public class PlayerController : MonoBehaviour {
public Player[] players;

// Use this for initialization
void Start () {
    players [0].currentPosition = 0;
    players [1].currentPosition = 1;
    players [2].currentPosition = 2;
}

// Update is called once per frame
void Update () {
    foreach(Player p in players)
    {
        if(p.mFormationType == Player.FORMATIONTYPE.ATTACK)
            p.transform.position = p.attackPositions[p.currentPosition];
        else
            p.transform.position = p.defensivePositions[p.currentPosition];
    }
}

public void swapPositions(Player selected)
{
    Debug.Log (selected.currentPosition);
    if(selected == null)
        Debug.Log("Balls - " + selected.gameObject);

    if(selected.currentPosition != 0)
    {
        int previousPos = selected.currentPosition;

        players[0].GetComponent<Player>().currentPosition = previousPos;
        selected.currentPosition = 0;
    }
}
}

```

And I've set the Player objects within the UI. I then later attempt to do this when I click on one of the Player objects:

```
void OnMouseOver()
{
    if(this.currentPosition == 0)
        return;

    if(Input.GetMouseButtonDown(0))
    {
        PlayerController pc = this.controller.GetComponent<PlayerController> ();
        pc.swapPositions (this);
    }
}

```

But it results in an NPE within the `swapPositions` method in the PlayerController class, when it attempts to access players\[...\]

I've stepped through and at the start of the PlayerController script they're all there and set up perfectly, but later on, they're null.

Can anyone explain why this is happening please?

Thanks in advance.

# Answer
I don't know if it will help anyone or not, but I managed to get this working. I attached my controller script to the main camera and now access the script like so:

```
Camera.main.GetComponent<PlayerController>().swapPositions(this);

```

...from within my Player object scripts.

Many thanks for all the help!
> 0 votes

# Answer
I think instead of players\[0\].GetComponent().currentPosition, you should just use it players\[0\].currentPosition
> 0 votes

---
Tags: unity, unityscript
---


title: In-Depth Lockstep Explanation

text:
# Question
Title: In-Depth Lockstep Explanation
I'm making a multiplayer game built upon a lockstep system and I'd just like a better grasp on the concept. My main question is on how to get every command to simulate at the same time on every client, or rather, on the same points in each client's timeline. I'm using a fixed update of 10 frames per second for simulating every object's position from movement commands (Click and move style) the same way. How do I tell all clients to execute all commands at the same relative time to the first command? Note I'm using Unity3D and a sufficiently accurate physics implementation. I just need to get across every command at the correct time.

# Answer
You need to have a future command queue that will only be acted upon once all parties will have confirmed reception of the command.

This queue will include no-operation null commands if no new command is to be executed.

The delay for each command can be dependent on the ping/lag.

The simulation on every peer only executes to the point (call it frame number, time, or step) where all commands have been confirmed as received so every peer will execute the same thing at the same time.

So let's say the step granularity is every 100ms, got a 175ms max network ping, we're at 332ms, the user click to move a unit, we send a packet "#N: unit A move to XY at 600ms" (332 rounded up to 400ms + rounded up ping to 200ms).

So long as a reply from all peers comes in saying "Packet #N Confirmed" before game time 600ms the game wont need to wait, if we don't receive confirmation we hold the game simulation and we resend the command packet every N ms (don't flood the network) until we get confirmation.

We also need to receive command packets from all peers for all steps, even if there are no commands send a no-command sync packet eg: "Nothing to do at 700ms".

"Confirmation of the confirmation" is simply the next command packet which is only sent if the peer has received confirmation of its previous packet, it will resend its previous command if no confirmation arrives until it gets a confirmation (or a time out and the connection is considered lost).

Confirmation can be sent as part of the next command packet to reduce traffic by increasing the queue to 2 commands with half the time (same lag overall, half the packets).

From there a lot can be added such as variable lag/ping detection/adjustments, prediction and rollbacks, etc, to reduce the perceived network lag.
> 4 votes

---
Tags: unity, networking, multiplayer, rts, synchronization
---


# Question
Title: give a prefab clones a script from another prefab in Unity3d
I have the following :

TurretBallmanager :

```
using UnityEngine;
using System.Collections;

public class TurretBallManager : MonoBehaviour {

// Use this for initialization
public GameObject BallPrefab;
public GameObject TurretPrefab;
public static TurretBallManager instance;
public int turretSpawnTime=35;
public int LastTurretTime=0;
Vector2 v;
void Start () {
    instance = this;
    v = new Vector2(TurretPrefab.transform.position.x,TurretPrefab.transform.position.y);
}

// Update is called once per frame
void Update () {
    if (Time.time > LastTurretTime + turretSpawnTime) {
        GameObject T = Instantiate(TurretPrefab,v,Quaternion.identity) as GameObject;
        //T.AddComponent<Turret>();
        v.x=T.transform.position.x+2;
    }
  }
}

```

Turret class :

```
using UnityEngine;
using System.Collections;

public class Turret : MonoBehaviour {

// Use this for initialization
double LastBallTime=0.0;
double LastTurretTime=0.0;
public decimal spawnballTime=1.5;
Vector2 v ;
void Start () {

}

// Update is called once per frame
void Update () {
    if (Time.time > LastBallTime + spawnballTime) {
        LastBallTime=Time.time;
        Debug.Log (transform.position);
        GameObject B = Instantiate(TurretBallManager.instance.BallPrefab, transform.position, transform.rotation) as GameObject;
        //B.AddComponent<Ball>();
    }

  }
}

```

Ball class :

```
using UnityEngine;
using System.Collections;

public class Ball : MonoBehaviour {

// Use this for initialization
void Start () {

}
void OnMouseDown() {
    Object.Destroy (gameObject);
}
// Update is called once per frame
void Update () {

}

void OnBecameInvisible ()
{
    Debug.Log ("destroyed");
    Destroy(gameObject);
}
}

```

I have a turret wish fire a ball every 1 sec ,the ball is a prefab wish have the Ball class ( when the ball is out of bounds or is touched it should be destroyed ) what i'm trying to do is creating a another turret every `35 sec` wish also should fire a ball every 1 sec .. what i am facing is the fallowing problem :

1. the turret is being created after `35 sec` but it's ball are not implementing the `ball script` and they are not being destroyed
2. An overflow is occurring due to the number of balls created and the whole project is freezing

* Image 1 : as soon as the game begin
* Image 2 : When 35 seconds ends
* Image 3 : you can see that millions of turrets are created at the same time as soon as 35 sec ends

The `turretballmanager` is a class given for the Maincamera

# Answer
`// Update is called once per frame`

Your timer is never being reset. This means that after the soon as your spawning condition is satisfied: `if (Time.time > LastTurretTime + turretSpawnTime)`, your program will continue to spawn turrets every time `Update()` is called. You appear to have a better approach in your ball spawner.

You could update the `LastTurretTime` like so:

```
 if (Time.time > LastTurretTime + turretSpawnTime) {
        LastTurretTime = Time.time;
        GameObject T = Instantiate(TurretPrefab,v,Quaternion.identity) as GameObject;
        //T.AddComponent<Turret>();
        v.x=T.transform.position.x+2;
    }

```
> 0 votes

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