# Question
Title: Tile based movement with SKAction (Xcode 8, Tile Map)
I am trying to make a game where the Hero can move like in Pokemon with SKActions. But the movement looks unprofessional and have delays. How can we handle to move the Hero smoothly with SKActions from tile to tile without checking every frame if up is touched?

(the Joystick sends just a signal if a direction is pressed and released)

Edit: I am using Xcode 8 and the new Tile Map function

# Answer
I've added an example project to my Github account. You can download for reference.

With regards to the example project it's important to understand the Component pattern. SpriteKit has build-in support for this pattern through GKEntity and GKComponent. In this project the `Tiles` and `Hero` are **entities** and each **entity** has a **component** (`VisualComponent`) responsible for graphics & animation.

Additionally the project makes use of the Update Method pattern in a very limited way. Again, SpriteKit has build in support for this pattern. We make use of this pattern through the `updateWithDeltaTime` method in the `Game` class.

---

The approach used is the following …

The `Hero` entity stores the destination point in a variable called `toGridPosition`. The variable is set to `nil` when either the destination cannot be reached or the destination is reached already.

The example project uses a custom implementation for a tiled grid, but GameplayKit could be used instead (see GKGridGraph). The most important code in the `Hero` class is as follows:

```
override func updateWithDeltaTime(seconds: NSTimeInterval) {
    guard
        let vc = componentForClass(VisualComponent),
        let toGridPosition = self.toGridPosition else {
            return
    }

    let heroPos = vc.gridPosition

    // Calculcate distance between hero position and destination in world units.
    let dx = toGridPosition.x - heroPos.x
    let dy = toGridPosition.y - heroPos.y

    if dx == 0 && dy == 0 {
        // Stop movement if destination is already reached.
        stopMove()
    } else {
        // Move 1 world unit closer to destination point.
        var nextGridPosition = heroPos

        if dx > 0 {
            nextGridPosition.x += 1
        } else if dx < 0 {
            nextGridPosition.x -= 1
        } else if dy > 0 {
            nextGridPosition.y += 1
        } else if dy < 0 {
            nextGridPosition.y -= 1
        }

        if Game.sharedInstance.canMoveToGridPosition(nextGridPosition) {
            vc.moveToGridPosition(nextGridPosition)
        }
    }
}

```

The next move is automatically initiated as part of the update loop which is triggered by the `GameScene`. In the `Game` class the updateWithDeltaTime method is implemented as follows:

```
func updateWithDeltaTime(seconds: CFTimeInterval) {
    // Update game systems, state, add and remove entities, etc... here.

    hero.updateWithDeltaTime(seconds)
}

```

This method should be called around 60 times per second. So the next move will be triggered almost immediately once a move animation is finished.

In `VisualComponent` the move animation is implemented as follows:

```
func moveToGridPosition(gridPosition: int2) {
    if isMoving {
        return
    }

    isMoving = true

    let pos = Game.sharedInstance.positionForGridPosition(gridPosition)
    let move = SKAction.moveTo(pos, duration: 0.5)

    sprite.runAction(move) {
        self.isMoving = false
    }
}

```

A very important thing to remember (perhaps not relevant for you): **never** use `SKShapeNodes` when performance is important. Apple notes that `SKSpriteNode` has better performance than `SKShapeNode`, `SKShapeNode` should be used sparingly. It's easy to convert a `SKShapeNode` into a `SKTexture` however, which can be used to construct a `SKSpriteNode`:

```
extension SKShapeNode {
    var texture: SKTexture? {
        get {
            var texture: SKTexture?

            let converterView = SKView()
            if let shapeTexture = converterView.textureFromNode(self) {
                texture = shapeTexture
            }

            return texture
        }
    }
}

```

---

***One final note:** In the simulator the movement might still seem choppy (it certainly does for me on my MacBook Pro from 2015), but on devices the animation should be smooth using this approach.*
> 0 votes

---
Tags: movement, tilemap, spritekit, swift
---


title: Color Correction in DirectX

text:
# Question
Title: Color Correction in DirectX
After playing games like Star Wars Battlefront & GTA 5 I was wondering how dev's implement Color Correction in their Engines. I know that this can be done through the use of 3D LUT's but I was wondering if there are any other ways to do this. A good example of this would be in GTA 5 when a Characters special ability is triggered the colors on screen have a tint applied to them which over a period of 2 seconds the intensity of the effect gradually increases.

https://www.youtube.com/watch?v=LNGF7J3y5\_Y

If someone can explain how this is done/ implemented that would be great.

# Answer
> 4 votes
Color correction is commonly done through post processing shaders. Basically first you render the scene to a framebuffer, then draw a fullscreen quad that has a shader that takes that framebuffer and applies some effects on it. This is how color correction, bloom, dof, motionblur etc. are done these days.

Here is a simple GLSL shader performing gamma correction.

```
uniform sampler2D framebuffer;
uniform vec2 resolution;

void main()
{
    //Read the framebuffer
    vec4 inColor = texture2D(framebuffer, gl_FragCoord.xy / resolution);
    float gamma = 2.2;
    //Gamma correct
    gl_FragColor = vec4(pow(inColor.rgb, vec3(1.0/gamma)), 1);
}

```

---
Tags: directx, directx11, color
---


# Question
Title: Unity Camera - Clamping when Zoom changes?
I've got a basic camera I am working on for a 2D game that moves with the player and clamps to the area of the map. To the basics I've introduced a combination of player and eventual height-based zoom sort of Ski Safari or Lunar Lander style.

Zooming, however, changes the clamp positions and allows the land edges to be seen again. How can I fix this in the code, to prevent the edges that should be clamped from being seen when zoom is in effect?

```
using UnityEngine;

public class CameraController : MonoBehaviour
{
    public int zoomSpeed = 1;
    public int zoomMax = 25;
    public int zoomMin = 50;

    public float tarVelocity;
    public GameObject target;
    public Vector3 offset;

    private Vector3 targetPos;

    private Camera _cam;

    void Start()
    {
        _cam = GetComponent<Camera>();
        targetPos = transform.position;
    }

    void FixedUpdate()
    {
        if (target)
        {
            Vector3 targetDirection = (target.transform.position -   transform.position);
            tarVelocity = targetDirection.magnitude * 5f;
            targetPos = transform.position + (targetDirection.normalized *   tarVelocity * Time.deltaTime);
            transform.position = Vector3.Lerp(transform.position, targetPos + offset, 0.25f);
        }

    }

    void LateUpdate()
    {
        ClampCamera();
        CheckZoom();

        Vector3 posNoZ = transform.position;
        posNoZ.z = -10;

        transform.position = posNoZ;

    }

    private void ClampCamera()
    {
        Vector3 clampMovement = transform.position;

        clampMovement.x = Mathf.Clamp(clampMovement.x, 8f, 112);
        clampMovement.y = Mathf.Clamp(clampMovement.y, 6.6f, 100);

        transform.position = clampMovement;
    }

    private void CheckZoom()
    {
        if (Input.GetAxis("Mouse ScrollWheel") > 0 && Camera.main.orthographicSize > zoomMax)
            Camera.main.orthographicSize -= zoomSpeed;

        if (Input.GetAxis("Mouse ScrollWheel") < 0 && Camera.main.orthographicSize < zoomMin)
            Camera.main.orthographicSize += zoomSpeed;
    }
}

```

# Answer
> 0 votes
You should change the way you clamp the camera position. You are just limiting the position on the camera, which is the center of the camera. You should clamp the position of the camera according to the camera size.

If you want to limit what is seen in the camera in the Y coordinate, you should clamp between `LowerLimit+Camera.main.orthographicSize` and `UpperLimit - Camera.main.orthographicSize`

For the X axis is a bit trickier, as the horizontal area view depends on your aspectRatio. So you should clamp between `LeftLimit + Camera.main.orthographicSize*Camera.main.aspect` and `RigthLimit-Camera.main.orthographicSize*Camera.main.aspect`.

Your clamp function should look somethin like this:

```
private void ClampCamera()
{
    Vector3 clampMovement = transform.position;
    float CamSize = Camera.main.orthographicSize;
    float ascpet = Camera.main.aspect;

    clampMovement.x = Mathf.Clamp(clampMovement.x , 8f + CamSize*aspect, 112- CamSize*aspect);
    clampMovement.y = Mathf.Clamp(clampMovement.y, 6.6f +CamSize, 100-CamSize);

    transform.position = clampMovement;
}

```

I'd also suggest calling your `CheckZoom()` function BEFORE calling `ClampCamera()`, so clamp camera has the correct aspect ratio value when clamping.

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


# Question
Title: How do multiple shaders in a DirectX Engine work?
So as I have been learning DirectX 11, I have been looking at a few tutorials online and in the sample code provided there are more than the usual pixel and vertex shaders (along with the geometry shaders etc..). Based on my understanding there should be minimum 2 shaders (vertex & pixel) which work together.

With these additional shaders how do they work with the vertex and pixel shaders? In these additional shaders there are alse PS and VS functions so could someone explain whats going on here? So as soon as I call the return function in one shader the data is passed to the next?

# Answer
> 3 votes
Might be misunderstanding your question but from the screenshot, it looks like you have a common library of functions to use with your three different shaders: BasicEffect \[VS, PS\] Brdf \[VS, PS\] RadianceMap \[VS, PS\]

You probably already know that, for example, you can link BasicEffectPS and BasicEffectVS, then render a model with your uniform variables, to achieve a BasicEffect on the final render.

You can perform more than one effect in a number of different ways, just depends on how you want it to look.

For example, you can create a new technique that has three passes. Each pass represents each of your three shaders. If you need the output of one shader as the input into the next shader. You will have to create a texture for it as a uniform, then set that texture before moving onto the next pass.

Otherwise, if you just want to draw on the frame three times, just render the model against all three passes and stack the outputs on top of each other like layers.

So to recap, the data from one shader is not passed to the next, but there is a way to link them by passes. That's how I have done it anyway.

---
Tags: shaders, directx, directx11, hlsl
---


title: Unity 5 Syncvar not working

text:
# Question
Title: Unity 5 Syncvar not working
I have a cube in my scene. I want to change its color and I wanna server and all players to see it in this color. I have attached script on the cube:

```
using UnityEngine;
using System.Collections;
using UnityEngine.Networking;

public class Cube : NetworkBehaviour
{
    [SyncVar(hook = "OnColorChanged")]
    public Color myColor;

    void OnColorChanged(Color value)
    {
        GetComponent<Renderer>().material.color = myColor;
        Debug.Log(value + "," + myColor);
    }

    void Update()
    {
        Debug.Log(myColor);
    }
}

```

I run `GameObject.FindWithTag("cube").GetComponent<Cube>().myColor = Color.red;`this in my host script when I want to change the color of the cube, but nothing happens.

# Answer
> 1 votes
From the documentation on SyncVar:

* These variables will have their values sychronized **from the server to clients** in the game that are in the ready state.

Its possible that you are applying the change on a client.

SyncVars only sync changes from the server to the clients. If you want to update a SyncVar from a client, make the client send a `Command` from the client to the server that updates the value.

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


title: Google on different versions of games

text:
# Question
Title: Google on different versions of games
I'm focusing on a game for the Android platform, and thinking of building multiple versions with different themes. Every one of them would have a distinct name, graphics, and content, but the same game engine.

I would be maintaining the same code base for these 20 apps. If I capitalize on this format with different themes, is that forbidden in Google play?

# Answer
> 2 votes
It is not forbidden by Google play. I have published several games using the same game engine. They don't have a problem with it. In fact, the game engine is one I modified from a book and I know that many people have published games using the same engine.

Look at lgdx -- many people are publishing using basically the same underlying code.

Alternatively, look at 'Choices' -- they acknowledge the 'sameness' of the engine with different content.

---
Tags: unity, android, marketing, google-play
---


# Question
Title: Problem with setting box2dsprite dependencies error Could not find property 'gdxUtilsVersion'
Hello i am trying to use BitBucket's Box2DSprite, i am having trouble in setting dependencies i used this link for Dependency https://bitbucket.org/dermetfan/libgdx-utils/wiki/Dependency%20Instructions

i am getting error like-**Error:(91, 0) Could not find property 'gdxUtilsVersion' on org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler\_Decorated@570f3dca. Open File**

and my gradle build file is

```
   buildscript {
        repositories {
            mavenLocal()
            mavenCentral()
            maven { url "https://oss.sonatype.org/content/repositories/snapshots/" }
            jcenter()
        }
        dependencies {
            classpath 'de.richsource.gradle.plugins:gwt-gradle-plugin:0.6'
            classpath 'com.android.tools.build:gradle:1.5.0'
        }
    }

    allprojects {
        apply plugin: "eclipse"
        apply plugin: "idea"

        version = '1.0'
        ext {
            appName = "Now_create"
            gdxVersion = '1.9.3'
            roboVMVersion = '2.1.0'
            box2DLightsVersion = '1.4'
            ashleyVersion = '1.7.0'
            aiVersion = '1.8.0'
        }

        repositories {
            mavenLocal()
            mavenCentral()
            maven { url "https://oss.sonatype.org/content/repositories/snapshots/" }
            maven { url "https://oss.sonatype.org/content/repositories/releases/" }
        }
    }

    project(":desktop") {
        apply plugin: "java"

        dependencies {
            compile project(":core")
            compile "com.badlogicgames.gdx:gdx-backend-lwjgl:$gdxVersion"
            compile "com.badlogicgames.gdx:gdx-platform:$gdxVersion:natives-desktop"
            compile "com.badlogicgames.gdx:gdx-box2d-platform:$gdxVersion:natives-desktop"
            compile "com.badlogicgames.gdx:gdx-freetype-platform:$gdxVersion:natives-desktop"
            compile "com.badlogicgames.gdx:gdx-tools:$gdxVersion"

        }
    }

    project(":android") {
        apply plugin: "android"

        configurations { natives }

        dependencies {
            compile project(":core")
            compile "com.badlogicgames.gdx:gdx-backend-android:$gdxVersion"
            natives "com.badlogicgames.gdx:gdx-platform:$gdxVersion:natives-armeabi"
            natives "com.badlogicgames.gdx:gdx-platform:$gdxVersion:natives-armeabi-v7a"
            natives "com.badlogicgames.gdx:gdx-platform:$gdxVersion:natives-arm64-v8a"
            natives "com.badlogicgames.gdx:gdx-platform:$gdxVersion:natives-x86"
            natives "com.badlogicgames.gdx:gdx-platform:$gdxVersion:natives-x86_64"
            compile "com.badlogicgames.gdx:gdx-box2d:$gdxVersion"
            natives "com.badlogicgames.gdx:gdx-box2d-platform:$gdxVersion:natives-armeabi"
            natives "com.badlogicgames.gdx:gdx-box2d-platform:$gdxVersion:natives-armeabi-v7a"
            natives "com.badlogicgames.gdx:gdx-box2d-platform:$gdxVersion:natives-arm64-v8a"
            natives "com.badlogicgames.gdx:gdx-box2d-platform:$gdxVersion:natives-x86"
            natives "com.badlogicgames.gdx:gdx-box2d-platform:$gdxVersion:natives-x86_64"
            compile "com.badlogicgames.gdx:gdx-freetype:$gdxVersion"
            natives "com.badlogicgames.gdx:gdx-freetype-platform:$gdxVersion:natives-armeabi"
            natives "com.badlogicgames.gdx:gdx-freetype-platform:$gdxVersion:natives-armeabi-v7a"
            natives "com.badlogicgames.gdx:gdx-freetype-platform:$gdxVersion:natives-arm64-v8a"
            natives "com.badlogicgames.gdx:gdx-freetype-platform:$gdxVersion:natives-x86"
            natives "com.badlogicgames.gdx:gdx-freetype-platform:$gdxVersion:natives-x86_64"
        }
    }

    project(":html") {
        apply plugin: "gwt"
        apply plugin: "war"

        dependencies {
            compile project(":core")
            compile "com.badlogicgames.gdx:gdx-backend-gwt:$gdxVersion"
            compile "com.badlogicgames.gdx:gdx:$gdxVersion:sources"
            compile "com.badlogicgames.gdx:gdx-backend-gwt:$gdxVersion:sources"
            compile "com.badlogicgames.gdx:gdx-box2d:$gdxVersion:sources"
            compile "com.badlogicgames.gdx:gdx-box2d-gwt:$gdxVersion:sources"
            compile "net.dermetfan.libgdx-utils:libgdx-utils:                      $gdxUtilsVersion:sources"
            compile "net.dermetfan.libgdx-utils:libgdx-utils-box2d:              $gdxUtilsVersion:sources"
        }
    }

    project(":core") {
        apply plugin: "java"

        dependencies {
            compile "com.badlogicgames.gdx:gdx:$gdxVersion"
            compile "com.badlogicgames.gdx:gdx-box2d:$gdxVersion"
            compile "com.badlogicgames.gdx:gdx-freetype:$gdxVersion"
            compile "net.dermetfan.libgdx-utils:libgdx-utils:$gdxUtilsVersion"
            compile "net.dermetfan.libgdx-utils:libgdx-utils-box2d:$gdxUtilsVersion"

        }
    }

    tasks.eclipse.doLast {
        delete ".project"
    }

```

i can summerize the changes i have made first add these dependency to core project

```
compile "net.dermetfan.libgdx-utils:libgdx-utils:$gdxUtilsVersion"
        compile "net.dermetfan.libgdx-utils:libgdx-utils-box2d:$gdxUtilsVersion"

```

and add these to Html

```
  compile "net.dermetfan.libgdx-utils:libgdx-utils:$gdxUtilsVersion:sources"
    compile "net.dermetfan.libgdx-utils:libgdx-utils-box2d:$gdxUtilsVersion:sources"

```

# Answer
I guess you are missing something,try adding this line to ext in all project

```
ext{
    gdxUtilsVersion = '0.13.3'
}

```
> 1 votes

---
Tags: android, libgdx, sprites, box2d, gradle
---


# Question
Title: Single object decreasing frame rate from 60 to 5
I'm new to game development and I'm not sure what I've done wrong. My game runs at about 60 frames per second until I add one instance of a model I made in Blender. As soon as I add it the frame rate drops between 5-6fps and even the Unity UI seems sluggish.

I created the model using Blender v2.77a and it has 25,925 vertices, 22,919 faces and 49,224 triangles in 3 objects plus an armature, camera and hemi light source (6 objects total). Two of the objects contain very little. They were made just for me to attach a line renderer in Unity. The third object contains the entire model so there is only 1 UV map. I created about 5 materials, Baked them to an image (using the Blender Game engine), then deleted the materials and made a single material to apply the image. Then I exported an fbx file (mainly so I could adjust the axis to match unity) and imported that along with the texture image in to Unity.

For some reason two volumes in my model also render in Unity with the faces facing the camera invisible. If I move the camera those faces become visible and the others become invisible.

My PC is a few years old now so it's not the fastest. But I didn't expect it to struggle with one object. I'm running an Intel Core2 Quad Q9400 (2.67GHz), 8GB RAM and a single Radeon HD5770. The hard drive is a standard SATA 2 with 7.2k spindle and I'm using Win 10 x64.

If you need any more info, please let me know.

Edit: Here's a screenshot of the Profiler.

# Answer
I solved the problem so thought I'd post it for anyone else who may encounter it.

The problem is that I had two objects which contained vertices and edges but no faces. The purpose of these objects was for me to attach a line renderer in Unity. I noticed in warnings Unity's console for each of these objects saying "Can't calculate tangents because mesh doesn't contain normals".

The solution was to simply create a face in each of the two objects. My frame rate is now back to 60fps.

As for my other problem where faces were invisible when facing the camera, I discovered that the normals were facing the wrong direction. This was making the faces visible from inside the volume instead of outside. To fix this problem I selected all my faces and pressed CTRL + N to make them face outwards (if you're trying to render from inside a volume E.g. using the inside of a cube for a room. You can do the same thing and tick the 'Inside' option in the tools pane).
> 2 votes

---
Tags: unity, blender, blender-game-engine
---


# Question
Title: Will importing more items from unity packages increase the build size?
I'm developing a GoogleVR (formerly Google Cardboard) application and need to import the GoogleVR SDK. While I only expect to use some of the items available in the Unity package, I'd like to import them all at once and save potential headaches later when I can't find something I might need. However I'm worried that including everything in the project may affect the build size, which would be troublesome on a mobile application.

# Answer
> 3 votes
The unity build process only builds stuff in the included set of scenes that you add through the build configuration dialog ...

https://docs.unity3d.com/Manual/BuildSettings.html

... after selecting your desired set of scenes and the build platform you want to build for you can start the build by clicking the appropriate button.

So in short ...

Adding stuff in to a unity project in itself does not increase the size of a build unless those new package resources are used in your selected set of scenes.

# Answer
> -1 votes
It does increase build size. I am not 100% sure, but unless unity has "smart building" and ignore scripts and objects not used in your application, it will increase the size for sure

---
Tags: unity, google-cardboard
---


# Question
Title: Limit a scrollbar's OnValueChanged to full step intervals only
So I have done some research on the matter but I can't find anything.

I created a UI scrollbar and asigned 10 steps to it.Then I noticed that the values of the scrollbar does not change in reference of the handle's steps but in reference of the pointer's position(like a slider).That seriously slows down the performance since it has a lot more to process "onValueChanged" and it is unnecessary for what I am trying to achieve.

The values of the steps should go step 1: 0.1(1),step 2: 0.2(2) etc.I need to get these values and nothing in between or the step that the handle is currently on.

How can I do that ?

# Answer
> 2 votes
As you noticed the value, when the scrollbar is dragged, changes in accordance to pointer's position (this does not happen if you are using keys). From Unity docs:

> The Scrollbar has a single event called On Value Changed that responds as the user drags the handle.

Scrollbar `OnValueChanged` is called at most once per frame. This allows you to react to scrollbar movement in every frame.

If you need to fix your update operations to a given step you need to account for that in your code. Store the last scrollbar `Value`, and in `OnValueChanged` check if the new position corresponds to a different step than in the previous frame, otherwise return (this will have little impact on performance). Example code (incomplete):

```
public OnValueChanged(float value) {
  currentStep = Mathf.round(scrollbar.Value * 10.0f);
  if (currentStep == lastStep) return;

  // Your code here (depending on your needs you may need to iterate
  // from last to current step)...

  lastStep = currentStep;
}

```

One thing that is calling my attention is that a scrollbar will automatically set its handle `size` according to the target scroll area, thus making the `numberOfSteps` unuseful. Perhaps you shall consider using a `Slider` instead.

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


# Question
Title: Triangulation of "polygon with holes" for NavMesh
Just for fun, I am working on a little side-project: As a first step, I want to be able to build a grid-based world (think Dungeon Keeper), generate a nav-mesh for this world and then let agents wander around it. I've already done plenty of googling and ended up following the instructions given in the answer to this gamedev question: How can I generate a navigation mesh for a tile grid?

Now, I've completed step 1 in that I now have iso-lines representing the outlines of the walkable area. This could look like this:

The blue lines are the generated outlines of the walkable area. As you can see, in this case there is one walkable areas defined by two lines because the area is a circle.

This is where I'm stuck: If it were a regular polygon I'd probably be able to implement some sort of triangulation algorithm (there's plenty of examples on the net, I guess), but how do I go about this case? Do you have any pointers for me?

# Answer
If you want a generic "good for all cases" solution (and it looks that you need one, given how varied DK kind of game levels can be, unlike, say, a circle-racing game) then you should refer to the question you have linked (How can I generate a navigation mesh for a tile grid?). It deals with this problem in steps 2-7. Not simple, I agree, but universal.
> 1 votes

---
Tags: mathematics, path-finding, triangulation, navmesh
---


# Question
Title: Make UI Button Image Size Independent of Screen size Unity
I have two UI Buttons with image sprites in `Panel` (inside canvas). I have set their sizes to 40 in the inspector. If I run game in maximize mode, buttons retain constant assigned size of the inspector, instead of adjusting themselves with screen size. I have already added `Canvas Scalar` component with value `Scale with Screen Size`. Text fonts are able to adjust with screen size present in same canvas, but button with image does not.

Any guide on this? Thanks.

# Answer
> 0 votes
If I understand your question correctly, you are using the new (Unity 4.6 and up) UI system. Part of that system includes a set of triangularly shaped handles (when viewed using the rectangular toolbar...tool.

As an example, that tool is selected in the above image and the selected button has the triangular handles all set to the button's upper left corner. These are the UI object's *anchors* and are used to dictate how the UI object scales when the screen resolution changes. In the above case, the button would not scale at all and would remain anchored to the upper left corner of the canvas (as that's where the anchors are).

Alternatively, you can modify the anchor values directly in the inspector using the \>Anchors property or the Rect Transform's quick anchor align tool (in the above image it shows "top left" with a square with the top and left sides in red).

This is effectively what you want to do, although you will need to figure out what specific values your UI needs.

---
Tags: unity, image
---


# Question
Title: Controlling spawn properties and overriding NetworkManager in Unity
I'm trying to find the best approach to controlling the spawn process in a multiplayer unity game.

Having looked over the docs, I have a NetworkManager and it's easy enough to set a player prefab and some other registered prefabs.

What I need to do, it randomly pick the prefab that the player spawns as (from a predefined set).

Having looked over the docs and tutorials I have found two potential options but have not managed to implement either.

a) Override the network manager and provide an implementation of `OnServerAddPlayer` as per this page: https://docs.unity3d.com/ScriptReference/Networking.NetworkManager.OnServerAddPlayer.html

* With this approach I'm not sure how to attach my overridden network manager class to the scene. Do i add it as a component to the NetworkManager? Do I remove the network manage and use this script instead?

b) Provide a spawn manager class as per this page: http://docs.unity3d.com/Manual/UNetCustomSpawning.html

* With this approach I'm also unsure how to attach the spawn manager to the rest of the scene. I've tried adding it in the hierachy within an empty game object, but I'm unsure then how to make use of it within my NetworkManager. The docs only give examples of using it to control bullets being created programmatically.

Afraid I'm quite new to unity and just trying to get to grips with the basics. Would really appreciate some pointers on this one.

# Answer
You can follow the first approach and you can attach it in the same way as you attach the default `NetworkManager`, i.e. create a game object and attach your new script to it.
> 1 votes

---
Tags: unity, multiplayer
---


# Question
Title: How do I include the gizmo in my simulation?
My company is developing 3D simulation program using Unity 5.x and we need a gizmo in our solution. My goal is to displaying that a factory is building.

I don't know how do programmatically use Unity Engine. How do I include a gizmo like the gizmo in the scene view, or the one in the image?

# Answer
> 2 votes
The gizmo you are referring to is deliberately for display in the Unity Editor. With use of the `UnityEditor` libraries, you have some control over it; however, this does not help you in the final build. The easiest solution removes all programming requirements: **build your own!**

## Issues with using the Unity gizmo in a final build

While there is probably a way to export this gizmo to your final build, you have two issues:

1. Using this specific asset can be tricky, due to it not being provide with such intentions. It *may* involve more programming, which as you say, you are completely unfamiliar with.
2. The gizmo is not intended for final product display. There is likely a legal issue in that they are not really giving you permission to use it in your own software. If you *really* must use this variation, and solve the initial problem of retrieving the asset, you could always contact the Unity legal team and simply ask. I don't see why they would have a problem, but its best practice to make sure.

## Building your own gizmo

There is an easy solution here. Make your own gizmo! In essence, the gizmo is just a cube with some cones sticking out of it. Someone with a basic understanding of 3D modelling would be able to create their own version quite quickly, in practically any 3D modelling software. You could also create a variation using the basic geometric shapes provided in Unity, if you *really* had to.

The colour scheme follows a common standard; across many pieces of software, red is often the colour of the X-axis, green is often the colour of the Y-axis, and blue is often the colour of the Z-axis. You will probably want to stick to these colours, as the uniformity greatly facilitates user familiarity.

Apart from that, you should tailor the gizmo to your own style preference or need. All it intends to represent is the direction of the 3 axis. The fact that it does so with cones is nothing particularly important - you may find that other shapes better suit your needs. Play around, and find out what works best for you.

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


# Question
Title: Enemy shake/vibrate when following character
I am using the arongranberg A\* path finding project to create way points for **one** enemy to follow the player. However, the enemy vibrates back and forward by about 0.1 - 0.2 unit distance when moving. I have done a lot of research regarding this problem in the past few days but to no avail I could not find a solution that solves it. This is link to a gif to show what I mean.

I have tried,

changing Application.targetFrameRate = 30;

changing fixed update to update and vice versa;

using rigidbody2d and turn interpolate on plus using velocity to move;

turning iskinematic on and off;

using translate to move.

none of the above solution works. Below is the script I have for my enemy. Any advice would be appreciated.

```
    using UnityEngine;
    using System.Collections;
    //Note this line, if it is left out, the script won't know that the class 'Path' exists and it will throw compiler errors
    //This line should always be present at the top of scripts which use pathfinding
    using Pathfinding;

public class AstarAI : MonoBehaviour
{
    //The point to move to
    public Transform target;

    private Seeker seeker;

    //The calculated path
    public Path path;

    //The AI's speed per second
    public float speed = 200;

    //The max distance from the AI to a waypoint for it to continue to the next waypoint
    public float nextWaypointDistance = 0.02f;

    //The waypoint we are currently moving towards
    private int currentWaypoint = 0;

    Rigidbody2D rb;

    public void Start ()
    {
        rb = this.GetComponent<Rigidbody2D> ();
        seeker = GetComponent<Seeker>();

        //Start a new path to the targetPosition, return the result to the OnPathComplete function
        seeker.StartPath( transform.position, target.position, OnPathComplete );
    }

    public void GoToNewTarget(Transform newTarget) {
        //path = null;
        currentWaypoint = 0;
        nextWaypointDistance = 0.02f;
        target = newTarget;
        seeker = GetComponent<Seeker>();
        seeker.StartPath( transform.position, target.position, OnPathComplete );
    }

    public void OnPathComplete ( Path p )
    {
        Debug.Log( "Yay, we got a path back. Did it have an error? " + p.error );
        if (!p.error)
        {
            path = p;
            //Reset the waypoint counter
            currentWaypoint = 0;
        }
    }

    public void Update ()
    {
        if (path == null)
        {
            //We have no path to move after yet
            return;
        }

        if (currentWaypoint >= path.vectorPath.Count)
        {
            Debug.Log( "End Of Path Reached" );
            return;
        }

        //this.GetComponent<Rigidbody2D> ().MovePosition (path.vectorPath[currentWaypoint]);
        //Debug.Log (path.vectorPath[currentWaypoint]);
        //Direction to the next waypoint
        Vector3 dir = ( path.vectorPath[ currentWaypoint ] - transform.position ).normalized;
        //GetComponent<Rigidbody2D> ().velocity = new Vector2 (dir.x * 3, dir.y * 3);
        //Vector3.MoveTowards(transform.position, path.vectorPath[ currentWaypoint ], 2*Time.fixedDeltaTime);
        dir *= speed* Time.deltaTime;
        rb.velocity = dir;
        //this.gameObject.transform.Translate( dir );

        //Check if we are close enough to the next waypoint
        //If we are, proceed to follow the next waypoint
        if (Vector3.Distance (transform.position, path.vectorPath [currentWaypoint]) < nextWaypointDistance) {
            currentWaypoint++;
            return;
        }
    }
}

```

# Answer
What is most likely happening is you are calling `GoToNewTarget` before the enemy has finished the path it is currently on (which seems to be the case from the gif).

This is an issue because the path finding library takes some time to find a new path, and in that time the enemy has traveled further down the existing path. When the new path is found, it will start at a point behind the enemy's position (where the enemy was when `seeker.StartPath` was called), and so the enemy will move backwards to the start of the new path.

To fix this, you can move the next waypoint check to before the movement, and put it in a `while` loop to make sure you are up to the right waypoint whenever you go to move.
> 1 votes

# Answer
If you are using a rigid body, then freeze the rotation and position under the rigid body constraints. This worked for me.
> -1 votes

---
Tags: unity, 2d, path-finding
---


# Question
Title: How to call the logic of a class into another class?
I am new to c# game development and just start. I decided to start with the basics, **Console Applications.**

I am try trying to recreate a game created by Lincoln Li and it's called **Mr Sprinkle's Great Escape.**

There are 2 classes **Stats** (An attribute system) and **Death** where they kind of linked together. Here is the snippet of the code:

**Stats**

```
private static int thirst;

    static public void ThirstLevel()
    {
        Console.WriteLine("Your thirst level is: {0}", thirst);
    }

    static public void DecreaseThirstLevel()
    {
        thirst--;
        Console.WriteLine("Your thirst level is: {0}", thirst);
        if (thirst == 20)
        {
            Console.WriteLine("Your thirst level is 2/3 gone!");
            Console.WriteLine();
            Console.WriteLine("You're getting thirsty!");
            Console.WriteLine();
        }
        else if (thirst == 10)
        {
            Console.WriteLine("Danger! Danger! Your thirst level is 1/3 gone!");
            Console.WriteLine();
            Console.WriteLine("Better go get some water!");
            Console.WriteLine();
        }
        else if (thirst <= 0)
        {
            Console.Clear();
            Death.DeathByThirst();
        }
    }

```

Now my question, is how will I implement **Death.DeathByThirst** in the **Death** class. How will I proceed to call the logic of the Stats class to Death Class?

So far I'm stumped here :/

```
 static public void DeathByThirst()
    {
            ???
    }

```

Your help will be appreciated! :)

# Answer
> 1 votes
You will have to declare an instance of the Stats class within the Death Class to use the methods and properties of the Stats class, make sure the classes are public you are trying to access.

Declare the Stats Class in the Death Class and perform a myStatsClass\[Dot\] whatever your methods are named in the method that you want to use the Stats class IE in the Death Class Declare :

```
Stats myStatsClass;

```

In the Death Class Method :

```
public void DeathByThirst()
 {
    myStatsClass.CallStatsClassMethod();
 }

```

---
Tags: c#, console, text-based
---


# Question
Title: Performance of 8 bit / 16 bit games vs Android/iOS games!
**CONTEXT**

I have always been intrigued by video games - NES and SNES in particular. Now I am a 32 years old computer professional who has mostly done his coding in Java and C#. I recently found great inclination for Android games and posting this question to much wiser community in the field for knowledge and awareness of everyone.

**INTRO**

NES brought an invasion of 8 bit games. Very sleek, very entertaining and surprisingly very compact in size - few hundred Kb only. Games like Mario/Contra/Ninja/Zelda and countless more.

SNES followed the suite and brought an era of much graphically appealing games in 16 bit - still the size of the games were very compact and games were very powerful.

For Android, I have been doing some research for some good game engine and found that `LibGDX` is very powerful, open source and written for Java developers. A plus for any Android game developer.

**THE QUESTIONS**

1. What I am not able to understand is that how those classic game developers managed to put all those endless levels and game characters and features and goodies in just few hundred kbs! I am trying to replicate just 1 level of Mario and the size is already reaching to 300Kb, let alone adding the files code and characters sprite images!
2. Can we implement similar principles of compact and powerful coding using Android and LibGDX? If yes, how - If no, why not!
3. Is it possible to create a game in 8bit/16bit code and then migrate it to the Android/iOS platform?

# Answer
> 1 votes
I surmise the OP wants to know why games designed for classical consoles and computers are so much smaller than modern games. Hopefully some of this is useful; I have just an interest in retro systems.

If you look at two main elements that make up an image we see code and data.

For the data portion if we examine graphics, one methodology may be to have a 16 colour image where the palette is stored separately to the image itself. In order to represent 16 unique values we require 4 bits per pixel, and then a palette (depends on number of colours the VDP can display) loaded onto the display processor which declares what each of those 16 colours represent (with one being transparent).

The Mega Drive for example has 4 palettes and all the pixels on screen are taken from these palettes. If on a modern system you chose to use a 24bit bitmap for your Mario sprite each pixel will need nearly 17 million bits. By changing the palette many games would reuse the same images and simply change the colour to give the impression of new enemies and environments. Games were typically also built from tile maps (e.g. 8x8 tiles) so the same levels were created from a selection of small images; this is more space efficient than creating larger images and only using them a handful of times. Systems like the Super Nintendo had scaling, rotation; etc built into the hardware which helped reduce code size as this didn’t need to be done in software, but was more useful for computational efficiency. The same sort of argument applies for the music and sound effects in games.

Games were usually written by hand in assembly which even now amongst homebrew is popular due to the small code size/efficiency that can be achieved compared to a compiler, though modern compilers are much better than some of the older ones. Object oriented languages are often not used for embedded processors due to the small overhead involved, which is not really an issue on smartphones and modern PCs. Many games are also created using interpreted languages with huge libraries (compared to the memory size of old consoles), often including a lot of code which is never even executed. I first started programming with older versions of Game Maker and even a game with just a single empty room would be well over 1MB in size, before I added anything to the game.

Hopefully the examples I’ve shown illustrate that in order to create a game for the 8/16 bit era you would have to know a great deal about the hardware you are running on (at least at the time) whereas modern frameworks or game engines abstract the hardware detail away from the user. You don’t need to know exactly how the hardware works or concern yourself with the vast amount of hardware variations that exist in Android devices; each layer of abstraction introduces inefficiency but can potentially help developers (this is especially important for large complex projects not possible on less powerful hardware).

I’m not sure on modern devices; they may need to be rooted. If you could write your own drivers to interface directly with the hardware instead of using a high level framework which in turn talks to the OS which then controls the hardware, you may be able to natively control the device using a very small end-to-end footprint. If you are only interested in reducing the size of your games using this framework you should probably start by examining the size of your image and music files, perhaps create a barebones room and check the size of the image produced and check the size difference to the Mario level you produced to see if it’s the framework you are using or your work that is introduced the bloat.

---
Tags: android, libgdx, assembly
---


title: Opengl - Shadow mapping issue

text:
# Question
Title: Opengl - Shadow mapping issue
I am currently trying to do a shadow map.

Here is the depth map when drawn on a quad (Which looks good to me):

And here is the final result when i try to cast the shadow in my fragment shader:

As you can see, there is no shadow being cast where it should be but instead, there is a lot of weird shadow looking spots all over the ground plane.

Any idea what is causing this ?

Code that i am using:

**My shadow class**

```
#pragma region Constructor - Destructor
Shadow::Shadow() {
 glGenFramebuffers(1, &m_depthMapFBO); //Create frame buffer
 m_shadowWidth = 1024; //Set shadow map size
 m_shadowHeight = 1024;

 glGenTextures(1, &m_depthMap);
 glBindTexture(GL_TEXTURE_2D, m_depthMap);
 //Generate the texture with gl_depth_component settings
 glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, m_shadowWidth, m_shadowHeight, 0, GL_DEPTH_COMPONENT, GL_FLOAT, NULL);

 //Set texture parameters
 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);

 glBindFramebuffer(GL_FRAMEBUFFER, m_depthMapFBO);
 glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, m_depthMap, 0);
 glDrawBuffer(GL_NONE);
 glReadBuffer(GL_NONE);
 glBindFramebuffer(GL_FRAMEBUFFER, 0);
}

Shadow::Shadow(GLuint shadowWidth, GLuint shadowHeight) {
 glGenFramebuffers(1, &m_depthMapFBO); //Create frame buffer
 m_shadowWidth = shadowWidth; //Set shadow map size
 m_shadowHeight = shadowHeight;

 glGenTextures(1, &m_depthMap);
 glBindTexture(GL_TEXTURE_2D, m_depthMap);
 //Generate the texture with gl_depth_component settings
 glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, m_shadowWidth, m_shadowHeight, 0, GL_DEPTH_COMPONENT, GL_FLOAT, NULL);

 //Set texture parameters
 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);

 glBindFramebuffer(GL_FRAMEBUFFER, m_depthMapFBO);
 glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, m_depthMap, 0);
 glDrawBuffer(GL_NONE);
 glReadBuffer(GL_NONE);
 glBindFramebuffer(GL_FRAMEBUFFER, 0);
}

Shadow::~Shadow() {

}
#pragma endregion

#pragma region Get
const GLuint* Shadow::GetDepthMapFBO() const { return &m_depthMapFBO; } ;
const GLuint* Shadow::GetDepthMap() const  { return &m_depthMap; } ;
const GLuint Shadow::GetShadowWidth() const { return m_shadowWidth; };
const GLuint Shadow::GetShadowHeight() const { return m_shadowHeight; };
#pragma endregion

#pragma region Prototypes definition
void Shadow::ConfigureShaderAndMatrices() {

}

void Shadow::RenderToDepthMap() {
 glViewport(0, 0, m_shadowWidth, m_shadowHeight);
 glBindFramebuffer(GL_FRAMEBUFFER, m_depthMapFBO);
 glClear(GL_DEPTH_BUFFER_BIT);
}

void Shadow::Unbind() {
 glBindFramebuffer(GL_FRAMEBUFFER, 0);
}

#pragma endregion
```

My render function :

```
void Render() {

 //--------------- SHADOW ------------------

 m_shadow->RenderToDepthMap(); //Set the scene for rendering from light position

 GLfloat near_plane = 1.0f, far_plane = 7.5f;
 glm::mat4 lightProjection = glm::ortho(-10.0f, 10.0f, -10.0f, 10.0f, near_plane, far_plane);
 glm::vec3 lightPos = glm::vec3(m_lights[0]->GetPosition().x, m_lights[0]->GetPosition().y, m_lights[0]->GetPosition().z);
 //lightPos *= 2.5f;
 glm::mat4 lightView = glm::lookAt(lightPos, glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(0.0f, 1.0f, 0.0f));
 glm::mat4 lightSpaceMatrix = lightProjection * lightView;

 if (m_objectPool.size() > 0) {
  for (Model* m : m_objectPool) {
   m->RenderForShadow(m_Shaders[e_normal]->GetProgram(), &lightSpaceMatrix);
  }
 }

 m_shadow->Unbind(); //Unbind the frame buffer

 //--------------- Normal rendering with shadow  ------------------

 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); //Set black as clear color - Set him the depth
 glViewport(0, 0, glutGet(GLUT_SCREEN_WIDTH), glutGet(GLUT_SCREEN_HEIGHT));

 //Update the lights for the texture shader
 m_Shaders[e_texture]->Bind();
 m_Shaders[e_texture]->SetUniform("numLights", (int)m_lights.size()); //Set the ammount of lights
 //Set value for each light
 for (int i = 0; i < m_lights.size(); i++) {
  m_Shaders[e_texture]->SetUniform("lights[" + std::to_string(i) + "].position", m_lights[i]->GetPosition());
  m_Shaders[e_texture]->SetUniform("lights[" + std::to_string(i) + "].intensities", m_lights[i]->GetIntensities());
  m_Shaders[e_texture]->SetUniform("lights[" + std::to_string(i) + "].ambientCoefficient", m_lights[i]->GetAmbientCoefficient());
  m_Shaders[e_texture]->SetUniform("lights[" + std::to_string(i) + "].attenuation", m_lights[i]->GetAttenuation());
  m_Shaders[e_texture]->SetUniform("lights[" + std::to_string(i) + "].coneAngle", m_lights[i]->GetConeAngle());
  m_Shaders[e_texture]->SetUniform("lights[" + std::to_string(i) + "].coneDirection", m_lights[i]->GetConeDirection());
 }

 m_Shaders[e_texture]->SetUniform("cameraPosition", m_camera->position());

 //Render tools
 /*if (m_grid)
  m_grid->Render();
 if (m_axis)
  m_axis->Render();
 if (m_skybox)
  m_skybox->Render();*/

 //Add the shadow map to the shader and the light matrix
 glActiveTexture(GL_TEXTURE5);
 glBindTexture(GL_TEXTURE_2D, *m_shadow->GetDepthMap());

 GLuint lightMatrixLocation = glGetUniformLocation(*m_Shaders[e_texture]->GetProgram(), "lightSpaceMatrix");
 //Give the info to the shader
 glUniformMatrix4fv(lightMatrixLocation, 1, GL_FALSE, glm::value_ptr(lightSpaceMatrix));

 if (m_objectPool.size() > 0) {
  for (Model* m : m_objectPool) {
   m->Render();
  }
 }
 /*
 m_Shaders[e_quad]->Bind();
 glActiveTexture(GL_TEXTURE0);
 glBindTexture(GL_TEXTURE_2D, *m_shadow->GetDepthMap());

 RenderQuad();*/

 //m_terrain->Render(); //Render the terrain

 glFlush();
}
```

**My vertex shader**

```
#version 430
in vec4 position;
in vec2 texture;
in vec3 normal;
in vec3 tangent;

out vec2 fragTexcord;
out vec3 fragNormal;
out vec3 fragVert;
out mat4 f_modelView;
out vec4 FragPosLightSpace;

uniform mat4 model;
uniform mat4 view;
uniform mat4 projection;
uniform mat4 modelView;
uniform mat4 lightSpaceMatrix;

void main(){
 fragVert = vec3(position);
 gl_Position = projection * view * model * position;
 fragTexcord = texture;
 fragNormal = normal;
 f_modelView = modelView;

 vec4 pos = model * position;
 FragPosLightSpace = lightSpaceMatrix * pos;
}
```

**My fragment shader**

```
#version 430
#define MAX_LIGHTS 15
uniform int numLights;

uniform struct Light{
 vec4 position;
 vec3 intensities;
 float ambientCoefficient;
 float attenuation;
 float coneAngle;
 vec3 coneDirection;
} lights[MAX_LIGHTS];

uniform float materialShininess;
uniform vec3 materialSpecularColor;

uniform vec3 cameraPosition;
uniform mat4 model;

uniform bool specularMapping;
uniform bool normalMapping;
uniform bool glossMapping;
uniform bool ambientOcclusionMapping;

uniform sampler2D diffuseTexture;
uniform sampler2D specularTexture;
uniform sampler2D normalTexture;
uniform sampler2D glossTexture;
uniform sampler2D aoTexture;
uniform sampler2D shadowMap;

in mat4 f_modelView;
in vec2 fragTexcord;
in vec3 fragNormal;
in vec3 fragVert;
in vec4 FragPosLightSpace;

out vec4 color;

float ShadowCalculation(vec4 fragPosLightSpace)
{
    // perform perspective divide
    vec3 projCoords = fragPosLightSpace.xyz / fragPosLightSpace.w;
    // Transform to [0,1] range
    projCoords = projCoords * 0.5 + 0.5;
    // Get closest depth value from light's perspective (using [0,1] range fragPosLight as coords)
    float closestDepth = texture(shadowMap, projCoords.xy).r;
    // Get depth of current fragment from light's perspective
    float currentDepth = projCoords.z;
    // Check whether current frag pos is in shadow
    float shadow = currentDepth > closestDepth  ? 1.0 : 0.0;

    return shadow;
}

vec3 ApplyLight(Light light, vec3 diffuseColor, vec3 normal, vec3 fragPosition, vec3 surfaceToCamera, vec4 specularColor, float shininess){
    vec3 surfaceToLight;

    float attenuation = 1.0;
 float pointAttenuation = 1.0f;

    if(light.position.w == 0.0) {
        //directional light
  surfaceToLight = normalize(light.position.xyz);
        attenuation = 1.0; //no attenuation for directional lights
    } else {
        //point light
        surfaceToLight = normalize((light.position.xyz - fragPosition));
        float distanceToLight = length(light.position.xyz - fragPosition);
        attenuation = 1.0 / (1.0 + light.attenuation * pow(distanceToLight, 2));

        //cone restrictions (affects attenuation)
        float lightToSurfaceAngle = degrees(acos(dot(-surfaceToLight, normalize(light.coneDirection))));
        if(lightToSurfaceAngle > light.coneAngle){
   if(lightToSurfaceAngle - light.coneAngle < 2.5f){ //Smooth around the spotlight by 2.5 degree
    pointAttenuation = 1 / lightToSurfaceAngle;
    pointAttenuation = clamp(pointAttenuation, 0, 1);
   }else{
       attenuation = 0.0;
   }
        }else{
   pointAttenuation = (1 + 15) / lightToSurfaceAngle; //Smooth color from center
   pointAttenuation = clamp(pointAttenuation, 0, 1);
  }
    }

 //Ambient
 vec3 ambient = diffuseColor.rgb * light.ambientCoefficient * light.intensities * pointAttenuation;

 //Diffuse
 float brightness = max(0,dot(normal, surfaceToLight));

 vec3 diffuse = brightness * light.intensities * diffuseColor.rgb;

 //specular
 float specularCoefficient = 0.0f;
 float cosAngle;

 cosAngle = dot(surfaceToCamera, reflect(-surfaceToLight, normal));

 if(shininess < 255){
  if(brightness > 0.0){
   cosAngle = clamp(cosAngle, 0,1);
   specularCoefficient = pow(cosAngle, shininess);
  }
 }

 vec3 specular = specularCoefficient * materialSpecularColor * light.intensities * specularColor.rgb;

 //Attenuation relative to distance
 float distanceToLight = length(vec3(light.position.xyz) - fragPosition);

 float shadow = ShadowCalculation(FragPosLightSpace);

 return ambient + ((1.0 - shadow) * (diffuse + specular));
 //return ambient + attenuation * (diffuse + specular);
}

void main(){
 float shininess = materialShininess;

 vec4 diffuseColor = vec4(1);
 vec4 specularColor = vec4(1);
 vec4 normalColor = vec4(1);

 diffuseColor = texture(diffuseTexture,fragTexcord); //Color on the diffuse texture

 if(ambientOcclusionMapping)
  diffuseColor *= texture(aoTexture, fragTexcord) * 1.2;

 if(specularMapping)
  specularColor = texture(specularTexture,fragTexcord); //Color on the specular texture

 if(glossMapping)
  shininess =  texture(glossTexture, fragTexcord).r;

 vec3 fragPosition = vec3((model * vec4(fragVert,1)).xyz);

 mat3 normalMatrix = transpose(inverse(mat3(model)));
 vec3 normal = normalize(normalMatrix * fragNormal);
 vec3 surfaceToCamera = normalize(cameraPosition - fragPosition);

 if(normalMapping){
  normal = normalize(normalMatrix * fragNormal);
 }

 //Calculate all the lights
 vec3 finalColor = vec3(0);

 for(int i = 0; i < numLights; i++){
  finalColor += ApplyLight(lights[i], diffuseColor.rgb, normal, fragPosition, surfaceToCamera,specularColor,shininess);
 }

 //HDR (high dynamic range)
 finalColor = vec3(1.0) - exp(-finalColor * 0.8);

 //Gamma correction
 vec3 gamma = vec3(1.0/2.2);

 //Final color calculation

 //Gamma calculation : color = vec4(pow(linearColor,gamma),diffuseColor.a);

 color = vec4(finalColor,diffuseColor.a);

 float shadow = ShadowCalculation(FragPosLightSpace);

 //color = diffuseColor *  (1 - shadow);

}
```

# Answer
> 0 votes
I had the exact same problem with the exact same fractal-like black spots all over my scene. I figured it out though!

I also used a box with a crate-like texture in my scene and it turned out that my fragment shader did NOT use my shadow map to do the shadow calculations, but the diffuse texture of my box.

What you see is probably the diffuse texture of your box being projected into the scene as shadow. I figured this out when I somehow managed to tile that texture and voilà, I looked at 4 black- and nothing versions of the side texture of my box. You could test this by assigning for example some plain text to your boxe's texture.

I solved this by assigning every sampler manually to the corresponding slot for each render iteration. In my shader, I assigned a uniform location for each texture, e.g. the diffuse texture:

```
private static int location_diffuseTextureSampler;
location_diffuseTextureState = super.getUniformLocation("material.hasDiffuseTexture");

```

For each entity that I render, I load its textures by calling:

```
textureLightShader.loadMaterial(entity.getModel().getMaterial());

```

...doing this:

```
 loadDiffuseTexture(0);
 loadSpecularTexture(1);
 loadEmissiveTexture(2);
 loadBumpTexture(3);
 loadNormalTexture(4);

```

Those in turn do this:

```
public void loadDiffuseTexture(int slot){
    super.loadInteger(location_diffuseTextureSampler, slot);
}

```

I basically now do the same thing for my shadow map texture! From my shader:

```
private static int location_shadowMapSampler;
location_shadowMapSampler = super.getUniformLocation("shadowMap");

```

From my render function:

```
textureLightShader.loadShadowMap(5);

```

From my fragment shader:

```
uniform sampler2D shadowMap;

```

That way, my fragment shader actually used the shadow map instead of my box texture.

Still I do not have shadow maps working correctly. So if you have further issues getting it to work I would like to ask you to contact me. Maybe I have the same problems, maybe I have solutions and maybe you have solutions for me :)

---
Tags: opengl, glsl, shadow-mapping
---


# Question
Title: Is a mesh OK to use for grass if there will be 1000's of them across the terrain?
Am creating a low poly game in Unity 3D for PC. The terrain is made in Blender, so it's a fixed size, but quite large for the player to explore. I want to add things such as grass and flowers, but am not sure the best practices are for creating those types of assets.

Is using a mesh for small clumps of grass the wrong way to do this if there will be 1000's of them?

I will likely be using the occlusion culling system Unity provides, but I'm not sure if I still need to look at doing things such as grass in a different way for performance sake.

# Answer
Don't create the terrain in Blender. Use the Unity Terrain engine instead.

It has a lot of advantages over using an imported 3d model:

* Collision handling is far faster. A 3d model will force you to use a very complex mesh collider. But the terrain system can use some optimizations which speed up collision handling a lot.
* Unity can not render a different LOD (level of detail) for different parts of the same model. That means every single vertex of your whole Blender terrain mesh will always be rendered, even when it is so far away that it's not even a pixel in size. But Unity's terrain system has automatic LOD. Those regions which are further away will automatically be rendered in lower detail. That drastically improves render performance with larger terrains.
* When you try to add your own grass, then each patch of grass would have to be an own GameObject. You might have millions of grass patches around your terrain which results in millions of GameObjects to manage. That will be too much to handle for even the strongest computer. But Unity's terrain editor also allows you to easily place grass and trees. These have automatic LOD, So only the grass near the player will be rendered. The Unity grass patches aren't individual game objects, so it has virtually no overhead.
> 1 votes

# Answer
If you're making a large enviroment, you're probably going to need LOD along with max viewdistance. I would also recommend making use of planes, but from the comments I see you've already begun.
> 0 votes

---
Tags: unity
---


# Question
Title: Sprite animation cannot be play when player retry Unity
In my unity2d game I've create a sprite animation, like a mushsroom bounce.

When I start the game for the first time the animation plays properly, but when the player dies, and retries, the animation won't play. I cannot reload the scene, I have to reset the player's transform.position.

How can I solve this problem?

```
if (target.tag == "Masroom") {
        target.gameObject.GetComponent<Animator> ().enabled = true;
        playerRigidBody.velocity = new Vector2(0,8);
    }

```

# Answer
> 2 votes
You need to do this :

```
 if (target.tag == "Masroom") {
        target.gameObject.GetComponent<Animator>().Play("MasroomBounce");
        playerRigidBody.velocity = new Vector2(0,8);
    }

```

What you are doing now is enabling the whole Animator component and that will play only once unless the whole scene is reloaded.

Edit: You have to create a empty state with a transition to your state like this and then the code repeats the animation

---
Tags: unity, animation
---


title: What exactly is a physics engine?

text:
# Question
Title: What exactly is a physics engine?
A program should take input, process it and give output. So what exactly does a physics engine take as input and provide as output?

# Answer
> 58 votes
A physics engine is responsible for simulating the motions and reaction of objects as if they were under the constraints of real-world (or similar to real-world) physics. It is, I should note, not usually a standalone program but rather a component of a larger, more interesting program (such as a game).

The input to a physics simulation is generally a collection of objects ("bodies") with properties (such as whether they are rigid or soft, their masses, shapes, and so on) as well as the collection of forces acting on those bodies.

Based on that input, the engine simulates updated positions and orientations of the bodies and applies ("outputs") them. Generally, when objects collide or overlap, that is included in the output of a simulation step in the form of a callback that client code can hook into to handle the specific gameplay logic relevant to the collision.

# Answer
> 6 votes
The input it speed, mass, and time, the output is new speeds. Sometimes rotation/angular momentum is an input and output too.

Essentially Physics engines try to simulate the effects of both gravity and collisions. For better physics engines that means they include both permanent and temporary deformation of objects, including splitting objects into multiple objects, and angular momentum of objects. Ideally they'd also simulate stress, e.g. how many trucks can cross that bridge until it collapses, but that's quite rare. Further simulation variables like air resistance would also count as physics engine, but as far as I know these haven't made it into any game yet.

Most physics engines are specialized to some degree and will simulate physics to a point that's necessary for the game. Physics engines for car games are often quite different from physics engines for 3D shooters. And the physics engine of a golf game might have excessive calculations of the interactions of the golf ball and the individual grass leaves, while completely missing the handling of high speed collisions and deformation of a car (in case it get's hit by a golf ball).

# Answer
> 4 votes
Typically a physics engine is used to make object in a game behave in a realistic manner relative to their environment without having to design specific animations for every possible scenario.

Specifically a physics engine will take a model with a set of properties (mass, joints etc) and render it in-game according to a set of parameters.

An early example of this were raggdoll engines (eg in Unreal) which modelled the way that limp bodies would fall down steps etc.

In current technology physics engines will often be closely integrated in an overall game deign package along with AI, in-game UI, cutscene generation etc.

You could certainly argue that physics engines go back to the dawn of games design eg pong could be considered a crude physics engine. However the main point is that a physics engine is capable of generating animation points on the fly based on a set of parameters rather than just using predetermined animation sequences from motion capture or manual animation.

As mentioned in other answers, in some classes or game like driving or flight simulation the physics engine may be fundamental to the game play and as such will be the main input driving the on-screen animation. Although typically the term is used for a general purpose tool which can be applied to a variety of situations without requiring very specific knowledge of or analysis of the context in question on the part of the developer, rather than a very specific simulator built from the ground up for a specific application.

# Answer
> 4 votes
**A physics engine is responsible for simulating the motion of objects in "the world"** (whatever that means in the context of the engine). Most physics engines nowadays use Newtonian mechanics to do this, as they are relatively simple to simulate and "accurate enough" for most purposes unless you're doing a space sim.

**In theory, a "pure" physics engine would take three inputs:**

* The state of the world (the objects, their positions, and their velocities) as of the last "tick" (the last instant in time that the engine had to model)
* How much time has passed since the last tick happened
* A list of the forces that have been acting on various objects in the world since the last tick

Taking inertia and the forces into account, the engine moves the objects around. **The output of the physics engine is simply the new state of "the world"**, which the game can then read out and modify as necessary.

**In practice, physics engines are not necessarily so "pure"**. Objects need to be created and destroyed, and sometimes they need to be moved around in ways that the physics engine's laws would not allow. This can sometimes be done outside of the engine, but sometimes it's done inside, and to do that, the engine needs more inputs. But the three inputs stated above cover the basics.

For example, let's say that you needed to move a character in a game using a joystick. If you aren't using a physics engine, this is pretty straightforward: when you see that the user is moving the joystick, you move the object accordingly. **With a physics engine, you don't move the object directly: you apply a force to it, corresponding to the direction you want the object to go, and let the engine handle actually moving it**.

What's the difference? Even if there is nothing else in the world, the object is unlikely to move in quite the same way, because the physics engine will handle things like realistic acceleration. But it is also possible that **other forces might be acting on the object at the same time, as might inertia, and the engine will take all of them into account**. For example, if you apply a northward force on the object, but something else is applying a westward force (or the object was already moving westward and nothing is slowing that down), then the engine will move the object northwest.

That's what a physics engine gets you: It keeps track of objects, their positions and velocities, and the forces acting on them. Thanks to the laws of mechanics, it can even create some forces on its own, to automatically handle things like collisions, friction, and gravity, all without you, the game developer, having to do anything extra.

# Answer
> 1 votes
A Physics Engine is basically a simulator of physics bodies.

## Input

It allows you do create a body (or multiple ones) specifying its physics properties like mass, size, density, etc...

It also allow you to define the properties of the physics world where the simulation occurs (e.g. gravity).

Finally it allows you to apply forces or create joints among bodies.

## Output

Once you defined all these things you can start the simulation and the Physics Engine will tell you where every body will be placed on the next **timestep** (which usually correspond to the next frame in your game). And the next one, and so on...

You see the Sprites moving on the screen because every frame the Game Engine ask the Physics Engine

> Where is this body now?

and the Game Engine updates the graphics representation accordingly.

## Considerations

I usually like to see the Physics Engine like a tool to apply the physics laws in a **declarative** way.

Infact instead of writing code to describe which computations should be performed to determine where a body will be on the next timestep I simply describe the physics world setting the attributes of the bodies (and of the physics world itself) and I let the physics engine answer that question for me.

---
Tags: physics-engine, terminology
---


# Question
Title: Input.GetAxis("Horizontal") not updating
I'm having trouble with Unity's basic character controlling. After i implemented the crouching in the code below the Input.GetAxis("Horizontal") does not update (while the left control is pressed (crouching), Input.GetAxis("Horizontal") is always set to zero even if left or right arrows are pressed.

The reason why this happens is not because of keyboard buffer etc. because horizontal input is working while jumping, which is implemented pretty much the same way the crouching is implemented in the code below. Btw. no root motion is used. Here's the code:

```
void HandleInput()
{
    currentBaseState = animator.GetCurrentAnimatorStateInfo(0);

    var deadZone = 0.1f;

    verticalVelocity = moveVector.y;
    moveVector = Vector3.zero;

    // print for testing
    print(Input.GetAxis("Horizontal"));

    if (Input.GetAxis("Horizontal") > deadZone || Input.GetAxis("Horizontal") < -deadZone)
    {
        yRotation += Input.GetAxis("Horizontal");
        animator.SetFloat("Direction", Input.GetAxis("Horizontal"));
    }

    if (Input.GetAxis ("Vertical") > deadZone)
    {
        speed += 0.1f;
        moveVector += new Vector3 (0, 0, Input.GetAxis ("Vertical") + speed);
    }
    else if(Input.GetAxis ("Vertical") < -deadZone)
    {
        if(speed >= 0)
            speed -= 0.1f;
        else
            speed += 0.1f;
        moveVector += new Vector3 (0, 0, Input.GetAxis ("Vertical") + speed);
    }
    else
    {
        moveVector += new Vector3(0, 0, Input.GetAxis ("Vertical") + previousSpeed);
        if(speed > 0)
            speed -= 0.1f;
    }

    animator.SetFloat ("Speed", Input.GetAxis ("Vertical"));

    totalRotation = yRotation * rotationMultiplier;

    transform.eulerAngles = new Vector3(0, totalRotation, 0);

    moveVector = transform.TransformDirection(moveVector);

    if (moveVector.magnitude > 1)
        moveVector = Vector3.Normalize(moveVector);

    Physics.Raycast (gameObject.transform.position, Vector3.down, out hitInfo, 0.5f);
    if(hitInfo.distance < 0.5f)
    {
        if (enableJump)
        {
            if (Input.GetButtonDown("Jump"))
            {
                animator.SetBool("Jump", true);
                verticalVelocity = jumpSpeed;
                skillSlider.value -= 1f;
                if(skillSlider.value == 0f){
                    enableJump = false;
                    bunnyImage.gameObject.SetActive(false);
                    skillSlider.gameObject.SetActive(false);
                }
            }
        }
    }

    if (Input.GetButtonDown ("Crouch")) {
        animator.SetBool ("Crouch", true);
        crouching = true;
    }

    if (Input.GetButtonUp("Crouch")) {
        crouching = false;
    }

    if (currentBaseState.fullPathHash == crouchState) {
        if(!animator.IsInTransition(0)){
            if(!crouching)
                animator.SetBool("Crouch", false);
        }
    }

    if (currentBaseState.fullPathHash == jumpState) {
        if (!animator.IsInTransition(0)) {
            animator.SetBool("Jump", false);
        }
    }

    previousSpeed = speed;

    moveVector = new Vector3(moveVector.x, verticalVelocity, moveVector.z);

    if (moveVector.y > -terminalVelocity)
        moveVector = new Vector3(moveVector.x, moveVector.y - gravity * Time.deltaTime, moveVector.z);

    if (characterController.isGrounded && moveVector.y < -1)
        moveVector = new Vector3(moveVector.x, -1, moveVector.z);

    characterController.Move(moveVector * Time.deltaTime);

}

```

# Answer
> -1 votes
The problem you are facing is called Keyboard Ghosting. Hardware limitations of each keyboard can lead to keys not registering the pulse when several keys are pressed. Laptops usually suffer from this problem more often.

Usually, keyboards tend to make the most typical keys to be pressable at the same time (for example WASD keys, to make sure FPS games work properly). This is a problem you will have to take into account when deciding the controls for your game, and unfortunatelly, there is no way to avoid this problem through software, its purelly on the hardware side.

There is an articles, with a visual explanation, here.

---
Tags: input, unity
---


# Question
Title: How to keep a rigidbody on the ground going up/down a slope? (Unity 2D)
I'm not sure if this is possible, but Im working a 2D project to has randomly generated loops (imagine a sin or cos graph). I have a 2D character (a quad for now). I want my character want to ski a long the slopes. The bottom surface always needs to be in contact with the terrain, unless it's a sudden slope change. Im trying to use to rigidbody for this, but when going down slopes the character just bounces and rolls down the hill. What can I fix this?

# Answer
> 1 votes
I'm not sure if I understood the problem right but maybe you can limit the Z rotation of the character to a certain angle so it can't tumble when you are going downhill. But if you also want your character to be able to flip in the air at certain heights for extra points or whatever your score system is, you can set the rotation limit only if the player is closer to the ground for a certain distance.

# Answer
> 1 votes
Changing the gravity scale of the game (under physics2d settings inspector) could be a solution, but I still won't suggest it, since the jumps based on physics will get affected by it. You could always increase the force applied when jumping, though.

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


# Question
Title: (Unity 5) Force child object to be perpendicular to the ground?
As i mentioned in the header, i want my MainCamera child object to stay perpendicular to the ground, any ideas?)

# Answer
> 1 votes
`transform.eulerAngles` is in global rotation space. You attach a script to the child object that does this every update:

```
transform.eulerAngles = new Vector3(0,transform.eulerAngles.y,0);

```

---
Tags: unity, rotation
---


# Question
Title: How to make an object move outside the map and appear on the other side with a tilemap?
I have a tilemap where a character moves from tile to tile. I'm trying to make it possible for the character to move outside the screen and reappear on the other side, just like the tunnel in Pacman.

The movement works like following:

1. Look for which arrow key is being pressed.
2. Check if the tile where the user wants to go to is walkable. If not, go back to 1.
3. If walkable, set it as target and start moving towards the tile.
4. When arrived to the target, go back to 1.

The problem I have is that there're no tiles outside the screen. I've tried to set the target to the tile on the other side of the map if the target doesn't exist, but then the character would move across the whole screen.

I've tried a couple other solutions that either don't work or require lots of additional code in many different files.

Does anyone know a good solution or recommend another approach?

I'm programming in Python with Pygame but know other languages in general. Here's MVCE code for my class:

```
import pygame
import math

TILE_SIZE = (16, 16)

class Player(pygame.sprite.Sprite):

    def __init__(self, pos, size):
        super().__init__()
        self.rect = pygame.Rect(pos, size)  # Rectangle representing the character's pos.
        self.image = pygame.Surface(size)
        self.position = pos  # In order to have the position in float precision, (x, y).
        self.speed = 80  # Pixels per second
        self.tile_index = (pos[1] // TILE_SIZE[1], pos[0] // TILE_SIZE[0])  # (Row, column).
        self.moving = False
        self.target = self.rect

    def handle_events(self, level):
        key = pygame.key.get_pressed()
        if key[pygame.K_w] or key[pygame.K_UP]:
            self.set_target(level, y_offset=-1)
        elif key[pygame.K_s] or key[pygame.K_DOWN]:
            self.set_target(level, y_offset=1)
        elif key[pygame.K_a] or key[pygame.K_LEFT]:
            self.set_target(level, x_offset=-1)
        elif key[pygame.K_d] or key[pygame.K_RIGHT]:
            self.set_target(level, x_offset=1)

    def set_target(self, level, x_offset=0, y_offset=0):
        tile = level.get_tile(self.tile_index, x_offset, y_offset)
        if tile.is_walkable:
            self.target = tile.rect
            self.moving = True

    def move(self, dt):
        distance_x = self.target.x - self.rect.x
        distance_y = self.target.y - self.rect.y
        # Make sure the player move at 'speed * dt' or distance, depending on the smallest.
        x = math.copysign(min(abs(distance_x), self.speed * dt), distance_x)
        y = math.copysign(min(abs(distance_y), self.speed * dt), distance_y)
        self.position = (self.position[0] + x, self.position[1] + y)
        self.rect.topleft = self.position

    def stop_if_arrived(self):
        if self.rect.contains(self.target):
            self.moving = False
            self.tile_index = self.target.y // TILE_SIZE[1], self.target.x // TILE_SIZE[0]

    def update(self, level, dt, *ignore):
        if not self.moving:
            self.handle_events(level)
        else:
            self.move(dt)
            self.stop_if_arrived()

```

# Answer
This is very simple. Just add another row of tiles "off screen" for the player to walk into and have that trigger the teleport. Or limit the visible tiles to one less row than you are now using.
> 1 votes

# Answer
Your set\_target() method currently chooses the next tile to move your player. You will need to know the bounds of your tilemap to move the player to the other side when reaching a wall. A simple way to do this teleportation is to check if the current x or y value is the size of your map and if the next move will make the value less than or greater than it, change the value to the opposing bounds.

For example: You have a 50x50 tilemap (origin is (0, 0) and in top left) and your player is at position (10, 49). The player moves down, causing the next move to be (10, 50) which is out of bounds. Instead, change the y-coordinate to be 0, teleporting the player to the opposite side.
> 3 votes

---
Tags: movement, tilemap, pygame
---


# Question
Title: Different executions with different results using the same Random seed in LIBGDX
In my Libgdx project (for PC) I am using a Java Random object initialized with a constant seed. I use the Random object to generate a lot of different pseudorandom integers. I am not using multithreading, but the integers are a bit different each time I execute the application.

How can this be possible?

EDIT: What is really strange is that the Random object is called a few times more in some executions and I don't know why, causing the random numbers to be a bit different for each execution.

# Answer
> 1 votes
If the number of RNG (Random Number Generator) calls changes depending on frame rate such as using the delta-time (animations, etc) to decide when to pull numbers out of the RNG you will get different results as the frame rate is unlikely to ever be the same between two runs.

# Answer
> 0 votes
As per the documentation for Random,

> If two instances of `Random` are created with the same seed, and the same sequence of method calls is made for each, they will generate and return identical sequences of numbers.

This holds true if the instances are made via subsequent executions of the code. If your output is diverging, them somehow you are making more or less calls on different runs - the sequence of numbers generated is still the same, but your effectively sampling differently from the sequence each time. For example, imaging thumbing through a book front to back & looking at the first word on the left page - the order of words is fixed, but if you're skipping pages differently each time, the output you observe will diverge between runs.

@StephaneHockenhull gave a likely source as to why this might be. If some casual inspection into that doesn't pin it down for you then I recommend building a wrapper class around Random that increments a counter each time you make a call to get a random number. Dumping the number of calls made at intermediate points of execution will let you zero in on where your runs are diverging. Also, I find it's much easier to add breakpoints to wrapper classes; they can feel like a bit of a hassle, but they rarely take longer to code up than the amount of time wasted by blind trial & error debugging.

---
Tags: java, libgdx, random
---


# Question
Title: How do .HLSL files work together compared to .FX?
So I have been slowly reading and working through Frank Luna's D3D11 book which uses the .FX file format which uses effects, techniques and passes which I understand now. However I have read online that the FX framework is no longer supported so I shouldn't use it. How do .HLSL files work? Do techniques, passes and effects still work the same way? Can I still use functions like:

```
CreateEffectFromMemory();

```

# Answer
> 1 votes
You can use the Effects for Direct3D 11 library (aka FX11), but should keep in mind that the HLSL compiler support for is deprecated, support for it exists "as is" (i.e. there are some known bugs in the `fx_5_0` profile that will not get fixed), and may be removed in a future update. You should use the GitHub version of the runtime library as it has a number of fixes that are not present in the legacy DirectX SDK version.

As to your original question, here's some info from the soon to be defunct CodePlex: What's the difference between an .fx and .hlsl file anyhow?

> Historically the extension '.fx' refers to a HLSL shader intended to be built using the legacy effects fx\_4\_0, fx\_5\_0, etc. profiles; while '.hlsl' refers to individual HLSL shaders. The reality is that there's no consistency here. You will see lots of '.fx' files without any technique/pass statements.
>
> Unlike C/C++ source files, HLSL files can contain a lot of stuff that gets ignored in a given invocation of the compiler. If you have a big .fx file with a dozen shaders in it and a bunch of technique/passes, you can compile the same file many times with different entry-points and profiles to generate lots of shaders.
>
> It's really all a matter of how you want to build your shader content. For example, DirectX Tool Kit uses a command-line script to build all the possible combinations of shaders: currrently it builds 86 shader blobs from 7 .fx files (and actually it can build them twice: once with the Windows compiler and once with the Xbox One XDK compiler, but only one set of these shader blobs is included in a given build of the DirectXTK.lib anyhow).
>
> If you use the Visual Studio 2012/2013 content pipeline to build your shaders, you do have to deal with a limitation of MSBuild which assumes each source file is built once for each result. So in that case, you'd want an individual '.hlsl' file for each shader combination (which for the DirectX Tool Kit example would mean 86 '.hlsl' files). One way to handle this would be to keep the shader source itself in a single file, and then have a bunch of .hlsl files that #include the 'source' file. Something like:
>
> BasicEffectVSBasicVertexLighting.hlsl
> #include "BasicEffect.fx"
> BasicEffectPSBasicVertexLighting.hlsl
> #include "BasicEffect.fx"
>
> You then compile each of these .hlsl files once with the proper shader profile and entry-point. This approach works fine for smaller projects, but doesn't scale well to large complex shaders without using legacy fx profiles. In that case, other build solutions like DirectX Tool Kit's build solution is probably better.
>
> If you are using legacy fx profiles, you of course only have to compile each .fx once and it will generate all the shaders it specifies in technique/passes in one go.

---

Frank Luna's Direct3D 11 book is a victim of its timing. It was published just prior to the legacy DirectX SDK being deprecated. The basics of the book are great, but FX11, D3DX11, and XNAMath all have replacements that avoid using the legacy DirectX SDK. See Living without D3DX, Introducing DirectXMath, and Book Recommendations.

**UPDATE**: While it's still strongly recommended that you not use D3DX9, D3DX10, or D3DX11 in new projects, for tutorials or books like Luna's that assume you have the legacy DirectX SDK installed, there's now an easier-to-use solution for modern toolsets: use the NuGet package Microsoft.DXSDK.D3DX. See this blog post for details.

Effects was always an optional system which made it easier to bind a group of related shaders and state based on a file format. You don't need Effects, and you can always compile the `fx` file multiple times for each permutation of the individual shaders and handle setting up all the related state yourself.

> If you are new to Direct3D 11 development, you should take a look at DirectX Tool Kit and it's tutorials as it provides a number of 'stock' shaders which can get you a long way.

# Answer
> 4 votes
No.

The Effects framework, and `.fx` files, were something like a container wrapper for shaders and state associated with those shaders. "Techniques" and "passes" are concepts introduced by the Effects framework, and don't exist otherwise unless you build your own abstraction.

Pixel/vertex shaders alone will just contain the code for the shader itself, and declarations of input uniforms and so on. Binding and supplying values for those uniforms and setting up any rendering state the shader wants to assume are all your responsibility when you leave the Effects framework behind.

---
Tags: directx, directx11, hlsl
---


title: Layers in PixiJS

text:
# Question
Title: Layers in PixiJS
I am using the PixiJS framework to create a 2D RPG Game.

How can I create a `PIXI.Container` with a transparent background which I can render on top of my main stage container?

My goal is it to have 4 layers which contain `PIXI.Sprite`s and `PIXI.Text`s:

layer 1 should be rendered beneath the player
layer 2 should be rendered above layer 1
layer 3 should be rendered above the player and above layer 1 and layer 2
layer 4 should be rendered above everything else for debug information

In case I can cannot use multiple `PIXI.Container` then how else could I achieve this effect?

# Answer
If you for some reason don't want to use preordered containers, then you need to sort the render list.
> 1 votes

---
Tags: javascript, sprites, blending, alpha-blending
---


# Question
Title: How to change colors where two boxcollider2d objects intersect (Unity 5 2D)
I'm creating a 2D game in Unity that relies on combining colors. For instance, if the yellow sprite in in a position, and the player slides a magenta sprite partly over it, the area where the two intersect should become red. If someone then slides a cyan sprite, the cyan+yellow should be green, the cyan+magenta should be blue, and the cyan+red should be black.

I was planning to use box collider 2d and use a OverlapArea on TriggerStay2D, but that didn't work. I'm assuming in my code below that pointA is the upper left coordinate of the first sprite, and pointB is the upper left coordinate of the second sprite (though perhaps I'm wrong on that).

```
void OnTriggerStay2D(Collider2D collisionInfo)
{
    Debug.Log("I am still colliding");

    Vector2 pointA;
    Vector2 pointB;

    pointA = this.transform.position;
    pointB = collisionInfo.transform.position;

    Vector2 pointC = Physics2D.OverlapArea(pointA, pointB);

}

```

After reading the documentation, I think I'm not understanding what OverlapArea returns - it seems to return a Collision, but that doesn't make a whole lot of sense.

Any thoughts on this? Is there a better way than trying to find a pair of 2-Tuples that would bound the collision area and create a new sprite of the new color over that area?

# Answer
`Physics2D.OverlapArea(pointA, pointB)` just returns which collider is under the area covered by a rectangle with pointA and pointB as corners.

This will not be useful for what you are trying to achieve. You will need a shader that combines the colors being rended.

You could create a new material, and use the "Particles-\>Multiply", then use this new material on your SpriteRenderers (if you are using sprites).

With this shader the colors will blend like you described, but keep in mind that it will blend with the backgroun too, so the background should be white to keep the colors of the sprites "clean".
> 1 votes

# Answer
You can use triggers to detect when a new intersection happens. Or could could calculate it manually.

Anyway, once you detect an intersection, you should determine manually which areas should have which colors. I mean, you should have two different data structures: the physical objects that the player manipulates, and the color fragments. Therefore, each physical object will be rendered by a combination of color fragments.

Suppose that two rectangles overlap each other in a cartesian way, so the overlap zone is a rectangle and each rectangle has an L-shaped non-overlapping zone. You would need two physical objects (one for each rectangle), and five color fragments (one for the overlapping tectangle, and two for each of the L-shaped zones).

Each time the physical objects move, you should recalculate the color fragments, according to their position in the scene.
> 0 votes

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


# Question
Title: Unity can't recognize class and namespace, how can I fix it?
I just updated Unity to 5.4 today, though as I saw, this problem was present in previous versions too.

So the error message is :

> The type or namespace name 'FirstPersonController' could not be found (are you missing a using directive or an assembly reference?)

This happens when I try to reference the FPSController prefab's FirstPersonController.cs (obviously I'm talking about the one from StandardAssets/Characters).

Yes, I did try including

```
using *UnityStandardAssets.Characters.FirstPerson*

```

in my script, but no, it did not work. Doesn't even recognize is as a valid namespace.

The same happens when I try the other way: when I try referencing my script inside the FirstPersonController.cs. It just doesn't recognize it as valid.

Anybody has any idea how to solve it?

# Answer
> 2 votes
I had an identical issue with the `AeroplaneController` script.

While I do not acknowledge it as the absolute solution, I solved the issue by actually moving the script to my local scripts folder.

The problem appears to be in having native access to scripts across a folder hierarchy. If script A is in a different parent folder to script B, neither will have the ability to immediately reference each other.

Ofcourse, this added some other problems. In my case, `AeroplaneController` referenced one or two scripts (or *was* referenced *by*, I honestly can not remember for sure), and moving it outside of the folder structure removed the ability to see the other scripts / `AeroplaneController` from the other scripts. I would have either moved the important scripts, as well, or removed the reference to `AeroplaneController` in the unimportant scripts simply to remove the error.

# Answer
> 0 votes
It sounds like you have a conflict between the versions of unity the project is referencing.

Are you using VS to edit your scripts? If so, expand the `references` node in the solution explorer and see if you have any missing/broken references.

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


# Question
Title: How to avoid 2d enemy to see through walls
I am using `RayCastCallback` to detect the line of sight. So I the enemy avoid seeing the player through walls, problem is there's a limited field of view. So I added another two rays to the left and right side, with a total of 3 rays. Another problem is when the distance is longer the rays can't handle to see the player, so I added another more rays to fill the field of view. I don't know if this kind of idea is good or there is a better way without using rays?

Look in the below image, it seems the there is a circular sensor or like a radar. I am trying to achieve this kind of enemy sight (enemy sight demo ).

# Answer
You only need to do two things: check if there is line of sight (raycast between the player and enemy) and if the angle of that ray is within the field of view (using atan2 to get an angle or using the dot product between the facing vector and the raycast direction vector)
> 3 votes

# Answer
I found a solution with the help of box2d, I could create a circle or cone shape as *FOV* (Field of View) and set as sensor. Now that I could check if the enemy is on the *FOV*, I could now use a single ray to use in `RayCastCallback` starting from an enemy position to target position. In this kind of way I could now make the enemy avoid seeing through walls. I have not yet tested this but I think this would work and also I minimize the stress of using multiple rays.
> 0 votes

---
Tags: libgdx, box2d, ai, raycasting
---


# Question
Title: Server and client showing different spawned object - How do I unify them?
I have overridden `OnServerAddPlayer` and put some custom logic in place to set the rendered prefabs color. Something like this:

```
    var playerCount = NetworkServer.connections.Count;

    if(playerCount == 1)
    {
        player.GetComponentInChildren<Renderer>().material.color = Color.green;
    }

```

When I test the code with two application instances, the server host shows the expect result (first character is green, second is red) but the client instance shows both characters as red (the default).

Is my logic for setting the colour incorrect? or do I need to do something special to ensure that the my clients will see the colour I have set for the characters on the server?

# Answer
Firstly, OnServerAddPlayer only runs on a server, so the clients don't run this code. Secondly, combined with the fact that the properties of child objects are not transmitted with a NetworkBehaviour, so the change to set the material color will not be sent to clients.

So you need a client-side hook to leverage when an item is added to the scene; you should implement NetworkBehaviour.OnStartClient within your player class.

https://docs.unity3d.com/ScriptReference/Networking.NetworkBehaviour.OnStartClient.html

Also look into using the SyncVar attribute; it's used for persisting field values on a class which inherits from NetworkBehaviour.

https://docs.unity3d.com/ScriptReference/Networking.SyncVarAttribute.html

With these combined, you could do something like the below:

```
public class Player : NetworkBehaviour
{
    [SyncVar] private Color objectColor;

    public virtual void OnStartClient(NetworkClient client)
    {
        this.GetComponentInChildren<Renderer>().material.color = objectColor;
    }
}

```

FYI: A good overview of these concepts is here: Unity Documents - Object Spawning
> 1 votes

---
Tags: unity, multiplayer, unet
---