# Question
Title: NegaScout with Zobrist Transposition Tables in Chess
I'm trying to put Transposition tables into my alpha beta scout. I do see an incremental speed boost I think toward mid or late game, however, even with a table size of 1-2GB, its may or may not be slower than just not reading from the Transpose table at all. I'm also noticing some less than efficient moves if I were to play the exact same game without the tables.

I tested my Zobrist key hashing, and they come out properly even after making and undoing moves. I don't believe they are the issue. I tried to follow the advice of these articles in designing the alpha/beta pruning. http://web.archive.org/web/20070809015843/http://www.seanet.com/~brucemo/topics/hashing.htm http://mediocrechess.blogspot.com/2007/01/guide-transposition-tables.html

Can anyone help me identify a mistake? Perhaps I'm not understanding the evaluation of checking alpha vs beta from the hash. Or is 1-2GB too small to make a difference? I can post more of the Transposition table code if need be.

```
 public int alphaBetaScout(Board board, int depth, int alpha, int beta, bool color, bool
quiscence)
{
    // !!!! With or without this specific section, and any other Transpose.Insert, doesn't make the game play or evaluate any faster.
    HashType type = HashType.AlphaPrune;
    HashEntry h = Transpose.GetInstance().Get(board.zobristKey);
    if (h != null)
    {
        if (h.depth >= depth)
        {
            if (h.flag == HashType.ExactPrune)
            {
                return h.scored;
            }
            if (h.flag == HashType.AlphaPrune)
            {
                if(h.scoredState > alpha)
                {
                    alpha = h.scored;
                }
            }
            if (h.flag == HashType.BetaPrune)
            {
                if(h.scoredState < beta)
                {
                    beta = h.scored;
                }
            }
            if (alpha >= beta)
            {
                return alpha;
            }
        }
    }

    if (board.terminal)
    {
        int scoredState = board.Evaluate(color);
        Table.GetInstance().Add(board.zobristKey, depth, Entry.EXACT, scoredState);
        return scoredState;
    }

    //May do Quescience search here if necessary && depth = 0

    Stack movesGenerated = GeneratePossibleMoves();
    while(!movesGenerated.isEmpty())
    {
        int scoredState = MAXNEGASCOUT;

        board.MakeMove(movesGenerated.pop());
        int newAlpha = -(alpha +1)
        scoredState = -alphaBetaScout(board, depth - 1, newAlpha, -alpha, !color, quiscence);

        if (scoredState < beta && alpha < scoredState)
        {
            scoredState = -alphaBetaScout(board, depth - 1, -beta, -scoredState, !color, quiscence);
        }

        board.UndoMove();

        if (scoredState >= beta)
        {
            Table.GetInstance().Add(key, depth, Entry.BETA, beta);
            return scoredState;
        }

        if (scoredState > alpha)
        {
            type = HashType.ExactPrune;
            alpha = scoredState;
        }
    }
    Table.GetInstance().Add(key, depth, type, alpha);
    return alpha;
}

```

# Answer
> 0 votes
The code seems OK at first glance. I would suggest profiling the transposition table, maybe your actual implementation is just to slow at storing and retrieving the entries. Which would also explain why you get better moves with transpositions, although you do not get a speed benefit.

# Answer
> 0 votes
Do not insert into transposition table at the leaf node.

So comment the "Add" command in this block "if (board.terminal)"

---
Tags: c#, software-engineering, ai, strategy, chess
---


# Question
Title: Cycling UV-coordinates with instanced drawing c++/opengl/glsl
I'm trying to animate 2d sprites using `glDrawArraysInstanced()`, and I'm having trouble separating for each "cycle" ran through the pipeline.

according to one of the tutorials I'm reading, it says:

```
"Send the age of each particle along with the position, and in the shaders, compute the UVs"

```

But without clarifying exactly how to do so. This is what my vert shader looks like atm:

```
#version 400 core
layout ( location = 0 ) in vec3 vertex_position; //vertices, 1 box
layout ( location = 1 ) in vec2 tex_cord; //1 tex cord
layout ( location = 2 ) in vec4 color_vec4; //1 vec4 color per texture
layout ( location = 3 ) in mat4 in_mat; //4 vec4 to make 1 mat4

//flat out int InstanceID; //use but how?

out vec2 UV;
out vec4 color4;

void main()
{
    gl_Position=in_mat*vec4(vertex_position,1.0);

    color4=color_vec4;
    UV=tex_cord;
}

```

And my frag shader:

```
#version 400 core
in vec2 UV;
in vec4 color4;

uniform sampler2D png_tex;  //texture atlas

void main()
{
    gl_FragColor=texture(png_tex,UV)*color4;
}

```

Does anyone know how to get the vec2-uv coordinate to change/cycle, when using instanced drawing?

**Solution:**

adding this to my vert shader:

```
UV=vec2
(
(tex_cord.x/info_vec4.z)+(1.0/info_vec4.z*info_vec4.x),
(tex_cord.y/info_vec4.w)+(1.0/info_vec4.w*info_vec4.y)
);

```

I know this can be done cleaner, but I'm not sure exactly how atm. This works however, and its alot faster than having to pass a new png/texture per update. The explanation for it is: info\_vec4 is an ivec that I pass as an attribute with information of the current primitive/triangle. It holds: x=xcord (1-5), y=ycord (only 1), z=number of x frames total, and w=number of y total. The trick was figuring out how to iron out UV.x=0, basically by adding 1\*somevalue to 0.

# Answer
> 1 votes
As the tutorial suggests you should send the age or the frame number along with the instanced position.

On top of that you'll want to set 2 parameters one for how many frames you have horizontally and one for how many you have vertically.

Then you simply do:

```
uv.X = (frameNum % horiontalFrames)/horizontalFrames;
uv.Y = floor(frameNum/horizontalFrames)/verticalFrames;

```

This assumes of course that your animation frames are evenly spaced inside a texture and don't have any offset to the edges etc.

---
Tags: opengl, glsl
---


# Question
Title: Understanding SpriteBatch.Draw overload XNA
I'm talking about the
public void Draw (Texture2D texture, Vector2 position, Nullable sourceRectangle, Color color, float rotation, Vector2 origin, float scale, SpriteEffects effects, float layerDepth) method.

My Sprite has Scaling, Position and Rotation. I want it to rotate from the center, towards the mouse.

This is the method I've tried using so far:

```
public void RotateTo(Vector2 point)
{
    var angle = AngleBetween(Position, point);
    Rotation = MathHelper.ToRadians((float)angle);
}
public static double AngleBetween(Vector2 first, Vector2 second)
{
    double sin = first.X * second.Y - second.X * first.Y;
    double cos = first.X * second.X + first.Y * second.Y;
    return Math.Atan2(sin, cos) * (180 / Math.PI);
}

```

But as you can imagine, this didn't work well. First of all, the origin of the sprite wasn't the center. I've tried changing the origin parameter in the Draw method to `sprite.Texture.Bounds.Center.ToVector()` (ToVector is an extention method) but that also didn't work. The sprite was rotating in a weird way, not focusing around the mouse, because it seemed that the sprite was rotating around a different center point, not the mouse itself.

I didn't manage to find in depth explanations about `SpriteBatch.Draw`, so I hoped someone here would have the knowledge and experience to help me.

Thanks for reading, and thanks in advance for the help!

# Answer
Basic explaination about the method with regards to positioning, scaling and rotating:

This draws a sprite with `myTexture` with the topleft corner on 100,200:

```
sprite.Draw (myTexture, new Vector2(100,200), null, Color.White, 0, Vector2.Zero, 1, SpriteEffects.None, 0);

```

This draws a sprite with `myTexture` with the center on 100,200:

```
sprite.Draw (myTexture, new Vector2(100,200), null, Color.White, 0, new Vector2(myTexture.Width/2,myTexture.Height/2), 1, SpriteEffects.None, 0);

```

This draws a sprite with `myTexture` with the center on 100,200, rotated 90 degrees:

```
sprite.Draw (myTexture, new Vector2(100,200), null, Color.White, MathHelper.PiOver2, new Vector2(myTexture.Width/2,myTexture.Height/2), 1, SpriteEffects.None, 0);

```

This draws a sprite with `myTexture` with the center on 100,200, rotated 90 degrees, scaled to half the size:

```
sprite.Draw (myTexture, new Vector2(100,200), null, Color.White, MathHelper.PiOver2, new Vector2(myTexture.Width/2,myTexture.Height/2), 0.5f, SpriteEffects.None, 0);

```

**Added clarification:**

The origin determines two things:

1. The position of the sprite in relation to the `position` parameter in the `Draw` call.
2. The center of rotation for the rotation parameter.
3. The center of scaling.

The green dot in the image below represents the 'origin' parameter. From the examples given above the center is given in the number of pixels in relation to the top left corner of the sprite. If the grey box in the image has a size 100 x 100 pixels: the center would be `50,50` and the rightmost example (origin outside the sprite) would be `125,50`.

The blue box is an indicator of where the box was without rotation or scaling. As you can see, the box is rotated 45 degrees in all three images. However, where the result ends up is different. The center of rotation is based on the origin and the box is rotated *in relation* to that point.

With regards to scaling; setting the scale to `0.5f` would in all three images result in a box half the original size. Also where it ends up will be different due to the center of scale being *relative to* the origin, as shown in the image below.
> 6 votes

---
Tags: xna, rotation, spritebatch
---


# Question
Title: Display Rich Text in a TextMeshProUGUI component
I am rading a text to be displayed in a Text UI from an asset using the standard commands

```
Resources.Load<TextAsset>("nameOfMyTextAsset");

```

The text is a .txt.

The text contains richtext tags to format the text in bold or italics. The richtext tags are displayed as such.

I am using TextMesh Pro and insert the text via the following cmd

```
public TextAsset MainText;
MainText = Resources.Load<TextAsset>("nameOfMyTextAsset");
this.GetComponentInChildren<TextMeshProUGUI>().text = MainText.text;

```

The text is displayed like this

How can I read text with richtext tags from a text asset?

# Answer
Here we go, thanks for the hint, @DMGregory. By trial and error:

One has to enable rich text before assigning the text to the object. The full commands would be

```
using UnityEngine;
using System.Collections;
using TMPro;

public TextAsset MainText;

// put this in some function
MainText = Resources.Load<TextAsset>("nameOfMyTextAsset");
// enable rich text
this.GetComponentInChildren<TextMeshProUGUI>().richText = true;
this.GetComponentInChildren<TextMeshProUGUI>().text = MainText.text;

```
> 1 votes

---
Tags: unity, c#, text, format
---


# Question
Title: How to stop SDL from freezing the rendering while resizing the window?
I have a simple SDL application with a re-sizeable window. If I minimize it and then maximize the window the rendering freezes. I've included a simple code example below which makes the screen flash through varying shades of grey. Try minimizing and then maximizing the window, and you can see that the rendering halts while the window is resizing. How do I stop the rendering freezing when going from minimized to maximized?

```
//FLASHING SCREEN CODE
//Demonstrates screen freeze when you minimise then maximise the screen....

#include "SDL.h"

using namespace std;

int main( int argc, char* args[] )
{
    //Initialise SDL2, declare Window + Renderer
    SDL_Init( SDL_INIT_VIDEO | SDL_INIT_AUDIO ); //Initialize SDL for video and audio
    SDL_Window* pWindow = NULL;
    SDL_Renderer* pRenderer = NULL;
    pWindow = SDL_CreateWindow("Minimise Maximise Test", 50, 50, 1200, 600, SDL_WINDOW_RESIZABLE | SDL_WINDOW_MAXIMIZED);
    pRenderer = SDL_CreateRenderer(pWindow, -1, SDL_RENDERER_TARGETTEXTURE);

    //The Screen colour which is going to flash through different shades of grey
    SDL_Color screenColour = {0, 0, 0};

    //SDL event for detecting X-out (quit)
    SDL_Event event;
    bool quit = false;

    //Loop
    while( quit == false )   //While SDL has not been X'ed out
    {
        //Handle quit
        if (SDL_PollEvent(&event) != 0)
        {
            if(event.type == SDL_QUIT) quit = true; //Press X-out to quit (but not visible on fullscreen)
        }

        //Make screen flash by changing its colour through shades of grey
        screenColour.r++;
        screenColour.g++;
        screenColour.b++;

        //Render the screen
        SDL_SetRenderDrawColor(pRenderer, screenColour.r, screenColour.g, screenColour.b, 255);
        SDL_RenderFillRect(pRenderer, NULL);
        SDL_RenderPresent(pRenderer); //like SDL_flip
    }

    //Shutdown
    SDL_DestroyRenderer(pRenderer);
    SDL_DestroyWindow(pWindow);
    SDL_Quit();

    return 0;
}

```

I'm currently running SDL2.0 v 2.0.3 on Windows 10 machine (experienced the same problem running on previous Windows 7 machine).

# Answer
This is not something you can do, at least not using pure SDL. This seems to be a bug in SDL, which apparently is not fixed yet. However, at least to me, this isn't a huge issue, but perhaps this annoys you.

I tried tinkering around SDL with specific WinAPI calls and ugly hacks to access the Windows message loop, but I was unable to get any results. SDL simply seems to halt the game process while the window is being resized and dragged, and there really isn't much you can do about it.

If you feel confident working using the Windows API and WM events, you might want to investigate how you could get a hand on those events before SDL does, but that will of course drop your multi-platform support that you gained with choosing SDL as your windowing library.
> 3 votes

---
Tags: sdl2
---


# Question
Title: MonoGame sprites not consistently drawing
Please don't mark this as a duplicate of my previous question which was asked anonymously. this is a reattempt because i cannot edit the first attempt.

What I have so far is: \- randomly generated tile set with items on SOME tiles \- one creature spawner that spawns up to 5 creatures which can be controlled by the player \- the ability for creatures to pick up items and bring them back to the spawn and store them for later use

What I am noticing is when i launch the game, it doesnt always show all the sprites. Sometimes the spawner is missing, or the creatures, or the GUI. ANd when things DO appear, if i tell the creatures to pick up anything, other items on the ground randomly appear and disappear. even the spawn sometimes disappears! what I do notice is that when i have multiple creatures, some will disappear when crossing invisible lines but not all of them. i forced two creatures to go east at the same speed and time, and one vanished and the other didnt.

If you have any ideas as to what might be causing this, please let me know. if you have any questions, i'll try to edit to appease you.

thanks for reading!

I have my draw method like this:

```
GraphicsDevice.Clear(Color.CornflowerBlue);

// TODO: Add your drawing code here

spriteBatch.Begin(SpriteSortMode.BackToFront,
          null, null, null, null, null,
          camera.GetTransformation());

worldEntity.Draw(spriteBatch);

guiManager.DrawGUI(spriteBatch);

spriteBatch.End();

base.Draw(gameTime);

```

for the world entity... its draw method systematically goes through each tile in the world and calls its draw method. the tile draws itself using

```
Vector2 topLeftOfSprite = new Vector2(this.X, this.Y);
Color tintColor = Color.White;
spriteBatch.Draw(tileTexture, topLeftOfSprite, tintColor);

```

and then proceeds to call the draw method of any items on it.

creatures and items have very similar draw methods.

the gui also draws itself in a similar fashion.

what i DO notice is that ive NEVER seen ground tiles vanish, only the items on them or creatures in the world. Could it be their Z isn't set appropriately?

# Answer
> -1 votes
Okay, OP. what you needed to do was google for 15 minutes, find the deferred setting and use that. THEN realize that you were drawing the GUI only to an exact location and NOT relative to the window.

---
Tags: sprites, monogame
---


title: UI Text Won't Change Color in Unity 5

text:
# Question
Title: UI Text Won't Change Color in Unity 5
In Unity 5 on Windows 10, I try to change the text color from the Inspector and in scripts, but the color won't change. Here are some screenshots of my Text objects open in the inspector, with there colors set to red and white, but staying the default black in the Scene and Game windows:

Here are the lines of code I am using to change the color

```
var textColor = beatBestTime ? "#FF0" : "FFF";

scoreText.text = "Time " + FormatTime (timeElapsed) + "\n<color="+textColor+">Best " + FormatTime (bestTime)+"</color>";

```

which I can verify are being run, but the color remains the same!

# Answer
> 3 votes
I got stuck on this same thing in this tutorial. My fix was to assign the font material to the text component's material directly underneath where you change it red.

# Answer
> 1 votes
Like user @JaredBrowne says, just go ahead and add the material that was created when you made the "Create Edible Copy".

# Answer
> 0 votes
If it's a bitmap font, you need to make sure that the letters in the sprite sheet are white so that colors will be applied correctly with Unity's default text shader. Most tools, including Unity's "Create Editable Copy," create black letters, but this will lead to the exact symptoms you describe. If you have an existing sprite sheet with black letters, you can just do a quick color replacement in your editor of choice.

---
Tags: unity, gui, color, text
---


# Question
Title: How to keep a round body rotating without rotating it's center
I want to make a game in Unity in which the Player is a sad star. I want to have the points (The "arms and legs and head") of the star to rotate like a circle but to keep it's face (which is in it's center) still. How can I do that ?

The body should rotate and it's center should stay still. Many thanks in advance!

# Answer
Have your gameobject hierarchy like so:

```
STAR
  - FACE
  - BODY

```

Then rotate the Body of the star. Your face and body will be two seperate entities of course, where the face will be drawn overtop the body gameobject.

This keeps both gameobject independent from one another.

**EDIT**

Have your main script on the Star gameobject. Then attach the RigidBody to the Body gameobject.

Your script will rotate and move using the RigidBody component. The one caveat of this approach is that you will have to also update the "Face" gameobject to follow your RigidBody.

```
void LateUpdate() {
    Face.transform.position = Body.transform.position;
}

```
> 9 votes

# Answer
A Wheel Joint 2D should allow the face to remain *relatively* upright when attached to the rotating star. Think of it as the classic car model but the wheel is bigger than the car body and the car body is closer to the screen than the wheel. In this case, the wheel (star) is what has the RigidBody2D.

You *might* need to put a motor in the face whose speed is -1 x the star/wheel's speed.

I'm not sure you need Update code *for this*. Save it for if you want to change facial expressions or allow a slight rotation for some effect (speed, pain, powerups, etc.). The less code in Update, the better!
> 0 votes

---
Tags: unity, 2d, graphics, unityscript
---


# Question
Title: Handwriting or handwritten text recognition in augmented reality
Is there any way available to detect **handwriting of a user** using augmented reality within Unity. Or convert user hand written text into characters?

# Answer
> 1 votes
You're asking an extremely broad question considering there are so many specific design decisions that relate not only to your application but also the hardware you'll want to use. *Augmented reality* is really broad considering it can apply to anything from VR Headsets, to things like the Kinect, to even phones. You'll probably get more helpful answers if there's a specific point that you're having trouble with but from what you asked there can only be broad answers. The entire task from sensor input to alpha-numeric characters can be broken down into two parts.

1. Capture input handwriting data
2. Put input handwriting data into library

## Capture Input Handwriting Data

Requirements to track handwriting data will be

* Determine when the user wants to start
* Determine the actual path the user is drawing
* Determine when the user "picks up pen" while writing
* Determine when the user wants to stop

*Possible solution 1: A button* \- The most intuitive way to solve this problem would be to give the user some sort of button (like in the HTC Vive, Oculus Touch, etc). You might have to provide the user with a button if you're using something else (Leap Motion, Xbox Kinect). The use would then draw within the space of the motion tracking camera while holding the button.

The button would delineate between a writing and non-writing mode so that users could determine when they want to start, stop, and break up words. Motion tracking would take care of the actual path the user is drawing.

*Possible solution 2: A box* \- Another way you might solve this would be to have a distance from the augmented reality camera or interaction with a physical surface on a virtual level be the start and stop writing action. Similar to how you interact with a signature pad at a point of sale system, pressing "into" (in this case beyond) the surface would trigger writing while pulling back would stop writing.

There's probably other solutions that more creative people will come up with but these are the most obvious to me.

## Put input handwriting data into library

From the previous step we can assume that we get a list of vector paths that each represent portions of the handwriting. You'd have to then transform this data to put it into the handwriting library.

This might include (again, hardware and application specific):

* Flipping the data horizontally depending on the direction your camera is facing relative to the user.
* Transform your input data so that it lays on a flat plane as a handwriting library would expected (either disregarding the cameras view vector axis or treating the text as mapped onto a cylinder perpendicular with the up direction to remove any 3 space curvature from the text)
* Breaking up the pathing data into discrete units so the handwriting library can work its magic.

You could then shove the new data into your glyph/writing recognition library from which you have multiple choices (from a quick google search).

And from the many choices above, you would get some sort of string representations of what was written.

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


# Question
Title: What is the class name in Unity's AddComponent?
Unity's AddComponent() method has an optional parameter of a `string`. This `string` is the `className`. What is the class name? What is it used for? I could not find any documentation on this.

# Answer
It's the class name of the component you want to add. For example, if you created a MonoBehaviour script named `GoToPosition` and wanted to add it to a game object via script you would call: `AddComponent("GoToPosition");`

That being said, this isn't typically a method I use. I'd rather be explicit about it and use the alternate method of adding components: `AddComponent<GoToPosition>()`. This ensures a few things:

1. It's strongly typed, so I know if I spelled the component name correctly.
2. If I change the name of the component, I can confirm the name changes everywhere (doesn't work as well when the name is a string)

Now, *that* being said. The text version does have advantages. I've used it when creating a system for externally scripting entities. In that case, I can just add the names of the components I want to add to an entity in an external text file. Then I can use the text version of `AddComponent` to easily add the components to entities when parsing the external text file. It's kind of a shortcut for using reflection to find the component class myself.

Both have their uses, but in most cases, you should use the generic type method `AddComponent<GoToPosition>()`.
> 5 votes

# Answer
It appears to just be the *name of the type* of component, used to look up which actual object to create or which component to get (later, when you called `GetComponent`).

The string versions of these functions exist, presumably, for untyped languages that could not use `Type` (inferred from a generic parameter) like C# can.
> 4 votes

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


title: Error rendering map android

text:
# Question
Title: Error rendering map android
I'm trying to read this text file and render the corresponding tiles on the screen.

The code for reading the map is as follows:

```
private void loadMap(InputStream is) throws IOException {
    ArrayList<String> lines = new ArrayList<String>();
    int width = 0;
    int height = 0;

    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    while (true) {
        String line = reader.readLine();
        if (line == null) {
            reader.close();
            break;
        }

        if (!line.startsWith("!")) {
            lines.add(line);
            width = Math.max(width, line.length());
        }
    }
    height = lines.size();

    for (int j=0; j < 18; j++) {
        String line = (String) lines.get(j);
        for (int i=0; i < width; i++) {

            if (i < line.length()) {
                char ch = line.charAt(i);
                Tile t = new Tile(i, j, Character.getNumericValue(ch));
                tiles.add(t);
            }
        }
    }

}

```

The first problem I have is with `Character.getNumericValue(ch)` as this does not seem to be doing anything, resulting in a NullPointerException. When I remove it and replace it with either a 1 or a 2 I'm able to render the tiles onto the screen but somehow the spaces in between the digits are interpreted as tiles, resulting in a continuous block of tiles eg in the second line with 1s results in tiles beginning from the left margin up until the last 1. How can I fix this?

# Answer
If I have analyzed the problem correctly the issue here is that `Character#getNumericValue(ch)` is returning -1. This is because it is reading *all* characters in the line, including whitespace characters, which does not have a numeric value. The `Character#getNumericValue(ch)` javadocs read:

> If the character does not have a numeric value, then -1 is returned.

The solution would be to do something like this inside of your for-loop where you create the tile:

```
// Inside of the for-loop...
if(i < line.length()) {
    char ch = line.charAt(i);
    int charValue = Character.getNumericValue(ch);

    // Checks if the character is an invalid character such as a whitespace.
    if (charValue == -1)
        continue;

    Tile t = new Tile(i, j, charValue);
    tiles.add(t);
}

```
> 1 votes

---
Tags: android, tilemap
---


# Question
Title: Does A* actually find the shortest path?
It's said A\* guarantees to find the shortest path but I think for certain paths with certain obstacles it won't find the nearest path. My example below is marked (with pink and blue lines) for what I think is the best path.

Maybe I don't know really the problem and its my mistake. Is that really a problem or weakness of A\*? Are there any solutions for this?

im not sure that I think right about A\* but I just in A\* we just have an open list and closed list. in A8 we just care about next step. so in every steo we see for every state with lowest F value and go the that state and put that state to closed list. am I right? its said that A\* uses some back trackings. is that right?

# Answer
> 3 votes
A\* works with a heuristic. Modifying the heuristic changes the outcome for your path. Depending on your needs, your heuristic will need to change to ensure what you define as an optimal path.

Your example shows three different algorithms.

The top left is Dijkstra’s Algorithm, which is mainly based on the number of steps taken from the source.

The top right example shows Greedy Best-First Search, which is mainly based on distance to the target (which can easily lead to non optimal paths).

Finally, the bottom center shows A\*. A\*'s heuristic is a combination of both of the above (steps taken from source and distance to target). This is the optimal path in for this scenario.

There are multiple equally optimal paths in this scenario. Your blue line shows one such example, and A\* found another example. Since this heuristic is only concerned about minimizing the number of steps to reach the goal. Both examples have the same number of steps.

If this scenario allowed for diagonal movement, then your blue line path would indeed be a shorter path.

(For those that want to check out the included examples live, see Amit's site)

---
Tags: path-finding
---


title: Unity strange clones behavior

text:
# Question
Title: Unity strange clones behavior
I am setting up a grid of tiles (2d sprites) in Unity with this code:

```
public class Grid : MonoBehaviour {

public GameObject slot;
public int gridW = 9;
public int gridH = 9;

private GameObject [,] grid = new GameObject[9, 9];

void Awake(){

    for(int y=0; y<gridW; y++)
    {
        for(int x=0; x<gridH; x++)
        {
            GameObject gridSlot = (GameObject)Instantiate(slot, new Vector3(x, y, 0), Quaternion.identity);
            gridSlot.transform.parent = transform;
            grid[x,y]=gridSlot;
        }
    }

}

```

I then would like to have printed on the console the x,y coordinates of an individual tile when clicked on it. This is the script attached to the tile prefab:

```
public class Tile : MonoBehaviour {

void Start () {

}

void Update () {

    if(Input.GetMouseButtonDown(0))
        Debug.Log(transform.position.x + " " + transform.position.y);
}

```

Yet when I click on a tile I get printed the coordinates for ALL of the tiles on the grid. Why is this happening? Is there something very basic I am missing...?

Thanks!

# Answer
> 2 votes
> Yet when I click on a tile I get printed the coordinates for ALL of the tiles on the grid. Why is this happening? Is there something very basic I am missing...?

It appears as though you are spawning one `Tile` for every tile on your map. So an 8x8 map would have 64 `Tile` instances. Every instance is `Update`'d by the Unity runtime. When the mouse is down, every instance checks if `Input.GetMouseButtonDown(0)` is true, and when it is, prints its own position.

So every time you click, every tile prints its position.

You probably want to *either* check if the clicked position is actually within the bounds of the tile (the simplest-possible-solution) or have something else at a higher level, possible the map object, handle the mouse click, determine which tile was clicked, and tell that specific tile to do whatever needs to be done in response to a click.

---
Tags: unity, grid, console
---


# Question
Title: LibGDX: I need to get from SpriteBatch to Batch in order to draw a Touchpad
I have created a little game using LibGDX and it uses a SpriteBatch when it renders the game objects. Now I want to add a Touchpad to it, and the draw method of Touchpad takes a Batch as a parameter, but my game uses SpriteBatch. What can I do?

# Answer
Because `SpriteBatch` implements `Batch` this means it can be used wherever a function requires a `Batch`. So when you call `Touchpad#draw(batch)` you can give it your `SpriteBatch` instance and it will work just fine. You should probably read up on polymorphism in Java.
> 1 votes

---
Tags: android, libgdx, spritebatch
---


# Question
Title: Move to specified coords - libgdx and java
So I am making my bullets go to a point and travel further. Only its acting really really weird. Its like its thinking that the 0,0 location is at the top left instead of the bottom left.

This is the code:

```
float speed = 100;

    Vector2 direction;
    Vector2 thisPos = new Vector2(getX(), getY());
    Vector2 mousePos;

    public Bullet(){
        super();
        setSprite(sprite);
        setX(0); setY(0);
        float dx = Gdx.input.getX() - getX();
        float dy = Gdx.input.getY() - getY();
        mousePos = new Vector2(Gdx.input.getX(), Gdx.input.getY());
        direction = new Vector2(dx, dy);
        //sprite.setRotation(direction.angle(thisPos));
        direction.nor();
    }

    public void update(){
        Vector2 dirAd = new Vector2(direction);
        thisPos.x += dirAd.x * speed * Gdx.graphics.getDeltaTime();
        thisPos.y += dirAd.y * speed * Gdx.graphics.getDeltaTime();
        setPosition(thisPos.x, thisPos.y);
        super.update();
    }

```

I hope someone can help me what I did wrong with this.

# Answer
This is simply because in the screen coordinate system `(0, 0)` *is* the top left corner. This is also called the `y-down` coordinate system.

If you wish to use the standard (y-up) coordinate system you can calculate the corresponding point on the screen by calculating `screenHeight - yPosition`. So on your case you could make your `setY()` method look something like this:

```
public void setY(int y) {
    int newY = Gdx.graphics.getHeight() - y;
    thisPos.y = newY; // Or however you set your position...
}

```
> 1 votes

# Answer
If you wanted to make (0,0) the bottom left an easy way to do this would be to:

setPosition(getGlobalBounds().width, getGlobalBounds().height)
> 0 votes

---
Tags: java, libgdx, vector
---


title: [Unity][C#] Coding Better Camera Recoil

text:
# Question
Title: [Unity][C#] Coding Better Camera Recoil
I am trying to get a good camera recoil system in Unity, but what I have tried so far doesn't seem to look very good. My current method, is using Quaternion.Lerp. With the way I have my shooting system set up, the camera recoil going up all happens within one frame, so when you shoot faster, it tends to look choppy, whereas the recoil going back down is smooth and normal. My question is, is there a better way to handle the camera recoil, while keeping the same look and effect, but having it look much more smooth? I have a quick video to show how the camera recoil looks (watch as the camera moves upwards) https://www.youtube.com/watch?v=HsS0rtoj9l4

And here is the part of my code that handles the camera recoil

```
void Update () {
    Recoil2();

    Vector3 cameraRecoil = weaponSettings.CurrentWeapon.cameraRecoil;
    Transform cameraClimb = generalSettings.cameraClimbHolder.transform;
    string fireMode = weaponSettings.CurrentWeapon.fireMode.ToString();

    if (fireMode == "Semi")
        if (Input.GetButtonDown("Fire1"))
            Shoot();
        else
            CameraRecoil1 = Vector3.Lerp(CameraRecoil1, new Vector3(0, 0, 0), Time.deltaTime * cameraRecoil.z / 10f);

    if (fireMode == "Auto")
        if (Input.GetButton("Fire1"))
            Shoot();
        else
            CameraRecoil1 = Vector3.Lerp(CameraRecoil1, new Vector3(0, 0, 0), Time.deltaTime * cameraRecoil.z / 3f);
}

void Shoot ()
{
    if (shoottime <= Time.time && !isBusy && !isReloading && !isRunning)
    {
        shoottime = Time.time + weaponSettings.CurrentWeapon.fireRate;

        WeaponInfo currentWeapon = weaponSettings.CurrentWeapon;
        Transform cameraClimb = generalSettings.cameraClimbHolder.transform;
        Vector3 cameraRecoil = weaponSettings.CurrentWeapon.cameraRecoil;

        CameraRecoil1 = Vector3.Lerp(CameraRecoil1, new Vector3(-cameraRecoil.x, Random.Range(-cameraRecoil.y, cameraRecoil.y), 0), Time.deltaTime * cameraRecoil.z);
    }
}

void Recoil2 ()
{
    Vector3 cameraRecoil = weaponSettings.CurrentWeapon.cameraRecoil;
    Transform cameraClimb = generalSettings.cameraClimbHolder.transform;

    cameraClimb.localEulerAngles = CameraRecoil1;
}

```

Anyone have any ideas? I appreciate anyone who can help me!

# Answer
> 1 votes
Your use of `Vector3.Lerp` seems out of place. It is intended to find a point along a line as a percentage distance from 0 to 1.

What you may be looking for instead is `Vector3.MoveTowards` or `Vector3.SmoothDamp`.

Also, when initially creating the recoil inside of `Shoot()`, I would assume you'd want to set `CameraRecoil1` to a value independent of its current value, rather than `Lerp`ing (or `MoveTowards`ing) it.

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


title: Playerprefs dont work fine!

text:
# Question
Title: Playerprefs dont work fine!
because it don't work fine! i am pretty sure there is no else problem. also how can i remove playerprefs data in windows? i used Playerprefs.Deleteall(); but it also don't work. is there any problem with this code?

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

public class s1sc : MonoBehaviour {
    int isfirsgamestart = 1;

    //load saved variable in playerprefs
    void Start(){
        isfirsgamestart = PlayerPrefs.GetInt("is player first game?");
    }

    //save variable in playerprefs
    public void _SetInt(){
        PlayerPrefs.SetInt("is player first game?", isfirsgamestart);
    }

    //delete all playerprefs
    public void _delete(){
        PlayerPrefs.DeleteAll ();
    }
}

```

# Answer
> 0 votes
> PlayerPrefs.DeleteAll(); Removes all keys and values from the preferences. Use with caution.

PlayerPrefs.DeleteAll(); work correctly just it work when reset the game(because when reset game load again values)

```
//delete all playerprefs
public void _delete(){
    PlayerPrefs.DeleteAll ();
    Application.LoadLevel (Application.loadedLevel);
}

```

because it just remove keys and values from the preferences,this is mean it delete information so you need load them again

```
//delete all playerprefs
public void _delete(){
    PlayerPrefs.DeleteAll ();
    isfirsgamestart = PlayerPrefs.GetInt("is player first game?");
}

```

another ways:

```
public void _delete(){
    PlayerPrefs.DeleteKey ("is player first game?");//delete key
    isfirsgamestart = 0;//initialize again
    //________OR____________
    PlayerPrefs.SetInt("is player first game?", 0);//set int to zero mean reset
}

```

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


title: Touch to continue (coroutine) in unity

text:
# Question
Title: Touch to continue (coroutine) in unity
When the object gets destroyed in my game, I want a `touch to continue` function after a delay. This is what I tried.

this is the `SceneManager` class which is attached to the `Main Camera`

```
 public bool ttc;
 public void NextLevel()
{
    StartCoroutine(Delay());
}
IEnumerator Delay()
{

    yield return new WaitForSeconds(2);
    print("touch to continue");
    ttc = true;}

```

My Object class:

```
   void OnDestroy()
  {
   Camera.main.GetComponent<SceneManager>().NextLevel();
    if (Camera.main.GetComponent<SceneManager>().ttc == true)
    {
        if (Input.GetKeyDown(KeyCode.V))
        {
            Application.LoadLevel("TheGame2");
        }
    }
}

```

I also tried this:

```
IEnumerator Delay()
{
    yield return new WaitForSeconds(2);
    print("touch to continue");
    if (Input.GetKeyDown(KeyCode.V))
        {
            Application.LoadLevel("TheGame2");
        }
    }

```

*side note: I will change the 'KeyCode.V' to a mouse button later*

# Answer
Do this:

```
IEnumerator Delay()
{
    yield return new WaitForSeconds(2);
    print("touch to continue");
    var pressed = false;
    while(!pressed){
        if (Input.GetKeyDown(KeyCode.V))
        {
            pressed = true;
        }
        yield return null;
    }
    Application.LoadLevel("TheGame2");
}

```
> 0 votes

# Answer
Since you stated you will add a mouse button, I'll add that code here as well.

You would need to attach this to your scene manager

```
public bool IsDestroyed = false;
public bool ActivateGUI = false;

IEnumerator Delay()
{
    yield return new WaitForSeconds(2);
    ActivateGUI = true;
}

void OnGUI() //Button related stuff
{
    if (ActivateGUI)
        if (GUI.Button(new Rect(Screen.width - 10 - 100, Screen.height - 10 - 50, 100, 50), "Press Here"))
            Debug.Log("This repalces the press V code");
}

void Update()
{
    if (IsDestroyed)
    {
        StartCoroutine(Delay());
    }
}

```

The Update funtion is checking every frame if you object is detroyed. The OnGUI stuff is what draw the button.

Your OnDestroy funtion shoul be something similar to this

```
void OnDestroy()
{
    GameObject go = GameObject.Find("GameManager");
    GameManager gm = go.GetComponent<GameManager>();
    gm.IsDestroyed = true;

    Destroy(gameObject);
    Debug.Log("Object destroid");
}

```

I have read on the Unity forums that the GameObject.Find it is a really slow funtion, so caution is advised.

Hope this helps.
> 0 votes

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


# Question
Title: Game engine + editor + gameplay dependency
I've tried to find my answer here but the other "similar topics" were different or just wasn't able to find the right one.

This is mainly a design (and some c++) question about the dependency between the different projects. Let me describe my problem:

So I've already used Unity and UE4 and I like the approach(es) they're using. They have a (game) engine an editor application and a user-created gameplay code. You can use your own gameplay code in the editor - you can assign scripts to objects, run/pause/step/stop (and debug!) the actual game in the editor.

I've checked the UE4 source code (which is actually pretty big) and the way this works is they're using custom build and preprocess tools (like Unreal Header Tool) and they've implemented everything they're using. As I could see, they're not using any STL class/function, they've implemented their own. This way they can make the "engine project" shareable, so they can build the libraries to dlls and that's it.

I'm using the same component-based approach. Different components can be attached to an object, and an important component base class is the Behavior. The "gameplay components" inherits from the Behavior base class.

So back to the problem: I (will) have 3 different projects:

* Engine
* Gameplay
* Editor

The Engine is the core, that is a static library with every required thing except the game-specific code, of course. The Gameplay depends on the Engine and is built as an executable (\*.exe). This contains the actual gameplay code while using the engine.

And here comes the real problem: the Editor depends on both the Engine and the Gameplay projects. Why? The Editor is using the Engine to create the window, draw buttons, log messages, etc. However it would be nice to be able to assign the "scripts" (in the terms of Unity) to objects and that would be the best if I could "play the game" in the editor, like in Unity.

Why is this a problem at all? Because I'm not able to use a shared library for the Engine project. Why? Because I should dll-export a lot of things which is not even possible while using the STL. It's a known "fact" that most of the STL objects cannot be used with dll-export (and I should write a lot of export code now, heheh). Also I don't want to use any bigger library like Boost or Qt.

However if I'm using static library for the Engine project then the Editor and the Gameplay will have its "own copy" of the Engine.

Maybe a half-solution could be the following: I could have a 4th project for the gameplay code exports which would be a dll. This project should only contain some functions which would be used in the Editor - eg. query the list of the available scripts with the visible variables, etc. However the game code is not actually available in the editor, so any "play in the editor" wouldn't be possible.

# Answer
I think you are overcomplicating and over-engineering your solution, and I think it comes down to some misconceptions you have about what Unreal is doing and why:

The problem with passing objects across DLL boundaries is *not* a problem with passing STL objects across DLL boundaries. It's passing *any C++ type* across DLL boundaries; C++ doesn't have a standard ABI, so any two compilers or even the same compiler with different settings can result in binary incompatibilities between DLLs.

Unreal does *not* solve this problem. It simply expects that you will not be mixing and matching DLLs built with different tools and with different settings. It builds everything on the same tools with the same settings, which means the lack of a standard ABI isn't a problem because they all still end up using the *same* ABI.

It also does not produce separate executables from separate projects for the game and the editor. The executable is one project, and there are several project configurations that build either an editor executable (which is the game plus the editor stuff) or a standalone executable (which is just the game with all the editor stuff compiled out).

Unreal splits a lot of stuff up into DLLs because of its module paradigm (and there *are* editor-only module DLLs) which enforces type access and enables hot-reload of C++ code. That's all rather advanced stuff and likely overkill for your project.

---

If you want to implement the Unreal paradigm, this is the direction you should take: one engine library, one executable, using the preprocessor to compile-out editor functionality for the standalone build configurations (look at all the `#if WITH_EDITOR`... blocks in Unreal).

Strictly speaking, you don't even need to bother with a DLL and the worry of potential ABI mismatching. Since you just have one executable, linking a static library containing the engine code is just fine. In fact you wouldn't have to deal with a library *at all* (although it can be nice to do so to really force a separation between engine and gameplay code).
> 5 votes

---
Tags: c++, architecture
---


# Question
Title: D3DXLoadSurfaceFromResource failed to load bitmap image
I'm working on a small DX9 game project for learning purpose. I'm current dealing with resources manager file (\*.rc) which I'm not used to (I have only worked with direct file until now).
If I use `D3DXLoadSurfaceFromFile`, it worked fine, the image was drawn on windows. When I changed to `D3DXLoadSurfaceFromResource`, I think it can not load the image, only a black screen & the `Hresult` that it returns is `S_FALSE`.

This is the create surface function :

```
bool Surface::CreateSurface()
{
    if (FAILED(m_Device->CreateOffscreenPlainSurface(
        m_Width,
        m_Height,
        D3DFMT_X8R8G8B8,
        D3DPOOL_DEFAULT,
        &m_Surface,
        NULL
    )))
        return false;

    if (FAILED(D3DXLoadSurfaceFromResource(
        m_Surface,
        NULL,
        NULL,
        GetModuleHandle(NULL),
        MAKEINTRESOURCE(m_RsSymbol),
        NULL,
        D3DX_DEFAULT,
        0,
        NULL
    )))
        return false; // S_FALSE and return false while debug
    return true;
}

```

This the render function :

```
void GWindow::Render()
{
    Surface Hello_Brown(146, 146, m_lpD3DV, IDB_SAMPLE); // IDB_SAMPLP will be assigned to m_RsSymbol
    LPDIRECT3DSURFACE9 backbuffer;
    if (NULL == m_lpD3DV)
        return;

    m_lpD3DV->Clear(0, NULL, D3DCLEAR_TARGET, D3DCOLOR_XRGB(0, 0, 255), 1.0f, 0);

    m_lpD3DV->GetBackBuffer(
        0,
        0,
        D3DBACKBUFFER_TYPE_MONO,
        &backbuffer
    );

    m_lpD3DV->StretchRect(
        Hello_Brown.GetSurface(),
        NULL,
        backbuffer,
        NULL,
        D3DTEXF_NONE
    );

    m_lpD3DV->Present(NULL, NULL, NULL, NULL);
}

```

Where I am wrong and how do I fix it?

Resource file : link

I linked the file above, because it too long to post here.

# Answer
This is failing because the resources in your .rc are of the wrong type. See the documentation for D3DXLoadSurfaceFromResource:

> The resource being loaded must be of type RT\_BITMAP or RT\_RCDATA. Resource type RT\_RCDATA is used to load formats other than bitmaps (such as .tga, .jpg, and .dds).

Your incorrect entry:

```
IDB_MARIO               PNG                     "Resouce Files\\Images\\Mario.png"

```

And the correct equivalent:

```
IDB_MARIO               RCDATA                  "Resouce Files\\Images\\Mario.png"

```

By convention a resource of type RCDATA also has it's name prefixed with IDR\_ rather than IDB\_ (or anything else), but since this is just a #define in your resource.h it most likely doesn't matter.
> 0 votes

---
Tags: c++, directx9
---


title: DX11 Clear Issue, Irregular pattern

text:
# Question
Title: DX11 Clear Issue, Irregular pattern
So far I've put together a bare minimum of a DirectX 11 application. All it does is clear the window to a random shade of red.

```
const FLOAT clearColor[4] = { rand() / (float) RAND_MAX, 0.0F, 0.0F, 1.0F };

context->ClearRenderTargetView(renderTargetView.Get(), clearColor);
context->ClearDepthStencilView(depthStencilView.Get(), D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, 1.0F, 0.0F);

swapChain->Present(0, 0);

```

What I get however is a constant flickering (sort of like z-fighting, but apparently not).

If I enter fullscreen by pressing Alt + Enter, and then leave, this problem is solved, it no longer flickers in any way. What settings does alt + enter end up changing?

**What could cause this?** I don't want to continue and find out this becomes an issue later. I'll update the question with code on request.

*Secondary question*: In fullscreen mode, there's a lot of flickering in horizontal bars, yet images only capture a single colour at once. Is this normal, some illusion, or also avoidable?

Update: When using "swapChain-\>Present(1, 0);" the original flickering still occurs (Seemingly less severely), but no longer in fullscreen mode.

# Answer
> 1 votes
It turns out that it's been an unknown local issue. After resuming the project later with no changes, other than restarting and Windows updates, I'm not having this issue anymore. The Windows 10 Anniversary Update (intrusively) did revert a lot of settings to default however and this may have impacted it.

# Answer
> 0 votes
This isn't Z-fighting, it's screen-tearing.

Z-fighting, by definition, cannot occur with your code:

> ...a phenomenon in 3D rendering that occurs when two or more primitives have similar or identical values in the z-buffer.

You don't even have any primitives and your Z-buffer is just set to a single constant value, so Z-fighting is impossible. Both your main problem, and that observed in your secondary question, are simple screen-tearing.

Pressing Alt-Enter to go fullscreen resolves it because you most likely have not called IDXGIFactory::MakeWindowAssociation to disable automatic DXGI handling of this transition. So DXGI itself is stepping in and changing to a valid fullscreen mode with vsync forced on, which will prevent screen-tearing.

Calling Present(1,0) yourself doesn't fully resolve it because you most likely have your swapchain initialized to an invalid refresh rate. Typically this happens when you specify a refresh rate of 60Hz but your monitor's *real* refresh rate is actually slightly different (maybe 59.95 or something similar). The way to resolve this is to enumerate your display modes properly using IDXGIOutput::GetDisplayModeList and use one of those enumerated modes for the DXGI\_MODE\_DESC member of your DXGI\_SWAP\_CHAIN\_DESC. Pay particular attention to the Numerator and Denominator members of DXGI\_MODE\_DESC::RefreshRate to understand the difference: this happens more commonly than you might think.

---
Tags: directx11, graphics-programming, depth-buffer
---


title: Structure of server on MMO mobile game

text:
# Question
Title: Structure of server on MMO mobile game
I'm working on Unity and I use node for my serverside.

I'm starting a multiplayer project on mobile. I'm searching for a good structure for my game that how server controls the events. For example my players do some requests like upgrades and... simply my server receives those requests and after validation saves them in database and... but in some parts 2 player should start the game and get sync to play the game. in that part a copy of game for server should run to calculate ingames parts and respond to player requests like move inputs and...

The problem is should my server for every game for 2 players run a copy of game and send and receive data with socket from that copy to run the game or there is other ways to do that?

# Answer
> 1 votes
Conceptually, you need only one server. In practice, for scalability, you may want to split this "one server" in many server processes, possibly on different machines, to distribute load... but that need is far into the future and you should worry about it when you get there. Not now.

So, what you need is one server. That server, in the context of your question, will have two jobs:

* to transmit updates to the game state to all connected clients
* to replicate the current game state entirely to any newly-connecting clients

That means that as the server gets requests from clients and processes them, it updates the game state and tells any clients about those updates (if it matters to the client).

Similarly, when a new client connects, the server sends it information about whatever the *current* state of the game is, at least as far as what matters to the client. It's quite possible for one logical server to do and in fact it is somewhat easier to work with as that one server has all the state, makes all the decisions, and knows about all the clients. That means there is no server-to-server state replication to worry about, no additional layer of complexity introduced by run N copies of the game *on* the server for *N* clients, like you were suggesting in your question.

Just use one server, have it sends relevant updates to connected clients, and relevant complete state for new clients.

(I keep saying "relevant" and "what matters to the client" because you only want to tell the client about things it should know about; don't tell it about things that it can't yet see, for example, because that enables client-side "map hacks" and the like.)

---
Tags: unity, multiplayer, mmo
---


# Question
Title: Scene2d scrollbar not showing even though it exists in uiskin.json/atlas
Using `uiskin.json, uiskin.png, uiskin.atlas, default.fnt` from libgdx tests I'm trying to make a console window, however the scroll bar is not shown. uiskin atlas contains a two relevat fragments:

```
default-scroll
  rotate: false
  xy: 78, 29
  size: 20, 20
  split: 2, 2, 2, 2
  orig: 20, 20
  offset: 0, 0
  index: -1
default-round-large
  rotate: false
  xy: 57, 29
  size: 20, 20
  split: 5, 5, 5, 4
  orig: 20, 20
  offset: 0, 0
  index: -1

```

Which are referenced in uiskin.json

```
com.badlogic.gdx.scenes.scene2d.ui.ScrollPane$ScrollPaneStyle: {
    default: { vScroll: default-scroll, hScrollKnob: default-round-large, background: default-rect, hScroll: default-scroll, vScrollKnob: default-round-large }
}

```

And this is my console window:

```
//Skin is above mentioned uiskin.json, png, atlas
Window window = new Window("CONSOLE", skin);
window.padTop(20f);
window.setWidth(500f);
window.setHeight(250f);
window.setMovable(true);
window.setModal(true);
window.setResizable(true);
window.defaults().expand().fill();

Label consoleLog = new Label("TEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXT" +
                             "TEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXT" +
                             "TEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXT" +
                             "TEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXT" +
                             "TEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXT" +
                             "TEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXT" +
                             "TEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXT" +
                             "TEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXT" +
                             "TEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXT" +
                             "TEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXT", skin)

consoleLog.setWrap(true);
ScrollPane scrollPane = new ScrollPane(consoleLog);
window.add(scrollPane);
window.row();
window.add(new TextField("", skin));

```

When I run this, I get a window with a label and a textfield, and I can scroll the label using mouse scroll or by dragging the text, but the scrollbar is not visible.

what am I doing wrong?

# Answer
> 3 votes
The cause of this problem is actually the way I constructed the `ScrollPane` object. I called the `ScrollPane(widget)` constructor without providing the skin which constructs the `ScollPane` like this:

```
public ScrollPane (Actor widget) {
    this(widget, new ScrollPaneStyle());
}

```

this basically means that for styling the `ScrollPane` it uses an empty `ScrollPaneStyle` which, among other things, doesn't have any images set for scrollbars.

So to fix that I just added the missing skin reference while constructing the `ScrollPane`.

```
ScrollPane scrollPane = new ScrollPane(consoleLog, skin);

```

And now the scrollbar displays properly.

---
Tags: libgdx, scene2d, scrolling
---


title: Java Graphics - big images slowing down

text:
# Question
Title: Java Graphics - big images slowing down
I'm working on a little game for learning purposes so please don't recommend me to use any library like libgdx or slickutils.

I have just one simple question. Does rendering bigger images with `Graphits.drawImage();` slow the Process down?

I'm currently drawing about 200 little Objects (PNG, 64x64 resized to 48x48), but they don't seem to be an issue (i know resizing them each frame is not very performant).

The game slows down as soon as I draw the background with a parallax effect (several layers and at least 3 seamless fitting objects per layer).

They Art drawn in their original size 900x900 Pixel. But they keep slowing the game down. It's only the `graphisch.drawImage();` Part. The Rest of the calculation doesn't seem to affect the game at all.

I store all Images I need once when starting the game in a class called Resources in BufferedImages.

I hope someone can explain this to me.

# Answer
> 1 votes
I haven't seen your code, but likely it may be that you should render the background separately and only update it when it changes, not on every frame.

Check out this related q&a on stack overflow, it discusses performance issues with Graphics2D. The code in that answer renders the background separately. It also mentions using a BufferStrategy.

---
Tags: java, graphics, performance
---


# Question
Title: How AI is balanced across different type of races in RTS games?
There are some real-time strategy games (like StarCraft 1 or 2) where AI needs to be balanced across different type of races (in SC it's Protoss, Terran, Zerg), so despite they've different type of troops to play, no specific type of opponent have any advantage. Not to mention that they need to consider different type of maps, so in overall each AI playing different race have the same changes of win.

How in general this balance can be achieved by gaming companies? Is it just by playing massive amount of games headlessly with different setups?

---

This study and this one plus this dataset may help answering it, but it could be not related.

# Answer
Common ways to balance RTS AIs:

1. Have all races be the same but with a different "coat of paint" on each races.
2. Have the races be different but make sure each unit has an exact counter in each other race (rock-paper-scissor)
3. Have the AI cheat
4. Don't balance them (You get to beat some races AIs quickly while others take more practice.)

Some of the different way AIs are programmed to cheat to increase the difficulty:

* No fog of war for them
* They know what you are producing so they build the counters as soon as you start your own production
* They start with more resources
* They collect resources faster
* All AI races ally against you
* They can micro-manage better than any human can, adjusting the micro-management latency to adjust AI difficulty.

There usually will be the regular amount of play testing in which the races might be tweaked but overall it does not matter if the player always wins against one race: If the player wants a higher challenge then the player can pick a different race as it's opponent.

It is also very difficult to know during testing if one race is weak or if the player playing style in the case study sample just happen to be good against that AI race.

In the case of E-Sports RTS games there is usually no AI in matches and companies do not divulge their tweaking methodologies but from my observations the races get tweaked to make the E-Sport broadcasts more interesting, keeping the ratings up. With less focus on the player-vs-AI experience since the big money is in the PvP experience.

Often using a combination of in-depth analytics to know `what to adjust` and trial-and-error for `how much to adjust`.
> 3 votes

---
Tags: ai, starcraft-2
---


# Question
Title: Use of FlxG.camera.follow to follow a character vertically
I am developing a prototype for a game in Flixel in which a character floats upward continually to traverse the level. I would like to have a "tall" layout for levels and set the FlxG.camera to follow the character as he floats upward. My issue is in understanding the proper use of FlxG.camera. I have my game constructor coded as follows:

```
package
{
    import flash.display.Sprite;
    import org.flixel.*;

    [SWF(width="640",height="480",backgroundColor="#000000")]
    public class MyGame extends FlxGame
    {
        public function MyGame()
        {
            super(320,240,PlayState,2);
            forceDebugger = true;
        }
    }
}

```

In the override of create() in the PlayState.as file I attempt to set the camera to follow the player as follows:

```
public var TheClimber:BalloonHero;

        override public function create():void
        {
            /*set background color*/
            FlxG.bgColor = FlxG.BLUE;

            /*Set data for player*/
            TheClimber = new BalloonHero(FlxG.width/2-5,480);

            /*Add camera and set it to follow The Climber*/
        //which will automatically set the boundaries of the world.
        FlxG.camera.setBounds(0,1280,640,1280,true);
        FlxG.camera.follow(TheClimber,FlxCamera.STYLE_PLATFORMER);

            /*add player to the game*/
            add(TheClimber);
        }

```

I assumed this would set the camera bounds to twice the height of the SWF background(i.e. the FlxG height) and then scroll the background along with the specified FlxObject(TheClimber in this case) until it had reached the height of the game. However, I must be going about it incorrectly because when the zoom is 2 and the game height 720 the camera starts at the top of the screen with the player character not visible at the bottom of the game height. Is there a way to start with the camera/game focused on the bottom of the game object(FlxG.height) ? Or am I going about this the wrong way and have other issues with the way I am using the camera? Thanks in advance.

# Answer
> 2 votes
You don't set the world size with:

```
public function MyGame()
{
    super(320,720,PlayState,2);
}

```

That is setting the size of the screen Flixel will draw onto. If you want a zoom level of 2 you should have `super(320, 240, PlayState, 2)`.

You should check out the source for Mode to see how to create a world larger than the screen. What happens in Mode is that the world size is set to 640x640 and the player, blocks and enemies are added in that world space.

The create() and generateLevel() methods are where most of this happens.

# Answer
> 0 votes
I don't know if you've gotten your answer im quite new to flixel and as3 myself , but ill tell you what i have i got my code open right now .. I see i put FlxG.camera.follow(player, FlxCamera.STYLE\_PLATFORMER); FlxG.camera.setBounds(0, 0, map.width - 16, map.height); FlxG.worldBounds = new FlxRect(0, 0, map.width - 16, map.height); Background.scrollFactor = new FlxPoint();

These are the codee for my camera .. The scroll factor is so the background doesnt leave the screen when you move the world bounds is so your player doesnt fall through the floor when he goes to far and the camera.setbounds is so the camera doesnt go off screen this is what i just learned about yesterday so im not a professional or anything. . you should use the flixel tutorial on newgrounds its sort of like playing a game when you learn it but it helps alot

---
Tags: flash, actionscript-3, camera, flixel
---


title: How does code translate to graphics?

text:
# Question
Title: How does code translate to graphics?
I know this is kind of a basic question, but I'm trying to create my own game from scratch and really don't understand this. How does the code of a videogame program certain pixels to be certain colors and then move them in agreement with the player's movement?

For example, in a 2D platformer, how does the code program the on-screen visuals of the world that the player is in? And then, how does it move a certain object matching the speed of the player and then eventually have it go off screen?

Thanks in advance!!

# Answer
> 2 votes
I think you need to start with: How is anything drawn to the screen -- text, windows, shapes, sprites, etc.? A very simple answer is people have written code that makes basic 'drawing' happen and then other people have written methods/functions/code to use those drawing functions to do things like animate a character on screen.

I would try creating some 'non-game' programs first before trying to produce even a simple game (a non-trivial task). This will teach you the basics of things like rendering. Then you can move on to create games.

---
Tags: graphics, software-engineering, game-mechanics, graphics-programming
---


# Question
Title: Getting Sprites from a SpriteSheet with Rows and Columns
I am having trouble reading a spritesheet with rows and columns. If it is just one row, then my code works fine. The sheet looks like this:

Source: Character animations, clothes, armor, weapons, skeleton enemy, combat dummy

Right now, it only works with the first row. I can't figure out how to move it down to the next row. I know I have to change my `SourceRect` for the `x` and `y` but don't know to what.

Here's my code:

```
class SpriteSheet
{
    public Texture2D Texture { get; set; }
    public Vector2 Origin { get; set; }
    public Rectangle SourceRect { get; set; }
    public Vector2 position;

    private float timer, interval;
    private int currentFrame;
    private int spriteWidth, spriteHeight, spriteSpeed;
    private int rows, columns;
    private KeyboardState currentKBState, previousKBState;

    public SpriteSheet(Texture2D texture, int spriteWidth, int spriteHeight, int rows = 1, int columns = 0, int currentFrame = 1)
    {
        Texture = texture;
        this.currentFrame = currentFrame;
        this.spriteWidth = spriteWidth;
        this.spriteHeight = spriteHeight;
        this.rows = rows;
        this.columns = columns;

        spriteSpeed = 100;
        interval = 200;
    }

    // Handle movement of sprite
    public void Update(GameTime gameTime)
    {
        previousKBState = currentKBState;
        currentKBState = Keyboard.GetState();

        // Get the sprite from the sheet
        // THIS LINE NEEDS TO BE CHANGED I THINK
        SourceRect = new Rectangle(currentFrame * spriteWidth, 0, spriteWidth, spriteHeight);

        if(currentKBState.GetPressedKeys().Length == 0)
        {
            if (currentFrame > 0 && currentFrame < 9)
                currentFrame = 0;

            if (currentFrame > 9 && currentFrame < 18)
                currentFrame = 9;

            if (currentFrame > 18 && currentFrame < 27)
                currentFrame = 18;

            if (currentFrame > 27 && currentFrame < 36)
                currentFrame = 27;
        }

        // Animate Up
        if (currentKBState.IsKeyDown(Keys.Up))
        {
            AnimateUp(gameTime);

            // Check boundary
            if (position.Y > 25)
                position.Y -= (float) (spriteSpeed * gameTime.ElapsedGameTime.TotalSeconds);
        }
    }

    private void AnimateUp(GameTime gameTime)
    {
        if (currentKBState != previousKBState)
            currentFrame = 1;

        timer += (float)gameTime.ElapsedGameTime.TotalMilliseconds;

        if(timer > interval)
        {
            currentFrame++;
            if (currentFrame > 8)
                currentFrame = 0;

            timer = 0f;
        }
    }
}

```

# Answer
Your y-coordinate is always 0, so only the first row is used. You need to change this line:

```
SourceRect = new Rectangle(currentFrame * spriteWidth, 0, spriteWidth, spriteHeight);

```

into something like this (see the second parameter):

```
SourceRect = new Rectangle(currentFrame * spriteWidth, wantedRow * spriteHeight, spriteWidth, spriteHeight);

```
> 3 votes

# Answer
So I changed up the code a bit to make it work:

Constructor change:

```
public SpriteSheet(Texture2D texture, int rows = 1, int columns = 0, int currentFrame = 0)
{
    this.texture = texture;
    this.sheetRows = rows;
    this.sheetColumns = columns;

    // Default = top left
    this.currentFrame = currentFrame;

    // Get a single sprite's width and height
    sheetWidth = texture.Width / sheetColumns;
    sheetHeight = texture.Height / sheetRows;
}

```

I noticed I didn't have to manually supply the `width` and `height` of the sprite and I could just get it from the sprite sheet. I handle the `spriteSpeed` and `interval` in my movement methods instead of the constructor now.

I removed the `SourceRect` line from the `Update` method and moved it to a custom `Draw` method:

```
public void Draw(SpriteBatch spriteBatch)
{
    // Get the correct frame
    spriteRow = currentFrame / sheetColumns;
    spriteColumn = currentFrame % sheetColumns;

    sourceRect = new Rectangle(sheetWidth * spriteColumn, sheetHeight * spriteRow, sheetWidth, sheetHeight);
    origin = new Vector2(sourceRect.Width / 2, sourceRect.Height / 2);

    spriteBatch.Draw(texture: texture, sourceRectangle: sourceRect, position: position, origin: origin, scale: new Vector2(1.0f));
}

```

Finally, getting the `row` and `column` of the sprite became easier with a little division.

If I wanted `row 3` and `column 1`, the `currentFrame` would be `18`. Knowing this, it was pretty straightforward to fix the part of the code where I reset the `currentFrame` where no keys are pressed.
> 0 votes

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


title: Color mapping of difference

text:
# Question
Title: Color mapping of difference
I have two arrays `A` and `B`. I want to do color mapping of their difference `A - B`. So far, I am doing this:

```
1) calculate d = A - B
2) find min / max in d
3) linear mapping of d from (min, max) to (0, 1)
4) convert (0, 1) to color

```

The problem is, that sometimes, there are noise values in my data. For example, several values in `B` are too large (like 100 times bigger than the rest) and it leads to enormous difference and increased `min` or `max`. After mapping to (0, 1) all other values are "wiped". How can I solve this?

# Answer
I would suggest two options:

1. use percentile instead of min/max (e.g. 95/5%, you need to experiment here), with linear mapping clamped to (0,1) range. To do so sort the `d` array and pick `(N - 1) * percentile + 1`th member as minimum/maximum, map as normal and clamp `r = Min(1.0, Max(0.0, r))` the results in (0,1) range
2. Use non linear mapping, for example the logarithmic scale is often used in scientific applications `d = log (d)`

The option 1 attempts to filter the data from erroneous values rather than displaying them, the quality heavily relies on on percentile settings, which is (input)data-dependent. The option 2 tries to use non-linear mapping in order to display meaningful values even for erroneous data, but requires users to understand logarithmic scale.
> 2 votes

---
Tags: color
---


# Question
Title: Unity - Pass an instance of an object to another
I am using Unity. I created a `Background` class and a `Cube` class which are empty. Also I have a `GameEngine` class.

I have a 5x5 background prefabs on the game screen. I want every background to have a cube object. So I wrote `public Background b;` in `Cube` class.

GameEngine

```
using UnityEngine;
using System.Collections;

public class GameEngine : MonoBehaviour {

    public GameObject backgroundPrefab;
    public GameObject CubePrefab;

    public int X = 5, Y = 5;

    void Start () {
        Background b;
        Cube c;

        for (int i = 0; i < X; i++)
            for (int j = 0; j < Y; j++) {
                Vector3 pos = new Vector3(backgroundPrefab.transform.localScale.x * (i - (X - 1) / 2f), 0, backgroundPrefab.transform.localScale.z * (j - (Y - 1) / 2f));
                b = Instantiate(backgroundPrefab, pos, Quaternion.identity) as Background;
                c = Instantiate(CubePrefab, pos, Quaternion.identity) as Cube;
                //c.b = b;
            }
    }

    void Update () {

    }
}

```

It works like that but when I uncomment that line, it gives me that:

```
NullReferenceException: Object reference not set to an instance of an object
GameEngine.Start () (at Assets/Scripts/GameEngine.cs:20)

```

How can I attach every cube object to the background objects? And why is this not working? Isn't `b` is an instance of `Background`?

# Answer
It looks like the problem might be that you're trying to cast the results of Instantiate to a Background and Cube, respectively. The "as" keyword in C# will return null if the requested cast is not appropriate. Double-check what type Instantiate returns...

Even though you defined "Background" and "Cube" classes, you probably made them as script components of their respective GameObject prefabs. Instantiate probably returns GameObjects and GameObjects != script component classes. Script component classes are subclasses of MonoBehavior (or something like that), and those instances need to be accessed by the GetComponent method of the GameObject.

edit: Ya see, check this out, looks like you want this:

> After cloning an object you can also use GetComponent to set properties on a specific component attached to the cloned object.
>
> ```
> using UnityEngine;
>
> public class InstantiateComponentExample : MonoBehaviour
> {
>     // Instantiate a prefab with an attached Missile script
>     public Missile missilePrefab;
>
>     void Start()
>     {
>         // Instantiate the missile at the position and rotation of this object's transform
>         Missile clone = (Missile)Instantiate(missilePrefab, transform.position, transform.rotation);
>     }
> }
>
> ```
>
> (see http://docs.unity3d.com/ScriptReference/Object.Instantiate.html)

Conceptually, if every Cube is supposed to have a Background, then can you just create a GameObject that has the Background and Cube already together and make that combo GameObject into a prefab?
> 0 votes

# Answer
*OP please clarify what I commented in my answer. This answer has wrong details I'd like to clarify before fixing it.*

With respect to the written code, although having a GameObject variable out there, it is not a priori linked to anything.

*If you have done more steps related to this answer, then please notify and I adapt it. For what I know right now, it seems these steps are missing.*

You declared your public variables:

```
public GameObject backgroundPrefab;
public GameObject CubePrefab;

```

In the properties editor: You will select your object and add your `GameEngine` component (or select your object already having such custom component you created). You will see a slot named `backgroundPrefab`, with a combobox. Set the appropriate value from the combobox, which will be an already-instantiated object to prototype from (prefabs also count to this respect). This also applies to `CubePrefab`.

Just after you did that, the `CubePrefab` public variable will hold a value other than `null`, and you will be able to clone it. Otherwise you are getting just null as well, and then sentences like `c.b = b` explode appropriately.

**Please note**: `Initialize` does not support setting custom values to the properties in the behaviors. If using code instead of the editor, you will do like this:

```
using UnityEngine;
using System.Collections;

public class GameEngine : MonoBehaviour {

    public GameObject backgroundPrefab { get; private set; };
    public GameObject cubePrefab { get; private set; };
    public Background b { get; private set; };
    public Cube c { get; private set; };
    public int X = 5 { get; private set; };
    public Y = 5 { get; private set; };

    void InitializeWholeData(GameObject backgroundPrefab, GameObject cubePrefab, int X, int Y) {
        this.backgroundPrefab;
        this.cubePrefab;
        this.X = X;
        this.Y = Y;
        for (int i = 0; i < X; i++) {
            for (int j = 0; j < Y; j++) {
                Vector3 pos = new Vector3(backgroundPrefab.transform.localScale.x * (i - (X - 1) / 2f), 0, backgroundPrefab.transform.localScale.z * (j - (Y - 1) / 2f));
                this.b = Instantiate(backgroundPrefab, pos, Quaternion.identity) as Background;
                this.c = Instantiate(CubePrefab, pos, Quaternion.identity) as Cube;
                this.c.b = this.b;
            }
        }
    }
}

```

*This code is untested*

Then you create, somewhere else, your object like this:

```
GameObject foo = new GameObject("foo");
foo.AddComponent<GameEngine>().InitializeWholeData(aBackgroundPrefab, aCubePrefab, 10, 10);

```
> -1 votes

---
Tags: unity
---


# Question
Title: Approximating particles with with nebula
I have a 2d galaxy where each star is rendered a particle:

I'd like to approximate it with nebula, so that instead of seeing lots of tiny dots from afar, users will see lots smooth light in the area. Something like this:

I'm more interested in technology-agnostic solution which accurately resembles underlying particles. E.g. how would one approach this problem from math/physics standpoint?

But if you have hints how to do it in a specific technology - those are welcome too! I don't even know how to approach it. The final thing is implemented with WebGL.

# Answer
> 2 votes
To get something decent I think would be pretty easy.

1. Render your particles in the general pattern of nebula, make them very bright.
2. Add perlin noise or similar.
3. Add some very bright areas here and there to represent large stars.
4. Apply bloom and hdr.
5. Consider adding doing the same on a smaller scale and using it to occlude a few areas to represent darker areas.
6. Save results in a texture (your nebula is not going to change over time right?)

I am sure you could take it a lot further than that but it would probably require experimentation. The nice thing with problems like this is you can process as much as you want because it's an offline problem really.

# Answer
> 2 votes
From a physics standpoint you would first need to choose which kind of nebula you want. Now, it looks like you actually want a galaxy, which is a different kind of object. From there we get three kinds of light:

> When we look at a galaxy, the light we see comes from two sources. First, we see light from its billions of stars; since most galaxies are so far away, we don't see individual stars - just the combined diffuse light of all. Second, we see fluorescent light emitted by gas ionized by hot, luminous stars. These glowing gas clouds mark the sites of newly born stars - they often look like beads stringing the arms of spiral galaxies. The light from both stars and gas is dimmed to some extent by dust within the galaxy's interstellar medium.

http://skyserver.sdss.org/dr1/en/astro/galaxies/galaxies.asp

So, to get an "exact" physical solution, you would:

1. Create an enormous amount of stars with varying levels of light emission using some reasonable distribution.
2. And add a gas cloud which gives off a certain amount of light per unit volume - possibly connected to the stars in two ways (being "lit" by stars and being concentrated around stars)
3. And then finally add a fog-like effect that dims and softens both kinds of light. It should be "volumetric" (not as some sort of layer above).

In practice this is probably not feasible.

If you're definitely using 2d, then I would just make the first 2 steps in a number of layers, and then dimming them out wrt to z. The gas could possibly be done using perlin noise as Lunquil suggest, but I think you should have a model that lets the stars and the gas cloud interact to make it look more natural.

Maybe using some caustics or some reaction-diffusion system.

https://en.wikipedia.org/wiki/Reaction%E2%80%93diffusion\_system

# Answer
> 1 votes
> I'm more interested in technology-agnostic solution which accurately resembles underlying particles. E.g. how would one approach this problem from math/physics standpoint?

The issue with the math/physics solution is that given the sheer scale of astronomical quantities it is wholly impractical to go the "fully accurate" route.

The reason that a nebula appears to be a solid glowing thing isn't that there are a bunch of stars and gasses very close together; it's that each individual glowing star and piece of gas is far enough away from us that we cannot resolve the individual pieces -- given their distance from us, they are so close together that the angle between adjacent points is small enough such that our eyes can literally not differentiate between different stars or heated gasses in the nebula (Look up the Rayleigh criterion if interested).

Furthermore, the propagation of light from a nebula, or more accurately from anything, follows what is known as the "inverse-square law:" the intensity of the light changes in inverse proportion to the square of the distance from the source. So, doubling the distance between you and a light source would quarter the intensity of light hitting you. Perhaps slightly less important for a computer game, but the result is that brighter parts of the nebula may not end up looking that much brighter than other parts (but of course, it depends on the actual brightness values involved).

And the actual frequencies of light which we can see are a product of black-body radiation. In simple words, the wavelengths of light emitted by a light source depend upon the temperature of said light source. And to make things even more complicated, the dopper effect, which applies to sound, light and other electromagnetic radiation, specifies that any relative movement between us and the observed light source can shift the frequency/color of light we observe towards either red (moving apart) or blue (moving closer), phenomenons called "redshift" and "blueshift" (Scientists are so creative at naming things!)

And that's not even getting into the formation & structure of your galaxy or nebula in the first place!

Replicating such accurate behavior in a computer program would be a rather daunting effort: the creation and simulation of many, many individual particles (stars), with a distribution of distances and temperatures, and then determine accordingly how a layer of gas around the stars would be heated and which frequencies of light it would emit at various spots. And that's all before you can even attempt to figure out how to draw it.

If you want to go that route, good luck. If at all possible I'd recommend doing the calculations and rendering offline and then just use a selection of pre-made images for your final game.

Still reading? Don't want to try to do this completely from a math/physics viewpoint? I don't blame you.

Anyways, my suggestion for how to do this in a somewhat reasonable way without too much pain:

1. Start off by assigning each of your star-particles a color and brightness (probably via some distribution function)
2. Add a bit of glow around each point according to its brightness and color. Individual stars would probably still be somewhat visible at this point, but the space between stars shouldn't be too much darker.
3. If you want more uniformity of light, take the entire thing and blur it a bit more so that it, on average, looks about the same brightness. Ideally there would still be some bright spots, but not too many.

Optional -- Overlay some darker "clouds" to simulate masses of gas obscuring or blocking the light behind.

Essentially, take your point-lights and blur them together until it looks okay. It might not be perfect, but if done properly I don't think it would look too bad. (I'd try to make an example picture for you, but I'm not great at Photoshop)

# Answer
> 1 votes
This is probably the stupidest solution that you're going to see for all of the answers. But just here me out on this.

Have you thought about building a mesh out of the particle points, and interpolate vertex colors across them? This seems weird at first to think about... but this has actually worked when it comes to making resolution independent lens flares.

https://simonschreibt.de/gat/xrebirth-geometric-lensflares/

This also works great for keeping art looking nice too.

https://simonschreibt.de/gat/homeworld-2-backgrounds-tech/

What you would do is create some set of rules that would define the vertex color of the particles in relations to space before the simulation begins. As you do that, you'd build the mesh. Once it's done, you just scale it outwards.

To give a bit more volume to it, you can run sprite particles along the surface of certain portions of the mesh to give it that lit up dust effect.

# Answer
> 0 votes
I cannot agree with solutions proposing involving millions of particles, or just building up the result from a multitude of individual small pieces.

* 1st off, it will be a hard work to place such tiny buildstones in huge 3d space in a sensible way (do YOU know the star distances, luminances, colors, densities? I don't :-)).
* 2nd, the piececs lose their meaning along the downscaling anyway, as they end up in for example 500 by 500 pixels on the screen.
* 3rd, there is no fixed rule for how the end result should look (the images you find will google are most likely improved in many ways anyway), and
* 4th light equations are always surprising; in the end result you must clamp all color channels into 0...255 anyway, meaning the values smaller than 0.5 simply and harmfully fall off, although they had a relevance in the "physiclly correct" model.

This is artwork! If you only need to view the result in 2d, meaning no need to fly around the nebula, or enter into it, my approach would definitely be working with a shader and doing pixel processing from a handful of argument textures. One could indeed even have a handful of 3d objects as first guidance, if a view from different angles as needed (grab an isometric snapshot onto a rendersurface, work onwards from that). Reading textures and doing suitable custom maths on the color values (or numbers, if float32 argument textures) would be my approach to this challenge. Additive rendering on top of each other may be a way to go (eg. bouncing between 2 render surfaces a few times).

Would be about grabbing a good hires, middle res, low res and potentially a micro res texture, where the 2 last would be nicely tiling ones, and then just doing texture lookups and after calculation combining into a result that pleases the eye. The textures don't need to look like nebulas initially, they'd only be pixel and color/float32 value placeholders for the shader calculation.

Likely one could build a colorful nebula even from a picture of supermans pyjama and a tiling concrete texture, if using some creative pixel shader coding :-).

(Remember to use float32 surfaces always, so to not force intermediate calculation results into only 256 possible values per channel)

---
Tags: 2d, physics, mathematics, shaders, graphics
---


# Question
Title: LibGDX: Is there a maximum amount of vertices for a PolygonShape?
When you use `PolygonShape.set(Vector2[] vertices)`, is there a limit of vertices of the array which is passed to the method?

# Answer
> 1 votes
Calling `set` on `com.badlogic.gdx.physics.box2d.PolygonShape` calls `set` on `org.jbox2d.collision.shapes.PolygonShape`, which does check the `Settings.maxPolygonVertices` (see `PolygonShape` source).

Thus, unless you've set `org.jbox2d.common.Settings.maxPolygonVertices` to something yourself, the number of vertices needs to be between 3 and 8 (inclusive) as the default is set to

```
/**
 * The maximum number of vertices on a convex polygon.
 */
public static int maxPolygonVertices = 8;

```

Be careful about changing that number as it has an impact on performance.

# Answer
> 0 votes
Method that you mentioned looks like this:

```
public void set (Vector2[] vertices) {
    Vec2[] v = new org.jbox2d.common.Vec2[vertices.length];
    for (int i = 0; i < v.length; i++) {
        v[i] = new Vec2(vertices[i].x, vertices[i].y);
    }
    shape.set(v, v.length);
}

```

Other methods in `PolygonShape` and her parent - `Shape` don't have the `length` limits too. I'm 100% sure that `PolygonShape` has no limit of vertices :\_)

---
Tags: libgdx, box2d
---


title: WWWForm - .AddField vs .headers

text:
# Question
Title: WWWForm - .AddField vs .headers
I am using WWWForm to do the equivalent of GET and POST from python. To add headers to my unity requests, according to the documentation I could two options:

WWWForm form = new WWWForm ();

form.AddField("user", username); //***OPTION 1***: https://docs.unity3d.com/ScriptReference/WWWForm.AddField.html

form.headers\["user"\] = username; //***OPTION 2***: https://docs.unity3d.com/ScriptReference/WWWForm-headers.html

With the risk of asking a very naive question: Can someone explain the difference between the two? Thank you

# Answer
> 1 votes
*I'm not familiar with Unity, nor with c#, this is all based on my reading the documentation. If any improvement should be made, please do so :)*

---

Let's take a look at option 2 from your question:

```
WWWForm form = new WWWForm (); // create a form
form.headers["user"] = username; // modify the form's headers

```

Looking at the documentation you kindly linked to out, here, `headers` is read-only. This means that the code would not compile.

The confusion you seem to ask about is: *Why do they do it in the example?*

The answer: *They're not.*

Let's take a closer look at the example, and only to the relevant lines, with my annotations:

```
// COPY the headers to a new modifiable collection
Hashtable headers = form.headers;

// Modify the copy
headers["Authorization"] = "Basic " + System.Convert.ToBase64String(
    System.Text.Encoding.ASCII.GetBytes("username:password"));

// Use the copy
WWW www = new WWW(url, rawData, headers);

```

So the collection is not directly modified in the `form` object: it is copied to a local modifiable variable first, and it is that variable that is modified.

Perhaps they should not have named the variable `headers` like this, maybe `localHeaders` would have been a better name.

You'll notice that the `form` instance is not used after that in the example, probably because they used it to generate the basic headers and the basic data, but once they modified the custom headers, the object is probably no longer needed.

---

Now, why are there two ways to add headers? Probably for legacy reasons: maybe the option 2 (adding the headers as a hastable, and creating WWW with 3 parameters) was the first one introduced, and eventually option 1 was introduced to further simplify the process. As the documentation says, it's a helper class.

# Answer
> 1 votes
These two do different things.

`WWWForm.AddField` adds a key/value pair of data which is part of the body of the POST request.

`WWWForm.headers`, or the headers you pass to the constructor of `WWW`, are the HTTP header fields which are in the head of the request.

The first is application-specific data, the second are standardized instructions for proxies and web servers about how to treat the request itself. Intermediaries might mess with the HTTP headers (I've seen proxy servers which just strip any headers they don't understand), but not with the POST data.

Here is an example of a complete HTTP POST message as it goes over the wire (stolen from: http://www.jmarshall.com/easy/http/#postmethod):

```
POST /path/script.cgi HTTP/1.0
From: frog@jmarshall.com
User-Agent: HTTPTool/1.0
Content-Type: application/x-www-form-urlencoded
Content-Length: 32

home=Cosby&favorite+flavor=flies

```

`From`, `User-Agent`, `Content-Type` etc. are headers. `home=Cosby&favorite+flavor=flies` is POST data.

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


# Question
Title: Box collider don't catch mouse button press event
I have a cupboard with 2 colliders - one for cupboard and one for it's box. When I press on the box, I want to open/close it. It worked fine, but now by some reason it only work when I press on the edge on the box. When click on the center, it don't work.

Video: https://youtu.be/OozsAi7KNzs

Here is the code, which play animation (open/close cupboard), when I press on the box:

```
public Animation[] animations;
public string[] animationName;
public bool playOneDirection;   // should revert animation speed after second playing?
public AudioSource myAudioOpen;
public AudioSource myAudioClose;

private bool isDoorClosed;
private bool isAimationReadyToPlay = true;
private Collider thisCollider;

public void Start()
{
    thisCollider = GetComponent<Collider>();
}

void Update ()
{
    if (Input.GetButton("Fire1"))
        if(DoPlayerLookAtButton() && isAimationReadyToPlay)
            OpenCloseDoor();
}

bool DoPlayerLookAtButton()
{
    RaycastHit _hit;
    Ray _ray = Camera.main.ScreenPointToRay(new Vector3(Screen.width / 2, Screen.height / 2, 0));
    bool isHit = Physics.Raycast(_ray, out _hit, 1.5f);

    if (isHit && _hit.collider == thisCollider) return true;
    else return false;
}

public void OpenCloseDoor()
{
    if (!isDoorClosed) // Play animation with normal speed
    {
        myAudioOpen.Play();
        for (int i = 0; i < animations.Length; i++)
        {
            animations[i][animationName[i]].speed = 1.0f;
            animations[i].Play();
        }
    }

    if(playOneDirection)
        return;

    if (isDoorClosed) // Play animation with revert speed
    {
        myAudioClose.Play();
        for (int i = 0; i < animations.Length; i++)
        {
            animations[i][animationName[i]].speed = -1.0f;
            animations[i][animationName[i]].time = animations[i][animationName[i]].length;
            animations[i].Play();
        }
    }

    StartCoroutine("DelayBetweenAnimations");
    isDoorClosed = !isDoorClosed;
}

IEnumerator DelayBetweenAnimations()
{
    isAimationReadyToPlay = false;
    yield return new WaitForSeconds(0.5f);
    isAimationReadyToPlay = true;
}

```

# Answer
> 2 votes
You are more than likely hitting another collider before reaching the cabinet collider.

Try using RaycastAll instead. Something like this:

```
RaycastHit[] hits = Physics.RaycastAll(_ray, out _hit, 1.5f);

for (int i = 0; i < hits.Length; i++) {
    RaycastHit hit = hits[i];

    //check if cabinet
    if (hit.gameObject.tag == "Cabinet") {
        if (isHit && _hit.collider == thisCollider) return true;
        else return false;
    }
}

```

# Answer
> 0 votes
I've made the main camera starting from the center of the player, so raycast hits player's collider. I made it trying to fix the bug when camera can go throuth the wall like on the screen below.

Raycast can be seen passing through the player and did not reach the box

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