title: AI pathfinding in mostly-free space

text:
# Question
Title: AI pathfinding in mostly-free space
I'm working in an action/strategy proyect. Consider it a RTS game. The game is in 2D (with LibGDX), and I have a lot of soldiers moving along. Now I have to implement the AI. Let me say some things about my current design:

* The map has been constructed with tiles. However, I want to allow the soldiers to move in every direction -so using the tiles as graph for A\* is not a good idea.
* The obstacles are given by collision rectangles. Maps will have a lot of free space, and collision rectangles don't fit the tiles -that makes even worse the election of A\* with tiles.
* Waypoints, for the same reason, are not a good idea. I would need a very big net and soldiers would move in strange ways, as pointed out here: http://www.ai-blog.net/archives/000152.html
* I've taken a look to the LibGDX-AI library. I would like to make soldiers follow the captain or use some kind of formation. Looks like this library is a good choice to make that.

Some things I know:

I also have read about potential/vector fields and navigation mesh. The fields look interesting, but I'm not sure of how to implement them for my case. They could be good for pahtfinding, but some soldier have to follow the captain and move in formation. I think nav meshes won't solve my problem. As I've said, I have a lot of free space, and soldiers can move whatever they want, so the question "how to move the soldier inside the mesh?" remains.

QUESTIONS:

* How to make a free-space AI pathfinding which avoid my collision rectangles?
* How to make this compatible with formations like following the player across the map?
* Is there any way to use LibGDX-AI to do this?

# Answer
Knowing how A\* works, it's not always the best choice for open spaces. Sometimes a simple if x\>myPos.x then x = x - 1 type of model is fine for what you need to do. What would be better, I'm thinking, is a simple position change model backed up by A\* when it finds obstacles.

A good source for A\* algorithm-type-stuff is:

A\* Algorithm

This is what I used when I was learning the algorithm. It also goes into its pros and cons.

Back to your questions: From my personal experiences with A\*, there are other, quicker algorithms for finding paths until you need to find a way around obstacles, which I assume aren't too trappy (they look like cups or they could easily make the AI walk through an inner space for a while while chasing you). For the "trappy" areas, A\* is fair as well.

However, the obstacles do not need to be on a perfect grid either, there is plenty of research on non-square "grids." Instead of focusing on squares, you could place "nodes" on the corners of your obstacles instead, creating a quadrilateral shape that isn't necessarily square. This would be referred to Theta\*, and it doesn't look horrid for an open space, which would be less complex to traverse with Theta\*.

Theta\* Algorithm

I don't have as much experience with herding behaviors, but my best idea is to make a node in the center of the group of moving bodies, then make all the moving bodies move to fit a position surrounding that central node.

Let's pretend &s are soldiers, and the * is the above mentioned node:

```
       &
   & & * & &
     &   &

```

Then all you'd have to do to make new formations would be to define new "relative" positions around the central node for your little AIs to follow, and your central node would be the thing that'd actually be used in the A\* algorithm to find the path, the little AIs would follow the node's predefined formation. That's one way of making some basic squads.

It might look like this

node.x + 10, node.y + 0

```
     * &

```

little AI should move slightly to the right of the central node at all times

I'm not honestly too sure about LibGDX AI. But with some determination, you could do it yourself too. But if you're focused on LibGDX AI, you can fashion nodes/coherent grids from your objects if you can find a tile size small enough to be roughly correct but not too small and feed them into the AI framework.

Mostly, I just recommend you put a good amount of focus on the amount of nodes you are checking on each pass, because A\* can get really slow on large open areas and AI traps because of how long it takes to sort through a massive array of nodes; it will be correct, but it will also be noticeably and annoyingly slow. But if you're implementing this, one good way I've found for sorting through the nodes is the Binary Heap, which is easier to use when sorting through "good" nodes in the A\* algorithm, which is a high score contest for found nodes. They're quick, and they're not too hard to implement even for a beginner.

Binary Heap
> 1 votes

---
Tags: libgdx, ai, path-finding, rts, strategy
---


# Question
Title: Why does accessing a uniform float make my shader more than twice as slow?
My fragment shader was significantly slowed down by a recent change, and I've been trying to understand why.

I isolated the main slow-down to accessing a single particular uniform float. If I include this line:

```
float not_used = my_uniform;

```

then the shader runs more than twice as slowly as it does without this line. The `not_used` float is never referenced again.

Why would this be happening? I hope to understand it so that I can try to come up with a workaround that runs more quickly.

I'm running this on a mac with Intel HD Graphics 3000. I'm measuring the performance by making OpenGL timestamp queries before and after executing my `glDraw` calls and looking at the ms intervals. I can provide more specs / details if it would be helpful in diagnosing the problem.

# Answer
Are you using `glGetUniformLocation` to get the uniform's location? If the uniform has been optimized out, this function will return -1, then when you give the -1 as the location argument to `glUniform1f`, nothing will be sent to the shader and this will likely save some time.
> 2 votes

# Answer
Sounds like an alignment or memory size issue. Perhaps with this one increased float your memory needs are being bumped up to some magic number that slows down the MAC (I don't use MACs myself) but most likely it is causing an alignment issue.

Consider a C++ type structure in pseudo code:

```
struct myStruct {
    char x;
    int y;
}

```

If this structure is allowed to be created normally with an int size of 4 bytes and a char size of 1 byte the structure would be 8 bytes, not the expected 5 bytes. This is because if a word (4 bytes in 32 bit systems) is not aligned on a 4 byte boundary then more work has to be done by the CPU to move this word around. It is a single assembly instruction to move a word (int in this case) if it is properly aligned. If it is not properly aligned then half the word is moved, a pointer is changed and then the other half and this slows things down. So, a structure will normally try to properly align itself when compiled.

If you were to do something like #pragma packed which would remove the unused padding bytes the size would be the expected 5 bytes and things would be slower.

So, I think you need to look at where you are declaring that float and what is declared immediately before it and after it to find out where your possible memory alignment issues are coming from.
> -2 votes

---
Tags: opengl, glsl, performance
---


# Question
Title: Game Mechanics Suitable for a Game about Issues of Immigrations
So, I'm working on a video game design concept, dealing with the problems of an immigrant family and how they will try to blend in the society. The universe is a fictional universe.

I was wondering what game systems/mechanics/genres are suitable for such a concept? How can I use the mechanics in a sense that will be coherent with the narrative that I'm trying to tell?

# Answer
> 2 votes
There's a genre that most of developers forget about, and it's the visual novel/text adventures.

In that games, you simply select where do you want to go. In the places, you can speak with people. In the conversations, the player can choose between some options. The decisions of the player will change the story. It's like the modern version of "choose-your-own-path" books. Visual novel is a good way to focus a game in which the most important thing is the story.

Although the original, pure basic visual novel only have text, dialogues and choices, you can add different elements to make it original. For example, the Phoenix Wright series are visual novels, but only one choice is the correct, and it contains investigation scenes. Also, Hotel Dusk offer the possibility to walk around in a 3D space - however, the story depends on your decisions, and it's a game focused in dialogues and text. If you want examples, there are lots of visual novels (usually with manga-style drawing) on the Internet, which you can download and play for free.

I think that style could fit well for educational purposes. Players could walk around (in 2D or 3D) and have to speak with people and make decisions -and see what are the consequencies of their choices.

In any case, if you decide to make a pure visual novel, without players moving freely in a world or some strange gamplay, another advantage is that there're specific engines to make visual novels (for example, Ren'Py). That kind of game is really easy to code using that engines, because you can focus on writing your story rather than programming textboxes, decisions, transitions and other technicals elements.

# Answer
> 1 votes
The question of "what genre" is a bit odd, as the answer is whatever speaks to you, as the designer. There are genres that might be less appropriate, (like FPSs) and genres that might be more so (like simulations), but the field is still wide open.

However, there *are* still considerations when wanting to drive an experience through game design, especially one so untouched as cultural assimilation. What's important here is to dissect the process and finding which parts of cultural assimilation are trade-offs, compromises, or other kinds of "interesting decisions" an immigrant must make.

The most obvious of these, of course, is the straightforward "The more you assimilate, the less you adhere, identify with, and even remember the home culture." Assimilation allows for support systems, relationships, a sense of familiarity, comfort, and security. Traditions and old cultural ties are a source of identity. Any game mechanics should, mechanically, contrast the need for relationships, jobs, social support, local services, and a sense of belonging with the sense of personal identity and need to stay connected to the old.

I can't, obviously, give any specific details, because there is no definitive mechanic (for this or any other concept). This is where the designer comes in and determines how to best serve the contrast of social and financial security with personal identity. But the important note is that the contrast and the balance of those two are where you'll find the mechanics telling the experience of cultural assimilation.

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


title: SDL2 event mouse wheel trouble

text:
# Question
Title: SDL2 event mouse wheel trouble
it's been all day I have a problem getting mousewheel events properly in one of my program. I can make a program from scratch and it work properly, however as soon as i do the same things inside this one, nothing seem to work as i want:

```
#include <iostream>

#include <SDL2/SDL.h>

int    SCREEN_WIDTH = 640;
int    SCREEN_HEIGHT = 480;

SDL_Event e;
SDL_Window* gWindow;

bool initSDL();

bool handleKeys();

void close();

bool initSDL()
{

    if( SDL_Init( SDL_INIT_EVERYTHING ) < 0 )
    {
    }

    gWindow = SDL_CreateWindow( "Opengl Test",
                                SDL_WINDOWPOS_CENTERED,
                                SDL_WINDOWPOS_CENTERED,
                                SCREEN_WIDTH,
                                SCREEN_HEIGHT,
                                SDL_WINDOW_SHOWN );

    return true;
}

bool handleKeys()
{
    while( SDL_PollEvent( &e ) )
    {
        if ( e.type == SDL_MOUSEWHEEL )
        {
            std::cout << "WhhheeeeeelllllllLLLLLLLLlllllll" << std::endl;
        }

        if  ( e.type           == SDL_QUIT )
        {
            return true;
        }

    }
}

void close()
{
    //Destroy Window
    SDL_DestroyWindow( gWindow );
    gWindow = NULL;

    //Quit SDL subsystem
    SDL_Quit();
}

int main()
{
    if(!initSDL())
    {
    }

    while( !handleKeys() )
    {
    }

    close();
}

```

I compile with this makefile:

```
#comment
#Compiler to use:
CC=g++
#Compiler flags:
APPNAME=TutOpengl
OBJ=main.o
#LIBS=-lSDL2
LIBS=-lSDL2
CFLAGS=-c -g -Wall -std=c++11 -I ./src $(LIBS)

all: $(APPNAME)

$(APPNAME): $(OBJ)
    $(CC) $(OBJ) -o $(APPNAME) $(LIBS)

main.o: main.cpp
    $(CC) $(CFLAGS) main.cpp

clean:
    rm -rf *.o $(APPNAME)

```

Under Ubuntu(14.04), SDL2. I can't get MouseWheel events properly and as of today i'm unable to find out. In the larger program set i get the MOUSEWHEELS events only every now and then like at random. Compiling should give you one warning, thanks in advance if anyone can help.

# Answer
> 1 votes
Adding a delay of 1 millisecond at the end of handlekeys() function seem to solve the issue entirely. I'm clueless why, will try to find a answer but so far... no luck.

Edit

According to a friend of mine it's common in event-built programs to suffer from "too fast loops". If the loops are too fast, in some ways, sometimes, you don't give time to update the states. I don't know the exact details, I'm not that good. But if I have to speculate it's something to deal with the automatic "sleep" that the compilers use nowday use when they identify loops void of significant instruction. But this is just speculation by me.

---
Tags: events, sdl2
---


title: Repeat texture in libgdx

text:
# Question
Title: Repeat texture in libgdx
How to fill region with repeated texture? Now I'm using next method:

```
spriteBatch.begin();

final int tWidth = texture.getWidth();
final int tHeight = texture.getHeight();

for (int i = 0; i < regionWidth / tWidth; i++) {
    for (int k = 0; k < regionHeight / tHeight; k++) {
        spriteBatch.draw(texture, i*tWidth, k);
    }
}

spriteBatch.end();

```

It's very obvious. Maybe is there any built in method?

# Answer
You want to set the texture's `TextureWrap` setting to `Repeat`. See the documentation for more information, and the texture method.

Specifically:

```
setWrap(Repeat, Repeat);

```
> 14 votes

# Answer
You can use "SetWrap" on your texture and create a TextureRegion based on that Texture. To Create a 3x3 mirrored image (or axb size)

```
Texture imgTexture = new Texture(Gdx.files.internal("badlogic.jpg"));
imgTexture.setWrap(Texture.TextureWrap.MirroredRepeat, Texture.TextureWrap.MirroredRepeat);
TextureRegion imgTextureRegion = new TextureRegion(imgTexture);
imgTextureRegion.setRegion(0,0,imgTexture.getWidth()*3,imgTexture.getHeight()*3);

```

**Important:** It took me a while to figure it out, but to be mirrored, your texture must be a power of two size. It was working on Android but not on iOS and you don't get a message - it was shown as black. So it must be 4x4 or 8x8, 16x16 .. 256x256 or 512x512 ..

Will give you this:

Below you can see the sample code that generated that picture using a Stage and Image Actor (Scene2D)

```
public class GameScreen implements Screen {

    MyGdxGame game;
    private Stage stage;

    public GameScreen(MyGdxGame aGame){
        stage = new Stage(new ScreenViewport());
        game = aGame;
        Texture imgTexture = new Texture(Gdx.files.internal("badlogic.jpg"));
        imgTexture.setWrap(Texture.TextureWrap.MirroredRepeat, Texture.TextureWrap.MirroredRepeat);
        TextureRegion imgTextureRegion = new TextureRegion(imgTexture);
        imgTextureRegion.setRegion(0,0,imgTexture.getWidth()*3,imgTexture.getHeight()*3);

        TextureRegionDrawable imgTextureRegionDrawable = new TextureRegionDrawable(imgTextureRegion);
        Image img = new Image();
        img.setDrawable(imgTextureRegionDrawable);
        img.setSize(imgTexture.getWidth()*3,imgTexture.getHeight()*3);
        stage.addActor(img);
    }

    @Override
    public void show() {

    }

    @Override
    public void render(float delta) {
        Gdx.gl.glClearColor(1, 0, 0, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
        stage.act(delta);
        stage.draw();
    }

    @Override
    public void resize(int width, int height) {
        stage.getViewport().update(width, height, true);
    }

    @Override
    public void pause() {

    }

    @Override
    public void resume() {

    }

    @Override
    public void hide() {

    }

    @Override
    public void dispose() {
        stage.dispose();
    }
}

```
> 4 votes

---
Tags: textures, tiles, rendering, libgdx, spritebatch
---


title: Continuous running vs timed tasks?

text:
# Question
Title: Continuous running vs timed tasks?
I've started making a browser-based game, as a hobby, where users log in via a website and can manage a soccer team. I need to have some sort of process running to handle player development, running matches, age players, generally progressing time..

I've never done anything like this before and therefore I'm putting this out there to get some feedback from other people.

So, my idea was that I could have a continuously running application which can handle all the "off-line" processing. But, that got me thinking that another approach could be to have, f.ex. a "PlayerTrainingTask" running daily, a "RunMatchesTask", running on a fixture-based schedule, et.c.

Which approach is most appropriate? or is there another option I haven't thought of?

What are your thoughts?

# Answer
> 1 votes
Anything that doesn't have a real life time requirement should be moved to **update the simulation on demand** before passing back the results.

For example, a real life time requirement might be that you have matches at Sunday afternoon and email out results to team owners. You would run that process once a week, there's no need to keep it running all the time.

Without needing the real life requirement to email out results weekly you could **just wait until someone logs in before updating the entire simulation**.

You will have to build the team data model to have a **history of events over time** alongside current state of the team.

Side effects of designing that way is that multiple simulation results will need to be queued up and added to the team history. The example being that if someone was away for three weeks they will log in and when they ask for their team state the simulation has to run three weeks of updates and play three matches, each of which will require its own result to be added.

Note that since the team simulation is updated on demand, when a match is called for in the simulation **the other team will then be updated recursively to be ready** for the match, and so on. The effect will be that **one person logging in will spawn a flurry of simulation updates** but only as many as are touched by events like simulated matches that need other teams.

Gameplay in this setup comes from logging in daily (or often enough) to make player decisions on training, morale, etc... Where someone who logs in a lot can tune up their team to be effective while someone who only comes on every week or two will have an unspecialized team with lower morale.

PS: don't forget to add social functions for team owners to get together and talk, a forum or something simple, this will help players feel more invested in the game.

---
Tags: game-design
---


# Question
Title: How do I create a playing field of collapsing bubbles, as in Tsum Tsum?
Tsum Tsum App is a pretty interesting game and I am wondering how the main play area's data structure is, erm, structured?

Characters are stacked, disappear as the player swipes over matching ones, causing the ones above to fall down and replace them.

Tsum Tsum ⓒ Disney, via games.disney.com

Initially, it seems that it is a 2D hex grid? But I see a lot of physics going on (Tsum Tsum bounce and roll off of each other). In fact, it seems that even as you try to connect them that the chain can be interrupted while the Tsum Tsum are falling away from its closest neighbor. Also, if you connect enough Tsum Tsum, a power-up bubble appears in the chain, which pushes the Tsum Tsum out of the way. So I'm doubting that this hex grid is constantly updating with the position of the Tsum Tsum given that the Tsum Tsum rarely stops moving.

# Answer
> 2 votes
Examining this gameplay video, it looks like a physics engine, not a hex grid.

At the beginning, 0:11 :

There is no obvious grid. The lines are uneven and there's even a gap left in the top center as pieces settle.

To me, the results look typical of an iterative physics solver. For example, note how everything "rises" slightly after settling, when the engine corrects placement of things that ended up slightly overlapping. See also the green eye ball center second row from bottom, which gets erroneously pushed into intersecting with the one below, but which the engine slowly retreats back out. None of this would happen with a grid. I'd guess it's Box2D with small iteration constants, low restitution, and high damping.

I think what you're seeing as a "hex grid" is simply A2 lattice circle packing, the most efficient packing that uniformly-sized circles affected by gravity tend to fall into. In fact, I think the bottom surface of the play area is lightly curved to prevent the circles from always falling into that packing.

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


title: What do shaders encompass?

text:
# Question
Title: What do shaders encompass?
I'm researching shaders as I'm thinking about doing them for my final year project at Uni. I've looked at a lot of examples online and I think I get it. It's something that you apply to an object or scene in order to create a desired effect without changing the original object/scene, I think. I know that there are different types of shaders but that's the basic goal right?

Furthermore, what do shaders encompass? Are weather systems in games shaders? Particle effects? Landslides? I don't know where the line is drawn between animations/cinematics and shaders. Also I guess shaders which effect something in the game world, for example, a tower blowing up in BF4. The explosion itself would be shaders but the way the tower effects the world around it would be physics and collisions. Am I right?

# Answer
Shaders are a system for specifying *how* you want something to be managed by the GPU. There a different types of shaders, such as vertex shaders, fragment shaders, geometry shaders, etc.

## Vertex Shaders:

Models are built up of points, aka vertices. In order to move that object around in a scene, that model needs a matrix to direct how each vertex of the model should be transformed in order to display it in a desired position. Further, if the camera is to move, then that camera needs a matrix as well. These matrices get multiplied together, along with the vertex for the model all on the GPU in a vertex shader, directing **where the triangles should appear on the screen**.

## **Pixel/fragment Shaders:**

Once a triangle is defined, it needs to get filled in, otherwise it would just be wireframe. Fragment shaders direct how these triangles get filled in. These can take in values such as light sources as well as textures, and **output a color for a given pixel.**

## Geometry Shaders:

Particle effects can also use shaders. These can be managed by geometry shaders - a type of shader which can **output vertices** to a vertex shader, effectively generating particles without the overhead incurred by the CPU doing it.

## A Shader program:

A shader program is when all the basic types of shaders needed are **bound together**, such as a vertex & a fragment shader. Depending on how an application is built, there can be be many many many shader programs. An application can even define a separate shader to be used for post processing effects.

---

> Are weather systems in games shaders?

No, rather custom shaders could be used to define *how* a weather system should render.

> I don't know where the line is drawn between animations/cinematics and shaders.

If it needs to display on the screen in some fashion, it will **employ** a shader program to direct how it should render.

Let me give you an example, if a box is to be rendered, the box would upload its vertices, UV's, and textures to the shader program. Next, it would use the vertex shader to direct how its triangles should appear on the screen. Then the GPU would use the fragment shader to direct how each texel should be filled in.
> 2 votes

---
Tags: shaders
---


# Question
Title: Why do FPS games often automatically reload?
*Was pointed here by Arqade's Meta*

On *every* first-person-shooter game I've played I've noticed that the 'automatically reload when empty' game mechanic is *always* used:

I've always found it annoying, and so do many others:

and many more results.

Is there a particular reason why this specific game mechanic is *extremely* common in first-person-shooter games?

A couple of *possible* reasons why:

* Makes it easy for new players
* Using the same mechanics as other games makes it easier to learn your way around the game

# Answer
> 0 votes
This type of dumbing-down happens in most genres of games. It's the same reason that most packaged foods are bland: because they are trying to find the middle ground that appeals to the widest audience. Anytime you make something appeal to the average, you end up with something average.

Most FPS games are not made for technical accuracy. Most are made to be mindless shootem-ups, made for mass consumption. While some players may not like the auto-reload, they are a minority and when it comes down to dollars and cents with a target demographic of probably 12 to 18 years old, who is the developer going to cater to? The abundant, trigger-happy gamers who get their kicks from simply blowing stuff up or the hard-core few who get their thrills from perfecting advanced tactics? It's a very different experience. Most gamers don't like having to think too much.

Simplifying the mechanics also helps to level the field between new and advanced players, which makes it more inviting to new players. This is especially true for tournament style FPS games.

If you want more realistic mechanics, then don't play games like CoD. Try games that have a lot more depth instead, like Rainbow Six.

# Answer
> 1 votes
Well, I suppose, in most cases, it doesn't hinder the player to have an automatic reload. In the gif you've provided, the player simply runs forward, interrupting the reload. Not having automatic reloads would just require the player to notice they are out of ammo. It would be a very small game design element.

---
Tags: game-design, game-mechanics, first-person-shooter
---


# Question
Title: In Physijs, how do I detect that an object is still?
I have a cylinder that simulates a flipping coin. I am using Physijs. The coin might bounce off the surface multiple times before stopping. How can I know when the coin has completely stopped moving?

# Answer
On each update event, simply check that the coin's linear and angular velocities are very small.

```
var epsilon = 0.0001; // or any small enough value for your purposes
if ( coin.getLinearVelocity().lengthSq() < epsilon &&
     coin.getAngularVelocity().lengthSq() < epsilon ) {
  // stopped moving
} else {
  // still moving
}

```

This approximation is often necessary because the velocities may not *quite* reach absolute `0`, due to simulation instability or floating-point errors, or it may take a long time to get there.

I used `.lengthSq()` rather than `.length()` to avoid a costly square root operation. When comparing to a small value, the difference in meaning is unimportant.
> 2 votes

---
Tags: 2d, physics
---


# Question
Title: How to close an app correctly on desktop?
When I use `Gdx.app.exit()` the game window closes but the resources don't appear to be released and the app is still running.

For instance, to exit on when the escape key is pressed:

```
public boolean keyDown(int keycode) {

//...

    if (Gdx.input.isKeyPressed(Keys.ESCAPE))
        Gdx.app.exit();

```

The window closes, the `dispose()` method is called but Eclipse still reports that the app is open (because the terminate button is still available):

If the app had exited properly, the path to the JVM would have `<terminated`\> in front of it, and the red terminate button would be greyed out.

Also when I use `hide()` and then `dispose()`:

```
@Override
public void hide() {
    dispose();

}

@Override
public void dispose() {
    map.dispose();
    ...
    playerHitbox.dispose();
    System.out.println("----- END OF OUTPUT -----");

}

```

The same thing happens. You have to terminate the app with the button provided by Eclipse, or in the release version use the `kill` command (or task manager).

So my question is, how can I properly exit the app so all resources are gracefully unloaded, the window hides and the process exits in LibGDX?

# Answer
I found the solution!

In my `DesktopLauncher` class, I had set `config.forceExit` to `false` instead of `true`, which caused the app to exit incorrectly (keep the running in the background.)

And there are no AL lib cleanup errors or native-related libraries having issues.
> 5 votes

# Answer
A simple `System.exit(0);` should do the trick. Depending on your project setup, `Gdx.app.exit();` could be terminating the LibGDX app, and not the entire program, where an added system exit will kill the runtime.
> 1 votes

---
Tags: java, libgdx
---


# Question
Title: What's the most efficient way to find the position of a point in relation to corners of a rectangle despite rectangle's scale
I am struggling to achieve the following with C# (in Unity). I need to find the position of the points that lay at a given distance (let's say 1m) from the corners of a rectangle, in a way that the segment between these points and the given rectangle corners form 135 degrees with the corresponding sides the of rectangle - no matter where the rectangle goes, what is its rotation or what is its size. Like the following:

So, using the picture above as reference, it means that the red dotted line has always the same length and divides the angle ABC in the middle. So, the angle of the line with AB is 135 and with BC is also 135.

One of the ways to achieve that is the following code:

```
    Vector3 dotpos = rectangle.transform.TransformPoint(rectangle.transform.localPosition.x+1.5F,0,rectangle.transform.localPosition.z+1.5F);
    bluedot.transform.position = dotpos ;

```

The problem is that in such solution the distance between the blue dot and the corner of the rectangle is not independent of the scale of the rectangle. It means, the greater the rectangle, the blue dot goes more distant from the corner.

Can anybody tell what is the most efficient way to achieve what I want, i.e. so the position of the blue dot is always at the same distance from the corner no matter the scale, position or rotation of the rectangle?

PS: blue dot is not an object that can be made child of the rectangle.

# Answer
Assuming you know world position of corner B:

```
vec3 dotpos = B - (rectangle.transform.forward + rectangle.transform.right).Normalize() * distance;

```

*note: did not checked up and right vectors are the "correct" ones(direction of AB and BC), if not just try one of the other pairs.*
You can also replace normalization with multiplication by constant of value `1/sqrt(2)` because you know the length of hypotenuse of unit square.
The `-(rectangle.transform.up + rectangle.transform.right)` is getting vector "between" AB and BC direction, minus is for inverting. It is effectively the same as computing angles.
> 2 votes

# Answer
I would do this using vectors and angles. You can get the angle that line segment AB makes with the x-axis, by doing the following:

```
angleAB = atan2(B.y - A.y, B.x - A.x);

```

You can add 45° (or π/4 radians) to that angle and project a point from B that is the length you desire by doing this:

```
newAngle = angleAB + (M_PI / 4.0);
newPoint.x = B.x + length * cos(newAngle);
newPoint.y = B.y + length * sin(newAngle);

```
> 1 votes

# Answer
You can do it like this:

```
bluedot.transform.localPosition = rectangle.transform.localPosition;
bluedot.transform.localRotation = rectangle.transform.localRotation;
bluedot.transform.localScale = Vector3.one;

Vector3 dotpos = bluedot.transform.TransformPoint(1.5f + rectangle.localScale.x / 2, 0.0f, 1.5f + rectangle.localScale.z / 2);
bluedot.transform.position = dotpos;
bluedot.transform.rotation = Quaternion.identity;

```

Here I use bluedot's transform to hold temporary values, because Unity doesn't allow using transforms without gameobjects. Rectangle.localScale.x / 2 is half the rectangle width... In the end I override temporary values with new ones. Hope you get the point.
> 1 votes

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


# Question
Title: Find x and y position with angles in 3D world
I'm actually creating a Tracking Camera (or 3rd person camera), and to do so, I used two angles (X and Y) for the rotation of the camera and an other floating value for the distance between the target and the camera.

The camera system works fine, but I am searching a way to calculate the position of the correct position of the camera (for debug purpose only)

Do you have an idea of how I can do to figure it out?

This is the camera update function:

```
public void Update(GameTime gameTime)
{
  this.View =
    Matrix.CreateTranslation( 0, 0, 0 ) *
    Matrix.CreateRotationY( MathHelper.ToRadians( this.RotationAngle ) ) *
    Matrix.CreateRotationX( MathHelper.ToRadians( this.ArcAngle ) ) *
    Matrix.CreateLookAt(
      new Vector3( 0, 0, -this.Distance ),
      this.TrackingPosition,
      Vector3.Up );

  Viewport _viewport = this.graphicsDevice.Viewport;
  Single _aspectRatio = (Single)_viewport.Width / (Single)_viewport.Height;

  this.Projection = Matrix.CreatePerspectiveFieldOfView(
    MathHelper.PiOver4,
    _aspectRatio,
    NEAR_PLAN, FAR_PLAN );

  // Find x and y
  this.Position = new Vector3( 0, 0, -this.Distance );
}

```

# Answer
> 0 votes
polar to cartesian in 3d (spherical coordinate system)

x = r * sin(theta) * cos(phi)

y = r * sin(theta) * sin(phi)

z = r * cos(theta)

where theta and phi are your x , y angles

---
Tags: c#, xna, camera, monogame, coordinates
---


# Question
Title: How are Objects rendered or updated, when there's a Pool class?
I have a State (Title State for example), that has the ResourcePool (getImage();getSound(); etc.) and a list of the GameObjects.

How do GameObjects get access to the Resources in the Pool they need?

Should the GameObjects have a reference to their resources at construction time or possibly even the pool itself?

The GameObjects render/update themselves.

# Answer
> 1 votes
I would make `ResourcePool`'s methods static. If the performance is not an issue, I would suggest accessing the resources by their name, for the sake of readability.

*ResourcePool.hpp*

```
class ResourcePool
{
    static Image & getImage(std::string & filename);
    static Sound & getSound(std::string & filename);

    static std::unordered_map<std::string, Image &> imagePool;
    static std::unordered_map<std::string, Sound &> soundPool;
};

```

Somewhere in your code

```
texture.setBackground(ResourcePool::getImage("player.png"));

```

It also comes handy if you allow modding - modders just use the transparent access by filename, and if the resource doesn't exist, you can let them know (exceptions, returning error object, or whatever suits you best).

```
ResourcePool::getImage(filename)
{
    auto iter = imagePool.find(filename);

    // If we have already loaded the image, return the reference
    if(iter != imagePool.end())
    {
        return iter->second;
    }
    // If we haven't loaded the image, try to load it
    else
    {
        Image * loaded = loadImage(filename);

        // If the image cannot be loaded, throw an exception (pass an error object/whatever)
        if(loaded == nullptr)
        {
            throw ResourceNotFound(filename);
        }
        // Otherwise insert it into the pool and return it
        else
        {
            imagePool[filename] = *loaded;
            delete loaded;
            return imagePool[filename];
        }
    }
}

```

It's also useful if you have too many resources - you can preload the most used ones and the rest is loaded on demand. On top of that, if you run out of memory, you can remove those which weren't accessed for the longest time.

# Answer
> 1 votes
An alternative solution to having the resource pool static is implementing the resource pool as a Singleton.

* leave the methods as they are
* make the constructor private
* add a variable `private static ResourcePool instance`
* add a public `getInstance()` method which checks if `instance` was already created, and when not creates it. It then returns `instance`.

Any class which needs the resource pool would obtain the instance using `ResourcePool::getInstance()`.

The advantage of this pattern is that it allows you to do complex initialization of the resource pool when it is first used, even when the programming language you use doesn't support static constructors. It also provides you with more flexibility by giving you the option to create a new class which extends ResourcePool without sharing the state with the original class.

---
Tags: resource-management, architecture
---


# Question
Title: Python - Holding down key to move a sprite works, but only in one direction
I've been testing out movement for a fighting game that I'm creating in Python.

The problem is that when I try to move the sprite, it moves correctly to the left, but only ever works in that direction. I think the problem is with my event handling loop, but I don't have much experience so I have no idea how to solve the problem. Googling and spending a while doing trial and error was no help.

My main loop looks like this:

```
pressedLeft = None
pressedRight = None
pressedUp = None
pressedDown = None

while True:

    #event handling
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_a:
                pressedLeft = True
            elif event.key == pygame.K_d:
                PressedRight = True
            elif event.key == pygame.K_w:
                PressedUp = True
            elif event.key == pygame.K_s:
                PressedDown = True
        elif event.type == pygame.KEYUP:
            if event.key == pygame.K_a:
                pressedLeft = False
            elif event.key == pygame.K_d:
                PressedRight = False
            elif event.key == pygame.K_w:
                PressedUp = False
            elif event.key == pygame.K_s:
                PressedDown = False

    # movement
    if pressedLeft:
        profx -= 5
    elif pressedRight:
        profx += 5
    elif pressedUp:
        profy -= 5
    elif pressedDown:
        profy += 5
    DisplaySurf.fill(white)
    DisplaySurf.blit(profImg, (profx, profy))
    pygame.display.update()
    fpsClock.tick(FPS)

```

# Answer
> 5 votes
You have an issue with the capitalization of your variable names.

You use a lowercase first letter for `pressedLeft`, but you're not careful with the other names (`PressedRight` vs `pressedRight`, same for up and down).

This results in the creation of never used values in your `if` blocs.

The syntax colouring helped my spot it right away.

This should do the trick:

```
pressedLeft = None
pressedRight = None
pressedUp = None
pressedDown = None

while True:

    #event handling
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_a:
                pressedLeft = True
            elif event.key == pygame.K_d:
                pressedRight = True
            elif event.key == pygame.K_w:
                pressedUp = True
            elif event.key == pygame.K_s:
                pressedDown = True
        elif event.type == pygame.KEYUP:
            if event.key == pygame.K_a:
                pressedLeft = False
            elif event.key == pygame.K_d:
                pressedRight = False
            elif event.key == pygame.K_w:
                pressedUp = False
            elif event.key == pygame.K_s:
                pressedDown = False

    # movement
    if pressedLeft:
        profx -= 5
    elif pressedRight:
        profx += 5
    elif pressedUp:
        profy -= 5
    elif pressedDown:
        profy += 5
    DisplaySurf.fill(white)
    DisplaySurf.blit(profImg, (profx, profy))
    pygame.display.update()
    fpsClock.tick(FPS)

```

---
Tags: 2d, python
---


# Question
Title: Unity C# - Raycasts, How to Ignore Triggers?
Let's say I have a Raycast, but I don't want it to collide with any triggers. I don't want to change the Project settings since that's a little inflexible.

How can I have a Raycast ignore any triggers?

# Answer
> 7 votes
There is a (optional) parameter for that in Physics.RayCast which is available in Unity 5.2 and up:

```
public bool RaycastNoTriggers(Vector3 startPosition , Vector3 direction, float distance)
{
    Ray ray = new Ray(startPosition, direction);
    RaycastHit hit;
    return Physics.Raycast(ray, out hit, distance, DefaultRaycastLayers, QueryTriggerInteraction.Ignore);

}

```

# Answer
> 0 votes
Select a tag to all triggers called "Ignore Raycast" this will make the Ray ignore the triggers and pass through.

# Answer
> -1 votes
```
public bool RaycastNoTriggers(Vector3 startPosition , Vector3 direction, float distance)
{
    Ray ray = new Ray(startPosition, direction);
    RaycastHit hit;
    Physics.Raycast(ray, out hit, distance);
    if (hit.collider != null && !hit.collider.isTrigger) {
        return true;
    }
    return false;

}

```

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


title: set sprite to current animation texture

text:
# Question
Title: set sprite to current animation texture
In my game I have some box2d bodies where I add sprites using the following code in my `render()` method.

```
for (Body body : worldBodies) {
        if (body.getUserData() instanceof Sprite) {
            Sprite sprite = (Sprite) body.getUserData();

            Vector2 position = body.getPosition();
            sprite.setPosition(position.x - sprite.getWidth() / 2 , position.y - sprite.getHeight() / 2);
            sprite.setRotation(body.getAngle() * MathUtils.radiansToDegrees);
            sprite.draw(batch);
        }
    }

```

One of the bodies has to be animated.

```
birdAnimation = new Animation(1, birdAtlas.getRegions());
birdAnimation.setPlayMode(Animation.PlayMode.LOOP_PINGPONG);

```

This is the animation and now I tried to set the body's sprite `obstacle6` to the current textureRegion from the Animation unsing this code:

```
obstacle6.setRegion(birdAnimation.getKeyFrame(delta));

```

Somehow it just shows the first texture of the atlas. How can I get it to change? Or is there an other way to animate a box2d body? If you need any other information just comment.

# Answer
Don't pass `delta` to `getKeyFrame`, `getKeyFrame` takes the state time. The state time is likely something like the sum of all the `delta`s you've seen so far.

The state time indicates how "far" into the animation you've gone, and by constantly passing `delta` (which if you're running at 60 fps will be 0.016s) the `Animation` will always yield the first frame.
> 1 votes

---
Tags: libgdx, animation, box2d
---


# Question
Title: How does the Unity3D entity system work?
I saw the Java Artemis Entity Component System and thought of the entity system in Unity3D.

In Artemis for example you can only add one component type to each entity and the logic is not in the component.

In Unity3D it's completely different. Can someone explain me how the entity system in unity 3d works?

I mean, is Unity3D a real entity system, or is it something else?

# Answer
> 5 votes
Yes, it's still an entity system. There's no strict definition for how an entity system should work, so it's OK that it's different from Artemis. Both still have entities that are composed of components.

The goal of an entity system is to move away from inheritance based designs. Unity's system accomplishes this goal.

Similar to Artemis, you can add components to an entity to make a new object. Changing the data in the components can, on a surface level, drastically change the object produced. Some key differences are where the logic is stored, and how components are grouped for processing. While these differences might seem dramatic, they're not too different. Both approaches can be modified to be even more similar. For example, you could create components with just data in Unity, and create "system" that finds all the game objects with specific components and processes them.

Either way, you're going to have components and entities. Where the entities are not derived from a long list of inherited classes. This reduces code duplication, trims out unnecessary code and data and gives you an easy way to think about how objects are created.

# Answer
> 1 votes
Unity3D works on top of GameObject-Component model. It's so much different than Entity Component Systems. To my experience it's worse because when you want to code some logic it's put into Script Component, instead of Systems. How different is it to OOP model? Unity3D GameObject contains data and logic - same as in OOP, those components aren't reusable (which is one of reasons for not doing OOP). Of course, you can make some bulletproof conventions which will hold you from mixing data and logic but it might be a pretty hard work to do so continously.

Dependencies. When you work in ECS, every System has an Aspect (it's described which components it manages). Thanks to the Aspect your Components are depended by System and not by other Components. I've seen code where few Components were referencing to each other. When order of execution wasn't set properly, then... total mess. When you refactor Component (logic) dependencies it's better to do it in ONE place, like System, instead of few places (Components).

The another great disadvantage of model used in Unity3D is a problem to manage objects of same Aspect (set of components). In my opinion it is best to go ECS way if possible or something more closer to it. To take that approach in Unity3D, look at @Byte56 answer.

# Answer
> 1 votes
Although definitions can vary, I wouldn't define Unity3D as an Entity System engine. When we talk about Entity System, we should follow the Adam Martin definition.

According his idea, the Systems should be created by the programmer, while in Unity3D the "systems" are predefined in the engine and cannot be extended.

This is an old way to manage Entities and Components, it's more an evolution of the ancient technique where game objects were holding pointers to components compatible with the engine functionalities (like rendering, culling and so on).

Of course when is not possible to extend the "Systems" functionalities, the only way to extend the logic of our entities is to add logic inside Components. This is anyway a step forward from the classic OOP techniques. Component Oriented (I call them Entity Component, without System) frameworks like the one in Unity, push the coder to favor Composition over Inheritance, which is surely a better practice.

All the logic in Unity should be written inside focused MonoBehaviour. Every MonoBehaviour should have just one functionality, or responsibility, and they shouldn't operate outside the GameObject itself. They should be written with modularity in mind, in such a way they can be reused independently on several GameObjects. Monobehaviours also hold Data and their design obviously follows the basic concepts of OOP.

Modern design tends instead to separate data from logic. See for example the MVC or MVP patterns. Data, Views and Logic should be separated to achieve a better code modularity.

The real problem with the Unity Entity Component design is about the complexity needed to put two entities in communication in a reasonable way that doesn't lead to the use of various anti-patterns.

Unity inverts the control of the creation of entities, thus the coder doesn't have any control on the creation of them. Inverting the creation control is a good thing, but Unity doesn't do it in a proper way. Not being able to inject dependencies in Entities is a limitation that forces coders to use anti-patterns in order to overcome all the intrinsics consequences.

Eventually the cleanest option available is to use Singletons in order to share information between entities.

That's why is quite hard to manage and maintain big projects with Unity. I wrote a lot about these problematics in my blog. So if you want you can continue reading my thoughts there:

http://www.sebaslab.com/ioc-container-for-unity3d-part-1/

http://www.sebaslab.com/ioc-container-for-unity3d-part-2/

http://www.sebaslab.com/the-truth-behind-inversion-of-control-part-i-dependency-injection/

http://www.sebaslab.com/the-truth-behind-inversion-of-control-part-ii-inversion-of-control/

http://www.sebaslab.com/the-truth-behind-inversion-of-control-part-iii-entity-component-systems/

http://www.sebaslab.com/the-truth-behind-inversion-of-control-part-iv-dependency-inversion-principle/

http://www.sebaslab.com/the-truth-behind-inversion-of-control-part-v-drifting-away-from-ioc-containers/

In these posts I extensively discuss about the Unity3D design flaws that hinder the development of big projects and both IoC container and Entity Component System framework as possible solutions.

---
Tags: unity, 3d, architecture
---


# Question
Title: Calculate the extreme points of a quadrilateral
Given four points (a,b,c and d) how do I find the extreme points (b,d) from the perspective of the player (p).

I was trying to do it by finding the angle to the centre of the quadrilateral then checking for the furthest point either side but that obviously wouldn't work when the player is parallel to a point.

Any nudges in the right direction would be welcome.

# Answer
> 1 votes
I would pick any point on the shape\* as starting value of extremes and iterate over all other points on shape testing whether they lie on left/right side of line from P to left/right extreme respectively, reassigning value if new extreme is found:

```
void extreme_points(Point& left, Point& right, Point& p, std::vector<Point> polygon)
{
  left = right = polygon[0];
  for(auto v : polygon)
  {
    if(isLeft(p, left, v) > 0.0)
    {
       if(abs(isLeft(p, right, v)) > Epsilon)
         left = p;
       else { /*handle special case where P is parallel,*/}
    }
    if(isLeft(p, right, v) < 0.0)
    {
       if(abs(isLeft(p, right, v)) > Epsilon)
         right = p;
       else { /*handle special case where P is parallel,*/}
    }
  }
}

```

where isLeft is well-known "sign test". Example of implementation:

```
float isLeft( Point P0, Point P1, Point P2 )
{
    return ( (P1.x - P0.x) * (P2.y - P0.y)
           - (P2.x - P0.x) * (P1.y - P0.y) );
}

```

You may also want to handle cases for *almost* zero values(all three points are on the same line) picking, for example, the closer one. You can also find a library with more accurate isLeft implementation.
\*this should work for any convex and star-shaped polygons.

---
Tags: mathematics
---


title: Slingshot gravity effect

text:
# Question
Title: Slingshot gravity effect
I am trying to make a sling-shot that fires a projectile. I want it to act like the standard sling-shot in angry birds.

So far I managed to get the "pulling" effect, ie. If I draw backwards it fires in the opposite angle of the direction my finger went, and with different speeds depending on how far I dragged the finger from the "start-position".

Touch Code/logic:

```
@Override
    public boolean touchUp(int screenX, int screenY, int pointer, int button) {
        touchPos.set(screenX, screenY, 0);
        camera.unproject(touchPos);
        Vector2 temp = new Vector2(touchPos.x, touchPos.y);

        Vector2 d = temp.sub(startPos); //subtract finger-position from start-position
        float velX = d.x * FIRE_SPEED; //add speed
        float velY = d.y * FIRE_SPEED;
        d.set(velX, velY); // set the velocity

        projectile.setVelocity(d); //send velocity to object
        projectile.setFired(true); //signal the object that its been fired

        return false;
    }

```

Object Code:

```
public void update(float delta){
        if(fired){
            pos.x -=  velocity.x * delta; //since I want it to move the opposite direction of where I dragged, I subtract
            pos.y -=  velocity.y * delta;
        }
    }

```

How would I go about adding gravity here? I want it to shoot in the set direction, then after a certain time/distance I want it to start falling (taking into account the direction so that it looks like real gravity), exactly as in angry birds.

# Answer
> 1 votes
You add the gravitational acceleration to the vertical component of velocity.

```
    if(fired){
        pos.x -=  velocity.x * delta; //since I want it to move the opposite direction of where I dragged, I subtract
        pos.y -=  velocity.y * delta;
        velocity.y += g*delta;
    }

```

# Answer
> 1 votes
Gravity is a constant downward acceleration. Acceleration is a change in velocity.

Simply subtract a constant value from `velocity.y` every update.

```
public void update(float delta){
    if(fired){
        velocity.y -= GRAVITY * delta;
        pos.x -=  velocity.x * delta;
        pos.y -=  velocity.y * delta;
    }
}

```

The ideal value for GRAVITY depends on the scale of your game and is something you need to find out through experimentation.

---
Tags: java, physics, libgdx
---


# Question
Title: Assigning Objects when duplicated in the editor?
I'm wondering if there is a way to have an Object when duplicated in the editor assign a GameObject variable to the newly duplicated version of itself. Is there an option in Unity or do I have to code it out.

So I would like it to follow these steps:

1. So I would have the old GameObject with the variable named "nextStop" with nothing assigned to it.
2. Then I duplicate said object and the older object's variable is assigned to the newly duplicated object.
3. Done.

I'm doing this for a rail editor to make it easier to create new rails to follow.

I would like not to have to assign to each and every Object it will make things so much easier to explain for others to use. "Just duplicate these objects."

And in case you need it and Unity doesn't already have an option built in here's my code for the track.

```
using UnityEngine;
using System.Collections;

public class Rails : MonoBehaviour {

    public GameObject nextStop;
    LineRenderer myLine;
    public bool endLevel = false;
    public Train myShip;
    void OnDrawGizmos()
    {
        if (nextStop) {
            Gizmos.color = Color.green;
            Gizmos.DrawLine(transform.position, nextStop.transform.position);
        }
    }
    void OnTriggerEnter(Collider other)
    {
        if (other.gameObject.tag == "train")
        {
            if (nextStop)
            myShip.track = nextStop;
            if (endLevel)
            {
                // Load the next level
            }
        }
    }
}

```

Oh yeah I should mention I have little experience modifying code to do things in the editor.

# Answer
> 1 votes
As Editor code goes, this is pretty straight forward, so don't worry. I would do it as a context menu for the component.

```
using UnityEngine;
using UnityEditor;

public class Rails : MonoBehaviour
{
    public Rails NextStop;

    [ContextMenu("Copy And Point")]
    public void DoThing()
    {
        var copy = Instantiate(gameObject);
        var rails = copy.GetComponent<Rails>();

        rails.NextStop = this;

        Selection.activeObject = copy;
    }
}

```

Then, in the inspector panel, you can right click on the rails component and select "Copy and Point."

This will create a copy of the current game object and point the next stop to this one. The last line will make sure that the new object gets focus in the editor.

Hope it helps!

---
Tags: c#, level-design, unity, gameobject
---


# Question
Title: Why is my delta time constantly under 1 millisecond?
I have a game loop that looks like this:

```
while (Sync())
{
    DoStuff();
}

```

The sync function computes my delta time like this:

```
bool Sync()
{
     EndTime = GetTime();
     DeltaTime = (EndTime - StartTime) / TimerFreq
     StartTime = EndTime

}

```

However the delta time I compute is not correct. The DeltaTime should be in milliseconds but I always end up with less than 1 millisecond... Clearly this is not right.

# Answer
**Yes, it is right.**

Computers are really fast nowadays and you are not computing anything in DoStuff enough expensive to expend more than 1ms.
> 3 votes

---
Tags: c++, algorithm, game-loop, timing
---


# Question
Title: How do I implement an item that can hold other items?
I'm attempting to implement a "storage item" into my game. But I'm having trouble planning out how it would work. I already have an inventory system made, but this storage item is giving me trouble.

The storage item basically acts as a pouch you hold in your inventory, like a coin purse that holds money, or a potion sack that holds your potions.

So far I have the following:

```
public class Inventory{
    public ItemStack[] inventory;
}
public class ItemStack{
    public Item item;
    public int amount;
}
public abstract class StorageItem : Item{
    public Item storedItem;    //Specific Item the StorageItem can contain.
    public int storedMax;      //Maximum amount the StorageItem can contain
    //StorageItem's Item.maxStack = 1; Should never be stackeable, but should hold stacks of storedItem
}
public abstract class Item{
    public int id;
    public string name;
    public int maxStack;
}

```

Does anyone have an idea how they would get `ItemStack` and `StorageItem` to work together in an inventory system?

Example: If I wanted to add a health potion, my inventory would search through, find all existing stacks, (including storage items holding health potions), and attempt to fill them. But the `ItemStac` that holds the `StorageItem` already has an amount, which corresponds to the actual `StorageItem` rather than the item it stores. And since `StorageItem` should never be stack on itself (but stacks other items in itself), it is always 'full'.

# Answer
You're thinking about this a little to much. You really only need 2 things: An array for inventory, and items to put in the array.

```
Object[] inventory;

public abstract class item{
    public int id
    public string name;
    public int maxStack;
    public int amount;
}
//down the road to use this:
item x = new item(id, name, maxstack, 1);
inventory.push(x);

//inventory[0] is now x with 1 of them stored
int y = inventory[0].amount; //y = 1
Debug.Log(y); //logs 1
inventory.RemoveAt(inventory[0]);

```

This is a very simple way to use it, but might not be copy pastable. The real theory here is to create an array for the player that is an inventory. Then create an item to put into inventory(needs to know how many of itself are in the stack) and push them onto the array.

EDIT: saw your comment on another post. If the case is that you want to change how many max stacks you can have it's EASY. Simply:

```
newMax = 50000;
inventory[0].maxStack = newMax;
//as long as you setup your permissions or mutators correctly this will work

```

Now if you're meaning to start storing stacks of things in an inventory that's easy as well with just a two dimensional array by creating a sub inventory(an object with an array in it)

```
public abstract class Bag = {
    public object[] contents;
    public int maxObjects;
    public function addTo(item item){
        if(contents.Length < maxObjects){
            contents.push(item);
        }
    }
}

//put that bag into inventory
inventory.push(new Bag(maxObjects)); //bag is now in inventory at [0]
//the constructor should know how to handle creating an empty array

inventory[0].addTo(Item);

```

So there are a couple of examples that should help you think about this in a different way.
> 1 votes

# Answer
If you don't want the inventory to have a specific layout (like 2D grid or something else) you can just have a `HashSet<ItemStack>`.

HashSet

You can extend your class `Inventory` to have methods such as `Add` or `Remove` to find an item of the same class already stored, and increment or decrease the amount of items in stack

A possible solution could be to implement IEqualityComparer in ItemStack so you can't have duplicates.
> 0 votes

# Answer
After gathering different Ideas from multiple sources, I think I've found what I'm really looking for. For those who come along and ask the same question I'll post what I've found adequate here.

I've decided to create a new class called ItemContainer, which my StorageItem, and Inventory will inherit from. Thusly making my StorageItem a mini-inventory.

ItemContainer will have methods like addStack, removeStack, etc. But if I want to add an Item to a StorageItem, I'd simply have to check if the StorageItem holds the Item I want to add, and then call the StorageItem's ItemContainer to add the item to it. Effectively putting Items into another Item.
> 0 votes

# Answer
*While this is a very simple, and undoubtedly effective way to manage an Inventory, I already have an Inventory System working. What I truly wanted was to "Put Items into another Item". ex: Coins into a Coin Pouch. Potions into a Potion Sack. Or in a more general sense: Items into an ItemBag*

Ultima Online's solution uses containers inside containers (backpacks, bags, crates...).

Just let your class `Inventory` extend `Item`.
> 0 votes

---
Tags: unity, rpg, inventory
---


title: Recording narration for a game

text:
# Question
Title: Recording narration for a game
I am the narrator for a RPG game I'm creating. I have two questions:

1) **Quality**: I have a mic that seems to pick up a lot of background static along with my voice, so the overall quality sounds terrible. Is there a specific type of mic that should be used for game narration?

2) **Performance**: Narration quality is important for the game, but there will be many audio files. Is there a method to delivering quality audio files while compressing the file? Since it's narration, I need the audio to be snappy and clear.

# Answer
> 2 votes
**Quality** \- No, not really. I've made quality audio files with the cheap mic that came with my computer over 20 years ago. Nowadays, though, when that doesn't cut it I use the same mic I use for music, which is a Shure SM58. Use a pop filter and/or the noise reduction features of your recording software. Lowering the gain/recording volume of your mic will also cut down on general background noise. You don't, as previously suggested, need to build a sound booth. I've worked on professional projects where the audio was recorded in the office. The sound engineer just closed the door and told everyone to keep it down while they were working. Read the reviews of various USB/DI mics in your budget range and pick the one you like the best.

**Performance** \- The lowest sampling rate I've used was 11khz. It sounded fine, but it wasn't "granular" enough for the lip-synching software I was using to pick up much in the way of nuances. You should probably just stick to the default 44khz, 16-bit standard that most recording is done at.

# Answer
> 1 votes
You can do a lot but preventing the background noise from reaching the mic.

This requires building a sound booth of some description where you will be recording your voice.

For which microphone to use is offtopic here. A crap setup will give crap quality. The 3.5mm microphone jack you will find on most computers will not give good quality.

# Answer
> 0 votes
Well, talking about the quality thing, I think yeah mic does play a role but even a decent mic can do the job, I have done this for recording my voice in walkthrough videos for my gaming channel, I would suggest you to use audacity, its a great free tool available learn how to use it efficiently by seeing YouTube videos, it is going to help for sure. And about the performance adobe audacity can be very helpful here to deliver good and compressed quality audio file.

---
Tags: rpg, audio
---


title: iOS game center game is out of sync

text:
# Question
Title: iOS game center game is out of sync
I've been building a game center game for iOS and it works great so far. I finally started testing the game and theres (obviously) some latency, which is causing the game to be out of sync.

Basically I have 2 players, each controlling a game character. The game character can shoot fireballs and iceballs etc. These attacks do damage, and they have effects. For example. the ice ball effect will freeze the opponent for 3 seconds if it makes contact. the fireball will do extended fire damage for 3 seconds.

so the problem is, when I was playing against my brother, because of the latency, my game said I had 40 health left and he was down to 0, while on his device, the game said I had 0 and he had 20.

This means that attacks were registering/colliding on one device (based on the positions of the characters/fireballs) and not on the other. and vice versa.

I'm currently using the default peer-to-peer game-center architecture. Would using a client-server architecture (one person becomes the server) solve this out-of-sync problem?

if not, what other options do I have with the game kit API?

# Answer
> 1 votes
I've found a solution to this problem.

> Note: this will be a relatively long answer.

One thing that I did implement was the use of `udp` for some of my data transfers that are not as critical as others. For example, since I'm sending movement data about 10 times a second, I figured its ok if 1 or 2 of the 10 get lost once in a while.

---

**Now to the actual problem:**

---

So what was happening is the following- since I'm using a `p2p` architecture, both clients have a delay when they see the game 'world'. This means that on my device, I see the enemy player at a position that is delayed 100-200 milli seconds. (so he was actually there 100-200 ms in the past).

The problem with this, is that, when I shoot a projectile at the enemy, and I see a collision, if the collision was right on the edge of his sprite (his feet or head), in his screen, he was already past that position - PLUS - my fireball appears 100ms delayed on his screen. This means on his device, he was able to dodge my attack. This can happen a random number of times, but I'd guess its probably below 30% of the time. 70%, both devices see the collision.

---

**The solution**

---

What I came up with is to send a message to the other player when either device sees a collision. And remember, each device has no idea if the other saw a collision or not. So I have no way of knowing whether both devices saw a collision, or only 1, and the other saw that the attack was dodged.

This means I have to send a message to the other player every time theres a collision. Now, because of the way I've architected my game, when a collision is sent, I'm automatically applying the collision event (meaning, damage dealt, projectile effect that took place - like ice bolt freezing the player it collided with) This is problematic, because what if both devices saw the collision. That means both devices are sending each other a message of collision, and applying collisions again.

To get around this, I've added a "spell number" to each spell/attack, and when a collision happens, I save this number with the player that the collision happened with as the "last collision spell number". So if a collision takes place with that spell, the player knows he/she already collided with that specific object, so collision logic doesn't run twice.

---
Tags: ios, multiplayer, client-server, game-center, peer-to-peer
---


# Question
Title: How to not render what is behind object?
I am working on a 3d project using openGL. I am looking for a way to optimize my renderings. Is there a way to tell if an object is behind another object and thus not visible to not waste time rendering it ? I am already working on a frustrum culling implementation to not display what is not visible because out of the viewing frustrum, but I didn't find a way to know if an object in located behind another object. Can any of you help me about this, please ?

# Answer
> 4 votes
If you aren't doing any depth testing, then you can use the OpenGL **depth test** functionality to prevent further away texels from getting filled in (relative to the view port), this way only the texels that are closest to the view frustum are rendered.

To do this you execute:

```
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LESS);

```

And when you clear your screen at the start of every frame, also perform this line (after the lines posted above)

```
glClear(GL_DEPTH_BUFFER_BIT);

```

Further, if you render this scene to an custom Frame Buffer Object (FBO) (rather than your default FBO), and employ a deferred shading technique, you could substantially improve performance by only applying fragment shader calculations to the physical 2D image of your scene stored in the FBO.

That technique can be used like this:

* render the scene to an FBO
    + Output fragment world positions to a texture, only closest fragments to the camera get used
    + Output scene textures merged into a screen-space texture
* render a quad in front of the camera
    + quad's fragment shader sample's from the screen-space texture given the positions in the position texture

That technique is quite useful for when there is lighting and other effects going on, as the lighting calculations are bounded to areas on influence and only occur on the small regions of pixels that actually make it to the screen.

---
Tags: opengl, 3d
---


# Question
Title: How do I move a sprite with out the sprite leaving a trail?
NEW IMAGE NO SPRITE WITH :

```
   if(q>=15){
        screen.clear(0);
        screen.render(Art.sprites[i][0], 20 , cx);
        i++;
        movement();
        cx+=1;
        if(i>=3)i=0;
        q=0;

    }

```

This sprite leaves a trail and I can't find a way to fix it. I spent close to a good 2 hours trying to look online for it and could not fix it if someone could help that would be great. \<3

Note: The sprite is drawn in the "render" method. (I hope that there is enough information. Also 1st time working with sprites)

```
import java.awt.Canvas;
import java.awt.Color;
//import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferStrategy;

import javax.swing.JFrame;

 import me.matt.tower.gfx.Art;
 import me.matt.tower.gfx.Screen;

  public class TowerComponent extends Canvas implements Runnable{

/**
 *
 */
private static final long serialVersionUID = 1L;
public static final int WIDTH = 640, HEIGHT = 480;
private boolean running =false;
public static final String NAME = "Tower Of Death";

private Screen screen;
public int q=0;
public int i=0;
public int cx= 20;
public int cy= 20;

public TowerComponent (){
    screen = new Screen (WIDTH, HEIGHT);

}

public void stop(){

    running = false;

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

@Override
public void run() {
    int fps = 0, tick = 0;

    double fpsTimer = System.currentTimeMillis();

    double nsPerTick = 1000000000.0d / 60;
    double then = System.nanoTime();
    double unprocessed = 0;

    while(running){
        boolean canRender = false;
        double now = System.nanoTime();

        unprocessed += (now-then) / nsPerTick;
        then = now;
        while (unprocessed >=1){

            //Updates game objects
            tick++;
            tick();
            canRender = true;
            --unprocessed;

        }

            try {
                Thread.sleep(1);
            } catch (InterruptedException e) {

                e.printStackTrace();
            }
            //draws game objects
            if(canRender){
                fps++;
                render();
            }
            //FPS Counter Report
            if(System.currentTimeMillis()- fpsTimer >1000){
                System.out.printf("%d fps, %d tick%n",fps,tick);
                fps = 0; tick =0;
                fpsTimer +=1000;
            }

    }

}
private void render() {

    BufferStrategy bs = getBufferStrategy();
    if(bs == null){
        createBufferStrategy(2);
        requestFocus();
        return;
    }
    Graphics g = bs.getDrawGraphics();
    //Rendering

        q++;// counts frames.... use fps count later?

    if(q>=15){
        screen.clear(0);
        screen.render(Art.sprites[i][0], 20 , cx);
        i++;
        movement();
        cx+=1;
        if(i>=3)i=0;
        q=0;

    }
    //done rendering

    g.drawImage(screen.image, 0,0, WIDTH,HEIGHT,null);

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

public void movement(){
 cx+=10;
 cy+=10;
 screen.clear(0);
 repaint();
 }

private void tick() {

}

public static void main(String [] args){
    TowerComponent game = new TowerComponent();
    Dimension dimension = new Dimension(WIDTH,HEIGHT);
    game.setMaximumSize(dimension);
    game.setMaximumSize(dimension);
    game.setPreferredSize(dimension);
    game.setSize(dimension);
    JFrame frame = new JFrame();
    frame.setTitle(NAME);
    frame.add(game);
    frame.pack();
    frame.setResizable(false);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
    frame.setLocationRelativeTo(null);
    game.start();

}

}

```

Bitmap class

```
package me.matt.tower.gfx;

import java.util.Arrays;

public class Bitmap {

public int w,h;
public int [] pixels;
public Bitmap(int w , int h){
    this.w = w;
    this.h = h;
    pixels = new int [w*h];
}

//public void clear(int color){
//  Arrays.fill(pixels, color);
//}
public void render(Bitmap bitmap, int x, int y){
    int x0= x;
    int x1 = x + bitmap.w;
    int y0=y;
    int y1 = y + bitmap.h;
    if(x0 <0)x0=0;
    if(x1>w) x1 = w;
    if(y0 < 0)y0=0;
    if(y1 >h) y1=h;
    int ww = x1 - x0;

    for (int yy= y0; yy < y1; yy++){
        int tp = yy *w +x0;
        int sp = (yy - y )* bitmap.w + (x0 -x);
        tp -= sp;
            for(int xx = sp; xx < sp + ww; xx++){
                int col = bitmap.pixels[xx];
                if (col < 0) pixels [tp+xx] = col;

        }

    }
}

}

```

Screen class

```
package me.matt.tower.gfx;

import java.awt.image.BufferedImage;
import java.awt.image.DataBufferInt;

public class Screen extends Bitmap{

public BufferedImage image;

public Screen(int w, int h) {
    super(w, h);
    image = new BufferedImage(w ,h , BufferedImage.TYPE_INT_ARGB);
    pixels = ((DataBufferInt)image.getRaster().getDataBuffer()).getData();

}

}

```

Art class

```
import java.io.IOException;

import javax.imageio.ImageIO;

import me.matt.tower.TowerComponent;

public class Art {

public static final Bitmap [][] sprites = cut("/SpriteSheet.png", 32 ,32);
private static Bitmap[][] cut(String string, int w,int h){
    return cut(string ,w,h,0,0);

}

private static Bitmap[][] cut(String string, int w, int h, int sx ,int sy){
    try {
        BufferedImage image = ImageIO.read(TowerComponent.class.getResourceAsStream(string));
        int xTiles = (image.getWidth()- sx)/w;
        int yTiles = (image.getHeight()-sy)/h;
        Bitmap[][] result = new Bitmap[xTiles][yTiles];
        for(int x= 0; x< xTiles;x++){
            for(int y=0;y< yTiles;y++){
            result[x][y]=new Bitmap(w,h);

            image.getRGB( sx + x * w, sy + y * h,w,h,result[x][y].pixels,0,w);
            }
        }

        return result;
    } catch (IOException e) {

        e.printStackTrace();
    }
    return null;
    }

}

```

# Answer
The way a computer draws to the screen is very different to say... how we draw on a piece of paper. The computer actually is flipping bits on a memory array, called the *video memory*. This memory array happens to be represented on the screen as an image a human can understand. With this in mind, let's start:

When you draw a sprite—several times, on different positions and without clearing the screen first—the PC actually grabs the array representing the sprite and copies the values into its video memory, **but only modifies the region that the sprite will occupy.** This means that whatever was already on the video memory will still remain there, leading to something similar to this:

So in order for you to prevent this to happen, you **totally clear** all the bits on the video memory that represent the screen to a certain color, and then draw your new sprites all over again. Of course you only clear the screen **once** and only **once** per frame, not for every sprite (which I think is what happened on your second example screenshot).

The process can be outlined like this:

1. You clear the screen to whatever color you like.
2. You draw all that needs to be drawn on a single time step of your game.
3. You flip the display if you have Double Buffering enabled.
4. Repeat.

So, I think I misunderstood how the drawing works in your specific code, but the thing is that you have to find the spot outside any loop that draws objects and clear the screen there, just in time before starting to draw the new frame.

While this example example uses a different language (C) on a different API (Allegro 5) this section applies the process quite well:

```
al_clear_to_color(al_map_rgb(0,0,0));

al_draw_bitmap(bouncer, bouncer_x, bouncer_y, 0);
al_draw_bitmap(ball, ball_x, ball_y, 0);
al_draw_bitmap(monster, monster_x, monster_y, 0);

al_flip_display();

```

*Note: The code on the link doesn't have the ball and monster lines, I just added them to exemplify point 2 of the process I described above.*
> 4 votes

---
Tags: sprites, movement, spritesheet
---


# Question
Title: Applying the input for the always-moving player in the multiplayer game
I've read several articles published on gambrielgambetta.com, gafferongames.com plus some pages about how Valve handles multiplayer networking in its games but I still can't get it how to implement the client-side prediction for my game where the player's always moving and he controls the speed by pressing the spacebar. When the client input has arrived the server already had simulated the world using the old velocity values. So we get a stretch in time.

Let's imagine that the player is moving between the 0.0 and 1.0 values. The current position is 0.2. The normal speed is 0.1. The "crawling" speed is 0.05.

Let's assume the server and the client have framerates both fixed and the latency is two steps high.

> STEP 0
> server 0.2
> client 0.2
>
> STEP 1
> server 0.3 (+0.1)
> client 0.3 (+0.1)
>
> STEP 2
> server 0.4 (+0.1)
> client 0.4 (+0.1)
>
> STEP 3 (Spacebar's pressed)
> server 0.5 (+0.1)
> client 0.45 (+0.05)
>
> STEP 4 (Spacebar's still pressed)
> server 0.6 (+0.1)
> client 0.5 (+0.05)
>
> STEP 5 (Spacebar's still pressed. Finally, the input has arrived)
> server 0.65 (+0.05)
> client 0.55 (+0.05)
>
> STEP 6 (Spacebar's still pressed)
> server 0.7 (+0.05)
> client 0.6 (+0.05)
>
> STEP 7 (Spacebar's released. Input was sent)
> server 0.7 (+0.05)
> client 0.7 (+0.1)
>
> STEP 8
> server 0.75 (+0.05)
> client 0.8 (+0.1)
>
> STEP 9 (Input has arrived)
> server 0.85 (+0.1)
> client 0.9 (+0.1)

It looks like nothing's wrong with this data while every multiplayer game's trying to hide the latency. But what if the periods of pressing the spacebar are different and the latency is different and the server and client have different framerates. I can't use the input duration when updating the player position because it allows the player to cheat (just lower the duration and you will start moving slower). And the server reconciliation works not very good since I'm getting the effects derived in the statistics above. When pressing the spacebar the player just jumps back and starts moving slower. So I need to compensate that somehow.

The core of the problem is how to handle the player input when the user can only decrease the speed of the character while the character's moving with the predefined speed.

# Answer
To do server reconciliation, you not only need to know **what** the client inputs are, but **when** they were made. That means when the player sends "pressed space", you need to know when that input was actually made. An easy way to do that would be for the client to send it, i.e. "pressed space on step 3". You could also guess on the server side, "the client is approximately 2 steps behind, so when I receive a press space on step 5, it actually happened on step 3". Each method has its merits but the important part is that you figure out when the commands happened.

Once you have that, the server needs to be able to **apply commands that happened in the past**. When this happens, movement will become discontinuous for the server and other clients, but at least the positions will be synchronised most of the time. When you have multiple clients, you also need to deal with the possibility of **paradoxes**, i.e. if two clients both want to travel to the same position, but due to the effects of latency, none of them think they are running into each other. As the server you'll need to decide what happens, one way or the other, and tell the client(s) "nope, due to a collision in the past, your current position is actually *here*".

But without going too deep (and it goes pretty deep), here's what things would look like, in a table:

```
    Space (C)   Position (C)   Position (S)   Space (S)                                        Notes
--- ----------- -------------- -------------- ----------- ----------------------------------------------------------------------------------
0   N           0.2            0.2            N
1   -           0.3            0.3            -
2   -           0.4            0.4            -
3   Y           0.45           0.5            -
4   -           0.5            0.6            -
5   -           0.55           0.55           Y           Server rewinds to step 3, reapplies movement using the slow speed for frames 3-5
6   -           0.6            0.6            -
7   N           0.7            0.65           -
8   -           0.8            0.7            -
9   -           0.9            0.9            N           Server rewinds to step 7, reapplies movement using the fast speed for frames 7-9

```

Note that on step 5, it would appear that the client moves backwards, and on step 9 the client jumps forwards. To make this look nicer, some games will interpolate the jump over a number of frames.
> 3 votes

---
Tags: networking, multiplayer, lag
---


# Question
Title: Call touchUp() programattically for sprite in LibGDX
I'm trying to call touchUp() for a sprite i've created in my app.

i'm getting success but the co-ordinates do not match while i call it manually.

```
final int x = (int)mySprite.getX() + 10;
final int y = (int)(Gdx.graphics.getHeight() - (mySprite.getY() - 5));

touchDown(x, y, 0, 0);

```

this code calls method perfectly but positions do not match. x and y values that i get in touchUp() method is different. it call touch up event of another sprite.

# Answer
> 1 votes
you have to unproject your coordinates

```
  getCamera().unproject(new Vector3(actorX,actorY,0))

```

this method gives you a Vector3 with the coordinates you want. If you want to do the opposite call project() method

---
Tags: libgdx
---