# Question
Title: Why does selecting a tile return a negative coordinate?
I created a class template named `PlayField<T>`, where `T` is the type of the `GridObject`. I wrote this class using Cocos2d-x.

The point of this class is to make it easy for me to create a grid for games like *"Tetris"*, *"Bejeweled"* or *"Minesweeper"*. One of the main goals for this class is to place it anywhere by a position offset. At the time of creation, each `GridObject` will position itself according to this offset. This way, I could make the grid center align perfectly, or adjust the position horizontally or vertically depending on the layout.

I am able to do this easily with SFML, since the coordinate system there is top-left. The coordinates system in Cocos2d-x is bottom-left, which has given me a challenge, writing up a simple framework for creating the grid.

---

One of the key functions of my class is the ability to convert the pixel position of the mouse or touch input into a grid position. For example, 245 x 245 returns grid position of 4 x 4.

Clicking on each `GridObject` should only return positive coordinates, so I can use this to access them via a 2D vector. However, clicking on the bottom-most part of the grid returns a negative coordinate for the Y-axis. I think I made some wrong calculations, since I am new to programming bottom-left coordinates, and having a difficult time doing so.

Why does selecting a tile return a negative coordinate?

---

Here is my template class:

```
(...)

template<class T>
PlayField<T>::PlayField(const cocos2d::Vec2 & position, const cocos2d::Size & gridSize,
    int offset) : mGridSize(gridSize), mOffset(offset), mGridPositionOffset(position),
    mDrawNode(nullptr)
{
    mGridPositionOffset.y = mGridPositionOffset.y - (gridSize.height * offset);
}

template<class T>
PlayField<T>::~PlayField()
{

}

template<class T>
void PlayField<T>::initialize(cocos2d::Scene * scene)
{
    for (int y = 0; y < mGridSize.height; ++y)
    {
        mGrid.push_back(vector<unique_ptr<T>>());

        for (int x = 0; x < mGridSize.width; ++x)
        {
            cocos2d::Vec2 actualPosition;
            actualPosition.x = (x * mOffset) + mGridPositionOffset.x + (mOffset / 2.0f);
            actualPosition.y
                = mGridPositionOffset.y + ((y + 1) * mOffset) + (mOffset / 2.0f);

            T * gridObject = createGridObject(cocos2d::Vec2(x , y), scene);
            mGrid[y].push_back(unique_ptr<T>(gridObject));

            onGridObjectCreated(gridObject, actualPosition , cocos2d::Vec2(x , y));
        }
    }

    onGridCreationFinished(mGrid);
}

template<class T>
bool PlayField<T>::isWithinBounds(const cocos2d::Vec2 & position)
{
    if ((position.x >= 0 && position.x < mGridSize.width)
        && (position.y >= 0 && position.y < mGridSize.height))
        return true;

    return false;
}

template<class T>
cocos2d::Vec2 PlayField<T>::convertToGridPosition(const cocos2d::Vec2 & position)
{
    cocos2d::Size gridPixelSize
       = cocos2d::Size(mGridSize.width * mOffset, (mGridSize.height-1) * mOffset);

    cocos2d::Vec2 ipos;
    ipos.x = (mGridPositionOffset.x + gridPixelSize.width)  - position.x;
    ipos.y = (mGridPositionOffset.y + gridPixelSize.height) - position.y;

    cocos2d::Vec2 gpos;
    gpos.x = static_cast<int>(ipos.x / mOffset);
    gpos.y = static_cast<int>(ipos.y / mOffset);

    //gpos = cocos2d::Vec2(mGridSize.width - 1 , mGridSize.height - 1) - gpos;

    gpos.x = (mGridSize.width - 1) - gpos.x;

    return gpos;
}

template<class T>
int PlayField<T>::getOffset() const
{
    return mOffset;
}

(...)

```

---

This is how I initialize the grid; I set a small size so that I can simplify testing:

```
mScreenSize = cocos2d::Director::getInstance()->getOpenGLView()->getFrameSize();
cocos2d::Size gridSize = cocos2d::Size(3, 3);

cocos2d::Vec2 actualPosition;
actualPosition.x = (mScreenSize.width / 2.0f) - ((gridSize.width  * 50) / 2.0f);
actualPosition.y
    = ((mScreenSize.height / 2.0f) + (((gridSize.height-1) * 50) / 2.0f) - 74.0f);

mJewelBoard.reset(new JewelBoard(actualPosition, this));

```

---

The `JewelBoard` constructor automatically sets the grid into a size of 3 x 3. with a tile size of 50 x 50 pixels in its constructor. The size of the game screen is 600 x 550. I set the position of the `JewelBoard` to the center using the `actualPosition` variable. Notice that I subtracted `74.0f`, so it goes little bit downward to match the background borders.

That is where I notice that the grid coordinates being returned are negative, on the y-axis. I must have missed something, in calculation. Also take note that getting the position of the touch and mouse location is starting at the top-left. Also note that I prefer my 0 x 0 to start at the bottom-most part. as well. to keep it aligned with my other code. That way, I don't have to do flip-axis conversions.

Here is the picture to better understand my situation:

What has gone wrong? Why does selecting a tile return a negative coordinate?

# Answer
I just figured it out. The mGridPositionOffset is pointing to the top-most corner of the grid. So that makes it (grid.height + mGridPositionOffset.height). As you can notice. That was very wrong. The mGridPositionOffset is already accounting the height of the gridBox plus the grid height. I just figured it out when I make realtime and actual measurement. That was painstaking. Yes, the formula I wrote works, its just that it over accounted the height of the grid which threw the calculations off the expected output. The mGridPositionOffset already accounted the height of the grid since it is on the top-left most corner. What I did is to make sure that the offset actually starts on the bottom-most part of the grid. So the coordinate system is consistent all over the place.

To make that happen, consider the changes I made:

```
    template<class T>
cocos2d::Vec2 PlayField<T>::convertToGridPosition(const cocos2d::Vec2 & position)
{
    //if (!isWithinPixelBounds(position))
    //  return cocos2d::Vec2(-1, -1);

    // TODO fix y-axis not aligning properly

    cocos2d::Size gridPixelSize = cocos2d::Size(mGridSize.width * mOffset, mGridSize.height * mOffset);

    cocos2d::Vec2 ipos;
    ipos.x = (mGridPositionOffset.x + gridPixelSize.width ) - position.x;
    ipos.y = ((mGridPositionOffset.y - gridPixelSize.height) + gridPixelSize.height) - position.y;

    CCLOG("Position : %f , %f" , ipos.x , ipos.y);

    cocos2d::Vec2 gpos;
    gpos.x = static_cast<int>(ipos.x / mOffset);
    gpos.y = static_cast<int>(ipos.y / mOffset);

    gpos.x = (mGridSize.width - 1) - gpos.x;
    gpos.y = (mGridSize.height - 1) - gpos.y;

    return gpos;
}

```

Also, I made sure that the touch/mouse position actually starts on the bottom as well:

```
cocos2d::Vec2 touchPosition = touch->getLocationInView();
touchPosition = cocos2d::Director::getInstance()->convertToGL(touchPosition);

```

Now the grid can now throw the correct coordinates wherever the grid is on the screen!

Hope it helps.
> 0 votes

# Answer
The fast and simple solution is just to increment all returned Y values by 2.

I'm not seeing an obvious error although I can't see the whole situation. I suspect when you subtract 74 pixels to offset the grid you either did or didn't also subtract 74 pixels from every pixel input to methods.

It may also have something to do with your offsets or your additions and subtractions to the y coordinate.

I can help you debug the program though, you start with your incorrect result and then work backwards until you find your error.

In this case you are receiving an incorrect index from I assume the method convertToGridPosition. So you can write a print statement to console or to screen to ensure that it is getting an accurate position input. If yes then your error is in that method, otherwise it is before that method. You work backwards and then forwards through the offending method until you find the statement that is incorrect.
> 1 votes

# Answer
I can't quite spot the error in your code, but this looks odd.

`cocos2d::Size gridPixelSize = cocos2d::Size(mGridSize.width * mOffset, (mGridSize.height-1) * mOffset);`

Why the - 1 on height?

Also, in general to do something like this, you should abstract away the screen coordinates entirely. Make a *hierarchical* system so that when handling clicks, you only have to deal with local coordinates, and never global screen coordinates, except when getting the click from the user.

Something like this, in pseudocode:

```
// A container is a rectangle that can be moved around on the screen.
// Children of the container move with it.
class Container
     // A rectangle (x, y, w, h) relative to the parent coordinate system
     Rectangle local_bounds;
     // A rectangle (x, y, w, h) relative to the screen.
     Rectangle global_bounds;
     // If the parent is null, all coordinates are global. Otherwise,
     // local coordinates are relative to the parent.
     Container parent;
     // A container may have zero or more children.
     List<Container> children;

     // Computes the global bounds of a rectangle based on its parent
     void ComputeGlobalBounds():
          if (parent == null):
              global_bounds = local_bounds;
          else:
              global_bounds = (parent.global_bounds.x + local_bounds.x,
                               parent.global_bounds.y + local_bounds.y,
                               local_bounds.w,
                               local_bounds.h);

     // Gets the local coordinates of a point on the screen.
     Point GetLocalCoords(Point global_coords):
         return (global_coords.x - global_bounds.x, global_coords.y - global_bounds.y);

     // Called when the mouse is clicked (or a touch event, etc.). The coords
     // are global screen coordinates.
     void OnClick(Point global_coords):
         OnLocalClick(GetLocalCoords(global_coords);

         foreach(Container child in children):
             child.OnClick(global_coords);

     // Called from OnClick
     void OnLocalClick(Point global_coords):
          // Do something....

```

Then for a grid, you would do something like this:

```
// This container puts all of its children in a grid.
class GridContainer extends Container:
    // The children are laid out in a grid of this size.
    int num_cells_x;
    int num_cells_y;

    // Get the size of a child in pixels.
    float GetChildSizeX():
       return local_bounds.w / num_cells_x;

    float GetChildSizeY():
       return local_bounds.h / num_cells.y;

    // Add a child at the specified grid coordinate.
    void AddChild(Container child, int x, int y):
        children.Add(child);
        float size_x = GetChildSizeX();
        float size_y = GetChildSizeY();
        child.local_bounds = (size_x * x, size_y * y, size_x, size_y);

```

Now, whenever `OnClick` is called, the appropriate child will automatically get a callback.
> 1 votes

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


# Question
Title: Environment mapping - cube mapping using OpenGL
I'm trying to do cube mapping. Problem is that I'm getting this: This is what I get when I rotate it:

But it should look like this

Here is code for **vertex shader**

```
varying vec2 tex_coord;

void main()
{
 vec3 v = vec3(gl_ModelViewMatrix * gl_Vertex);

 gl_TexCoord[0].stp = normalize(gl_Vertex.xyz);
 gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;

 //gl_ModelViewMatrix * gl_Vertex
}

```

**fragment shader**

```
uniform samplerCube _tex;
void main()
{
 //gl_FragColor = vec4(1.0, 1.0, 1.0, 1.0);
 gl_FragColor = textureCube(_tex, gl_TexCoord[0].stp);
}

```

Could you please tell me what am I doing wrong?

# Answer
> 1 votes
```
gl_TexCoord[0].stp = normalize(gl_Vertex.xyz);

```

Is your problem, I believe you need:

```
gl_TexCoord[0].stp = normalize(gl_Normal.xyz * gl_ModelViewMatrix);

```

Possibly without the matrix multiplier -- I'm a bit rusty.

Note that the meaning of 'normal' can be a bit confusing here -- The 'vertex normal' (gl\_Normal) is a vector pointing directly 'away' from the vertex -- it's the direction you'll want the reflection to come from on the cubemap. The 'normalize()' function takes a vector, and returns a vector with the equivalent direction, but a length of 1 (which is what you want, because texture coords go from 0 to 1).

---
Tags: opengl, c++, shaders, cubemap
---


title: Do >2-state cellular automata exist?

text:
# Question
Title: Do >2-state cellular automata exist?
I'm trying to implement a zone system into my game that randomly sets chunks (the cells) to a certain value from a list and that would effect nearby chunks. It's basically a cellular automaton in which instead of the cells being on/off, they would have multiple options, like red/green/blue/yellow/brown or such.

Do this kind of cellular automata exist?

# Answer
> 3 votes
Yes: wireworld has 4 states, for example.

The on/off was created in a quest for the simplest Turing complete model of an automaton, but there is no reason for you to also be limited to 2 states. (Neither is there a reason for the kernel (transition function inputs) to be limited to just the direct neighbours.)

---
Tags: procedural-generation
---


# Question
Title: Certain random content rendering differently
On the main menu of my game there is (obviously) several buttons. 2 of which, in different positions on different screens, render a different colour to the rest.

As you can see below, "New game" renders black, while the others render grey and on the options screen "Back" does the same thing (this one has literally only just started doing it but I don't know what would cause it).

The code for both buttons is basically exactly the same:

```
public class ButtonNewGame extends Button
{
    public ButtonNewGame(int height, String text)
    {
        super(height, text);
    }

    @Override
    protected void click()
    {
        //Begin drawing the correct components and stop the unneeded ones
        Main.instanceManager.menuInstance.draw = false;
        Main.instanceManager.introInstance.draw = true;
    }
}

```

The only difference between the two are the draw booleans they change, and their names. V.s one of the other buttons the code is again pretty much exactly the same.

The main button class:

```
public abstract class Button extends Component //TODO Fix strange render issues with new game and options back buttons
{
    private UnicodeFont font;
    private String text;
    /**
     * True if user just clicked. Used to stop button spamming on toggle buttons.
     */
    protected static boolean clicked;

    /**
     * Create a new button
     * @param height the text size
     * @param text the text to display
     */
    public Button(int height, String text)
    {
        createFont(height, true, false); //Create font to draw with
        this.text = text;
    }

    /**
     * Render the button
     * @param x start x position
     * @param y start y position
     * @param width the button width
     * @param height the button height
     */
    public void draw(double x, double y, int width, int height)
    {
        Color.white.bind();
        glPushMatrix();
            glTranslated(x, y, 0); //Make sure to draw the button at the specified coordinates

            //Get mouse coordinates
            int mouseX = Mouse.getX();
            int mouseY = Main.WINDOW_HEIGHT-Mouse.getY(); //Compensates for mouse being calculated from bottom up

            //Check for mouse status and call correct draw method accordingly
            if((mouseX > x && mouseX < x + width) && (mouseY > y && mouseY < y + height))
            {
                if(Mouse.isButtonDown(0) && !clicked) //If the button has been clicked
                {
                    drawClick(x, y, width, height); //This will very rarely, if at all, be seen.
                    click(); //Actual click event
                    clicked = true;
                }
                else
                {
                    drawHover(x, y, width, height); //When the mouse is within the button area
                }
            }
            else
            {
                drawNormal(x, y, width, height); //When the mouse is not within the button area
            }

            if(!Mouse.isButtonDown(0)) clicked = false; //Only reset clicked once the mouse button is released

            drawFont(0, 0, this.text, Color.white); //Draw the button text
        glPopMatrix();
    }

    /**
     * Draw the button when nothing is happening to it
     * @param x start x position
     * @param y start y position
     * @param width the width of the button
     * @param height the height of the button
     */
    protected void drawNormal(double x, double y, int width, int height)
    {
        glBegin(GL_QUADS);
            glColor4d(0.6, 0.6, 0.6, 0.8);
            glVertex2d(0, 0);
            glVertex2d(width, 0);
            glVertex2d(width, height);
            glVertex2d(0, height);
        glEnd();
    }

    /**
     * Draw the button when the mouse is hovering over it
     * @param x start x position
     * @param y start y position
     * @param width the width of the button
     * @param height the height of the button
     */
    protected void drawHover(double x, double y, int width, int height)
    {
        glBegin(GL_QUADS);
            glColor3d(0.7, 0.7, 0.7);
            glVertex2d(0, 0);
            glVertex2d(width, 0);
            glVertex2d(width, height);
            glVertex2d(0, height);
        glEnd();
    }

    /**
     * Draw the button when the mouse is hovering over it and held down
     * @param x start x position
     * @param y start y position
     * @param width the width of the button
     * @param height the height of the button
     */
    protected void drawClick(double x, double y, int width, int height)
    {
        glBegin(GL_QUADS);
            glColor3d(0.75, 0.75, 0.75);
            glVertex2d(0, 0);
            glVertex2d(width, 0);
            glVertex2d(width, height);
            glVertex2d(0, height);
        glEnd();
    }

    /**
     * Font setup
     * @return UnicodeFont for drawing
     */
    @SuppressWarnings("unchecked")
    private UnicodeFont createFont(int size, boolean isBold, boolean isItalic)
    {
        //Try to load the font from file
        try
        {
            InputStream inputStream = ResourceLoader.getResourceAsStream("assets/fonts/handwriting_draft.ttf");

            Font awtFont = Font.createFont(Font.TRUETYPE_FONT, inputStream);
            font = new UnicodeFont(awtFont, size, isBold, isItalic);

        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

        //Load the font effects and set to white as backup
        font.addAsciiGlyphs();
        ColorEffect colour = new ColorEffect();
        colour.setColor(java.awt.Color.white);
        font.getEffects().add(colour);
        try
        {
            font.loadGlyphs();
        }
        catch (SlickException e1)
        {
            e1.printStackTrace();
        }
        return font;
    }

    /**
     * Draws the pre-setup font
     * @param x x-offset inside the button
     * @param y y-offset inside the button
     * @param text the text to render
     * @param colour the text's colour
     */
    private void drawFont(int x, int y, String text, Color colour)
    {
        glEnable(GL_TEXTURE_2D);
            font.drawString(x, y, text, colour);
        glDisable(GL_TEXTURE_2D);
    }

    protected abstract void click();
}

```

I think this class is probably responsible, however I also believe it could be down to my OpenGL setup method which is called every frame (is that a bad thing to do?):

```
private void setCamera()
    {
        glClear(GL_COLOR_BUFFER_BIT); //Clear screen

        //Modify projection matrix
        glMatrixMode(GL_PROJECTION);
        glLoadIdentity();
        glOrtho(0, Display.getWidth(), Display.getHeight(), 0, 1, -1);

        //Enable transparency, so the text doesn't have a black background
        glEnable(GL_BLEND);
        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

        glEnable(GL_TEXTURE_2D); //For loading textures

        //Modify modelview matrix
        glMatrixMode(GL_MODELVIEW);
        glLoadIdentity();
    }

```

If however I am completely wrong all of the code can be found here: https://github.com/Roboguy99/World-Map-Game

I have no idea what is causing this, and my knowledge on OpenGL is very limited. I appreciate any help I can get, thanks.

# Answer
> 0 votes
You need to disable textures before drawing the quads. Here's basically what's going on:

1. You enable textures (in setCamera).
2. You draw a button which:
3. Draws a quad (which is textured, not just a solid color, but texcoords aren't set so...weirdness happens, and it might not be entirely predictable)
4. Then you draw text (correctly) by:
5. Enabling textures.
6. Drawing the font with textures.
7. Disabling textures \<-------
8. Back to step 2, to draw the next button -- but it starts with DISABLED textures this time, so things happen as you expect.

If you'll note, on the 'options' screen, you are drawing the 'back' button first (even though it's the 'last' button).

As an entire sidenote... Almost everything you're doing is deprecated in OpenGL -- fixed pipelines are not the way it's done anymore. With that said, it IS probably the easiest way to start grasping the concepts of 3D programming as everything is done step-by-step. On the other hand, when you start trying to do more complex things, you're going to run into some problems, not the least of which is finding any tutorials that aren't many years old. If you're looking for resources on 'the new way', do searches for 'OpenGL 3.3', or 'OpenGL Core Profile'.

---
Tags: opengl, java, rendering, lwjgl, menu
---


title: single Key press

text:
# Question
Title: single Key press
I have my following (static) KeyListener http://pastebin.com/gR1i3Xzb

and this is my update Method:

```
@Override
  public void update()
  {
    input();
    /*...*/
  }

  private void input()
  {
    if (KeyBinding.downDown)
    {
      nextEntry();
    }
    else if (KeyBinding.upDown)
    {
      previousEntry();
    }
  }

```

someone has an idea to make single presses?

Let's say I have a menu. If I press the Down key for a short amount of time, many menu entries are skipped. But I want to take the next menu entry only once.

# Answer
You could check to see if the key was pressed in the previous frame. Consider doing something like this:

```
bool DownPressed;
bool UpPressed;

....

if (KeyBinding.downDown)
{
   if (!DownPressed)
   {
       DownPressed = true;
       nextEntry();
   }
}
else
{
    DownPressed = false;
}

if (KeyBinding.upDown)
{
   if (!UpPressed)
   {
       UpPressed= true;
       previousEntry();
   }
}
else
{
    UpPressed= false;
}

```

I would suggest that you encapsulate the click logic in a Button class or something, as you can see this style of coding could get messy pretty quickly if you had a lot of different key bindings.
> 1 votes

---
Tags: java, keyboard
---


# Question
Title: Why does Unity increase the size of image when I use the image in Unity?
I try to make a game in Unity 2d. But when I drop the image in Unity the image size increases 3 or 4 times. Can I fix that or is this normal?

# Answer
The default sprite size in Unity is 100 pixels per unit.

This means that if you have a sprite that is 100 pixels wide, it would occupy "1" Unity unit. If you moved this sprite to the left by 1 unit, it would shift 100 pixels to the left.

You can change this value by selecting your sprite, and changing its "Pixels per Unit" property.

I typically set my sprites to their native size, for example, if a sprite is 64x64, I set it to 64 pixels per units.
> 5 votes

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


# Question
Title: zoom, scale, pan etc in an application and printing
I have a C# windows application where I display photos for editing. The displayed image is scaled to fit the screen. I allow pan, zoom, rotate, crop operations. Once the editing is done, I would like to print. Now since the displayed image is scaled before any of these operations, how can I print the photo correctly?

* one option is to do the operations on the original image and then scale it and display it.

Is it what is normally done?

# Answer
What I would do, is load two copies of the image into memory.

One of the copies would be used to display a preview to the user, the other would be used to apply the edits made.

Once the user is happy with their edits, offer to save the new image from memory to disk.
> 1 votes

---
Tags: graphics
---


# Question
Title: Unity - PoolingSystem failing to instantiate
I am wanting to spawn monsters into my scene in Unity. I was told to use a Pooling System, so I got the free one Unity offers in the Asset store. I have followed the little documentation that there is, and am encountering an error. I do not know if I am just missing something but I am getting an object reference not set error.

```
NullReferenceException: Object reference not set to an instance of an object
PoolingSystem.InstantiateAPS (System.String itemType) (at Assets/Advanced Pooling     System/PoolingSystem.cs:104)
MobSpawner.Start () (at Assets/_Scripts/MobSpawner.cs:16)

```

It throws this on the following code:

```
private PoolingSystem poolingSystem;

// Use this for initialization
void Start () {
    poolingSystem = PoolingSystem.Instance;

    poolingSystem.InstantiateAPS("Resources/EnemyPrefabs/Skeleton");
}

```

Could someone please guide me in the right direction or tell me what is wrong here?

# Answer
> 1 votes
I looked at the source code, and it looks like InstantiateAPS requires the Prefab name as a parameter.

```
poolingSystem.InstantiateAPS("Skeleton");

```

This should probably work, so as long as you actually have a Skeleton prefab in your Resources folder.

---
Tags: unity
---


# Question
Title: In Unity, how do I make separate mute buttons for sound-effects and music?
I'd like to have a button to mute game sounds and another to stop the game music. How can I do this?

# Answer
In the past, I've attached a script to the music `AudioSource` that sets `ignoreListenerVolume`, to bypass the main volume controls.

A crude example to get the point across:

```
void Start() {
    AudioSource music = GetComponent<AudioSource>();
    music.ignoreListenerVolume = true;

    //you can manage the music's volume directly, now
    music.volume *= 0.5f;
}

```

To adjust SFX volume, change the master volume of the audio listener. To adjust music volume, change the volume for the music's audio source(s).

This doesn't take into account the new audio system that shipped with Unity 5. It may now be easier to manage this with audio groups and mixer controls.
> 1 votes

# Answer
One approach is to set ignoreListenerPause on the AudioSource for your music and then set a mute on the overall game using AudioListener.pause. Now AudioListener.pause will mute everything except your music, while you can still mute that audio source directly. I take that approach in the audio chapter of my book (see my profile).
> 0 votes

# Answer
This is not directly possible in Unity because:

1. There is no difference between sound and music for the Audio Sources
2. The volume of every Audio Source is independent of eachother

You will need to search for the Audio Sources in your local scene to iterate through them with `Object.FindObjectsOfType`.

```
var audioSources = Object.FindObjectsOfType(typeof(AudioSource)) as AudioSource[];
foreach (var audioSource in audioSources)
    audioSource.volume = 0;

```

To distinguish between sound and music you can use tags and check them with `audioSource.gameObject.CompareTag`.
> -2 votes

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


# Question
Title: Unity: How to make script work with duplicated objects?
I have an object in my game that, when clicked, causes the player to move toward it. It does this by sending its position to the player's SetTarget function. The player's Move function then heads toward the position.

This is working, but when I duplicate the object and click on it, the player still moves toward the **original** object's position. When I print debugging statements to the console, it appears that both positions are being calculated, but the original position is the last one and wins out. (I'm using the object's this.transform.position to send the position to the player's SetTarget function.)

Can I not duplicate objects like this and expect the script to work? Do I need to use a prefab? If so, how? I know how to create prefabs but am not sure what I would need to change with the script or other settings when they are created. Thanks.

Here's the code:

```
public class PotController : MonoBehaviour {

private GameObject chefObject;

void Start () {
    chefObject = GameObject.Find ("Chef");
}

void Update() {
    if(Input.GetMouseButtonDown(0)){
        //print ("pot clicked!");
        ChefController chefScript = chefObject.GetComponent<ChefController> ();

        print (this.gameObject.transform.position);
        chefScript.SetTheTarget (this.gameObject.transform.position);
    }
}
}

public class ChefController : MonoBehaviour {

private Vector3 target;
public float speed = 2;

// Use this for initialization
void Start () {
    target = this.transform.position;
}

private void MoveTowardsTarget() {
    Vector3 targetPosition = new Vector3(0,0,0);
    targetPosition = target;
    Vector3 currentPosition = this.transform.position;
    //check distance to target
    if(Vector3.Distance(currentPosition, targetPosition) > 0.4f) {
        Vector3 directionOfTravel = targetPosition - currentPosition;

        directionOfTravel.Normalize();

        this.transform.Translate(
            (directionOfTravel.x * speed * Time.deltaTime),
            (directionOfTravel.y * speed * Time.deltaTime),
            (directionOfTravel.z * speed * Time.deltaTime),
            Space.World);
    }
}

void Update () {
    MoveTowardsTarget ();
}

public void SetTheTarget (Vector3 position){
    target = position;
}

}

```

# Answer
> 2 votes
**EDIT**

Okay, so the problem is that you need to identify which pot was clicked. With your current code, whenever the mouse is clicked, it fires off code in every PotController.

What you should do, is add a collider to your Pot, which would allow you to perform a collision check on the mouse to see which Pot was clicked.

Then instead of your Update() code, you would have:

```
void Update()
{
    if (Input.GetMouseButtonDown(0))
    {
        RaycastHit2D[] hits;
        Vector2 pos = Input.mousePosition;
        pos = Camera.main.ScreenToWorldPoint (pos);
        hits = Physics2D.RaycastAll (pos, new Vector2 (0, 0), 0.01f);

        for (int i = 0; i < hits.Length; i++) {
            if (hits [i].collider.gameObject == this.gameObject) {
                 ChefController chefScript = chefObject.GetComponent<ChefController> ();
                 print (this.gameObject.transform.position);
                 chefScript.SetTheTarget (this.gameObject.transform.position);
                 break;
            }
        }
    }
}

```

But quite frankly, the Raycasting should probably be done from the Player class, and then you would call a Pot.SetTarget() from there. This is not very efficient, but it should show you how to do this.

---
Tags: unity
---


title: OpenGL Shaders Ignored

text:
# Question
Title: OpenGL Shaders Ignored
I have been following this tutorial to try and start learning OpenGL. However, upon compiling my code, my triangle turns out to be black. At first I thought that there was something wrong with the fragment shader, but when I tried hard-coding x-values for the vertex shader, I noticed that it had no effect (notice the 0.7f x-value on the vertex shader).

**main.cpp**

```
#define GLFW_DLL
#include <iostream>
#include <fstream>
#include <GL/glew.h>
#include <GLFW/glfw3.h>

GLfloat verticies[] = {
    -1.0f, -1.0f, 0.0f,
    0.0f, 1.0f, 0.0f,
    1.0f, -1.0f, 0.0f
};

// Objects
GLuint VBO;
GLuint VAO;
GLuint vertShader;
GLuint fragShader;

void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode)
{
    if(key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)
    glfwSetWindowShouldClose(window, GL_TRUE);
}

std::string readFile(const char* filePath)
{
    std::string content;
    std::ifstream fileStream(filePath);

    if(!fileStream.is_open())
    {
    std::cout << "Failed to open " << filePath << "." << std::endl;
    return "";
    }

    std::string line = "";
    while(!fileStream.eof())
    {
    std::getline(fileStream, line);
    content.append(line + "\n");
    }

    fileStream.close();
    return content;
}

void createShader(const GLenum shaderType, const char* shaderPath, GLuint& shaderObject)
{
    // Create the shader.
    shaderObject = glCreateShader(shaderType);

    // Read the shader code from the shader file.
    const GLchar* shaderCode = readFile(shaderPath).c_str();

    // DEBUG:
    std::cout << shaderCode << std::endl;

    // Assign the shader code to the shader object.
    glShaderSource(shaderObject, 1, &shaderCode, NULL);

    // Compile the shader.
    glCompileShader(shaderObject);

    // Check to see if it compiled successfully.
    GLint success;
    GLchar infoLog[512];
    glGetShaderiv(shaderObject, GL_COMPILE_STATUS, &success);
    if(!success)
    {
    glGetShaderInfoLog(shaderObject, 512, NULL, infoLog);
    std::cout << "ERROR::SHADER::VERTEX::COMPILATION_FAILED\n"
          << infoLog
          << std::endl;

    }
}

int main(int argc, char *argv[])
{
    // Initialize GLFW.
    glfwInit();
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
    glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);

    // Create OpenGL window. Exit if fails.
    GLFWwindow* window = glfwCreateWindow(800, 600, "LearnOpenGL", nullptr, nullptr);
    if (window == nullptr)
    {
    std::cout << "Failed to create GLFW window" << std::endl;
    glfwTerminate();
    return -1;
    }

    // Make window current
    glfwMakeContextCurrent(window);

    // Initialize GLEW.
    glewExperimental = GL_TRUE;
    if (glewInit() != GLEW_OK)
    {
    std::cout << "Failed to initialize GLEW" << std::endl;
    return -1;
    }

    // Set viewport size and position.
    glViewport(0, 0, 800, 600);

    // Set callback functions.
    glfwSetKeyCallback(window, key_callback);

    // Set clear color state.
    glClearColor(0.5f, 0.5f, 0.5f, 1.0f);

    // Create vertex and fragment shaders.
    createShader(GL_VERTEX_SHADER, "../src/shaders/vertex.vert", vertShader);
    createShader(GL_FRAGMENT_SHADER, "../src/shaders/fragment.frag", fragShader);

    // Attach then link shaders
    GLuint shaderProgram;
    glAttachShader(shaderProgram, vertShader);
    glAttachShader(shaderProgram, fragShader);
    glLinkProgram(shaderProgram);

    // Delete the shaders
    glDeleteShader(vertShader);
    glDeleteShader(fragShader);

    // Check if it succeeded.
    GLint linkSucceeded;
    glGetProgramiv(shaderProgram, GL_LINK_STATUS, &linkSucceeded);
    if(!linkSucceeded)
    {
    GLchar infoLog[512];
    glGetProgramInfoLog(shaderProgram, 512, NULL, infoLog);
    std::cout << "ERROR::SHADER::PROGRAM::LINK_FAILED\n"
          << infoLog
          << std::endl;
    }

    // Generate the VAO and bind it.
    glGenVertexArrays(1, &VAO);
    glBindVertexArray(VAO);

    // Create VBO and bind to it.
    glGenBuffers(1, &VBO);
    glBindBuffer(GL_ARRAY_BUFFER, VBO);

    // Send verticies to buffer's memory.
    glBufferData(GL_ARRAY_BUFFER, sizeof(verticies), verticies, GL_STATIC_DRAW);

    // Set up vertex attributes
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), (GLvoid*)0);
    glEnableVertexAttribArray(0);

    // Unbind VBO
    glBindBuffer(GL_ARRAY_BUFFER, 0);

    // Unbind VAO
    glBindVertexArray(0);

    // Game loop.
    while(!glfwWindowShouldClose(window))
    {
    // Get input.
    glfwPollEvents();

    glClear(GL_COLOR_BUFFER_BIT);
    glUseProgram(shaderProgram);
    glBindVertexArray(VAO);
    glDrawArrays(GL_TRIANGLES, 0, 3);
    glBindVertexArray(0);

    // Swap buffers.
    glfwSwapBuffers(window);
    }

    // De-allocate resources.
    glDeleteVertexArrays(1, &VAO);
    glDeleteBuffers(1, &VBO);

    // Terminate and close.
    glfwTerminate();
    return 0;
}

```

**Vertex Shader**

```
#version 330 core

layout(location = 0) in vec3 position;

void main()
{
    gl_Position = vec4(0.7f, position.y, position.z, 1.0f);
}

```

**Fragment Shader**

```
#version 330 core

out vec4 color;

void main()
{
    color = vec4(1.0f, 0.5f, 0.2f, 1.0f);
}

```

# Answer
Of course right after I post this I realize what I did wrong:

```
// Attach then link shaders
GLuint shaderProgram;

```

should be

```
// Attach then link shaders
GLuint shaderProgram = glCreateProgram();

```
> 0 votes

---
Tags: opengl, shaders, glsl
---


title: Applicaton.ExternalEval(String script)

text:
# Question
Title: Applicaton.ExternalEval(String script)
I was wondering, if `Application.ExternalEval(String script);` in Unity3D can return something.

Like:
`String playerName = Application.ExternalEval("prompt("Please enter your name", "player1")");`

Thank you in advance!

# Answer
I don't think . But you can try to call a javacript like this (using Application.ExternalEval(.. ):

```
<script type="text/javascript" language="javascript">
<!--
//initializing the WebPlayer
var u = new UnityObject2();
u.initPlugin(jQuery("#unityPlayer")[0], "Example.unity3d");

function SaySomethingToUnity()
{
    u.getUnity().SendMessage("MyObject", "MyFunction", "Hello from a web page!");
}
-->
</script>

```

who sends a message back to Unity.. check this and let me know..
> 1 votes

# Answer
Disclaimer. My first intention was to update existing answer, but then I understood that I totally rewrote it. That's why I am creating new one.

---

Yes, it's possible. The communication is possible between the browser and unity in both directions. In the unity documentation this topic is well described. So it's possible to create a general function that will allow you to call javascript code from c# and get the result of it's evaluation in c#. Just remember that it will work only in WebPlayer or WebGL, but not in Editor, since `Application.ExternalCall` and `Application.ExternalEval` will just log to the editor console in Editor.

```
public static void Evaluate(string js, System.Action<string> callback);

```

So actually you need to use callbacks here. The only catch is to store those callbacks somehow. You can do a dirty trick by using and `id` for them. And storing callbacks in a dictionary where the key is `id`. And attach this id to `js` string, so in javascript you extract id, evaluate `js` and then send result with attached `id`. And then in the c# you again extract `id` and get callback by `id` from dictionary of callbacks and call this callback on the result. Sounds creepy. So it's simple implementation will look like

```
public class JSEvaluator : MonoBehaviour {

    private int id;
    Dictionary<int, Action<string>> callbacks;

    public static void Evaluate(string js, Action<string> callback) {
        ++id;
        callbacks[id] = callback;
        // ':' is separator to know where id ends
        Application.ExternalCall("evaluate", id.ToString() + ":" + js);
    }

    private void OnJSResult(string result) {
        var stringSeparators = new string[] {":"};
        var res = source.Split(stringSeparators, StringSplitOptions.None);
        var i = Convert.ToInt32(res[0]);
        var cb = callbacks[i];
        var rem = res[0] + ":";
        cb(result.Remove(result.IndexOf(rem), rem.Length););
        callbacks.Remove(i);
    }

}

```

Several catches here. First, we increase `id`. For every `Evaluate` call. And if you make a lot of them. At some point you might experience strange results. By a lot of I mean more than 4294967296. Also we don't check of result for having `id`.

Also important thing here. `OnJSResult` is not `static`. You can't call `static` methods from javascript. Due to how `SendMessage` works. Also, `JSEvaluator` must be `MonoBehaviour`.

In javascript it would be something like.

```
function evaluate(input) {
    var inp = input.split(":");
    var id = parseInt(inp[0]);
    inp.shift();
    var arg = inp.join(":");
    var result = eval(arg);
    // for UnityPlayer you need to u.getUnity().SendMessage
    SendMessage("GameObjectName", "OnJSResult", result);
}

```

Just don't forget to create an object named `GameObjectName` on the scene and attach to it `JSEvaluator`. I think that's pretty much it. Just remember that in general this thing is not very great. But I shown you an example of communication.
> 0 votes

---
Tags: unity, javascript, webgl
---


title: How does hidden surface removal work?

text:
# Question
Title: How does hidden surface removal work?
Lately, I've been learning some OpenGL for fun, and I've been thinking about hidden surface removal.

Say you have a high poly count static scene, with nothing that moves, no bones, physics, etc. Just static models to be drawn. I was thinking that you could put all the faces in the scene into a quad/octree. And with the camera position, and dimensions of the view frustum, you could traverse the tree to construct an index buffer of all the faces that are within the view frustum (facing towards you of course). You could then update the index buffer with `glBufferSubData()`, and draw with `glDrawElements()`, and you would do this every frame, and if my limited understanding is correct, this should theoretically draw only the faces you see, right?

So is this a good/valid way to do occulusion culling? If not, how else can you do it?

# Answer
It's all about tradeoffs.

But first, occlusion culling is to hide what is being hidden by other objects, not what falls outside the viewing frustum. What you described is called frustrum culling.

Sure, you can do that and only request to draw polygons that you will see, but those calculations, along with the time required to update the index buffer may have a non negligible impact on performance, mostly on the CPU, but will also require a GPU sync to reupload the index buffer.

Compare that to drawing everything without culling. You will certainly need to upload your data to VRAM, but only once. GPU processing will then happen for each vertex. The CPU will hardly notice this is going on.

Keep in mind that viewport culling is an extremely simple operation for the GPU.

Ultimately, you're trading GPU cycles for CPU cycles. Deciding whether to do what you propose is affected by a number of factors, including fhe type of geometry you have, the hardware you use, and what else is going on in your game besides rendering.

As always, when we talk performance, it is usually advisable to measure first and act later. Bottlenecks may exist where you least expect them, and places where you think bottlenecks exist may wxhibit no problems at all.

Consider also changing the unit of culling. It may not be necessary to do per polygon culling, when you can get away with per mesh, or per submesh culling.
> 1 votes

---
Tags: graphics, algorithm, culling
---


# Question
Title: OpenGL poor performace with instanced drawing
I'm just started learning OpenGL and this is my first project besides tutorials. I'm trying to load a huge enginering model:

The data is structured in a way that I thought I could use instancing for very good performance, because many items are simple primitives (cylinder, torus, cones, etc) with different transformation matrices. So I structured my data this way:

```
Primitive 1
  VAO
    VBO -> vertices
    VBO -> indices

    Instance 1.1
      VBO -> object color
      VBO -> transformation matrix

    Instance 1.2
      VBO -> object color
      VBO -> transformation matrix

    Instance 1.n
      VBO -> object color
      VBO -> transformation matrix

Primitive n
  VAO
    VBO -> vertices
    VBO -> indices

    Instance n.1
      VBO -> object color
      VBO -> transformation matrix

    Instance n.n
      VBO -> object color
      VBO -> transformation matrix

```

The model has ~50k unique primitives and ~120k instances, so in general each primitive has 2 instances. But in practice, some have 10 and some have only 1. I end up with 50k VAOs and then call dlDrawElementsInstanced for each VAO.

The model is being draw at only 3 fps. I gues it's because of the number of glDraw calls (50k for the triangles and 50k for the outlines). The shaders are very simple, not even lightning is being applied.

To be sure of that I changed the way I organize the buffers: I put everything in a single buffer, but to do that I had to pass the color and transformations matrices as vertex attributes to each vertex. I know this isn't right but I had to test if the problem was the number of glDraw calls. I couldn't even load the model this way because the buffers get way to big and I get out of memory. So I tested this theory on a smaller model that was taking 50ms to render in the instanced way. With a single VAO for everything and only a single glDrawElements call the model is taking less than 1ms to render.

I know that putting everything in a single VAO and passing the trasnformations for every vertex is not the correct way of doing this. Now I also know that instancing isn't the tool for this due the very few intances for each mesh. So the question is, what would be the correct way to setup the buffers to minimize the number of glDraw calls?

I think that it would be perfect to store all in a single VAO (so I could call glDrawElements a single time) but use something like the glVertexAttribDivisor used in instancing to inform the shaders when to use the next shaders. But not exactly because I had to manually inform when to use the next matrix, in way like glPrimitiveRestartIndex works.

I'm using OpenGL 3.3

# Answer
Your performance hit come from driver overhead (state changes). Having 50K VAOs is wayyyyy too much.

If all your models are the same format (for example the format x,y,z,r,g,b,a) then you should use one VAO and one VBO.

You can use something like `glMultiDrawArraysIndirect` for rendering large amounts of object and you can create commands (which require no OpenGL calls) and then dispatch them all in one go with one OpenGL call to `glMultiDraw*Indirect`.

Using `glMultiDraw*Indirect` means you can store all your vertex data in one VBO too.

You can also get a preformace win by using glBufferStorage & persistantly mapped buffers to dispatch you matrix transforms & colour to the GPU.

This presentation show how you can avoid a lot of the driver overhead, along with source code too!

Also this presentation might be more geared towards what you are trying to do.
> 4 votes

---
Tags: opengl, instancing
---


# Question
Title: Adding shadow and other effects on a spritefont Monogame
Is there a way that I can add shadow effect on text drawn in monogame? Because you cannot add shadow effect when creating a new spritefont file in Monogame Content Pipeline.

Thanks.

# Answer
One way to do this, is to draw your text 2 times in a different color at specific offsets.

For example:

```
    public static void DrawText(SpriteBatch spritebatch, SpriteFont font, string text, Color backColor, Color frontColor, float scale, Vector2 position)
    {
        Vector2 origin = Vector2.Zero;

        spriteBatch.DrawString(font, text, position + new Vector2(1 * scale, 1 * scale), backColor, 0, origin, scale, SpriteEffects.None, 1f);
        spriteBatch.DrawString(font, text, position + new Vector2(-1 * scale, 1 * scale), backColor, 0, origin, scale, SpriteEffects.None, 1f);
        //spriteBatch.DrawString(font, text, position + new Vector2(-1 * scale, -1 * scale), backColor, 0, origin, scale, SpriteEffects.None, 1f);
        //spriteBatch.DrawString(font, text, position + new Vector2(1 * scale, -1 * scale), backColor, 0, origin, scale, SpriteEffects.None, 1f);

        spriteBatch.DrawString(font, text, position, frontColor, 0, origin, scale, SpriteEffects.None, 0f);
    }

```

Might be good enough for what you are trying to do.
> 5 votes

---
Tags: xna, c#, monogame, windows-phone-8
---


title: A deterministic game loop

text:
# Question
Title: A deterministic game loop
I want to make a game loop that is deterministic sort of like a physics engine but it's for game update and rendering.

I've done a lot of reading and I still was a bit confused.

I've read these articles:

The one that made the most sense was the final article about multiply delta time or not.

I want to have fixed time step so I will design my games to fit in either 30 or 60 fps. So if I target 60fps all logic needs to be done in 0.166ms on a pc but if I am making an app that runs on mobile 0.33ms.

With those ideas in mind how would I setup the game loop that's deterministic but also frees the renderer but I am unsure how to go about doing the rendering loop? Would I interpolate the position before rendering?

# Answer
Your rendering and deterministic simulation don't have to run at the same frequency

If you fall behind, you can run the simulation multiple times between renders.

If you get ahead, you do multiple renders between simulations and use interpolation of the values in your renderer.

If you fall too far behind you can see that you might fall into a death spiral where you can't simulate fast enough to catch up to "real time". In this case, your best bet is to probably just let it fall behind.

If it's a networked game, this might be problematic but if it isn't, this is fine, and doesn't break the determinism of course (:
> 2 votes

---
Tags: game-design, game-loop
---


# Question
Title: How do games such as aa Game have high levels in the structure of their code
How do games such as aa Game have high levels in the structure of their code? I mean if we want create a game with high levels, should we create and use a class for each level? I do not want code from you. only I want know for creating a game with high levels in android, What we should do in coding? Is it good if we create and use a class for each level?

# Answer
> 3 votes
The simple answer is that in general, your levels should be defined as data, and your code should be the same for all levels, it just reads the data to know what to do.

---
Tags: android
---


title: Problem with Rotation - C#/XNA

text:
# Question
Title: Problem with Rotation - C#/XNA
I have a projecile(Hook) and the tail of the projectile(yellow balls)

`TailProjectile` class draws a ball at the exact position of the projectile(hook) and let it there until the projectile ends

I'd like to draw the ball at the start of the hook(red circle) because by now it draws at the projectile image position(blue point)

How can I do it independent of the rotation of the hook?

This is how I calculate the rotation of the projectile

```
distanceY = endPosition.Y - initialPosition.Y;
        distanceX = endPosition.X - initialPosition.X;

        if (distanceX < 0)
            animation.SprtEffects = SpriteEffects.FlipVertically;
        animation.Rotation = (float)Math.Atan2(distanceY, distanceX);

```

Then I pass the projectile to the tail and draw the ball

```
        if (hasTail)
            tail.Update(gameTime,  position , animation.Rotation,animation.SprtEffects);

```

And at the TailProjectile update class :

```
  public void Update(GameTime gameTime,Vector2 p,float rotation,SpriteEffects sprtEffect)
    {
        if (Vector2.Distance(animations[animations.Count - 1].Position, p) > distanceBetween)
        {
            Animation tempAnimation = new Animation();
            tempAnimation.LoadContent(content, image, "", p);
            tempAnimation.Rotation = rotation;
            tempAnimation.SprtEffects = sprtEffect;
            tempAnimation.DrawColor = color;
            animations.Add(tempAnimation);
        }

```

And the Animation Draw:

```
spriteBatch.Draw(image, position + origin, sourcRect, drawColor * alpha, rotation, origin, scale, sprtEffects, 0.0f);

```

Edit: Using rotation matrix solve half of the problem :

My problem now is how can I calculate it for angles higher than 90º ? (third picture of the image)

```
 double xO, yO;
        xO = originpoint.X * Math.Cos(rotation) - originpoint.Y * Math.Sin(rotation);
        yO = originpoint.X * Math.Sin(rotation) + originpoint.Y * Math.Cos(rotation);
        initialAnimation.Position = new Vector2((float)xO + initialAnimation.Position.X, (float)yO + initialAnimation.Position.Y);

```

# Answer
I think you might be overcomplicating things - why not just set the "origin" of the hook to

```
new Vector2(0, hookTexture.Height / 2)

```

If you simply draw it like this:

```
spriteBatch.Draw(hookTexture, position, null, Color.White, rotation, new Vector2(0, hookTexture.Height / 2), 1.0f, SpriteEffects.None, 0.0f);

```

That way the hook is drawn and rotated around where it would connect to the balls.

Hope this helps! If I misunderstood anything, please comment. Thanks! :)

Edit: Here's some sample code for a small demo of what I mean:

(just copy-paste it into a new c# xna project, import your hook and ball images, and run the program)

```
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;

namespace demoforgamedev
{
    public class Game1 : Microsoft.Xna.Framework.Game
    {
        MouseState M = new MouseState();

        Vector2 TailStartSpot;
        Vector2 HookPosition;
        Texture2D hookTexture;
        Texture2D ballTexture;

        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;

        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
        }
        protected override void Initialize()
        {
            base.Initialize();
        }
        protected override void LoadContent()
        {
            spriteBatch = new SpriteBatch(GraphicsDevice);

            hookTexture = Content.Load<Texture2D>("hook");
            ballTexture = Content.Load<Texture2D>("ball");
        }
        protected override void UnloadContent()
        {

        }
        protected override void Update(GameTime gameTime)
        {
            M = Mouse.GetState();
            TailStartSpot.X = graphics.GraphicsDevice.Viewport.Width / 2; // The tail of the projectile will start at the center
            TailStartSpot.Y = graphics.GraphicsDevice.Viewport.Height / 2; // of the screen, just for demonstration purposes.

            HookPosition = new Vector2(M.X, M.Y); // The projectile will be drawn at the mouse position, just for demonstration purposes.

            base.Update(gameTime);
        }
        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.White);

            DrawProjectile(spriteBatch, true, TailStartSpot, HookPosition);

            base.Draw(gameTime);
        }
        public void DrawProjectile(SpriteBatch spritebatch, bool hasTail, Vector2 point1, Vector2 point2)
        {
            // Given a start point and an end point, draw a projectile (possibly) with a trail.

            float rotation = (float)Math.Atan2(point2.X - point1.X, -point2.Y + point1.Y) - (float)(Math.PI / 2); // Find the rotation

            spritebatch.Begin();

            Vector2 plusequals = (point2 - point1) / 9;
            spriteBatch.Draw(hookTexture, HookPosition, null, Color.White, rotation, new Vector2(0, hookTexture.Height / 2), 1.0f, SpriteEffects.None, 0.0f);
            for (int i = 0; i < 10; i++)
            {
                spritebatch.Draw(ballTexture, new Rectangle((int)point1.X, (int)point1.Y, (int)ballTexture.Width, (int)ballTexture.Height), Color.White);
                point1 += plusequals;
            }

            spritebatch.End();
        }
    }
}

```
> 1 votes

---
Tags: xna, c#, rotation
---


# Question
Title: How to display three dimensional Objects in a 2D Game using OpenGL and orthographic Projection?
I am creating a 2D (2.5D) game using OpenGL and orthographic projection.

It is simple to have relatively flat objects, e.g. characters. I simply use a quad with a texture of the character and move that about.

However, what is the best way to draw big objects that have depth, e.g. a big house? Do I use one quad with a three dimensional looking represantation of the house on it, or do I use multiple quads (e.g. front, side, top)?

I prefer using one quad with a three dimensional looking texture on it. What are the drawbacks to this approach?

# Answer
> 1 votes
Having done both, I can say that using a single quad is best in circumstances where none of your larger objects take up more than one grid square and/or are square/cube-shaped. Otherwise, you will eventually run into Z-sorting issues.

The multiple-quad solution was the best one that I found to deal with that particular situation. IE, if you had larger, irregular-shaped objects it was best to slice them into quads that represented each grid square that they occupied.

It ultimately depends on your engine; the former is the easier, but it won't work in all situations. The latter will, but may be overkill for the type of game you're doing.

---
Tags: opengl, 2d
---


# Question
Title: Efficient container(s) for units in an 2D RTS game
As the title says, I'm toying around with developing a 2D space RTS game. All of my units are spaceships that basically just shoot at one another, but they have to do a variety of other things as well: they have to "discover" (notify, draw, etc) other ships and planets not owned by the owner of this ship and within the arbitrary range of the ship's "scanners" (since they would otherwise be hidden), and if the ship is told to fire on an enemy ship, it needs to find the closest enemy (and fly to it if out of shooting range), and then shoot it obviously.

I've been wondering what efficient data containers could I use for the ships if there is going to be a large number of ships (100s to maybe 1000s) and why them? Also to note, is that ships must be distinguished by their owner (I may go to war with one player, so I obviously do not want my ships to search for ships of other players), where ownership will probably be represented by some integer (1 = player 1, 2 = player 2, etc) or maybe the unique pointer/memory address of a "player" object (0x4ff = player 1, 0x5ea = player 2, etc) or some other simple identifier.

I initially thought about using an array of vectors (C++), with the index of the array representing the player and each vector being the ships belonging to that player; then take all ships belonging to whatever player you are at war with and place them into a priority queue, whose root would be the enemy ship closest to a specific (friendly) ship and decide if its in range or not, but this seemed far too slow and memory-expensive, and didn't really address how to scan for ships/planets.

I then read up a few related posts about quadtrees and this lead me to other such tree data structures, like R-trees, that are also used for optimal spatial queries, but I do not quite understand exactly how they work and whether or not they would be best for me, so here we are.

# Answer
Use an influence map for target searching. Have a grid and on each node, reserve a spot in a collection of units for each team.

For each unit, generate a collection of coordinates within range and offset these coordinates as the unit moves. When a unit searches for a new target, enumerate over its coordinates within range. If another unit is on one of these coordinates, then that unit is within range.

Check this video out for visualization: https://www.youtube.com/watch?v=MEd6XV2Pecw.

I used this method for attack behaviors between about 1000 objects on 4 teams shown here: https://www.youtube.com/watch?v=y\_ewoxlZlgc.

This target searching should be used as a broadphase. Once a target is acquired, range checks should still be done for more accuracy but the overhead for that is so small it's insignificant.
> 1 votes

---
Tags: c++, data-structure, quadtree, space-partitioning
---


title: Tiled - move all tiles

text:
# Question
Title: Tiled - move all tiles
I'm making a map in Tiled.

I quickly ran out of room in the north of my map and would like to "shift" the tiles down. I'd prefer not to have to redo each of the tile layers.

Is this possible?

This is a picture of my minimap. I'd like to move them down around the red square.

# Answer
You can choose the selection tool at the top, select all the tiles you want to move then press ctrl + x to cut and press ctrl + v to paste it where you want.
> 3 votes

---
Tags: html5, tilemap, html-canvas, tiles
---


# Question
Title: C++ SFML and Box2D: Move world or move player?
I'm currently making a top-down shooter game and it's my first time developing with SFML. I came across and issue and I want to know if there is a better way to solve it.

I need to get the "camera" to move around with the player. I can think of two ways to do this: 1) move the world around the player and keep the player in the same spot to keep the illusion that the player is moving. Or 2) actually make the player move and have the camera follow. The problem with the latter is that (as far as I'm aware) there isn't any way to move the SFML "camera" because there isn't one, it just draws stuff on the window according to where you tell it to, so I have to go with the first option. The reason I'm asking this on here is to see if anyone can recommend a better method because I'm fearful that by moving the world it will mess with the physics and drastically effect the performance of the game.

# Answer
You're right, it can be done in two ways:

-Moving the player -Moving the world

This seems like a 50-50 deal. It doesn't matter how you do it, right?

I don't agree. I would ALWAYS suggest moving the player. Because if you choose to move the world now, and a few months further on in development, when you have enemies, npc's, and other entities on screen, you might change your mind about the camera. You might want to center the camera on an enemy for a second. You might want to center the camera on a door that's opening because of the button you're standing on (Legend of Zelda, anyone?). You also might decide that you don't want to center the camera on the player, but you want it centered between your character and the crosshair (if you don't understand what I mean by that, check out "Soldat", it's a fun little shooter).

Anyway, long story short: Flexibility is added by moving the player.
> 1 votes

---
Tags: c++, box2d, movement, sfml
---


# Question
Title: Monogame / XNA - Multple 2D Cameras (Rectangle) on screen
I recently started building a simple 2D roguelike game using Monogame 3.4. I was keen on building the game "engine" myself as I saw it as a fun learning curve. Monogame was pretty much the best option for me to get started as I'm a C# dev by profession. After getting my sprite to run around on the screen, I figured I probably need a proper level to continue with the more interesting stuff. So I decided to build a level builder for the game.

I've been struggling and digging around tutorials regarding building a 2D Camera.

I used this camera tutorial and I preferred this specific implementation. My only problem is, currently, I have two Rectangles (Cameras) on my screen.

The Rectangle on the left represents a scrollable panel with all the available sprites but is also a sort of overlay. Underneath it, the level "map" is drawn. My question is simply, how would I enable my level Rectangle to scroll past the overlay to view the left-hand side of it, which is currently being obscured by the panel.

Relevant code files are here

I would appreciate all the help I can get. Thanks!

# Answer
> 1 votes
Managed to fix this by using Viewports when drawing the Rectangles / Cameras

```
        GraphicsDevice.Viewport = new Viewport(_level);

        spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.PointClamp, null, null, null, _camera.ViewMatrix);
        DrawLevelTiles();
        spriteBatch.End();

        GraphicsDevice.Viewport = new Viewport(_panel);

        // draw panel
        spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.NonPremultiplied, SamplerState.PointClamp, null, null, null, null);
        _spritePanel.Draw(spriteBatch);
        spriteBatch.End();

        // draw tiles to panel
        spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.PointClamp, null, null, null, _panelCamera.ViewMatrix);
        DrawTiles();
        spriteBatch.End();

```

---
Tags: xna, c#, 2d, camera, monogame
---


# Question
Title: Where are the files UnityEngine.dll and UnityEditor.dll located on a Windows filesystem?
Visual Studio can't find the UnityX.dll files after I copied my assets folder from one computer to another. Where can I find these .DLLs?

* UnityEditor.dll
* UnityEditor.iOS.Extensions.XCode.dll
* UnityEngine.dll
* UnityEngine.UI.dll

# Answer
> 7 votes
* `UnityEngine.dll` and `UnityEditor.dll` can be found `Editor\Data\Managed` subfolder of your Unity installation.
* `UnityEditor.iOS.Extensions.XCode.dll` is in `Editor\Data\PlaybackEngines\iossupport` and
* `UnityEngine.Ui.dll` is in `Editor\Data\UnityExtensions\Unity\GUISystem\Standalone`

---
Tags: windows, visual-studio, unity, dll
---


# Question
Title: WebGL techniques for normal mapping on morph targets?
I'm currently morphing some meshes by interpolating their positions and normals between target arrays, on the GPU, in WebGL.

Now I need to apply normal maps to those morphs.

For normal maps on static meshes, I'm computing the vertex tangent vectors in JavaScript, which I then use in the shader for the normal mapping math.

For morphs, what I was about to do was compute those tangents for each morph target, then include those in the morph interpolations within the shader morphing routine, so that at every instant we have interpolated tangents with which to do the normal mapping.

Does anyone have experience with this? Does this seem reasonable? Know any examples out there I should look at?

# Answer
> 2 votes
You can interpolate tangents just like you would everything else, there should be no problems with that, as long as your mesh (morph target) count is low - I think there was a rather low limit on how many attribute slots you can use (GLES2.0 says there must be at least 8, Chrome seems to have 16).

An alternative (if you can take the pressure on the pixel shader) is to try doing normal mapping without precomputed tangents:

That would likely take even more pressure off your vertex shaders/attribute channels (no need to pass tangents or even normals) so you could blend even more meshes together.

---
Tags: animation, webgl
---


title: Audio slider doesn't change value

text:
# Question
Title: Audio slider doesn't change value
For some reason, my slider and audio resets back to 0 when I stop and play the game after I changed the value. Here is the code, I can't spot anything wrong with it:

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

public class MainAudio : MonoBehaviour {

public Slider slider;

void Awake()
{
    PlayerPrefs.Save ();
    GetComponent<AudioSource> ().volume = PlayerPrefs.GetFloat ("CurVol");
    if (slider)
    slider.value = GetComponent<AudioSource> ().volume;
}
public void VolumeControl(float volumeControl)
{
    GetComponent<AudioSource> ().volume = volumeControl;
    PlayerPrefs.SetFloat ("CurVol", GetComponent<AudioSource> ().volume);
    PlayerPrefs.Save ();
}
}

```

# Answer
> 0 votes
You can use the `Update` method to update the current volume.

```
private void Update()
{
    VolumeControl(slider.value);
}

```

And use the `OnApplicationQuit` method to save your current volume to the PlayerPrefs. Receiving the saved volume from the PlayerPrefs in the `Awake` method can be done like in your code snippet, but without the `PlayerPrefs.Save` statement.

---
Tags: unity, c#, scripting, audio, ui-design
---


# Question
Title: RPC's in Legacy Unity, what to use in Unity 5.1?
I have created a small experiment in 5.1, a server has an AI character pathfinding around a map over a grid, so its a straight line node to node before it reaches the end.

I would like for the client to also view this pathfinding character.

Using the networking scripts built in it sends fine, however the client see's a stuttering character and not something smooth like the server sees. So my solution to this is that when the server calculates the new node for the character to go to that the location of this node is sent to the client, the client moves its character to the node and so on. So instead of constant transform data being sent, the clients AI can go to the node and wait for the next node location to be sent, therefore being smooth.

In previous versions of Unity I would've used RPC's, but this is labelled as Legacy now, what can I use now to send a node location from the server to the client?

# Answer
> 2 votes
Reading more into this area I have come across Client RPC calls covered here ... http://docs.unity3d.com/Manual/UNetActions.html

ClientRpc calls are sent from objects on the server to objects on clients. They can be sent from any server object with a NetworkIdentity that has been spawned. Since the server has authority, then there no security issues with server objects being able to send these calls. To make a function into a ClientRpc call, add the \[ClientRpc\] custom attribute to it, and add the “Rpc” prefix. This function will now be run on clients when it is called on the server. Any arguments will automatically be passed to the clients with the ClientRpc call..

ClientRpc functions must have the prefix “Rpc”. This is a hint when reading code that calls the method - this function is special and is not invoked locally like a normal function.

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


title: How to design parameters for events

text:
# Question
Title: How to design parameters for events
I'm working on the event system for my engine, and have some trouble deciding what types of parameters my events should have to be both generic and specific at the same time. I want to be able to notify entities in the world about anything that is happening using something similar to the observer pattern, but merely the notification message itself is not enough, some messages need to carry additional information such as location, radius, damage, and so on. How do I encapsulate all these different kinds of parameters in one event type without making it very bloated like it would be if every event held a field for every type of parameter?

Some examples to show what I would like to achieve and what I have considered so far:

```
struct Event {
    TYPE     type;
    int      x, y, z;
    unsigned radius;
    float    damage;
    unsigned cost;
    float    healing;
    ...
void Observer::notify(Event event) {
    if (event.type == explosion)
        handle_explotion(event.x, event.y, event.z, event.damage);
    else if (event.type == healing)
        add_hitpoints(event.healing);
    ...

```

That would make the `Event` type very bloated, and the handling gets tedious quickly. I considered having fewer parameters, but they would remain unspecified:

```
struct Event {
    int arg1, arg2, arg3, arg4;
    const char * str1, str2, str3;
    bool b1, b2, b3;
    ...

```

This would cut down on the amount of parameters because all types are condensed into the same few fields. However from a user point of view this approach is much worse because now I have to remember what each parameter was supposed to represent every time; was `arg3` the radius or the damage in an explosion? To fix this maybe the parameters could live in a `std::map`, but that still makes handling obnoxious:

```
struct Event {
    std::map<const std::string, int> int_data;
    std::map<const std::string, float> float_data;
    ...
void Observer::notify(Event event) {
    if (event.type == collision)
        resolve_collision(event.int_data["x"], event.int_data["y"],
                          event.int_data["z"], event.int_data["width"],
                          event.int_data["height"]
    ...

```

I considered making the event hold some kind of general data field that can be cast to the appropriate type:

```
struct Event {
    void * data;
    TYPE type
};
void Observer::notify(Event event) {
    if (event.type == weapon_augment)
        modify_weapon((Weapon *)(event.data));

```

This makes instantiating and deleting the event somewhat more tedious, but at least it allows me to use specific types for every event handler.

What is the conventional approach to solving this problem? Even better, what is your own ingenious solution? Thanks.

# Answer
Don't shove all the events into one type. You are using C++, a language that supports Abstract Data Types. Use them!

**Inheritance/Interfaces**

```
struct Event {
    TYPE type;
    virtual void Handle() = 0;
};

struct DamageEvent : Event {
    float damage;
    int target;
    void Handle() final {
        FindTarget(target).TakeDamage(damage);
    }
};

void Observer::notify(Event event) {
    if (/* event.type needs to be handled here */) {
        event.Handle();
    }
}

```

One thing you need to watch out for here is **object slicing**. You'll need to store pointers to events, instead of by value in containers; preferably using smart pointers e.g. `std::vector<std::unique_ptr<Event>>`

**Unions**

```
struct Event {
    TYPE type;
    union {
        struct {
            float damage;
            int target;
        } damage;
        struct {
            int x, y, z;
            unsigned radius;
            float damage;
        } explosion;
        // ...
    };
};

void Observer::notify(Event event) {
    switch (event.type) {
    case EVENT_DAMAGE:
        FindTarget(event.damage.target).TakeDamage(event.damage.damage);
        break;
    // ...
    }
}

```

Note that by using a union, those data members take up the same memory, so adding more event types does not increase the size of `struct Event`. Instead, it is as big as it needs to be, to fit the largest type of event. They're useful if you need to avoid dynamic memory for some reason. Outside of C where it is used to fake inheritance, it's kind of rare in C++. But at least you're dealing with real variable names instead of `argN`.
> 4 votes

# Answer
Another way you could go about it by using a "generic" map for your parameters:

```
int HashStringToInt(const std::string& aStringToHash) {
  // Hash your string here
}

union Value
{
  int _int;
  double _double;
  bool _bool;
};

struc Event
{
  int _id;
  std::map<int, Value> _parameters;
};

void
boom()
{
  static const int EVENT_EXPLOSION = HashStringToInt( "EVENT_EXPLOSION" );
  static const int PARAM_X         = HashStringToInt( "PARAM_X"      );
  static const int PARAM_Y         = HashStringToInt( "PARAM_Y"      );
  static const int PARAM_Z         = HashStringToInt( "PARAM_Z"      );
  static const int PARAM_DAMAGE    = HashStringToInt( "PARAM_DAMAGE" );

  Event event;
  event._id = EVENT_EXPLOSION;
  Value param;
  param._double = 2.5;
  event._parameters[PARAM_X] = param;
  param._double = 1.4;
  event._parameters[PARAM_Y] = param;
  param._double = 0.0;
  event._parameters[PARAM_Z] = param;
  param._double = 200.0;
  event._parameters[PARAM_DAMAGE] = param;

  // fire your event
}

void Observer::notify(Event event)
{
  static const int EVENT_EXPLOSION = HashStringToInt( "EVENT_EXPLOSION" );
  static const int PARAM_X         = HashStringToInt( "PARAM_X"      );
  static const int PARAM_Y         = HashStringToInt( "PARAM_Y"      );
  static const int PARAM_Z         = HashStringToInt( "PARAM_Z"      );
  static const int PARAM_DAMAGE    = HashStringToInt( "PARAM_DAMAGE" );

  if ( event._id == EVENT_EXPLOSION )
  {
    // fetch the values back from the event parameters map and
    // process the explosition
  }
}

```
* I'm using hashed strings because comparisons are faster between ints than between strings.
* You can pas the events by copy, by ref, by unique\_ptr, by shared\_ptr, whatever suits your needs.

Pros of this way of doing it:

* **very** loosely coupled events and parameters: **there is absolutely no link between the sender and the receiver of the event**, read: *you don't need to include a header that describes the event structure in the event sender and the event receiver*.
* Events are copyable (off course, there is a cost)
* You get only what you need (you don't get what you don't need)

Cons:

* using strings as basis for parameters and events names may cause some small issues if you misspell some values
* wrongly using the union may get unexpected values (put an int, get a double.. you'll mess up in this case; please note: this is an issue with the union, not with the design); take a look at boost::variant for an improvement on this
* your hash algorithm has to be good enough to avoid collisions in event names, and in parameter names within an event (you started by using strings, if you're comfortable with the overhead, you could use straight strings instead of hashes)

As you see, there seems to be more *cons* than *pros*, but the first *pro* is a real one, IMHO, so it's worth considering :)
> 1 votes

---
Tags: c++, events, messaging
---


# Question
Title: ETC1 Support on android alpha problem (GLSL cocos2d-x)
I want to support etc1 in my game, but somehow it doesn't work (I'm using cocos2d-x

C++

```
 GLProgram* glp = new GLProgram();

glp->initWithVertexShaderFilename("testv.vsh", "test.fsh");
glp->addAttribute(GLProgram::ATTRIBUTE_NAME_POSITION, GLProgram::VERTEX_ATTRIB_POSITION);
glp->addAttribute(GLProgram::ATTRIBUTE_NAME_COLOR, GLProgram::VERTEX_ATTRIB_COLOR);
glp->addAttribute(GLProgram::ATTRIBUTE_NAME_TEX_COORD, GLProgram::VERTEX_ATTRIB_TEX_COORD);
glp->link();
glp->updateUniforms();

Texture2D* tex = Director::getInstance()->getTextureCache()->addImage("MenuButton_alpha.pkm");

GL::bindTexture2DN(1, tex->getName());
GLuint t1Location = glGetUniformLocation(glp->getProgram(), "tex1");
glp->setUniformLocationWith1i(t1Location, 1);

MySprite->setShaderProgram(glp);

```

.vsh

```
attribute vec4 a_position;
attribute vec2 a_texCoord;
attribute vec4 a_color;

varying vec4 v_fragmentColor;
varying vec2 v_texCoord;
varying vec2 v_texCoord2;

uniform sampler2D tex1;

void main()
{
    gl_Position = CC_MVPMatrix * a_position;
    v_fragmentColor = a_color;
    v_texCoord = a_texCoord;
    v_texCoord2 = v_texCoord;

}

```

.fsh

```
varying vec4 v_fragmentColor;
varying vec2 v_texCoord;
varying vec2 v_texCoord2;

uniform sampler2D tex1;

void main()
{
    vec3 tex = texture2D(CC_Texture0, v_texCoord).rgb;

    float alpha = texture2D(CC_Texture1, v_texCoord2).a;

    gl_FragColor = vec4(tex.rgb,alpha);
}

```

Somehow it shows my sprite in the middle but the transparent part is black. can anyone help me?

# Answer
> 1 votes
You need to check two things:

**1.Texture** **and** **Shader**

ETC1 doesn't support alpha.

You'd have to use a separate texture read (which you seem to be doing on texture2D(CC\_Texture1, v\_texCoord2). You can use tools to extract alpha channel from a RGBA texture and use a single texCoord for both samplers. Your code could be something like this:

```
vec3 tex = texture2D(CC_Texture0, v_texCoord).rgb;
float alpha = texture2D(CC_Texture1, v_texCoord).a; <- use same coord

```

Check this link for more info on ETC1 and alpha: http://malideveloper.arm.com/develop-for-mali/sample-code/etcv1-texture-compression-and-alpha-channels/

**2. Blending**

You'll also need to set blending. I don't know how to do that in Cocos2D, but in OpenGL it would be something like this:

```
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRCALPHA);

```

Now, if you want a texture compression that supports alpha you can use ETC2 (all opengl es 3 devices support it), and for better performance and quality ASTC. Not many devices support it now but the quality difference from ASTC to ETC1 is brutal, plus ASTC supports alpha.

---
Tags: c++, shaders, glsl
---


# Question
Title: GLSL Fragment shader lighting lambert term
Just a simple question: Should I or should i not normalize the SurfaceToLight vector to calculate the lambert term on a GLSL lighting shader?

I mean, here:

```
vec3 CalculateLights ( void )
{
vec3 OverallResult = (AmbientLight.Color * AmbientLight.Intensity * Material.Ambient.xyz );
vec3 SurfaceToCamera = WorldFragPosition - CameraPositionWorld;

// Apply point lights
for ( int LightIndex = 0; LightIndex < PointLightCount; ++LightIndex )
    {
    vec3 LightResult = vec3 ( 0, 0, 0 );
vec3 SurfaceToLight = PointLights[LightIndex].Position - WorldFragPosition;

float Distance = length ( SurfaceToLight );
if ( Distance > PointLights[LightIndex].Cutoff )
    continue;

// Calculate normalized vectors and Lambert term
vec3 NormalizedFragVertexNormalWorld = normalize( fragVertexNormalWorld );
vec3 NormalizedSurfaceToLight = normalize( SurfaceToLight );
//  float LambertTerm = max( dot( NormalizedSurfaceToLight, NormalizedFragVertexNormalWorld ), 0 ); // Should I use normalized here?
float LambertTerm = max( dot( SurfaceToLight, fragVertexNormalWorld ), 0 ); // Should I use normalized here?

// Compute the diffuse term.
vec3 DiffuseResult = LambertTerm * PointLights[LightIndex].Intensity * PointLights[LightIndex].Color * Material.Diffuse.xyz;
LightResult += DiffuseResult;

// Compute specular
//  float SpecularCoefficient = 0.0;
//  if ( LambertTerm > 0.0 )
//      SpecularCoefficient = pow ( max ( 0.0, dot ( SurfaceToCamera, reflect(-SurfaceToLight, NormalizedFragVertexNormalWorld))), Material.Shininess);
//  vec3 SpecularResult = SpecularCoefficient * Material.Specular.xyz * PointLights[LightIndex].Color;
//  LightResult += SpecularResult;

// Compute attenuation
float Attenuation = PointLights[LightIndex].ConstantAttenuation + PointLights[LightIndex].LinearAttenuation * Distance + PointLights[LightIndex].ExponentialAttenuation * pow ( Distance, 2 );

//  float Attenuation = 1.0 / (1.0 + PointLights[LightIndex].ConstantAttenuation * pow(Distance, 2));
LightResult /= Attenuation;
OverallResult += LightResult;
    }

return OverallResult;
}

```

As you can see, i've been trying out some different formulas on this shader. Specular still does not work. Here is the normalized and non-normalized versions of the image

# Answer
> 1 votes
Of course you should normalize it - it isn't the Lambert term if it isn't normalized.

Lambert term = max(cos(angle between direction to light and surface normal),0)

And (in HLSL-ish pseudocode): `dot(A,B) = cos(angle(A,B)) * length(A) * length(B)`

So to get `dot(A,B) = cos(angle(A,B))`, length of both vectors must be equal to 1 (which is what normalization does - divides a vector by its length).

https://en.wikipedia.org/wiki/Lambert's\_cosine\_law

# Answer
> 0 votes
Yes, you should always normalize light computation vectors.

`dot(N, L) = cos(angle(N, L)) * length(N) * length(L)`, so, if vectors are normalized `max(0.0, dot(N,L))` will get you values in the range of \[0,1\] which is exacly what you want.

0 being light perpendicular to surface normal, 1 being light pointing exaclyt at the same direction of normal (thus giving most contribution). Negative values means light is hit the back of surface, thus the need o max(0.0, dot()).

A few things worth noting:

**1. Linear and Gamma Space**

Monitors use a non-linear color space (gamma), so you should be aware of this or your light will appear darker. Textures that come from programs are already written in gamma space and you should convert them to linear space to compute lighting and after lighting done you should convert final result to gamma again.

Now you either use an sRGB texture and framebuffer extension to do this automatically for you or you need to do this in your shader.

So, for instance, you'd have to do:

```
vec3 finalCol = do_all_lighting_and_shading();
return vec4(pow(finalCol, 1.0 / 2.2), pixelAlpha);

```

For more information on linear and gamma space check this link: The Importance of Being Linear, and this is how to add sRGB extension to do gamma/linear conversion automatically for you: Using sRGB color space with OpenGL.

**2. A word on Specular**

I see you're using Reflect vector to compute specular. A better approach is to use **Half** vector. Check this: https://en.wikipedia.org/wiki/Blinn%E2%80%93Phong\_shading\_model

---
Tags: glsl
---


# Question
Title: Unity 5 Client RPC call: Failed to Invoke ClientRpc
I have a Unity 5 client and server running. On the server a path is generated and I want the client to receive the position of each target node on this path. Following the Client RPC calls section here http://docs.unity3d.com/Manual/UNetActions.html I have created the following script:

```
public class AccessingTargetPos : NetworkBehaviour {

[ClientRpc]
void RpcPosFromServerToGoTo(Vector3 pos)
{
    UnityEngine.Debug.Log ("Going to ... " + pos);
}

public void PrintPath(Vector3 pos)
{
    if (isServer)
    {
        UnityEngine.Debug.Log (pos);
        UnityEngine.Debug.Log("Send Pos ...");
        RpcPosFromServerToGoTo (pos);
        UnityEngine.Debug.Log("Sent!!");

    }
}

}

```

Both the client and the server have this script, assigned to a game object. However with the above I receive the following in my console:

At the moment all I want is for the client to output the positions received. When I get this I'll move on. I have followed the link, where have I went wrong here?

# Answer
> 1 votes
My problem here was not reading the RPC calls section of http://docs.unity3d.com/Manual/UNetActions.html properly. "They can be sent from any server object with a NetworkIdentity that has been spawned." When I had the client object reading in the locations become a spawned object under Registered Spawnable Prefabs (under Spawn Info, under Network Manager Script from Unity 5) then the RPC was called. I was calling the RPC on a static object before hand, throwing up the errors seen above.

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


# Question
Title: How can I set up a pixel-perfect camera using OpenGL and orthographic projection?
I am creating a 2D game using OpenGL and orthographic projection. For sprites, I use textured quads (actually two triangles).

I want the pixel art textures for the sprites to be displayed in a multiple of the original size to avoid blurry textures.

How can I set up a pixel-perfect camera using OpenGL and orthographic projection? After doing so, how do I size the qauds?

# Answer
**Please take note that the question was unclear and changed meaning 3 times, hence the 3 answers in one**

## How can I verify that a given size is a multiple of another?

This is a very good case to use the Modulo operator.

Let's say you have a texture `tex` with size `(width, height)`. Now you want to render the texture with size `(drawWidth, drawHeight)` on the screen. You can verify that the draw size is a multiple of the original texture size using the following test:

```
if (drawWidth % tex.width == 0 && drawHeight % tex.height == 0
    && drawWidth != 0 && drawHeight != 0) {
    // Render the texture
}

```

*We need to test if `drawWidth` and `drawHeight` are not 0 because 0 modulo anything will return 0.*

The Modulo operator returns the remainder of an integer division. So let's say your texture is 64x64, like in your question, and you want to render it with size 127x234:

```
64 % 127 = 63 (1 remainder 63) // This will fail the test
64 % 234 = 42 (3 remainder 42) // This will fail the test too

```

But using a multiple (for example, 128x192) gives the following result:

```
64 % 128 = 0 (2 remainder 0) // Pass
64 % 192 = 0 (3 remainder 0) // Pass

```

If you want to keep the ratio (always draw a square if the texture is a square, or always draw 2x3 if the texture has a ratio of 2x3), you can add the following to the condition:

```
if (drawWidth % tex.width == 0 && drawHeight % tex.height == 0
    && (drawWidth / tex.width) == (drawHeight / tex.height)
    && drawWidth != 0 && drawHeight != 0) {
    // Render the texture
}

```

This will test if the ratio is the same as the original image. The division will always return an integer value because both modulos returned 0.

## How can I render these sizes without them being blurry in my viewport?

**NOTE: This only needs to be applied if your camera viewport is not alreay pixel-perfect.**

Let's say you have a viewport with the following attributes:

```
screenWidth  // Width of the screen, in pixels
screenHeight // Height of the screen, in pixels
viewWidth    // Width of the OpenGL viewport
viewHeight   // Height of the OpenGL viewport

```

To render your texture with size `(drawWidth, drawHeight)`, you have to calculate the ratio of the pixels compared to the viewport:

```
ratioX = viewWidth / screenWidth;
ratioY = viewHeight / screenHeight;

```

`ratioX` and `ratioY` tells you how many units the viewport spans in 1 pixel. If your camera spans from -1 to 1 on the X axis (default OpenGL camera), and your screen width in pixels is 1024, then the ratio will be `2 / 1024 = 0.00195...`, which tells you that for each pixel on the screen, the OpenGL position increments by that amount.

You then need to multiply your `drawWidth` and `drawHeight` with those ratios:

```
drawWidth *= ratioX;
drawHeight *= ratioY;

```

This will give you pixel-perfect rendering of textures. If you want to take into account a texture position, you can multiply your `drawX` and `drawY` the same way to scale it.

## How can I setup a pixel-perfect camera then?

It is simple to setup a pixel-perfect orthographic projection. You only need to modify 2 matrices in OpenGL (legacy):

```
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glViewport(0, 0, screenWidth, screenHeight);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glOrtho(0, screenWidth, 0, screenHeight, 1, -1); // Origin in lower-left corner
glOrtho(0, screenWidth, screenHeight, 0, 1, -1); // Origin in upper-left corner

```
> 4 votes

---
Tags: opengl, 2d, textures, sprites
---


# Question
Title: Evenly distributed checkpoints in a procedurally generated world?
Got a procedurally generated world. It's succinctly described as an undirected acyclic graph where vertices are junctions and edges weights/length note the amount of time/effort guesstimated to be needed by the current player to traverse between vertices.

Now, the thing is that I'm not a big fan of permadeath as a feature to be forced on the player. It is a great thing for gamers that enjoy the added challenge but a deterrent to casual players. So now I'd like to add checkpoints evenly distributed across an existing game world.

My rule is that I don't want any spot (vertex) on the map to be more than `T` distance away from the nearest checkpoint with the added constraint that I want the smallest number `k` of checkpoints possible.

So brute force is not going to work cause the real graph has thousands of vertices. Now I'm wondering if there is a heuristic that can get a pretty good equivalent of the optimal result. Given `k` or `T`, I'd like to find the best setup.

# Answer
> 4 votes
Looking at your image gives an idea of how this should work. Two points are apparent:

1. Endpoint nodes (those with only one connected neighbour) are the least likely to have checkpoints, since they share with the fewest other nodes; endpoint nodes will in fact only contain a checkpoint iff they are isolated as a degenerate DAG, i.e. they have no neighbours in which case they must serve as their own checkpoint.
2. Highest-order intersections, i.e. those providing a concourse to the most "arms" & "sub-arms" , are most likely to have checkpoints.

So... I would suggest a weight-based approach (this is a very rough answer as I'm pressed for time): assign a value of 1 to all end nodes. Walk "inward" from the end node. Now for the node you have walked to, look at all of it's neighbours that have already had a value assigned (at the start, just 1's) and make this node's value the sum of all of those. Repeat and continue. At each step, check whether you have met or exceeded `T`; if you have, cap the value at `T` (i.e. never allow any node's value to exceed T). As you get to intersections like the top left one marked in purple, you should start to get rather high values (if your graph is to be taken as a working result, then these would already have met or exceeded the value of `T`). Iterating further, ultimately those nodes directly between the purple nodes (four of them) will also be `T`. Thus your resultant graph is the purple intersections A & B, the two nodes between them, and B & C and the 2 nodes between those, or a linear graph of 7 nodes. This is a kind of "straight skeleton" or "watershed" as it is known in computational geometry or GIS, respectively. You are quite literally creating a watershed network out of the graph, that is, those edges closer in to the centre of the (mountain) network are highest up, whilst outlying ridges sit at a minimal height of 1 (sea level).

At this point, I suspect that selecting nodes off this skeleton in order to provide the best-spaced checkpoints should be a *reasonably* trivial exercise. Thousands of nodes or not (though hopefully down to hundreds by this point), graph operations are by their nature iterative and so the best you can do is `O(n)` in the number of nodes.

Of course the "skeleton" will not always be "straight", it may indeed branch. And that is as it should be if you want a workable solution for your game.\**

**EDIT** I missed your comment about distance being computer by sum of edge lengths. You can factor this into the above calculation: Endpoint nodes must then be represented as zero (which is the distance from edge) while inner node weights are distance to nearest endpoint.

# Answer
> 1 votes
There are two questions here:

1. How to assign the *fewest number of checkpoints*, so that every vertex is within at most T distance from some checkpoint.
2. How to spread those checkpoints *as evenly as possible*.

**Question 1 turns out to have a linear-time solution:**

First, fix some root node arbitrarily. If this is a level, then some start/spawn point makes a natural choice. Next we define...

```
UncoveredDistance(node)
{
  greatest = 0

  // Initialize least > 0. If least drops to/below 0, it tells us
  // this node is covered by a checkpoint deeper in its descendant tree.
  least = 1

  foreach (child of node)
  {
    distance = UncoveredDistance(node)

    // We'll use NaN as a special value to indictate this branch should be ignored.
    if(isNaN(UncoveredDistance(node)))
       continue;

    // Greatest represents the depth of the deepest node descended from
    // this one that is still not covered by any checkpoint.
    greatest = max(greatest, distance)

    // least represents the most "spillover" coverage from a checkpoint
    // placed deeper in the tree. (Represented as negative uncovered distance)
    least = min(least, distance)
  }

  // If the spillover completely covers the uncovered nodes in our descendant tree,
  // then this whole subtree is covered, with additional coverage to pass upward
  if(greatest + least <= 0)
     greatest = least

  // Include depth from node's parent, so we know whether to place a checkpoint
  // before the next hop takes us too far away.
  // (Treat the root as having a rootwardEdgeLength of 0)
  myDepth = greatest + node.rootwardEdgeLength

  // If no later checkpoint could cover this whole subtree, add one now.
  if(myDepth > T)
  {
     AddCheckpoint(node)
     myDepth = node.rootwardEdgeLength - T
  }

  // This whole subtree is already covered but without surplus,
  // so signal parent node to ignore this branch.
  if(myDepth > 0 && greatest <= 0 && least <= 0)
     return NaN

  // Pass upward any coverage surplus or shortfall we have.
  return myDepth
}

// Finally, kick off the process at the root:
if(UncoveredDistance(rootNode) > 0)
   AddCheckpoint(root)

```

I've shown a recursive version, but this can also be done in one linear scan by first sorting the nodes in topological order (depending on how you generate your graph, they might already be in such an order)

The trick is that this doesn't necessarily solve question 2, of spreading out the checkpoints equally. It puts off adding a checkpoint for as long as it can, which tends to pull all the checkpoints as close to the root as they can go. So some checkpoints may be arbitrarily close together, and intermediate nodes may be within T range of multiple checkpoints, even though the set of checkpoints is still minimal.

If this is a problem, there may be a post-process we can apply, given a minimal checkpoint set, to jiggle those checkpoints around the topology to a more even spacing.

# Answer
> 1 votes
Assuming we wish to have `N` checkpoints:

1. we being by randomly picking `sqrt(N)` vertices on the graph (possibly a tree).
2. We now pick `N` random distinct vertices. We compute the Dijkstra distances of each such randomly picked vertex from the closest existing checkpoint.
3. We then proceed to declare the winner as the one furthest away from any other existing checkpoint and add it to the set.
4. We now pick a "bad" checkpoint to remove by looking for the checkpoint closest to another checkpoint (there is a pair) and then compare by closeness to the second closest checkpoint.
5. We remove the "bad" checkpoint.
6. We repeat step (2) twice.
7. We go back to (4) until we have enough checkpoints.

# Answer
> 0 votes
I propose a recursive pseudo code aproach to use while creating the tree

Keep track of placed check points in a listlike structure:

```
stacked_check_point_collection

```

here comes the recursive method:

```
create_node(last_check_point_distance, current_node) //recursive method
add current_node to tree;
if last_chec_point_distance > T {
    /*check other checks point distance using stacked_check_point_collection */
    FOR_EACH check_point in stacked_check_point_collection
    {
        IF check_point distance from current_node < T {
            last_chec_point_distance = check_point distance from current_node
            found = true
            break //exit foreach loop
        }
    }
    if not found {
        /*place check point here*/
        SET CHECK POINT IN current_node
        last_chec_point_distance=0
        stacked_check_point_collection.ADD(current_node)
    }
}
foreach outgoing arc{
        create_node(last_chec_point_distance + arc.lenght, new node)
}

```

---
Tags: mathematics, graph
---