# Question
Title: How to get the attack animation cycle all the way through after one KeyEvent without twitching? (Java awt)
So I figured by myself (supposedly) how to make the attack animation cycle all the way through after pressing a key without needing to keep it pressed. But now it doesn't always start at the same frame index and sometimes doesn´t even complete the animation (as you will see, sometimes it does). Heres a gif of what's going on.

These go in the constructor

```
    aR = new Animation(50, Assets.aRight);
    aL = new Animation(50, Assets.aLeft);
    aF = new Animation(50, Assets.aFront);
    aB = new Animation(50, Assets.aBack);

```

I use this timer to keep track of the cooldown and also set the flag (timerFlag) that indicates the start of the attack animation to true.

```
    attackTimer += System.currentTimeMillis() - lastAttackTimer;
    lastAttackTimer = System.currentTimeMillis();
    if(attackTimer < attackCooldown){
        timerFlag = false;
        return;
    }

    if(!handler.getKeyManager().attack)
        return;

    timerFlag = true;

```

(after a little bit of code attackTimer is set to 0)

To decide what the game will render I use an int (stillLock) that saves the last direction the player faced and I have a second static flag that indicates that the animation started. (I even reset the index every time it starts just to make sure \*sadface)

```
else if(timerFlag&&!animCd){

        switch (stillLock){
        case 1:      //to attack
            animCd = true;
            timerFlag = false;
            aL.setIndex(0);
            return aL.getCurrentFrame();
        case 2:
            animCd = true;
            timerFlag = false;
            aR.setIndex(0);
            return aR.getCurrentFrame();
        case 3:
            animCd = true;
            timerFlag = false;
            aB.setIndex(0);
            return aB.getCurrentFrame();
        case 4:
            animCd = true;
            timerFlag = false;
            aF.setIndex(0);
            return aF.getCurrentFrame();
        }
    }
    else if(animCd){
        switch (stillLock){
        case 1:         //to finish attack animation
            aL.tick();
            return aL.getCurrentFrame();
        case 2:
            aR.tick();
            return aR.getCurrentFrame();
        case 3:
            aB.tick();
            return aB.getCurrentFrame();
        case 4:
            aF.tick();
            return aF.getCurrentFrame();
        }

```

And this is the Animation class where the magic happens

```
public class Animation {

private int speed, index;
private long lastTime, timer;
private BufferedImage[] frames;

public Animation(int speed, BufferedImage[] frames){
    this.speed = speed;
    this.frames = frames;
    index = 0;
    lastTime = System.currentTimeMillis();
    timer = 0;
}

public void tick(){
    timer += System.currentTimeMillis() - lastTime;
    lastTime = System.currentTimeMillis();

    if(timer > speed){
        index++;
        timer = 0;
        if(index >= frames.length){
                index = 0;
                Player.animCd = false;
        }
    }
}

public BufferedImage getCurrentFrame(){
    return frames[index];
}

public void setSpeed(int speed){
    this.speed = speed;
}

public void setIndex(int index){
    this.index = index;
}

```

}

And finally it renders like this.

```
public void render(Graphics g)
{
    g.drawImage(getCurrentAnimationFrame(), (int) (x - handler.getGameCamera().getxOffset()),
            (int) (y - handler.getGameCamera().getyOffset()), width, height, null);
}

```

I'm trully sorry for the code dump, I swear I worked hard narrowing it down only to the important stuff and being specific. Hope you can help me, I've been stuck with this for weeks... :)

# Answer
So I found the answer myself, it was actually really simple. I used a static flag to turn off the attack animation (animCd) but didn't realize other instances of Animation were running (even though attack animation was running) so it turned off before sometimes because of that. I added an extra condition so it was only turned off when they were attack animations. Hope other people find this helpful. Peace.
> 0 votes

---
Tags: java, animation, sprites, combat
---


# Question
Title: Alternative in-game dev console implementations
I'm developing a dev console for my game. Currently I have a simple parser which is basically a regex which accepts words with dashes and dots (ie. `list`, `1.0`, `list -i`) or simplistic arrays and maps (ie. `[1,2,3]`, `[x:1.0, y:2.0]`). I plan on making an AST parser later on but for now this works well enough.

When these tokens get parsed first token in parsed line is the *command* token which is used to invoke a registered command. Commands are classes which implement a `ConsoleCommand` interface which looks like this (basic command pattern):

```
interface ConsoleCommand {
    val description: String
    val instructions: String
    fun execute(args: Array<Any>): String
}

```

This works, but I'm not quite satisfied since to actually register any console commands I must do so where I can access the entity. For example if I want to register the player as an interactable console command I must do so either in a custom system only created for the specific console command, or add console specific code into existing systems, basically polluting my codebase with console specific code.

My question here is what are alternative dev console implementations? Is there a way to implement a console which wouldn't affect the rest of the codebase?

I have an inkling of an idea where the console could be some sort of an observer and it itself would register onto entities and stuff, but I don't see a way of implementing that without having the entities implement some sort of special observable interface so that they can actually be observed, as well as the fact that `observers` usually don't manipulate the entities themselves....

# Answer
> 4 votes
Use your integrated script engine, if you have one.

The console just provides a place where you type lines of code and prints output from scripts. No need for a new parser. No need for a new command system. No need for a custom logging/response framework.

You can often configure such scripting languages to have a custom "global context" for the console that controls which global variables exist. For instance, you might set the global object to use configuration keys as globals, so changing a setting is as easy as typing `fullscreen=1`. Likewise, you can automatically print the value the previous statement for languages with those semantics so that printing output is as easy as typing the variable name or calling a function.

Some languages have syntaxes that are especially friendly to these uses. Lua or JavaScript for instance are strong choices. Some languages even let you call functions without parenthesis so you type `spawn "orc"` instead of `spawn("orc")` if such things matter to you.

You can even do help systems easily in many languages. E.g. if the result of an expression is a function, print the `documentation` attribute attached to the function object. If an exception is thrown, you can inspect it to see which function is at the top of the stack, and extract attributes from it.

# Answer
> 0 votes
I may not be understanding your question correctly, but my interpretation is as follows:

* You have an ECS-type engine implemented in some form
* Your entities can be interacted with via your dev console
* You're trying to about having the console handling code strewn about randomly through your systems

My suggestion would be to add another layer of abstraction, a system that is higher level than your main subsystems (rendering, collision, etc.), and serves only to dispatch lower level messages to your entities through your usual messaging means. This doesn't really need to be a true part of your ECS, but it should do something like:

* Allow your dev console to access a list of entities purely for dispatch (query your EntityManager if you have one?)
* Store a list of Console commands (Command pattern)
* Accept messages from your dev console (e.g, ConsoleCommandMessage (command,args))
* Your ConsoleCommand object stores how the command is converted into lower level system messages, and your ConsoleSystem is responsible for dispatching those commands to the lower level systems

Based on the specifics of your implementation, you could reduce the coupling purely to the ConsoleSystem, instead of to all of the other systems in your codebase. Systems could even register their own ConsoleCommands as they're available.

Again, I'm unclear if you've already considered and ruled out this approach, but I would expect it to be a lot cleaner than the sort of coupling you're trying to avoid. You'll have to do the coupling -somewhere- in order to interact with entities, and a higher level system would let you keep that encapsulated in one spot.

# Answer
> 0 votes
It's easier if we look at a concrete example: telling the player to fire their weapon, via the console. To do this, the console needs to be able to:

* Find a player (say, by entity id)
* Tell that player to fire

But really, this is no different to what an input handler (press X to fire) or, if your player is AI-controlled, an AI routine, needs to do. Therefore if you know how to decouple these systems, you can treat the console the same way.

Two patterns helpful for this is the observer pattern or an event queue. These abstract away game entities (like players) from things that might need to access their state, or send them commands. There's no reason why your codebase needs to be polluted with console code, any more than input handling code pollutes player code, or achievement code pollutes physics code.

The only difference is that the console is sort of a global system, unlike say an input handler which is associated with one particular player. Therefore your console needs access to the global game state, so that it can see and command any game entity.

---
Tags: architecture
---


# Question
Title: How can I create a 2D "gooey"/"sticky" separation effect?
I want to create an effect similar to this animation where two shapes separate over time but are connected (for a time) by something gooey that stretches and eventually breaks. Like pizza cheese, but *specifically* in 2D.

I'm using Swift and SpriteKit. I'm thinking this probably involves keyframes bezier path animations, but I'm not sure. How can I achieve this effect?

# Answer
One way to do it using simple 2D transforms is to have multiple sprites to create each strand, which seems like how your example does it. Using separate colours, it might look like this:

And as the pizza stretches, make the strand (yelow) and the connectors (blue) thinner:

The advantage of this is that you can individually animate strands getting thinner and snapping.

There are other approaches that could work too, like faking it with a single, textured sprite that stretches, or traditional, frame-by-frame animation. It depends on how much work you want to do, and how realistic and adaptive you want it to be.
> 1 votes

# Answer
You could try to create few attachment points on your sprites and define a line between the two you want to stick and create a couple attachment points along that line, then connect the dots with a sticky barbell-like sprite.
> 0 votes

---
Tags: animation
---


title: How can we test a section of a game?

text:
# Question
Title: How can we test a section of a game?
I'm making a clone of an old atari 2600 game, so it's simple, only slightly more complex than the original.

I'm realizing that even the simplest of games have different "parts", what is a good design method to be able to test those sections without having to "play through" to that part?

Specifically, (it's a "breakout" clone) if I'm modifying and testing code that runs when the game is beaten, I don't want to have to play through the whole game just to see if my code works. I can only imagine how complicated this kind of testing is for a game of substantial size.

How do real devs make their game such that they can test just a certain section, or test a section under certain possible in-game circumstances without having to play through to that part?

# Answer
> 3 votes
They have console commands.

There is a reason skyrim has all the commands in it. That game was very extensibly tested. And because it has couple hundred hours of content with every cave and guild, and some of this content is bound to a level, there is no way to make everyone play through everything.

Do the same, create some commands whivh put you on an entered level, one which destroys every block, etc.

You of course don't need to keep it in the game when you release it. Some games do that to make players be able to ppay around with the game a bit more.

# Answer
> 2 votes
A bad development team would hire a bunch of QA staff (testers) to play the game over and over again, reporting bugs into an ever vacuous database. Even with the aid of console commands this is an expensive and slow process, and **not** what you should be using a QA team for. The testers should be exploring edge cases and pushing the game to its logical limits, not validating your own wobbly code you couldn't be bothered to test.

A studio with solid development practices will write automated tests that run every time they check in new code. This allows certainty that new changes don't break previous functionality. With projects as vast as the ones you find in game development this is the only way to confidently deliver a functioning product. Not following these practices is what leads to crunch, and crunch kills good developers. In today's modern age of games like Overwatch or Dota 2 that have to be maintained and altered consistently after release it's the only way to iterate a product sustainably.

The answer is to automate as much testing as you can. In your case write a helper method that destroys all the blocks and then engineer a test that executes this and validates the win conditions are being satisfied. If this is difficult to test in your environment then it's potentially a sign your current code is too coupled and could do with some abstracting.

---
Tags: architecture, actionscript-3, testing
---


title: How to use JWT in unity

text:
# Question
Title: How to use JWT in unity
Is it possible to use JWT in my unity games?

I've read here that JWT needs .NET version 3.5+ and in Unity 5.4.1f1 the .NET version is "2.0.50727.1433". Is this information correct or incorrect?

If it is incorrect, can anyone point me to the right direction as to how I would go about implementing JWT in C#?

Sorry if I made any mistake, I'm completely new to JWT

# Answer
afaik unity isn't currently capable of running on microsoft's own .NET framework, but rather uses mono an open clone of .NET

The version number you mentioned is the mono runtime version.

That version is roughly compatible with .NET 3.5

Whether or not you can run JWT will thus depend on whether you can compile and run the library you need on mono.

if there isn't any library that can actually decode / encode JWT requests and compiles / runs in mono, you'll have to write your own.

::update::

Looks like someone has done exactly that

https://github.com/monry/JWT-for-Unity
> 1 votes

---
Tags: c#, .net, json, authentication
---


title: LibGDX - change actor's texture

text:
# Question
Title: LibGDX - change actor's texture
Is there a way to change actor texture without creating a new object?

I want to change my `ImageButton` texture when `resize()` is called, and for example for `screen > 800px`, `ImageButton` have bigger texture, and if `screen <= 800px`, `ImageButton` have smaller texture?

Now when I'm increasing my window size, `ImageButton` is scaling up but quality is bad so I want to load bigger texture.

Thank you for help.

# Answer
> 1 votes
You have to change it in `ImageButton`'s style and convert your `Texture` to `Drawable` using `TextureRegionDrawable`:

```
// load your texture:
Texture newImage = new Texture(Gdx.files.internal("biggerImage.png"));

// get button's style
ImageButtonStyle style = myButton.getStyle();
Drawable drawable = new TextureRegionDrawable(new TextureRegion(newImage));
style.imageUp = drawable;
style.imageDown = drawable;

```

Done!

@Edit

`new TextureRegionDrawable` won't allocate memory, because we pass an existing 'newImage' texture to it's constructor, BUT - it's a bad programming practice to make objects in places like `render()`, `resize()` etc. To do this right, declare two `Textures` at the start of your screen, big and small one, declare two `Drawables`, also at the start and load them via new `TextureRegionDrawable` and then in `resize()` put only:

```
if(screenSizeIsBig){ // your condition for big screen size
    style.imageUp = bigDrawable;
    style.imageDown = bigDrawable;
}else{ //
    style.imageUp = smallDrawable;
    style.imageDown = smallDrawable;
}

```

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


title: Möller-Trumbore false positive

text:
# Question
Title: Möller-Trumbore false positive
I've implemented the Möller-Trumbore algorithm but I hit some false positive:

```
Ray: vec3(2.100000, -1.000000, 3.314214), vec3(0.685786, -1.000000, 1.900000)
Collide with: vec3(1.000000, 1.000000, -0.999999), vec3(0.999999, 1.000000, 1.000001), vec3(1.000000, -1.000000, 1.000000))
uvt=vec3(0.435307, 0.198000, -1.603999)

```

If I draw the collision, I see clearly that the ray does not intersect with the triangle.

From this site: http://www.scratchapixel.com/lessons/3d-basic-rendering/ray-tracing-rendering-a-triangle/moller-trumbore-ray-triangle-intersection I wrote this code:

```
bool Node::rayIntersectTriangleDebug(const glm::vec3 orig, glm::vec3 dir
                       , const glm::vec3 vert0, const glm::vec3 vert1, const glm::vec3 vert2
                       , glm::vec3 &result)
  {
    //dir = glm::normalize(dir);

    const glm::vec3 edge1 = vert1 - vert0;
    const glm::vec3 edge2 = vert2 - vert0;
    const glm::vec3 pvec = glm::cross(dir, edge2);
    const float det = glm::dot(edge1, pvec);

    const float Epsilon = std::numeric_limits<float>::epsilon();

    if (det > -Epsilon && det < Epsilon)
      return false;

    const float invDet = 1.0f / det;

    const glm::vec3 tvec = orig - vert0;

    result.x = glm::dot(tvec, pvec) * invDet;
    if (result.x < 0.0f || result.x > 1.0f)
      return false;

    const glm::vec3 qvec = glm::cross(tvec, edge1);

    result.y = glm::dot(dir, qvec) * invDet;
    if (result.y < 0.0f || result.x + result.y > 1.0f)
      return false;

    result.z = glm::dot(edge2, qvec) * invDet;

    const float abs = std::abs(result.z);
    const float dist = std::abs(glm::distance(orig, dir));

    const glm::vec3 intersection = vert0 + result.x * edge2 + result.y * edge1;

    if (abs < dist)
      {
         return true;
      }
     return false;
  }

```

Also I'm not sure if I have to normalize my direction vector.

EDIT

I've red here that

> I'm not sure if it should be normalized or not, but tests I've conducted over a normalized version yelded valid results

I've tried to normalize my direction with the following code without success:

```
const glm::vec3 dir = glm::normalize(officialDirection - orig);

```

# Answer
I though that the vector t could be positive if the ray faced the triangle or negative if the ray was in the back of the triangle but this is *not* true. It's positive if you are hitting the triangle and negative if not.

Here is the working implementation:

```
  bool Node::rayIntersectTriangleDebug(const glm::vec3 orig, const glm::vec3 dir
                       , const glm::vec3 vert0, const glm::vec3 vert1, const glm::vec3 vert2
                       , glm::vec3 &result)
  {
    const glm::vec3 edge1 = vert1 - vert0;
    const glm::vec3 edge2 = vert2 - vert0;
    const glm::vec3 pvec = glm::cross(dir, edge2);
    const float det = glm::dot(edge1, pvec);

    static const float Epsilon = std::numeric_limits<float>::epsilon();

    if (det > -Epsilon && det < Epsilon)
      return false;

    const float invDet = 1.0f / det;

    const glm::vec3 tvec = orig - vert0;

    result.x = glm::dot(tvec, pvec) * invDet;
    if (result.x < 0.0f || result.x > 1.0f)
      return false;

    const glm::vec3 qvec = glm::cross(tvec, edge1);

    result.y = glm::dot(dir, qvec) * invDet;
    if (result.y < 0.0f || result.x + result.y > 1.0f)
      return false;

    result.z = glm::dot(edge2, qvec) * invDet;

    const float abs = std::abs(result.z);
    const float dist = std::abs(glm::distance(orig, dir));
    const glm::vec3 intersection = vert0 + result.x * edge2 + result.y * edge1;

    if (result.z < Epsilon)
      return false;

    /* Convert the barycentric coordinate to wold Cartesian ones: */
    //const glm::vec3 intersection = vert0 + result.x * edge2 + result.y * edge1;

    return true;
  }

```

This implementation works and does not need to have a normalized direction. I convert barycentric coordinate to wold position with this formula:

```
const glm::vec3 intersection = vert0 + result.x * edge2 + result.y * edge1;

```
> 0 votes

---
Tags: c++, collision-detection
---


title: Why bind only first attribute?

text:
# Question
Title: Why bind only first attribute?
I'm create OpenGL renderer, but when I bind vertex attributes I can attribute only first attributes. Where I got error? My code:

```
Mesh::Mesh(Shader &shader, int size, GLuint *indices) {
    shaderProgram = &shader;
    _meshLenght = size;

    glGenBuffers(1, &_ebo);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _ebo);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices)* sizeof(GLuint), indices, GL_STATIC_DRAW);
}

void Mesh::AddDataPointer(GLchar *name, const GLvoid *data, GLenum type, GLint size) {
    GLint variableLocation = glGetAttribLocation(shaderProgram->GetProgram(), name);
    if (variableLocation == -1) {
        std::cerr << "Variable does not exist, or it name began with prefix gl!" << std::endl;
        return;
    }

    GLuint vBuffer;
    glGenBuffers(1, &vBuffer);
    glBindBuffer(GL_ARRAY_BUFFER, vBuffer);
    glBufferData(GL_ARRAY_BUFFER, sizeof(data)*sizeof(GLvoid*), data, GL_STATIC_DRAW);
    glBindBuffer(GL_ARRAY_BUFFER, 0);

    GLuint vertexArray;
    glGenVertexArrays(1, &vertexArray);
    glBindVertexArray(vertexArray);
    glEnableVertexAttribArray((GLuint) variableLocation);
    glBindBuffer(GL_ARRAY_BUFFER, vBuffer);
    glVertexAttribPointer((GLuint) variableLocation, size, type, GL_FALSE, 0, (const GLvoid *) 0);
    glBindBuffer(GL_ARRAY_BUFFER, 0);
    glBindVertexArray(0);

    VertexData vertexData = {
            vertexArray,
            data,
            type};
    _variables.insert(_variables.end(), vertexData);
}

void Mesh::Draw() {
    for (auto const& value : _variables) {
        glBindVertexArray(value.location);
    }
    if (_ebo==0)
        glDrawArrays(GL_TRIANGLES, 0, _meshLenght);
    else {
        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _ebo);
        glDrawElements(GL_TRIANGLES, _meshLenght, GL_UNSIGNED_INT, 0);
    }
    glBindVertexArray(0);
}

```

# Answer
> 1 votes
You aren't using `vertexArray` correctly. There should only be 1 per object

```
Mesh::Mesh(Shader &shader, int size, GLuint *indices) {
    shaderProgram = &shader;
    _meshLenght = size;

    //create one here
    glGenVertexArrays(1, &_vao);
    glBindVertexArray(_vao);

    glGenBuffers(1, &_ebo);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _ebo);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices)* sizeof(GLuint), indices, GL_STATIC_DRAW);
    //vao also stored the GL_ELEMENT_ARRAY_BUFFER binding

    glBindVertexArray(0);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
}

void Mesh::AddDataPointer(GLchar *name, const GLvoid *data, GLenum type, GLint size) {
    GLint variableLocation = glGetAttribLocation(shaderProgram->GetProgram(), name);
    if (variableLocation == -1) {
        std::cerr << "Variable does not exist, or it name began with prefix gl!" << std::endl;
        return;
    }

    GLuint vBuffer;
    glGenBuffers(1, &vBuffer);
    glBindBuffer(GL_ARRAY_BUFFER, vBuffer);
    glBufferData(GL_ARRAY_BUFFER, sizeof(data)*sizeof(GLvoid*), data, GL_STATIC_DRAW);

    //bind here
    glBindVertexArray(_vao);
    glEnableVertexAttribArray((GLuint) variableLocation);
    glVertexAttribPointer((GLuint) variableLocation, size, type, GL_FALSE, 0, (const GLvoid *) 0);
    glBindBuffer(GL_ARRAY_BUFFER, 0);
    glBindVertexArray(0);//unbind

    VertexData vertexData = {
            vBuffer,
            data,
            type};
    _variables.insert(_variables.end(), vertexData);
}

void Mesh::Draw() {
    glBindVertexArray(_vao); //bind again for draw

    if (_ebo==0)
        glDrawArrays(GL_TRIANGLES, 0, _meshLenght);
    else {
        glDrawElements(GL_TRIANGLES, _meshLenght, GL_UNSIGNED_INT, 0);
    }
    glBindVertexArray(0);
}

```

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


# Question
Title: What are the main questions you have to clarify in terms of Game Design before starting development?
I am looking for a list of questions that helps me to get my idea to a clear game vision. I heard and read about "world book" or "game bible" - a document where everything is documented. But what is **everything**?

Even at Udemy are no courses that take care of the pre production process of game development. Since I am a lead dev and project lead in online products, I might have a clue how to develop products - but that is kinda different to games.

So is there a check list game designers use to see if their idea is good/bad? I know I could start with pen and paper before I do anything digital - but that still does not help me to know what is important to prove my idea.

# Answer
> -1 votes
I would say this is a fairly opinion-based question, and a mod may elect to close it as off-topic for this site, but since I'm not a mod, I'll give it a shot anyway:

* Setting (places, overarching themes, level of realism, etc.)
* Core Mechanics (what do you want players of your game to -do-? very high level, e.g, for a game like Borderlands, it might be, "Complete quests while finding tons of awesome loot")
* Character sketches (high level ideas for what characters you may want to incorporate)
* Quest/Plot ideas (high level ideas for things the characters will see/do)
* Storyboarding/high level progression ideas (how does the game progress? are there forks in the playthrough? etc.)
* Art direction ideas ("realistic appearance", "cartoony", etc.)
* Sound ideas ("Should feel like {music genre/band examples", etc.)
* Single player or Multiplayer?
* Online or Offline?
* Number of players, if multiplayer
* Overarching project plan (is it a self-contained game? Do you need modding support? etc?)

...basically, it should be a reference for you/your team, to track, consider, brainstorm, and ultimately, make key choices about the game. It's not really about subscribing to a specific philosophy/mechanism for this information, but rather, putting it all down in a way that makes sense to -you-/-your team-.

I would say, the main questions to ask yourself about whatever approach you choose, would be:

* Does this keep me focused on what I -really- want the game to be?
* Can I understand the format it's in, and can my team?
* Can I easily track/note changes to the scope, concepts, etc.?
* Is it in a format I'm inclined toward keeping up to date?

Personally, I use notes on my Blackberry for this, but what you track, and how you track it, depends on what's important for -you-, as the project lead/designer.

---
Tags: game-design, pre-production
---


# Question
Title: Do any games have this type of mechanic?
This question got closed on gaming SE as off topic. I hope it's on topic here.

Many years ago, a friend and I prototyped a simple 2d rpg with what we thought was a unique idea for the combat mechanics. It used wandering monsters and a cutaway battle screen system. We added a bunch of effects like "conditions" that could affect your player - the standard stuff like blind, dazed, weak, etc.

The unique part is that we wanted to make the combat as close to you, the player actually fighting, and not just you commanding a character to do stuff. So we made it so what the character experiences, you experience. The basic combat screen included an outline of the enemy, and one of you. At randomized times, targets would appear on either figure, and begin to shrink. On the enemy, these were "openings" and you had to click them before they disappear, the closer to center, the better the hit. On your figure, you had to click to defend from an attack before the target shrank.

The conditions on your character made this interesting. Like I said, they were intended to affect the player literally. So blindness literally dimmed the screen 90%. If you were dazed, the targets would wobble randomly. If you were weak, your mouse cursor would lag and glide around. Everything translated to an actual impairment in your gameplay, not some arbitrary "your attacks do half damage".

This would have logically extended into a spell system, where you actually have to remember spell words and combine them into creative combinations and type them real time. I know some games have done variants of this kind of spell system.

Looking back, I think this was still a fun idea, but it seems awful from an accessibility standpoint. Players like their games to make them feel powerful, not to acknowledge and emphasize their real life flaws. So have any games attempted something like this and had some success? What came of it? If not does it seem like a reasonable and creative idea to try?

# Answer
There's been similar stuff in various games, where you character becomes harder to control when you're drunk or on drugs (GTA3 et. al.), where aim stability is affected by experience/etc and also where the screen display is severely affected by different things (many RPG-FPS:es has this).

I suggest you research that and see if it makes for a good gameplay component. It will make users be frustrated if done improperly, so careful tuning is required.

Usually challenging, but overcome-able (...) gameplay mechanics are good. So a dim view, or laggy/overshooting (but predictable) mouse pointer may work well, but be careful with randomness. Game outcome based too much on chance aren't that fun (for most of us at least, some people enjoy bingo... but these rarely buy videogames).

Personally, I enjoy "bad control" or "random jittery targets" as an occasional change to the regular gameplay, but I don't think I'd enjoy having it as a core gameplay feature.
> 9 votes

# Answer
In roguelikes, blindness makes your character disappear (so you don't know where you are, unless you're counting steps) and confusion makes him move in random direction. In Morrowind (and I think other Elder Scrolls games) blindness made the screen totally black. A lot of games where bow is used make crosshair wobble when the bow is tightened for too long (Thief did that, for example). Many games that have booze in them made screen wobble when the character is drunk (GTA, Deus Ex); Carmageddon had drugs that messed with the palette, transforming the picture into a mess of clashing colors. Metro 2033 makes mouse cursor lag when your character is under heavy burden. Note that many players considered this a bug and were very frustrated!

However, I'm not aware of any game where this stuff was a central mechanic. It might be interesting if the effects are varied enough and not TOO challenging.
> 7 votes

# Answer
Look out for Nintendo DS titles. They tend to use the stylus for game mechanics similar to yours.

There are rhythm games like Elite Beat Agents employing something similar to your attack/defend game mechanics but based on music. Elite Beat Agents is actually quite challenging but fun to play.

I'd also recommend playing The World Ends with You! It's an action RPG with very similar combat mechanics. It's also quite innovative and unique.

Regarding crippling the player (controls) I'd always advise not to. I haven't seen a single game where not-being-in-control due to darkness, staggering, impairing effects, etc. was adding fun. Realism != Fun != Immersion.
> 4 votes

# Answer
Something to that extent is certainly nothing I've heard of before. However, you should be *careful* when implementing it. The number one thing players expect from their game is control. Actions or sequences that remove control from the player are the most universally derided gameplay mechanics. A player expects to have complete and total control, within interface limitations.

It would certainly be an interesting idea, and objectively a great mechanic, but I think you'll find that in reality, human players will hate it.
> 3 votes

# Answer
Carmaggedon had some psychadelic colors on the screen and the camera moving everywhere when taking a drug power up.

RPG like Bladur's gate also reduce the player's field of vision by increasing the 'fog of war' when you're blinded. (the interface is not affected though...)

Anyway, how would this system work when you cast a blind spell on a computer controlled enemy for example? You would need different impairing rules for the AI.
> 3 votes

# Answer
> Magicka

has been able to deploy active spellcasting and succeed.

Obviously you can't type actual words with 1 hand so you do combinations.

The earliest active casting i can think of is

> WC3: Dota - Invoker hero. It was a successful character as well - even imbalanced as his adaptability is very high.
> 0 votes

# Answer
Wildstar, an MMORPG, has such mechanics too (blind = dark screen, confuse = inversion of commands).

Well done, such mechanics can work even on highly competitive environnements like hardcore MMO raiding scene.
> 0 votes

# Answer
Excluding your targeting allusion, a very good example of effects impacting your player in the scope of a first-person RPG is Borderlands (any of the games).

In Borderlands, any elemental proc damage that impacts the player, does so with a visual HUD effect, as well as a tangible impact on play. For example, with incendiary damage, if you get caught on fire, your screen fills with flames (similar to if you were wearing the flame suit Till from Rammstein wears on stage), and your character takes constant DoT from the fire. This also impacts your ability to aim, due to the proc effect.

Weapons/quest items that cause more obscure effects like drunkenness have a notable effect on your accuracy of firing your weapon, and directly impact your aiming ability.
> -1 votes

---
Tags: game-design, game-mechanics
---


# Question
Title: What is the specific name of this UI component?
Is there a specific name for this kind of ui component? Sometimes it only renders a symbol (without text) so using name like `TextComponent` is imo not very fitting.

# Answer
> 6 votes
Not formally, but I usually see them referred to as "damage floaters." In the occasions where they do not actually convey damage, they're usually called "*some other kind of* floater," or just "floaters."

Et cetera. You can find several other references via Google searches (I'd recommend you include the term "UI" in the search though; otherwise you tend to get a lot of results about retina detatchment and such, which are decidedly unrelated).

---
Tags: gui, terminology
---


title: Smooth Lighting Falloff

text:
# Question
Title: Smooth Lighting Falloff
So, I'm having some issues with lighting in my Unity game. I had implemented torches, which seem to be working fine, but I have a creature (gelatinous cube) that I've put spot lights facing to give it a "glow". The reflected and refracted light ends up having two issues:

1. the light abruptly ends at the edge of floor tiles, and
2. depending on the position, the light sometimes goes from it's blue color to a reddish color.

I have a short (11 second) video here: http://www.labyrintheer.com/wp-content/uploads/2016/11/Nov-17-2016-21-07-57.mp4 so that you can see what I'm talking about. I've tried changing global lighting settings and playing with the settings on the spot lights, but nothing seems to resolve the issue.

Still images for anyone hesitant to click the video link:

Hard falloff:

Reddish color:

Using a single point light inside the cube, instead:  You can see it on the wall in the upper right and the floor at the top a bit. The upload seems to have lowered the quality a bit, but you can still see it. The single light makes it a *little* bit better, but there's still complete falloff.

# Answer
> 1 votes
It may have to do with your number of per-pixel lights. If you have too many, Unity will fall back to per-vertex lighting for some lights instead. Try increasing the number of per-pixel lights in quality settings (which can be costly).

Ideally you should change the way you light the scene so you don't need a lot of per-pixel dynamic lights. Six spotlights for one object seems really excessive.

You could also consider using deferred shading if it works with your target platforms, as it lets you use unlimited per-pixel lights.

---
Tags: unity, 3d, lighting
---


# Question
Title: Fragment shader coordinates: Displacing pixels and texCoord problems
I'm trying to create a shader that creates a displacement on an object, slicing horizontally the sprite.

These is an example of the atlas I'm using and the effect I'm trying to achieve:

I tried to achieve this creating a fragment shader, that would read the Y coordinate of the texcoord, and depending on the height, displace it horizontally.

But I found two main problems:

1) If my atlas had more rows of sprites, I can't really tell at what height I'm drawing the sprite in the fragment shader. Since values of texcoord go from 0 to 1 relative to the atlas being use, the more rows I have, the smaller values should I choose to create the horizontal cut. Is there any way to know the position inside the drawn?

2) The problem is similar to the previous point. When displacing the pixels horizontally, if the displacement is too big, I end up sampling the sprite next to the one being rendered. The idea is for it to loop back the the begining of the sprite. If I had the width of the sprite, I could tell how to do so, but using texcoord alone is just not posible. How can I do this?

# Answer
> 1 votes
Easiest way to do this is to not use a packed sprite and instead use a plain unpacked texture so you can wrap-around using the texture samplers directly.

---

That said, UV displacement in the pixel shader (called a "**dependent texture read**") is costly on any GPU, it's best to avoid it when you can especially on mobile.

Slicing and sliding the sprite on the CPU by generating geometry could be much faster than having the GPU do it if those sliced sprites cover a large part of the screen.

A 1Ghz mobile CPU can generate 3 "quads" (3x 2 triangles) of geometry to avoid a displacement shader much faster than a 500Mhz mobile (or integrated) GPU will spend having to process all those pixels causing dependent reads in a displacement shader.

---
Tags: unity, shaders, fragment-shader
---


# Question
Title: How to work out the height of a point on a tilted surface?
I have a plane which gets tilted on the X and Z axis (y+ is the normal).

Given an X and Z coordinate and the X and Z rotation of the plane, how do I find out the height (Y) at that point?

I assume this is a trigonometry question... I could use simple sin & cos to work it out if it was moving on just the X or Z axis, but what if it's at 3,8 (x,z)? Maybe an average of the sin/cos heights?!

# Answer
> 1 votes
Assuming your plane passes through the origin, then it can be defined in terms of its normal vector as the set of all points perpendicular to the normal, ie.

```
dot(position, normal) = 0

```

Here your normal is the object's local y-axis, `transform.up`.

So you want to find a coordinate triple `(x, y, z)` perpendicular to `transform.up`. We can solve:

```
dot((x, y, z), transform.up) = 0
y * transform.up.y + dot((x, 0, z), transform.up) = 0
y * transform.up.y = -dot((x, 0, z), transform.up)
y = (-x * transform.up.x - z * transform.up.z)/transform.up.y

```

And now we have an expression for `y` in terms of `x` & `z`, without using any transcendental functions, just ordinary multiplication subtraction and division. :)

# Answer
> 0 votes
Ah - looks like you just add them together!

```
float angX = Mathf.Sin(Mathf.Deg2Rad * transform.eulerAngles.z);
float angZ = Mathf.Sin(Mathf.Deg2Rad * transform.eulerAngles.x);

foreach(GameObject item in GameObject.FindGameObjectsWithTag("Fart")) {
  float yx = fart.transform.position.x * angX;
  float yz = fart.transform.position.z * -angZ;
  item.transform.position = new Vector3(item.transform.position.x, (yx + yz), item.transform.position.z);
}

```

---
Tags: physics, mathematics, rotation, trigonometry
---


# Question
Title: Unity3d Rigidbodies overlap even at low speeds
I have an issue that I can't solve. There are many questions relating to similar issues and they come down to "*change some settings*" and "*object is travelling too fast*". My problem doesn't seem to equate to either of these.

I am running through the basic tutorial for the Breakout Game and have added some of my own tweaks to the code, my issue is that even at low speed my ball overlaps with the bricks, rather than bouncing off them.

I have read various related questions but nothing seems to fix this for me.

Things I've done:

* Set Project Settings \>\> Physics2d \>\> Maximum penetration For Overlap = 0.0001
* Set Ball RigidBody Collision detection to "*Continuous Dynamic*" .
* Set Brick RigidBody Collision Detection to "*Continuous*"
* Forced a speed limit on the ball of ~~25~~ **15**. Which I think is not fast at all, as most the given solutions are talking about situations arising when the offending object is travelling at much higher speeds.
* Bricks are standard rigidbody cubes and ball is a standard rigidbody sphere.
* According to this answer I have also set the rigidbody interpolation to "interpolation" for both ball and bricks. But this seems processor expensive and doesn't solve the issue.
* As well as set the Project Settings \>\> Physics \>\> Solver Iteration Count to 25. This does seem to have helped somewhat (ball no longer gets "stuck" inside brick wireframes, but still overlaps).

Below are some screenshots of my issue and my code.

The only aspect that I can't fully account for is that I've added an acceleration function so when ball is launched it accelerates over a course of several seconds to it's max speed. It's start speed is 8 (although the force applied is actually 1000 when launched, ignore that figure), and the max speed is set to ~~25~~ **15**. I don't know enough to say if this is somehow "breaking" rigidbody overlap detection but it seems pretty silly if so. See line 63 below:

**Ball Source Code:**

```
using UnityEngine;
using System.Collections;

public class Ball : MonoBehaviour {

    public float initialVelocity = 500f;
    public float accelerationSpeed = 5f;
    public float MaximumSpeed = 15f;
    private Rigidbody rb;
    private bool ballInPlay = false;

    void Awake () {
        rb = gameObject.GetComponent<Rigidbody>();
    }

    void Update () {
        if (Input.GetButtonDown("Fire1") && ballInPlay == false)
        {
            transform.parent = null;
            rb.isKinematic = false;
            rb.AddForce(new Vector3(initialVelocity,initialVelocity,0));
            ballInPlay = true;
        }
    }

    void FixedUpdate ()
    {
        /***
         * Gradually increase ball speed
         ***/
        if (ballInPlay == true && rb.velocity.magnitude < MaximumSpeed)
        {
            speedUp();
            Debug.Log("Ball Speed is "+rb.velocity.magnitude);
        }

        /***
         Clamp to maximum speed
         ***/
        if (ballInPlay == true && rb.velocity.magnitude > MaximumSpeed)
        {
            rb.velocity = rb.velocity.normalized * MaximumSpeed;
        }

    }

   //     rb.velocity.magnitude

    void speedUp()
    {
        /***
         This is line 63:
         ***/
        rb.AddForce(rb.velocity.normalized * accelerationSpeed,ForceMode.Acceleration);
    }

}

```

**Why are the rigidbodies not detecting and preventing overlap?**

# Answer
First - you don't need SpeedUp(); - your rigidbody on the ball has no angular drag and no drag, they are 0. Also you could change Friction to 0 in physics material. Your ball won't lose speed.

Second - check if your bricks have box collider on them and it's not trigger. Also you can remove rigidbody from your bricks if they don't move using Physics. It will give you better performance. Only 1 body that is colliding can have rigidbody to detect collisions - no need for other bodies to have rigidbody.

I would have left this answer in comments if I had more than 50 points - I'm just not allowed to do so now.
> 1 votes

---
Tags: unity
---


title: How to join two cubes?

text:
# Question
Title: How to join two cubes?
If I want to make a character (in Blender) made of cubes, to export it to unity later, should I leave these cubes and all the other body parts as separate objects, or join them all into one mesh?

And, If I should join them - is it a good idea to leave the cubes elements inside of each other?

Or I should remove them, add some loops and connect the vertexes?

In the last case it will be difficult to keep the cubes surfaces flat, because of the vertex shifting during joining.

# Answer
Ultimately, you can take whichever option suits you best, personally. You would easily get away with either.

### Leaving the Cubes Separate

If you do not join the cubes, they should import into your scene as separate objects, grouped under a parent object to represent your character. This is fairly easy to run with, but there *are* considerations you should make:

* If you automatically generate box collider's, remember that your boxes collide, internally. If you treat each collider separately, you will likely constantly trigger `OnCollisionEnter()` or `OnTriggerEnter()`. If you do use `OnCollisionEnter()`, this will likely result is your object breaking apart. The best solution would be to use a single collider on the parent object to cover all internal parts.
* Ensure you transform the object by the *parent*, and not by any internal *children*, or you will change the way that object appears.
* When you transform the parent, ensure that this does not have a weird offset impact on the internal objects. This should not be an issue with *translation* and *rotation*, but I have seen cases where *scaling* similar parent objects resulted in using the individual centers of each child object, instead of scaling everything in to/away from the center.

### Joining the Cubes

Joining the cubes as you detail should work pretty good. You say the vertex won't be straight after the merge, but it should not be particularly noticeable. Just as before, you still want to make some considerations:

* Now, you *will* have a single game object. If you had *intended* to use multiple box collider's for whatever reason, remember that you can only hold *one* collider component per game object. A workaround would be to store additional colliders as empty children game objects. Ultimately, you should probably just use the same model as a *mesh collider*. In fact, if you go for option A (multiple internal objects), you could use this version as a single mesh collider.
* Naturally, we lose the ability to directly transform the individual boxes. If you should want to do this, for any reason, you should not merge them before importing.
> 2 votes

# Answer
If you generate box collider's on empty objects with shape of these boxes, and your scripts are on a parent of 2 objects that have these colliders, any of these colliders will trigger OnCollisionEnter() method, so don't worry about it, just remember to parent them to 1 object.

Remember to set a pivot where you want - it will influence scaling.

If this mesh is one whole part and it those objects won't be controlled by separate scripts, you can of course join them together, but the question as I see was about - which way is the best practice. To answer this I should say that number of triangles matters. It's always better if there are less triangles, but the look of the model doesn't change. That is why Normal maps are used.

In case not merging them gives you less triangles, it's better to leave them inside each other.

But in case you need to merge I suggest you use boolean modifier that merges meshes automatically, also I would recommend to install boolean add-on - that is better from standart boolean modifier. Of course you can merge them manually (and sometimes it is better - if you can do this without losing the proper shape of the model).
> 2 votes

---
Tags: unity, models, grid, 3d-modeling
---


# Question
Title: How to save a text file to relative Path
I'm creating an app that should be accessable from every platform (android, IOS, windows). At this moment I'm saving a file that is set to a specific path. c:\test\test.exe. Now I know that Android and IOS don't have such directory. I was wondering if it was possible to save the file to a relative path? If not I might have to adapt the code that checks on what kind of device the app is running

psuedocode:

If runningOnWindowsOS writefile(c:\test\test.txt)

if runningOnAndroid writefile(NOCLUE)

If runningOnIOS writefile(NOCLUEEITHER)

this is my code at the moment:

```
        string path = @"C:\test\test.txt";

        string createText = txt3.text + txtToLog + System.Environment.NewLine;

        File.WriteAllText(path, createText);

```

any clues on how to proceed with this

# Answer
Utilize Unity's `persistentDataPath`.

> Contains the path to the game data folder (Read Only).

This is path is platform specific.
> 1 votes

# Answer
I had had some problems with Loading of Json file from `persistentDataPath` and `dataPath`, so if you will have a problem like that - another solution is to write and load files from Resources folder that is Resources \- it also allows you to load and write files and even specify a type of the file loaded Load.

Note: remember to use forward slashes - all Unity assets use them.
> 0 votes

---
Tags: unity, c#, android, ios, windows
---


# Question
Title: get value from UniformParameterPtr in Ogre
I have a variable of type `UniformParameterPtr` decalared by `Ogre` and I want to get its value.
What is the right way to this?
I tried the method `.get()` but it doesn't really give the value.
something else?

# Answer
`UniformParameterPtr` is a typedef for `Ogre::SharedPtr<UniformParameter>`. With `Ogre::SharedPtr` the behavior is always the same:

You can retrieve the actual object instance that is encapsulated in the shared pointer via `get()`, which would in your case give you an `UniformParameter` instance.

Alternatively you can directly access the members of the object encapsulated in the shared pointer via `->` as if it were a regular pointer.
> 1 votes

---
Tags: c++, data-structure, ogre
---


# Question
Title: Cannot find Natural front 3D facial animation plugin in Window drop down
I am using Unity version 5.4.2 which is the latest, I tried to go through the tutorial video for creating 3D animations of 2D pictures but I am unable to find the icon of

-\> Natural front 3D facial animation plugin

under the window drop down. What is the step I am missing? Am i supposed to download anything extra?

# Answer
> 0 votes
The Natural Front 3D animation plugin is not included by default with unity. If you do a quick search on the unity store you should be able to find  Few Varieties.

Generally if it has plugin in the name that alludes to an extra install.

---
Tags: unity
---


# Question
Title: Is there any way to get the HWND from a window in LWJGL?
I've started some experimentation in Java and LWJGL (via Slick), and it seems very solid. However, I have some legacy code that requires a HWND integer as a parameter. I'm not sure how I'd be able to get this, or if LWJGL would be able to report this for me. Any help?

# Answer
> 4 votes
An hWnd is a Windows API window handle. Here's an example that shows how to get it for an AWT component and does some other stuff (from here):

```
JNIEXPORT jlong JNICALL Java_test_Transparency_getWindowHandle
  (JNIEnv * env, jclass cls, jobject component)
{
   JAWT awt;
   JAWT_DrawingSurface* ds;
   JAWT_DrawingSurfaceInfo* dsi;
   JAWT_Win32DrawingSurfaceInfo* dsi_win;
   jint dsLock;
   jboolean result = JNI_FALSE;

   // Get the AWT
   awt.version = JAWT_VERSION_1_4;
   result = JAWT_GetAWT(env, &awt);

   if ( result == JNI_FALSE )
   {
      printf( "%s:%i -  JAWT_GetAWT() failed.\n", __FILE__, __LINE__ );
      return 0;
   }

   // Get the drawing surface
   ds = awt.GetDrawingSurface(env, component);

   if ( ds == NULL )
   {
      printf( "%s:%i -  GetDrawingSurface() failed.\n", __FILE__, __LINE__ );
      return 0;
   }

   dsLock = ds->Lock(ds);

   // Get the drawing surface info
   dsi = ds->GetDrawingSurfaceInfo(ds);

   // Get the platform-specific drawing info
   dsi_win = (JAWT_Win32DrawingSurfaceInfo*)dsi->platformInfo;

   HWND handle = dsi_win->hwnd;

   ds->FreeDrawingSurfaceInfo(dsi);
   ds->Unlock(ds);
   awt.FreeDrawingSurface(ds);

   return (jlong)handle;
}

```

# Answer
> 1 votes
I actually coded this up before I noticed that `long org.lwjgl.WindowsSysImplementation.getHwnd()` (also private) contains essentially the same code (Although it runs it as a privileged action). Note that the answer from Matthew Read does (what appears to be at first glance, anyway) the same thing as `long org.lwjgl.opengl.WindowsDisplay(Canvas)`

I figured this was cleaner because it uses reflection to get the HWND used directly by LWJGL, instead of guessing the window/canvas/etc/ it uses, as well as not being native, so you can reduce native errors as much as possible. I didn't put much error checking into this, but you should be able to edit it to have as much or as little as you want.

```
protected long getLWJGLHwnd() throws Exception {
    //long org.lwjgl.opengl.WindowsDisplay.getHwnd()
    try {
        Method methImpl = Display.class.getDeclaredMethod("getImplementation");
        methImpl.setAccessible(true); //Make it accessible, since it is private
        Object impl = methImpl.invoke(null); //Static with no parameters, type not visible anyway so keep as object
        Class clsWinDisplay = Class.forName("org.lwjgl.opengl.WindowsDisplay"); //Not visible, so can't use constant WindowsDisplay.class
        if(!clsWinDisplay.isInstance(impl)) throw new Exception("The current platform must be Windows!"); //Throw on non-windows host
        Method methHwnd = clsWinDisplay.getDeclaredMethod("getHwnd");
        methHwnd.setAccessible(true);
        Long value = (Long) methHwnd.invoke(impl);
        return value;
    } catch (ClassNotFoundException | NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e){
        e.printStackTrace();
        return 0;
    }
}

```

If it means anything to anyone, before I found I could do this, I was just using EnumWindows to cycle through the windows, and get the one with the right PID/name combination, but thats another question.

---
Tags: java, lwjgl, slick
---


title: MMO server use mysql offline?

text:
# Question
Title: MMO server use mysql offline?
Im going to write an MMO server for a game, however in my last attempt to do this I used mysql with xampp-server and the game-server was getting the data offline tru mysql(xampp server was offline).

I was wondering if this will be fast enough when hundreds of players are constantly sending request to the game-server and the game-server to mysql(offline) for pulling or saving data(ex. constantly saving position for each player etc etc)

If not what would be an appropriate way to archive this? Thanks

# Answer
> 3 votes
You'll want to store most of this data in-memory *and* offline, in a database.

You will need an in-memory representation on the server(s) of the data while a player is actively logged in and manipulating characters. It's easier to work with and usually more efficient.

You will also want to periodically serialize this in-memory data into the persistent database for character data, in case the server crashes, et cetera.

---
Tags: java, mmo, server, mysql
---


# Question
Title: How to implement large data files without using up a lot of space at runtime?
Say I have a bunch of images that I want to use with my game; I want the image files to be external, so overall I have the game's executable and a directory full of images. Let's say there are 100+ images and the size of the directory is ~500 MB.

I don't want the player to easily access these image files, so rather than having a directory containing 100+ individual files, I pack all the images into one large 500 MB file: "images.big"

With compression, I can reduce the size of "images.big" to ~50 MB. So all the player needs to download is the executable and a 50 MB file.

The problem is when I want to display the images in the game, it has to decompress "images.big" which creates a temporary 500 MB file and then it has to unpack all the images into a temporary directory (taking up another 500 MB) so it can display them based on filename. The game's directory goes from 50 MB to 1 GB, and on top of that the player can easily access the image files while the game is running.

Is there a much better way to go about this, or is it really a non-issue for a game to be creating such large temporary files/directories at runtime?

# Answer
You can compress images individually, then align all of those into your own data file images.big, with a header index so that you can find each compressed image at runtime.

The index will have the start point of each individual image file location and store names/ids if those as well. When you need to load "Image.png" from images.big, the index will tell you the offset and length of the compressed data for the file within the .big
> 5 votes

---
Tags: game-design, graphics, file
---


# Question
Title: Unity JS to C# conversion - Incomplete list of public variables in Inspector
I'm trying to convert a javascript file to a C# script for Unity, mostly because the rest of my workflow is in C#, and I'm much more comfortable with C#. In this case, it's an audio controller script.

The .js looks like this:

```
var audioClips              : AudioClips[];                     // Array of single use audio clips
var audioLoops              : AudioClips[];                     // Array of loops

class AudioClips{
    var name            : String;
    var audioClips      : AudioClip[];
    var volume          : float             = 1.0;
    var volumeBySpeed   : boolean           = false;
    var minVolume       : float             = 0.2;
    var pitchBySpeed    : boolean           = false;
    var minPitch        : float             = 1.0;
    var maxPitch        : float             = 1.0;
}

```

and the editor looks like this:

My C# script looks like this:

```
public class AudioClips : MonoBehaviour
{
    public string       _name;
    public AudioClip[]  audioClips;
    public float        volume          = 1.0f;
    public bool         volumeBySpeed   = false;
    public float        minVolume       = 0.2f;
    public bool         pitchBySpeed    = false;
    public float        minPitch        = 1.0f;
    public float        maxPitch        = 1.0f;
}

public class AudioController_SFB_C : MonoBehaviour {

    public AudioClips[] audioClipsArray;                        // Array of single use audio clips
    public AudioClips[] audioLoopsArray;                        // Array of loops

```

and the editor looks like this:

The C# code doesn't reflect all of the public variables. Interestingly, even if I comment out the `public AudioClip[]` section and the code that relies on it, my inspector looks the same. I'm thinking maybe there a scoping issue or a strong-typing issue that I'm missing, but I can't seem to see it.

# Answer
> 6 votes
Your missing data from the included instance of `AudioClips`. UnityScript is a little more flexible, in that it already serialises these things for you. In C#, you need to specify that you intend to use serialisation, with the `[System.Serializable]` attribute.

As a side note, you have included the inheritance of `AudioClips : MonoBehaviour`. We need to expressly note inheritance in C#, where UnityScript correctly assumes. However, this particular class is being used to store data, not to represent a mono behaviour. We should not inherit from `MonoBehaviour`.

Simply remove the inheritance and add the attribute to your class, as follows, and it should display in the editor.

```
[System.Serializeable]
public class AudioClips
{
    public string _name;
    public AudioClip[] audioClips;
    public float volume = 1.0f;
    public bool volumeBySpeed = false;
    public float minVolume = 0.2f;
    public bool pitchBySpeed = false;
    public float minPitch = 1.0f;
    public float maxPitch = 1.0f;
}

```

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


# Question
Title: Trying to abstract OpenGL model loading but can't draw triangle... (C++)
Recently, I have been trying to learn modern OpenGL and I think I've grasped it (or the basics, at the **very** least.) but I have been having issues trying to make a triangle display on the screen but it doesn't seem to be working and I can't find where or what's going wrong. The console has proven fruitless and I've looked at examples on the internet for inspiration but I couldn't find what I was looking for.

Some things to note:

* I know that the shaders are working correctly as I have them being loaded in at the start of the program and errors would appear in my program's console if they weren't working correctly. I have also checked and the shader program ID *is* correct.
* I have loaded a triangle before in a rendering loop previously. However, I used const arrays instead of using STL vertex lists, which is what I'm using just now.
* There are no empty lists. (As far as I and Visual Studio's inspector can tell, anyway.)
* I have created a custom structure to help with loading in for glVertexAttribPointer called "VertexAttribPointerClass"
* It's probably a very silly mistake.

Anyway, here's the code:

***GraphicsModel.h***

```
#ifndef GRAPHICSMODEL_H
#define GRAPHICSMODEL_H

#include "ExternalLibraries.h"
#include "Shader.h"

namespace game
{
    namespace model
    {
        namespace gfx
        {
            struct VertexAttribPointerClass
            {
                //  glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), (GLvoid*)0);
                int _shaderPosition, _vectorSize, _type, _normalised, _stride, _offset;
                VertexAttribPointerClass()
                {}

                VertexAttribPointerClass(int shaderPosition, int vectorSize, int type, int normalised, int stride, int offset) :
                    _shaderPosition(shaderPosition), _vectorSize(vectorSize), _type(type), _normalised(normalised), _stride(stride), _offset(offset)
                {}
            };
            class Model
            {
                GLenum _drawSpeed;
                GLuint _shaderProgram;
                GLuint VAO, VBO, EBO;
            public:
                std::vector<GLfloat> _vertices;
                std::vector<GLuint> _elements;
                std::vector<VertexAttribPointerClass> _vapclasses;
                bool _wireframeMode;

                Model() {}
                Model(std::string shaderName, std::map<std::string, game::shader::ShaderClass*> shaderRegister, std::vector<GLfloat> vertices, std::vector<GLuint> elements, std::vector<VertexAttribPointerClass> vapclasses, GLenum drawSpeed, bool wireframeMode);
                virtual ~Model();

                void DrawModel();
            };
        }
    }
}

#endif

```

***GraphicsModel.cpp***

```
#include "GraphicsModel.h"

game::model::gfx::Model::Model(std::string shaderName, std::map<std::string, game::shader::ShaderClass*> shaderRegister, std::vector<GLfloat> vertices, std::vector<GLuint> elements, std::vector<VertexAttribPointerClass> vapclasses, GLenum drawSpeed, bool wireframeMode)
{
    _shaderProgram = game::shader::getShaderClassFromRegister(shaderName, shaderRegister)->getShaderProgram();

    _vertices = vertices;
    _elements = elements;
    _vapclasses = vapclasses;

    _drawSpeed = drawSpeed;
    _wireframeMode = wireframeMode;

    glGenVertexArrays(1, &VAO);
    glGenBuffers(1, &VBO);
    glGenBuffers(1, &EBO);

    glBindVertexArray(VAO);

    glBindBuffer(GL_ARRAY_BUFFER, VBO);
    glBufferData(GL_ARRAY_BUFFER, sizeof(_vertices[0]) * _vertices.size(), &_vertices[0], _drawSpeed);

    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(_elements[0]) * _elements.size(), &_elements[0], _drawSpeed);

    for (int i = 0; i < _vapclasses.size(); i++)
    {
        glVertexAttribPointer(_vapclasses[i]._shaderPosition, _vapclasses[i]._vectorSize, _vapclasses[i]._type, _vapclasses[i]._normalised, _vapclasses[i]._stride, (GLvoid*)_vapclasses[i]._offset);
        glEnableVertexAttribArray(_vapclasses[i]._shaderPosition);
    }

    glBindVertexArray(0);
}

game::model::gfx::Model::~Model()
{
}

void game::model::gfx::Model::DrawModel()
{
    if (_wireframeMode)
        glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
    else
        glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);

    glUseProgram(_shaderProgram);
    glBindVertexArray(VAO);
    glDrawElements(GL_TRIANGLES, _elements.size(), GL_UNSIGNED_INT, &_elements[0]);
    glBindVertexArray(0);
    glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
}

```

***Initialisation Code***

```
/*MODELS*/
    std::vector<GLfloat> testModelVertices =
    {
        -0.5f, -0.5f, 0.0f, //0
         0.5f, -0.5f, 0.0f, //1
         0.0f,  0.5f, 0.0f  //2
    };
    std::vector<GLuint> testModelElements =
    {
        0, 1, 2
    };
    std::vector<game::model::gfx::VertexAttribPointerClass> testModelVAPClasses =
    {
        game::model::gfx::VertexAttribPointerClass(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), 0)
    };
    currentGameEnvironment->currentGameVariables.models.testModel = game::model::gfx::Model("testShader", currentGameEnvironment->currentGameVariables.util.shaderRegister, testModelVertices, testModelElements, testModelVAPClasses, GL_STATIC_DRAW, false);

```

***Render Loop***

```
bool game::graphics::render(GLFWwindow* window, game::core::GameEnvironment* currentGameEnvironment)
{
    //Sets "window's" OpenGL context to be current.
    glfwMakeContextCurrent(window);

    glClearColor(0.8f, 0.8f, 1.0f, 1.0f); //Sets the colour for glClear.
    glClear(GL_COLOR_BUFFER_BIT); //Clears the COLOR-BUFFER-BIT with the colour above. Other available bits are GL_DEPTH_BUFFER_BIT and GL_STENCIL_BUFFER_BIT

    currentGameEnvironment->currentGameVariables.models.testModel.DrawModel();

    glfwSwapBuffers(window);

    return true;
}

```

Sorry if I haven't uploaded enough information. -I can do so if needed, it's just that it isn't commented very well and I know for a fact that the other things work correctly.

Any help is appreciated!

**EDIT #1:** Used incorrect ENUM in glBindBuffer for VBO.

# Answer
The problem I had was that I mistakenly put the `_element` array into the last parameter of `glDrawElements` when it just needed to be `0`.

e.g.

```
glDrawElements(GL_TRIANGLES, _elements.size(), GL_UNSIGNED_INT, 0);

```

Not this:

```
    glDrawElements(GL_TRIANGLES, _elements.size(), GL_UNSIGNED_INT, &_elements[0]);

```

According to www.learnopengl.com, the last parameter is to specify an offset in the element array. (Maybe for animations?)
> 1 votes

---
Tags: opengl, c++, model-loader
---


# Question
Title: GameMaker (RPG) Room transition problem how to save the progress made?
My problem is that I made 2 levels and made 2 doors and since I want to go from room1 to room2 so I wrote this code in the door:

```
new_room = rm_number2;
new_x = 96;
new_y = 32;

```

and this code in the player:

```
/// Go through the door
if (room_exists(other.new_room)) {
    room_goto(other.new_room);
    x = other. new_x;
    y = other. new_y;
}

```

but my problem is that when I kill the enemy and go through the door to room2 and go back they respawn. The room is persistent. But since every time the player goes through the door the door makes a new room1 (or at least that is what I think the problem is) the game doesn't keep room1 as it was before going through the door.

# Answer
> -1 votes
NVM ppl i found the way its by triggering a save .ini every time i use the door and load it and over write it not in that order but u get it

---
Tags: game-maker
---


title: LibGDX: Max number of textures?

text:
# Question
Title: LibGDX: Max number of textures?
I've been developing a game targeted at android. I know not to think about program optimization until the project is finished, but I have to wonder how many textures most phones can handle safely without melting or murdering battery. I've seen that the max SIZE of a texture should be 1024 or 2048 pixels squared (I've been combining sprite-sheets into 1024x1024 atlas's) but I can't help but wonder if there is a limit to how many of these I can use at runtime. I understand it should depend on the GPU but what spec determines it?

# Answer
> 1 votes
## The only limit on texture count is memory

The vast majority of mobile devices (and desktops with integrated graphics rather than a dedicated graphics card) use a shared memory architecture where *VRAM* \- that's RAM reserved for video - is part of system RAM. Textures used by graphics APIs are simply pointers to a block of VRAM; there's no artificial limits imposed by the APIs themselves.

A typical source of confusion here is there's a very limited number of texture units. These are circuits in the GPU hardware which can 'bind' to a particular texture and perform the sampling for us. Importantly though, the limit only applies to a single shader. In effect if a system has, for example, 32 texture units, then a single shader can use at most 32 textures *simultaneously*. Note that there is also another similar limit that affects how many textures a particular stage of the shader can use simultaneously (the textures per stage limit).

Quick aside note: A simple way to improve memory usage is to use texture compression. Most mobiles support some form of texture compression nowadays and many engines enable it by default (those texture units can sample straight from compressed data).

## Texture size

Those texture units are dedicated pieces of hardware and as a result are physically restricted on the size of textures they can deal with. The circuits that perform sampling are designed to operate on images with a power-of-2 size. This is why devices have limited texture sizes, ranging from around 512 up, and they're always a power of 2. 1080 is an awkward size for an atlas as it's not a power of 2 (so the hardware might decide to upscale it *all the way to 2048*).

# Answer
> 0 votes
The limit depends on:

* the phone's memory bandwidth
* the GPU's cache size
* how large (in bytes) the textures are
* the phone's memory size accessible to the GPU
* how much of the texture you're using per frame
* what mipmap level is being used (if any)
* how well ordered your draw calls are so the GPU cache can work effectively
* how much opaque draws you have vs blend or alpha test (hidden surface removal)
* what the screen resolution is
* how complex the shaders are (bottlenecks?)
* how busy the CPU is

It's not a question of how many. It's not a question of how large. It's a question of all those factors combined.

You could have 4000 16x16 textures displayed and a phone could probably handle that faster than four 1024x1024 textures drawn over the screen.

Both CPU and GPU share the same memory bus on most mobile platforms which means if one is using the bus to read or write memory the other has to wait it's turn.

So you can run a test and see that the GPU is fine drawing N triangles with AxB textures at a certain frame rate, and run a test for CPU speed, but when you combine both GPU (drawing) and CPU processing (audio, loading/decompression, physics, particles & 3D model animations) suddenly the GPU performance drops. Or it could be the other way around where the GPU has priority over the CPU to access memory, or a mix of both depending on the system.

GPU and CPU usually run in parallel but they still have to "fight" over memory access on a shared memory system.

---
Tags: opengl, android, libgdx, textures, gpu
---


title: glm::perspective isn't working?

text:
# Question
Title: glm::perspective isn't working?
So I'm learning how to make games and program, and while trying to setup a projection camera using GLM in GFLW, this line of code refuses to work and I can't figuire out why. The code is in the image below. Thanks!

# Answer
> 0 votes
the width and height of the window were actually ints they needed to be floats so I just casted it to a float and it worked.

# Answer
> 1 votes
The message you're seeing is saying your argument types aren't right. As 3 of the arguments are `float` values and they correctly match, then that means `m_windowWidth / m_windowHeight` must be an integer when it needs to be a float. So, try:

```
glm::perspective(45.0f, m_windowWidth / static_cast<float>(m_windowHeight), 0.1f, 100f);

```

---
Tags: camera, perspective, glm, glfw
---


# Question
Title: Unity 5: Third Person Control Based on Current Camera
I'm creating Third Person game with multiple switching cameras. I'm using the default Third Person Control asset provided with Unity, and it comes with a script that aligns the movement to the camera.

The problem is, this script only seems to align with the "Main Camera" tagged camera. My game has multiple cameras with their own tag (Camera), and I need to switch the controls based on the current active camera's direction. I briefly modified the script to substitute "main" with "current", so the movement could be based around the current active camera instead, but it doesn't seem to work.

Could someone explain what am I missing here? Thanks!

```
using System;
using UnityEngine;
using UnityStandardAssets.CrossPlatformInput;

 namespace UnityStandardAssets.Characters.ThirdPerson
{
  [RequireComponent(typeof (ThirdPersonCharacter))]
  public class ThirdPersonUserControlCamera : MonoBehaviour
  {
      private ThirdPersonCharacter m_Character; // A reference to the ThirdPersonCharacter on the object
      private Transform m_Cam;                  // A reference to the main camera in the scenes transform
      private Vector3 m_CamForward;             // The current forward direction of the camera
      private Vector3 m_Move;
      private bool m_Jump;                      // the world-relative desired move direction, calculated from the camForward and user input.

      private void Start()
      {
          // get the transform of the main camera
          if (Camera.current != null) // changed from Camera.main to Camera.current
          {
              m_Cam = Camera.current.transform; // changed from Camera.main to Camera.current
          }
          else
          {
              Debug.LogWarning(
                  "Warning: no main camera found. Third person character needs a Camera tagged \"MainCamera\", for camera-relative controls.", gameObject);
              // we use self-relative controls in this case, which probably isn't what the user wants, but hey, we warned them!
          }

          // get the third person character ( this should never be null due to require component )
          m_Character = GetComponent<ThirdPersonCharacter>();
      }

      private void Update()
      {
          if (!m_Jump)
          {
              m_Jump = CrossPlatformInputManager.GetButtonDown("Jump");
          }
      }

      // Fixed update is called in sync with physics
      private void FixedUpdate()
      {
          // read inputs
          float h = CrossPlatformInputManager.GetAxis("Horizontal");
          float v = CrossPlatformInputManager.GetAxis("Vertical");
          bool crouch = Input.GetKey(KeyCode.C);

          // calculate move direction to pass to character
          if (m_Cam != null)
          {
              // calculate camera relative direction to move:
              m_CamForward = Vector3.Scale(m_Cam.forward, new Vector3(1, 0, 1)).normalized;
              m_Move = v*m_CamForward + h*m_Cam.right;
          }
          else
          {
              // we use world-relative directions in the case of no main camera
              m_Move = v*Vector3.forward + h*Vector3.right;
          }
 #if !MOBILE_INPUT
          // walk speed multiplier
          if (Input.GetKey(KeyCode.LeftShift)) m_Move *= 0.5f;
 #endif

          // pass all parameters to the character control script
          m_Character.Move(m_Move, crouch, m_Jump);
          m_Jump = false;
      }
  }
 }

```

EDIT: This script manages the camera:

```
  using UnityEngine;
  using System.Collections;

  public class CameraManager : MonoBehaviour
 {
  public GameObject[] cameras;
  public GameObject startCamera;

// Use this for initialization
void Start()
{
    cameras = GameObject.FindGameObjectsWithTag("Camera");

    for (int i = 0; i < cameras.Length; i++)
    {
        cameras[i].SetActive(false);
    }

    startCamera.SetActive(true);
}

public void DeactivateAllCameras()
{
    cameras = GameObject.FindGameObjectsWithTag("Camera");

    for (int i = 0; i < cameras.Length; i++)
    {
        cameras[i].SetActive(false);
    }
  }
}

```

This script triggers other cameras:

```
    using UnityEngine;
    using System.Collections;

    public class CameraTrigger : MonoBehaviour
    {
public GameObject myCamera;
private CameraManager myCameraManager;

// Use this for initialization
void Start ()
{
    myCameraManager = GameObject.FindGameObjectWithTag("GameManager").GetComponent<CameraManager>();
}

void OnTriggerEnter(Collider other)
{
    if(other.CompareTag("Player"))
    {
        myCameraManager.DeactivateAllCameras();
        myCamera.SetActive(true);
    }
  }
}

```

# Answer
> 0 votes
Add a public SetCamera(camera) method to your third-person controller, and have that method put the camera transform into m\_cam. Then whatever code changes the camera view also calls controller.SetCamera(newCamera)

# Answer
> 0 votes
based from http://answers.unity3d.com/questions/15801/finding-cameras.html

**Use Something Like This**

```
 Camera cam = GameObject.Find("YourCameraName").GetComponent<Camera>();

```

```
if( cam == GameObject.Find("CameraOne").GetComponent<Camera>() ) {

}

if ( cam == GameObject.Find("CameraTwo").GetComponent<Camera>() ) {

}
```

This will be alot of hardwork so , goodluck :)

```
   ANSWER EDITED

```

---
Tags: unity
---


# Question
Title: Handling Player "sessions" on a UDP based server
I've been building a UDP server and have hit a bit of a stumbling point. Since UDP is not a persisted connection, there really isn't a way for me to track if the Player has left the current session/closed the game etc.

What I was planning on doing was having the server/client perform some kind of handshake when the client first attempts to join a game session. The server would store the server-side Player object and it's associated EndPoint(s) in a collection. This way, when Player A does something that affects Player B, I can update the two player objects on the server-side and send both players updated info.

What happens if Player A closes the game? I need to clean up my collection of Player/Endpoint(s). I'm not sure how that is typically handled. Should I have a timer that runs every minute or two, pinging clients and removing them if no ping comes back? Since It's UDP, I can't assume that "no new datagrams" really means the player isn't playing. It's possible that they've just not needed to send any data for a while (maybe it's paused or something idk). I have a low-overhead async timer API that runs on background threads that I could use, but it feels like a lot of overhead to ping every connected client every couple of minutes.

# Answer
> 1 votes
It's fairly simple. Timeout

Make each client ping the server every few seconds. If the server haven't received any packets from the client for say 15 seconds, consider it at timeout.

But by default you should not rely on timeout to remove clients. When the client leaves or closes the game, it should send a leave message to the server. Timeout should only happen if the client crashes or loses his internet connection.

Additionally you might also want to add timeout on the client in case the server should crash.

---
Tags: networking, udp
---


# Question
Title: OpenGL Textures not sitting right on model
I have been trying to get textures loading properly onto my models but to no avail. I'm using picopng to load my images.

Here is my code. \[Texture code\]

```
std::vector<unsigned char> buffer, image, aaa;

std::ifstream file(location.c_str(), std::ios::in | std::ios::binary | std::ios::ate);
std::streamsize size = 0;
if (file.seekg(0, std::ios::end).good()) size = file.tellg();
if (file.seekg(0, std::ios::beg).good()) size -= file.tellg();
if (size > 0)
{
    buffer.resize((size_t)size);
    file.read((char*)(&buffer[0]), size);
}
else {
    buffer.clear();
}
unsigned long w, h;
int error = decodePNG(image, w, h, buffer.empty() ? 0 : &buffer[0], (unsigned long)buffer.size());

if (error != 0) std::cout << "error: " << error << std::endl;

glEnable(GL_TEXTURE_2D);
GLuint id;
glGenTextures(1, &id);
glBindTexture(GL_TEXTURE_2D, id);

glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);

glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);

glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, &image[0]);

glBindTexture(GL_TEXTURE_2D, 0);

glGenerateMipmap(GL_TEXTURE_2D);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
float mipMapingAffectivness = 0.4f;
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_LOD_BIAS, mipMapingAffectivness);

```

Any advice?

\[Update\] I have tried flipping the image but to no avail, I have tried all 8 orientation variations and non seem to work.

# Answer
> 1 votes
OpenGL textures are bottom to top, PNG are top to bottom.

You need to either flip the UVs vertically or flip the image vertically.

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


# Question
Title: How to construct the marching cubes tables algorithmically?
I want to implement the marching cubes algorithm from scratch, but I'm stuck at the polygon generation phase (building edge loops with correct orientation and triangulating them). Obviously, I should consider all 2^8 = 256 cases, find out zero-crossing edges (build 12-bit edge masks) and figure out the triangulation in each case.

Could you please give me some ideas on how to correctly construct and triangulate edge loops?

I'd like to avoid considering each MC configuration (out of 15) separately as it seems somewhat tedious and messy to me.

# Answer
I also had exactly the same thoughts as you. For my final university project I studied different methods of voxel mesh smoothing. The best method I found was Surface Nets. It produces a result that looks very similar to March Cubes but without all that lookup table hassle. You can also choose how smooth you want the object by performing more passes of the algorithm.

The basic procedure is to do what Marching Cubes does to start with:

* Find all the points of voxel volume that intersect the current voxel cube
* Interpolate to get the edge of that volume

You then take these interpolated points and find their 'centre of mass', this gives you a point to place a vertex at. From this vertex position you connect outwards to other vertices in neighbouring voxels.

I currently do not have access to any of my source code to help expand on this solution but I will edit this answer as soon as possible to make it clearer and to support the article I've referenced.

---

**Edit**:

There's going to be a lot of code splurged below, followed by an open source licence, feel free to ask me more questions!

So here is my GetCentreOfMass function, I'll try to break down in comments:

**Get Centre Of Mass Method**

```
/// <summary>
/// Gets the centre of mass of a voxel for use in the SurfaceNets mesh generation
/// algorithm.
/// </summary>
/// <param name="voxels">The voxels.</param>
/// <returns></returns>
/// <exception cref="Project.VoxelEngine.Visualisation.VoxelNotOnSurfaceException">Voxels not on surface\nvoxels before:  + voxelStringBefore + \nedge positions:  + edgePositionsString + \nvoxels after:  + voxelStringAfter + , edgePosition count:  + edgePositions.Count</exception>
public Vector3 GetCentreOfMass(Voxel[] voxels)
{
    string voxelStringBefore = voxels.ElementsToString(", ");
    string edgePositionsString = "";
    List<Vector3> edgePositions = new List<Vector3>();

    // For each edge definition: here an edge definition is a relationship between two of
    // the vertices of a voxel, so it will contain 2 numbers which are an indices that
    // point to voxels relative to the current voxel we want to find the centre of mass
    // for. The index 0 would be this current voxel, while the index 1 means the voxel in
    // front of the current one in the x direction, 2 would mean forward in the y
    // direction etc
    for (int i = 0; i < edgeDefinitions.Length; i++)
    {
        Voxel voxelA = voxels[(int)edgeDefinitions[i].x];
        Voxel voxelB = voxels[(int)edgeDefinitions[i].y];

        // Evaluate whether or not the surface crosses the edge,
        // here we want to work out whether or not the density of the voxels at either end
        // of the current edge definition changes from positive to 0 across the edge, this
        // is similar to part of the marching cubes process

        if(voxelA.GetDensity() == 0 && voxelB.GetDensity() != 0 ||
            voxelA.GetDensity() != 0 && voxelB.GetDensity() == 0)
        {

            // Interpolate the position that the surface crosses this edge, we
            // mathematically find a fast and rough guess for where the 'physical' surface
            // of the voxel volume lines on this edge definition. This will be where one
            // of the faces of our mesh will cut across between two voxels.
            // Once we've found a value we add it the edge positions list, a collection
            // of positions where the surface intersects with the boundaries of this
            // current voxel and its neighbours.

            int difference = voxelB.GetDensity() - voxelA.GetDensity();
            float lerp = (1f / Voxel.maxDensity) * Mathf.Abs(difference);
            if (difference < 0)
            {
                // In this part VoxelGridData.neightbourVectors is a structure that
                // I have in a static class that gives me the physical vector of a
                // neighbour based on the index we have from the edge definition (bit
                // convoluted I know)
                edgePositions.Add(Vector3.Lerp(
                    VoxelGridData.neighbourVectors[(int)edgeDefinitions[i].x],
                    VoxelGridData.neighbourVectors[(int)edgeDefinitions[i].y],
                    lerp));
            }
            else
            {
                edgePositions.Add(Vector3.Lerp(
                    VoxelGridData.neighbourVectors[(int)edgeDefinitions[i].y],
                    VoxelGridData.neighbourVectors[(int)edgeDefinitions[i].x],
                    lerp));
            }

            // Debugging stuff :P
            edgePositionsString += "\nEdge Definition: " + i + ", Edge Position " + (edgePositions.Count-1) + ": " + edgePositions[edgePositions.Count-1] + ", maxDensity: " + Voxel.maxDensity + ", difference: " + difference + ", lerp: " + lerp;
        }
    }

    // If we found some intersections, i.e. the voxel actually sits on the surface, if
    // it doesn't my algorithms that call this method have actually failed so I throw an
    // exception
    if (edgePositions.Count > 0)
    {
        // Find the centre of mass of edge intersections with the surface using simple
        // maths!
        Vector3 centreOfMass = new Vector3();
        centreOfMass.x = edgePositions.Sum(i => i.x) / edgePositions.Count;
        centreOfMass.y = edgePositions.Sum(i => i.y) / edgePositions.Count;
        centreOfMass.z = edgePositions.Sum(i => i.z) / edgePositions.Count;
        return centreOfMass * this.voxelData.GetScale();
    }
    else
    {
        string voxelStringAfter = voxels.ElementsToString(", ");
        throw new VoxelNotOnSurfaceException("Voxels not on surface\nvoxels before: " + voxelStringBefore + "\nedge positions: " + edgePositionsString + "\nvoxels after: " + voxelStringAfter + ", edgePosition count: " + edgePositions.Count);
    }
}

```

This is pretty hefty and it's only getting the centre of mass but it does the job well. To fully build the mesh I store this centre of mass and an edge mask (for each voxel 8 bits: 1 for an edge on the surface and 0 for an edge not on the surface) together in a structure called a NetVertex. I then use these to create the mesh, the vertices are easy:

**Mesh Vertex Generation Method**

```
foreach (KeyValuePair<Vector3, NetVertex> netVertex in this.netVertices)
{
    vertices[i] = netVertex.Value.GetVertexPosition(); // Set the actual vertex from the netVertex
    netVertex.Value.SetVertexIndex(i); // Store which actual vertex relates to this NetVertex
    i += 1;
}

```

Triangles of the mesh are somewhat more complicated:

**Mesh Triangle Generation Method**

```
// For every net vertex
foreach (KeyValuePair<Vector3, NetVertex> netVertex in this.netVertices)
{
    // Get the edgeMask of the net vertex.
    int[] edgeMask = netVertex.Value.GetEdgeMask();
    // For each edge that can have a triangle crossing it
    for (int j = 0; j < triangleEdges.Length; j++)
    {
        // If the edgeMask says that the surface crosses this edge
        if (edgeMask[triangleEdges[j]] != 0)
        {
            // Get the vectors of the two new points of the triangle
            Vector2 triangleVectorIndices = triangleVectors[(j % 3)];
            Vector3 origin = netVertex.Key;

            // Find out the triangle facing direction
            int sign = 0;
            if (j <= 2) sign = -1;
            else if (j >= 3) sign = 1;

            // Get the two net vertex positions of the other points of the triangles
            Vector3 netVertexPosition1 = origin + (neighbourVectors[(int)triangleVectorIndices.x] * sign);
            Vector3 netVertexPosition2 = origin + (neighbourVectors[(int)triangleVectorIndices.y] * sign);

            // If these net vertices exist
            if (this.netVertices.ContainsKey(netVertexPosition1) && this.netVertices.ContainsKey(netVertexPosition2))
            {
                // Add the three vertex indicies to build the triangle, taking care of facing direction
                triangles.Add(netVertex.Value.GetVertexIndex());
                if (edgeMask[triangleEdges[j]] == 1)
                {
                    triangles.Add(this.netVertices[netVertexPosition1].GetVertexIndex());
                    triangles.Add(this.netVertices[netVertexPosition2].GetVertexIndex());
                }
                else if (edgeMask[triangleEdges[j]] == -1)
                {
                    triangles.Add(this.netVertices[netVertexPosition2].GetVertexIndex());
                    triangles.Add(this.netVertices[netVertexPosition1].GetVertexIndex());
                }
            }
        }
    }
}

```

---

All the source code I've added to this post follows the standard MIT open source licence:

```
The MIT License (MIT)

Copyright (c) 2015 Matthew Torr

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

```
> 2 votes

# Answer
Disclaimer: Not tested yet. Edit: Tested and works, code on demand.

The configuration, or rather the mesh, can be calculated in a slightly simpler, in my opinion, way, although this is less efficient, but can be memoized, I think.

Lets call the nodes that have the active/inactive state as "ControlNode", and the 3 nodes that each of those hold "SubNode".
So each Cube holds 8 ControlNodes and 12 SubNodes.

The Cubes need to store this data in such a way that you know which SubNodes are neighboring which ControlNodes. Remember that the ControlNodes themselves have 3 SubNodes where one or more usually land outside the Cube, we don't want those.

Now to get the vertices that we need to build the mesh for this Cube:
1) Create an array for the states of the **SubNodes**. Yes SubNodes.
2) Iterate over the active ControlNodes, turning "on" the adjacent SubNodes, or turning them "off" if they were already "on".
3) The SubNodes that are "on", after step 2, are the vertices you need to use to build the mesh.
4) Alas, we don't know the direction of the surface, but we can calculate it! The Normal can be calculated by simply calculating the average positions of the selected SubNodes (A) and active ControlNodes (B).
Vector AB should be the Normal.
5) Having the vertices, and the normal, you can construct triangles from the data collected.

Extra: If you want to make this work faster, save the configuration as a number, as in the original algorithm, and store the results for each configuration as you find them.

Edit: A simple iteration will not work for cases where the configuration creates 2 separate meshes!
A solution to that is placing the active nodes in a list, and running a "paint bucket" style search, such as BFS, to get a cluster of active ControlNodes that are all "connected" (meaning forming one mesh), removing the affected ControlNodes from the list. And if any ControlNodes remain, then we do the same for that group as well.
Adjacency for the BFS can be determined by proximity, since the distance between neighboring ControlNodes is known.

Not as simple as I first thought, but it should provide a general case solution.
Hope that answers the question.
> 1 votes

---
Tags: mathematics, computational-geometry, marching-cubes
---


# Question
Title: How do I integrate Nvidia Ansel into my Unity game?
I want to be able to use the super high resolution image capabilities that ansel have to offer but I don't know how to add it as the only thing that i can find are C++ libraries on their website.

# Answer
Since November this year Nvidia have started releasing plugins as part of their partnership with Unity to integrate Gameworks into the engine.

As of now there is a plugin available on the asset store that allows you to add support. Once you have it there is a pdf included in the plugin files that should help you with integrating it into your game.

https://assetstore.unity.com/packages/tools/camera/nvidia-ansel-74758

Since Unity and Nvidia are working together it wouldn't surprise me if they simply move all of the Gameworks stuff into the engine in a future release.
> 0 votes

---
Tags: unity, nvidia, integration
---


# Question
Title: LibGDX: Shape from ShapeRenderer won't show up when put in another class
I am currently trying to make a little snake clone as my second project with LibGDX. I want to draw the borders of the screen with a ShapeRenderer. The Shape gets displayed flawlessly when I create/draw it in the render method of my game. I wanted to outsource the code into an own "Border"-Class, to get a single object for collision and graphics, but if I do this, the shape does not get displayed anymore.

**Working code before outsourcing to a Border-Class:**

```
public void render(float dt){

...
borderRenderer = new ShapeRenderer();
    borderRenderer.begin(ShapeRenderer.ShapeType.Filled);
    borderRenderer.setProjectionMatrix(gameCam.combined);
    borderRenderer.setColor(1.0f, 0.3f, 0.3f, 1);
    borderRenderer.rect(x , y , width, height);
    borderRenderer.end();
}

```

**ShapeRenderer outsourced, gets not displayed anymore:**

```
public void render(float dt){
...
for (Border border : borders) {
            border.draw();
        }
}

public class Border {
    private ShapeRenderer borderRenderer;
    private OrthographicCamera gameCam;
    private float x, y, width, height;

    public Border(float x, float y, float width, float height, OrthographicCamera gameCam){
        this.gameCam = gameCam;
        this.borderRenderer = new ShapeRenderer();
    }

    public void draw(){
        borderRenderer.begin(ShapeRenderer.ShapeType.Filled);
        borderRenderer.setProjectionMatrix(gameCam.combined);
        borderRenderer.setColor(1.0f, 0.3f, 0.3f, 1);
        borderRenderer.rect(x , y , width, height);
        borderRenderer.end();

    }

}

```

The border also gets properly initialized in the constructor.

As I was writing this I recognized that using assets for this would probably be a better idea, but I'm still curious. Thanks in advance for your help !

# Answer
> 1 votes
In your Border constructor you never assign `x`, `y`, `width`, or `height` to local variables, which means they all default to 0. Once I added those assignments the rest of the code worked fine for me.

---
Tags: java, libgdx
---