# Question
Title: How do you manage a crowdfunding campaign for an indie game?
I am a programmer and I recently started creating small games in C++. It was to practice my skills and learn more about game development and the techniques used to program a game. Recently I got the idea to create an indie game with a friend of mine, but the problem is that the development has to be funded so we can actually make time to create it. So the first thing that popped into my mind was the idea to kickstart it on kickstarter.com. This is a commonly used method to gain attention for the development and get people to fund it, but when I look at the projects submitted in the 'Video Games'-category and sort them on end date, I find out that only about 10% will reach their goal in time. What I notice is that almost every successfully funded project has a good story and a nice amount of promising concept art. But it doesn't seem to guarantee a successful kickstart. I also see a lot of games which have all the things that would make them succesful, but somehow they they don't really seem to get off the ground. I have the feeling that there has to be some advertisement done to gain more attention, but also make it attractive and rewarding enough to get people to fund your project. I've listed a few things I think will greatly improve the amount of money raised below:

* **Make it look attractive:** This means there has to be a nice logo or an image representing the game that attracts people. Also there need to be a lot of things that show what the final product will look like and what the game currently looks like in some gameplay. The concept art will define the style that the game will have, but also create an attractive cinematic promise.
* **Video of project:** A youtube video that represents the game will probably be a very good way to explain the way the game works, is played and show some insights. By talking to the viewer as the developer you get more personal and really encourage them to fund.
* **Rewards:** To get people to fund your game, you have to make it as attractive as possible by creating a good reward-system. The more money they fund to your game, the more they will be rewarded. This can be done in-game, but also physically by sending them a T-shirt or something similar.
* **Website:** Setting up a website seems a very important thing to do as it will be a way for people to get updates about your game and will a thing to build on as you progress in your development.
* **Promotion:** This might be the most important part of the kickstarter campaign, as it will let people know what you are doing. The more people know, the more people will fund the project. I thought about a few ways to do this, but it is something I don't know much about it.

+ *Divide the development into separate stages:* Alpha, Beta and Release. This will create more reward options, but also create opportunities to gain attention for each stage.
    + *Game news:* websites or blogs that focus on discovering new games and reviewing them would be a great way to get attention. The problem is that I don't know if these websites/blogs are willing to write an article about a game in development.
    + *Youtube:* Youtube seems to be a great way to promote your game. By this I don't mean paying Youtube to advertise, but asking Youtubers to play your game seems to be a very efficient way to let people know about your project. This can be done by giving Youtubers special access to your game, but the problem here is that you have to have something presentable, which you probably won't have in the first stages in you development.

**EDIT:**

* **Risks:** By explaining the risks you are taking by starting your project, you show people that you have thought about every aspect of the process, by which you will gain more trust. As jsx stated: *'when you've outlined the things that can go wrong after telling someone the solutions, they end up telling you why those things aren't really problems. And having that person tell you why your project is going to succeed is a great position to be in'*.

These are all the things I could think of to get people to fund your project, but there have to be more and better ones. Are there more (efficient) methods I don't know about or tips about the things I wrote in the list above?

# Answer
The most important thing, and the one I think causes most game projects to fail, is not understanding feasibility. To put it another way:

**The *Risks* section of your business plan, Kickstarter, or whatever, is the most important part.**

Maybe not to everyone, but to you and your team, and especially to the people who can market your project to their audience. You need to really understand your risks and address those if you want people to invest in your project and address those directly. Otherwise there's no point in having any of those things.

If you know or can find a project manager, they can help with this.

Here are some example considerations:

* People not being interested in the finished product is a risk. So what is going to make them interested in it? What makes your product better than similar/cheaper/other versions of the same?
* You could end up working so slowly that you would never finish, not knowing when to make changes to the plan. How are you going to demonstrate momentum? Are you going to keep a dev blog? Engage in an early release program?
* Your team might not be capable of doing what you say, in the time you've budgeted. What have you or your team completed in the past? Is this bigger or smaller than past projects? How does this compare?

The fundamental reason why projects are successful (in terms of funding or completion) is this understanding and management of risk. You post concept art to demonstrate competence. You talk about the writing to capture people's interest and imagination, to show that the story is well written. You give examples of past projects to show that you're capable of commitment. If you can't take a good hard look at your project and tell me the most likely reasons it could fail and how you're addressing them, you haven't put enough thought into it for me to give you money for it.

Once you can address all the risks, ideally with evidence but a passionate explanation can go a long way too, that's when you know you have enough to go ahead with a financing campaign.

As an exercise to find out what's important to your project, you can examine similar but failed campaigns on crowd funding sites to see what risks they failed to address adequately. Especially helpful are the ones that look really polished, but didn't come anywhere near their funding needs.
> 3 votes

---
Tags: game-design, marketing, fund-raising, advertisements
---


# Question
Title: Unity3D setting blend mode in shader using vertex data
I'm porting a game from iOS / Obj-C / OpenGL ES 2.0 to Unity.

I have a procedural mesh script that generates a batch of quads that need to blend together to create a game board. Some of the quads add a highlight effect, others on top of those darken the scene. This is handled with the blend mode and the color of the object.

In the old version I did things inefficiently and just drew each quad individually, as needed setting the blend mode (glBlendFunc) and a color uniform. I batched similar things as I could.

In Unity3D rather than having 500 sprite gameObjects which IMO would be difficult to manage. I have one gameObject with a mesh = one draw call. I use per vertex color attribute instead of a uniform to set colors for each quad/sprite. But I want to also set the blend mode per quad by using vertex data. I'm sending the blend mode as uv2 data.

I found this question. See the second answer: http://answers.unity3d.com/questions/399074/change-blend-mode-from-outside-shader.html

Which says you can do this:

```
Pass {
    Blend [MySrcMode] [MyDstMode]
}

```

But in the example `MySrcMode` and `MyDstMode` are shader properties (uniforms) and again would set the blend mode for the entire draw call. I want to change it per quad which would have to be done per fragment.

I understand GLSL shaders. They make sense to me. But Unity shaders are still a bit mysterious. The unity docs aren't getting through to me and I can't find any good tutorials on really how they work and what gets called in what order. I tried:

```
Blend [texcoord1.x] [texcoord1.y]

```

But that didn't work. (Meaning that it's not getting a value for texcoord1 there.) My `Blend` is above the `Pass{}`. Moving it inside the `Pass` either is the same or produces an error depending where it goes.

My other option would be to do something like a `gl_LastFragData` to fetch the current fragment and do my own per fragment blending.

Or do I have to pull out the quads that use a different blending into another game object. Which would mean having geometry sorted into game objects based on their blending mode and not their behavior or the script that creates and manages them.

# Answer
If I have understood your approach, instead of drawing let's say a grid on nxn quads, you are building a mesh from all that quads and trying to render it with a single draw call, right?

Storing sprite colors into vertex color attributes it's fine, and that's a rather common approach.

For what concern blending (and not considering `gl_LastFragData`), you can't specify a different blend mode without using an additional drawcall neither on plain `OpenGL`, am I wrong?

In other words, you should setup different blend modes using glBlend in between drawing indexed primitives(glDrawElements), if all vertices are store inside the same `VBO` or `VAO`. Am I wrong?

> But Unity shaders are still a bit mysterious. The unity docs aren't getting through to me and I can't find any good tutorials on really how they work and what gets called in what order. I tried:

Even if blend options (and lot of other stuff such as stencil test, depth test,..) are stored inside unity .shader files, their aren't compiled into shader code. AFAIK are just "meta data", used by the engine to setup blend modes just before the drawcall with the real compiled shader(that under the hood is just `Cg` or `GLSL`).

I guess the minimum number of draw call correspond to the different blend mode you need to support.

When you generate it and set the indices you can specify the **submesh index** they belong to. At each submesh you can (maybe must), assign a different material (that can have a different shader accordingly to the required blend mode).

Assuming you are using a single pass shader, you can have one draw call for each material. If you have multiple static meshes with the same materials, then unity can batch them together.

If you have multiple dynamic meshes, than you can consider using Graphics.DrawMesh with MaterialPropertyBlock in order to minimize state changes. (More drawcall, but cheaper due to less GPU state changes)

hope this helps
> 2 votes

---
Tags: unity, shaders, alpha-blending
---


# Question
Title: How does Unity input work with touchscreens
I'm trying to make a racing game on android using unity. I want to make a car move forward when I touch an image button like in the picture below. I've already made it work using the keyboard. How do I do the same with on-screen buttons and touch input in android?

# Answer
If you are using Unity 4.6+ then you have access to its new UI system. If you ever used NGUI, which is a popular unity UI frame work, its based on that architecture I believe.

This is a good tutorial on the subject of buttons and how they work.

http://unity3d.com/learn/tutorials/modules/beginner/ui/ui-button

Quick summary tho:

1. In the scene create new and select UI-\>Button
2. Select the new button in the scene and find its Button script in the inspector
3. Make a new on click event
4. Assign the object you want to act on when the button is press and the function to call (whatever your current movement code is)

At step #2 if you want to listen for more specific events just add a new EventTrigger script and pick a more specific event type and set it up by assigning an object and callback.

More on that here: http://unity3d.com/learn/tutorials/modules/beginner/ui/ui-events-and-event-triggers
> 1 votes

---
Tags: unity, android, touch
---


# Question
Title: Z-Value of clip-space position is always 1.0
I render a lot of quads on the screen into z direction (20 x 2000). I want to get the depth value in a final render target. But it looks like z is always 1.0f. I checked the result with the OpenGL debugger. Any advice?

**Vertex shader:**

```
#version 410

layout(row_major) uniform UView
{
    mat4 m_View;
    mat4 m_Projection;
};

layout(row_major) uniform UModelMatrix
{
    mat4 m_ModelMatrix;
};

layout(location=0) in vec2 VertexPosition;

out vec3 PSVSPosition;

void main(void)
{
    vec4 VSPosition = m_View * m_ModelMatrix * vec4(VertexPosition.xy, 0.0f, 1.0f);

    PSVSPosition = VSPosition.xyz;

    gl_Position = m_Projection * VSPosition;
}

```

**Fragment shader:**

```
#version 410

layout(row_major) uniform USettings
{
   mat4  m_ProjectionMatrix;
};

layout(location = 0) out vec4 PSColor;

in vec3 PSVSPosition;

void main(void)
{
    // Calculate depth
    vec4 CSPosition = m_ProjectionMatrix * vec4(PSVSPosition, 1.0f);

    CSPosition.xyz /= CSPosition.w;

    PSColor = vec4(vec3(CSPosition.z * 0.5f + 0.5f), 1.0f);
}

```

Result:

Closer result:

view-space position result:

clip-space position result:

# Answer
> 2 votes
When you divide by the post-projection-matrix .w, you don't get a linear depth from -1 to 1, it mostly gets bunched up near 1.0.

To get linear depth you could do, instead, something akin to:

```
float linearDepth = PSVSPosition.z / 2000.0; // if +2000 is your far plane
PSColor = vec4(vec3(linearDepth), 1.0f);

```

# Answer
> 0 votes
Try using a color ramp to represent the final depth values. Instead of writing the `z` value directly to the pixel, use that value to sample a 1 dimensional texture. This works well because, as you've done, it's easy to get the `z` value into the range of `[0, 1]`. Then you can write the retreived color to the pixel.

**Fragment shader:**

```
#version 410

uniform sampler2D UColorRamp;

layout(row_major) uniform USettings
{
   mat4  m_ProjectionMatrix;
};

layout(location = 0) out vec4 PSColor;

in vec3 PSVSPosition;

void main(void)
{
    // Calculate depth
    vec4 CSPosition = m_ProjectionMatrix * vec4(PSVSPosition, 1.0f);

    CSPosition.xyz /= CSPosition.w;

    vec3 color = texture(UColorRamp, vec2(CSPosition.z * 0.5f + 0.5f, 0.5f)).rgb;

    PSColor = vec4(color, 1.0f);
}

```

Here is a color ramp I've used in the past. It doesn't need to be this tall of course. A height of 1 is sufficient.

---
Tags: opengl, depth-buffer, depth, projection-matrix
---


title: Draw 3D model on top of another one

text:
# Question
Title: Draw 3D model on top of another one
I am trying to draw a 3D model I made with Blender in Monogame/XNA and this is the result I get when I draw 2 of them on top of each other

How can I make it so that the colors don't add up, but the one covers the other ? Here is my drawing code:

```
protected override void Draw(GameTime gameTime)
{
    GraphicsDevice.Clear(Color.Black);
    Vector3 modelPosition = new Vector3(-2500, 1500.0f, 0.0f);
    Vector3 cameraPosition = new Vector3(0.0f, 0.0f, 5000.0f);
    float aspectRatio = (float)graphics.GraphicsDevice.Viewport.Width /
          (float)graphics.GraphicsDevice.Viewport.Height;
    Vector3 scale = new Vector3(1f, 1, 1);
    Matrix[] transforms = new Matrix[Brick.Bones.Count];
    Brick.CopyAbsoluteBoneTransformsTo(transforms);
    foreach (ModelMesh mesh in Brick.Meshes)
    {
        foreach (BasicEffect effect in mesh.Effects)
        {
            effect.EnableDefaultLighting();
            effect.World = transforms[mesh.ParentBone.Index]*Matrix.CreateScale(scale)*
           Matrix.CreateRotationY(modelRotation)*Matrix.CreateTranslation(modelPosition);
            effect.View = Matrix.CreateLookAt(cameraPosition, Vector3.Zero, Vector3.Up);
            effect.Projection = Matrix.CreatePerspectiveFieldOfView(
                  MathHelper.ToRadians(45.0f), aspectRatio, 1.0f, 10000.0f);
        }
        mesh.Draw();
    }
    base.Draw(gameTime);
}

```

# Answer
You need to set the blendstate to alpha blending when rendering your objects. You can do it like this:

```
GraphicsDevice.BlendState = BlendState.AlphaBlend;

```

This piece of code should go before drawing your mesh.
> 1 votes

---
Tags: xna, c#, 3d, monogame
---


title: glPush/PopMatrix on projection Matrix?

text:
# Question
Title: glPush/PopMatrix on projection Matrix?
I am trying to simulate a camera which is always at same distance behind my player, my plan is, to transform the projection matrix correctly with `glPush/PopMatrix`, as i do it with the modelview matrix. While it's no problem, to rotate the view constantly, it doesn't work to save the current matrix with `glPush/PopMatrix`. In another thread, I've read that the size projection stack is very limited, one or two at most. If this is true and the 'stack' doesn't offer the possibility to save the current matrix, is there another way to get what i want? Or is my idea a non-practicable approach at all? Is there no alternative to use `gluLookAt()`? Or is it the right solution to transform the modelview matrix and save the position of the player figure?

# Answer
> 1 votes
Assuming that what you want to achieve is done as you outline, you can emulate pushing and popping by reading and loading the matrix into storage of your own with:

* `float m[16]; glGetFloatv(GL_PROJECTION_MATRIX, m);` and
* `glMatrixMode(GL_PROJECTION); glLoadMatrixf(m)`

---
Tags: opengl
---


# Question
Title: change sprite color from properties of parent object in inspector
I have a compound GameObject that is made up of 5 sprites name dot1 till 5. I'd like to have a little script on the parent object that would allow me to change the colours of the child objects from the unity inspector. I want the colours to change directly in my scene without having to press play. This already happens when I would set the colours directly from the child objects. But I'd like to have the properties visible in my main object and set the colours from there.

So far I'm unable to make the changes visible in scene mode.

\[ExecuteInEditMode\]

```
public class Chain : MonoBehaviour {

    public GameObject dot1;
    public GameObject dot2;
    public GameObject dot3;
    public GameObject dot4;
    public GameObject dot5;

    public Color Color1;
    public Color Color2;
    public Color Color3;
    public Color Color4;
    public Color Color5;

    void Start () {
    dot1.renderer.sharedMaterial.color = Color1;
    dot2.renderer.sharedMaterial.color = Color2;
    dot3.renderer.sharedMaterial.color = Color3;
    dot4.renderer.sharedMaterial.color = Color4;
    dot5.renderer.sharedMaterial.color = Color5;
    }

    void Update () {

    }
}

```

# Answer
You can add a method like this:

```
#if UNITY_EDITOR
void OnValidate()
{
     if(dot1 != null && dot1.renderer != null)
         dot1.renderer.sharedMaterial.color = Color1;

     if(dot2...
}
#endif

```

The # lines ensure this function only compiles in editor builds.

OnValidate() is called in-editor anytime a value changes in the inspector. Because this includes when the script is first added to an object, and hasn't had all of its public fields populated yet, you need to be a little extra careful about checking for null values even in places that would never be null at runtime.

You can streamline this code if you replace the separate GameObject & Color fields for items 1-6 with a pair of Renderer\[\] and Color\[\] arrays - that way you can iterate over them instead of writing the same line 6 times, and Unity will enforce that whatever you put in the first array will have a Renderer component, saving a validation check in your code.

Note that changing the sharedMaterial's color will change the current material asset that each dot is referencing. That means if any two dots are sharing one material, whichever one gets its color set last will apply to both. If you're using version control, these material files will constantly show up as having been edited, because Unity detects that code has changed them anytime someone opens a scene with an instance of this script in it.

You can avoid this by creating a copy of the material before modifying it, but note that Unity doesn't garbage collect materials, so you'll need to manually destroy the copy when the script is deleted/unloaded, even in Editor (using DestroyImmediate) to keep duplicate materials from building up in memory.
> 1 votes

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


# Question
Title: Relative movement in Box2D (keep object from falling off planet)
I'm creating a game with planets orbiting around a sun, like this:

The brown square is the earth, rotating around its center and around the sun. The yellow square is the sun, which doesn't move.

Now imagine a player standing on the planet, the planet moves at a velocity of 20 m/s. How do I prevent the player from falling off? I have to give the perception to the player that the planet isn't moving.

I got the gravity on earth working, but I don't know how I can keep the player on the planet! I have thought about two solutions until now:

1. Just apply the angular velocity and linear velocity of the planet on the player (if it's in a specified radius), I think this method will cause jittery movement/glitches.
2. Create a separate Box2D world for the planet and render this Box2D world with the rotation/translation of the planet. This method is complex though since it would add the problem of moving bodies between different worlds if the player would leave the planet. This image explains it:

I think there is another (better) way to fix this problem, but I haven't found a solution yet.

# Answer
It works now! I have created a seperate Box2D world for every planet and Solar Systems. The Solar System rotates the planet, so it looks like the planet is rotating. But the player (in the world) isn't rotating at all.

The result looks like this: https://i.stack.imgur.com/vRZ2r.jpg
> 1 votes

---
Tags: box2d, physics, jbox2d
---


title: SDL2 jagged/staircase edges

text:
# Question
Title: SDL2 jagged/staircase edges
I am using SDL2 and SDL2 Image to render png images.

When I rotate the textures, they turn out very ugly, like this:

This is the code responsible for the rotation and alpha mod.

```
SDL_Rect srcRect;
SDL_Rect destRect;
srcRect.x = width * currentFrame;
srcRect.y = height * currentRow;
srcRect.w = destRect.w = width;
srcRect.h = destRect.h = height;
destRect.x = x;
destRect.y = y;

SDL_SetTextureAlphaMod(m_textureMap[id], alpha);
SDL_RenderCopyEx(pRenderer, m_textureMap[id], &srcRect, &destRect, 10.0, 0, flip);

```

Do I need to set a blendmode too?

# Answer
So it seems I was missing this in my Game class, which makes sense:

`SDL_SetHint( SDL_HINT_RENDER_SCALE_QUALITY, "1" );`

https://wiki.libsdl.org/SDL\_HINT\_RENDER\_SCALE\_QUALITY
> 6 votes

---
Tags: sdl, image, sdl2
---


title: Java Game not rendering properly

text:
# Question
Title: Java Game not rendering properly
Hello I have a game that you can play(duh). When you start the game a loading screen pops up and on the loading screen I display an image of an eye I drew. In paint.net they eye looks perfect but in game it dose not.

Here is the image in paint.net:

Here is the image in game:

I don't understand why the image is all messed up as much. Please help me! Thx.

# Answer
Only thing I see wrong is that you made the circle 1 pixel thicker on right and bottom side. That's not problem of your code though, only your drawing skills.
> 2 votes

---
Tags: java
---


title: Java game loop delta not working

text:
# Question
Title: Java game loop delta not working
Hello I have game loop where I can change framerate. But when I change framerate to other, delta time not working fine. For example when framerate is lower everything is faster.

Here is game loop:

```
double delta = 0.0;
private double framerate = 60.0;
private double frameTime = 1.0/framerate;

public void run() {
    runFlag = true;
    int frames = 0;
    double frameCounter = 0;

    double lastTime = (double)System.nanoTime()/(double)1000000000L;
    double unprocessedTime = 0;

    while(runFlag) {
        boolean render = false;

        double startTime = (double)System.nanoTime()/(double)1000000000L;
        double passedTime = startTime - lastTime;
        lastTime = startTime;

        unprocessedTime += passedTime;
        frameCounter += passedTime;

        while(unprocessedTime > frameTime) {
            render = true;

            unprocessedTime -= frameTime;

            tick();

            delta = frameTime;

            if(frameCounter >= 1.0) {
                this.frames = frames;
                Display.setTitle("  FPS: "+frames+"  DELTA: "+(float)delta);

                frames = 0;
                frameCounter = 0;
            }
        }
        if(render) {
            render();

            frames++;
        } else {
            try {
                Thread.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        Display.update();
    }
    destroy();
}

```

What is wrong with this game loop ?

# Answer
> 1 votes
Your delta will be **always** equal to 1/60, but that's not what delta time is. Delta is the time that passed between current and previous call. Here's an example:

```
double delta;
double currentTime, lastTime;

while (doingStuff)
{
    currentTime = getCurrentTime() //You have to define this method somewhere

    delta = currentTime - lastTime;

    lastTime = currentTime;
}

```

In this example, delta is the difference between time of last and current iteration of the loop.

The "delta" you calculated is the perfect time you want between frames. And there's a **giant** difference between the time you want, and the time you actually have.

---
Tags: java, game-loop
---


# Question
Title: How should I handle animation state systems in derived classes?
I'm trying to get some kind of state system for my game objects.

I have a base Actor class that is derived by classes like Policeman, Informant or Brawler. Each of those classes describes different functionality, but I want as much of the functionality to be shared.

On of those is animation system. Each class has their own states (for example Policeman has Walking, Shouting and Shooting, while Informant has Idle and Whispering).

What is the best way of handling such states? Do I have the Actor class have something like

```
enum ActorState
{
state1,
state2,
state3,
...
}

```

And just map each behaviour of appropriate actor (Policeman, Informant, etc) to ActorState, so that the rendering system of ActorState can take over?

Or maybe is there some better solution that people use.

Game is 2D, sprite based, and I'm using Unity3D system, with Actor being a component to GameObjects.

# Answer
> I have a base Actor class that is derived by classes...

This design goes completely against Unity's design, unfortunately. If you try to use a large class hierarchy within Unity's system, things are going to be very difficult. Unity chooses to use *composition* over *inheritance*, or *has-a* over *is-a*.

To build unique objects in Unity, you should prefer to compose components, rather than inherit functionality. This makes functionalities reusable, independent and focused. Look at what you have in your monolithic classes and see how they might be split up. For example an actor may be broken up into these components:

```
-Move( could be an interface to a *movable*, meaning any type of movement can be "plugged" in. )
-Health( keeps a health count. )
-Respawn( may respawn after health reaches zero. )
-DamageOnCollision( may damage enemies or players etc on collision )
-WeaponUser( may provide functionality for using certain weapons in some ways. )

```

Seeing this, you can *compose* different game objects. I apologise if you are already doing this, your post just made it seem as if you're not.

Now, there is a huge problem with this. The things I listed above describe only one state. We don't want each component to check what state the object is in because then it ties that component( which is meant to be independent ) to a particular game object and destroys it's portability between objects. So, how do we communicate state changes?

What I've done in a project I've been working on is create a state machine component. This component simply holds a dictionary of *states* with the key being the state name. What does a state hold? A state holds a list of all components that will be active while that state is active. So, when we transition from one state to another:

```
-Disable all components that are in the old state but NOT in the new state.
-Enable all components that are in the new state but NOT in the old state.

```

For this to work each component must strictly follow these rules:

```
-OnDisable must do any clean up to make sure it no longer has any effect on outside objects.
-If a component is disabled, it should have NO effect whatsoever.

```

Using these rules, a component can be enabled and disabled on state transitions and work correctly. A serialized list or dictionary can allow you to drag and drop each component into a state to allow this control from the editor.
> 2 votes

---
Tags: unity, animation
---


title: Jmonkey loading texture from fails

text:
# Question
Title: Jmonkey loading texture from fails
I have the following basic code:

```
public void simpleInitApp() {
    Box b = new Box(1, 1, 1);
    Geometry geom = new Geometry("Box", b);
    Texture cube1Tex = assetManager.loadTexture(
    "/home/glados/codes/3/assets/Textures/map/oldParchment.jpg");

    Material mat = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md");
    mat.setTexture("ColorMap", cube1Tex);
    geom.setMaterial(mat);

    rootNode.attachChild(geom);
}

```

which is supposed to simply attach a texture to the cube loaded from Textures/map/oldParchment.jpg

My resource setup is as following:

running this gives the following error:

```
com.jme3.asset.AssetNotFoundException: /home/glados/codes/3/assets/Textures/map/oldParchment.jpg (Flipped) (Mipmapped)
    at com.jme3.asset.DesktopAssetManager.loadAsset(DesktopAssetManager.java:283)
    at com.jme3.asset.DesktopAssetManager.loadTexture(DesktopAssetManager.java:346)
    at com.jme3.asset.DesktopAssetManager.loadTexture(DesktopAssetManager.java:356)
    at mygame.Main.simpleInitApp(Main.java:27)
    at com.jme3.app.SimpleApplication.initialize(SimpleApplication.java:226)
    at com.jme3.system.lwjgl.LwjglAbstractDisplay.initInThread(LwjglAbstractDisplay.java:130)
    at com.jme3.system.lwjgl.LwjglAbstractDisplay.run(LwjglAbstractDisplay.java:207)
    at java.lang.Thread.run(Thread.java:744)

```

Anybody know what I'm doing wrong?

# Answer
> 2 votes
The path you are giving assetManager should start from the assets folder of your project.

So the path should just be:

"Textures/map/oldParchment.jpg"

This is the same for all assets loaded with assetManager.

Compare your code to the tutorial for loading assets.

---
Tags: java, textures, image, assets, jmonkeyengine
---


# Question
Title: Tiled PolygonObjects rendering wrong in libgdx
this is how I render the polygons in Tiled this is how they get rendered in libgdx. Notice the top part of the triangles is straight instead of being hollow. here is the code I use to convert the polygon object to a polygonshape

```
    PolygonShape polygon = new PolygonShape();
    float[] vertices = polygonObject.getPolygon().getTransformedVertices();
    float[] worldVertices = new float[vertices.length];

    for (int i = 0; i < vertices.length; ++i) {
        worldVertices[i] = vertices[i] / ppt;
    }

    polygon.set(worldVertices);

    BodyDef bd = new BodyDef();
    bd.type = BodyDef.BodyType.StaticBody;
    Body body = world.createBody(bd);
    body.createFixture(polygon, 1);
    polygon.dispose();

```

it this normal behavour for libgdx? to flatten the top of the polygons?

# Answer
> 1 votes
Your problem is that the physics library, probably Box2D, supports only convex shapes. You are passing in a non-convex (concave) shape, and what you get as a result is that the convex hull of your shape is used as collision body.

To avoid this, you can either manually make sure your collision primitives are convex, or you can triangulate the polygon (there are probably libraries available for this, if libgdx does not have it) and use the triangles as fixtures.

---
Tags: libgdx, box2d, tiled
---


title: Encoding/decoding data with byte arrays

text:
# Question
Title: Encoding/decoding data with byte arrays
For my multiplayer game, I'm trying to figure out a system to send multiple pieces of data from one client to another and separating pieces of data.

When sending a message, all parameter data has to be converted into a byte array (with BitConverter.GetBytes) and will arrive as such on the other side.

What I'm not sure about is how to send multiple numbers in one message and identify them. For example, how would I send a ushort and a ulong in a single byte array? Are there any clever methods to identify the individual numbers or will every number have to be packaged in 4 bytes each?

# Answer
> 1 votes
> Int32, Int16, Int16, Int32, Int32, Int32

If your app wrote these numbers in this order, then you just read them in the same order. It is your game and you just know the format you are sending and read it the same way you wrote it.

If you want to be able to change the format (e.g. send Int8 for a small map and Int16 for a big one) you define a key that tells you the upcoming format. E.g.:

> is\_small\_map, Int32, Int8, Int8, Int32, Int32, Int32
>
> is\_big\_map, Int32, Int16, Int16, Int32, Int32, Int32

When you need to pass arrays - write elements count first and then write/read them in a loop.

---

When you need to pass multiple packets over net, one after another you just pass them, letting the receiver side to decode the packets individually. For that each packet needs to include it's Length, so when you decode it you know exactly where this packet ends and next one starts.

# Answer
> 0 votes
I was brainstorming something like that where the first 5 bytes in my array will define the lengths of all my numbers (types won't be needed; they're all integral numbers). The first 4 bytes identifies the byte length of every following number.

---
Tags: networking, data-structure
---


# Question
Title: How to estimate number or packets required to sent per second in a multiplayer lockstep RTS game?
Considered a typical lockstep implementation, what's a solid rate to send packets at for UDP protocol that games can start with in the beginning?

If anyone has experience in this field, I'd like to know the general optimal packet sends per second for a lockstep RTS game.

# Answer
This is rather broad and vague question.

Lockstep requires at least one command sent per tick to indicate there is no actions happened. Also you need to send a packet to verify to other clients that the client has received their packets.

Each step every player needs to send his commands (wrapped into one packet for simplicity) and confirmations of receiving other players commands to each client. Without optimizations, general approach formula can start at:

> ((Commands\_per\_step * Player\_count) + (Confirmations\_per\_step * Player\_count)) * Steps\_per\_second
>
> 2 * N * Player\_count * Steps\_per\_second

For 8p game at 10 ticks a second that is around 160 packets per client per second. Not including utility packets like ping or text, they can be bundled with commands.

Is 160 too much ? For the number in you exact circumstances, you best off at writing a test app that spews packets and measure how much is too much. Ask your friends around the world to test it and collect the stats.

However there is a place for optimizations. In best case, you can optimize by bundling everything client needs to send into 1 packet (per step or even more rare), sent to the game server and making it replicate and spew packets to all clients as needed. That will increase lag slightly, but save you packet count.
> 1 votes

---
Tags: networking, multiplayer, rts, udp
---


title: LibGdx Scalling sprites on Android

text:
# Question
Title: LibGdx Scalling sprites on Android
I have a sprite that is a few buttons but need them in the center of the screen for all android devices. I tried setting it's location to the center of the screen by dividing the orthogonal camera by 2, but it doesn't help. Any simple way to fix this?

# Answer
> 1 votes
If you want to draw the sprite in the exact center, you have to take the sprite's height and width into account. Assuming your viewport's width and height are set equal to the device's width and height. You can set the sprite's position this way

```
sprite.setPosition((Gdx.graphics.getWidth() - sprite.getWidth())/2 ,(Gdx.graphics.getWidth() - sprite.getheight())/2 );

```

or even:

```
batch.draw(texture, (Gdx.graphics.getWidth() - texture.getWidth())/2 ,(Gdx.graphics.getWidth() - texture.getheight())/2);

```

---
Tags: android, libgdx, sprites, scale
---


# Question
Title: Can I use my directx 9 code to visual studio 2013 that already has directx11?
I am facing problem with my directtx 9 code?

# Answer
VS 2013 Express for Desktop, VS 2013 Pro+, or VS 2013 Community include the full Windows 8.1 SDK. This includes the system headers for Direct3D 9 (d3d9\*.h) as has been the case since Windows SDK 6.0.

The problem is that your Direct3D 9 code likely makes use of the deprecated D3DX9 library such as D3DXmath, FX9, the original HLSL compiler, etc. You can switch to use the D3DCompile APIs and FXC.EXE which are in the Windows 8.1 SDK which supports shader model 2.x and shader model 3.0 profiles. You can use DirectXMath in the Windows 8.1 SDK. However, FX9 and other parts of D3DX9 are only available in the legacy DirectX SDK. In order to use the DirectX SDK with VS 2013, you have to *reverse* the long-standing path recommendations in your VC++ Directory settings to put the DirectX SDK include/lib paths last rather than first as they are now outdated compared to the Windows SDK. See MSDN for details and some other notes.

```
$(IncludePath);$(DXSDK_DIR)Include
$(LibraryPath);$(DXSDK_DIR)Lib\x86 or x64

```

Furthermore, there is no support for the Direct3D 9 debug runtime in the Windows 8.1 SDK. You can install the legacy DirectX SDK to get it for Windows XP SP2 - Windows 7, but you can't get a version of it for Windows 8.x or Windows 10.

There's no support for Direct3D 9 in the VS 2013 Graphics Diagnostics. Legacy PIX for Windows in the DirectX SDK should work for Direct3D 9 apps given these caveats.

Finally, this all assumes you are using the "v120" Platform Toolset. If you use the "v120\_xp" Platform Toolset you are actually using the Windows 7.0A SDK rather than the Windows 8.1 SDK. This is more old school and you have to use the legacy DirectX SDK as you've done in the past. See this post for the implications of doing that.

```
$(DXSDK_DIR)Include;$(IncludePath)
$(DXSDK_DIR)Lib\x86 or x64;$(LibraryPath)

```

See A Brief History of Windows SDKs and DirectX SDKs of a certain age.
> 1 votes

---
Tags: directx11, directx9
---


# Question
Title: Is this specific server architecture okay for a multiplayer game?
So I am making a game in Node.js / HTML5.

And I am really struggling to determine what an effective server architecture looks like?

---

Right now I have a server for a multiplayer game ( I plan on making servers instanced, so up to 80 people per instance).

So everybody in the instances location and health are shared.

And when an attack happens, i.e. a meteor is dropped from the sky, the x-value is the only data passed to the rest in the instance ( they all do the computations on their own computer locally).

When you are hit, you tell the server you were hit. (can't tell the server to hit other people, only yourself, becuase otherwise it's exploitable).

---

That's the kind of architecture I was going for, you can only tell the server about events that damage yourself. ( I don't believe these events are overridable but I will try to determine that).

--

Do I have the right idea about how to go ahead with this server?

Do you have any tips or resources?

NOTE: It's under MMO but servers will hopefully top off at about 80. MMO in the same sense as Realm of the Mad God. = )

# Answer
The problem with this setup is that the clients can say that they weren't hit and therefore this is exploitable. Why not use an authoritative server setup where clients are dumb, and the server says when everyone is hit?
> 2 votes

---
Tags: multiplayer, mmo
---


title: How to make hard to hack leaderboards

text:
# Question
Title: How to make hard to hack leaderboards
Okay, someone tasked me to make a leaderboard for their game. However, the one I have right now is *really* insecure. All it does is check if someone is in the top 100, and if they are, post the score to the server, where the server will completely trust the client to give a real score.

My question is: How would I make it harder, or better, impossible, to send a fake high score, because right now they can just post a value to an easy-to-find endpoint.

**Clarifications**: The game is running in an interpreted environment, therefore obfuscation is not practical, and the game has a lot of input (an hour's worth at least), so sending that to the server is also impractical.

# Answer
> 8 votes
Scrambling the transmitted score is probably worthwhile.

To avoid cheat-engine type stuff, you can always scramble it in memory too. If you're storing seven variables, each of which, %10, is a digit, and you add a random number of 10s to each variable whenever a score changes, then it will be tricky to find a variable that matters. You could also get quite silly with that, by having certain values of the multiples-of-ten be illegal, and affect the score in "special ways", or send a signal to the server "this player is messing with the scores".

Another slight layer of security-through-obscurity you can add is to have score increments always be a multiple of some number, say, three. Then you can check to see if score % 3 != 0 the score has been faked. But since the attacker has access to the client code, this is mere obfuscation, and not super helpful.

So, most importantly, you should do what you said you cannot do, and send gameplay progress.

Sending every keystroke is not infeasible (MMOs do it!), but it would require storing a state machine of each game serverside. So, simplify.

So if it's, say, a platformer, then you have it send what level they are on, and a notification each time they kill a mob. You then validate that by saying, you know their weapon can kill at most 4 people, and fires once every second. Then if they claim to kill ten people at once, that's not legit. If they claim to kill more people than are on their current level, it's not legit. If the mob ids they send with their kill are from different rooms and could not be simultaneously killed, that's not legit.

Don't accept a score that's jumped infeasibly high in one go.

But, it's the internet, and lag happens, so you have to allow a certain flexibility in timing.

What if it's, say, a racing game? Well, you can give checkpoint timings. You know the car specs, you know its max speed, max acceleration, you know the min distances between checkpoints, so you can calculate the min possible time (allowing a little leeway for speeding up by getting hit from behind, powerups, etc).

So you avoid the "999999points" obvious hacks, and instead, they have to submit a whole BUNCH of packets, saying "lap 1 done in \[theoretical best time\]", \[wait a bit\] "lap 2 done in \[theoretical best time\]", ... "end of race", "prize money spent on buying \[upgrade\] to improve theoretical best time"... improving each time.

Essentially: split the game down into gated waypoints, for each waypoint send what metadata you can validate serverside, and write logic that accepts or rejects the score increment based on that. Decide what to do if you reject: do you boot them out of the game, or report "score desynch, score could not be saved" but let them carry on playing the level?

This is a serious and hefty way to tackle the problem, and you should only do as much towards it as is worth. For a free online web game, just prevent the most obvious all-nines scores and be done with it. For a for-pay game, it's worth taking it further, depending on how core a game mechanic the leaderboards are.

# Answer
> 5 votes
If what you get is just a score number, you can not verify how it was achieved.

To make it more secure you need to obtain a full replay and verify that the game was fair (no cheats used, no score hacking). One of possible implementations of this idea is keeping the game on the server. If all logic is on the server and player can only send his actions, then you can be sure, that there was no cheating. Of course that leaves exploitations of game bugs. You decide "if" and "how" you need to cope with those.

# Answer
> 4 votes
You are right that there is risk in just letting a player post any score they want. That said, it will be very hard for you prevent cheating, as long as the player is playing offline and on their own machine. If the game is online, and your server is calculating all scores, then you can safely store the score, since you trust how it was calculated.

There are some things you can do to slow down the easy hacks though. Here's one suggestion...

**Require users to register online with you before they can post to a leader board**

1. Internally with your game, have a stored/permanent "user registration ID" value. This is initially blank.
2. If a user wants to post to the leader board and the registration id is blank, they must register first.
3. Registration is done from inside your game.
4. Game sends registration request with user's desired name.
5. Your server validates the name (is it unique for example?)
6. Your server allocates a new registration ID (something like a UUID (look it up)) and sends it back to the game.
7. The game stores the registration ID internally for future reference.

**Encrypt the score before you send it, to make it harder to submit fake scores**

1. When the game sends a score, it encrypts the value and sends the encrypted version of the score, along with the registration ID of the player. It does not send a direct score value as an open number!
2. Your server decrypts the score value, and registers the score.
3. You will need to store the encryption key inside your software, which potentially could be hacked.

PS You might check out https://stackoverflow.com/questions/25999/secure-online-highscore-lists-for-non-web-games for a similar question and answers. Also http://gamasutra.com/blogs/PriyadarshiChowdhary/20141121/230744/Design\_and\_safety\_tips\_for\_leaderboard.php for an article on the subject.

# Answer
> -2 votes
To make this happen you must ensure that the game is always online. it has pros and cons also.

This is only method by which you can ensure validity of score.

at login time validate the score from server and when connection breaks store the last score made by user and next time he logins to the server update and match the score from server.

---
Tags: server, leaderboards, anti-cheat
---


title: How to merge 2 textures into single SRV

text:
# Question
Title: How to merge 2 textures into single SRV
I have 2 textures in 2 different ShaderResourceViews. What's the fastest/least expensive way to merge them into one? I would use CopySubresourceRegion but copying a texture is quite a bit expensive. I'm using DirectXTex toolkit for loading textures.

# Answer
> 1 votes
You can do the next trick: make a destination texture, set it as render target, draw a quad to it covering all the texture area, in pixel shader make any kind of blending from two (or even more) textures.

---
Tags: c++, directx, directx11
---


# Question
Title: What is actually done by the deferred rendering pipeline in this context?
I have been reading a student's thesis regarding deferred rendering and have stumbled across a piece of his work that I couldn't quite understand.

The thesis; in chapter 1.3 it says:

> Stalker (see Figure 02) for example is using only deferred lighting to calculate their light accumulation due to complex lighting conditions in the environment, while the rest of the engine still runs in forward rendering

Could someone possibly explain what he means by this? What is the deferred pipeline actually being used for?

# Answer
> 2 votes
It says right in the quote: to calculate the effect of lights in the scene (how much light falls on a particular fragment, what color is it, et cetera).

Computing the effects of more and more light sources is something that forward rendering handles badly; it scales very inefficiently. Deferred rendering alleviates a lot of that computational pressure, making it significantly easier to throw a ton of lights into the scene ("lots of lights" is probably, at least in part, what is meant by "complex lighting conditions").

One reason to mix deferred and traditional rendering pipelines in this fashion was to allow the use of the deferred pipeline for what it was good for (lights, lights, lights) and the forward pipeline for what *it* was good for (transparency, which is not readily accomplished with a deferred system, especially early on in the technology's use).

---
Tags: deferred-rendering
---


# Question
Title: How can I handle the subject of an action disconnecting before the action executes?
Let's assume I have a `CEntity` class that describes every entity within the game.

Each entity class has it's own `std::vector` of `CAction`s. Each `CAction` is just an action that the entities can perform, for example `CActionFight` would have the logic for fighting.

To command my player (or any other entity) to fight all I do is:

```
CActionFight *pActionFight = new CActionFight();
pActionFight->SetTarget(pTargetEntity);
pPlayer->AddAction(pActionFight);

```

Before this action is started, all other actions queued earlier have to be finished. Imagine player starting to execute the `CActionFight` over `pTargetEntity` and suddenly, `pTargetEntity` disconnects. `pTargetEntity` is invalid and here's my question.

How do you normally handle that in actions?

If a disconnection event of an entity is received on the server side, do you iterate through the actions of all entity in the map and remove these which are related to an entity that has just dropped connection?

**EDIT** Liked Josh's approach and implemented the solution, sounds very sensible and worked like a charm.

```
// Example of an action, checking wether Entity is still valid.
void CActionFight::Execute()
{
    m_iCycles--;

    if(m_iCycles>0)
    {
        if(m_pTarget->IsValid() == false)
        {
            m_pTarget = NULL;
            m_bValid = false;
        }
        else
        {
            printf("Attacking.%s\n", m_pTarget->GetName().data());
        }
    }
    else m_bValid = false;
}

```

# Answer
> 1 votes
> If a disconnection event of an entity is received on the server side, do you iterate through the actions of all entity in the map and remove these which are related to an entity that has just dropped connection?

You could do that, but it may be unnecessarily inefficient. When an entity gets disconnected from the simulation or otherwise leaves the world, the server should note that and propagate that information through to it's own internal representations of the entity (as well as forward this new information along to clients).

The problem in your scenario, I would say, is this: "`pTargetEntity` is invalid" once the host for the entity disconnects from the world. The solution is not to invalidate `pTargetEntity` immediately. Instead, put the entity into a 'invalidated' or 'pending removal from simulation' state. This avoids any issues stemming from `delete`ing `pTargetEntity` immediately, leaving everybody else with a dangling pointer.

It also lets you check for that state in the processing of an action. In the action processor, and/or the action itself if appropriate, you can check that all entities involved in the action are still valid. If they are, you continue normally, if they are not, you can abort the action and immediately begin processing the new one.

You can finally release the memory for the disconnected entity once you know all outstanding references to it are removed. There are various ways to do this, such as using a handle idiom or smart pointers to refer to the entity elsewhere, instead of bare pointers. In fact, C++'s built-in `std::shared_ptr` may be exactly what you need (although it's hard to say for sure if shared ownership is the correct course of action without knowing more about your specific implementation, you should look into it though; if it isn't you can relatively easily build your own handle abstraction).

---
Tags: rpg, mud
---


# Question
Title: Logic outside of game loop running slower than calculated
I've been trying to figure out what is happening when I run functions from the update loop in XNA that the game freezes for a few seconds until the function is done. When I do performance testing to see how long the function is taking its lower than what is actually being taken to do the function when timed by a stop watch on my phone.

Is there something that is going on with how XNA times its updates and draws that is causing this?

I'm using XNA since MonoGame works with it.

I've got IsFixedTimeStep = false in the constructor of my game that I'm building.

For the update code:

```
    protected override void Update(GameTime gameTime)
    {
        // Allows the game to exit
        if (Keyboard.GetState().IsKeyDown(Keys.Escape))
            this.Exit();

        if (Keyboard.GetState().IsKeyDown(Keys.Space))
            doOnce = false;

        // TODO: Add your update logic here

        // trying to determine issue with game freezing when doing the function below.
        if (!doOnce)
        {
            doOnce = true;
            startTime = DateTime.Now;
            TestFunction();
            endTime = DateTime.Now;

            timeTakenToScale = new TimeSpan(endTime.Ticks - startTime.Ticks);
        }

        if (gameTime.TotalGameTime.TotalMilliseconds < nextFrameTime)    // don't draw the game unless its past its frame time
        {
            SuppressDraw();
            base.Update(gameTime);
        }
        else
            nextFrameTime = gameTime.TotalGameTime.TotalMilliseconds + maxFrameRate;    // set next frame to time
    }

```

# Answer
Ok I found out the issue. Apparently when I was doing the time calculation I forgot to put totalmilliseconds and had milliseconds. Feel like an idiot for sure. :(
> -1 votes

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


# Question
Title: How to use Audio Profiles in Cocos2d Ver 3.3 AudioEngine
I have 2 audio files that I want to play at different times: background.wav a sneeze.wav. I believe that I have to convert both wav files into mp3, caf and ogg files. Then I do this:

```
static const int FILE_COUNT = 2;
std::string _audioBackgroundFiles[FILE_COUNT];
_audioBackgroundFiles[0] = "background.mp3";
#if CC_TARGET_PLATFORM == CC_PLATFORM_IOS || CC_TARGET_PLATFORM == CC_PLATFORM_MAC
    _audioBackgroundFiles[1] = "background.caf";
#else
    _audioBackgroundFiles[1] = "background.ogg";
#endif

for(int index = 0; index < FILE_COUNT; ++index){
        auto id = AudioEngine::play2d(_files[index], false, 1.0f, &_audioProfile);
}

```

I don't understand how to create an audio profile? Do you create a profile for every sound? I'm very confused.

# Answer
This is what I ended up doing:

```
#include "audio/include/AudioEngine.h"

using namespace cocos2d::experimental;

[...]

_musicVol = 5;
_backgroundAudioProfile = AudioEngine::INVAILD_AUDIO_ID;

if (_backgroundAudioProfile == AudioEngine::INVAILD_AUDIO_ID) {
    _backgroundAudioProfile = AudioEngine::play2d("background.mp3", true, _musicVol);
}

AudioEngine::pause(_backgroundAudioProfile);

```
> 1 votes

---
Tags: c++, cocos2d-x, audio
---


# Question
Title: Fire an event while the mouse is down within my box 2d collider in Unity
The method `OnMouseDown()` is called **once** when the mouse presses my box 2d collider.

Is there a method that keeps firing while the mouse is **still holding the button down inside the collider**? Something like `WhileMouseDown()`.

I could use `Input.GetMouseButton(0)` in the `Update()` method. However, this does not check if the mouse is pressing the collider.

# Answer
> 2 votes
You could use a combination of both `OnMouseDown` and `OnMouseOver`:

> OnMouseOver is called every frame while the mouse is over the GUIElement or Collider.

You might want to set something like `bool mouseIsBeingHeld = true;` to track this and change it when `OnMouseUp` or `OnMouseExit` happens.

---

If you'd ever also want to just use `Input.GetMouseButton(0)`, the other way to see if a Collider2D is being hovered over is via Collider2D.OverlapPoint.

---
Tags: unity
---


# Question
Title: Confused about Max Vertex Uniform Vector limit
While coding my WebGL app I've encountered an interesting phenomena:

On my first PC (with GPU Radeon HD 5850), BrowserLeaks (link) tells me that in my browser - Google Chrome Version 36.0.1985.143m the Max Vertex Uniform Vectors value equals 1024 - which is true, when I try to create inside the shader an attribute array bigger than 1024, the browser throws an error: `too many uniforms`, which f.e. in my case let's me draw about 85 simple cubes in a single draw call.

Meanwhile on my other PC (with GPU Intel X3100) with Opera-Next Version 12.15 installed, where BrowserLeaks shows a value 4096 next to the Max Vertex Uniform Vectors field, I can init an array of size 250 000 and even bigger, I can draw 20 000 cubes in a single draw call and everything works fine (except a very low framerate).

So now my question is: Why those numbers varies so much, why in the second case the upper limit value does not seem to be valid? How would I find the true upper limit value (and read it inside my WebGL app at the runtime)?

EDIT: Ok, I've found out how to get this parameter inside a WebGL app: `gl.getParameter(gl.MAX_VERTEX_UNIFORM_VECTORS)`, but the question now is how would I adapt it to shaders...

# Answer
> 2 votes
The answer is relatively similar to this one except you already figured out how to query the limits, so I try to exand it a little bit.

There is no clear perfect solution how to work with those limits, but a good strategy seem to be to only use uniforms you absolutely need to get things to display at all ( which should be really low ) and then "use up" the remaining slots for optional enhancements you can enable / disable or number of lights you can increase / decrease.

edit: you may struggle with the fact that all your for loops must be constant, you can't plainly write `for( int i = 0; i < numLights; i++ ) { ... }`. It's a bit unintuitive but if you want that you have to write.

```
#define MAX_LIGHTS 4

uniform int numLights;

void main ( void ) {
     for( int i = 0; i < MAX_LIGHTS; i++ ) {
         if ( i == numLights ) break;
         /* your lighting calculations */
     }
}

```

Remember that you can also easily runtime compile your shaders in webgl in order for them to work very well in different configurations, it's common for webgl engines to split their shader code into small parts they can parameterize / exchange. The above example has the disadvantage to always "use up" all the active uniforms for the maximum amount of lights, even if the actual amount is lower. If you'd want to do something else with it you'd have to recompile it.

# Answer
> -1 votes
Old hardware had more limits how many uniforms can be allocated. DX10 hardware removed this limit with constant buffers.

---
Tags: javascript, webgl
---


title: How to optimize my lighting shader?

text:
# Question
Title: How to optimize my lighting shader?
I want to create a lighting effect on a gray-scaled world using cocos2d-x. What I've done is creating a layer which runs a shader program that receives light positions and radiuses as input and greyscales every pixel that doesn't fall in a light area. The lights are standard CCSprites which are children of my custom layer and are blended with the background.

The problem is that my fragment shader code is very slow on iPad where the frame rate drops to 15 fps.

```
#ifdef GL_ES
precision mediump float;
#endif

varying vec2      v_texCoord;
varying vec4      v_v2Position;

uniform sampler2D u_texture;
uniform vec2      u_v2LightPositions[8];
uniform int       u_iLightStatus[8];
uniform float     u_fRadiusSquared[8];

void main()
{
  vec4 currentTexelColor = texture2D(u_texture, v_texCoord);

  float gray = dot(currentTexelColor.rgb, vec3( 0.299, 0.587, 0.114 ) );

  for(int i = 0; i < 8; i++)
  {
      float fDistance_x = v_v2Position.x - u_v2LightPositions[i].x;
      float fDistance_y = v_v2Position.y - u_v2LightPositions[i].y;
      if( ( u_iLightStatus[i] == 1 )
       && ( ( (fDistance_x * fDistance_x ) + ( fDistance_y * fDistance_y ) ) <  u_fRadiusSquared[i] ) )
      {
          gl_FragColor = currentTexelColor;
          return;
      }
  }

  gl_FragColor = vec4( gray, gray, gray, currentTexelColor.a );

}

```

Is there any way to optimize this shader? I tried unrolling the loop by writing calculations for each light by hand but I didn't get any better results.

# Answer
> 0 votes
Try to declare your float variables outside of the loop. It doesn't make sense to declare them in each run of the loop. Let me know, how many frames you could gain.

---
Tags: shaders, glsl, lighting, cocos2d-x
---


# Question
Title: How do I add a gameobject to a prefab's script's public gameobject field in Unity?
Okay, I have a prefab with a script. It has the public field gameobject, and I see that in the inspector. When I try to drag an object from the scene into that slot, I'm simply unable to. No error or anything, just acts like it's any other part of the screen.

Is there a type mismatch here? How do I drag something from the hierarchy?

# Answer
make a prefab of the object you will use as yourObject then drag it in the script's public field from the "project" tab rather than the scene
> 0 votes

# Answer
I think the problem is that the prefab can not see instantiated objects that are already in the scene. A way to think about this is: What would your game do if it instantiated the prefab in a scene without that other asset, even though you linked it in the prefab? "Well, I'm not going to do that though" is not a good excuse to the Unity Editor, for what reason I don't know.

My preferred method to get around this is to add a reference to the object at run-time. Depending on what you are working on, it might be as simple as:

```
//On the Gameobject in the scene
public void Start(){//you can use start, awake, or other event as needed
    OtherComponentClassOfPrefab.staticSetupMethod(this.gameobject);//using a static method to pass this reference to other class.
}

//On the Prefab that uses the other object in the scene
public static staticSetupMethod(GameObject go){
    go.Stuff();//do stuff to go, or store it for later use.
}

```

Again, depending on your setup, if a singleton works for you then you can pass the reference to the instantiated prefab directly through that. And if not, a variation of the above will go pretty far if you are creative enough with it. Hope that helps!
> 0 votes

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


# Question
Title: Where the fxc.exe is located in Windows SDK?
I'm using Windows SDK under Windows 8 with Visual Studio 2013. Where I can find fxc? I do not use old Directx SDK.

# Answer
> 2 votes
For the future generations: the path to fxc.exe is desribed here: https://blogs.msdn.microsoft.com/chuckw/2012/03/22/where-is-the-directx-sdk/

On my Windows 7 the path looks like this: C:\Program Files (x86)\Windows Kits\8.0\bin\x86

---
Tags: directx
---


# Question
Title: Camera position and angle different when running inside Unity and when running on Android
On Windows, running Unity 4.6.1p5, my simple game with only a cube, camera and light looks like this

but under Android (Gingerbread on a 5 inch Galaxy Player) the cube appears lower down, slightly different angle and smaller (relative to the screen size). Sorry couldn't get a screenshot with my screenshot app...

Any ideas why please?

# Answer
Somehow the 2 views were because Unity wasn't updating the Windows build, so it seems to have remained at a different camera position.
> 0 votes

# Answer
The reason for this is most likely the different *field of view* (FOV in general or specific for Unity) in combination with the aspect ratio of the Android device.

This thread covers the same problem: http://answers.unity3d.com/questions/23291/same-visible-area-regardless-of-aspect-ratio.html#

The idea is to calculate the target FOV like this and apply it to the camera:

```
float normalAspect = 16/9f;

myCam.fieldOfView = myDesiredHorizontalFov * normalAspect / ((float)myCam.pixelWidth / myCam.pixelHeight);

```
> 1 votes

---
Tags: unity, android
---


title: Lockstep dealing with lag

text:
# Question
Title: Lockstep dealing with lag
I understand how properly connected clients in a lockstep model deal with lag but what about the lagger? How does the lagger know that he or she is lagging? Should I continuously ping the central server?

Also, as the game follows the lockstep model, how does the lagger sync if he needs to? Should the desync be altogether prevented by fast pinging?

# Answer
You can safely throw out Ping from the board.

Lag compensating can work relying on just number of ticks for which commands were received (including NoCommand commands) and confirmed. Since the game is p2p (via server or not it does not matter), each client has number of packets from other clients queued for execution and confirmations of packets he sent.

Now in a lag-less situation each client has roughly the same number of commands/confirmations queued. If there are too many command queued ahead, client can adjust ticks duration to catch up with the plan and reduce the number planned ticks (or plan less commands ahead).

If there's a lag environment, even if one client is lagging, all will, since lag affects both commands received and confirmed. In such situation, clients will need to pause and wait for commands/confirmations to arrive, to fill up the queue. Once the queue is filled with at least one command/confirmation client can make another step. While at that, clients can send several NoCommand commands, to increase the queue length (which will compensate lag better, but make the game less responsive).

All of that can be managed through a server, in centralized manner, or individually. The system is self-balancing and that's the beauty of it.
> 4 votes

---
Tags: networking, latency
---


title: anisotropic fog of war

text:
# Question
Title: anisotropic fog of war
Here I am not talking about how to render fog of war, but how to model exploring of terrain in a more sophisticated way.

In a straight-forward approach, terrain explored by a game unit is simply represented by a circle whose radius is how far this unit can see. And visible area is just union of isometric circles. But I can tell that it is not the case in popular games.

Please take a look at the following screenshot from League of Legends, for example.

The sight of view is anisotropic. The shape of surrounding terrain is also taken in to account.

Any idea how this can be done?

# Answer
> 4 votes
**The shape is irregular because of the obstacles.**

If you shoot a ray in every direction (360 cicle around unit), you determine if you hit an obstacle, and if yes, at what distance. If the ray does not encounter any obstacles before reaching the line of sight distance, then it stops, otherwise it stops at the point of encounter. This is by no means efficient or conclusive, but I hope it helps.

You can then create a smooth path that passes through the ray endpoints.

If your units have a direction, you could also reduce the maximum line of sight distance by applying an angle-based reduction:

```
max_los_distance *= dot( normalized_unit_direction, normalized_ray_direction)*0.2 + 0.8

```

With the above, rays towards the direction of the player use the full los, while rays shot towards the back of the player use 60% of the los.

# Answer
> 1 votes
The main point is obviously to "somehow" include visibility data. You can cast rays from the unit through the terrain at runtime (as noted in Babis's answer), but this is likely to be very expensive, at least if your terrain is fully 3D.

If your representation of terrain is tile-based (or if it is sufficiently regular so that it makes sense to project a grid on your terrain), you can precompute the visibility from each tile to others: either store all pairs in a matrix, or just store a list of nearby tiles with direct visibility for each tile. At runtime you just filter the precomputed visibility data for the current tile with the visibility distance for the unit and smooth the boundaries of the fog of war.

On the other hand, if your terrain is already tile based, than your raycasts would be probably very fast...

# Answer
> 0 votes
I reckon they're doing it in two parts.

The first is working out the boundary of the line of sight. There's lots of different ways of doing this and they're pretty well documented elsewhere.

The way the boundary of the line of sight is displayed is a different thing though. I think I've seen something like this in Unity using projectors (implemented using shaders).

See UnityChat's tutorial here https://www.youtube.com/watch?v=bE6DQdnfe3U&list=PLcGWkWha2wFd5Azr14ZJjvfnAmUKM\_3E7&index=6

That approach projects a light onto the ground from above so it hugs the surface nicely - which seems to me to be the effect with which you are enamoured? That's implemented using a opengl shader something like this: http://wiki.unity3d.com/index.php?title=ProjectorAdditive

---
Tags: terrain, line-of-sight, fog-of-war
---


title: how to close lua file call luaL_dofile?

text:
# Question
Title: how to close lua file call luaL_dofile?
i created tool that generate lua script on each level which contain lot function, and they named based on the object+id format. ex : trigger1(), etc; so every level may have same function name, what i need is call luaL\_dofile on beginning level load.(+ registration ofcourse)

on game every level load i call do\_file this lua script, so i can call it in the code. the thing is, when i try to change level to another level, i dont want close entire lua state and do rereigistration / initialization ,i just want close previous luaL\_dofile and change it with new luaL\_dofile on the next lua level script. since i want instaneous transition each level.

can anyone help me on this ?

# Answer
You can just run the next file. You shouldn't lose your previous state or variables, but you might want to do some cleanup between.

However, what I'd suggest, is using different threads (which won't work like they might sound).

Basically, you've got your parent instance of a lua VM and you create one child thread for each level.

With some table magic, this also allows you to define globals in your parent VM, while the childs (i.e. the level scripts) will be able to access the globals, but they're not able to change anything outside their own scope.

Unfortunately, things changed for Lua 5.2, so I can't give you any snippet for the latest version.

For 5.1 you could do something like this:

```
LC = lua_newthread(L);
lua_newtable(LC);
lua_pushvalue(LC, -1);
lua_pushliteral(LC, "__index");
lua_pushvalue(LC, LUA_GLOBALSINDEX);
lua_settable(LC, -3);
lua_setmetatable(LC, -2);
lua_replace(LC, LUA_GLOBALSINDEX);

```
> 0 votes

---
Tags: c++, game-design, lua
---


# Question
Title: What will happen if the argument of mix() or clamp() is above 1 or below 0?
There's two magnificent intrisincs: `mix()` in GLSL and `clamp()` in HLSL, which are used to implement linear interpolation. Let's say we have a variable:

```
float v = ?; // where ? can be [-FLOAT_MAX, +FLOAT_MAX]

```

and then we do:

```
gl_FragColor = mix(value1, value2, v);

```

So, the question is: does it works the correct way under GL or DirectX? Should I EXPLICITLY normalize the value of v like this:

```
gl_FragColor = mix(value1, value2, clamp(v, 0.0, 1.0));

```

# Answer
> 4 votes
> The return value is computed as `x*(1−a)+y*a`.

in other words if `a` is -1 then the result will be `2*x-y`

---
Tags: shaders, glsl, hlsl, interpolation
---


title: NAT punchthrough failed

text:
# Question
Title: NAT punchthrough failed
I finished my game while I was unaware of this error since it only shows up when I disable "WIFI" on my phone and testing it with `3G` and `4G`. Otherwise, when both devices are on my personal network (and I believe the same network in general) the game works perfectly fine.

Whenever two players connect via my own `MasterServer` I have setup on Amazon AWS services I get this error `Receiving NAT punchthrough attempt from target "XXXXXXXXXXXXX" failed` in the Unity console for both players. I am running both the Unity `MasterServer` and `Facilitator` on the server.

There are many question around the internet like this but not a single one with a answer. If this is really not easily fixable Unity should at least mention it's flaws where it provides the MasterServer. I would love to have an answer or at least some insight since now I have my own Linux server on Amazon I'd like to use it too. Currently it looks like my best alternative is using the multi-player options from Google Play Services.

This is the log I get from the server. Looks perfectly fine but it might help answering.

```
03-02-2015 02:28:31     INFO    New connection established to 24.XXX.XXX.X:62501
03-02-2015 02:28:31     INFO    Query request from 24.XXX.XXX.X:62501
03-02-2015 02:28:31     DEBUG   Version 2.0.0 connected
03-02-2015 02:28:31     INFO    Table Buckrider_Studio_FourInARow3D not found during query or row removal from 24.XXX.XXX.X:62501
03-02-2015 02:28:41     INFO    Connection with 24.XXX.XXX.X:62501 closed
03-02-2015 02:28:41     INFO    Removing rows for IP 24.XXX.XXX.X:62501
03-02-2015 02:28:41     INFO    24.132.7.159:62501 has diconnected
03-02-2015 02:28:41     INFO    New connection established to 24.XXX.XXX.X:61335 (166633197962428130)
03-02-2015 02:28:41     INFO    New connection established to 24.XXX.XXX.X:61336
03-02-2015 02:28:41     INFO    Update row request from 24.XXX.XXX.X:61336
03-02-2015 02:28:41     DEBUG   Version 2.0.0 connected
03-02-2015 02:28:41     DEBUG   Table Buckrider_Studio_FourInARow3D created.
03-02-2015 02:28:41     INFO    Sent row ID 0 in Buckrider_Studio_FourInARow3D to host at 24.XXX.XXX.X:61336
03-02-2015 02:28:41     DEBUG   Updating, inserting 4 at column 4
03-02-2015 02:28:41     DEBUG   Updating, inserting public at column 5
03-02-2015 02:28:41     DEBUG   Updating, inserting 6 at column 6
03-02-2015 02:28:41     DEBUG   Updating, inserting 7 at column 7
03-02-2015 02:28:41     DEBUG   Updating, inserting 8 at column 8
03-02-2015 02:28:41     DEBUG   Updating, injecting 24.XXX.XXX.X at column 9
03-02-2015 02:28:41     DEBUG   Updating, injecting 61336 at column 10
03-02-2015 02:28:41     DEBUG   Updating, inserting Welcome to Connect four 3D! at column 11
03-02-2015 02:28:41     DEBUG   Updating, inserting 166633197962428130 at column 12
03-02-2015 02:28:41     DEBUG   Internal port is 23466 IPs set as 192.XXX.XXX.X
03-02-2015 02:28:50     INFO    New connection established to 188.XXX.XXX.X:46374
03-02-2015 02:28:50     INFO    Query request from 188.XXX.XXX.X:46374
03-02-2015 02:28:50     DEBUG   Version 2.0.0 connected
03-02-2015 02:28:50     INFO    Fetching existing table Buckrider_Studio_FourInARow3D
03-02-2015 02:28:51     INFO    Connection with 188.XXX.XXX.X closed
03-02-2015 02:28:51     INFO    Removing rows for IP 188.XXX.XXX.X:46374
03-02-2015 02:28:51     INFO    188.XXX.XXX.X:46374 has diconnected
03-02-2015 02:28:51     INFO    New connection established to 188.XXX.XXX.X:46375 (300946669)

```

# Answer
> 1 votes
Nat punch-through is not guaranteed to work in all circumstances. ISPs can filter out these types of requests, and phone networks are notorious for doing so. This is what unity says about networking on mobile devices, and This is where they talk about nat punchthrough (which you are right, they make it sound like 'maybe' it will work). I hate giving bad news, but from my little amount of research on this subject, it looks to me like a nonstarter. As a last ditch effort, perhaps confirming that the ports are reachable is the best place to start troubleshooting, perhaps by using a tool like canyouseeme.org or similar. If the ports are accessible (but just don't work over phone networks), then unfortunately you might be out of luck.

---
Tags: unity, networking, mobile
---


# Question
Title: Trying to add a feature to my (basic) level parsing algorithm - not sure how to (JAVA)
Right now this method goes through a list of `GameObjects` (e.g. `JetPack`, `Platform`) with their respective x and y positions in a text file called level1.txt:

```
platform 840 280
platform 1130 280
coin 900 300
coin 950 300
coin 1000 300
coin 1000 400
jetpack 1090 400
platform 650 500
platform 500 400
platform 200 400
NEXT
platform 200 200
coin 250 300
coin 350 700

```

What currently happens is whenever my Player reaches the end of the screen, he goes back to the start (x = 0). When he does reach the end of the screen, I want all the objects BEFORE `NEXT`to disappear and all the objects AFTER `NEXT` to be drawn. I know why my algorithm doesn't work as it should but I'm unsure how to fix it. Can anyone have a look at it and tell me how I can modify it to do what I want it to? `list`is a list of GameObjects in the text file btw.

```
public void loadLevel(String level) {
        list.clear();
        FileHandle file = Gdx.files.internal(level);
        StringTokenizer tokens = new StringTokenizer(file.readString());
        while (tokens.hasMoreTokens()) {
            String type = tokens.nextToken();

            if (type.equals("platform")) {
                list.add(new Platform(Integer.parseInt(tokens.nextToken()),
                        Integer.parseInt(tokens.nextToken())));
            }
            else if (type.equals("coin")) {
                list.add(new Coin(Integer.parseInt(tokens.nextToken()), Integer
                        .parseInt(tokens.nextToken())));
            } else if (type.equals("flag")) {
                list.add(new Flag(Integer.parseInt(tokens.nextToken()), Integer
                        .parseInt(tokens.nextToken())));
            } else if (type.equals("jetpack")) {
                list.add(new JetPack(Integer.parseInt(tokens.nextToken()),
                        Integer.parseInt(tokens.nextToken())));
            } else if (type.equals("pipe")) {
                list.add(new Pipe(Integer.parseInt(tokens.nextToken()), Integer
                        .parseInt(tokens.nextToken())));
            } else if (type.equals("NEXT") && player.getxPos() > SCREEN_WIDTH) {
                list.clear();
            }
        }
    }

```

Any help is highly appreciated, many thanks in advance.

# Answer
The problem is here:

```
} else if (type.equals("NEXT") && player.getxPos() > SCREEN_WIDTH) {

```

Granted that loadLevel is run at the start of your game, it will run and finish well before player.getxPos() is off the screen width. It will only check once when the level is initially loaded.

You need to be able to 'stop' reading the file at 'next', and be able to continue where it left off, when appropriate. You will also need to check every once in a while for when the player's x position is off the screens width, and when that happens that's when you resume the level load.

For me, I would store the text file at a string array (or better a queue), then go through the list of commands, parse them as needed and run them until you hit next or other 'flow control' command. Then later, when the player does something that continues the load process, the level first is 'cleared' then loading continues reading where it left off and runs more commands and the process repeats as needed.
> 1 votes

---
Tags: java, 2d, libgdx, algorithm
---


# Question
Title: How can I get "Good enough" collision for entities?
I am developing a Pirate ship fighting game.

It's a great concept: Ships firing cannonballs, sinking each other, having to work as a team to complete the mission... But.. I've tested it with about 20 people (with ~5 online at once) and the issue is simple: It is not enough fun.

The problem is that collision detection is horrible. With the ships, I detect if a CannonBall is in one of the coordinates that the ship is in with a delayed task. The Ship-To-Ship collision has been impossible for me to implement. I've attempted to add some sort of collision "box", but I cannot make it follow the Ship's rotation.

This means that I cannot have ships hitting each other. It means that I cannot add people to the game. It means that CannonBalls look horribly unrealistic (They just explode inside the ship!). It also means that I cannot add any sort of obstacles into the game (e.g. floating debris). All of these degrade the gameplay horribly.

My plan with the game is to have crew members who have to fight and take over a ship, and then give you the ability to plunder it. Also to add critical damage, e.g. damaging other peoples' cannons, setting them on fire, damaging the sails, etc.

In short, I can do NOTHING without a better collision detection system! My current system can *Roughly* get if something is colliding with the ship, but it is just NOT GOOD ENOUGH!

JBox2D is out of the equasion (I've tried using that), and JBullet also does not work well enough for my needs. Besides, I do not want a collision **ENGINE**! I just want to be able to know when a person is colliding with something and be able to get if that something is in front, to the left/right, or behind the entity.

What is worth trying? Is there any techniques that I have been missing in getting accurate collision detection in my game? Should I be looking at collision engines (even though the ones I have tried do not suit my needs)?

Also, I'm not sure if it is relevant, but it will be the server doing the collision detection.

# Answer
Have you tried Quadtrees combined with SAT?

You can do all your collision detection in 2d, and once you detect that a cannonball is within the bounds of a ships 2d bounding box you can check if it's height is low enough compared to the ships.
> 1 votes

---
Tags: opengl, java, collision-detection, lwjgl
---


# Question
Title: Can't post from Unity to Facebook feed properly
I'm using Facebook SDK for Unity. I'm posting to the user's feed with the Feed function.

According to Facebook, I do not need any permission for it.

"Sharing stories via Feed Dialog does not require any extended permissions, and a person can easily change the audience for each story they choose to share." https://developers.facebook.com/docs/sharing/reference/feed-dialog/v2.2

```
1) FB.Init(OnInitComplete);

2) FB.Login("", OnLoginComplete);

3) FB.Feed(link: LinkToApp,
           linkName: LinkName,
           linkCaption: LinkCaption,
           callback: OnPublishLinkComplete);

```

When I log in with a user which is not an admin this is the process:

1) the application is asking permission for my public profile - I click ok

2) A popup of sharing comes up, I type in my text and click Post

3) Gets me back to the app but not posting happened

4) Trying to post again

5) A popup of "Oops, Something Went Wrong" comes op

Then the process repeats itself from 2 to 5.

---------- Update ----------

If I use the 6.2.1 version, I get "Oops, Something Went Wrong". If I use the 6.0 version, the post gets shared, but the callback returns with {"cancelled":true}.

# Answer
> 1 votes
This is a known bug in their SDK for Unity: https://developers.facebook.com/bugs/598200610227965/

There is a workaround, you can change the DialogMode in the FbUnityInterface.mm

From this

```
self.dialogMode = NativeDialogModes::FAST_APP_SWITCH_SHARE_DIALOG;

```

To this

```
self.dialogMode = NativeDialogModes::WEBVIEW_DIALOG_MODE;

```

---
Tags: unity, facebook
---


# Question
Title: Static SFML 2.2 libraries and Code::Blocks on windows 7
I am starting to program games for the first time, but I've been doing general programming for a couple years now. I have Code::Blocks, which I am fairly comfortable with, but now I am struggling with trying to add a game library to my projects.

I decided on SFML 2.2 because it has all of the features I need. I am also planning on writing this in C++ if that affects anything. I read the instructions that SFML has on their site, but I still can't seem to get it to work. I am also under the impression that having the static version of SFML implemented will make the end result program be all one executable file rather than a file that accesses other files. If that is not what this means, please correct me.

I messed with the directories settings like their site mentioned, as well as the linker settings and the compiler settings. I keep getting errors that say something along the lines of...

```
"Undefined reference to 'sf:VideoMode::VideoMode(unsigned int, unsigned int, unsigned int)"

```

...along with many other undefined functions. Any help on implementing game libraries in general would be very helpful as well.

For reference, the tutorial I attempted to follow is at http://www.sfml-dev.org/tutorials/2.2/start-cb.php

# Answer
> 0 votes
There's two common pitfalls when using a static library on Windows, one being particular to your linker:

Symbols exported from DLLs have `__declspec(dllexport)` decoration and need to be `__declspec(dllimport)` decorated on use. Software tends to have defines like `SFLM_STATIC` whose presence or absence indicate the right mangling to use.

The GNU linker is sensitive to the order in which libraries and object files are mentioned. Ensure that items that require symbols occur before the items that provide the symbols on the linker command line.

---
Tags: c++, sfml
---


# Question
Title: How do I access my existing script from a different script attached to a different gameobject?
I have my health (script) component on my player GameObject that gets boosted whenever we tap on that GameObject. However, I want to add a separate GUI texture button GameObject and tap on that to boost my health.

How do I access the health script with this new button button to get it working? I actually want to test this method for tapping on my health packs to increase the health.

This is the existing script I want to access:

```
//this is my health bar script which increases by tapping
var health = 300;

function OnGUI(){
    if(GUI.Button(Rect(10,10,health,10), "")){
        health += 25;
    }
}

```

# Answer
Your new script will need to reference the gameobject that holds your health script, or directly reference your health script from your new script.

For example, I would modify your existing health script (I'm going to write it in C#, but you can convert it to UnityScript if you prefer):

```
//this is my health bar script which increases by tapping
int health = 300;

void OnGUI(){
    if(GUI.Button(Rect(10,10,health,10), "")){
        AddHealth();
    }
}

public void AddHealth() {
    health += 25;
}

```

Then in your other gameobject script you can write something like:

```
public GameObject healthObject;
void Start() {
   healthObject = GameObject.Find("NameOfYourHealthGameObject");
}

void OnGUI(){
    if(GUI.Button(Rect(10,10,health,10), "")){
        healthObject.GetComponent<NameOfYourHealthScript>().AddHealth();
    }
}

```

You have lots of options here. You can also assign the object manually by dragging and dropping the health GameObject onto the new script's `healthObject` field in the inspector (if you do that remove the code in the `Start` method). Or you could use the event system, or lots of other options.

I've also noticed you're using the old `OnGUI` method of creating your GUI. I'd suggest moving to the new GUI system recently released from Unity. It's much easier to use and provides a lot of functionality for you automatically. Additionally, for someone who's new to Unity, it allows a lot more work to be done solely in the Unity editor, which means less scripting and more game making.
> 1 votes

# Answer
No problem with the new UI you can Add a button and place where you would like it. Set the image as the image you would like to use. Then you can create a OnClick event and drag your object with the script accessing the health to it. Click on the function in the onclick and set it to the function to increase the health change to something like this and you will be able to select it as a function in the Buttons OnClick

```
public void IncreaseHealth()
{

        health += 25;
        Debug.Log(health);

}

```
> 0 votes

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


# Question
Title: How do I efficiently perform collision detection on an NxN rectangle grid?
I have a simple level that is constructed from an NxN rectangle grid. Some of the rectangles are walls, and some of them are the path. The player is allowed to move only on the path they are on and also the path rectangles on the grid. So I have two kinds of rectangles in the grid:

1. "path"
2. "wall"

The player is a sprite above the grid. I want to efficiently find if the player is colliding with the wall. I want to loop through the rectangles, to see if they intersect. What is the best method?

# Answer
> 1 votes
The most efficient way is probably not calculating anything. You can "precalculate" collision simply by drawing the wall "a bit smaller". Just subtract half of player *r* from the wall, the wall is still "physically" on whole tile but its image just don't reach its edges. Floor the float value of your player position, query grid matrix...and done!

```
inline bool isCollision()
{
    return (grid[(int)player.x, (int)player.y] is Wall);
}

```

# Answer
> 1 votes
Assuming your grid is represented as a 2d array of booleans (0 for path, 1 for wall) or integers (n for path, m for wall), and the player is smaller than the tiles, you need to check if any of the four corners of the player are inside a wall.

If the center of the player's "square" is `x, y` and the width is `w` then you need to check in

```
(x - width/2,  y - width/2) // top left
(x + width/2,  y - width/2) // top right
(x - width/2,  y + width/2) // bottom left
(x + width/2,  y + width/2) // bottom right

```

You check if a point is inside a tile by dividing that point's `x, y` position by a tile's width and height and then check if there is a tile in the resulting position in the 2d array that represents the tiles.

```
checkCollision(x, y)
{
    tileX = Math.floor(x / TILE_WIDTH);
    tileY = Math.floor(y / TILE_HEIGHT);
    tile = grid[tileX][tileY];
    return isWall(tile);
}

```

# Answer
> 0 votes
You need to calculate the area covered by the played in a grid.

If you consider each wall a position inside a grid, you only need to check the collision against the cells occupied by the player.

If you consider your player has a size of 1x1, you can know in which cell of the grid your player falls into if you divide it's position between the size of each cell.

So if you player is in position (12,9), and your cells are 5x5 units in size:

(12,9)/5 = (2,1)

Since you start counting in 0, the player would be in the third cell in the second row.

If you are storing your cell information inside a matrix you should only check collision against position \[2,1\].

The same applies if the player cover a bigger area: Just check which cells cover the corners of your player.

---
Tags: collision-detection, grid
---


# Question
Title: What is the correct way to raycast on click?
I am using raycast from screen point to detect if the user has clicked/touched on something.

The following fails 1/10 times; at first I thought due to the raycast missing the subject below, but after adding in the drawline i realise that it randomly doesn't even fire:

```
// layerMask declared with correct layers
void FixedUpdate(){
    if(Input.GetMouseButtonDown(0)){
        Debug.Log("click");
        Ray ray;
        RaycastHit hit;
        if(Physics.Raycast (ray, out hit, Mathf.Infinity, layerMask)){
            Debug.Log("You clicked on " + hit.collider.gameObject.name,hit.collider.gameObject);
        }
}

```

If I run this in `Update()` function instead, it will work perfectly - so `FixedUpdate()` seems to understandably cause the missed clicks... but i'm told I should always run the raycasts in `FixedUpdate()` for physics optimisation.

Maybe I should split this basic action over 2 functions?

A friend said i need an event handler

# Answer
Imagine a static menu scene with no physics. There would be no need to use fixed updates because there is no physics involved in a menu. In this case, your raycast is an interface type interaction, not a collision-detection or force-application type interaction. Even if you were going to apply a force based on that click, you would want to schedule that for the fixed update in order to keep those concerns separated.

So yes, you could use an event handler, but the heart of the issue is separation of *UI* from *Physics*.

See also Execution Order of Event Functions \- particularly the *Script Lifecycle Flowchart*

**Edit:** Aha, there's the wording I was looking for. They say specifically to use FixedUpdate "when dealing with Rigidbody." (MonoBehaviour.FixedUpdate)
> 3 votes

---
Tags: unity, raycasting
---


# Question
Title: Smooth transitions between 2d animations
I am writing a 2d game (in libGDX, but I think that doesn't matter too much). In that game I want to have smooth transitions between animations. For example, let's think of a guy walking around. Now that guy is hit by something (a bullet for example) and dies. So I want to play the death animation for this guy now.

The problem: I cannot simply exchange the walking animation by the death animation, because the guy's current walking animation frame is not necessarily the same as the first frame of the death animation. So for the player that would look as if the animation "jumps" from walking to death.

So my question is: what is the "typical" way to achieve a nice and smooth transition from animation to another, in general?

# Answer
> 6 votes
There are several different options for handling what you are attempting: These are not all or nothing solutions, you can mix and match them to balance the workload between programming and creating animations.

**Option 1**

Can be used on a case by case basis. Obscure it. The transition between animation states can simply be hidden behind various effects. Blood spurts, explosions, dust clouds are all common options

**Option 2**

Applies mostly to frame based animations. Create a lot of transition animations, you generally don't need to consider every frame of every animation transitioning to the beginning of every other animation, just enough to get the smoothness you desire.

**Option 3**

Applies to animations based on skeletons. Use an animation system that provides interpolating from one animation to another. An example would be Spine, which has a runtime for libGDX.

**Option 4**

Delay the transition until your first animation reaches a point that it can be transitioned. This can be combined with a change in the game update to speed up or slow down the look of the game as desired.

---
Tags: libgdx, animation
---


# Question
Title: Client-Server Game Communication (w/ Protobuf, Relevancy and Delta Compression)
So, I have reached another problem while trying to implement my client-server communication. From everything I've read there are three main ways to minimize packet size:

1. Only send what has changed to the client (Delta Compression)
2. Only send what gameobjects are relevant to the client (Relevancy)
3. With large packets, zip/compress them (L4Z?) \[Not key for this question\]

I have already implemented a delta compression scheme throughout my codebase using dirty bits and some interfaces. It's not as easy to use as I'd like, but it is decent and it works. Now I need to figure out how to add relevancy. I can certainly determine relevancy for each GameObject, but keeping track of all these deltas and which client has received them I think could get inefficient and complicated.

I considered having Players keep a NetworkComponent that tried to keep track of sending and maintaining what hasn't been sent, but I feel that could get complicated.

Advice on how to implement or improve either of these?

# Answer
> 3 votes
My solution has been to combine both 1 and 2 into a "watching me list" on each object. When adding a client to an object's list, it sends a full state packet. Then on each update, it can send a delta compressed packet. When the object is no longer relevant to a client, simply remove it from the list and possibly send a "forget me packet" so the client knows it will not be receiving packets on this object anymore.

---
Tags: c#, networking, component-based, client-server, compression
---