# Question
Title: Porting deprecated OpenGL to "modern" issues
In relation to my previous question: Rendering without VAO's & VBO's?

I came to realize that i have completely to port the example in modern OpenGL with VAO's and VBO's .

So their rendering function was this :

```
void renderTriangleModels()
{
  // Draw simulation model

  const ParticleData &pd = model.getParticles();
  float surfaceColor[4] = { 0.2f, 0.5f, 1.0f, 1 };

  if (shader)
  {
    shader->begin();
    glUniform3fv(shader->getUniform("surface_color"), 1, surfaceColor);
    glUniform1f(shader->getUniform("shininess"), 5.0f);
    glUniform1f(shader->getUniform("specular_factor"), 0.2f);

    GLfloat matrix[16];
    glGetFloatv(GL_MODELVIEW_MATRIX, matrix);
    glUniformMatrix4fv(shader->getUniform("modelview_matrix"), 1, GL_FALSE, matrix);
    GLfloat pmatrix[16];
    glGetFloatv(GL_PROJECTION_MATRIX, pmatrix);
    glUniformMatrix4fv(shader->getUniform("projection_matrix"), 1, GL_FALSE, pmatrix);
  }

  for (unsigned int i = 0; i < model.getTriangleModels().size(); i++)
  {
    // mesh
    TriangleModel *triModel = model.getTriangleModels()[i];
    const IndexedFaceMesh &mesh = triModel->getParticleMesh();
    Visualization::drawTexturedMesh(pd, mesh, triModel->getIndexOffset(), surfaceColor);
  }
  if (shader)
    shader->end();
}

```

And calls Visualization::drawTexturedMesh which is the following :

```
template<class PositionData>
void Visualization::drawMesh(const PositionData &pd, const IndexedFaceMesh &mesh, const unsigned int offset, const float * const color)
{
    // draw mesh
    const unsigned int *faces = mesh.getFaces().data();
    const unsigned int nFaces = mesh.numFaces();
    const Vector3r *vertexNormals = mesh.getVertexNormals().data();

    if (MiniGL::checkOpenGLVersion(3, 3))
    {
        glEnableVertexAttribArray(0);
        glVertexAttribPointer(0, 3, GL_REAL, GL_FALSE, 0, &pd.getPosition(offset)[0]);
        glEnableVertexAttribArray(2);
        glVertexAttribPointer(2, 3, GL_REAL, GL_FALSE, 0, &vertexNormals[0][0]);
    }
    else
    {
        float speccolor[4] = { 1.0, 1.0, 1.0, 1.0 };
        glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, color);
        glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, color);
        glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, speccolor);
        glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, 100.0f);
        glColor3fv(color);

        glEnableClientState(GL_VERTEX_ARRAY);
        glEnableClientState(GL_NORMAL_ARRAY);
        glVertexPointer(3, GL_REAL, 0, &pd.getPosition(0)[0]);
        glNormalPointer(GL_REAL, 0, &vertexNormals[0][0]);
    }

    glDrawElements(GL_TRIANGLES, (GLsizei)3 * mesh.numFaces(), GL_UNSIGNED_INT, mesh.getFaces().data());

    if (MiniGL::checkOpenGLVersion(3, 3))
    {
        glDisableVertexAttribArray(0);
        glDisableVertexAttribArray(2);
    }
    else
    {
        glDisableClientState(GL_VERTEX_ARRAY);
        glDisableClientState(GL_NORMAL_ARRAY);
    }
}

```

Assuming that I run the Demo with OpenGL 3.3 the if else isn't really required but I posted it anyway. So "translating" those functions to use VAO's and VBO's I have created the following.

```
void initVAO()
{
    glGenVertexArrays(1, &vao);
    glBindVertexArray(vao);
    glGenBuffers(3, vbo);
    glGenBuffers(1, &ibo);

    ParticleData &pd = model.getParticles();

    TriangleModel *triModel = model.getTriangleModels()[0];
    const IndexedFaceMesh &mesh = triModel->getParticleMesh();
    const unsigned int offset = triModel->getIndexOffset();

    const unsigned int *faces = mesh.getFaces().data();
    const unsigned int nFaces = mesh.numFaces();
    const Vector3r *vertexNormals = mesh.getVertexNormals().data();
    const Vector2r *uvs = mesh.getUVs().data();

    glBindBuffer(GL_ARRAY_BUFFER, vbo[0]);
    glBufferData(GL_ARRAY_BUFFER, pd.size(), &pd.getPosition(offset)[0],       GL_STATIC_DRAW);
    glEnableVertexAttribArray(0);
    glVertexAttribPointer(0, 3, GL_REAL, GL_FALSE, 0, BUFFER_OFFSET(0));
    glBindBuffer(GL_ARRAY_BUFFER, 0);

    glBindBuffer(GL_ARRAY_BUFFER, vbo[1]);
    glBufferData(GL_ARRAY_BUFFER, mesh.getUVs().size(), &uvs[0][0], GL_STATIC_DRAW);
    glEnableVertexAttribArray(1);
    glVertexAttribPointer(1, 2, GL_REAL, GL_FALSE, 0, BUFFER_OFFSET(0));
    glBindBuffer(GL_ARRAY_BUFFER, 0);

    glBindBuffer(GL_ARRAY_BUFFER, vbo[2]);
    glBufferData(GL_ARRAY_BUFFER,mesh.getVertexNormals().size(),
    &vertexNormals[0][0], GL_STATIC_DRAW);
    glEnableVertexAttribArray(2);
    glVertexAttribPointer(2, 3, GL_REAL, GL_FALSE, 0, BUFFER_OFFSET(0));
    glBindBuffer(GL_ARRAY_BUFFER, 0);

    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, (GLsizei)3 * mesh.numFaces(), mesh.getFaces().data(), GL_STATIC_DRAW);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);

    glBindVertexArray(0);
}

```

And I modified draw to this:

```
template<class PositionData> void drawTexturedMesh(const PositionData &pd, const IndexedFaceMesh &mesh, const unsigned int offset, const float * const color, GLuint text)
{
    // draw mesh
    const unsigned int *faces = mesh.getFaces().data();
    const unsigned int nFaces = mesh.numFaces();
    const Vector3r *vertexNormals = mesh.getVertexNormals().data();
    const Vector2r *uvs = mesh.getUVs().data();

    glBindBuffer(GL_ARRAY_BUFFER, vbo[0]);
    glBindBuffer(GL_ARRAY_BUFFER, vbo[1]);
    glBindBuffer(GL_ARRAY_BUFFER, vbo[2]);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo);

    //glDrawElements(GL_TRIANGLES, nFaces, GL_UNSIGNED_INT, BUFFER_OFFSET(0));

    glDrawElements(GL_TRIANGLES, (GLsizei)3 * mesh.numFaces(), GL_UNSIGNED_INT, mesh.getFaces().data());
}

```

-**If** the uncommented glDrawElements is used I get nothing, according to RenderDoc all Position values passed to shader are 0.

-**If** the commented one is used I get a shape which is not even nearly close to what the example draws.

Does anyone has any clue or tip on why this is happening? Or can you notice something different or wrong? Would appreciate it.

Thanks.

**Edit:** Le Comte du Merde-fou 's answer is indeed correct! I was giving the wrong size to the buffers. **Still** a wrong mesh is being generated.

I modified my code to this:

```
glBindBuffer(GL_ARRAY_BUFFER, vbo[0]);
glBufferData(GL_ARRAY_BUFFER, sizeof(Vector3r) * pd.size(), &pd.getPosition(offset)[0], GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_REAL, GL_FALSE, 0, BUFFER_OFFSET(0));
glBindBuffer(GL_ARRAY_BUFFER, 0);

glBindBuffer(GL_ARRAY_BUFFER, vbo[1]);
glBufferData(GL_ARRAY_BUFFER, mesh.getUVs().size() * sizeof(Vector2r), &uvs[0][0], GL_STATIC_DRAW);
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 2, GL_REAL, GL_FALSE, 0, BUFFER_OFFSET(0));
glBindBuffer(GL_ARRAY_BUFFER, 0);

glBindBuffer(GL_ARRAY_BUFFER, vbo[2]);
glBufferData(GL_ARRAY_BUFFER, mesh.getVertexNormals().size() * sizeof(Vector3r), &vertexNormals[0][0], GL_STATIC_DRAW);
glEnableVertexAttribArray(2);
glVertexAttribPointer(2, 3, GL_REAL, GL_FALSE, 0, BUFFER_OFFSET(0));
glBindBuffer(GL_ARRAY_BUFFER, 0);

glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, (GLsizei)3 * mesh.numFaces(), mesh.getFaces().data(), GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);

```

And my draw function to this:

```
// draw mesh
const unsigned int *faces = mesh.getFaces().data();
const unsigned int nFaces = mesh.numFaces();
const Vector3r *vertexNormals = mesh.getVertexNormals().data();
const Vector2r *uvs = mesh.getUVs().data();

glBindBuffer(GL_ARRAY_BUFFER, vbo[0]);
glBindBuffer(GL_ARRAY_BUFFER, vbo[1]);
glBindBuffer(GL_ARRAY_BUFFER, vbo[2]);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo);

glDrawArrays(GL_TRIANGLES, 0, nFaces);

```

It really has started getting under my skin... Is this a good porting according to the old code I posted???

I can provide more code if asked , but i cannot post it all since it's pretty big by now.

Thanks again.

**Update** So after banging my head long time, I decided to calm down. And I did what I hate to do . I opened up RenderDoc and started checking the vertices passed to GPU manually one-by-one in order to find why the mesh is screwed up. So in certain points i found values like vec3(0.97, 68548, 1) . Then I banged my head some more. And then I calmed down again and starting checking why those values show up. What I found out affects this line of code (on their side).

```
glVertexAttribPointer(0, 3, GL_REAL, GL_FALSE, 0, &pd.getPosition(offset[0]);

```

As you can see they use GL\_REAL which is typedef as GL\_FLOAT . Silly me they also have it typedefed as GL\_DOUBLE... So my Positions vertex was defined as GL\_DOUBLE while it was passed to the GPU as GL\_FLOAT. Changing it to GL\_DOUBLE almost gave me the expected result...

I still have an issue because some more triangles show up in the side of the mesh. I will update tomorrow to show the new mesh.

Thanks to Le Comte du Merde-fou 's again for the help in indicating that the size parameter was obviously wrong in GL\_BUFFER\_DATA.

# Answer
```
glBufferData(GL_ARRAY_BUFFER, pd.size(), &pd.getPosition(offset)[0],       GL_STATIC_DRAW);
glBufferData(GL_ARRAY_BUFFER, mesh.getUVs().size(), &uvs[0][0], GL_STATIC_DRAW);
glBufferData(GL_ARRAY_BUFFER,mesh.getVertexNormals().size(),
glBufferData(GL_ELEMENT_ARRAY_BUFFER, (GLsizei)3 * mesh.numFaces(), mesh.getFaces().data(), GL_STATIC_DRAW);

```

Assuming that .size() here returns std::vector::size, the first three of these are wrong. The second parameter of a glBufferData call is **the size of the data in bytes**, not the number of vertices or indices.

Even if .size() returns the correct value, the fourth is also wrong for the same reason.
> 2 votes

---
Tags: opengl, c++, vbo, vao
---


# Question
Title: Disabling and re-enabling the clicked child objects
I am currently working on 2D platform game. The following script adding the child objects inside the array and identifies the child object I click on and checks the tag on it. Now I don't know how to disable the child object that I have clicked and I want the disabled child object to be re-enable when I click on another child object inside the same parent object. Any help would be appreciated.

```
public class SelectedPlatform : MonoBehaviour {

    public GameObject platform;
    void Start()
    {
        Transform[] children = new Transform[transform.childCount];
        for (int i=0; i<transform.childCount; i++)
        {
            children[i]=transform.GetChild(i);
        }
    }

    void Update()
    {
        if(Input.GetMouseButtonDown(0))
         {
            RaycastHit2D hit = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector2.zero);

            if(hit.collider.gameObject.tag == "Platform")
            {
                Debug.Log ("Target Position: " + hit.collider.gameObject.transform.position);
            }
         }
    }
}

```

# Answer
I'd be tempted to handle this with two scripts:

```
// Put this on each container object:
public class ToggleableContainer : MonoBehaviour {

    ToggleableItem _currentSelection;

    // On initialization, find all toggleable children of this parent.
    void Start() {
       ToggleableItem[] children = GetComponentsInChildren<ToggleableItem>();
       // Let each child know who to talk to when they're clicked:
       foreach(var child in children)
           child.SetContainer(this);
    }

    // When one platform is clicked, disable it and re-enable the last selection (if any).
    public void Select(ToggleableItem target) {
       if(target == _currentSelection)
          return;

        if(_currentSelection != null)
            _currentSelection.gameObject.SetActive(true);

        if(target != null)
            target.gameObject.SetActive(false);

        _currentSelection = target;
    }
}

```

.

```
// Put this on each platform object you want to toggle between enabled/disabled:
public class ToggleableItem : MonoBehaviour {

    ToggleableContainer _container;

    // Allow the parent container to register itself.
    public void SetContainer(ToggleableContainer container) {
        _container = container;
    }

    // For simple click interactions, Unity will handle the raycasting for you
    // if you just implement a method to respond to the "OnMouseDown" message.
    void OnMouseDown() {
        // Tell our container we've been selected - it will handle coordinating the rest.
        if(_container != null)
             _container.Select(this);
    }
}

```
> 1 votes

---
Tags: unity, c#, 2d
---


# Question
Title: 3D collision physics. Response when hitting wall, floor or roof
I am having problem with the most basic physic response when the player collide with static wall, floor or roof. I have a simple 3D maze, true means solid while false means air:

```
bool bMap[100][100][100];

```

The player is a sphere. I have keys for moving x++, x--, y++, y-- and diagonal at speed 0.1f (0.1 * ftime). The player can also jump. And there is gravity pulling the player down. Relative movement is saved in: relx, rely and relz.

One solid cube on the map is exactly 1.0f width, height and depth. The problem I have is to adjust the player position when colliding with solids, I don't want it to bounce or anything like that, just stop. But if moving diagonal left/up and hitting solid up, the player should continue moving left, sliding along the wall.

Before moving the player I save the old player position:

```
    oxpos = xpos;
    oypos = ypos;
    ozpos = zpos;

    vec3 direction;
    direction = vec3(relx, rely, relz);

    xpos += direction.x*ftime;
    ypos += direction.y*ftime;
    zpos += direction.z*ftime;

    gx = floor(xpos+0.25);
    gy = floor(ypos+0.25);
    gz = floor(zpos+0.25);
    if (bMap[gx][gy][gz] == true) {

        vec3 normal = vec3(0.0, 0.0, 1.0); // <- Problem.
        vec3 invNormal = vec3(-normal.x, -normal.y, -normal.z) * length(direction * normal);
        vec3 wallDir = direction - invNormal;
        xpos = oxpos + wallDir.x;
        ypos = oypos + wallDir.y;
        zpos = ozpos + wallDir.z;
    }

```

The problem with my version is that I do not know how to chose the correct normal for the cube side. I only have the bool array to look at, nothing else. One theory I have is to use old values of gx, gy and gz, but I do not know have to use them to calculate the correct cube side normal.

# Answer
You need to detect which face you have collided with, penetration depth and then decide which way to resolve out. Essentially you don't have enough information to do what you need.

To do this you represent the cube faces as planes. That is a normal and dot product. You then calculate distance from the sphere position to the planes and choose the face with the smallest depth to resolve out of.

So if you have a plane pointing directly up it's normal would be vec3(0.0,1.0,0.0). Depending on where the plane is its offset would be the planes height so for a cube on the floor, 1m high the offset would be 1. The cube face on the floor would be vec3(0.0,-1.0,0.0) and offset zero.

You then calculate penetration depth of your sphere. This is simply the dot product between the normal & sphere position. So if your sphere is at (3.0,6.9,1.4) then the dot product with the top plane is 6.9. Subtract the offset of 1 and you get a distance of 5.9. So if the sphere has a radius \> 5.9 then you have an intersection. Penetration depth is radius - distance to resolve out. Collision normal is the normal of the face Vec3(0.0,1.0,0.0).

Now that you have the resolution depth & normal you can r solve the sphere out as well as adjust velocity to remove the velocity towards the cube face. This is something like NewVel = OldVel - facenormal\* Dot(facenormal,OldVel)

You'll have to check the maths because I'm writing this on iPad.

That's how you, basically, resolve sphere and plane collisions. However this is a rabbit hole you are going down.

Far smarter is to use a Physics library to do this. You'll get better results and it'll save you a ton of time.
> 2 votes

# Answer
Forgive me if I didn't understand your question (just comment below and I can modify my answer) but it sounds like what you need to implement is something like a "Slide along wall" if you detect that the player is going to hit a wall.

Usually I would implement this as a swept-sphere against plane test, or a capsule for plane test. I'm sure you can find source code for this in Ericson's Real-Time Collision Detection book, where the source is free to download online.

The idea is to compute the closest point on a line-segment to each plane of a cube. This line segment is the center of one sphere to the center of the swept sphere. Then you compare the computed distance from segment to plane with the radius of the sphere itself.

If a collision is detected with a plane you can move your sphere to the time of impact, and then take the leftover translation and project it onto the collision plane. This would require some sort of "slide along wall" function. The slide along wall function can use projection or the outer product to perform a projection, whichever is your preference. Given a plane with the normal `u`, you can project any vector `v` onto the plane corresponding to `u` like so:

```
(I - (u * u))v

```

Where that * symbol is the outer product. The outer product produces a matrix. I believe the inner product form would look like:

```
v - u(u ∙ v)

```

Source: Stan Melax - Math for Game Programmers - GDC 2013
> 0 votes

# Answer
You dont need complex math for this simple thing. To get the slide collision response do this: move along x axis, if collision=true adjust x position (stop the x movement). Pick this new positon add y movement and test collision. If true adjust y position. Pick this new position and add the z movement adjust z movement in case of collision. The key to slide is move one axis at a time, adjusting positions.

Sorry my poor english...
> 0 votes

---
Tags: collision-detection, physics
---


# Question
Title: What does pressing CTRL do when editing a sprite sheet?
I have a multi-sprite sprite sheet. When I have a blue box selected, and I hold CTRL, the box turns green. I have played with it, but cannot figure out what it does. I checked the documentation, but I don't see anything about turning the boxes green.

What does holding CTRL when editing a sprite within a multi-sprite sprite sheet do?

# Answer
> 4 votes
Holding `ctrl` in the Sprite Editor allows you to manually move the pivot point with snapping. With `ctrl` pressed (or`cmd` on a Mac), you can snap the pivot to one of the pre-defined locations, as defined under *Pivot* on the control panel: *Center*, *Top Left*, *Top*, *Top Right*, *Left*, *Right*, *Bottom Left*, *Bottom* and *Bottom Right*.

---

The Unity manual does not mention this feature, though it does mention an alternate:

> ## Using the Editor
>
> **...**
> ...
> There are also settings for the sprite’s pivot, which Unity uses as the coordinate origin and main “anchor point” of the graphic. You can choose from a number of default rectangle-relative positions (eg, Center, Top Right, etc) or use custom coordinates.
> <sup>**\- Unity Manual: Sprite Editor**</sup>

---

If I may speculate, I would say this feature has been implemented for the purpose of consistency. The manual does not deliberately mention it, but pressing `ctrl` to enable pivot snapping is a feature I have seen in other programs, before. While Unity officially directs you to use the control panel, the shortcut key has likely been implemented for users who are already use to holding `ctrl`. Such implementations are often referred to as *external consistency*, and helps facilitate human-computer interaction.

---
Tags: unity, spritesheet
---


# Question
Title: For each array within array using UnityScript
I am trying to randomly generate some values for a character using Javascript in Unity.

I have two arrays, one for colour, and one for body type. I want to get one value out of each array, randomly, which so far I have achieved like this:

```
var colours = new Array('red', 'green', 'blue');
var bodyTypes = new Array('thin', 'average', 'fat');

var colLen = colours.length;
var colour = colours[Random.Range(0,colLen)];

var bodLen = bodyTypes.length;
var bodyType = bodyTypes[Random.Range(0,bodLen)];

Debug.Log(colour);
Debug.Log(bodyType);

```

This works fine, however I would like to optimise it slightly, by putting the two arrays into another array and then using a loop to get each value. So far I have tried this:

```
var colours = new Array('red', 'green', 'blue');
var bodyTypes = new Array('thin', 'average', 'fat');

var arrays = new Array(colours, bodyTypes);

for(var array in arrays) {
    var arrayLen = Random.Range(0, array.length);

    Debug.Log(array[arrayLen]);
}

```

This gives the error "Length is non a member of Object". Is there any way of achieving what I want to do? I am very new to any type of game development, so I don't really know the best way to go about it.

# Answer
Generally in javascript, you use `for`...`in` for objects. For arrays, you can use `forEach`. Like this:

```
var colours = new Array('red', 'green', 'blue');
var bodyTypes = new Array('thin', 'average', 'fat');
var arrays = new Array(colours, bodyTypes);

arrays.forEach(function(array, index,arrays) {
  var arrayLen = Random.Range(0, array.length);
  Debug.Log(array[arrayLen]);
})

```

...On a side note, I don't know if the `new Array()` constructor style is a Unity convention; if not, the typical JS way to define an array is just with `[]`.

```
var colours = ['red', 'green', 'blue']
var bodyTypes = ['thin', 'average', 'fat'];
var arrays = [colours, bodyTypes];

```
> 2 votes

---
Tags: unity, unityscript
---


# Question
Title: Occlusion culling of BV tree nodes behind terrain
So I have a bounding volume tree, almost an octree but not quite.

Anyway I'm trying to optimize my drawing, right now I have a few different culling frustums that I use to cull different ranges of the BV tree, its very fast, I can pull all my world data in less than 1ms but when it comes to culling the grass and the other mesh data I'm thinking that because I have lots of mountains and hill that I'm rendering stuff that is inside the frustum but occluded but hills and mountains.

What would be the right way to cull this? Should I do a ray cast against my terrain from each corner of the bounding boxes to the player and cull anything that gets a hit? or should I find some fancy way to do it on the GPU?.

I only have to test maybe 1k boxes x 8 corners, so the ray casting shouldn't take to long.

# Answer
Ok so after a few days of tinkering I found out that ray casting that much against my terrain is bad and slow, part of it is because the physics in run on another thread so syncing is hard and there was just way to much data so now I have setup some predicate query's and so far so good.

It works like this:

Fill Gbuffer-\> Do predicate query's using the bounding boxes from the frustum culled tree nodes-\> Finish the frame-\> Check if query's are done, if not then just draw the next frame as normal but if they are then on the next cpu update I use the returned predicate values when I cull the visible tree nodes.

The predicate query's run a few frames behind but that's ok as I only update the visible mesh data every 6 frames and I have it set so it only uses the predicate culling after as certain distance so it hides the lag well.

I was running at 45-75 FPS with an average of 55 FPS but now I'm at 65-90 FPS with an average of 78 FPS so its culling out lots of data.

I have a few things to ask about predication but ill start a new question for that.
> 1 votes

---
Tags: directx11, terrain, culling, occlusion
---


title: Word Puzzle: Less or more difficult

text:
# Question
Title: Word Puzzle: Less or more difficult
I'm working on an app which is a Word Puzzle. Player has to arrange about 10 words in correct order to solve it. I have two options to build it:

1. Give user feedback (right or wrong) when he has put **each** word
2. Give user feedback (right or wrong) when he has put **all** words

In first option, the player gets quick feedback (as early as putting first word). But it is easy to brute-force the puzzle and hence the difficult of the game is low. In second option, the player has to wait for long time (until he/she puts all words). But the puzzle is difficult to brute-force and the difficulty of the game is high. I'm not sure which option should I choose?

# Answer
There are a few options I'd suggest here. I'm assuming some sort of drag and drop UI since you say "arrange".

First, there is a third alternative in only showing when words are in the right order. So Word1 and Word2 are in order relative to themselves, but maybe they're in Spot3 and Spot4 respectively. Perhaps you lock the two as a single unit to move now.

Second, as the comment above suggest, use both and give the player a difficulty option.

Third, combine all of these options but only make them available in response to the player's interaction. The simplest implementation of this would be to enable the easier options after a certain number of failed attempts.

If you are collecting any metrics on your game, you may find a certain number of failures before people quit playing on average. Then you can time these easier mechanics to come into play before that point.
> 1 votes

---
Tags: game-design, algorithm, difficulty, word-games
---


title: DirectX 11 instance mesh performance

text:
# Question
Title: DirectX 11 instance mesh performance
Today my question is a about instance mesh performance in DX 11, the way I do my instancing is the standard way I think, its the same way I did it in XNA.

To start with each frame(every 2nd) I build a vertex stream filled with the world matrix for the mesh I want to instance, this second vertex stream is then set to the GPU with the mesh vertex buffer in slot 1, I have it set to InputClassification.PerInstanceData in the vertex element array.

Looks like this:

```
  Public Shared Elements As InputElement() = New InputElement() {New InputElement("POSITION", 0, DXGI.Format.R32G32B32_Float, 0, 0, InputClassification.PerVertexData, 0),
                                                              New InputElement("NORMAL", 0, DXGI.Format.R32G32B32_Float, InputElement.AppendAligned, 0, InputClassification.PerVertexData, 0),
                                                               New InputElement("BINORMAL", 0, DXGI.Format.R32G32B32_Float, InputElement.AppendAligned, 0, InputClassification.PerVertexData, 0),
                                                               New InputElement("TANGENT", 0, DXGI.Format.R32G32B32_Float, InputElement.AppendAligned, 0, InputClassification.PerVertexData, 0),
                                                                New InputElement("COLOR", 0, DXGI.Format.R32G32B32_Float, InputElement.AppendAligned, 0, InputClassification.PerVertexData, 0),
                                                                New InputElement("TEXCOORD", 0, DXGI.Format.R32G32_Float, InputElement.AppendAligned, 0, InputClassification.PerVertexData, 0),
                                                                 New InputElement("WORLD", 0, DXGI.Format.R32G32B32A32_Float, 0, 1, InputClassification.PerInstanceData, 1),
                                                                 New InputElement("WORLD", 1, DXGI.Format.R32G32B32A32_Float, InputElement.AppendAligned, 1, InputClassification.PerInstanceData, 1),
                                                                 New InputElement("WORLD", 2, DXGI.Format.R32G32B32A32_Float, InputElement.AppendAligned, 1, InputClassification.PerInstanceData, 1),
                                                                 New InputElement("WORLD", 3, DXGI.Format.R32G32B32A32_Float, InputElement.AppendAligned, 1, InputClassification.PerInstanceData, 1)
                                                         }

```

This setup works fine but I'm still getting a big frame time hit when I draw my trees, my trees are made with SpeedTree and are around 3k-10k triangles, some of them could be up to 5 draw calls per tree and that's why I'm using instance because I figure it has to be faster to instance it than to not, I mean I'm drawing the same thing over and over so isn't that why you use instancing?

For my world I have 8 types of tree and 5 variations of each and some trees have up to 5 meshes, I can only seem to render around 750-1250 instances per frame and keep it running smooth, btw that's total for all the trees not each type, I'm not sure of the tree type count because its random but ill ball park it to 100-150 of each tree type.

I draw the leafs with alpha test so I don't get early-z on the trunks too because I have no way of turning off alpha test for the trunks right now.

I know there are many things that will affect my frame times but as far as I can tell this is whats costing the most right now, with no trees I'm running at 90-110 fps and with trees I drop to 35-55. If I change the tree cull distance then of course I get more frames.

I have a bit of batching going on, first by Mesh name then by blend state.

I use a tile based deferred render, its based on AMD's code, I also have cascaded shadow maps with 3 splits, water reflections and sometimes dynamic cube map faces. So each mesh could end up getting drawn 6 times but I dont update the last shadow cascade every frame, I split the cube rendering over 6 frames and only render stuff that the water can see into the reflection target.

So I guess my question is am I doing instancing correct and I'm just trying to draw to much and need to work on LoD or am I doing it wrong? What do others get from there instancing systems?

Ps. 90-110 fps isn't for an empty world that's what I get for my full world but without the trees

# Answer
> 0 votes
Turns out I'm doing instancing the right way, there is another way but I have no need for that just yet and there is a slower way that uses a constant buffer to hold the instance data instead of a vertex buffer.

I was doing a few other things wrong that all stacked up to hinder me while rendering the trees, ill list them bellow.

While building the instance buffers I was having problems with map and unmap, I was using a data stream and that was making lots of garbage so the GC was having a bad time so I had it just make a new buffer on another thread every time I needed to update it but again the GC has issues with that much disposing, not so much the GC but more the frame spikes when it would kick in..... happened lots.

I did some digging and found the right way to do it is with map and unmap, grow the buffer if I need but instead of using a datastream I should use the function that returns a databox and the call write on the native pointer to that memory so I can avoid using data stream.

Looks like this:

```
           If ObjectCount > LastObjectCount Then
                If instancebuffer IsNot Nothing Then
                    instancebuffer.Dispose()
                    instancebuffer = Nothing
                End If
                instancebuffer = device.CreateBuffer(New BufferDescription(ObjectCount * 64, ResourceUsage.Dynamic, BindFlags.VertexBuffer, CpuAccessFlags.Write, 0, 0))
            End If

            Dim dbox As DataBox = _Context.MapSubresource(instancebuffer, 0, MapMode.WriteDiscard, MapFlags.None)
            Utilities.Write(dbox.DataPointer, EnityList, 0, ObjectCount)
            _Context.UnmapSubresource(instancebuffer, 0)
            newdata.DrawData = instancebuffer
            newdata.Count = ObjectCount
            LastObjectCount = ObjectCount
            dbox = Nothing

```

That was my first problem but that only got my 1/2 to where I wanted to be.

The next problem was not with the trees or the drawing of the trees but more the fact I was using a few massive shadow maps that were sucking 3ms out of my frame time.

I just dropped the size of the shadow map down and fixed it so I didn't have to use a massive one to have it look nice.

The first fix saved me 3ms and smoothed out the frame times because the GC was not running all the time and I wasn't recovering big chunks of native memory every few frames.

The second fix saved me another 1.5-2ms.

Yay up to a 5ms saving! I can draw more, so I did and that dropped the frames again but I had my predication testing to fix that.

On a final note I'm now using my first fix anywhere I need to map\unmap on the fly so I'm seeing an overall drop in GC and memory traffic. Good Times!!

---
Tags: directx11, performance, sharpdx, instancing
---


title: How can I have cutouts in a texture?

text:
# Question
Title: How can I have cutouts in a texture?
I want to be able to have a gameobject that's basically just a black box on top of everything else. Then I want to be able to place other gameobjects which are just gradients on top of that and they should "cut out" of the black texture like this:

How can I achieve this sort of effect?

Please keep in mind that I have pretty much no experience with shaders :)

Here's a video that might help explain what I'm trying to achieve https://www.youtube.com/watch?v=L1dd4fkVSAM

# Answer
> 0 votes
I saw the video link you provided. I dont think you have to do much about shaders. This can easily be achieved by using lighting. Make the entire scene dark by deleting all the lights including directional light (or configuring the light to decrese its intensity). Assign a light (may be a point light) to the character and you get what you want. When the character moves, the area around the character would light up.

Otherwise if you want your black box to show gradients of textures dynamically, it needs shader programming. Hope this help.

---
Tags: unity, shaders
---


# Question
Title: How to draw an image on canvas without html
I'm trying to add a sprite to the canvas of my game. However, I don't want to use an image tag. However, I haven't found a way to do this no matter how hard I searched. Something like:

```
var image = 'sample.jpg'
draw(image)

```

# Answer
Philip's suggested improvement to DMGregory's answer is important.

```
//Create Image object
var image2 = new Image();

//Get context ready
var canvas2 = document.getElementById('mycanvasid');
var ctx2 = canvas2.getContext('2d');

//Now, set .onload with function(s) that require a loaded image, before setting .src
image2.onload = function () {
    var x = 0, y = 0;
    ctx2.drawImage(image2, x, y);  //aka, ctx2.drawImage(this, 0, 0);
}

//Finally, start the loading process
image2.src = 'path/to/your/image.png';

```
> 3 votes

# Answer
Recapping the doc examples discussed in the comments above:

```
// First, create a reference to the image we want to draw.
var image = new Image(); // or document.createElement('img');
image.src = 'path/to/your/image.png';

// Next, find (or create/add) our canvas, and get its drawing context.
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');

// Finally, draw our image onto the canvas with a given x & y position.
var x = 0, y = 0;
ctx.drawImage(image, x, y);

```
> 0 votes

---
Tags: javascript, html5, html-canvas, image
---


title: How do i put unity game exe at startup

text:
# Question
Title: How do i put unity game exe at startup
As i have only unity build in exe format how can i put it to the startup of my window so that it run automatically when computer becomes start. Remember I don't want to put it manually is there any scripting ref available to do this or else auto solution?

# Answer
> 1 votes
You can cause Windows to start an application at startup by adding a registry key to `HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\Current Version\Run`. You should already have some such keys on your own system which you can view with the Windows registry editor (regedit.exe) as an example.

This is best done in the installer. Most installer toolkits allow to set registry keys during installation. But if you want to set that registry key from your game executable itself, check out the method `Registry.SetValue` from the .NET framework.

---
Tags: unity
---


# Question
Title: My C++/OpenGL "Hello Triangle" Code Does Not Draw A Triangle When Using SDL As A Window Library
I have been using the website Learn OpenGL but I am using SDL as a window Library.

My code seems to builds the window correctly but no triangle appears. I am compiling my code using Visual Studio 2013. I have spent many hours looking over the code but cannot see an error. Can anyone tell me where I have gone wrong?

```
#include <iostream>
#include <string>

#include <GL/glew.h>
#include <GL/GLU.h>
#include <SDL.h>
#include <SDL_opengl.h>

//***************************************************************************
// The Width of the screen
//***************************************************************************
const GLuint SCREEN_WIDTH = 800;

//***************************************************************************
// The height of the screen
//***************************************************************************
const GLuint SCREEN_HEIGHT = 600;

bool success = GL_TRUE;

const GLchar* vertexShaderSource = "#version 330 core\n"
"layout (location = 0) in vec3 position;\n"
"void main()\n"
"{\n"
"gl_Position = vec4(position.x, position.y, position.z, 1.0);\n"
"}\0";

const GLchar* fragmentShaderSource = "#version 330 core\n"
"out vec4 color;\n"
"void main()\n"
"{\n"
"color = vec4(1.0f, 0.5f, 0.2f, 1.0f);\n"
"}\n\0";

int main(int argc, char *argv[])
{
    //***********************************************************************
    // Initialize SDL
    //***********************************************************************
    if (SDL_Init(SDL_INIT_EVERYTHING) < 0)
    {
        std::cout << "SDL could not initialize!SDL Error :" <<
            std::string(SDL_GetError());

        return EXIT_FAILURE;
    }
    else
    {
        SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
        SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3);
        SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK,
            SDL_GL_CONTEXT_PROFILE_CORE);

        SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8);
        SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);

        //*******************************************************************
        //The window we'll be rendering to
        //*******************************************************************
        SDL_Window *window = SDL_CreateWindow("Breakout",
            SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, SCREEN_WIDTH,
            SCREEN_HEIGHT, SDL_WINDOW_SHOWN |
            SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE);

        if (window == NULL)
        {
            std::cout << "Window could not be created!SDL_Error: " <<
                std::string(SDL_GetError()) << std::endl;

            return EXIT_FAILURE;
        }

        //*******************************************************************
        //OpenGL context
        //*******************************************************************
        SDL_GLContext context = SDL_GL_CreateContext(window);

        //*******************************************************************
        // Set the required callback functions
        //*******************************************************************
        SDL_Event windowEvent;

        //*******************************************************************
        //Use OpenGL 3.3
        //*******************************************************************

        //*******************************************************************
        // Set this to true so GLEW knows to use a modern approach to
        // retrieving function pointers and extensions
        //*******************************************************************
        glewExperimental = GL_TRUE;

        //*******************************************************************
        // Initialize GLEW to setup the OpenGL Function pointers
        //*******************************************************************
        GLenum glewError = glewInit();
        if (GLEW_OK != glewError)
        {
            std::cout << "Failed to initialize GLEW: " <<
                glewGetErrorString(glewError) << std::endl;

            return EXIT_FAILURE;
        }

        glEnable(GL_CULL_FACE);
        glEnable(GL_BLEND);
        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

        //*******************************************************************
        // Define the viewport dimensions
        //*******************************************************************
        glViewport(SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
            SCREEN_WIDTH, SCREEN_HEIGHT);

        //*******************************************************************
        // Build and compile our shader program
        // Vertex shader
        //*******************************************************************
        GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER);
        glShaderSource(vertexShader, 1, &vertexShaderSource, NULL);
        glCompileShader(vertexShader);

        //*******************************************************************
        // Check for compile time errors
        //*******************************************************************
        GLint success;
        GLchar infoLog[512];
        glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &success);
        if (!success)
        {
            glGetShaderInfoLog(vertexShader, 512, NULL, infoLog);
            std::cout << "ERROR::SHADER::VERTEX::COMPILATION_FAILED: " <<
                infoLog << std::endl;
        }

        //*******************************************************************
        // Fragment shader
        //*******************************************************************
        GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
        glShaderSource(fragmentShader, 1, &fragmentShaderSource, NULL);
        glCompileShader(fragmentShader);

        //*******************************************************************
        // Check for compile time errors
        //*******************************************************************
        glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &success);
        if (!success)
        {
            glGetShaderInfoLog(fragmentShader, 512, NULL, infoLog);
            std::cout << "ERROR::SHADER::FRAGMENT::COMPILATION_FAILED: " <<
                infoLog << std::endl;
        }

        //*******************************************************************
        // Link shaders
        //*******************************************************************
        GLuint shaderProgram = glCreateProgram();
        glAttachShader(shaderProgram, vertexShader);
        glAttachShader(shaderProgram, fragmentShader);
        glLinkProgram(shaderProgram);

        //*******************************************************************
        // Check for linking errors
        //*******************************************************************
        glGetProgramiv(shaderProgram, GL_LINK_STATUS, &success);
        if (!success) {
            glGetProgramInfoLog(shaderProgram, 512, NULL, infoLog);
            std::cout << "ERROR::SHADER::PROGRAM::LINKING_FAILED: " << infoLog << std::endl;
        }
        glDeleteShader(vertexShader);
        glDeleteShader(fragmentShader);

        //*******************************************************************
        // Set up vertex data (and buffer(s)) and attribute pointers
        //*******************************************************************
        GLfloat vertices[] = {
            -0.5f, -0.5f, 0.0f,     // Left
            0.5f, -0.5f, 0.0f,      // Right
            0.0f, 0.5f, 0.0f        // Top
        };
        GLuint VBO, VAO;
        glGenVertexArrays(1, &VAO);
        glGenBuffers(1, &VBO);

        //*******************************************************************
        // Bind the Vertex Array Object first, then bind and set vertex
        // buffer(s) and attribute pointer(s).
        //*******************************************************************
        glBindVertexArray(VAO);

        glBindBuffer(GL_ARRAY_BUFFER, VBO);
        glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices,
            GL_STATIC_DRAW);

        glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat),
            (GLvoid*)0);

        glEnableVertexAttribArray(0);

        //*******************************************************************
        // Note that this is allowed, the call to glVertexAttribPointer
        // registered VBO as the currently bound vertex buffer object so
        // afterwards we can safely unbind
        //*******************************************************************
        glBindBuffer(GL_ARRAY_BUFFER, 0);

        //*******************************************************************
        // Unbind VAO (it's always a good thing to unbind any buffer/array to
        // prevent strange bugs)
        //*******************************************************************
        glBindVertexArray(0);

        //*******************************************************************
        // DeltaTime variables
        //*******************************************************************
        GLdouble deltaTime = 0.0f;
        Uint64 lastFrame = 0L;
        Uint64 currentFrame = SDL_GetPerformanceCounter();

        while (true)
        {
            //***************************************************************
            // Calculate delta time
            //***************************************************************
            lastFrame = currentFrame;
            currentFrame = SDL_GetPerformanceCounter();

            deltaTime = ((currentFrame - lastFrame) * 1000 /
                (GLdouble)SDL_GetPerformanceFrequency());

            double tmpDeltaTime = deltaTime;

            //std::cout << "Hello 1 - deltaTime: " << std::to_string(deltaTime) <<
            //    std::endl;

            if (SDL_PollEvent(&windowEvent))
            {
                if (windowEvent.type == SDL_QUIT)
                {
                    break;
                }
            }

            //***************************************************************
            // Clear the colorbuffer and render
            //***************************************************************
            glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
            glClear(GL_COLOR_BUFFER_BIT);

            //***************************************************************
            // Draw our first triangle
            //***************************************************************
            glUseProgram(shaderProgram);
            glBindVertexArray(VAO);
            glDrawArrays(GL_TRIANGLES, 0, 3);
            glBindVertexArray(0);

            //***************************************************************
            // draw OpenGL: Swap the screen buffers
            //***************************************************************
            SDL_GL_SwapWindow(window);
        }

        //***************************************************************
        // Properly de-allocate all resources once they've outlived their
        // purpose
        //***************************************************************
        glDeleteVertexArrays(1, &VAO);
        glDeleteBuffers(1, &VBO);

        SDL_GL_DeleteContext(context);
        SDL_DestroyWindow(window);
        SDL_Quit();
    }

    return EXIT_SUCCESS;
}

```

# Answer
> 0 votes
This line:

```
glViewport(SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, SCREEN_WIDTH, SCREEN_HEIGHT);

```

... does not really make sense. You're passing in special constants only known by SDL to an OpenGL function that expects actual coordinates. If anything, I'd expect that to be `glViewport(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)`.

But then, I have never actually seen or used `glViewport`, and it looks like it's part of the deprecated fixed-function pipeline matrix stack, which you probably don't want to use since you're using shaders and VAOs. Simply remove the line, and voilà ! Triangle.

# Answer
> 1 votes
Try adding instead of

```
glClear(GL_COLOR_BUFFER_BIT);

```

The following line:

```
glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);

```

It is a pretty common issue.

**Edit:** Also try moving

```
glEnableVertexAttribArray(0);

```

before

```
glVertexAttribPointer(...);

```

**Edit2:** Also what Quentin says might be the problem. Try using

```
glViewPort(0, 0, width, height);

```

Let me know if any of these helps.

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


# Question
Title: On Click Add Listener not working on Game Object
I have this code attached to a 3D cylinder game object. I plan to use it as an arrow and rotate it when clicked and dragged. I had no idea what do as I am a beginner so I started with adding an onClick listener to a Button component on the Cylinder, and wrote this script which I added as component to the cylinder.. But the Rotate() function isn't called when I click on it, as there is no message in the Log.. This is the code:

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

public class MoveAim : MonoBehaviour {

    public bool isAiming;
    private Button button;

    void Start () {
        isAiming = true;
        button = GetComponent <Button>();
        button.onClick.AddListener (Rotate);
        Debug.Log ("Start!");
    }

    void FixedUpdate () {
    }
    void Rotate() {
        Debug.Log ("Click recorded");
    }

}

```

Any idea what to do? And how should I implement the rotation of the cylinder? Help would be appreciated!

Thanks!

# Answer
You are using a button, which is an UI element. It is not supposed to be used on 3d objects in the game world.

On 3d objects in game world you probably want to use IPointerClickHandler. They work like this:

```
using UnityEngine;
using UnityEngine.EventSystems;

public class Clickable : MonoBehaviour, IPointerClickHandler
{
  public void OnPointerClick( PointerEventData eventData )
  {
    Debug.Log ("Click recorded");
  }
}

```

Also note that the object should have a collider attached to it, and the scene must have EventSystem and Standalone Input Module attached to some object.

There are more events supported to allow different behaviours.
> 3 votes

---
Tags: unity, gameobject
---


title: Axis of affine transformation matrix

text:
# Question
Title: Axis of affine transformation matrix
Let's say I have a right handed column major 4x4 transformation matrix. Can I safely assume (even though there exist non uniform scale) that first column is X axis vector, second column is Y axis vector and third column is Z axis vector?

$$ \begin{bmatrix} Xx & Yx & Zx & 0 \\ Xy & Yy & Zy & 0 \\ Xz & Yz & Zz & 0 \\ 0 & 0 & 0 & 1 \end{bmatrix} $$

Iis the above layout correct? By the way I am using glm and I don't know if there is a function to extract these axis.

# Answer
Yes, in GLM it is laid out as such:

$$ \begin{bmatrix} ux & vx & nx & tx \\ uy & vy & ny & ty \\ uz & vz & nz & tz \\ 0 & 0 & 0 & 1 \end{bmatrix} $$

Where the vector t is translation, and the top-left 3x3 matrix is rotation.

You can also use the GLM method `decompose(...)`.

Note that the documentation is outdated - you need to include `<glm/gtx/matrix_decompose.hpp>` instead of `<glm/gtx/decomposition.hpp>`
> 0 votes

---
Tags: opengl, mathematics, transformation, glm
---


# Question
Title: Any idea unity game 2d coins reset when starting new game
I am newbie any help would be really much appreciated thanks in advance :) Example I am game over I earned 30 coins and start new game and coin in the game start with 0 and the coins collected in previous game is gone.

This is my code ....

*coin collected*:

```
     private var score : int=0;
     var saved ;
   public static var coins : float;
   private var coinsBegin : int;

  function Start () {
     saved = PlayerPrefs.GetInt("Coin");

    }

    function OnTriggerEnter2D( other : Collider2D ) {
          if (other.tag == "Coin") {
       coins += 1;
      PlayerPrefs.SetInt ("Coin", coins);
      coinsBegin++;
     PlayerPrefs.GetInt("Coin");
     DontDestroyOnLoad (other.gameObject);
            PlayerPrefs.Save();
            Destroy(other.gameObject);

          }

         }

        function OnGUI () {
         GUI.Label (Rect (20, 20, 200, 40), "score: "                +PlayerPrefs.GetInt("Coin"));

          }

```

and this is ... *coin display*:

```
     #pragma strict var MyFont : Font;

   function OnGUI(){
      GUI.skin.font = MyFont;
        GUI.Label(Rect(100,100,50,50), "Coins: "+   PlayerPrefs.GetInt("Coin"));
   PlayerPrefs.Save();
        }

```

# Answer
> 1 votes
Apparently you are trying to save the number of coins the player earned in the PlayerPref's. Your are even reading them in your Start function with `PlayerPrefs.GetInt("Coin");`. However, you are then storing the result in a variable `saved` which isn't used anywhere. Store the return value in `coins` instead (which I think should be an `int`, not a `float`, by the way).

# Answer
> 0 votes
Replace your Start function with this:

```
function Start () {
     coins = PlayerPrefs.GetInt("Coin");
}

```

---
Tags: unity, javascript
---


title: SFML with Box2D

text:
# Question
Title: SFML with Box2D
I'm using SFML and Box2D to create an application that spawns circles, triangles and rectangles at the current mouse point when the user presses the C, T, and R keys. The problem is that the shapes don't move even though the position of the graphic is constantly updated with the position of the physics body. I've looked at the code of working examples of similar setups and can't find any obvious explanation for why it isn't working.

Here is the complete code.

**Shape.h**

```
#include <Box2D/Box2D.h>

class Shape
{
public:
    Shape(float x, float y) : position(x, y) {};

    void setAsCircle(float radius);
    void setAsTriangle(float base, float height);
    void setAsRectangle(float width, float height);

    void createBody(b2World &world, bool dynamic = true);
    sf::Shape &getShape() { return *shape; };
    void update();

private:
    sf::Vector2f position;
    sf::Shape* shape;
    b2Body* body;

    const int worldScale = 30;
};

```

**Shape.cpp**

```
#include "Shape.h"

void Shape::setAsCircle(float radius)
{
    sf::CircleShape *circle = new sf::CircleShape(radius);
    circle->setPosition(position);
    circle->setOrigin(radius, radius);
    shape = circle;
}

void Shape::setAsTriangle(float base, float height)
{
    sf::ConvexShape *triangle = new sf::ConvexShape(3);
    triangle->setPoint(0, sf::Vector2f(0, height));
    triangle->setPoint(1, sf::Vector2f(base / 2, 0));
    triangle->setPoint(2, sf::Vector2f(base, height));
    triangle->setPosition(position);
    triangle->setOrigin(base / 2, height / 2);
    shape = triangle;
}

void Shape::setAsRectangle(float width, float height)
{
    sf::RectangleShape *rectangle = new sf::RectangleShape(sf::Vector2f(width, height));
    rectangle->setPosition(position);
    rectangle->setOrigin(width / 2, height / 2);
    shape = rectangle;
}

void Shape::createBody(b2World &world, bool dynamic)
{
    b2BodyDef bodyDef;
    if (dynamic) bodyDef.type = b2_dynamicBody;
    bodyDef.position.Set(position.x / worldScale, position.y / worldScale);
    body = world.CreateBody(&bodyDef);

    b2PolygonShape polygonShape;
    polygonShape.SetAsBox(shape->getLocalBounds().width / 2 / worldScale, shape->getLocalBounds().height / 2 / worldScale);

    b2FixtureDef fixtureDef;
    fixtureDef.shape = &polygonShape;
    fixtureDef.density = dynamic;
    fixtureDef.friction = 0.3f;
    body->CreateFixture(&fixtureDef);
}

void Shape::update()
{
    shape->setPosition(body->GetPosition().x * worldScale, body->GetPosition().y * worldScale);
    shape->setRotation(body->GetAngle() * 180 / b2_pi);
}

```

**App.h**

```
#pragma once

#include "Shape.h"
#include <memory>
#include <random>

class App
{
public:
    App();
    App(const App&) : world(b2Vec2(0, -10)) {};

private:
    void events();
    void update();
    void render();
    void handleKeyPress(int key);

    sf::RenderWindow window;
    std::vector<Shape> shapes;
    b2World world;

    const int windowWidth = 1024, windowHeight = 768;
};

```

**App.cpp**

```
#include "App.h"

App::App() : world(b2Vec2(0, -10))
{
    window.create(sf::VideoMode(windowWidth, windowHeight), "sf2D physics sandbox");

    Shape shape(0, static_cast<float>(windowHeight));
    shape.setAsRectangle(static_cast<float>(windowWidth), 0);
    shape.createBody(world, false);
    shapes.push_back(shape);

    while (window.isOpen())
    {
        events();
        update();
        render();
    }
}

void App::events()
{
    sf::Event event;
    while (window.pollEvent(event))
    {
        switch (event.type)
        {
        case sf::Event::Closed:
            window.close();
            break;

        case sf::Event::KeyPressed:
            handleKeyPress(event.key.code);
            break;
        }
    }
}

void App::update()
{
    world.Step(1 / 60, 8, 3);
    for (Shape &shape : shapes) shape.update();
}

void App::render()
{
    window.clear();
    for (Shape &shape : shapes) window.draw(shape.getShape());
    window.display();
}

void App::handleKeyPress(int key)
{
    float mouseX = static_cast<float>(sf::Mouse::getPosition(window).x);
    float mouseY = static_cast<float>(sf::Mouse::getPosition(window).y);
    sf::Color randomColor = sf::Color(rand() % 256 + 0, rand() % 256 + 0, rand() % 256 + 0);

    Shape shape(mouseX, mouseY);
    switch (key)
    {
    case sf::Keyboard::C:
        shape.setAsCircle(rand() % 100 + 25);
        break;

    case sf::Keyboard::T:
        shape.setAsTriangle(rand() % 100 + 25, rand() % 100 + 25);
        break;

    case sf::Keyboard::R:
        shape.setAsRectangle(rand() % 100 + 25, rand() % 100 + 25);
        break;
    }
    shape.createBody(world);

    shapes.push_back(shape);
}

```

**main.cpp**

```
#include "App.h"

int main()
{
    App app = App();

    return 0;
}

```

The position of the shapes do not change after they are created. Where have I gone wrong?

# Answer
Eventually I found the answer myself. The problem was with this line:

```
world.Step(1 / 60, 8, 3);

```

where 60 was considered an integer so the division rounded out to zero. This caused the world to simulate at a speed of zero, which explains why nothing happened.

I modified it as such:

```
world.Step(1 / 60.0f, 8, 3);

```

so that 60 was correctly assessed as a float. After some minor adjustments everything now works as expected.
> 2 votes

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


# Question
Title: LibGDX: Easy way to draw partial sprites
I am surely overlooking something, but is there an easy to draw for example only half a sprite in LibGDX? I originally thought I could do this with setBounds() but this distorts the sprite.

# Answer
It's quite possible to partially draw a sprite using the SpriteBatch.draw(Texture,...) rather than the SpriteBatch.draw(TextureRegion,...). As long as you only intend to draw a rectangular sub-section of that sprite. Note, Sprite is a TextureRegion.

If you have a Sprite that you are already drawing, you can get the Texture itself from the Sprite using the .getTexture() function.

For example, the following code could be used to draw only the left side of a sprite:

```
spriteBatch.draw(
    frame.getTexture(),
    x,                       /* x the x-coordinate in screen space                                            */
    y,                       /* y the y-coordinate in screen space                                            */
    width / 2,               /* originX the x-coordinate of the scaling and rotation origin relative to the screen space coordinates   */
    height / 2,              /* originY the y-coordinate of the scaling and rotation origin relative to the screen space coordinates   */
    /* We only want to draw half the width of the sprite */
    width / 2,               /* width the width in pixels                                                     */
    height,                  /* height the height in pixels                                                   */
    frame.getScaleX(),       /* scaleX the scale of the rectangle around originX/originY in x                 */
    frame.getScaleY(),       /* scaleY the scale of the rectangle around originX/originY in y                 */
    0 ,                      /* rotation the angle of counter clockwise rotation of the rectangle around originX/originY               */
    frame.getRegionX(),      /* srcX the x-coordinate in texel space                                          */
    frame.getRegionY(),      /* srcY the y-coordinate in texel space                                          */
    /* We only want to use half the source texture region */
    frame.getRegionWidth() / 2,   /* srcWidth the source with in texels                                            */
    frame.getRegionHeight(), /* srcHeight the source height in texels                                         */
    false,                   /* flipX whether to flip the sprite horizontally                                 */
    false);                  /* flipY whether to flip the sprite vertically                                   */

```

Where spriteBatch is the SpriteBatch and frame is a Sprite; x, y, width and height are the same as you would use in spriteBatch.draw(frame, x, y, width, height);

To only draw the top half of a sprite (as if the sprite was standing in a liquid, for example) you would set the height, the texture region height, and include a slight adjustment to the draw position:

```
spriteBatch.draw(
    frame.getTexture(),
    x,
    y + (height / 2),            /* reposition to draw from half way up from the original sprite position */
    width / 2,
    height / 2,
    width,
    height / 2,                  /* draw the sprite at half height*/
    frame.getScaleX(),
    frame.getScaleY(),
    0,
    frame.getRegionX(),
    frame.getRegionY(),
    frame.getRegionWidth(),
    frame.getRegionHeight() / 2, /* only use the texture data from the top of the sprite */
    false,
    false);

```

I hope this helps, Good luck.
> 5 votes

# Answer
If you are working solely with Sprites I do not believe there is a good way of drawing part of a Sprite. If you want to keep working only with Sprites I would recommend splitting the original Texture beforehand and creating a separate Sprite for each piece.

However, if you could work with Textures (i.e. you do not need to rotate the partial Sprite) then you can draw part of the texture using this method. It looks like this:

```
batch.draw(texture, xPosition, yPosition, xPositionInTexture, yPositionInTexture, widthInTexture, heightInTexture);

```
> 0 votes

# Answer
After much struggle, I finally found a way to draw texture portions. I really don't know why, but the other answers didn't help me in my case.

So I figured out another solution:

```
public static void
drawPortionFromButtom(
  SpriteBatch batcher, TextureRegion textureRegion,
  Vector2 position, float width, float height, float portionToDraw)
{
    batcher.draw(textureRegion.getTexture(),
            position.x,
            position.y + height*(1 - portionToDraw) ,
            width,
            (height * portionToDraw),
            textureRegion.getU() ,
            textureRegion.getV2() + (textureRegion.getV() - textureRegion.getV2()) * (1 - portionToDraw),
            textureRegion.getU2(),
            textureRegion.getV());
}

public static void
drawPortionFromTop(
  SpriteBatch batcher, TextureRegion textureRegion,
  Vector2 position, float width, float height, float portionToDraw)
{
    batcher.draw(textureRegion.getTexture(),
            position.x,
            position.y,
            width,
            (height / portionToDraw),
            textureRegion.getU() ,
            textureRegion.getV(),
            textureRegion.getU2(),
            textureRegion.getV() / portionToDraw);
}

```

Hope this helps someone else!
> 0 votes

---
Tags: libgdx, sprites
---


title: When mouse on a button image appear?

text:
# Question
Title: When mouse on a button image appear?
My canvas contains three buttons and three images. I would like the images to appear when the mouse hovers over buttons.

```
public GameObject button1;
public GameObject button2;
public GameObject button3;

public Image imag1;
public Image imag2;
public Image imag3;

void Update() {

}

public void OnPointerEnter (PointerEventData eventData)
{
    Debug.Log ("The cursor entered the selectable UI element.");
}

```

# Answer
> 0 votes
If I have understood it correctly all you need to do is following:

NOTE: you don't need code for this.

1): In the editor select the button you want to change the sprite of.

2): Then at your Button component in the inspector set the Transition property to Sprite Swap.

3): Now you will see three extra fields as: Highlighted Sprite(Pointer is on the button), Pressed Sprite(Button is clicked), and Disabled Sprite(button is not interactable).

4): Each of this field require an Sprite so just drag and drop the sprite, you want to show when pointer enters the button space, on the "Highlighted Sprite" field and you have what you wanted.

I hope this will work, I haven't tested it so it may not work. Do let me know if it works or not.

---
Tags: unity, gui
---


# Question
Title: Can't seem to translate in Y using "Jump" axis
I'm trying to write a character controller for a free-moving camera. I don't want it influenced by physics at all (no gravity, no collisions, no inertia). I've managed to get great movement in the X and Z axes with an Input.GetAxis call, but I'm at a bit of a loss for how to move the camera in the Y direction. I figured I should be able to use the Jump axis, but it isn't responding. Here's what I've got in my character controller update function:

```
float walk = Input.GetAxis("Vertical") * speed;
float strafe = Input.GetAxis("Horizontal") * speed;
float jump = Input.GetAxis("Jump") * speed;
walk *= Time.deltaTime;
strafe *= Time.deltaTime;
jump *= Time.deltaTime;

transform.Translate(strafe, jump, walk);

```

This seems simple enough to me, but the Jump button (space) does nothing. Also, possibly related, possibly tangential: when I go into the InputManager, it won't let me change the keys set for controlling the Jump axis. I can manipulate the values for gravity and sensitivity, but when I change what keys control the Jump axis, it just defaults back to space for positive and blank for negative once I click away from the box.

# Answer
If jump is configured to be a button then you should not be reading it as an axis but as a button.

```
Input.GetButtonDown("Jump")

```
> 0 votes

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


# Question
Title: Making a sales curve over time from a static baseline figure
I am making a game where there are objects that will be for sale. The objects have a reputation score, which is the amount of sales they get each week. This is calculated up front and remains the same for the entire release period. The release period is also created up front and represents a period of time in weeks.

In my example Object#1 has a sales score of 10,000 and a release period 8 weeks. This means it will sell 80,000 copies at 10k/week.

My aim is to take this flat line, and curve it, so it has rising sales at the start, a smoothed peak of sales in the middle, and lower sales at the end tailing off, like a gamma probability distribution curve. The total sales across the period will be the 80,000, but the distribution of weekly sales will change.

I am looking to create this distribution shape from the flat sales total. I'd ideally like to keep the sales volume the same, but as long as I have that curve, it doesn't matter too much. I have looked at the Wikipedia entries etc, but they are all about the maths side of distribution, and calculating distribution from figures, I am just looking to fake that distribution from a median figure.

The idea is once I have this algorithm (or a good tutorial), I can play with it to create other unique distributions, adding variety to object releases, to help make things feel less procedural.

(Any help with improving title and tags greatly appreciated).

Edit -----

I realised I missed out a chunk about looking for help with the programming. I have read a lot of math algorithms but converting what I am learning into code is proving more difficult. Ideally I'd like links/references to solutions for this from a C# perspective, to help me see my way past issues like the one below.

I have a function in math: BetaCDF(x,a,b) = (x\>=1)?1:(x\<=0)?0:sum\[k=1:b\] ( Gamma(a+k-1)/(Gamma(a)\*Gamma(k)) * x**a * (1-x)**(k-1) )

that i am trying to convert into a function. I have everything covered except for the sum. I need to sum `b` times the function on the right, however I cannot figure out how to do this in Unity C#. The function currently looks like this:

```
public static double BetaCDF(double x, double a, double b) {
    double k;
    return ((x >= 1) ? 1 : (x <= 0) ? 0 : Sum(k = 1,b )(Gamma(a + k - 1) / (Gamma(a) * Gamma(k)) * Math.Pow(x, a) * Math.Pow(1 - x, k - 1)));
}

```

# Answer
> 1 votes
You can use curve fitting programs to trace the line and guess a curve (also called regression). plot.ly can graph plotted points and has an analyze\>curve fit tool that can build an equation from that.

These kind of curves are Gaussian (probability distribution) curves: https://en.wikipedia.org/wiki/Gaussian\_function (perhaps more specifically a Hubbert curve: https://en.wikipedia.org/wiki/Hubbert\_curve)

You can get also crude approximations using 6+order polynomial functions over a limited domain, but that will likely look sloppy

---
Tags: c#, game-mechanics
---


title: Skeletal animation using directx 11

text:
# Question
Title: Skeletal animation using directx 11
I tried to find tutorials about skeletal animation or books that talk about subject to implement it, but I couldn't find any tutorials except talking md5 animated files. I would like tutorials that talk about that subject.

# Answer
Skeletal animaion is not specific to DirectX or a single file format. There are many articles on skeletal animation in general to help you with understanding how it works.

I would recommend working with MD5 while learning as it is a text based format, which should make it easier to play with values. (More info on the format: http://tfc.duke.free.fr/coding/md5-specs-en.html)
or the Blitz3D model format (http://www.blitzbasic.com/sdkspecs/sdkspecs/b3dfile\_specs.txt).

I would first worry about making sure whatever format you choose, that you can load it first. Then, the format you use shouldn't matter and you should be able to just deal with the math (Which any tutorial should be able to teach).

Note: do keep in mind that joint animation has slightly altered math from bone animation
> 0 votes

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


# Question
Title: Particle systems and sprites, draw order issue
I have a particle system, and my character, which is a sprite. I want to create a particle for smoke/dust raising from the ground, and I want my character to be able to move over it.

The problem is that the particles are all drawn in front or behind the sprite, even if the sprite is in the middle of the smoke:

If I move the sprite a little forward, all the particles are behind:

It's like all particles are sharing the same Z order of the particle system itself.

I have been facing this problem from a long time, and I tried using other shaders, new sorting layers, and messing with the particle system fudge, but the result is always the same.

I want the particles to be rendered in the correct order, those that are further away, behind the character; and those closer, in front of the character.

Any idea of what is happening here?

# Answer
> 1 votes
It is the case that all particles share the same Z order in unity. This is a weird design choice, but I believe it 's because the emitter is an object that is sorted with the rest of the world, and does its own internal sorting for particles. (You also cannot mix particle systems).

One way to handle this is to have two particle systems, one behind and one in front.
See https://www.youtube.com/watch?v=0IrCggoJCno for an example

---
Tags: unity, particles, draw-order
---


title: Unity UI making it responsive

text:
# Question
Title: Unity UI making it responsive
I am attempting to create a simple `Jeopardy` game using the UI features of Unity:

However as im trying to change the size of the screen it does not seem that my UI is responsive:

Here is it in 16:9:

Here it is in 600x900

My Question is. is there a way to make it responsive?

Is it even nessary to do so in unity or am i thinking way to much web based? :)

Hope someone is able to help me and guide me abit

# Answer
> 2 votes
This can be done using `Horizontal Layout Group` and `Vertical Layout Group`component for UI objects.

A parent UI object will have a `Vertical Layout Group`component and it's child objects will have a `Horizontal Layout Group` component. Then your objects with `Text` will be placed under these `Horizontal Layout Group` component holding objects.

On the `Text` components, tick `Best Fit` for font size and align as you need.

*I named the objects as their components for clarification.*

**Games are usually oriented either Landscape or Portrait. Using multiple orientation is bad game UX. Webpages are different than games in this case.**

---
Tags: unity, ui-design
---


# Question
Title: Integrating the Steamworks API achievements into your game
I'm coding a game in Visual Studio 2015 and am wondering how to go about adding steam achievements to it using the Steamworks API, do I need to have my game on steam before hand or if not what's the process of adding achievements?

# Answer
Most of the information you are asking for can be obtained at the Steamworks website.

But the quick answer to your questions (based on the Steamworks FAQ) is that while you can get access to it with a premium Steam account that has signed up for Steamworks, to actually use it with your own game requires a Steam Greenlight submission. This is because the API needs an "AppID" (of your game) to connect it to the Steamworks API.

Additionally, a quick look at the documentation shows that you can program it into your game once you have the API setup.

Hope this helped!
> 0 votes

---
Tags: c++, visual-studio, steam
---


# Question
Title: LIBGDX Perspective Camera in an Isometric view?
how can I set a `PerspectiveCamera` to view the game in an isometric view? What kind of angle would I use, and how would I actually translate this into the code? Math isn't my forte, so I can't really understand the maths on the wikipedia article here. It mentions to points A and B, but I'm not sure what those points would be.

# Answer
> 3 votes
You can't. A `PerspectiveCamera` uses a projection that gives you perspective, but for an isometric projection you don't want any perspective.

You can use the `OrthographicCamera` and tilt it in an angle that works for you, the projection does not use perspective.

---
Tags: java, libgdx, mathematics
---


# Question
Title: Closest to hardware/fastest pixel manipulation
I am currently working on the concept of a game, but I'm running into some problems.

For the game, I'd like to be able to directly change pixels on screen. However, all approaches that I tried so far resulted in my programs being rather slow, even without game mechanics attached to it.

Since a lot of games are also running on 60 fps with changing every pixel, you would expect it not to be hard to achieve such frame rates, if you could find the right way of changing pixels. The speed that I am aiming for is also at least 60 fps (if possible even on low-end hardware)

What is (or what library has) the fastest way to achieve this? It doesn't really matter what language the library is for, as long as I can get those high speeds.

# Answer
> 2 votes
Two general approaches come to mind:

* You could use a legacy, software-based pixel pusher like SDL or Fastgraph, that allows you to easily push pixels on CPU without GPU concerns. This is likely not to be as fast as GPU, but if your goal is simply to make a game and avoid technicalities, this may work better for you. You'll need C / C++ for these options, however... not an easy road.
* You could write individual texels / pixels to a viewport-sized texture in OpenGL, and render that to a screen-filling quad. Turn off bilinear filtering to ensure you get sharp pixels at 1:1 ratio. Since you mentioned you are using Java / LibGDX, you could then stick with them.

---
Tags: performance, per-pixel
---


# Question
Title: What does Steam require from a Greenlight submission?
I'm an indie developer getting ready to submit my game to Steam Greenlight, but have hit a road block. I don't know what to submit.

I've been searching and I haven't found anything detailing whether I should submit the game's files and let Steam do the rest or an installer to install the resource files and the executable in a certain spot?

Do I need to make any Steam-specific optimizations/additions to my game before it can be submitted?

# Answer
No, Steam doesn't even allow you to send executables directly to them. What you need instead is a trailer, and at least four screenshots of your game.

In addition to those, you need a written description of your game and a square-shaped branding image.

You also need to have paid the Greenlight fee.

Take a look at the Steam Greenlight FAQ, it was a great resource for me while I was getting prepared for my campaign. I also suggest that you take a look at a few submission pages.

Now, it's a different question whether you should provide a download link to a potential demo release to increase your chances of getting votes, but that cannot be answered very objectively.
> 5 votes

---
Tags: steam, export
---


# Question
Title: Best approach to implement server authority in client/server game
I am currently trying to create a 2D game with a client/server model, and was wondering how I could implement the server's authority over the client (when client moves, prediction happens, and server checks if the prediction was well done, and if not, client reverts to older state).

Should I create a `State` class where the local player's state is saved at every tick in a buffer, for revert being possible ? Or should I wait for the server to respond and should the client be a simple renderer ?

How could I make sure that client and server are synchronized ?

I use pure java `Socket` class as well as `DatagramSocket`s.

# Answer
> 2 votes
> Should I create a State class where the local player's state is saved at every tick in a buffer, for revert being possible ? Or should I wait for the server to respond and should the client be a simple renderer ?

In an ideal authoritative server you would do the latter. However, this might cause a problem for some games: Even the best internet connection still has a few ms of latency. The player will notice when their character reacts to their input with a certain delay. The more skill-oriented and fast your game is, the more annoying this will become.

For that reason you should implement "client-sided control with revert" for the player-character(s) and "listen to the server" for anything else.

The server should inform the client about everything which happens around it, including its own actions. When the player gives a command, then you should both process it on the client and send it to the server. The server will then respond with how it interprets the command. When the client receives an answer which agrees with its own interpretation, everything is OK. When the server disagrees with the client, the client needs to correct.

Example:

> **Player:** I press `W`.
>
> **Client:** Hey, Rendering Engine: move player from 10:10 to 12:10. Hey, Server: move my player from 10:10 to 12:10
>
> **Server:** That client wants to do *what*? Someone else just moved to 12:10 and blocks it now. And besides, the current maximum move speed of that player is just one unit per tick. The furthest it can move is 11:10. Hey, all clients: Player1 is now at 11:10.
>
> **Client:** Ok, my bad. Rendering Engine: move player back to 11:10.

# Answer
> 0 votes
Imagine that

* client - keyboard, monitor, sound system, maybe video card and etc.
* server - processor and RAM.

Client just connected to server and send input data. for example if I as player want to move forward - I send delta and start to render it, server decide can I move forward or not and send answer to client. If everything okay - client send another input information and start render it.

You can read this article:

GAFFER ON GAMES - What every programmer needs to know about game networking

---
Tags: java, networking
---


# Question
Title: How do I correctly use GetComponent to get the rigidbodies of each element in an array of colliders?
I was trying to implement an AddExplosionForce-script that was shown in a Unity live training session a few years back. It has out of date calls to rigidbodies because it uses the old `gameobject.rigidbody` way of accessing them. I tried doing the standard process of

1. declare a rigidbody,
2. link it to a `GetComponent<>`, and
3. act on the rigidbody through the resulting variable.

However, as shown below, the rigidbodies I need to interact with are used in a foreach loop that goes through an array of colliders. How do I access the rigidbody of each collider in the array as it is used? (and if that is the wrong approach, please let me know). Will using GetComponent in that way harm performance?

Here is the original script from the video, w/ minor comments. I have left out my botched attempt at fixing it for the sake of brevity.

```
public class MassExplosionScriptOriginal : MonoBehaviour
{
    public float force;
    public float radius;

    void Update()
    {
        if(Input.GetMouseButtonDown(0))
        {
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            RaycastHit hit;

            if (Physics.Raycast(ray, out hit, 100))
            {
                Collider[] colliders = Physics.OverlapSphere(hit.point, radius);
                // overlap sphere collects all the colliders that it overlaps
                // with/touches. From  the point you click (hit.point), create a sphere of the
                // given radius (radius),collect all the colliders from the objects overlapped,
                // and then return them with the array colliders.

                foreach (Collider c in colliders) // declare a variable to hold a //collider
                {
                    if (c.rigidbody == null) continue;
                    // the if statement clause says that, if the collider touched //has no rigidbody, then skip it and continue on.

                    c.rigidbody.AddExplosionForce(force, hit.point, radius, 1, ForceMode.Impulse);
                    // Whenever you click, this script will collect all the
                    // colliders and then apply the explosive force to them. It works on everything
                }
            }
        }
    }
}

```

# Answer
> 1 votes
I would simply use `GetComponent` in your `foreach` as you're doing and assign a variable, like so:

```
Collider[] colliders = Physics.OverlapSphere(hit.point, radius);
foreach (Collider c in colliders)
{
    Rigidbody r = c.GetComponent<Rigidbody>()
    if (r == null) continue;

    r.AddExplosionForce(force, hit.point, radius, 1, ForceMode.Impulse);
}

```

Depending on the number of objects returned by `OverlapSphere` and also the expense of `OverlapSphere` itself, performance will vary. But unless you're actually seeing performance issues or plan on dealing with hundreds of objects each frame, I wouldn't worry too much about it.

If it does become a problem or you are likely to deal with a lot of objects, you may find that moving the procedure to a Co-Routine rather than removing your `GetComponent` would be beneficial (executing at, say once every 250ms). You may also see some minor performance gain from changing your `foreach` to a `for` if there number of objects you expect to interact with is large.

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


# Question
Title: Detecting mouse click for the uppermost layered 2d sprite in Unity
I have two sprites. One for the entire background and another small sprite, which is a foreground object. I have written code for both of these objects in their `OnMouseDown()` functions. When I click on the foreground object, the`MouseDown()`method of background object also gets called since it is behind the foreground.I just want my foreground sprite to react when I click it, not both foreground and background sprites.

# Answer
OnMouseDown() should normally work, make sure that both the sprites have separate scripts attached to them, with OnMouseDown() defined in each script. A collider should be attached to the script for the mouse click to work, in any case.

You can do debugging like this:

```
void OnMouseDown()
{
   Debug.Log(sprite.name);
}

```

Or still if things dont work, then try this piece of code instead

```
if (Input.GetMouseButtonDown(0))
{
    RaycastHit hit;
    if (Physics2D.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hit))
    {
        if (hit.collider == collider)
        {
            //Do your thing.
        }
    }
}

```

Hope this helps.
> 1 votes

# Answer
You need to use RaycastAll and not Raycast, as suggested by others.

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

```

I would also suggest you tag your gameobject, and then use the tag to check if the object is the type you are looking for:

```
for (int i = 0; i < hits.Length; i++) {
     if (hits [i].collider.tag == "Foreground")
         //collider.GetComponent<ForegroundScript>().DoSomething();
}

```
> 1 votes

# Answer
The solution for this is to add raycaster to your sprites.

See this stackoverflow question for details :

https://stackoverflow.com/questions/35529940/how-to-make-gameplay-ignore-clicks-on-ui-button-in-unity3d
> 0 votes

---
Tags: unity, 2d, sprites, mouse, layers
---


# Question
Title: enabling and disabling the script in unity
I have three gameobject(G1,G2,G3) and I have set their tag name as "enemy".And I have another gameobject(Manager) where I have attached the script and I have a button when I click on the button the script in all the three gameobjects should be disabled .But the problem is that ,the script is disabled for only one gamobject.

```
public void ArrowIndicatorInvisible()
{
    GameObject.FindWithTag ("enemy").GetComponent<MessageScript>().enabled=false;
}

```

What will be issue.Can anybod help me solving it

# Answer
`FindWithTag` returns only the first `GameObject` with the tag. You need to use `FindGameObjectsWithTag` to retrieve a list of all `GameObject` that are in the Scene.

More info: https://docs.unity3d.com/ScriptReference/GameObject.FindGameObjectsWithTag.html
> 2 votes

# Answer
It looks like you probably need FindGameObjectsWithTag, which returns an array of `GameObjects` rather than a single object

Once you have that you can loop over the objects like so:

```
public void ArrowIndicatorInvisible()
{
    GameObject[] objs = GameObject.FindGameObjectsWithTag("enemy");

    for (int i = 0; i < objs.Length; i++) {
        MessageScript m = objs[i].GetComponent<MessageScript>();
        if (m != null) {
            m.enabled = false;
        }
    }
}

```
> 4 votes

# Answer
you need to use `GameObject.FindObjectsWithTag()` store the result of this method in a array or list, then iterate over said collection and set the enable of the script for each one. Your current code returns only one active game object with the specified tag.
> 2 votes

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


# Question
Title: How to sync a LineRenderer in a multiplayer game?
After a lot of searching online, I have come here as a last resort for my problem.

The question says it all. How to sync a LineRenderer?

One answer I found was to use a ClientRpc. I tried it with no effect.

Below is the snippet of my code,

```
    IEnumerator laserBeam()// This is called through another method on the click of a button
        {
            Beam = GetComponent<LineRenderer> ();
            Beam.SetVertexCount (2);
            Beam.material = BeamMaterial;
            Beam.SetWidth (0.07f, 0.07f);
            Beam.enabled = true;
            Beam.SetPosition (0, gameObject.transform.position);
            Beam.SetPosition (1, target.position);
            RpcDrawLines (gameObject, target.position, true);
            yield return new WaitForSeconds (1.0f);
            Beam.enabled = false;
            RpcDrawLines (gameObject, target.position, false);
        }

    [ClientRpc]
    public void RpcDrawLines(GameObject start, Vector3 end, bool isOn)
    {
        LineRenderer beam = start.GetComponent<LineRenderer> ();
        if (isOn) {
            beam.SetVertexCount (2);
            beam.material = BeamMaterial;
            beam.SetWidth (0.07f, 0.07f);
            beam.enabled = true;
            beam.SetPosition (0, start.transform.position);
            beam.SetPosition (1, end);
        }
        else
            {
                beam.enabled = false;
            }
        }

```

So, this is the code. Works fine on the Server but no effect in the client. I know I am doing something wrong in the client rpc. But I have no idea what it is. Any way of help would be appreciated. Thanks

**Note: I am using UNET**

# Answer
I did it. I solved it. I was an utter idiot to not think about using `[SyncVar]`.

Anyways, here's the solution,

```
 [SyncVar (hook = "OnBeamActive")]
 public bool isBeam = false;

```

Add this variable and set it to true on button press,

```
 isBeam = true; // set this to false when you want to disable the beam

```

Then define OnBeamActive as below,

```
 public void OnBeamActive(bool isOn)
    {
        Beam = GetComponent<LineRenderer> (); // LineRenderer has to be attached to the object to which this script is attached to
        if (!isOn)
           { // If "isOn" is false, you could disable "Beam" here using Beam.enabled = false
            return;
           }
        isBeam = isOn;
        Beam.SetVertexCount (2);
        Beam.material = BeamMaterial;
        Beam.SetWidth (0.07f, 0.07f);
        Beam.enabled = true;
        Beam.SetPosition (0, transform.position);
        Beam.SetPosition (1, target.position);//target is a Transform referring to the end point of the beam/line. Initialize it the way you want
        }

```

So, that's it. Make this a part of your script from where you want the line/laser beam to start from. Also, make sure you attach a LineRenderer component to this object.
> 0 votes

---
Tags: multiplayer, synchronization, unity-networking, unet
---