# Question
Title: Algorithm to draw particles in correct order?
For a game I'm making as a hobbyist project, I need to be able to draw smoke on the screen. I am doing this by setting up a particle system. The problem is I need all the particles drawn in order from farthest to nearest to the camera (because the particles do have a bit of transparency, and the entire texture transparency increases over time in the particles) and I cannot figure out a way to successfully do it. Here is the code that draws each of the particles, along with the code that that is supposed to determine what order to draw them in so that it draws them from furthest from the camera to nearest to it:

```
    void drawSmoke( Camera cam ) {

      int drawOrder [50];

    bool particleChecked [50] = {false};

    for ( int a = 0; a < 50; a++ ) {

    int furthest;
    float furthestDistance = 0;

        for( int check = 0; check < 50; check++){

                if ( !particleChecked [check] ) {

                float aSquared = ( cam.getPosition().x - smokeParticles[check].position.x ) * ( cam.getPosition().x - smokeParticles[check].position.x );
                float bSquared = ( cam.getPosition().z - smokeParticles[check].position.z ) * ( cam.getPosition().z - smokeParticles[check].position.z );
                float cSquared = aSquared + bSquared;

                float distanceFromCamera = sqrt ( cSquared );

                        if ( distanceFromCamera > furthestDistance ) {
                        furthest = check;
                        furthestDistance = distanceFromCamera;
                        }

                }

        }

        drawOrder [a] = furthest;

    }

GLuint transformLocation = glGetUniformLocation ( particleProgram, "transform" );
GLuint alphaLocation = glGetUniformLocation ( particleProgram, "alpha" );

for( int particle = 0; particle < 50; particle++ ) {
glm::mat4 model;
glm::mat4 view;
glm::mat4 projection;

int particleToDraw = drawOrder [particle];

model = glm::translate( model, glm::vec3 ( smokeParticles [particleToDraw].position.x, smokeParticles [particleToDraw].position.y + 10.0f, smokeParticles [particleToDraw].position.z ) );
model = glm::scale(model, glm::vec3 ( smokeParticles [particleToDraw].scaleFactor ) );
glm::vec3 diff = glm::normalize ( smokeParticles[particleToDraw].position - cam.getPosition() );
float angle = atan2 ( -diff.x, -diff.z );
model = glm::rotate ( model, smokeParticles[particleToDraw].rotation , glm::rotate ( glm::vec3(0.0f, 0.0f, 1.0f), angle, glm::vec3(0.0f, 1.0f, 0.0f) ) );

//rotating particle to face camera
model = glm::rotate(model, angle, glm::vec3(0.0f, 1.0f, 0.0f));

view = glm::lookAt(cam.getPosition(), cam.getTarget(), glm::vec3(0.0f, 1.0f, 0.0f));

projection = glm::perspective( 45.0f, (float)800/(float)600, 0.1f, 5000.0f );

glm::mat4 transform = projection * view * model;

glActiveTexture( GL_TEXTURE0 );
glBindTexture( GL_TEXTURE_2D, smokeTexture );
glUseProgram( particleProgram );
glUniformMatrix4fv( transformLocation, 1, false, glm::value_ptr(transform) );
glUniform1f( alphaLocation, smokeParticles[particleToDraw].alpha );
glBindVertexArray( smokeVAO );
glDrawArrays( GL_TRIANGLES, 0, 6 );
glBindVertexArray(0);
    }

```

What it looks like is on each frame every element of drawOrder is the same value. But I cannot figure out why. How can I fix this?

# Answer
> 0 votes
Although I'm not fluent in C++ or OpenGL, there are a number of issues with this code from what I can tell. I'll describe them on a high level, and leave this answer as a community wiki, in case anyone with more specific expertise would like to refine it with specific code suggestions.

1. Your sort function, even if implemented correctly, would be O(n^2). Because you never assign the particleChecked\[\] flags though, it ends up assigning the single furthest particle to the drawOrder array 50 times - so it does not sort the list of particles.

For a common task like this, I'd recommend using a standard library sorting function, which should give you a battle-tested O(n log n) solution, rather than trying to re-invent the wheel.
2. You compute distances, complete with square roots, 2500 times. To cut down on repeated work, you can store just 50 depths - each in a tuple with its particle/index, or in a parallel array - before you start sorting.

Since you only need a relative order, not a precise distance, you can skip the square roots. Or you could replace the distance calculation with a dot product of the particle's position with the camera's forward vector, which is better-suited to billboarded particles.
3. As mentioned in a comment above, you're issuing a separate draw instruction for each particle. To scale up to large volumes of particles, you'll likely want to build a vertex buffer containing all of the particles in your sorted order, and draw them as a single batch. You can use vertex colours to control the alpha of each particle so you don't need to change uniforms for every particle.

---
Tags: opengl, c++, particles, glm
---


# Question
Title: Differences between particles and using shader in creating effects
I'm working with particles and little bit with shader. Both of them can do the same task like creating effects of flame, snow, glowing ...

So which one is better and what are differences between them?

# Answer
**This will depend a lot on the specific effect you're trying to achieve**.

As one example, here's a pair of fire effects created by Edward del Villar. The one on the left uses particles, while the one on the right is a LineRenderer with a custom shader:

Because the version on the right is rendering on a continuous ribbon of geometry provided by the LineRenderer, it's able to bend and swish fluidly, while the particle solution visibly breaks up in motion, revealing the individual cards that make it up.

A particle system can be made more fluid/continuous by increasing the number of particles, but this can quickly eat into the fillrate available for the frame (drawing & blending over the same pixel multiple times instead of only once). This is especially concerning on mobile devices, so if you can make a shader that gives a similar effect in just one pass, it will often be faster (as long as the shader itself isn't too heavy)

But, the discrete particles also make it easier to make a chunky/cartoony stylized look to the flames, or create complex motion like swirling vortices and turbulence or sparks bouncing off walls. So if those aspects are important to your game's visual direction, particles could be a better choice.

Like everything in game development, there are many ways to achieve an effect, so with enough time investment we could probably give more fluid motion to the particle version, or more chunky art direction or complex animation to the shader version. More often than not, it will come down to which style makes it easier to get the effect you want quickly & reliably, since there are so many other features to work on. ;)

---

Finally, it's important to remember that **these two tools aren't mutually exclusive**, and you can often make spectacular effects by rendering custom shaders on particles themselves, on accompanying geometry, or in post-process effects on top of the particles, to compliment and enhance the visuals.

Check out this presentation on VFX used in Infamous Second Son for lots of inspirations for how shaders and particles can act in concert for beautiful results.
> 5 votes

---
Tags: shaders, particles, graphic-effects
---


title: OpenGL ES black screen

text:
# Question
Title: OpenGL ES black screen
I am a beginner to drawing with OpenGL ES and I have a problem. I am drawing a figure consisting of triangles in orthographic projection, but when I run my app, I see a black screen and system buttons only (I am using a real device and not an emulator).

Why do I get a black screen, and how could I fix it?

I am using OpenGL ES 1.0 version.

Initialization before drawing:

```
float[] verticesArray = new float[] {
        180.0f, 80.0f, 10.0f,
        260.0f, 80.0f, 10.0f,
        318.0f, 138.0f, 10.0f,

        260.0f, 80.0f, 10.0f,
        318.0f, 138.0f, 10.0f,
        318.0f, 216.0f, 10.0f,

        318.0f, 138.0f, 10.0f,
        318.0f, 216.0f, 10.0f,
        260.0f, 264.0f, 10.0f,

        318.0f, 216.0f, 10.0f,
        260.0f, 264.0f, 10.0f,
        180.0f, 264.0f, 10.0f,

        260.0f, 264.0f, 10.0f,
        180.0f, 264.0f, 10.0f,
        122.0f, 216.0f, 10.0f,

        180.0f, 264.0f, 10.0f,
        122.0f, 216.0f, 10.0f,
        122.0f, 138.0f, 10.0f,

        122.0f, 216.0f, 10.0f,
        122.0f, 138.0f, 10.0f,
        180.0f, 80.0f, 10.0f,

        122.0f, 138.0f, 10.0f,
        180.0f, 80.0f, 10.0f,
        260.0f, 80.0f, 10.0f
};
verticesAmountTotal = verticesArray.length/3;
coordsOfVerticesAmountTotal = verticesArray.length;

ByteBuffer byteBuffer = ByteBuffer.allocateDirect(coordsOfVerticesAmountTotal * 4);
byteBuffer.order(ByteOrder.nativeOrder());
vertices = byteBuffer.asFloatBuffer();
vertices.put(verticesArray);
vertices.flip();

```

Drawing method:

```
gl.glViewport(0, 0, glGraphics.getWidth(), glGraphics.getHeight());
gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
gl.glMatrixMode(GL10.GL_PROJECTION);
gl.glLoadIdentity();
gl.glOrthof(0, 480, 0, 320, 30, -1);
gl.glColor4f((float)Math.random(), (float)Math.random(), (float)Math.random(), opacity);
gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
gl.glVertexPointer(3, GL10.GL_FLOAT, 0, vertices);
gl.glDrawArrays(GL10.GL_TRIANGLES, 0, verticesAmountTotal);

```

# Answer
> 1 votes
I don't see anything obviously wrong with your code, but here are some possible things you can look at:

1. Is your call to `glViewport()` getting the values you think it is?
2. What is your clear color set to? If you set it to something like yellow, do you see anything else?
3. What is `opacity` set to?
4. Does Math.random() default to 0 if you don't seed it? If so, are you seeding it?
5. Is the vertex array getting set up before drawing?

Have you tried adding any calls to `glGetError()` to see if anything is going wrong? That might give you a clue as to what's happening.

---
Tags: java, android, opengl-es
---


title: Phaser Tiled map importing

text:
# Question
Title: Phaser Tiled map importing
How can I be sure that the tileset used in making a Tiled map remains as a multiple of 2, since this is a requirement of phaser when loading JSON tiled maps? I have tileset images which I got for free and they are not exactly up to phaser specs to be used.

# Answer
You're probably referring to this:

```
    // May be fractional values
    var rowCount = (imageHeight - this.tileMargin * 2 + this.tileSpacing) / (this.tileHeight + this.tileSpacing);
    var colCount = (imageWidth - this.tileMargin * 2 + this.tileSpacing) / (this.tileWidth + this.tileSpacing);

    if (rowCount % 1 !== 0 || colCount % 1 !== 0)
    {
        console.warn("Phaser.Tileset - " + this.name + " image tile area is not an even multiple of tile size");
    }

```

So for example, if your tile size was 32x32 and your tileset image was 64x64, that's ok (32 divides into 64), but if the tileset image was 65x65, that's 1px left over and 65 doesn't divide evenly into 32.
> 0 votes

---
Tags: html5, phaser, tiled
---


# Question
Title: TiledMap taking a lot of time to load in libgdx
I am developing a game using `libGdx` in which a level has 2400 * 450 tiles Map and each tile is of 4 pixels. I am also using `box2d` in my game.

My problem is that when I run the game on my phone it takes a lot of time to load the screen (more than a minute). How can I reduce this loading time?

I created tilemap using `Tiled` and I am using `Android Studio`.

Below is my code (SCALE is 2.0f and PPM is 4)

```
@Override
public void show() {
    w = Gdx.graphics.getWidth();
    h = Gdx.graphics.getHeight();

    camera = new OrthographicCamera();
    camera.setToOrtho(false, w / SCALE, h / SCALE);
    camera.update();
    viewport = new FitViewport(w / SCALE, h / SCALE  ,camera);
    viewport.apply();
  .
  .
  .

    map = new TmxMapLoader().load("maps/lvl3.tmx");
    tmr = new OrthogonalTiledMapRenderer(map, 1/SCALE);

}

@Override
public void render(float delta) {
    update(Gdx.graphics.getDeltaTime());

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

    tmr.render();

    .
    .
    .
    b2dr.render(world, camera.combined.scl(PPM));
}

public void update(float delta) {

    world.step(1 / 60f, 6, 2);
    cameraUpdate(delta);
    tmr.setView(camera);
    batch.setProjectionMatrix(camera.combined);
}

@Override
public void resize(int width, int height) {
    camera.setToOrtho(false, width / SCALE, height / SCALE);

    viewport.update( width , height );
}

```

Please help and thanks in advance

# Answer
> 1 votes
I solved the problem by reducing the tiles in a map and increased individual tile size (from 4 * 4 pixel to 64 \*64 pixels)

Moreover i used Asset manager to load the tiles . Thanx @Charanor

Now it completely smooth and takes very less time to load.

---
Tags: android, libgdx, tiles, tilemap
---


# Question
Title: Rendering multiple strings/text using SpriteBatch from LibGDx library
I am using the LibGDX library to render a 3D model in my Android application. Now, I am stuck, where I want to render multiple dynamic texts on to different 3D boxes located on different coordinates of the screen. I am able to render a single text using `SpriteBatch`, but I need to render different string values on different boxes.

```
SpriteBatch spriteBatch = new SpriteBatch();
BitmapFont font = new BitmapFont();
spriteBatch.maxSpritesInBatch = 5;

spriteBatch.setProjectionMatrix(camera.combined.cpy().scale(camera.combined.cpy()
    .getScaleX()/25,camera.combined.cpy().getScaleY()/25, 0.8f));

spriteBatch.begin();

font.setColor(1.0f, 0.0f, 0.0f, 1.0f);
float xPos = -90;
int count = 0;

for (Widget widgets : display.getWidgets())
{
    float boxWidth = widgets.getBounds().getWidth();
    float boxHeight = widgets.getBounds().getHeight();
    float boxHeightCenter = widgets.getBounds().getCenterY();

    if(count==0)
    {
        font.draw(spriteBatch, "Hello"+count, xPos, boxHeightCenter-25,
            boxWidth, 0, true);
        ++count;
    }
    else
    {
        font.draw(spriteBatch, "Hello"+count, xPos+boxWidth, boxHeightCenter-25,
            boxWidth, 0, true);
        xPos = xPos+boxWidth;
        ++count;
    }
}

spriteBatch.end();`

```

The above code renders only one string value. While debugging, the "for" loop is getting traversed, but no positive result is obtained. How do I fix this?

# Answer
> 0 votes
Initially i was not able to render multiple texts based on the number of nodes present in model. I wanted to render multiple text at different position so I achieved with this code. There was no error, but I was not able to achieve what I wanted i.e. rendering multiple text.

```
for (Widget widgets: display.getWidgets()) {

    for (int i = 0; i < widgets.nodes.size; i++) {

        Node node = widgets.nodes.get(i);
        if (node.id.equalsIgnoreCase("Camera") || node.id.equalsIgnoreCase("lamp")) {
        }
        else {
            BoundingBox nodeBox = new BoundingBox();
            final Vector3 center = new Vector3();

            node.calculateBoundingBox(nodeBox);
            nodeBox.getCenter(center);
            if (count == 0) {
                font.draw(
                    spriteBatch, "Hello" + count,
                    center.x, center.y, nodeBox.getWidth() * 25, Align.center, true);

                ++count;
            }
            else {
                font.draw(
                    spriteBatch, "Hello" + count,
                    center.x, center.y, nodeBox.getWidth() * 25, Align.center, true);
                xPos = xPos + (boxWidth * 2); ++count;
            }
        }
    }
}

```

---
Tags: libgdx, spritebatch
---


# Question
Title: How to solve "server lag" problems that break the game
How do real-time multiplayer games deal with latency problems (or “server lag”)?

Imagine an online fighting game where 2 players battle head-to-head in real time. When a player performs an action, there'll be a short delay until that player's action appears on the opponent's computer screen. This delay causes many game-breaking problems.

Let's say 2 hypothetical players, Player A and Player B, are fighting against each other right now in the game, and the latency is 1 second. Player A is moving toward Player B, but then Player B places a wall (or something of the like) that stops Player A from moving toward Player B. Player A doesn’t see the wall appear on his/her computer screen until 1 second later, but by then Player A has already moved past where the wall was placed.

In a more game-breaking situation, Player B is just about to kill Player A. Right before that happens, Player A uses a special attack that instantly kills Player B. But on Player B’s computer, Player B kills Player A, because it takes 1 second before Player A’s special attack happens on Player B’s computer. This makes it so both players die even though only Player B was supposed to die.

One solution to deal with the latency issue is to implement an artificial delay so that when there’s a discrepancy, one player’s game is momentarily paused to wait for the other player’s game state to “catch up.” This is not a good solution because it makes the game feel extremely laggy and unresponsive, and it also renders some reactive actions useless (like dodging) because of the artificial delay.

What can be done to fix these latency problems?

# Answer
> 5 votes
The easiest solution to the "who did it first?" problem is an authoritative server. Both players connect to the server which handles all the game mechanics. Whatever arrives first at the server is considered as happening first.

So if the server receives a message "I place a wall" from player B and then a millisecond later a message "I move to where the wall is" from player A, the server will reject the move-message as impossible and send player A a corrected position for their character.

What then happens on the screen of player A is that their character moves at first, but then the wall appears and the character is snapped back to its position before the wall.

This method of resolving timing conflicts gives an advantage and a better game experience to those players who have a better connection to the server ("Low Ping Bastards").

A different way to resolve conflicts is to take latency into account when resolving actions. In order to do that, the server needs some way to keep a history of the game state. When the "I move to where the wall is" message arrives at the server, the server checks Player A's latency, looks into the history if a wall was already there a few milliseconds before, and decides accordingly. That means the game looks more consistent for high-pingers, but low-pingers will far more often witness situations where other players seem to walk through walls shortly after they were placed.

---
Tags: multiplayer, synchronization, lag, latency, fighting-game
---


# Question
Title: Creating a movable camera using glm::lookAt()
I came across this tutorial on how to create a movable camera in OpenGL using `glm::lookAt(glm::vec3 position, glm::vec3 target, glm::vec3 up)`. In the tutorial, in order to keep the camera always facing in one direction while moving, the view matrix is created as such: `view = glm::lookAt(cameraPos, cameraPos + cameraFront, cameraUp);`, where cameraPos, cameraFront, and cameraUp are all `glm::vec3` type.

What I would like to ask is why does the second argument have to be `cameraPos + cameraFront`? If the camera position moved to the right without changing `cameraFront`, wouldn't `cameraPos + cameraFront` have an effect of rotating to the right as opposed to staying in the same direction (which I think is what should be needed)?

# Answer
The `cameraFront` vector is defined like this:

```
glm::vec3 cameraFront = glm::vec3(0.0f, 0.0f, -1.0f);

```

or like this, later in the tutorial:

```
cameraFront = glm::normalize(front);

```

In both cases, we see that it is a unit vector, which means a vector of length 1.

In the 'world of 3d' (and 2d), when you see a unit vector, it's generally because it is a direction.

And it is the case here.

When calling

```
glm::lookAt(cameraPos, cameraPos + cameraFront, cameraUp);

```

you instruct glm to create a matrix that will look from `cameraPos`, at `cameraPos + cameraFront`, so just in front of the camera. The trick here is that you move both the position *and* target at the same time, with the same offset, as the second parameter is based on the first parameter. This is why the camera does not 'rotate', it has the effect of 'strafing' in First person shooter games.

As an analogy: take a compass in your right hand, stretch your right arm as far as you can in front of you and make sure it is align with the North.

If you look toward your right hand, you can move around, but if you always see in the same direction.

That's what is happening here: the `cameraPos` vector is represented by you, moving around, while the `cameraFront` is represented by your right arm, stretched in front of you, always in the same direction, and always of the same distance.
> 1 votes

---
Tags: opengl, glm
---


title: HeightMap from a graph

text:
# Question
Title: HeightMap from a graph
This is just a toy experiment.

I laid out a graph in 2d space, so that every node has `x` and `y` coordinates. I'm considering degree of a node as a `height value` at position `x` and `y` of a height map.

I wonder what's the best strategy to interpolate this sparse heightmap with missing values?

Ideally I'd love to have some sort of gravitational pull towards the bottom in the places where I don't have height values. Think of it like somebody dropped fabric on bunch of spikes...

# Answer
> 2 votes
# TL;DR: Use bicubic interpolation or spline interpolation.

So, you're looking for a method of two-dimensional interpolation. Unfortunately, this isn't a perfect two-dimensional grid (mathematically, it's not a lattice). We have irregularly-spaced points, and so this makes things slightly less convenient. However, we still have plenty of options:

* **Nearest-neighbor interpolation:** For each point `pi(xi,yi)`, this method takes into account the value of the nearest point to `pi`. The result is something like a two-dimensional step function. While this method can be simple, it also results in functions which are discontinuous, and so it's pretty terrible for height maps (unless you like having cliffs everywhere, in which case go for it).
* **Bilinear interpolation:** Essentially, linearly interpolate in one coordinate (say, the *x*-direction) for each "slice" of the graph. Next, interpolate in the other (orthogonal) coordinate. The result is a chunky graph of plates at odd angles. While it doesn't have the discontinuities of the nearest-neighbor method, it does lead plenty of places where the terrain isn't differentiable. In some cases, this can lead to sudden shifts in the slope of the surface - again, not great for height maps.
* **Bicubic interpolation:** This is akin to bilinear interpolation in that it extends a one-dimensional method (cubic interpolation/cubic Hermite spline) to two dimensions. You'll see some benefits here: smooth, continuously differentiable functions (unless you're dealing with an objectively *evil* set of data), which are helpful in your case. If you want, you can do this to higher degrees by just modifying polynomial interpolation to the *n*th degree. However, cubic interpolation is often fine. Lagrange polynomials (which I discussed here) are something to be familiar with if you want to implement something like this by hand.
* **Spline interpolation:** This uses higher-degree polynomials called splines, which are generally smooth. It can remove some difficulties that may arise in polynomial interpolation, such as Runge's phenomenon (basically, freaky oscillations that nobody likes). It also generally has low errors and thus high accuracy.

Here's a visual comparison of these methods:

Image courtesy of Wikipedia user Cmglee under the Creative Commons Attribution-Share Alike 4.0 International license.

You can implement these by hand, if you so desire. However, many numerics libraries have them built-in. Take Python's SciPy, for instance (I'm using Python as an example because it's what I'm most familiar with). It has several methods of interpolation which can be used without too much trouble (I just came across this Stack Overflow answer by Andras Deak, an awesome comparison of some of them):

* `scipy.interpolate.interp2d` uses spline interpolation. The default is `linear`, i.e. bilinear interpolation. However, you can also choose `cubic` (bicubic) or `quintic`, if you want, both of which should have some advantages over `linear` \- as I discussed earlier. You might see some issues arise, especially if you use the "evil function" Andras Deak took as an example. It's *possible* that you might see some problems arise here, but for a height map, you could escape with your data (and dignity) intact.
* `scipy.interpolate.griddata` can also use various methods we discussed before (nearest-neighbor, bilinear, and bicubic). This beats out `interp2d` for evil cases and is still more accurate on some other challenging functions/data sets, but again, those are *probably* not going to arise in your applications.
* That SO answer also mentions `scipy.interpolate.Rbf`. This is a good choice *if and only if you have a function whose values are dependent entirely on distance from the origin.* This is likely to not be the case for almost any height map you'd realistically want to deal with. I've used it before, and it can have some cool results, but something like bicubic interpolation is often better - at least, in my experience.

---
Tags: mathematics, interpolation, heightmap, graph
---


# Question
Title: How Many Entities can the Unity Game Engine Handle Before it Starts to Lag?
I am building a player model for my game, the model is very complicated due to its ability to be customizable. A single player entity can have 70 + entities including the head, parts to the face, arms, legs, shoes, and the clothes and armor it wears, and the weapons it has equipped. I just need to know, at what point does the unity game engine start lagging due to too many entities? Also, the game is low poly, there are many entities, but each one is block based, or very simple in design.

# Answer
You can't generalize that because the resources consumed by an entity (CPU, system-memory, bus bandwidth, GPU and GPU-memory) vary greatly depending on their components. Do they have colliders? Do they have renderers, and if yes how complex are their meshes and their shaders? Do they have scripts? Do they have rigidbodies? Are they animated? All that (and many more) affects how much an entity taxes the engine.

Also, different target platforms have different resource capabilities. When you are targeting smartphones you won't be able to do as much as you would be able when you are targeting gaming PCs.

But keep in mind that you might be able to reduce the number of game objects by modifying meshes at runtime (which is useful for things like face customization) and merging meshes (which allows you to combine multiple objects into one object with one mesh).
> 3 votes

---
Tags: unity, lag, 3d-modeling
---


# Question
Title: How can I create a lightning attack similar to Agahnim's in Legend of Zelda: Link to the Past?
I'm currently trying to recreate this attack, and I'm unsure of how it works.

It seems like the boss creates 4 lightning bolts which move downward at 45 degree/diagonal angles, changing direction every so often.

I'm building my game in Zelda Classic. I'd preferably like to know how to do this in C++, although I am fine with Java or anything C++/C-like.

# Answer
> 3 votes
This looks to me like a Random Walk (image from Wikipedia):

1. Seed each lightning bolt with a start point (the orb in the enemy's hands)
2. Each step, the bolt's leading point moves down one unit, and with 50/50 probability moves either one unit left or one unit right, drawing a line between its previous & new positions.

(You can choose the size of the units yourself, or measure them from the frames of the original game if you want pixel-for-pixel fidelity)
3. You can advance each bolt one step per frame, or loop through n steps if you want the bolt to advance more quickly.
4. Once the bolt reaches the bottom of the screen, it's complete.

You can store up all the positions it's raced through along the way in an array to do collision checks (it may suffice to skip between every nth point to simplify your checks), and to re-draw the bolts in varying colours on subsequent frames to get the strobing effect.

To wipe the bolts, you start drawing from further and further down the array on subsequent frames, leaving the top part of the bolt un-drawn, until it's completely hidden.

---
Tags: c++
---


# Question
Title: How to import .obj file from server without using asset bundle in unity3d
I want to import .obj file from a server on run time in unity3D, read lot of questions/answers but not able to find a suitable solution. Using WWW in unity I am able to get .png file and store it in local repository but this thing not works for .obj file. Following is the code I used to get image from server

```
public string url = "http://images.earthcam.com/ec_metros/ourcams/fridays.jpg";
    IEnumerator Start() {
        WWW www = new WWW(url);

        while (!www.isDone)
            yield return www;

        if (www.isDone)
            Debug.LogError ("Done");

        File.WriteAllBytes("C:\\Users\\Admin\\Downloads\\conan\\test1.jpg", www.bytes);
    }

```

ans similarly I tried to get .obj file but it not works test .obj file created but without any data

```
public string url = "https://drive.google.com/open?id=0B5_UUyYa_2XdZUpuNlE4Z3pqWUk";
    IEnumerator Start() {
        WWW www = new WWW(url);

        while (!www.isDone)
            yield return www;

        if (www.isDone)
            Debug.LogError ("Done");

        File.WriteAllBytes("C:\\Users\\Admin\\Downloads\\conan\\test.obj", www.bytes);
    }

```

Kindly give me help in this regard.

# Answer
> 1 votes
I agree with the drive link comment. Google Drive does not allow for direct file access. Maybe try uploading your obj file to a server and then d9wnload it using www in unity. Should work.

---
Tags: unity, server, obj, import
---


# Question
Title: How to calculate view matrix for OpenGL 3.+ 2D Camera Roll
I'm trying to create a camera object for my 2D game engine, but I just can't seem to get the view matrix down right.

Here's the code I'm currently using:

```
glm::mat4 Camera::GetViewMatrix()
{
    glm::mat4 view;
    glm::vec3 camPos = glm::vec3(this->pos, CAM_Z);
    GLfloat xup, yup;

    xup = sin(this->rot);
    yup = cos(this->rot);
    view = glm::lookAt(camPos, camPos + glm::vec3(0.0f, 0.0f, -1.0f), glm::vec3(xup, yup, 0.0f));

    return view;
}

```

The result I get from this is as follows Before rotation:

After rotation:

As you can see, the camera is rotating around its top left corner. The top left corner is the origin point (0,0,0) and the camera's position is (0,0). Shouldn't the `lookAt` function position the camera at (0,0,1) and point it at (0,0,0)? That's not what seems to be happening.

I'm just trying to get the camera to roll about it's set position. Any help would be greatly appreciated! Thanks in advance!

# Answer
I found a solution :D

I just had to scrap the use of `glm::lookAt` and create the view matrix myself (quite easy since it's a 2D camera).

Here's the code that's working for me:

```
glm::mat4 Camera::GetViewMatrix()
{
    glm::mat4 view;
    glm::vec2 midOffset = glm::vec2(this->width * 0.5, this->height * 0.5);

    view = glm::translate(view, glm::vec3(midOffset, 0.0));
    view = glm::rotate(view, -this->rot, glm::vec3(0.0, 0.0, 1.0));
    view = glm::translate(view, glm::vec3(-midOffset, 0.0));
    view = glm::translate(view, glm::vec3(-this->pos, CAM_Z));

    return view;
}

```
> 3 votes

---
Tags: opengl, c++, 2d, camera, rotation
---


# Question
Title: How to only allow letters to be pressed on in pygame?
I want the user to press on any letter of the alphabet; it should block the input from the rest of the keys. How can I do this using pygame?

```
Keys=pygame.key.get_pressed()

```

# Answer
It's not exactly 'only allowing letters', but more 'only responding to letters'.

I'm not familiar with pygame, and my python is rusty, but according to the documentation, you could do something like this:

```
press=pygame.key.get_pressed()
  for i in xrange( pygame.K_a, pygame.K_z + 1 ):
    if press[i] == True:
      name=pygame.key.name(i)
      # do something with the key

```

---

However, I must emphasize the documentation of `get_keypressed`:

> Getting the list of pushed buttons with this function is not the proper way to handle text entry from the user. You have no way to know the order of keys pressed, and rapidly pushed keys can be completely unnoticed between two calls to pygame.key.get\_pressed(). There is also no way to translate these pushed keys into a fully translated character value. See the pygame.KEYDOWN events on the event queue for this functionality.

Depending on what you exactly intend to do with these alphabet letters, you might want to use the event route instead.
> 1 votes

---
Tags: input, python, pygame
---


# Question
Title: Dealing with multiple prerequisites in goal orientated action planning using A*
I'm currently having difficulty reasoning about how multiple prerequisites are satisfied using the A\* algorithm during planning.

Assuming the following actions (with prerequisites in brackets):

```
Get Material

Make Gloves (need material)

Get Iron

Make Axe (needs iron)

```

And the following goal (prerequisites in brackets):

```
Chop Tree (needs gloves, needs axe)

```

Now, assuming I am doing a backward search from the goal, as I understand it, I would start considering actions that have effects that directly correspond to the prerequisites of the node (this is where I think I'm going wrong).

The problem with that is, the first 2 actions to consider are `Make Gloves` and `Make Axe`. However, for this goal to be satisfied they *both* need to be done. If I only build my graph by linking effects to prerequisites, I only consider each of those actions once, and only choose one.

I.e. if I arbitrarily choose `Make Axe` that leads me to `Get Iron`, I don't have anything making me reconsider `Make Gloves` as `Get Iron` has no prerequisites.

For the actions and goal I had above there are many routes to solving it, below I have highlighted one to illustrate my point. As you can see, in this case I would need `Get Iron` to be done after `Make Gloves` even though their effects/prerequisites don't match in any way.

Can someone tell me where I'm going wrong in my thinking?

# Answer
> 4 votes
It looks like you've constructed your graph incorrectly. You have actions as nodes and states as edges, when it should be the other way around: states as nodes and actions as edges.

Graph search algorithms don't work with state directly. To deal with state, you need to transform the state into equivalent graph nodes, which can lead to lots of new nodes being added so that all possible states are covered. In your example, you'd actually have to add in nodes to cover all the permutations of "gloves", "axe":

* No gloves, no axe
* Gloves, no axe
* No gloves, axe
* Gloves, axe

And the only path to the final Chop Tree node is from the last state, "gloves, axe".

So your actual graph would look something like this:

(There could be more, if you ever want to model the cloth/iron states too)

Personally I prefer a simpler approach, especially since in this case it's not clear to me why you need A\*. Here's a decision-tree-based approach: https://gamedev.stackexchange.com/a/93134/26250

---
Tags: ai
---


title: Best Step by Step Approach for Unity

text:
# Question
Title: Best Step by Step Approach for Unity
I'm planning to start learning Unity 3D with a friend of mine. I would like to know if there will be a good step by step process of which I should start learning. I never had any background in game development. But have a good foundation of `C#`, any guide to which I should start would be a great help.

Thanks in advance.

# Answer
> -2 votes
A good place to start is the Unity homepage, more specifically the Learn/Tutorials section. There is a topic called "Interface & Essentials", where you learn the basics of the Unity editor. This could be a good starting point. There are also tutorials where you create a simple game from scratch, as well as tutorials on specific topics like 2D game creation. Just look for yourself:

https://unity3d.com/learn/tutorials

---
Tags: unity
---


title: 2D game board for android

text:
# Question
Title: 2D game board for android
I am trying my hand at android game development. I want to start with a simple 2D board game. What is the best way to draw a game board like the one in the image attacked below. The blue circles are points where the players can place objects.

# Answer
You should use a graph.

A graph is a set of connected nodes. In your case each node should have a position (vector), and an ID.

Outside the grapg you should store the connections. E.g. in your gfaph there are 5 nodes with the position (0;0), (0;1), (1;0), (1;1) and (0.5,0.5) and the IDs 0, 1 2, 3, and 4 respectively. Then your connection set would be

```
0-1, 0-3, 0-4, 1-4, 3-4, 2-1, 2-3, 2-5

```

Make sure they aren't duplicated.

You take every connection, get each IDs and their corresponding nodes, and using their positions, you draw a line.
> 2 votes

---
Tags: 2d, game-design
---


# Question
Title: Why do physics engine use impulses to solve collisions?
Usually, in most physics engines that are out there, the way that collisions are solved is by applying some impulse to both colliding bodies.

While I understand that impulses are just force that is already integrated into time, and will result into velocity added at the end of the frame, why not simply project both bodies out of collision and removing their velocity component that is going towards the collision?

I'm not really sure, but it really looks like classic platformers only stopped the character instead of adding impulse to it. Is this right?

And if yes, why the added complexity of using impulses in modern engines?

# Answer
In (real-life) physics there is the principle of conservation of momentum. in a collision between objects the sum of their momenta needs to be the same before and after the collision. In other words `m1*v1 + m2*v2 = m1*v1' + m2*v2'`.

If you have 2 physics enabled objects colliding in a non-elastic collision (they end up stuck together) what will the final speeds of the combined object be? The answer is the sum of their momenta. The way to ensure that this is the case is by making sure the change in momentum in both object are opposite and equal in magnitude. This change in momentum is the impulse.

When colliding non-spherical objects the location of the impulse also lets the simulator impart some rotation onto the object if the impulse isn't aligned to the center of mass.

The other important component in physics simulation is conservation of energy, where the total energy of the system must be maintained (or converted to other forms). This means that `m1*dot(v1,v1) + m2*dot(v2,v2) = lossFactor*(m1*dot(v1',v1') + m2*dot(v2',v2'))`. Making sure that lossFactor is less than 1 is important to make avoid crazy behavior that ends up with massive speeds.
> 2 votes

---
Tags: physics
---


# Question
Title: Unity AssetBundles, server and security concerns
We're trying to implement AssetBundles in our current Unity project for Android and iOS.

My question is about security. To download AssetBundles, our application need to connect to our server. On our server, we got a web service that returns the download link for the bundle needed by the application.

However, the ID and password to connect to our web service are written in plain text in our application. This may sounds as extremely naive, but is this an issue? Could someone find the ID and password from say, the .apk file?

I don't have a lot of knowledge in the field of servers and network security, so I'm trying to keep up with what our team is doing.

# Answer
> but is this an issue? Could someone find the ID and password from say, the .apk file?

Could be an issue if you don't want people to download those files or you use that ID and password for more important stuff. And yes, people can easily decompile your .apk and find the ID and password.

Anyway, I don't see the need in having to use an ID and password just to download some Asset Bundles, as when it's downloaded onto the user's device they can do whatever they want with it.
> 3 votes

---
Tags: unity, security
---


# Question
Title: Libgdx app closes immediately after opening
I have a libGdx app, and I am running it using android studio.

It closes immediately after starting it and I see no error report. Could anyone help?

Starfield.java

```
public class Starfield extends ApplicationAdapter {

    private static final float STAR_DENSITY = 0.01f;
    ShapeRenderer shapeRenderer;
    Array<Vector2> stars;

    @Override
    public void create() {
        // Initialize a shapeRenderer
        shapeRenderer = new ShapeRenderer();

        // Call initStars
        initStars(STAR_DENSITY);

    }

    public void initStars(float density) {
        // Figure out how many stars to draw. You'll need the screen dimensions,  which you can get using
        // Gdx.graphics.getWidth() and Gdx.graphics.getHeight().
        int screenHeight = Gdx.graphics.getWidth();
        int screenWidth = Gdx.graphics.getHeight();

        // Create a new array of Vector2's to hold the star positions
        stars = new Array<Vector2>((int) (screenHeight * screenWidth * density));

        // Use java.util.Random to fill the array of star positions
        Random random = new Random();

        for (int i = 0; i < stars.size; i++) {

            int x = random.nextInt(screenWidth);
            int y = random.nextInt(screenHeight);

            stars.add(new Vector2(x, y));

        }

    }

@Override
public void resize(int width, int height) {
    shapeRenderer = new ShapeRenderer();
    initStars(STAR_DENSITY);
}

@Override
public void render() {
    // Make the night sky black
    Gdx.gl.glClearColor(0, 0, 1, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

    // Begin a shapeRenderer batch using ShapeType.Point
    shapeRenderer.begin();

    // Loop through the star positions and use shapeRenderer to draw points
    for (Vector2 vec: stars) {

        shapeRenderer.point(vec.x, vec.y, 0);

    }

    // End the shapeRenderer batch
    shapeRenderer.end();

 }

    @Override
    public void dispose() {
        // Dispose of our ShapeRenderer
        shapeRenderer.dispose();
        super.dispose();
    }
}

```

Here is the gradle log

```
Run build   1s 241ms
Run init scripts    33ms
Configure settings  1ms
Configure build 327ms
Project :   326ms
Resolve dependencies :classpath 200ms
Resolve dependencies :android:classpath 0ms
Calculate task graph    26ms
Project :desktop    15ms
Project :core   3ms
Run tasks   824ms
:core:compileJava   82ms
Resolve dependencies :core:compileClasspath 5ms
:core:processResources  3ms
:core:classes   1ms
:core:jar   16ms
:desktop:compileJava    73ms
Resolve dependencies :desktop:compileClasspath  14ms
:desktop:processResources   2ms
:desktop:classes    0ms
:desktop:run    642ms
Resolve dependencies :desktop:runtime   3ms

```

EDIT: I got an error, dumb me, I did not see the console.

```
Exception in thread "LWJGL Application" java.lang.IllegalStateException:    autoShapeType must be true to use this method.
at com.badlogic.gdx.graphics.glutils.ShapeRenderer.begin(ShapeRenderer.java:198)
at gamedev.starfield.Starfield.render(Starfield.java:87)
at com.badlogic.gdx.backends.lwjgl.LwjglApplication.mainLoop(LwjglApplication.java:215)
at com.badlogic.gdx.backends.lwjgl.LwjglApplication$1.run(LwjglApplication.java:120)

```

Thanks, any help would be appreciated.

# Answer
You need to specify the `ShapeType` in the `begin` call on the `ShapeRenderer`.

```
shapeRenderer.begin(ShapeType.Point);

```
> 3 votes

---
Tags: java, libgdx, gradle
---


# Question
Title: How to stop player falling through blocks without bounce
So I have this game and I have applied gravity to it and when I load it up it just falls through the blocks and out of the screen. I have tried the bounce event but it just goes into an endless loop of bouncing.

# Answer
When checking for a collision with solid objects, don't use the *bounce* function, do use instead the *move to contact* function, and set the certical speed to 0. Furthermore, in the *Step Event* you may want to set gravity to `0.5` if there's no collision with solid objects below the player, and to `0` otherwise.
> 1 votes

---
Tags: collision-resolution, game-maker
---


title: why won't my character move

text:
# Question
Title: why won't my character move
I am using game maker because I am new to game development and I think it's the easiest to understand because I took a course on it but I put in all the events so that my playerobj moves when you press the A and D keys but when I load up the game it doesn't work here is the GML code below that I am using:

```
//Speed of player: 5 Pixels per frame
 playerSpeed = 5;

 //Shortcuts for keypresses
 MOVELEFT = keyboard_check(ord('A'));
 MOVERIGHT = keyboard_check(ord('D'));
 MOVEUP = keyboard_check(ord('W'));
 MOVEDOWN = keyboard_check(ord('S'));

 //Move Player
 if (MOVELEFT && x > sprite_width/2)
 {
x -= playerSpeed;
 }

 if (MOVERIGHT && x < room_width - sprite_width/2)
 {
x += playerSpeed;
 }

 if (MOVEUP && y > room_height/2)
 {
y -= playerSpeed;
 }

 if (MOVEDOWN && y < room_height - sprite_width/2)
 {
y += playerSpeed;
 }

```

# Answer
> 0 votes
Your player isn't moving because you associated this very code to the wrong instance event. Try this:

*Create Event*

```
/// Declare variables
playerSpeed = 5;    // 5 pixels per step
MOVELEFT = 0;       // Checks "A" presses
MOVERIGHT = 0;      // Checks "D" presses
MOVEUP = 0;         // Checks "W" presses
MOVEDOWN = 0;       // Checks "S" presses

```

Declaration of all variables is important for operations, as it's good practice to not let an assignment in further events be treated as a declaration too.

*Step Event*

```
///Move player
if ( (MOVELEFT) && (x>sprite_width/2) )
{
    x -= playerSpeed;
}

if ( (MOVERIGHT) && (x<room_width-sprite_width/2) )
{
    x += playerSpeed;
}

if ( (MOVEUP) && (y>room_height/2) )
{
    y -= playerSpeed;
}

if ( (MOVEDOWN) && (y<room_height-sprite_width/2) )
{
    y += playerSpeed;
}

```

You need to put this part of code in the instance's *Step Event* in order to check keys continuously and move your player every step accordingly. This should work fine.

---
Tags: movement, game-maker
---


title: Unity, grass chunk or dynamic batching

text:
# Question
Title: Unity, grass chunk or dynamic batching
In theory would it be faster to render a lot of grass patches that would dynamicly batch or big meshes of combined patches, too big for batching? Rendering chunks should be faster because unity doesn't have to combine them and it avoids some overhead but smaller patches will make it easier for culling.

# Answer
> 1 votes
With batching, the fastest - performance-wise - is to do your own batching that is tailor made to the problem. Built-in batching is much faster to implement, and usually not that much slower in terms of performance.

So what you do is:

1. Make it work. Implement it in the simplest way because simple solutions are simple to replace later.
2. Measure if the performance is acceptable.

2.5 If you can, estimate how much performance would increase if you made it "better"
3. Make a note.

Once the game is mostly done, look at all of the performance related notes, sort them to by how much estimated performance gain per development work they will yield, and then decide which one you want to work on.

To answer your actual question:

Either can be faster, depending on additional technical details, such as how big the patches will be on screen, and how complex the vertex and pixel shaders are, respectively.

---
Tags: unity, performance
---


title: 2D Tile Engine Architecture

text:
# Question
Title: 2D Tile Engine Architecture
I'm been working on a 2D tile game (sidescroller perspective) and I decided to rework my tile engine. Right now I store a new tile instance per block in the world (so there are like 1000 TileStone instances in memory). My plan was to change the current tile engine so that I store only a small object which tells the renderer a stone tile should be drawn there. The TileStone, TileDirt classes only store the block properties like hardness, texture and so on.

With this design I ran into a bit of a problem, some tiles, for example, a chest tile should be able to store custom data like the contents of the chest, or for instance a windmill block which needs to update all of its logic every update tick.

What would be a good way of implementing a tile engine, that meets these requirements?

Programming language: Java, Library: LibGDX

Thanks in advance -ProRed

# Answer
It sounds to me like you should also be divorcing the concept of a container or logic object or whatever else from the tile. The tiles should just be able the static (or mostly static) structure of the world.

Things like containers and windmills and whatever, which are significantly heavier-weight, should be non-tile *objects* stored in your world differently, and given a tile *position* to indicate where they (currently) are on the map.

But they're not actually tiles themselves (even if they point to similar-looking data for drawing purposes so that they *render* like tiles).

Then you can add extra data to them without worrying about bloating any tile-related storage that would otherwise not need it (for containers), and you can group them all in their own big contiguous array and update them all at once (windmills), et cetera.
> 5 votes

---
Tags: java, 2d, libgdx, architecture, tiles
---


# Question
Title: Managing draw calls for customized materials when targeting mobile
I want to know how to minimize draw calls when rendering multiple customized characters onscreen, presumably with 3-4 materials apiece. Is there a better way to achieve custom color configurations than instancing/duplicating materials? Am I overthinking the problem?

Our game is a frenetic, goofy arena fighter, made in Unity. We plan to publish on mobile, first. I am tasked with creating an art pipeline which allows for customizable additions and color changes to the player's avatar. I'm trying to look ahead to when this character creator will be a part of the game and consider the performance implications of this kind of system. A character creator could potentially serve us in the generation of random NPCs at launch, and will feature heavily when we move to multiplayer.

My concern is with the number of draw calls on mobile. Currently, we have a bunch of identical characters, all creating instances of the main material on spawn to differentiate by random color. Since draw calls are directly linked to the number of materials onscreen, this process concerns me. Before complicating the issue with variations in mesh and texture on a per-object basis, having 1 material per character already limits us to a certain number of NPCs onscreen.

I delivered a material solution which allows changing one color to differentiate from other characters. Now the director is asking about the feasibility of breaking each character into multiple materials to allow for player customization. With 4 materials per character (1 shared), draw calls would increase geometrically per spawn. I've heard mobile platforms tend to be limited to about 20-120 draw calls between low and high end devices. That would make for 5-35 characters allowed onscreen at once, assuming we could get the environment down to around 5 draw calls.

I would be especially interested in any material masking techniques people are aware of. Having a need for around 4 customizable aspects would seem to point towards using some sort of RGBA texturing and masking solution, but I have no idea how to make Unity do that.

# Answer
> 1 votes
While it's true that draw calls are expensive and we'll generally want to minimize them, we don't need to go full Highlander "There Can Be Only One" on it. ;)

Having one draw call for each character is not unreasonable - especially since character models often have enough vertex data / skinned animation that they don't dynamically batch together anyway.

But there are some ways you can minimize draw calls within a single customizable character, or minimize the impact of multiple draw calls:

* You can use Vertex Colours to tint parts of the mesh, rather than splitting each off into its own mesh/submesh/material.
* You can specify a multi-colour palette for the character in its material, and select a colour from this palette within your shader using either vertex attributes or a paint-by-numbers texture map. That way you can independently change multiple colours on a mesh in a single material.
* Material Property Blocks let you apply variations to a material in a somewhat lighter-weight fashion than instantiating a new unique material. It still generates additional draw calls, but the state changes are optimized to reduce the impact.
* Texture Atlases can let you assign unique texture content to several different character parts and render them all with a single material.
* Mesh.CombineMeshes will let you stitch multiple disparate mesh parts together into a single mesh for rendering.

---
Tags: unity, optimization, mobile, materials, masking
---


title: Movement based on direction of car?

text:
# Question
Title: Movement based on direction of car?
I'm currently making a simple racing game in libGDX. I am stuck on figuring out how to move my car object based on its direction. So far I have a class PlayerCar.java as shown below:

```
public class PlayerCar {

    private Vector2 position, velocity;
    private int width, height;
    private float rotation;
    private Rectangle boundingBox;

    public PlayerCar(float x, float y, int width, int height) {
        this.width = width;
        this.height = height;
        position = new Vector2(x, y);
        rotation = 0;
        velocity = new Vector2(0, 0);
        boundingBox = new Rectangle();
    }

    public void update(float delta) {
        position.add(velocity.cpy().scl(delta));
        boundingBox.set(position.x, position.y, width, height);
    }

    public void stop() {
        velocity.x = 0;
        velocity.y = 0;
    }

    //Code to deal with movement here

}

```

I'm stuck because in all the other 2d games I have developed the movement directions have always stayed the same.Can someone please tell me what is an efficient way to achieve this direction-based movement?

# Answer
> 0 votes
Enter trigonometry!

Getting a directional vector from an angle is very easy:

```
x = cos(angle)
y = sin(angle)

```

Where angle is the rotation in radians.

Then you multiply this with the velocity and add it to the position.

# Answer
> 0 votes
Store the speed as a scalar then rotate a vector by the direction (in degrees) by using the `rotate` method on the `Vector2` class:

```
public void update(float delta) {
Vector2 v = new Vector2().rotate (direction).scl(speed).scl(delta);
position.add(v);
    boundingBox.set(position.x, position.y, width, height);
}

```

Note that for performance reasons you probably dont want to new up a new `Vector2` every tick.

---
Tags: libgdx, rotation, direction
---


# Question
Title: How do I make my plane appear 3D like in the "Roll-a-ball" tutorial?
I am following the first tutorial on the Unity website, which details making a 'Roll-a-ball' game.

I am stuck at a point where I need to make a 3D plane object; it looks flat, to me, and unlike how it looks like in the tutorial.

How do I make my plane look 3D?

---

This is what I see:

This is what I see in the tutorial:

# Answer
> 1 votes
To solve your question, we need to start with some base understanding; planes *are* flat, by definition:

> plane
>
> 1. a **flat** surface on which a straight line joining any two points on it would wholly lie.
>
> *"the horizontal plane"*
>
> synonyms: **flat surface**, level surface;
>
> <sub>\- "Plane" as defined by a quick Google search (emphasis mine)</sub>

In fact, they only appear under "3D" in Unity because they are *rendered* in 3D space, using 3D drawing concepts. As a result, they look like flat lines, when viewed at from the side. *Exactly* as shown in your first screenshot.

---

In your screenshot, it appears your moving directly along the Z axis. It is most likely that you have initialised your Unity project in 2D, as opposed to 3D. Contrary to the answer provided by *lilotop*, there is no real reason to restart in 3D. Unity does not need to handle 2D and 3D across separate projects. There should only be two settings that need to be changed, for a new project.

When you start a 2D project, you will start in 2D mode, in the Scene view. This means that you will start off looking directly along the Z axis. It also means that `ALT + RMB` will *pan* the view. If we swap to 3D mode, in the Scene view, `ALT + RMB` will *rotate* the view, and let us see the plane in full 3D.

If you truly did start your project in 2D mode, there is one last thing we need to do. The camera used to render your game to the screen will likely be set to *Orthographic*, to render the area as a 2D image. It needs to be set to *Perspective*, to render an area in 3D. You will likely have to play around with it to get the exact perspective you want; but playing around with it is the only real way to learn - and you will likely have to do so regardless of it's initial settings.

---
Tags: unity
---


# Question
Title: Calculate vector3 global point projecting it in local space using Unity and C#?
How to project a vector 3 locally ? Unity has a special function for this?

For example, if a has a GameObject that contains 2 children Vector A (transform) "My A Arrow" and Vector C (transform) "My C arrow projection".

I wish a C# solution script for "C" vector (transform) so that it can be used in Unity Game engine.

Just for example: My game object "A" is child moving and rotating locally. I wish to make the projection locally. "B" is my world forward in case is needed. "C" is a simple projection of "A" to the plane in **local** axis.

Is simple to get the vector in world global axis, just taking x (x = 0f). But I fail locally, since my parent GameObject is rotating.

Attempted solution. public Vector3 vector\_A, projection\_C;

```
vector_A= new Vector3(4f, 5f, 11f);

void FixedUpdate()
{
    projection_C = transform.TransformPoint(vector_A);
}

```

I try using transform, rotation, vector3 unity functions and quaternion. My skill was not at the level to understand wich function to choose for the task reference: https://docs.unity3d.com/ScriptReference/Vector3.html

---

I was able to get the solution but was so complex that I was thinking that Unity has a function that makes the local projection.

This is my attempt to describe the process:

First you need to make a clone of the game object, rotate it to world global and move it to origine 000. The child vector will folow the perent game object. Now you can make the projection of "A" taking out x. The result "C" must be rotated and move by the original game object rotation and position.

# Answer
> 5 votes
Let's say you have a trasnformed coordinate system defined by a `quaternion` rotation, and `vector3` position. For example, the transformed coordinate system may represent the orientation and position of an object in your game.

You can use `Matrix.TRS` to get a transformation matrix that represents this coordinate system. It would be done as follows:

```
Matrix4x4 m = Matrix4x4.TRS(position, rotation, new Vector3(1, 1, 1));

```

Note: `new Vector3(1, 1, 1)` is the identity scaling vector, it means no scaling is applied.

Once you have the matrix, you can use it to convert points from the transformated coordinate system to wolrd coordinates:

```
Vector3 trasnformedPoint = m.MultiplyPoint3x4(point);

```

You may convert from world to the trasnformed coordinate system by using the inverse of the matrix:

```
Vector3 point = m.inverse.MultiplyPoint3x4(trasnformedPoint);

```

---

Alternatively, if you are using an scene object, you can use its `Transform` to get the same results.

```
Vector3 trasnformedPoint = transform.TransformPoint(point);

```

And in the opposite direction:

```
Vector3 point = transform.InverseTransformPoint(trasnformedPoint);

```

---

Once you have the point represented in the coordinate system you need it, you can proceed to manipulate it any way you need, and you can transform it back to the coordinate system you had it to begin with.

For example, we can transform a point, remove a component, and transform it back:

```
Transform transform = gameObject.transform;

// ...

Vector3 trasnformedPoint = transform.TransformPoint(point);
trasnformedPoint.x = 0;
Vector3 newPoint = transform.InverseTransformPoint(trasnformedPoint);

```

---
Tags: unity, c#, vector, transformation
---


# Question
Title: Entity Components Ids and Max Integer Values
I have been studying several entity component systems (Anax and EntityX) to get an idea of how they work.

For Entity ids, both use 2 numbers. The first number is basically a position in an array, and a second number is the "version" for the entity at that index. If a handle to an entity at a given index has a "version" older than the the version the container currently has, the handle is considered invalid. This would occur when an entity is deleted from the world and its index becomes free for a new entity.

This approach seems to suggest the maximum number of times an index can be reused is limited to whatever the max number a `uint32_t` (or whatever the system chooses to use) can hold.

In practice, I suppose this wouldn't occur often, but it doesn't seem impossible. If I made a simulation that endlessly spawned entities, moved them around on the screen a bit, and deleted them once they were off screen, then the program would *eventually* crash, or exhibit strange behavior, once the version number for an index reached the max for an int.

Here are some of the specific lines I've been looking at for each:

Is this a shortcoming of reusing indexes, and needing to invalidate old handles? Is there any real practical concern since even a 32bit in has a max value of 4 billion or so? Could these systems be broken by a soak test with a long, ongoing stream of short-lived entities?

# Answer
> 0 votes
This isn't a entity system specific issue; this pattern of versioned or salted handles can be used in almost any generic data structure (e.g., Sean Middleditch's slot map example). Related is the fact that you don't need to use this kind of versioned handle system in an entity/component system, either.

That said, your concerns are valid, but not quite as dire as you may think.

The purpose of the version bits are to allow you to differentiate between *stale* references to objects. The version bits don't actually have to impose an upper limit on the number of times the slot can be reused. You can make them do so if you like, but generally rolling over the version bits from the maximum value will not immediately crash you.

Once the version bits roll over, however, you can't reliably detect those stale references. If you allocate slot 10, version 0 to object A at the start of the program, and then release object A some time later, any handles referring to slot 10, version 0 are stale. You can detect that when you try to use them, since slot 10 will actually be at version 1.

If, *eventually*, you execute long enough to roll the versions over so that object Z ends up slot 10, version 0 *and* you happened to have kept a stale handle to object A around that long without dereferencing it, then at that point you won't be able to tell that that handle to A is stale. It will quietly, safely, dereference to object Z.

The likelihood of this occurring is exceedingly small. Small enough that it's generally not worth worrying about, given the value of the other benefits of this system.

You can help this by accounting for hysteresis. When you build the system, a simple approach is to use a stack of "free" slots. When you go to allocate, just pop the top entry off the stack, right? The problem with this is that if you allocate and destroy frequently, you tend to quickly increase the version of one slot. This can cause you to roll over the versions sooner. If instead you use a queue approach, you can distribute the versioning over a wide range of slots (although this is not without its own drawbacks).

You have to examine the expected use cases and decide which approach to reusing slots fits your case the best.

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


# Question
Title: Phong: Real-time rendering of Metal and Plastic Materials
Using a shader that works like Phong, what would be the difference between painted Metal and plastic?

I seem to remember reading in books that I no longer have access to, the following:

* Specular color for painted metal is same color as the paint.
* Specular color for plastic is always white.
* Ambient for metal should be darker than for plastic.

This also seems to correlate with what I see when I observe objects (in real world)

But I tried to verify this also by checking the Internet, and found conflicting versions, some said the complete opposite.

So what is true?

# Answer
> 0 votes
General rule of thumb: under white light, plastics and other non-metallic surfaces tend to have white specular highlights, whereas metals tend to have specular highlights which are a similar shade as the metal. (Or to be more pedantic, most of the color of a metal is actually its specular reflection; they tend to be quite dark, in terms of their diffuse color)

Once paint is on the metal, though, all bets are off.

For example, opaque paint might reflect light exactly like plastic does, even though there's metal underneath. If the light's not making it down to the metal, then it doesn't really matter at all that there's metal down there.

Similarly, it's very common to put a clear coat of paint on top of metal ("clearcoat"), which will add a white specular highlight, similar to the one you get on plastic, with the metallic light behaviour underneath, on the next layer down. (Disney is fairly well known for putting simulated clearcoat on virtually every surface in their recent 3D-rendered films)

Car paints are often translucent; some light will interact with the paint, some will pass through to the metal underneath, and the light which passes through to the metal underneath and is reflected will pass back through the paint *again* on the way back, being affected in both directions.

Phong was one of the first algorithms for estimating specular lighting, and it's far from "state of the art", these days; it can't model any of these more complicated surfaces to any degree of accuracy. But if you're not after accuracy, it can still do stylised lighting okay, as long as you control the size and color of the highlights to be appropriate for the materials you're simulating.

As a rough rule of thumb, in the absence of other factors, and under a white light, plastics tend to have a white specular highlight, while metals tend to have a colored one.

---
Tags: lighting, shading
---


# Question
Title: How do I rotate an object around another object with an angle and an offset?
I made a small game engine with a hierarchy, but have a with problem with applying transform down the hierarchy. I have an object with a parent, and I want the child to rotate around the parent with an offset (the childs `localPosition`, relative to the parent, and a parent rotation).

For example, I have a parent *"Earth"*, and a child *"Moon"*. The *"Earth"* rotates, and the *"Moon"* rotates with a `100, 50` offset.

How do I rotate an object around another object with an angle and an offset?

---

Each object has:

* x / y `localPosition`
* `private` x / y `globalPosition`
* `localRotation`
* `private globalRotation`

This is what I have, so far:

```
float atr = Deg2Rad(parent->GetGlobalRotation());
globalPosition.x = parent->GetGlobalPosition().x + cos(atr) * localPosition.x;
globalPosition.y = parent->GetGlobalPosition().y + sin(atr) * localPosition.y;

```

but it only only on the x-axis if localPositon is `50, 0`

# Answer
> 1 votes
The solution is to use a rotation matrix:

```
globalPosition.x = parent.GetGlobalPosition().x
    + (cos(atr) * localPosition.x) + (-sin(atr) * localPosition.y);

globalPosition.y = parent.GetGlobalPosition().y
    + (sin(atr) * localPosition.x) + (cos(atr) * localPosition.y);

```

---
Tags: c++, scene-graph
---


# Question
Title: Counting down a number of coins in the same total time duration, no matter the amount
Math has never been my strong suit and so I'm having trouble figuring out how to write this formula.

When you buy something in my game, the amount it costs to purchase that item will be taken off from your total coin amount one by one. It's a loop that repeats itself till the amount that needs to be taken off is 0. I have that system set in place, but I need to figure out a way to calculate the speed of decrease, or the time between each coin, making sure that each purchase will last the same amount of time, regardless of how much it costs.

What I figured out is that I need to come up with a formula in which the time it takes between each coins should become smaller/shorter the more coins it costs.

e.g. 10 coins taken from your total coin amount should take as long 200 coins. 10 coins -\> 0.1 seconds between coins -\> 1 second total 200 coins -\> 0.005 seconds between coins -\> 1 second total 500 coins -\> 0.002 seconds between coins -\> 1 second total And etc.

It would be greatly appreciated if anyone could push me in the right direction and/or give a little explanation to whether this is possible or not.

Thank you

# Answer
The answer to your current question is:

```
timeSpentOnOneCoin = timeSpentTargetValue * 1 / coinsSpentTargetValue

```

Where:

* timeSpentOnCoin - the value you are looking for
* timeSpentTargetValue - your desired total time
* 1 - you are spending one coin at a time
* coinsSpentTargetValue - amount of coins spent by user on a purchase

**However**, I assume that the point of this is to combine displaying rapidly changing numbers with some other timed event of a fixed duration (sound or other animation).

In that case you should consider that the number of coins displayed to the user will be updated according to user's current framerate (let's say 60 times a second) - therefore subtracting coins one by one is pointless, instead you should subtract a number of coins proportional to the time that passed between frames.

So the formula for this looks like **this**:

```
coinsSpentThisFrame = coinsSpentTargetValue / timeSpentTargetValue * timeSpentThisFrame

```

You will need to **calculate that number on every frame of your animation**, as the number of frames per second and the time between them isn't a fixed number.
> 3 votes

# Answer
Simply divide the desired total time by the number of coins, and you get the time per coin.

Edge cases you might want to be aware of:

* When you do a transfer of 0 coins for any reason, it gives you a division by zero. You might want to handle that case separately.
* With a very large number of coins, you might get a shorter time between coins than the timing system of your platform can handle. You might want to test how your platform behaves in that case. A possible workaround might be to transfer coins in larger packets when the transfer amount exceeds a certain threshold.
> 0 votes

---
Tags: mathematics
---


# Question
Title: How do I create a Button when I click another Button?
I need help. When I click a Button, I want to create a new Button. My code, however, creates four Buttons. What should I do?

```
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using System.Collections.Generic;

public class AddButton : MonoBehaviour
{
    public GameObject prefabButton;
    public RectTransform ParentPanel;
    public Button saveButton;

    void Update()
    {
        if (Input.GetMouseButton(0))
        {
           // for (int i = 0; i < 2; i++)
            {
                GameObject button = (GameObject)Instantiate(prefabButton) as GameObject;
                button.transform.SetParent(ParentPanel, false);
                button.transform.localScale = new Vector3(1, 1, 1);
             }
        }
    }
}

```

# Answer
> 1 votes
`Input.GetMouseButton(0)` will return true during every frame where you keep holding the button. Unity frames are quite fast, so it requires quite a lot of agility to hold a button for just one frame.

Try `Input.GetMouseButtonDown(0)` instead. It only returns `true` during the first update of a click.

By the way: Your code will spawn a new button no matter where you click, because it just detects mouse clicks, not where these clicks happen. If you want an event to happen when a button is clicked, you shouldn't use the Input class. Add a method as an event handler for that button, instead. You can do that in the editor or with a script.

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


# Question
Title: How to display unicode text in monogame?
I'm looking for ways to draw any characters that may be entered in any language, on any keyboard, so that I don't have any trouble with limited language support in a monogame project.

So far I've only found how to add specific ranges of characters to SpriteFont, which is a bit insane because it means there will be a huge texture with all the characters, and it would probably eat up tons of memory. And then changing font size would mean more textures if I want to keep the quality 100%.

Is there a way to render text without pre-baking textures for every character like that? I've read that it's possible to use DirectWrite, GDI or Windows' means of drawing text to a DirectX texture, but that info is 6 years old, and I'd like to know if there are better ways now.

**Update:** So far I've found that Awesomium seems to be how people render nice GUIs these days, including the ability to write any text from any unicode region, provided you have the font files to render them. But it would require some alchemy to render that over the game's viewport. I haven't figured out exactly how to do it yet.

# Answer
> -1 votes
It exist various way to rasterize glyphes at runtime, like the freetype library or stb\_truetype.h

All you need is a font with the set of character you want, and at runtime, you update a texture with the characters you need. The texture behave as a cache with a MRU logic to preserve glyphes across frames.

Another solution is to interpret the glyphe pathes directly and rasterize yourself.

# Answer
> -1 votes
You can use `DrawString` method of `SpriteBatch` object from: https://msdn.microsoft.com/en-us/library/microsoft.xna.framework.graphics.spritebatch.drawstring.aspx

For example, you can use `SpriteBatch.DrawString (SpriteFont, String, Vector2, Color)` to create your text sprite.

---
Tags: directx, monogame, windows, fonts, awesomium
---


# Question
Title: Tick() method error when I run it. HELP!
Okay so I get this error:

```
Exception in thread "Thread-2" java.lang.NullPointerException
at basic.game.here.Game.tick(Game.java:71)
at basic.game.here.Game.run(Game.java:54)
at java.lang.Thread.run(Unknown Source)

```

Here is the code it says the error relates to:

```
package basic.game.here;

import java.awt.Canvas;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferStrategy;

import basic.game.here.tiles.Ground;

public class Game extends Canvas implements Runnable {

private static final long serialVersionUID = 1L;

public static final int WIDTH = 960, HEIGHT = WIDTH / 12 * 9;

private Thread thread;

private boolean running = false;

private int FPS = 0;

private World world;
private Player player;

public Game(){
    new Window(WIDTH, HEIGHT, "BASIC", this);

    world = new World();

    player = new Player(500, 200);

}

public synchronized void start(){
    thread = new Thread(this);
    running = true;
    thread.start();
}

public synchronized void stop(){
    try{
        thread.join();
        running = false;
    }catch(Exception e){
        e.printStackTrace();
    }
}

public void run() {
    long lastTimeChecked = System.nanoTime();
    int frames = 0;
    while(running){
        tick();
        render();
        try {
            Thread.sleep(6);
        } catch (InterruptedException e){
            e.printStackTrace();
        }
        frames++;
        if(System.nanoTime() - lastTimeChecked >= 1000000000){
            FPS = frames;
            frames = 0;
            lastTimeChecked = System.nanoTime();
    }
}
}

private void tick() {
    player.tick();
}

private void render(){
    BufferStrategy bs = this.getBufferStrategy();
    if(bs == null){
        this.createBufferStrategy(3);
        return;
    }
    Graphics g = bs.getDrawGraphics();
    g.setColor(Color.BLUE);
    g.fillRect(0, 0, WIDTH, HEIGHT);

    g.setColor(Color.YELLOW);
    g.setFont(new Font("Dialog", Font.BOLD, 18));
    g.drawString("" + FPS, 5, 20);

    //g.drawString("(" + player.x + ", " + player.y + ")", 5, 40);

    world.render(g);
    player.render(g);

    g.dispose();
    bs.show();
}

public static void main(String[] args){
    new Game();
}

}

```

Here is the player class because I think it is related to this:

```
package basic.game.here;

import java.awt.Color;
import java.awt.Graphics;

public class Player {

private int x, y;

public Player(int x, int y){
    this.x = x;
    this.y = y;
}

public void tick(){

}

public void render(Graphics g){
    g.setColor(Color.CYAN);
    g.fillRect(x, y, 16, 16);
}

}

```

Thanks in advance!

# Answer
Your crash message indicates that `Game.tick()` is the source of the null reference exception:

```
>            Exception in thread "Thread-2" java.lang.NullPointerException at
> -- see --> basic.game.here.Game.tick(Game.java:71)

```

`Game.tick()` itself contains nothing but a call to `player.tick()`, so `player` is probably null. The player tick function is empty, so even if there were some kind of callstack trimming due to inlining, the only thing that *can* be null in this code is `player`.

Put a breakpoint on the `player.tick()` call in `Game.tick()` and verify that player is non-null; you *do* initialize it in the `Game` constructor, but *after* you pass the game to the window. Perhaps the window class is calling `run`, and thus `tick()` before you have executed the line of code that initializes the player.

You could also try moving the `player = new Player...` line up above the `new Window...` line.
> 0 votes

---
Tags: java
---


# Question
Title: Using Smartphone as a steering wheel on Linux
I am making a car simulation game, however, I find it being inefficient and difficult to test the simulation realism and accuracy via keyboard or even joystick control. I need a steering wheel controller to do this. However, getting good steering wheel controllers is so difficult - they cost **a lot**. However, I noticed(when playing Real Racing 3) that the phone actually can handle such task kinda well.

What sort of code could I write to use a smart phone as a steering wheel?

Looking forward to see some useful answers ;)

# Answer
> 2 votes
Check out **node-virtual-gamepads**. It does almost what you want (doesn't seem to have accelerometer support yet). From its blurb:

> This nodejs application provides the possibility to use your smarpthone as a gamepad controller on Linux OS simply by reaching a local address. You can virtually plug up to 4 gamepad controllers.

If for some reason you want to write your own, here's what you need:

1. A phone app to detect phone inputs like the accelerometer. node-virtual-gamepads uses a web front end, you can also write a native app.
2. A connection to your linux PC. node-virtual-gamepads uses web sockets, you can also use bluetooth.
3. A program on your linux PC which can emulate a virtual gamepad via a kernel module. node-virtual-gamepads uses uinput with a node server.

---
Tags: input, linux, controllers
---


# Question
Title: Collision Detection - Why is my implementation of Rectangle.intersects in my Player class causing errors?
Ok. I get this error:

```
Exception in thread "Thread-2" java.lang.NullPointerException
at basic.game.here.Player.collision(Player.java:42)
at basic.game.here.Player.tick(Player.java:23)
at basic.game.here.Game.tick(Game.java:69)
at basic.game.here.Game.run(Game.java:52)
at java.lang.Thread.run(Unknown Source)

```

This is the necessary code:

```
package basic.game.here;

import java.awt.Canvas;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.image.BufferStrategy;

public class Game extends Canvas implements Runnable {

private static final long serialVersionUID = 1L;

public static final int WIDTH = 960, HEIGHT = WIDTH / 12 * 9;

private Thread thread;

private boolean running = false;

private int FPS = 0;

private Player player;
Rectangle ground = new Rectangle(500, HEIGHT - 61, 32, 32);

public Game(){
    player = new Player(500, 200);

    new Window(WIDTH, HEIGHT, "BASIC", this);

    this.addKeyListener(new KeyInput(player));
}

public synchronized void start(){
    thread = new Thread(this);
    running = true;
    thread.start();
}

public synchronized void stop(){
    try{
        thread.join();
        running = false;
    }catch(Exception e){
        e.printStackTrace();
    }
}

public void run() {
    long lastTimeChecked = System.nanoTime();
    int frames = 0;
    while(running){
        tick();
        render();
        try {
            Thread.sleep(6);
        } catch (InterruptedException e){
            e.printStackTrace();
        }
        frames++;
        if(System.nanoTime() - lastTimeChecked >= 1000000000){
            FPS = frames;
            frames = 0;
            lastTimeChecked = System.nanoTime();
    }
}
}

private void tick() {
    player.tick();
}

private void render(){
    BufferStrategy bs = this.getBufferStrategy();
    if(bs == null){
        this.createBufferStrategy(3);
        return;
    }
    Graphics g = bs.getDrawGraphics();
    g.setColor(Color.BLUE);
    g.fillRect(0, 0, WIDTH, HEIGHT);

    g.setColor(Color.YELLOW);
    g.setFont(new Font("Dialog", Font.BOLD, 18));
    g.drawString("" + FPS, 5, 20);

    g.drawString("(" + player.x + ", " + player.y + ")", 5, 40);

    g.setColor(Color.GRAY);
    g.fillRect(ground.x, ground.y, ground.width, ground.height);

    player.render(g);

    g.dispose();
    bs.show();
}

public static void main(String[] args){
    new Game();
}

}

```

AND:

```
package basic.game.here;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Rectangle;

public class Player {

public float x, y;
public float velX = 0, velY = 0;
private float gravity = .05f;
private final int MAX_SPEED = 10;
private Game game;
Rectangle playerr;

public Player(float x, float y){
    this.x = x;
    this.y = y;
    playerr = new Rectangle(500, 100, 32, 32);
}

public void tick(){
    if(!collision()){
        playerr.x += velX;
        playerr.y += velY;
    }

    velY += gravity;
    if(velY >= MAX_SPEED){
        velY = MAX_SPEED;
    }

}

public void render(Graphics g){
     g.setColor(Color.CYAN);
     g.fillRect(playerr.x,  playerr.y,  playerr.width,  playerr.height);
}

public boolean collision() {
    boolean solid = false;
    if(game.ground.intersects(playerr)){
        solid = true;
    }
    return solid;
}

public float getVelX() {
    return velX;
}

public void setVelX(float velX) {
    this.velX = velX;
}

public float getVelY() {
    return velY;
}

public void setVelY(float velY) {
    this.velY = velY;
}

}

```

THANKS IN ADVANCE!!!

# Answer
> 0 votes
The variable `private Game game` in the class `Player` is never initialized, so it is `null`. That's why `game.ground.intersects` fails with a null pointer exception in `Player.collision`. Your IDE should actually give you a warning about that.

A good place to pass the game to the player would be in the constructor of `Game` when you create it.

---
Tags: java
---


title: D3D11 SetShader States

text:
# Question
Title: D3D11 SetShader States
I have some questions regarding the XXSetShader and what happens after, for instance I would like to know if when XXSetShader is called the subsequent calls would be bound to that particular shader, like PSSetShaderRsources. Because at load time I am bounding the resource views needed for that particular shader, then the next one and so on, but what I found is that the resources were not bound, I need to set them again every time the XXSetShader is called.

Am I doing something wrong? it's not supposed to work like that, the purpose of this is to have the least change states at runtime.

Thanks.

# Answer
> 1 votes
You can not bind resources to a particular shader, but a shader stage instead. For example, you bind a texture to pixel shader stage, then switch to an other pixel shader, the same texture will be bound to that new shader.

You should typically bind your resources before the draw call. To ensure few state changes, you can group a bunch of textures and bind them with a single call to XSSetShaderResources.

Good luck!

---
Tags: shaders, directx, state
---


# Question
Title: Should I compute impact damage with energy or momentum?
My game uses physics (Box2D in particular). Just about every object in the game can be destroyed, and the primary method of combat is by **slamming objects** into one another at **high speed.** It makes sense that I would use the object's velocity and mass in order to determine damage. My question is...how?

As I see it, my two main options for computing damage are as a function of the object's momentum (`p = m*v`) or its kinetic energy (`KE = .5 * m * (v^2)`), both **translational** and **rotational**.

The following statements hold true of my game:

* Objects can also collide with **walls**, which are indestructible (but not necessarily immovable). The object takes **damage**, but the wall does not.
* Objects can move freely, and certain kinds of objects can also **rotate**.
* This is a **top-down game**, so gravity is not a concern.
* Different objects can **vary** in size, mass, and shape, often **considerably.**

Given this...

* Which should I use to determine the damage an object takes upon collision; its **momentum** or its **kinetic energy**?
* What **other physical properties** should I consider when doling out collision damage, and how?
* How should I handle the (quite possibly substantial) **differences** in these quantities between the two colliding objects?

# Answer
> 2 votes
If you want realism, you should consider that on impact kinetic energy can be transformed in a few different ways. It can cause movement, or be converted into other forms of energy, usually by deforming/damaging the objects involved in the impact. Assuming that when two objects collide they bounce away in some manner, you could base damage on the loss of kinetic energy ie. the energy converted to other forms during the impact. (`delta_KE = KE_initial- KE_final`) This will not work if your collisions are totally elastic.Momentum is still conserved by inelastic collisions (the typical example being two cars crashing together).

This also causes damage to adapt to bounciness. Colliding with a large rubber object will make you bounce back faster than colliding with a metal object of equal mass. More velocity is converted to damage by the impact with the metal object, which makes sense. Although you did not mention a 'bounciness' property for your objects, this is a stand-in for whatever method/values you are using to determine how fast objects move away from each other.

Another effect of a kinetic energy based approach is that it causes speed to be more important than mass, so a bullet does more damage than bumping into a very heavy, very slow moving object. (This would happen for both KE and delta\_KE approaches) Momentum based approaches give equal importance to each object. (Correct me if I'm wrong but) From the tone of your question I think you want to encourage players to try to throw things as fast as possible more than they try to find the heaviest items. Rewarding the game-play you want with better damage will help with that.

# Answer
> 3 votes
You could use both, depending on case and need. Both are valid and both occur together.

The difference in your case is apparently how you define loss of energy, ie. what is more convenient and accurate.

In case of momentum, we have P=mv, and you can only work with v; in practice only with elastic collisions. Here is the classic example of (indestructable) momentum, in an (almost) closed system: Elastic collision

How would one manage energy loss there? Maybe by saying "next speed = 99 % of previous", or something. The mass remains, so only v is left. For truly elastic collisions, you could ofc estimate v1 (incoming speed) and v2 (what is left after collision - maybe hard code a max/min percent?), calculate the difference and transfer what was lost as momentum to the target object, using it's mass - you get a velocity. The target will then move nicely. One must ofc always do the calculation in both directions.

But as soon as there are more "daily" objects, and one aims for realism, i think the kinetic energy E=0.5mv^2 comes in. Then it's a question of defining how much the parties absorb when being hit, and then using the rest for calculating speed changes for the objects. Here is (almost) fully plastic collision.

It might be easier to work with the "how much absorbs" when using kinetic energy. Maybe use percentages of the full energy? Then you may have a better chance to get it look right by modeling, by using trial and error.

1. Calculate how much energy the whole system has at collision (say the two cars). That is 2 * 0.5mv^2.
2. Calculate how much of that A absorbs, how much B absorbs (use strength, health settings etc). Say A absorbs 20 % of the full energy, B absorbs 30 %. Remains 50 %.
3. Both "get" equally much of the remaining energy. So add 50 % of it (opposite direction!) to A:s existing energy, 50 % to B:s, then resolve a new (lower) velocities for both. If for example a car collides with a heavy truck, then remaing 50 % for the car will be so big that it may exceed it's original energy, and hence it changes direction of movement. The trucks remaining 50 % is small compared to it's original energy, so it only slows down.

The absorbing figures will likely be close to 100 % in total, as anything else will cause a bit of bounciness. I think you will have to spread out (repeat) the calculation over multiple frames, as these should be higher grade equations in reality. *If the collision isn't fully elastic, the objects absorb for a longer duration of time*.

Finally, you get a more realistic damage model when using kinetic energy, because apparently absorbing energy causes damage? Will be more accurate than using momentum.

---
Tags: physics, mathematics, box2d, game-mechanics, rigid-body-dynamics
---


# Question
Title: GameMaker project works fine when targeting Windows but not when targeting HTML5
As mentionned in the title, my GameMaker project works fine when targeting Windows.

However, when I build it for HTML5, I got those errors in the Chrome developer console:

```
Destructive Dark.js?VYNZB=1666826811:7 Uncaught TypeError: Cannot read property '_42' of undefined
    at _Qw1._M [as _L] (Destructive Dark.js?VYNZB=1666826811:7)
    at _Qw1._a4 (Destructive Dark.js?VYNZB=1666826811:1490)
    at _a72._a4 (Destructive Dark.js?VYNZB=1666826811:1380)
    at _lK1 (Destructive Dark.js?VYNZB=1666826811:1155)
    at _9v2 (Destructive Dark.js?VYNZB=1666826811:1742)
    at _Mu2 (Destructive Dark.js?VYNZB=1666826811:1748)
    at _Ju2 (Destructive Dark.js?VYNZB=1666826811:1733)

```

I suppose this error is not really useful since it seems to come from the obfuscated Javascript... However, I noticed that this error appears on the "Left mouse button released" event on one of my object. The code associated with this event is the following:

```
/// Select the square or switch its place with the current selected square

game_manager = instance_find(obj_game_manager, 1);

if (game_manager.lock_timer == 0) {
    if (game_manager.selected_square == noone) {
        game_manager.selected_square = self;
        inst = instance_create(x, y, obj_selection);
        inst.depth = -100;
        inst.image_alpha = 0.6;
    }
    else if (game_manager.selected_square == self) {
        game_manager.selected_square = noone;

        with (obj_selection) {
            instance_destroy();
        }
    }
    else {
        // Lock interactions
        game_manager.lock_timer = 2;

        // Switch the array cells
        var x_temp = game_manager.selected_square.x_grid;
        var y_temp = game_manager.selected_square.y_grid;
        var color_temp = game_manager.selected_square.color;

        game_manager.grid_array[x_temp, y_temp] = color;
        game_manager.grid_array[x_grid, y_grid] = color_temp;

        game_manager.selected_square = noone;

        with (obj_selection) {
            instance_destroy();
        }

        with (game_manager) {
            event_perform(ev_alarm, 0);
        }
    }
}

```

Not much info sorry, but I have no ideas where this error came from.

# Answer
> 1 votes
About code...

Use `id` instead `self`:

```
game_manager.selected_square = id;

```

Use `var` for temporary variables:

```
var inst = instance_create(x, y, obj_selection);
inst.depth = -100;
inst.image_alpha = 0.6;

```

(of course, if you knowingly use it as object variable, then it's ok)

Or even something like this:

```
with instance_create(x, y, obj_selection) {
    depth = -100;
    image_alpha = 0.6;
}

```

Don't use multiple dots without braces:

```
game_manager.selected_square.x_grid;   // no
(game_manager.selected_square).x_grid; // yes

```

Other way which can be useful there:

```
var square = game_manager.selected_square;
...
var x_temp = square.xgrid;
var y_temp = square.ygrid;
var color_temp = square.color;

```

It's shorter and, as a result, more comfortable for reading. (But keep in mind, that is usable for reading, but not for change original value, i.e. `game_manager.selected_square = noone;`, but not `square = noone;`).

When statement has only one command, you can omit curve braces:

```
    with (obj_selection) {
        instance_destroy();
    }

    with (obj_selection)
        instance_destroy();

```

or even

```
    with obj_selection
        instance_destroy();

```

(GMS highlights names of objects, so it's ok for reading). Same for `if`.

Now about your problem. Possible that problem is here

```
game_manager.selected_square.x_grid;

```

but if no, then not very hard to find where is it.

Write to debug console messages in key places of the code and you will know, where the error happens.

For example, firstly you can do it inside each `if`:

```
/// Select the square or switch its place with the current selected square

show_debug_message("script 1");

game_manager = instance_find(obj_game_manager, 1);

if (game_manager.lock_timer == 0) {
    show_debug_message("1");
    if (game_manager.selected_square == noone) {
        show_debug_message("2");
        game_manager.selected_square = self;
        inst = instance_create(x, y, obj_selection);
        inst.depth = -100;
        inst.image_alpha = 0.6;
    }
    else if (game_manager.selected_square == self) {
        show_debug_message("3");
        game_manager.selected_square = noone;

        with (obj_selection) {
            instance_destroy();
        }
    }
    else {
        show_debug_message("4");
        // Lock interactions
        game_manager.lock_timer = 2;

        // Switch the array cells
        var x_temp = game_manager.selected_square.x_grid;
        var y_temp = game_manager.selected_square.y_grid;
        var color_temp = game_manager.selected_square.color;

        game_manager.grid_array[x_temp, y_temp] = color;
        game_manager.grid_array[x_grid, y_grid] = color_temp;

        game_manager.selected_square = noone;

        with (obj_selection) {
            instance_destroy();
        }

        with (game_manager) {
            event_perform(ev_alarm, 0);
        }
    }
}

show_debug_message("script 1 finished");

```

For example, you found that `4` is last message was printed. Then do same for each line of that block:

```
else {
    show_debug_message("4");
    // Lock interactions
    game_manager.lock_timer = 2;

    show_debug_message("4-1");

    // Switch the array cells
    var x_temp = game_manager.selected_square.x_grid;
    show_debug_message("4-2");
    var y_temp = game_manager.selected_square.y_grid;
    show_debug_message("4-3");
    var color_temp = game_manager.selected_square.color;

    show_debug_message("4-4");
    game_manager.grid_array[x_temp, y_temp] = color;
    show_debug_message("4-5");
    game_manager.grid_array[x_grid, y_grid] = color_temp;
    show_debug_message("4-6");

    game_manager.selected_square = noone;
    show_debug_message("4-7");

    with (obj_selection) {
        instance_destroy();
    }

    show_debug_message("4-8");

    with (game_manager) {
        event_perform(ev_alarm, 0);
    }
}

```

And see what message will be last. Next line will be your goal.

---
Tags: html5, game-maker
---


# Question
Title: How can I convert an Android game to HTML5?
How can I convert an Android game to HTML 5?

# Answer
There are some frameworks (like PhoneGap) which can build an application for multiple build targets. But only if you developed the application from scratch with that framework.

When it is a native Android application, then you can't just push a button and turn it into JavaScript. You will have to rewrite it from scratch. But porting an application from one programming language to another is usually less work than it took to develop it initially. You already solved all the problems conceptually. You just need to translate your solutions to a different language.
> 3 votes

---
Tags: android, html5
---