# Question
Title: In Unity3D, what ways can I improve the batching with a single texture atlas and four-point material?
I'm building a randomized city terrain with a set of planes, custom 4 vertice square made in Blender. I've got a texture atlas working so that it draws on a single material and texture, but it's still hitting 97 batch calls when I render the layout. 4 of those are other things, leaving the ground resulting in 93 calls. Are there any other ways I can increase the efficiency? For the moment, the planes are created with a standard instantiate call:

```
    for (int y = 0; y < NumberOfTilesX; y++) {
        for (int x = 0; x < NumberOfTilesY; x++) {
            CityGround[i] = Instantiate(GroundTile, new Vector3(x, 0, y) * 6, GroundTile.transform.rotation) as GameObject;
            CityGround[i].transform.parent = City.transform;
        }
    }

```

After being created, they set their own texture within the atlas using a random choice selector.

# Answer
> 0 votes
I'm sure it supports this, although I don't know how to describe it in terms of where and what to click within Unity.

Using instancing:
Create a single, correctly-sized tile with 4 vertices (and 4 indices)

Edit: The index buffer is initialized and uploaded only once; it should be filled with the same 4 indices over and over, tileCount times. It's 16-bit-index size is (2 * 4 * tileCount) bytes. The vertex buffers will also be created and uploaded only once.

In addition to the per-vertex positions and UV's, send along per-instance world-translation and UV-translation vectors.

```
InputLayout
{
    {vector3 position, 0, per-vertex, 0}       //slot 0
    {vector2 UV, 0, per-vertex, 0}             //slot 0
    {vector3 worldOffset, 1, per-instance, 1}  //slot 1
    {vector2 UVOffset, 1, per-instance, 1}     //slot 1
}

```

Now, draw all tiles at once:

```
DrawIndexedInstanced(4, tileCount, 0, 0, 0);

```

That draws tileCount-instances, using the same 4 indices (and vertices) for each. After each tile is drawn, the per-instance data advances by 1, supplying the next tile's world and UV offsets.

The vertex shader would take the unit-tile-world-position and add the per-instance worldOffset before projection.

**Offloading more:**
Store only the "bottom-left corner" of each tile in a vertex along with the MIN and MAX UV coordinates. TileSize would presumably reside in a constant buffer. A geometry shader would spit out the original vertex plus the additional 3 indicated by TileSize as a finished, textured quad.

Since each tile(instance) can be re-constructed from a single vertex,

```
Draw(tileCount, 0);

```

is "instanced" and requires only a single bound vertex buffer.

```
InputLayout
{
    {vector3 oneCorner, 0, per-vertex, 0}  //slot 0
    {vector2 UV_Min, 0, per-vertex, 0}     //slot 0
    {vector2 UV_Max, 0, per-vertex, 0}     //slot 0
}

```

GS spits out a (right-handed) trianglestrip for each input vertex:

```
Vertex[0].Position = oneCorner;
Vertex[0].UV = (UV_Min.x, UV_Max.y);   //0,1
Vertex[1].Position = oneCorner + (0, 0, -g_TileSize.z);
Vertex[1].UV = (UV_Min.x, UV_Min.y);   //0,0
Vertex[2].Position = oneCorner + (g_TileSize.x, 0, -g_TileSize.z);
Vertex[2].UV = (UV_Max.x, UV_Min.y);   //1,0
Vertex[3].Position = oneCorner + (g_TileSize.x, 0, 0);
Vertex[3].UV = (UV_Max.x, UV_Max.y);   //1,1

```

**Thinking ahead:**

Then, by indexing these tile-in-one vertices, you can turn individual tiles on and off by re-uploading a new index buffer, leaving the "stale" vertices in place. Within the GS, you can also detect out-of-range/off-camera tiles and intentionally fail to emit any triangles for those tiles. This avoids having to sort the tiles on the CPU.

**Comment expansion:**

VertexPolyline was named to be similar to VertexPosition, VertexPositionNormal, etc.
VertexPolyline is the data and is tightly packed into the VB.
The class which I instantiate, PolylineVertex, maintains a reference to the actual vertex, and only manipulates it; the only data an instance contains is the Index into the VB.
Index is only used for recycling vertices; I take that Index out of the index buffer and leave the dirty vertex buffer in place.
Multiple polylines can share the same PolylineVertex which allows them to communicate adjacency information, etc. (A lot of PolylineVertex was omitted)

FYI, I'm using all of the above to draw a bezier-based road system similar to SimCity.

```
g_d3dContext->DrawIndexed(s_allSegmentIndices.size(), 0, 0);

```

draws the entire road system in one call, using only VertexPolyline's. Also, the VB and IB are only uploaded when new segments are being created.

While a new segment is in edit-mode and draggable, I'm currently re-uploading the entire VB, which is inefficient. As an analogue to what you're facing, I'm currently refactoring the new-segment code to use it's own VB. When I'm finished, I will only have to re-upload 4 vertices while in edit-mode and only update the "master" buffer when a segment is finalized.

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


# Question
Title: Randomised Path from A to B for cursor movement simulation
I'm trying to simulate the movement of the mousecursor, by creating a path from point A to B that has random variation. The algorithm I'm using at the moment is very basic, and is limited in that it's only really good for creating a path where X and Y distance from the start are the same, forming a square:

The code looks something like this:

```
   function calcualtePath(from, to)
   {
      var pathNodes = [];
      while (from.x != to.x || from.y != to.y)
      {
         var newTransition = {x: from.x, y: from.y};

         if (Rand(1, 3) != 1 && newTransition.x > to.x)       newTransition.x--;
         else if (Rand(1, 3) != 1 && newTransition.x < to.x)  newTransition.x++;
         if (Rand(1, 3) != 1 && newTransition.y > to.y)       newTransition.y--;
         else if (Rand(1, 3) != 1 && newTransition.y < to.y)  newTransition.y++;

         pathNodes.push(newTransition);
         from = newTransition;
      }
      return pathNodes;
   }

```

I'd like some assistance in creating is a relatively fast algorithm that creates a randomised path between point A and B, that has a more curve like path and isn't limited like the one above. Ideally something a bit like this, with a pronounced curve:

# Answer
> 2 votes
Have you thought about using bezier curves? Check out this link that explains them.

http://blog.demofox.org/2014/03/04/bezier-curves/

You'll have to come up with the intermediary control point(s) but it should be pretty simple to do.

Hermite interpolation might be more what you are after, but that is mathematically equivelant, just in a different form.

If you want it to look imperfect, you could add some jitter on top of the curve path (:

---
Tags: javascript, random, path
---


# Question
Title: Unity free look camera on two axes. How do I do it?
I'm new to Unity and c# but have programming experience... I have a a simple "game" in Unity that shows one sphere orbiting another. How do I allow the camera to be moved by the user in a "free look" dynamic? I want to be able to press the right mouse button and adjust the camera on two axes. I'm using Unity 5.0. Whenever I run the following Unity freezes when I press the right mouse button.

Here's the camera control script:

```
using UnityEngine;
using System.Collections;

public class CameraControl : MonoBehaviour
{
     private float horizontalSpeed;
     private float verticalSpeed;

     void Update ()
     {
           while (Input.GetMouseButtonDown(1))
           {
                 horizontalSpeed = Input.GetAxis ("Mouse Y");
                 verticalSpeed = Input.GetAxis ("Mouse X");
                 transform.Translate(verticalSpeed,horizontalSpeed,0.0f);
           }
     }
}

```

# Answer
> 2 votes
Update runs once per frame. Using while in the update script like that, in English reads like this: "Once for this frame, while the mouse button was held down for this frame, move the camera and stuff". The reason why this does not work well is because, the mouse will be in a 'down' state until the next frame, and it wont go onto the next frame until the mouse is not in a down state and instead will run what is in your while loop, and because of that, the next frame will need to wait until the while loop is completed (and that loop is waiting for the next frame before it is finished) --- and this logical loop causes unity to freak out (technically it's just spinning) and crash.

What you want to do, is have the camera update it's position each frame. To accomplish this it is relatively easy...

```
void Update ()
{
    if (Input.GetMouseButton(1))
    {
        transform.Translate(-Input.GetAxis ("Mouse X"),-Input.GetAxis ("Mouse Y"),0.0f);
    }
}

```

What that says now is: "If the button has been pressed this frame, move it by how much it moved this frame".

---
Tags: unity, camera
---


# Question
Title: Rectangular area light illuminance - colour banding
I'm currently working on an implementation of rectangular area lights but I am having some issues with the illuminance calculation, which gives me serious colour banding across the entire lit area. I'm using the paper published by DICE, "Moving Frostbite to Physically Based Rendering" (http://www.frostbite.com/2014/11/moving-frostbite-to-pbr/) as my base for implementation (Listing 12).

This is the relevant code used:

Solid angle of the rectangle

```
#define M_PI 3.14159265358979323846
float RectangleSolidAngle(vec3 worldPos, vec3 p0, vec3 p1, vec3 p2, vec3 p3)
{
    vec3 v0 = p0 - worldPos;
    vec3 v1 = p1 - worldPos;
    vec3 v2 = p2 - worldPos;
    vec3 v3 = p3 - worldPos;

    vec3 n0 = normalize(cross(v0, v1));
    vec3 n1 = normalize(cross(v1, v2));
    vec3 n2 = normalize(cross(v2, v3));
    vec3 n3 = normalize(cross(v3, v0));

    float g0 = acos(dot(-n0, n1));
    float g1 = acos(dot(-n1, n2));
    float g2 = acos(dot(-n2, n3));
    float g3 = acos(dot(-n3, n0));

    return g0 + g1 + g2 + g3 - 2.0f * M_PI;
}

```

Illuminance calculation

```
float RectangleIlluminance(vec3 worldPos, vec3 worldNormal, AreaLightData lightSource)
{
    float result = 0.0f;

    if (dot((worldPos - lightSource.position), lightSource.normal) > 0.0f)
    {
        float hWidth = lightSource.halfWidth;
        float hHeight = lightSource.halfHeight;

        vec3 p0 = lightSource.position + lightSource.right * -hWidth + lightSource.up * hHeight;
        vec3 p1 = lightSource.position + lightSource.right * -hWidth + lightSource.up * -hHeight;
        vec3 p2 = lightSource.position + lightSource.right * hWidth + lightSource.up * -hHeight;
        vec3 p3 = lightSource.position + lightSource.right * hWidth + lightSource.up * hHeight;

        float solidAngle = RectangleSolidAngle(worldPos, p0, p1, p2,    p3);

        float illuminance = solidAngle * 0.2f * (
                            Saturate(dot(normalize(p0 - worldPos), worldNormal)) +
                            Saturate(dot(normalize(p1 - worldPos), worldNormal)) +
                            Saturate(dot(normalize(p2 - worldPos), worldNormal)) +
                            Saturate(dot(normalize(p3 - worldPos), worldNormal)) +
                            Saturate(dot(normalize(lightSource.position - worldPos), worldNormal)));

        result = illuminance;
    }

    return result;
}

```

The paper mentions some level of banding but it should not be on the level which I am currently getting, which can be seen in motion in this video: https://youtu.be/gmkOOxIYc9s . These images show the illuminance without shadows or anything.

From what I can gather from the paper, the code is correct. The current solution is deferred, reconstructing position using the depth stencil texture and sampling normals from a RGBA32F texture (trying to eliminate precision issues). A directional light also seems to produce some level of banding, although not as visible as with the area light, which can be seen in the following images.

So maybe it's still just a precision issue? The code for handling my depth and position reconstruction looks like this:

```
uniform sampler2D gDepthStencil;

vec4 ReconstructWSPosition(float z, vec2 uv_f)
{
     vec4 sPos = vec4(uv_f * 2.0f - 1.0f, z, 1.0f);
     sPos = gInvProjView * sPos;
     return vec4((sPos.xyz / sPos.w ), sPos.w);
}

void main()
{
    ivec2 pixel = ivec2(gl_GlobalInvocationID.xy);
    float depth = texelFetch(gDepthStencil, pixel, 0).r * 2.0f - 1.0f;
    vec4 wPosition = ReconstructWSPosition(depth, uv);
}

```

Which to me looks correct, but I might be missing something. Any other ideas or suggestions? Maybe a matter of tonemapping/HDR problems?

# Answer
> 1 votes
It might be your display honestly. Some displays use less color depth than 32 bpp which can cause banding or flickering. You might consider dithering if you end up with no better option than addressing the banding.

# Answer
> 0 votes
Looking at the problem further, it just seems to be an issue in darker areas. Adding just a low level of ambient light, such as in the attached image, resolves the issue. Maybe someone else can elaborate on the cause of the problem? I consider the issue resolved for the moment, as I always have some level of ambient lighting present, but further explanation would be much appreciated.

---
Tags: opengl, glsl, lighting, hdr, pbr
---


# Question
Title: Shmup Unity, create an enemy spread shot to the player
Following this lecture: http://www.shmup-dev.com/forum/viewtopic.php?f=6&t=347 , i created a bullet that shoot from the enemy directly to the player, in a straight line.

Now i want to create 3 bullets that are shot from the enemy to the player creating a spread effect, one shot goes directly to the player, and the other two opens a little from the one of the middle,

This line of code is the one that create the line motion from the enemy to the player:

```
    // calculate the direction to the player
    shootVector = SharedInfo.getInstance().player.transform.position - myTransform.position;

```

How can i create the other two motions for the bullets?

http://postimg.org/image/ialuek24r/

Here is the code i have for one shoot (this code is applied to the enemy):

```
void Shoot() // waits for 'delay' seconds, then shoots directly at the player
{
    // get a bullet from the stack
    //var newBullet = gameManager.GetComponent(GameManager).enemyBulletStack.Pop();
    Bullet newBullet = (Bullet)SharedInfo.getInstance().enemyBulletStack.Pop();

    // position and enable it
    newBullet.gameObject.transform.position = new Vector3 (myTransform.position.x,
                                                           myTransform.position.y,
                                                           myTransform.position.z);
    newBullet.gameObject.SetActive(true);

    if (changeShootVector) {
        // calculate the direction to the player
        shootVector = SharedInfo.getInstance().player.transform.position - myTransform.position;
    }

    // normalize this vector (make it length 1)
    shootVector.Normalize();
    shootVector = new Vector3 (0, shootVector.y, shootVector.z);

    // scale it up to the correct speed
    shootVector *= enemyBulletSpeed;
    newBullet.motion = shootVector;
}

```

# Answer
You have options:

1. If all 3 bullets should hit the target within a certain radius, add a small random amount, in world-units, to a random player-local axis (X or Y), when calculating the angle.

`shootVector = player.pos + randomDriftInWorldUnits - myTransform.pos;`
2. If the 2 extra bullets can spread too far apart to hit the player, even if the center bullet does, add a small random deflection to shootVector after calculating it. Rotating a bullet on its local Y-axis produces horizontal drift; RotationX produces vertical. A value \<0.5 degrees would be a good starting point.

`shootVector *= Matrix.CreateRotationX(randomVerticalDeflection);`
`shootVector *= Matrix.CreateRotationY(randomHorizontalDeflection);`
`shootVector.Normalize();`

The last code is overly-simplified, the rotations need to be added to the bullets initial orientation, which you are not, currently, using. Basically, you can multiply a unit-forward vector by (bulletInitialRotationMatrix * deflectionRotationMatrix * bulletInitialTranslationMatrix).
> 0 votes

---
Tags: c#, unity, shoot-em-up, motion, patterns
---


# Question
Title: Rendering of a minimized / out of focus directx game is slow
I m working on a project that captures the game windows and send it to another node. As long as game is in focus or maximize, the rendering is smooth and steady. When the game is out of focus or minimized, the streaming shows jerky effect. When you maximize the windows, the affect again disappears. Is that an issue of directx game rendering or something else? How this problem can be solved?

# Answer
If the system is not under heavy load, there is nothing inherent in DirectX that will reduce performance for a minimized or background window's process. If the system is under heavy load, the OS may prioritize scheduling of the foreground window's process above other processes.

Games will often intentionally throttle back their rendering when their primary window is minimized or goes out of focus, in order to enable a better experience for users who temporarily alt+tab to another process (e.g. Teamspeak, a web browser, etc.).
> 1 votes

---
Tags: directx
---


# Question
Title: I can't drag'n'drop UI-Elements from the Scene-hierarchy into a public field (Unity 5)
I just watched this Video https://unity3d.com/learn/tutorials/projects/survival-shooter/player-health and tried to drag'n'drop the UI-Elements on the matching script, just like they did. But this is not working for me. If I hover the public field Unity shows up an error icon and I can't drop it there. If I set this UI-Element as prefab I can place it there, but it does not update the Element which is in the Scene when the Code is live. The Elements just gets an update after each restart. Can anybody explain to me why I cannot drag'n'drop my Object from the hierarchy to the public field?

# Answer
Instead of creating a regular game object, create a UI Image ( New \>\> UI \>\> Image/slider/etc.).

The new Unity UI system has specifics that aren't available to normal game objects, so when you make them public they need an exact type to be dragged onto them.

This has been my experience at least, hope it helps.
> 1 votes

---
Tags: unity, gui, objects, hud
---


title: LibGDX Android project in IntelliJ

text:
# Question
Title: LibGDX Android project in IntelliJ
I've created a LibGDX project. I imported the `build.gradle`. The `core` and `desktop` modules are imported successfully, but the `android` not. So I add the content roots. The project compiles, I could build an apk as well via gradle build, but the libgdx android libraries are not imported by the IDE, so classes like `com.badlogic.gdx.backends.android.AndroidApplication` are unresolved. This wasn't a problem so far, because it compiles, but now I'd like to develop Android specific code, so the code completion would be great. Any ideas how I could add the relevant dependencies from the build.gradle?

# Answer
As workaround, I personnaly use Android Studio which is based on Intellij Idea when developping LibGdx app for Android. Just import build.gradle in Android Studio, and you should be ready to edit your core, desktop and Android libGDX project without any further configuration.
> 1 votes

# Answer
Like Khopa has stated, use Android Studio. I still a beginner bit of a beginner to libgdx, but so for I have found that Android Studio covers all of my needs. You can even run the desktop version from A.S. and on the plus side, you can easily emulate an android device using the built in intel HAXM, only works with intel cpu's. For AMD use genymotion, which A.S. integrates into the IDE.

All you have to do is build the LibGdx project then load build.gradle from A.S. Make sure to build the game within core. Hopes this helps, have fun!
> 1 votes

---
Tags: libgdx, gradle
---


# Question
Title: Animate/Interpolate and wait for completion.
I'm implementing a blackjack game in flash and so far the logic is fine but there is no animation for the cards so they just appear and disappear which doesn't look very pleasing to the eye. I want to add some animations for when cards are dealt where they slide across to their position one by one.

Is there a simple way to just tell a displayobject to interpolate from one position to another while waiting for it to complete?

My current thought would be to just do something like this:

```
on enter frame:
   if a card is animating:
      move it further towards its destination;
      continue;
   else (if it is done animating):
      process as usual;
   end;
end;

```

I believe this would produce the results I'd expect because the game should only continue after the card being dealt is where it should be. However, this feels like a weird approach and I'm probably over thinking it which is why I'd like to know if any of you have a better solution.

# Answer
You are wanting to "lerp" between two Vectors, although I cannot tell you how to do it in AS3. The position will be based on a start-point, an end-point, and a % between the two. The % is usually a value of accumulatedAnimationTime divided by totalAnimationTime.

You could also use a multiple of the % to spin the cards as they move into place, etc.

```
(in degrees) rotation = lerp(0, 1440, percent) //spins card 4 times while landing

currentPosition = lerp(start, end, percent) == (start + (percent * (end - start)))

```

The Bezier formula is only slightly more complex; worth a Google.

Edit: The Bezier in my image is cubic, except that the two intermediate points are coincidental. Using only 3 positions, you can reduce it to the quadratic Bezier formula.

```
float3 QuadraticBasis(float t)
{
    float invT = 1.0f - t;
    return float3(invT * invT, 2.0f * t * invT, t * t);
}
float3 QuadraticBezier(float3 input[3], float percent)
{
    float3 basis = QuadraticBasis(percent);
    return (input[0] * basis.x + input[1] * basis.y + input[2] * basis.z);
}

```

For a visual explanation, refer to the animations about 2/3 of the way down the Bezier wiki
> 1 votes

# Answer
While it's certainly possible to implement the animation yourself (see Jon's answer), I'd suggest to use a tweening library for that.

There are lots of AS3 tweening libraries available. Personally I used the GreenSock Tweening library a lot. Several AS3 game frameworks (such as Starling or Flashpunk) already have tweening implemented.
> 0 votes

---
Tags: actionscript-3
---


# Question
Title: How to move objects in any direction by swiping with libgdx android game development
first of, I'm new to android game development so I don't know all the classes and dictionaries within android and libgdx. I'm actually following a game development tutorial for the first time (kilobolt) but I already have some ideas for games I want to make after finishing the tutorial. So here's my question:

Let's say you have a box with a small ball in it. When you touch-hold the ball, you hold the ball "in your hand". Then you swipe across the screen with the ball in hand and "let go" (release touch), the ball rolls in the direction you swiped with the speed of your swipe, decreasing in speed according to a set friction.

Is it possible to implement such a function with libgdx? If yes, could you please explain how to make it?

# Answer
> 1 votes
This may help a bit. As for knowing how to do what you exactly want to do, I would need hours of trial and error as I am also a bit of a beginner.

```
    public void create() {
        gestureDetector = new GestureDetector(HALF_TAP_SQUARE_SIZE,
        TAP_COUNT_INTERVAL, LONG_PRESS_DURATION, MAX_FLING_DELAY, new
        GestureHandler());
        Gdx.input.setInputProcessor(gestureDetector);
    }

```

The class that you are calling.

```
    public class GestureHandler implements GestureListener
    {
        public boolean touchDown(float x, float y, int pointer, int
        button);
        public boolean tap(float x, float y, int count, int button);
        public boolean longPress(float x, float y);
        public boolean fling(float velocityX, float velocityY, int
        button);
        public boolean pan(float x, float y, float deltaX, float
        deltaY);
        public boolean panStop(float x, float y, int pointer, int
        button);
        public boolean zoom(float initialDistance, float distance);
        public boolean pinch(Vector2 initialPointer1, Vector2
        initialPointer2, Vector2 pointer1, Vector2 pointer2);
    }

```

I learned a lot from this guy, check him out https://www.youtube.com/watch?v=N9AqGS\_Tlnw&list=PL6gx4Cwl9DGBsvRxJJOzG4r4k\_zLKrnxl&index=75

Also check out the libGdx demos, gives a better understanding how what is used and how to organize files: https://github.com/libgdx/libgdx/wiki/Running-Demos

I hope this helps.

---
Tags: android, libgdx, game-mechanics, gameobject, game-component
---


# Question
Title: rendering an image within c# & sharpdx dirext3d9 [game overlay]
I'm following this guide and the related blog post to implement a basic game overlay for DirectX 9 games using SharpDX.

So the tutorial already have an example for text rendering but I need to be also able to render a provided image to the overlay.

Any ideas, guides?

# Answer
> 1 votes
For DirectX 9 you can use a texture and a sprite. In DXHookD3D9.cs you could do something like the following in "DoCaptureRenderTarget". Don't create the resources each frame but for simplicity here it is all together.

```
// Create resources
SharpDX.Direct3D9.Texture tex = null;
Sprite sprite = null;
tex = SharpDX.Direct3D9.Texture.FromFile(device, filename);
sprite = new SharpDX.Direct3D9.Sprite(device);
// to resize/rotate/position sprite.Transform = some 4x4 affine transform matrix (SharpDX.Matrix)

sprite.Begin(SharpDX.Direct3D9.SpriteFlags.None);
SharpDX.Vector3 pos = new SharpDX.Vector3(0, 0, 0);
SharpDX.Color color = new SharpDX.ColorBGRA(0xffffffff);

sprite.Draw(tex, color, null, null, pos);

// Finish drawing
sprite.End();

```

---
Tags: directx, directx9, sharpdx, overlay
---


# Question
Title: Do Game Objects which lay outside camera view consume computer/mobile resources in Unity?
In unity, let us suppose that I have some Game Objects in my scene that are not visible to camera and so are not rendered while the game is running.

Will these Game Objects be consuming computer/mobile resources when the game is running?

Where can I find details about usage like these?

# Answer
What you want is a memory profiler, Which Unity does have. Here: http://docs.unity3d.com/Manual/ProfilerMemory.html

But your assumption is mostly right, if a gameObject is not visible to the camera it is not drawn, and it uses less resources, but it still must consume some. The gameObject still exists in memory, including all the textures, models scripts etc.. it also still consumes CPU time through the Update and FixedUpdate methods (and various others described here).

But usually the major slowdown is the drawing, a small amount of CPU time is used to determine that the object is outside the camera frustum (bounds), but no drawing is done.
> 13 votes

# Answer
I think you should also know about Frustrum Culling, or hiden surface removal: http://en.wikipedia.org/wiki/Hidden\_surface\_determination

This is an important bit of optimising a game, because even if your objects are not inside the frustrum at a given frame (i.e. visible), some draw calls (shaders) are still launched for them, therefore decreasing performance.
> 5 votes

# Answer
The short answer is "yes"; anything that is ready to be used in your game is taking up memory.

The other thing to consider is the cost to your frame-rate:

5 objects, with 5 separate textures, drawn separately require state-changes in-between. You may be able to save some memory by unloading textures that aren't used.

By loading all of the separate textures into a single atlas texture, the memory footprint becomes fixed and you can no longer unload an individual texture. Once created, you only have to bind the atlas once to draw all of your objects.

Another example is a simple vertex and index buffer. If many of the points frequently toggle between visible and not, it is faster to leave the "stale" points in the vertex buffer and only upload a new index buffer.

There are many others times where an increased up-front memory cost is preferable to many state-changes.

> If you rotate your camera, you definitely will not destroy those objects unless you know, that camera will not rotate back to check on that object." – Katu

Using a side-scroller as an example, if you can only move to the right (the map only scrolls to the left), any object that scrolls off the left side of the screen can be permanently unloaded since you will never use it again. Additionally, content for objects can be demand-loaded right before the object scrolls into view from the right.
> 3 votes

# Answer
A lot of answers are mainly considering the graphics aspect of your question.

The fact is they will take up various resources, and how expensive they are compared to drawing the object isn't fixed. It's not as uncommon as some answers implied for your components to be making more expensive operations than drawing does, but you can minimize how many resources they use. Also keep in mind that a GameObject takes up a small amount of memory, and so do it's components. The components may also be doing things that are taking up a fair bit of memory.

The simplest way to minimize the effect of off-screen components is a system based on the OnBecameVisible and OnBecameInvisible callbacks.

```
void OnBecameVisible()
{
    myComplexComponent.enabled = true;
}
void OnBecameInvisble()
{
    myComplexComponent.enabled = false;
}

```

Of course, that's of very limited usefulness since there are plenty of times when you'll want an off-screen object to affect the game. But you can expand on a pattern of this sort for a fine-grained system capable of minimizing the effect of your most expensive calculations. Even something as simple as reducing something like the quality of a path following script when the object is off-screen can result in big savings in the long run.
> 1 votes

# Answer
It takes memory to keep it alive and update its position and other properties.

But it doesn't consume computer/mobile graphic resources since it is not visible.

### So yes, it does consume memory resources but not graphics resources like a visible Game Object does.
> 1 votes

# Answer
Anything that is in a program consumes resources; You don't think programs run on simply hopes and dreams, do you?

The question should be how much resources does a game object consume, and to that end I think this is a pretty solid answer: http://answers.unity3d.com/questions/280455/how-much-memory-a-gameobject-consume.html

In short, they consume negligible resources on their own. But why would you want a bunch of game objects just sitting in your game doing nothing? At the end of the day, what you actually make those game objects 'do', is what is going to cause any sort of overhead- and how much resources that requires is very much on a case by case basis.
> 0 votes

---
Tags: unity, memory-efficiency
---


title: Geometry shader and triangle adjacency

text:
# Question
Title: Geometry shader and triangle adjacency
I'm currently trying to change my project to use GL\_TRIANGLE\_ADJACENCY instead of GL\_TRIANGLES.

Following this question, I have managed to construct my index buffer fine, but when it comes to the drawing stage, I'm getting unexpected results.

Here is my geometry shader code. Bare in mind that I store my indices like so:

(`vertex1/adjacent1/vertex2/adjacent2/vertex3/adjacent3`)

**Geometry Shader**

```
    #version 330

    precision highp float;

    layout (triangles_adjacency) in;
    layout (triangle_strip, max_vertices = 3) out;

    smooth in vec2 vVaryingTexCoords[];
    smooth in vec3 vVaryingNormals[];

    smooth out vec2 gsUV;
    smooth out vec3 gsNormals;

    void main(void)
    {
        int i;

        for(i = 0; i < gl_in.length(); i++)
        {
            switch(i)
            {
                case 0:
                case 2:
                case 4:
                    gl_Position = gl_in[i].gl_Position;
                    gsUV = vVaryingTexCoords[i];
                    gsNormals = vVaryingNormals[i];
                    EmitVertex();
                    break;

                default:
                    break;
            }
    }
    EndPrimitive();
}

```

Any ideas?

**EDIT**

Just like to point out that setting the adjacent index to be the same as the vertex index, i.e `v1/v1/v2/v2/v3/v3` still produces the same results.

# Answer
It is an old question but recently I faced the same problem doing some real time hatching in the geometry shader.

By the sound of your code seems there is nothing wrong in your GS, problem could possibly be in your algorithm to build an adjacency list. I found a good tutorial here, which provides an implementation for finding the adjacent triangles (tutorial is about silhouette detection).

It uses assimp for loading a model, but I'm sure the concept can be extended to any other model loader if you have a face list or a indices list.

hope it helps
> 1 votes

---
Tags: opengl, glsl, geometry, geometry-shader
---


# Question
Title: How would you guys call a class to instantiate both NPCs and players?
My idea is having a class to instantiate both NPCs and players. I have thought of some names like Entity but that is way too broad, as it could refer to anything from a block to an event really. I've also thought of Character, but that name seems to refer to only important characters in the story, not any NPC that you might encounter in the world. It's a pretty straightforward question, yet I've been racking my brain for about an hour and can't seem to get any useful ideas.

Thanks guys, and peace.

# Answer
> 1 votes
```
class Actor
{
   Vector3 position;
   ect..;
   ect..;
};
class PlayerCharacter : public Actor
{
   //input stuff
};
class NonPlayerCharacter : public Actor
{
   //AI stuff
};

```

# Answer
> 1 votes
In Unity Game Engine, I like to use a factory to create these objects;

```
class ObjectManager{
    public GameObject CreatePlayer() {
        ...
    }
    public GameObject CreateNpc() {
        ...
    }
}

```

Just attach Different Component to GameObject to make players or npcs.

```
public GameObject CreatePlayer() {
    var g = new GameObject();
    g.AddComponent<PlayerAI>();
    return g;

```

}

```
public GameObject CreateNpc() {
   var g = new GameObject();
   g.AddComponent<NpcAI>();
   return g;

```

}

# Answer
> 0 votes
I suggest the class name : Dude

---
Tags: character
---


title: GameObject scope over RPC call

text:
# Question
Title: GameObject scope over RPC call
Debugging my code I faced some unexpected behavior.

I called an RPC using `uLink.NetworkView` on the server passing some parameter including a `GameObject` tagged as `Player`.

Inside that RPC I make a call to `GameObject.FindObjectsWithTag("Player")`

What I refer to by saying "unexpected" is that that function returns all the gameobjects in hierarchy *INCLUDING* the gameobject passed as parameter to the RPC call.

I noticed that inside the editor it appears in hierarchy the gameobject passed to the RPC but without all the components *BUT* the transform.

My question is to know exactly how the scope is working, I seem to understand that the scope of the FindObjectsWithTags seems to include RPC parameters but without the most informations.

Any clue about this?

# Answer
http://docs.unity3d.com/ScriptReference/GameObject.FindGameObjectsWithTag.html

Returns a list of active GameObjects tagged tag. Only Find GameObject at root of scene, No recursive.
> -1 votes

---
Tags: unity, networking
---


# Question
Title: How to customize a character with new objects (clothes, body parts) in a 3D game?
how do we customize a character in a game by adding, for example, a different clothing? The character has an armature, made in Blender, if I add a new object with the game engine, I would have to copy the position for each frame, and the orientation?
Or is there a technique to make the model in Blender with different meshes, find the meshes in the .dae file (for scenekit, but it might be the same for fbx for unity), and replace it with a new object, and the orientation will be automatically copied?

Has anyone had some experience with this?

Thanks

# Answer
Parent the objects to bones and they will move with the bones.
> 5 votes

# Answer
this problem is divided into two situations：

### first: sword,

this thing can be just parented to the bone, then it will move with bone;

### second: cloth,

in blender, you need to use the same armature, then create two different cloth, and rig the cloth mesh to the armature.

in unity3d, read this article:

http://forum.unity3d.com/threads/stitch-multiple-body-parts-into-one-character.16485/
> 5 votes

---
Tags: unity, 3d, character
---


title: 2D soft-body physics engines?

text:
# Question
Title: 2D soft-body physics engines?
Hi so i've recently learned the SFML graphics library and would like to use or make a non-rigid body 2D physics system to use with it. I have three questions:

The definition of **rigid body** in Box2d is

> A chunk of matter that is so strong that the distance between any two bits of matter on the chunk is completely constant.

And this is exactly what i don't want as i would like to make elastic, deformable, breakable, and re-connection bodies. **1. Are there any simple 2D physics engines, but with these kinds of characteristics out there?** preferably free or opensource?

**2. If not could i use box2d and work off of it to create it even if it's based on rigid bodies?**

**3. Finally, if there is a simple physics engine like this, should i go through with the proccess of creating a new one anyway, simply for experience and to enhance physics math knowledge?** I feel like it would help if i ever wanted to modify the code of an existing engine, or create a game with really unique physics.

Thanks!

# Answer
You can use rigid body systems to create soft body and fluid dynamics. Physical reason behind it? Well, essentially, atoms are small rigid bodies. This isn't completely true of course, but for simplicity you can view them as such. And soft bodies are obviously made from atoms.

So, how do you create "soft bodies" using a rigid body engine like Box2D?

The essential technique is to bind points in your body together using joints. For example, if you connect the ends of a list of lines together using distance joints (meaning the distance between two joints must be constant), it will roughly behave like a piece of cloth.

But that's just a rough description. A lot of "elementary field work" with Box2D has been done by ewjordan, one of the developers of the Java-port of Box2D. Here's a good starting point: http://www.box2d.org/forum/viewtopic.php?f=8&t=1978
> 6 votes

# Answer
The term you are looking for is soft-body physics.

Wikipedia has a nice list. They're all 3D AFAICS, but should be good.

Also check out this SO question.

A great book (it's rigid body, but all the maths and physics are there; it's also 3D, but is trivial to transfer to 2D) is Game Physics Engine Development. It implements a particle based system before moving onto rigid bodies and collision.
> 2 votes

# Answer
One simple way to simulate soft bodies is to connect together small rigid bodies with elastic joints. Then the difficult part is to fine tune your model's parameters and map the texture to the underlying model.

The following blog post provides an implementation of a deformable ball with cocos2d engine: http://2sa-studio.blogspot.com/2014/05/soft-bodies-with-cocos2d-v3.html
> 1 votes

---
Tags: c++, physics
---


title: Is OnMouseUp()'s behavior intended?

text:
# Question
Title: Is OnMouseUp()'s behavior intended?
**Version:** Unity3D 4.6.2f1

I have a grid of tiles (Cube `GameObject`s with a `Tile` script attached). They are positioned at their index location `[x][y] = (x, y, z=0) World Coordinates`.

Below, I try to get the coordinates of the tile upon which the mouse left click is released.

Before into code:

> * **`OnMouseDown()`** \- OnMouseDown is called when the user has pressed the mouse button while over the GUIElement or Collider.
> * **`OnMouseUp()`** \- OnMouseUp is called when the user has released the mouse button.

Based on these definitions, *I assumed (mistake?) `OnMouseUp()` would be called by the object that above it, the mouse left click was released.*

On the `Tile` script, I have the following :

```
public class Tile : MonoBehaviour
{
    // variables
    private Vector2 _gridPosition = Vector2.zero;

    public Vector2 GridPosition
    {
        get { return _gridPosition; }
        set { _gridPosition = value; }
    }

    // functions
    string Vec2toText(Vector2 v)
    {
        return String.Format("(" + v.x + ", " + v.y + ")");
    }

    void OnMouseDown()
    {
        Debug.Log("TILE:: ON_MOUSE_DOWN:: " + Vec2toText(_gridPosition));
    }

    void OnMouseUp()
    {
        Debug.Log("TILE:: ON_MOUSE_UP:: " + Vec2toText(_gridPosition));
    }

    void OnMouseEnter()
    {
        Debug.Log("TILE:: MOUSE_ENTER: " + Vec2toText(_gridPosition));
    }

    void OnMouseExit()
    {
        Debug.Log("TILE:: MOUSE_EXIT: " + Vec2toText(_gridPosition));
    }
}

```

And here is the output:

```
TILE:: MOUSE_ENTER: (15, 15)
TILE:: MOUSE_DOWN: (15, 15)
TILE:: MOUSE_EXIT: (15, 15)
TILE:: MOUSE_ENTER: (14, 15)
TILE:: MOUSE_UP: (15, 15)    %% This line
TILE:: MOUSE_EXIT: (14, 15)

```

I would expect `OnMouseDown()` to be called by the object on which the mouse button was pressed (no problem here) and `OnMouseUp()` to be called by the object on which the mouse button was released (instead, it is called by the same object as `OnMouseDown()`).

Is this -- calling two functions by the same object even though I pressed left click some object and released it on some other object -- intended?

# Answer
I believe it is, because otherwise an object which is clicked won't be able to determine when the mouse button is released again.

The best alternative I can think of is raycasting.

Put all objects which can possibly be in front of the tiles in the `Ignore Raycast` layer.
Then, from a "manager" script, cast a `Raycast` from the mouse cursor's position into the world, check which tile is being clicked, store the clicked `GameObject` in a variable `lastClicked`, and call some kind of method in its `Tile` script to tell that it was clicked, each update.
When the current hovered object is no longer equal to the `lastClicked` object, call some kind of method in the `Tile` script to tell that tje tile is no longer clicked.

Just ask me if you want a code example!

Best regards
*TheDDestroyer12*
> 0 votes

---
Tags: c#, unity, events, callbacks
---


# Question
Title: Game Maker Studio - how do I disable mouse click for a duration of time?
I Have a button that starts in a rest state, and then after clicking on the button, it animates out. I want to disable the mouse click for around 30 steps after the button has been clicked, otherwise the player will be able to constantly click on the button, which resets the animation and messes up my menu.

Is there any way to disable the mouse click for a duration of time before enabling it again?

This is the code I have used to try and make the variable "click" alternate between true and false (it is supposed to remain false while alarm\[0\] is between 30 and 0).

Initially (in the create event)

```
click = false;
alarm[0] = -1;
alarmReset = true;

```

this is the code found in the step event:

```
if(mouse_check_button_pressed(mb_left))
{
    if(alarmReset == true)
    {
    click = true;
    alarm[0] = 30;
    alarmReset = false;
    }
}

if (alarm[0] > 0 )
{
    if (alarm[0] < 30)  click = false;
}
if (alarm[0] < 0 ) alarmReset = true;

```

When running this code, "click" is initially false, but when I click, it gets set to true, and then is never set to false again. Any help would be appreciated.

# Answer
> 2 votes
I would do this

```
if(mouse_check_button_pressed(mb_left) && click)
{
    click = false;
    alarm[0] = 30;
}

```

Then in your alarm\[0\] event say

```
click = true;

```

That way you don't have to check on what state the alarm is in all the time.

---
Tags: mouse, timer, game-maker
---


# Question
Title: Update single variable in DirectX Shader
I am trying to update a single variable within a CBuffer but I am unsure of how to do this.

I have a LightingBuffer which is passed to the GPU containing, ambient color, diffuse color etc and I want to be able to update the specularPower component of this CBuffer but not the rest.

In openGL I could just do glUniform1f and update it, however I cannot do this is DX / HLSL

How would I go about doing this?

# Answer
> 4 votes
In DirectX 10.x/11.0, constant buffers are intended to be updated as a unit (i.e. you have to update the whole thing). This is why our performance recommendations is to arrange your data in constant buffers by frequency of update rather than having large cbuffers that contain variables that are updated frequently (per-object) and others that are updated occasionally (per-frame or on window size changes).

See Windows to Reality: Getting the Most out of Direct3D 10 Graphics in Your Games

With DirectX 11.1 on Windows 8 or later, and appropriate drivers, you can make use of partial constant buffer updates with constant offsets. It's an optional hardware feature indicated by `D3D11_FEATURE_DATA_D3D11_OPTIONS.ConstantBufferPartialUpdate` and `D3D11_FEATURE_DATA_D3D11_OPTIONS.ConstantBufferOffsetting`. This allows you to use new parameters on `ID3D11DeviceContext1::XXSetConstantBuffers1` to achieve partial updates.

These optional hardware features are not supported with DirectX 11.1 on Windows 7. See MSDN.

# Answer
> 3 votes
From the question, this appears to be more a design problem rather than an API problem: **specular power is not a property of the light, it's a property of the surface**. By including it in your light properties cbuffer you're creating an artificial coupling between these two different classes of property, and it's likely to cause you further problems in the future.

There are a few different ways you can solve this.

**Use a separate surface properties cbuffer**

Right now specular power might be the only surface property you want to change, but in the future you might want to add more. Remember that cbuffer registers are groups of 4 floats (I'm deliberately ignoring other data types for the purpose of simplicity and clarity here) so if you update one float you effectively get 3 more float updates for free.

**Use instancing**

Add these per-surface properties to a per-instance buffer, adjust your input layout to match, and make a DrawInstanced or DrawIndexedInstanced call. Pass the values directly from the VS to the PS if required. Remember that *1 is a valid value for InstanceCount*. We should also note here that *all draw calls in forthcoming APIs are instanced draw calls*, so this suggests that we don't need to worry about instancing overhead going forward: there is none.

**Encode specular power in a texture**

This is the most flexible method and would let you vary the power across a surface: some parts of the surface may have a different specular power to other parts. It does of course come with the added cost of extra texture memory (but remember that it can be a lower-resolution texture) and an extra texture lookup (although you could abuse the alpha channel of an existing texture to hold it). Again, if you ever need to expand to other surface properties you can use e.g a 4 channel RGBA texture with each channel holding a different property.

---
Tags: graphics, directx11, hlsl
---


# Question
Title: Separating axis theorem implementation flaky minimum translation vector based on triangle orientation
I've implemented some collision detection using separating axis theorem. Works fine for axis-aligned rectangles and two out of four possible right triangle orientations. For some reason when the hypotenuse is oriented down left or up right, the minimum translation vector being calculated is that of the normal of the base or height of the triangle rather than the hypotenuse that is being collided with.

https://i.stack.imgur.com/W5WHH.png

I've got a jsfiddle demo of my implementation. The center box and right side triangles all show a correct MVT when the collision box collides with them. The ones on the left side do not. Move your mouse over the canvas to move the collision box.

http://jsfiddle.net/XLtdB/

# Answer
I know this is a very old question, but for those trying to use this code to make a collision engine (like me), I will present a solution, though not a very elegant one:

For a reason I haven't yet identified, flipping the hypotenuse normal of the 'broken' triangles corrects the collision resolution.

Hope this helps:)
> 1 votes

---
Tags: collision-resolution, separating-axis-theorem
---


title: FindNextValidTechnique fails

text:
# Question
Title: FindNextValidTechnique fails
My effect file compiles successfully, but `FindNextValidTechnique` fails.

Technique part of the shader:

```
technique Diffuse
{
    pass Pass0
    {
        VertexShader = compile vs_2_0 VertexShaderMain();
        PixelShader = compile ps_2_0 PixelShaderMain();
    }
}

```

I try to get the first valid technique after compilation:

```
pEffect->FindNextValidTechnique(NULL, pValidTechnique);

```

This returns some minus value which doesn't go along with `D3D_OK`.

I've used other flags than `D3DCREATE_HARDWARE_VERTEXPROCESSING` to test, but no result with them either.

**UPDATE**

I've read in documentation that, "Applying Compiler Flags or Assembler Flags to the incorrect API will fail shader validation.", but I'm not sure this applies to the compile time validation or afterwards. I have no problem in compile.

I compile with these flags:

```
D3DXSHADER_DEBUG |
D3DXSHADER_NO_PRESHADER |
D3DXSHADER_FORCE_VS_SOFTWARE_NOOPT |
D3DXSHADER_FORCE_PS_SOFTWARE_NOOPT

```

# Answer
I didn't get `FindNextValidTechnique` to work and I resorted to `ValidateTechnique` instead. I used the base method `ID3DXEffect::GetDesc` to get effect description and then counted techniques through a for loop and checked each technique:

```
D3DXHANDLE* pValidTechnique = NULL;

for (unsigned int i = 0; i < effectDesc.Techniques; i++)
{
    D3DXHANDLE technique = pEffect->GetTechnique(i);

    if (pValidTechnique == NULL)
    {
        if (pEffect->ValidateTechnique(technique) == S_OK)
        {
            pValidTechnique = &technique;

            break;
        }
    }
}

```

`ValidateTechnique` works while `FindNextValidTechnique` doesn't. Weird!
> 1 votes

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


# Question
Title: SDL2 LogInfo not outputting with different category?
So this is probably really simple but I just cannot see it.

I've made my own log class using the SDL\_Log functions to output to the console. Only thing is, is that it only outputs using one category type only.

For example. I use this:

```
Log::getInstance()->info(Log::getInstance()->CAT_APPLICATION, "This outputs fine.");
Log::getInstance()->info(Log::getInstance()->CAT_INPUT, "This doesn't get outputted");

```

which, in the log class, that uses the following code:

```
void Log::info(int category, const char* message, ...) { SDL_LogInfo(category, message); }

```

and:

```
int CAT_APPLICATION = SDL_LOG_CATEGORY_APPLICATION;
int CAT_INPUT = SDL_LOG_CATEGORY_INPUT;

```

I've also tried the normal method:

```
SDL_LogInfo(SDL_LOG_CATEGORY_INPUT, "but this doesn't get outputted either if the app cat is outputted first");

```

Any ideas on why it's not outputting "CAT\_INPUT" but is outputting "CAT\_APPLICATION"? And how I could get it outputting all of them?

# Answer
> 0 votes
According to Ginkgobitter, All SDL2 Logging Categories except for Application are at SDL\_LOG\_PRIORITY\_CRITICAL, whereas Application is at SDL\_LOG\_PRIORITY\_INFO. Since you are using SDL\_LogInfo(), it uses the SDL\_LOG\_PRIORITY\_INFO, thus hiding all others.

Looking at the documentation, it would appear that most of the categories are for internal SDL use, and that you really should be using SDL\_LOG\_CATEGORY\_CUSTOM as the start of an enum, as reference above.

---
Tags: c++, sdl2
---


# Question
Title: Game Networking: Client request or Server Sending
I'm trying to implement a basic client-server setup for my game. But what confused me was how I would approach sending updates.

Would I do:

1. Server has a tickrate, let's say at 20ms. Each tick would sends an `UDP` package to EVERY connection with the current game state and it's entities.

OR

2. Client request an update from the server and the server respond with the update. When the client receives it, it asks for another update and so on.

Pro-cons:

* 1. Con: Sends a package every tickrate and in this case 20ms. What if a clients broadband connection has a triptime at 300ms? Wouldn't that overload that client and his broadband? Pro: Consistent and fast?
* 2. Con: Requesting is done via `TCP` which is slower because the client has to wait before sending the next request. Pro: no overload?

So my question would be, what I'm I missing and how would I approach sending updates about the current game state?

Cheers!

# Answer
Given what you've wrote I'm guessing that you're working on a real time game, not turn based. So you'll want to send player specific UDP packets continuously at a more or less fixed rate. Do not use full TCP for real time games - if you need TCP-like behavior then emulate it with UDP. This is because both use IP (see also OSI model), and one protocol can interfere with the other.

If only the latest state matters then you don't need to send all changes in every update. Just send the changes that apply to that client. You can even transmit updates piece-wise - one packet contains some position changes, next contains a few more and an entity removal, etc. Essentially you'll architect your client so that it's acceptable to lose some packets and retroactively figure out what must have happened in the intervening time. Various methods of handling this are described elsewhere which amount to creating a very specialized version of TCP.

For example, a player moves from point A to C via point B. If we drop the update containing B, we can do some interpolation to figure out where they must have gone to get to C faster than it'll take a packet containing B to get to the observer.

From the client side perspective, you can use a variable tick rate to only send as many ticks as necessary to keep the server informed. Specifically, you'll want to send at least one packet often enough to indicate that the client is still alive. However, it's much simpler to use a constant update rate - most of the updates will effectively be "did nothing for 20 ms."
> 3 votes

# Answer
**When to send events?**

In a typical game design a particular range is set where the center is the player.

In the server point of view, it does not send you details on what does not concern your range of sight or range your player is affected at. So it does not send events(bandwidth) if it happens on \[another map\] or \[on the same map but you are not in range\]. It depends on how your game was designed.

Note some events are server wide hence it affects all players.

In the clients point of view, it does not send to server if you do not move or do anything unless you got time triggers from the client. Again it depends on how the game was pre-programmed.

**Putting that aside, here's more on server operation.**

On Server side, some good architecture games handles different job per task. Example a game server instance can handle logging in and out while another handles storage/item retrieval and another instance handles map/view updates. This map/view updates can be separated in different instances. Treat each instances as a executable program always running but separate to each operation. It can be operated on a similar physical server or a different server depending on the required performance.

As an example please research on how Ragnarok operates it's engines, it is good way to start.

**UDP & TCP**

TCP are targeted IP so obviously you can use it on client to server updates. UDP can be used by game server for broadcast while client just listens like in LAN games, so depending on your setup you can utilize it as well.

Hope this helps.
> 1 votes

# Answer
For a realtime Game there are two kinds of network packet:

1. client send request then server response
2. server push packet to client

if you want to sync game state such as hp, mp, position, client need to send these state packet to server, then server push these packet to all other clients;

server only send state change of each entities.

so for state sync, you need to use tickrate method;

if client want to initial state, client should use the request-response method.
> 0 votes

---
Tags: networking, multiplayer, client-server
---


# Question
Title: Input Assembler - Vertex Shader linkage error
I'm new to HLSL and have been struggling with this problem for a while and I can't figure it out. I'm getting the below error a number of times in the debug window:

D3D11 ERROR: ID3D10Device::DrawIndexed: Input Assembler - Vertex Shader linkage error: Signatures between stages are incompatible. Semantic 'TEXCOORD' is defined for mismatched hardware registers between the output stage and input stage. \[ EXECUTION ERROR #343: DEVICE\_SHADER\_LINKAGE\_REGISTERINDEX\]

VS\_NORMALMAP\_INPUT:

```
struct VS_NORMALMAP_INPUT
{
    float3 Pos     : POSITION;
    float3 Normal  : NORMAL;
    float3 Tangent : TANGENT;
    float2 UV      : TEXCOORD;
};

```

Vertex Shader:

```
VS_LIGHTING_OUTPUT LightingTransformTex(VS_NORMALMAP_INPUT vIn)
{
    VS_LIGHTING_OUTPUT vOut;

    // Use world matrix passed from C++ to transform the input model vertex position into world space
    float4 modelPos = float4(vIn.Pos, 1.0f); // Promote to 1x4 so we can multiply by 4x4 matrix, put 1.0 in 4th element for a point (0.0 for a vector)
    float4 worldPos = mul(modelPos, WorldMatrix);
    vOut.WorldPos = worldPos.xyz;

    // Use camera matrices to further transform the vertex from world space into view space (camera's point of view) and finally into 2D "projection" space for rendering
    float4 viewPos = mul(worldPos, ViewMatrix);
    vOut.ProjPos = mul(viewPos, ProjMatrix);

    // Transform the vertex normal from model space into world space (almost same as first lines of code above)
    float4 modelNormal = float4(vIn.Normal, 0.0f); // Set 4th element to 0.0 this time as normals are vectors
    vOut.Tangent = vIn.Tangent;
    vOut.WorldNormal = mul(modelNormal, WorldMatrix).xyz;

    // Pass texture coordinates (UVs) on to the pixel shader, the vertex shader doesn't need them
    vOut.UV = vIn.UV;

    return vOut;
}

```

Input Layout:

```
bool CModel::Load( const string& fileName, ID3D10EffectTechnique* exampleTechnique, bool tangents /*= false*/ ) // The commented out bit is the default parameter (can't write it here, only in the declaration)
{
    // Release any existing geometry in this object
    ReleaseResources();

    // Use CImportXFile class (from another application) to load the given file. The import code is wrapped in the namespace 'gen'
    gen::CImportXFile mesh;
    if (mesh.ImportFile( fileName.c_str() ) != gen::kSuccess)
    {
        return false;
    }

    // Get first sub-mesh from loaded file
    gen::SSubMesh subMesh;
    if (mesh.GetSubMesh( 0, &subMesh, tangents ) != gen::kSuccess)
    {
        return false;
    }

    // Create vertex element list & layout. We need a vertex layout to say what data we have per vertex in this model (e.g. position, normal, uv, etc.)
    // In previous projects the element list was a manually typed in array as we knew what data we would provide. However, as we can load models with
    // different vertex data this time we need flexible code. The array is built up one element at a time: ask the import class if it loaded normals,
    // if so then add a normal line to the array, then ask if it loaded UVS...etc
    unsigned int numElts = 0;
    unsigned int offset = 0;
    // Position is always required
    m_VertexElts[numElts].SemanticName = "POSITION";   // Semantic in HLSL (what is this data for)
    m_VertexElts[numElts].SemanticIndex = 0;           // Index to add to semantic (a count for this kind of data, when using multiple of the same type, e.g. TEXCOORD0, TEXCOORD1)
    m_VertexElts[numElts].Format = DXGI_FORMAT_R32G32B32_FLOAT; // Type of data - this one will be a float3 in the shader. Most data communicated as though it were colours
    m_VertexElts[numElts].AlignedByteOffset = offset;  // Offset of element from start of vertex data (e.g. if we have position (float3), uv (float2) then normal, the normal's offset is 5 floats = 5*4 = 20)
    m_VertexElts[numElts].InputSlot = 0;               // For when using multiple vertex buffers (e.g. instancing - an advanced topic)
    m_VertexElts[numElts].InputSlotClass = D3D10_INPUT_PER_VERTEX_DATA; // Use this value for most cases (only changed for instancing)
    m_VertexElts[numElts].InstanceDataStepRate = 0;                     // --"--
    offset += 12;
    ++numElts;
    // Repeat for each kind of vertex data
    if (subMesh.hasNormals)
    {
        m_VertexElts[numElts].SemanticName = "NORMAL";
        m_VertexElts[numElts].SemanticIndex = 0;
        m_VertexElts[numElts].Format = DXGI_FORMAT_R32G32B32_FLOAT;
        m_VertexElts[numElts].AlignedByteOffset = offset;
        m_VertexElts[numElts].InputSlot = 0;
        m_VertexElts[numElts].InputSlotClass = D3D10_INPUT_PER_VERTEX_DATA;
        m_VertexElts[numElts].InstanceDataStepRate = 0;
        offset += 12;
        ++numElts;
    }
    if (subMesh.hasTangents)
    {
        m_VertexElts[numElts].SemanticName = "TANGENT";
        m_VertexElts[numElts].SemanticIndex = 0;
        m_VertexElts[numElts].Format = DXGI_FORMAT_R32G32B32_FLOAT;
        m_VertexElts[numElts].AlignedByteOffset = offset;
        m_VertexElts[numElts].InputSlot = 0;
        m_VertexElts[numElts].InputSlotClass = D3D10_INPUT_PER_VERTEX_DATA;
        m_VertexElts[numElts].InstanceDataStepRate = 0;
        offset += 12;
        ++numElts;
    }
    if (subMesh.hasTextureCoords)
    {
        m_VertexElts[numElts].SemanticName = "TEXCOORD";
        m_VertexElts[numElts].SemanticIndex = 0;
        m_VertexElts[numElts].Format = DXGI_FORMAT_R32G32_FLOAT;
        m_VertexElts[numElts].AlignedByteOffset = offset;
        m_VertexElts[numElts].InputSlot = 0;
        m_VertexElts[numElts].InputSlotClass = D3D10_INPUT_PER_VERTEX_DATA;
        m_VertexElts[numElts].InstanceDataStepRate = 0;
        offset += 8;
        ++numElts;
    }
    if (subMesh.hasVertexColours)
    {
        m_VertexElts[numElts].SemanticName = "COLOR";
        m_VertexElts[numElts].SemanticIndex = 0;
        m_VertexElts[numElts].Format = DXGI_FORMAT_R8G8B8A8_UNORM; // A RGBA colour with 1 byte (0-255) per component
        m_VertexElts[numElts].AlignedByteOffset = offset;
        m_VertexElts[numElts].InputSlot = 0;
        m_VertexElts[numElts].InputSlotClass = D3D10_INPUT_PER_VERTEX_DATA;
        m_VertexElts[numElts].InstanceDataStepRate = 0;
        offset += 4;
        ++numElts;
    }
    m_VertexSize = offset;

    // Given the vertex element list, pass it to DirectX to create a vertex layout. We also need to pass an example of a technique that will
    // render this model. We will only be able to render this model with techniques that have the same vertex input as the example we use here
    D3D10_PASS_DESC PassDesc;
    exampleTechnique->GetPassByIndex( 0 )->GetDesc( &PassDesc );
    Device->CreateInputLayout( m_VertexElts, numElts, PassDesc.pIAInputSignature, PassDesc.IAInputSignatureSize, &m_VertexLayout );

    // Create the vertex buffer and fill it with the loaded vertex data
    m_NumVertices = subMesh.numVertices;
    D3D10_BUFFER_DESC bufferDesc;
    bufferDesc.BindFlags = D3D10_BIND_VERTEX_BUFFER;
    bufferDesc.Usage = D3D10_USAGE_DEFAULT; // Not a dynamic buffer
    bufferDesc.ByteWidth = m_NumVertices * m_VertexSize; // Buffer size
    bufferDesc.CPUAccessFlags = 0;   // Indicates that CPU won't access this buffer at all after creation
    bufferDesc.MiscFlags = 0;
    D3D10_SUBRESOURCE_DATA initData; // Initial data
    initData.pSysMem = subMesh.vertices;
    if (FAILED( Device->CreateBuffer( &bufferDesc, &initData, &m_VertexBuffer )))
    {
        return false;
    }

```

Any advice to help diagnose this problem will be much appreciated. I apologize if I provided to much code.

# Answer
> All the meshes are loading in from .x files by the CModel class

Loading them means parsing all of the binary data into Vertex/Index buffers. While filling those Vertex buffers, it is creating a specific type of vertex; i.e. VertexPositionNormalTexture. When you draw any mesh, you are feeding the IA VertexPositionNormalTexture's.

> Please confirm that you are creating per-mesh input layouts.
> Yes I am I think.

By using per-mesh InputLayouts, the IA cannot find them in the right place/order. In all cases, the InputLayout should match exactly what the IA will be fed; you cannot omit them here. In other words, the IA always sees the entire vertex.

The VS can, then, pick and choose semantics out of the assembled input to use. If the VS only asks for Position and Normal, the IA will skip over the unused data and arrive at the same register, for the same semantic, every time.

```
struct VertexPositionNormalTexture
{
public:
    VertexPositionNormalTexture();
    static const int ElementCount = 3;
    static const D3D11_INPUT_ELEMENT_DESC InputElements[ElementCount];
    Vector3 Position;   //R1
    Vector3 Normal;     //R2
    Vector2 UV;         //R3
};
InputLayout (out-of-order)
{
    { "POSITION", 0, ... }, //R1
    { "UV", 0, ... },       //R2
    { "NORMAL", 0, ... },   //R3
};
InputLayout (mismatch and/or out-of-order)
{
    { "POSITION", 0, ... }, //R1
    { "UV", 0, ... },       //R2
};

```

If the IA didn't complain, this would happen (each {} is an input to the VS):

```
{Position, Normal}, {UV, Position}, {Normal, UV}, {Position, Normal}, etc.

```

> Thanks for the explanation. Do you suggest I hard code the InputLayout for each mesh?

I suggest you determine which vertex format the .x compiler defaults to and just use it directly. When creating the input layout:

```
CreateInputLayout(VertexPositionNormalTexture::InputElements, VertexPositionNormalTexture::ElementCount, ...);

```
> 0 votes

---
Tags: c++, hlsl
---


# Question
Title: Do I have to commit the downloadable assets for Unity to the repo? Or a reference for the team to download them?
**QUESTION (Short version)**

I am going to use the `Unity Test Tools` asset to do unitary testing. Q: Do I have to commit the `Unity Test Tools` to my repo? (using `git`, by the way).

**CONTEXT**

Team / Workflow

* We are an indie team of 10 people (of which 4 coders, 2 graphics, 1 music, 2 marketing, 1 automation-test QA), remotely located.
* We built the team 2 weeks ago, have explored Unity, decided that unity shall be our devel framework, and finally we did an internal silly tic-tac-toe internal for us to check the workflow.
* Now we want to start developing our 1st game. Clean code. **Clean repo.**
* Using `git` for version control.
* We configured Unity to write all forced in *text* and *visible metas*.
* We are using Unity5 free edition.

Coding

* Up to now, I've managed to create a MVC schema. `MonoBehaviour` acts as the `Controller` and then we have *non-dependant classes* that act as the `Model` of our game. The controller calls methods of this model. The model throws events to notify the changes in its state.
* We want to **unit-test** the model.

Assets

* Yesterday I discovered the `Unity Test Tools`.
* This is the only downloaded asset, the rest of the assets are made by us.
* The wonderings presented by this question may happen again if we download other assets or if we want to keep a common own-made library across several games.

**QUESTIONS (Long version)**

As far as I've seen, assets get "copied" into your project. Okey for working. But... comitting?? I'm feeling uncomfortable.

The same way in `PHP` you may use `composer` to handle "dependencies" so if you need a library you do not commit it inside your project, you just commit a text file saying "I want this library, this specific version" -for the sake of example, you can tell composer to install `PHPUnit` for unit testing, and you commit the composer text file, you do not commmit a full copy of `PHPUnit`-, these are our questions/wonderings:

**Q1)** Do I have to commit all the `Unity Test Tools` in my repo? It is 10 Megas - may seem an overkill or not, depending on your optics... but, as it carries "examples" and I don't know how to filter what is needed and what not, it seems so overkill to me to commit all of it - but worse: this might happen with another asset that is 500 Megas for example. Committing downloadable assets seems anti-pattern. Do I have to commit?

**Q2)** Or it is better that I don't, and have all the members in the team to *manually* download the `Unity Test Tools`?

**Q3)** If they delete that repo and download it again, the `Unity Test Tools` seem to be kept local to the project, then a new download is imposed if it's not kept in the repo? Or Unity may store "local in your computer; still global to your projects" things like "the testing library" you are likely going to use in several projects?

**Q4)** Case one thinks "maybe each project needs its own version of libraries, best practice is do not keep anything global" then, committing them to the project still seems overkill... is there any standard of "config file" that I can place and then once the "git repo" is cloned, run some kind of "dependency installer" or so (much like the `composer install` action is to a recently cloned repo in `PHP`)?

I've seeked for information, but I'm still confused on this. I've seen it exists something like an "asset manager" but I'm not sure if this is what I need. Any pointer to documentation I must read will be highly appreciated.

*Note that the documentation in Unity website, as for example this one: Mastering Unity Project Folder Structure - Version Control Systems does not address my specific question.*

Thanks!

# Answer
I haven't worked with the asset in question but I work on a small hobbyist unity team and have faced a somewhat similar situation.

As assets may change quite a bit between versions I have found it is easier to keep an asset version I know works in the repo. If the asset is updated then I can download it, check that it still works, possibly update the project so it does and then commit.

As you mention your asset has a lot of stuff that is of little interest to you. You'll often find example scenes with unnecessary art assets, scripts etc when you download assets. I prefer to remove everything I don't need, not so much to save space, mostly to keep everything "clean" or you will have classes with conflicting names, three sets of redundant animations for "jump" etc.

I am in no way an expert in version control so I can't say what is "an antipattern" or not or what is the industry standard, just what I have found to work through trial and error...
> 1 votes

---
Tags: unity, assets, testing, asset-management, version-control
---


# Question
Title: Entity component system, Communication between components
I am trying to implement ECS for my simple 2D game. I would like to ask a question about how components should communicate between themselves and with entity.

I tried to implement few components, like `SpriteComponent`, `MoveComponent`, `CollisionComponent`, etc.. What is the appropriate way of communication between these components? E.g. my Sprite & Physics components need to know about current position, which is affected by Move component. I gave every single of my components handle that refers to the entity, which they can send to engine and call different functions, like `updatePosition(EntityHandle handle, float x, float y)`. Is this the right approach?

# Answer
> 2 votes
I supposed if you want maximum decoupling you would use a message system in order to pass events to your entity (can also happen indirectly with the entity being the listener to your components and broadcasting it to all other listeners/components) and other components can listen to those. I think this is your current approach.

Since you already reference your entity in your component you could ask your entity to return another ("neighboring") component (e.g. entity.getComponent( ID )) and typecast to your required component and pull any information you need or even invoke specific methods. you could also temporary store those (typecast) components as member variables but this might require additional thought on how to properly remove a component (since it might be referenced all over the place).

In a similar manner you could go hybrid and create custom entities implementing specific entity interfaces exposing access to certain components that are common or required by each other to properly work. (e.g. a transformation component that is required by collision, physics, etc) the components entity reference can than be the type of your interface (using generics for example). note that this increases coupling again and one could argue that this approach goes against the whole idea of using an entity component system in the first place.

I found the last approach to be useful for core related entity/components though and you can still implement a highly decoupled message system for application specific custom components.

A very different way to think about it would be to treat components as pure data structures not containing any processing methods the user or engine can invoke directly, but rather implement any component related logic into systems handling the relations between components for each given entity. e.g. having a physic component storing forces applied to your entity and another component storing position/rotation but using a physic system updating those 2 components for each entity. using this approach you are also highly decoupled but it increases complexity in how to efficiently manage entity component relations and is somewhat similar to classical relational database management with your components being pure data queried by systems to perform operations.

I guess a pure message system is probably the most straight forward approach and I suspect that the performance impact the indirect communication causes is neglectable.

---
Tags: c++, entity-system
---


title: Passing of board data in board games

text:
# Question
Title: Passing of board data in board games
Every time I make board game, I am faced with a decision. I have classes for the board and/or game logic, and another for the UI. I don't know how I should pass the board data to the UI. I could make a method on the board class that returns an array which represents the "board state", then just iterate over them on the UI. Or I can make a method that gets the value/s of a single coordinate, e.g. a `getValue(int row, int col)` method. Here are sample codes (in Java):

```
public class Board{
    private int[][] grid;
    private int rows;
    private int cols;

    // Constructor and other methods here, getRows(), getCols(), etc....

    public int getValue(int row, int col){
        return grid[row][col];
    }
}

public class UI{
    private Board board;
    // Constructor and other methods here

    public void someMethod(){
        for(int i = 0; i < board.getRows(); i++){
            for(int j = 0; j < board.getCols; j++){
                // Do something with board.getValue(i, j);
            }
        }
    }
}

```

or I can do this:

```
public class Board{
    private int[][] grid;
    private int rows;
    private int cols;

    // Constructor and other methods here, getRows(), getCols(), etc....

    public int[][] getBoardState(int row, int col){
        int[][] boardcopy = new int[][]

        for(int i = 0; i < board.getRows(); i++){
            for(int j = 0; j < board.getCols; j++){
                boardcopy[i][j] = grid[i][j];
            }
        }

        return boardcopy;
    }
}

```

What should I use? Or if this is debatable, could you just explain the pros and cons of each?

# Answer
> 1 votes
First, although I would side with option 1 ("more OO"), both options are fine in practice; since normal boards are small. **BUT**, this sounds like the classical application for the observer pattern.

The idea here is that your UI has it's state, which is initially derived from the initial state of the board. The UI registers a change handler on the game's model (board) and each time when the board changes it notifies all observers (the UI in this case) of the exact change. The UI then just needs to update what changed. This has the primary advantage that you don't keep updating things that did not change or need to implement exhaustive comparison logic.

---
Tags: java, oop
---


# Question
Title: submeshes and dynamic batching doesnt work as expected
I'm duplicating one object with submeshes frequently, and assigning a random material from five materials to each submesh. There is batching happening, but it's not quite as efficient as I would have expected (details here). Note objects are all less 900 vertices no light maps and ... All are dynamic batching ready

So if dynamic batching works there must be only 5 draw calls right but there isn't there is really much more than 5

# Answer
> 1 votes
In dynamic batching the 900 is that ultimate limit for 1 batch. It means that if you have a mesh with 900 vertices, it will fill a full batch and the next item will create a new batch!

For dynamic batching, Unity has to merge all of your vertices and create a new VBO every single frame. So even if it decreases your number of batches, it may still use a lot of CPU time to create those batches.

By the way, it's not 900 vertices, it's 900 "vertex attributes": http://docs.unity3d.com/Manual/DrawCallBatching.html

"If your shader is using Vertex Position, Normal and single UV, then you can batch up to 300 verts; whereas if your shader is using Vertex Position, Normal, UV0, UV1 and Tangent, then only 180 verts."

---
Tags: unity, performance, optimization, batching
---


title: How to detect the edge of a platform?

text:
# Question
Title: How to detect the edge of a platform?
I have create a enemy AI script. These enemies are animals in my game. What I want is that the enemy can detect the edges of a platform.

```
using UnityEngine;
using System.Collections;

public class EnemyAI : MonoBehaviour {

    public float walkSpeed = 2.0f;      // Walkspeed
    public float wallLeft = 0.0f;       // Define wallLeft
    public float wallRight = 5.0f;      // Define wallRight

    float walkingDirection = 1.0f;
    Vector2 walkAmount;

    float originalY; // Original float value

    void Start () {
        this.originalY = this.transform.position.y;
    }

    // Update is called once per frame
    void Update () {

        walkAmount.x = walkingDirection * walkSpeed * Time.deltaTime;

        if (walkingDirection > 0.0f && transform.position.x >= wallRight) {
            walkingDirection = -1.0f;
            Flip();
        } else if (walkingDirection < 0.0f && transform.position.x <= wallLeft) {
            walkingDirection = 1.0f;
            Flip();
        }

        transform.Translate(walkAmount);
    }

}

```

First of I store the original Y value inside a variable, so the object will be positioned on the platform I chose. Then in update it will do the walk animation.

**Problem**

I am now searching for a solution, so that the gameObject of enemy can detect the edges of the platform and turn away from it.

Looking out for some suggestions!

# Answer
> 1 votes
I would've added collider around the edges that will collide only with these characters' bodies. Then use OnCollisionEnter event (and maybe also check the tag of the colliding object) to turn around.

Could also use ray-casting... but I like the collider solution better. It's much more reliable.

---
Tags: unity, 2d
---


# Question
Title: What's the correct way to move 2d sprites in opengl 2.1?
I'm getting into Opengl 2.1 and wanted to know how can I move 2d sprites. I already created my vbo and ibo, and the vertex data is already there. But, how can I move a sprite once it's already drawn?

Should I update the vertex data with glBufferSubData(I don't think that's efficient), or whould I use glTranslate3f? If I use glTranslate I move all the sprites in the screen.

Any help appreciated, thanks!

# Answer
The usual way to do this in openGL 2.1 would be to draw each one like this (pseudocode):

```
    applyCameraTransformation();

    for sprite in sprites:
         glPushMatrix();
         glTranslate3f(sprite.x, sprite.y, sprite.z);
         sprite.draw();
         glPopMatrix();

```

However, notice that you now have many more draw calls, and each one has to send its own 4x4 matrix (16 floats altogether). If you can just update a single VBO, send all of the sprite data at once and then render it with a single draw call, then you would probably find that this is faster. As you add more sprites, this might become unwieldy, but less data sent and fewer calls to the graphics card will probably be faster.

At any rate, it's probably best to do whatever is easiest for you now and speed it up later if you have to. No matter what, drawing a bunch of 2D sprites is going to be pretty fast.
> 2 votes

# Answer
ochi12 you asked this question

https://gamedev.stackexchange.com/questions/97624/opengl-my-triangle-is-always-the-same-color

they closed your thread, but I understand the question. You asked why the color does not change, you need to send the vertex and color to the vertex shader then from there to the fragment shader, you try to send the vertex to one shader and the color to the other, the color must also go through the vertex shader.

in vec4 Color; in the frag shader is not enough.

add

in vec4 Color; to the vertex shader out vec4 frag\_Color;

and then use in vec4 frag\_Color; in the frag shader.

Or that worked for me.

Or that worked for me to get shader working for first time, I didn't see a way to PM you, so posting this in this other thread of yours.
> 0 votes

---
Tags: opengl, graphics-programming, c
---


# Question
Title: Script attached to one button triggers other buttons too in unity
As you can see in the image above, I have 4 buttons.

I have attached a C# script to only one button to change the scene on click.

Now the scene should change only when I click on the button to which I have attached the script.

But the scene changes even if I click anywhere else on the screen.

This is the script that I have attached -

```
public class ButnDoSmthng : MonoBehaviour {

        void Update () {

        if (Input.GetMouseButtonDown(0))
            Application.LoadLevel ("Scene1");
    }
}

```

Whats wrong here and what might be a solution ?

# Answer
`Input.GetMouseButtonDown(0)` will return true whenever mouse button `0` is pressed, no matter if the mouse is only pressed over the object that has that code in it's script.

You might be thinking, instead of `Update` to use `OnMouseDown()`, which only activates when that object's collider is clicked. But, you'd still being using Unity's buttons wrong.

What you need to do is a create a public `SceneChange` method, doesn't even have to be in a script attached to your button, just somewhere in the scene, perhaps on a `GameManager` object. Then is that `OnClick` event that's in your Button properties:

Under `Runtime` where it currently says `Button`, select the object that's holding the script with your `SceneChange` method. Then the drop down to the right will populate with a list of scripts, and sublists of their public methods. Select your `SceneChange` method from that drop down.

Now when your button is clicked, it'll fire an event which will trigger your `SceneChange` method, and it'll only be from the button you choose.

See this tutorial from Unity for a walkthrough of how to create these methods.
> 2 votes

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


title: Callback on Derived Class?

text:
# Question
Title: Callback on Derived Class?
How does Unity3D implement their system where if a class is derived from MonoBehaviour and has certain methods like Awake() or Update(), they are called accordingly? I want to do a similar system for classes inheriting from the class 'Ability' to store the classes in an array and call the callback method Execute() when they are being executed.

# Answer
We just have to declare Awake, Update, and any other function created by us, to be public and virtual on the parent. Override the function on the children.

```
public class AgentBehaviour : MonoBehaviour
{

    public virtual void Awake()
    {
        // your code here
    }

    public virtual Vector3 GetVector3 ()
    {
        return new Vector3();
    }
}

public class Seek : AgentBehaviour
{

    public override void Awake()
    {
        // in case you need to call the parent's Awake
        base.Awake();
        // and then add any other code
        // here
    }

    public override Vector3 GetVector3()
    {
        return Vector3.zero;
    }
}

```
> 4 votes

# Answer
As pctroll said, the right solution for you is to use virtual functions.

To answer the question "how does Unity do that" without virtuals (i.e.: you don't have to override `Awake` or `Update` in `MonoBehavior` derived classes) they use Reflection to call theese functions by their names (string).
> 3 votes

# Answer
# Unity doesn't virtualize its methods

Firstly, I want to say that I don't think pctroll is wrong in the context of the question (overriding-wise) but if you look in the update API, then Unity would generate a code closer to what it's bellow:

```
public class AgentBehaviour : MonoBehaviour
{
    public void Awake()//note the lack of the virtual keyword
    {
        // your code here
    }

    public virtual Vector3 GetVector3 ()
    {
       return new Vector3();
   }
}

```

# How Unity "virtualize" its methods

But I still feel that the question wasn't aswered properly

> How does Unity3D implement their system where if a class is derived from MonoBehaviour and has certain methods like Awake() or Update(), they are called accordingly?

I mean, have you ever notice that MonoBehaviour is indeed calling a lot of methods, like Awake, without overriding them? This is done due to a feature of C#, the extern modifier which allows external programs to implement behaviours and somehow the DLL your game builds is passed to Unity.

## I'm Sorry But...

Ok, I know I have seen it sowewhere in Unity documentation or code but I cannot prove it. So can you do me a solid? So try to enter in Unity's metadata (the DLL, kind of accessible through F12 if you code in VS) and see how it is implemented, then print and post it here.

If no one does it before I get on a computer with Unity, I'll try to get that image as a prove of what I've just written.
> 1 votes

---
Tags: c#, unity, inheritance, callbacks
---


# Question
Title: Unity problems with OnTriggerStay and Input.GetKeyDown
**Background information**

Some weeks ago, I start by creating my own platform game. You control a character, that can collect logs and should hold all the campfires on in the game. When the user has collect more then one log, the player have to use this log to hold the fire on. So you should walk to the campfire and should press E to give the log to the fire.

**Problem**

What the problem momently is, is that when I press the `E key`, it will fired the `input` more then one time. This is because I use a `OnTriggerStay2D` function, to check every second if my Player is collide with the campfire `object`.

Do some search on the internet, results in people with the same problem. So one of the solutions was to create an `bool` and set it to true on `OnTriggerEnter2D`. But this isn't working for me. The same problem as before will occur.

Is there another solution to fix this conflict. When the user press the button, it should be fired ones. Below script is linked to the campfire object.

Also tried it with: `if(Input.GetKeyDown(KeyCode.E)) { isTrigger = true; }` and the same for `GetKeyUp`, but then `isTrigger = false;`

My current working code:

```
public Animator anim;
    public int campfireStatus;
    bool inTrigger = false;

    // Use this for initialization
    void Start () {
        anim = GetComponent<Animator>();
    }

    // Update is called once per frame
    void Update () {
        anim.SetInteger("Intensity", campfireStatus);
    }

    void OnTriggerEnter2D(Collider2D other) {
        inTrigger = true;
    }

    void OnTriggerExit2D(Collider2D other) {
        inTrigger = false;
    }

    void OnTriggerStay2D(Collider2D other) {
        // If player comes in contact with gameObject
        if (other.gameObject.tag=="Player"){
            print ("player");
            if(Input.GetKeyDown(KeyCode.E)) {
                print ("E Pressed");
                if (WoodBehaviour.count > 0) {
                    campfireStatus++;
                }
            }
        }
    }

```

So when the `Player` is collide with the campfire object AND the player pressed the E key AND you have more then one logs (this counter will be set in the `WoodBehaviour` script, that is linked to the player object ) than it should increase the `campfireStatus` with plus one. The problem is, that the if statements will fired more then one times when pressing the E key.

# Answer
Yep, a flag works just fine, when used correctly:

```
void OnTriggerEnter2D(Collider2D other) {
    if (other.gameObject.tag=="Player"){
        inTrigger = true;
    }
}

void OnTriggerExit2D(Collider2D other) {
    if (other.gameObject.tag=="Player"){
        inTrigger = false;
    }
}

void Update () {
    if(inTrigger && Input.GetKeyDown(KeyCode.E)) {
        if (WoodBehaviour.count > 0) {
            campfireStatus++;
        }
    }
}

```

No need to use `OnTriggerStay2D`, which I've found to be somewhat unreliable. Just set the flag when entering and remove it when leaving. Then, in the update method, check the flag and the key.
> 2 votes

---
Tags: unity, 2d
---


# Question
Title: How do I keep my orbiting camera upright?
I am working on code that rotates the camera around a point on the in-game map when dragging the mouse. I understand how to lock it so it stays above the map surface.

However, if I keep rotating the view up, the camera will go "up and over" and be upside-down. How can I fix the camera orientation to make sure my camera stays upright?

---

A representative bit of code:

```
x += Input.GetAxis("Mouse X") * xSpeed;
y -= Input.GetAxis("Mouse Y") * ySpeed;

// when mouse moves left and right, rotate around local y axis
transform.RotateAround(target.position,transform.up, x);

// when mouse moves up and down, rotate around the local x axis
transform.RotateAround(target.position,transform.right, y);

```

# Answer
> 1 votes
You need to clamp the vertical rotation. I don't know off the top of my head the simplest way to adjust that code, but it'll just involve changing a couple lines around the transform.RotateAround() stuff, to use Mathf.Clamp() for the angle around the x-axis.

I think you just need to put in `y = Mathf.Clamp(y, -180, 180);` right after incrementing y. This way the downward rotation will be limited to straight down and never allowed to go too far.

# Answer
> 1 votes
The key is to analyze how an actual camera would work. If you're pointing it toward, say, a wall in front of you, then you point it toward the ceiling, and then keep turning it "up" you will find that the ground will actually start to come into view from the top. It seems odd at first - but the actual camera configuration you have is already "correct" IMO.

However, I can totally see why you wouldn't want it to be possible to view the map upside down. Even if it's correct - it is quite awkward. I do have a few suggestions to fix it:

* First, easiest fix. If you keep track of the camera rotation on the X axis (assuming the camera is pointed toward the positive z axis) then you can add some code so that the user can never go past straight down or straight up - which will force them to look at anything behind them by turning the camera left or right.
* Second, slightly more awkward fix (IMO). If you keep track of the camera rotation on the X axis (assuming the camera is pointed toward the positive z axis) then you can flip the camera when they go past straight down or straight up. Just rotate the camera on it's Z axis (still assuming it's pointed toward the positive z axis) 180 degrees if it passes one of those points, and then if it passes them again, rotate it another 180 degrees on it's Z axis. This is how the C# XNA "look at" matrix works.

Hope this helps! If anything sounds confusing - just ask. :)

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


# Question
Title: Best way to constrain character to a path?
I'm in the process of developing a level-based runner for mobile phones, and I've hit a wall when deciding which method to use to get the character to move through the level.

Basically - I need my character to travel a constrained path across the level as I manipulate the character by speeding up/down and jumping to avoid obstacles. I couldn't just place a straight path and use Curved World look as I needed a realistic feel to character motion. I also have up/down slopes that have to affect the character's speed.

I'm not use whether using iTween is the best for this as it makes it difficult to manipulate character speed and especially the jumping 'arc'. I've tried using MoveTo() but problems arose when trying to change character parameters... PutOnPath() made sense in theory but I found it harder to implement.

Is there any easier way to go about this? I'm almost completely new to Unity, so an easier implementation is what I'm going for, for now.

Thanks in advance!

# Answer
> 1 votes
If you end up having to roll your own, the common solution to having objects on paths (cameras moving over time, objects moving over time, cars driving in traffic lanes) is to use curves.

Here's a gentle intro to 2d bezier curves I wrote that you can easily extend to 3d.

http://blog.demofox.org/2014/03/04/bezier-curves/

http://blog.demofox.org/2014/03/22/bezier-curves-part-2-and-bezier-surfaces/

And an interactive web demo: http://demofox.org/bezcubic.html

# Answer
> 1 votes
Depending on your implementation and needs, this may not work for you, but one method is to use Unity Navmeshes. The way Navmeshes work is that you select the portions of the level which you want your runner to be able to move in and then bake them. This will then define where your runner can move. You will need to add a NavMesh Agent to your runner. The NavMesh Agent is what tells the object to stay within the NavMesh you defined earlier. You can use `SetDestination` and the shortest path to the point (that is on the NavMesh) will be calculated. You can also have sloped NavMeshes and define in your NavMesh Agent how steep of a slope it can traverse over.

---
Tags: unity, movement, path-finding, mobile, character
---


# Question
Title: (Unity) Is there a way to automatically create a material for each texture and assign the texture to it?
I have imported hundreds of textures in my Unity project, and I'd like to create a material for each of them. This would obviously take a lot of time, so how would I go about doing this automatically?

These are just basic textures that I want to assign to albedo on the standard Unity 5 shader. No need for normal maps.

# Answer
> 3 votes
Scripts put in a folder named Editor affect Unity's editor, rather than running when you play the game. You can use this functionality to extend the capabilities of the editor, to run custom functions you create. For example, here's a script that adds a window with buttons for custom functions: http://wiki.unity3d.com/index.php?title=FindMissingScripts

You probably want a script that will loop through all selected textures or something. You can then use AssetDatabase.CreateAsset to create material assets, as explained here: http://answers.unity3d.com/questions/21457/is-it-possible-to-create-a-material-asset-from-a-s.html

# Answer
> 1 votes
If you extend AssetPostprocessor you can receive a callback(OnPostProcessTexture) when a texture import is completed.

You can use that entry point to automatically create a new material and assign the relative texture to it.

---
Tags: unity, textures, materials
---


title: OpenGL multiple mesh management

text:
# Question
Title: OpenGL multiple mesh management
I've been working on coding a new 3D engine in Java. For the moment at least I'm sticking to openGL...

Currently I'm reworking how meshes get transformed and then drawn. ATM each mesh created has its own VBO and IBO along with its own draw method so if I wanted to draw multiple meshes it would look like this:

```
mesh1 = MeshLoader.loadMesh("cube.obj");
mesh2 = MeshLoader.loadMesh("pyramid.obj");

mesh1.addToBuffers(); //adds vertex and index data to vbo and ibo
mesh2.addToBuffers();

mesh1.draw();
mesh2.draw();

```

The draw method defined in class Mesh enables vertex attribute arrays, binds the bufffers, and then draws elements based on the ibo.

Then I send my projection matrix (transformation and perspective) as a uniform to the vertex shader.

**QUESTION:**

1. Games are made of many many meshes and each has to be identified so that transformation can be applied. I want to be able to apply transformations (translate, rotate, scale) directly to a given mesh, independent of the other meshes. In other words I want to move mesh1 and only mesh1 5 units to the right (on its own axis) without it affecting mesh2.
2. How do I do all this without making a million draw calls to the gpu?

Any advice appreciated.

# Answer
> 1 votes
As I understand it, now you are making some transforms and pass the matrix as a uniform which is the *same* for all meshes.

What you should do, is send different matrices for each mesh, which could be for example members of the mesh class. Then send the uniforms before rendering each mesh. Something like this:

```
void Update(){
    mesh1.transform = rotate/translate/scale....
    mesh2.transform = rotate/translate/scale....
    .
    .
}

void Render(){
    mesh1.SetUniforms(); // send mesh1.transform to the shader as usual
    mesh1.Draw();
    mesh2.SetUniforms(); // send mesh2.transform to the shader which is different
    mesh2.Draw();
    //...same for other meshes
}

void MainLoop(){
    while(...){
        Update();
        Render();
    }
}

```

and of course they could use the same shader.

---
Tags: opengl, java, 3d-meshes
---