title: LibGDX: Problems creating custom actor

text:
# Question
Title: LibGDX: Problems creating custom actor
I am creating a custom class that extends from `Actor`,just like this:

```
public class MyActor extends Actor {
ProgressBar bar;
Label nameLabel;
TextButton button;
public MyActor(String name, Skin skin){
    nameLabel = new Label(name, skin);
    button = new TextButton("Whatever",skin);
    bar = new ProgressBar(0f,5f,1f,false,skin);

}
@Override
public void act(float delta) {
    super.act(delta);
    bar.setBounds(getX(), getTop()-getHeight() / 3f, getWidth(), getHeight() / 3f);
    nameLabel.setBounds(getX(), getY()+getHeight() / 3f, getWidth(), getHeight() / 3f);
    button.setBounds(getX(), getY(), getWidth(), getHeight() / 3f);
}

@Override
public void draw(Batch batch, float parentAlpha) {
    super.draw(batch, parentAlpha);
    bar.draw(batch, parentAlpha);
    nameLabel.draw(batch, parentAlpha);
    button.draw(batch,parentAlpha);
} }

```

Then I try to add it to a `Table`:

```
Table myTable = new Table();
myTable.add(myActor).row();

```

But it always gets drawn in the 0,0 coordinates!, what am I doing wrong? Do I have to override another method?

# Answer
> 1 votes
I know its late but it might help someone, basically when we create actors, in the act() we'll have to set its layout boundary relative to the parent. Layout boundary helps identify the size of the custom actor.

```
someActor.setBounds( getParent().getX()+getX(), getParent.getY()+getY(), someActor.getPrefWidth(), someActor.getPrefHeight() );

```

# Answer
> 0 votes
I ran into a similar problem where despite multiple instances of my actor in table.add(myActor) they just stacked on top of each other. That is they weren't put into separate rows/columns visually using scene2d's Table.

I updated myActor to extend Widget (instead of extending Actor) and implemented getPrefWidth and getPrefHeight which solved the problem.

---
Tags: libgdx, scene2d
---


title: How can I outline text in Unity?

text:
# Question
Title: How can I outline text in Unity?
Since it generates more triangles and vertices, the official outline script isn't a good way to do text outlining in my project.

How can I outline my text, with better performance?

TextMesh Pro may be the solution, but it'll increase the usage of memory heavily and our game is aimed at mobile platforms, so we want to minimise use of memory.

# Answer
There is a very simple way to create outlined text. It's qill be a bit slower theoretically, but I've never come across a situation where an app was running slow because of this.

Let's say we have white text, and we want to outline it in black:

1. Draw the text in black, slightly offset to the left (1 or 2 pixels should usually suffice).
2. Do the same thing, but offset to the right.
3. Repeat steps 1 and 2, but offset the black text up and down.
4. Draw the white text without an offset.

If you need a very thick outline, and the offset distance increases, you may also want to draw the black text offset diagonally (in 4 directions)
> 1 votes

# Answer
Not sure if it works on mobile, but maybe this helps https://www.gamedev.net/blogs/entry/2264832-highlight-in-unity/. There are links in there for some other techniques which might suit you better also.

The idea is to have a second camera render the text you want to highlight in solid color, then create a dilated duplicate. Finally, you'd use the non-dilated render as a cutout for the first, effectively creating a solid outline. This outline render would then be passed to your main camera to be used as an 'overlay' RenderTexture.
> 0 votes

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


# Question
Title: Why specular reflection work only in center of virtual scene?
How to calculate this cpecular reflection?

HLSL

```
void calculateSpecular(
    in float4 Normal,
    in float4 SunLightDir,
    inout float4 Specular
){
        Specular = specularLevel * pow(saturate(dot(reflect(normalize(abs(eyePosition)), Normal), SunLightDir)), specularExponent);
}

```

```
/// in pixel shader
float4 Specular = float4(0.f,0.f,0.f,1.f);
calculateSpecular( input.normal, -sunLightDir, Specular );

///sunLightDir it's just camera position + vec3(0,10,0)

```

```
/// in vertex shader
output.normal = mul( float4( input.normal, 0.f ) , World );

```

# Answer
> 0 votes
Do not forget about the different types of light sources.

This article helped me solve the problem.

https://www.3dgep.com/texturing-lighting-directx-11/

---
Tags: directx11
---


# Question
Title: In tactical combat games, why does shooting end your turn?
I was wondering about this particular game mechanic in tactical combat games, like XCOM2, where you have two actions, which may be:

* move+move
* reload+move
* move+reload
* move+attack

...but not attack+move, because when attacking, it ends your turn.

If I compare this to tabletop D&D 5e, with its move+attack actions, it shouldn't be that different, but this restriction seems to make things completely different.

What is the game design purpose for this kind of restriction?

# Answer
> 8 votes
## Pacing

One standard rule not just of game design but of any form of entertainment is to aim for an engagement curve which slowly builds up excitement and then relieves the tension at the peak point.

Game designers usually aim for that curve not just in their overall narrative, but also in smaller events, down to the most basic game loops.

When you execute the turn of a unit in a tactical combat game, then the attack is arguably the most exciting part of it. So it makes sense to put this event at the end of this interaction.

Extra Credits has a nice video about the topic of macro-pacing and micro-pacing: Pacing - How Games Keep Things Exciting.

## Encourage offensive gameplay

If the player would attack and then move, they would be encouraged to move their units into a safe position after every attack before the enemy can strike back. This would encourage a very defensive gameplay style where the player takes very little risk.

On the other hand, having to move and then attack encourages a more aggressive playstyle. The player moves their units to the position from which they can attack most efficiently and hope they get rid of all threats before the enemy gets their turn.

There are several reasons why you want a more aggressive playstyle.

* Taking risks is usually exciting for the player (if done well).
* It leads to more fast-paced battles
* It is easier for most strategy games to develop a "good enough" AI to play against an aggressive player than it is to play against a defensive player.

# Answer
> 3 votes
Allowing a move after an attack lets you aggro an enemy then dash out of its range / behind full cover where your unit is no longer at risk.

It's a safe but dull strategy that avoids the drama of injuring or losing loved/useful/heavily-invested soldiers that's at the heart of a game like X-COM.

By requiring that the soldier stay in the place from which they shot, the game forces the player to weigh the pros of a good firing angle over the cons of an exposed position more heavily, and find ways that they can use their squad together as a team to support those on the front lines.

Together with things like "doomsday clock" mechanics, this is one way that the game's design tries to constrain the player's strategy toward the high-drama intended experience of constantly pushing forward, rather than a tedious/methodical/safe approach that never costs a soldier.

But not every tactical combat game works this way. For example, in Mario and Rabbids Kingdom Battle, you can choose to spend your movement and attacks in any order. This helps differentiate the experience of this game, which is not about the drama of risking a soldier in the field, but about accessible puzzle-solving. So allowing the moves in any order both widens the puzzle-solving possibility space, and makes the game more welcoming to players by having one less restriction to teach & remember when planning moves.

---
Tags: game-design, game-mechanics, turn-based, combat
---


# Question
Title: How can I create a Texture2D out of an array of color data?
I'm trying to make a simple engine with DirectX where you can draw to the screen with a function Draw(x, y, r, g, b). The function sets the pixel at x,y to the color r,g,b. The engine has a parameter for the size of a pixel, making the engine capable of looking somewhat retro or low resolution. My question is in the title. I would like to take an array of color data and paste it into a Texture2D which will then be rendered to the screen, and I would be greatful if someone could point me in the right direction of how I could go about doing that in DirectX.

# Answer
> 0 votes
I'll answer my own question, cause I recently figured it out.

first you'll need the array of data to fill your texture with usually of type uint32\_t:

```
uint32_t* colorBuffer;
m_colorBuffer = new uint32_t[CanvasWidth() * CanvasHeight()];
memset(m_colorBuffer, 0, sizeof(uint32_t) * CanvasWidth() * CanvasHeight());

for (int x = 0; x < TEXTUREWIDTH; x++) {
    for (int y = 0; y < TEXTUREHEIGHT; y++) {
        m_colorBuffer[x + y * CanvasWidth()] = (RED) | (GREEN << 8) | (BLUE << 16) | (ALPHA << 24); //R | G | B | A
    }
}

```

second you need a D3D11\_SUBRESOURCE\_DATA element to fill your texture with data.

```
D3D11_SUBRESOURCE_DATA subrecData;
subrecData.pSysMem = colorBuffer;
subrecData.SysMemPitch = TEXTUREWIDTH * sizeof(uint32_t);
subrecData.SysMemSlicePitch = 0;

```

and a D3D11\_TEXTURE2D\_DESC:

```
D3D11_TEXTURE2D_DESC desc;
desc.Width = TEXTUREWIDTH;
desc.Height = TEXTUREHEIGHT;
desc.MipLevels = desc.ArraySize = 1;
desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
desc.SampleDesc.Count = 1;
desc.SampleDesc.Quality = 0;
desc.Usage = D3D11_USAGE_DEFAULT; //or D3D11_USAGE_DYNAMIC for map/unmap
desc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
desc.CPUAccessFlags = 0; // D3D11_CPU_ACCESS_WRITE for dynamic usage
desc.MiscFlags = 0;

```

then create the texture with your device:

```
ID3D11Texture2D* texture;
myDevice->CreateTexture2D(&desc, &subrecData, &texture);

```

lastly create a D3D11\_SHADER\_RESOURCE\_VIEW\_DESC and ID3D11ShaderResourceView:

```
D3D11_SHADER_RESOURCE_VIEW_DESC srvd;
srvd.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
srvd.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
srvd.Texture2D.MipLevels = 1;
srvd.Texture2D.MostDetailedMip = 0;

ID3D11ShaderResourceView* shaderResourceView;
myDevice->CreateShaderResourceView(texture, &srvd, &shaderResourceView);

```

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


# Question
Title: How to code a game that can interact with custom controllers?
I want to have my work featured in alt.ctrl.gdc someday.

The process of building a bizarre custom controller is a question for a different stackexchange site, but

Can you tell me a way how to take data from a custom controller with potentially a lot of different bizarre data pouring in and then have that data control a game?

# Answer
> 0 votes
As you can imagine, this depends entirely on the kind of control device you want to implement.

At the beginner end of the spectrum, there are devices like the Makey Makey, which is basically a kit for setting up custom controllers out of everyday items like tinfoil or bananas.

The device has a circuit board you can wire up to electrodes on the controller you've built, and the circuit board itself connects to a PC via USB. It reports itself as a standard keyboard, so listening & responding to inputs from your custom controller is the same as reacting to key presses in your language/framework/engine of choice. No special software or libraries required.

It may seem simplistic, but you can make some pretty exciting controllers this way. Our first prototypes for the modular starship construction in Starlink were built using a Makey Makey and LEGO bricks. :)

---

The next level of complexity you might try is a programmable input emulator like GlovePIE on Windows (now dead, but an open-source alternative FreePIE exists), or OSCulator on Mac.

These programs know how to read input from a vast array of controllers — including things like Wii remote motion sensors — and can translate them to a standard format called "Open Sound Control". You can listen for these messages in your game using a suitable OSC library to react to these inputs, without managing all the complexity of device drivers or network protocols yourself.

You can then combine inputs from a whole batch of different devices, or even tear them apart and embed their guts in a custom form of your choosing. :)

---

The next level up would be using a miniature computer like an Arduino or Raspberry PI to build your controller. These hobbyist devices are commonly used for making one-off gadgets like controllers, so you should be able to find guides or pre-made kit parts for the features you need.

Because these are fully programmable computers, you have the freedom to make them work and communicate however you want - over USB, Bluetooth, Wifi, or other connections of your own design - but you'll usually have to implement your own networking code or device driver / human interface device reporting to make the connection on each end.

Other answers may be able to give more detailed insights into the types of communication or libraries that can help you here.

Beyond that, you can look at less hobbyist-friendly microcontrollers, paring down the feature set from the full computers onboard the Arduino/PI to just the bare minimum you need. (The final shipping Starship mounts & parts in Starlink use a much simpler chip, for example)

---
Tags: input, controllers, hardware
---


# Question
Title: Rotating a gameobject in the Inspector doesn't change direction
When I add a Cube to a scene, the blue axis (=forward) of the cube points into a certain direction.

When I now change the Y rotation of the cube to 90 in the inspector, the blue arrow doesn't rotate.

I would have expected it to rotate with the rotation that I have defined for the cube.

What is happening here?

To explain more in detail why this is bothering / confusing me:

I want to rebuild the RE4 inventory (which is actual 3D). The items in this inventory can be moved within the "grid":

To do that I have created a suitcase and then I added a gun to it:

As one can see, I have assigned the facing direction properly: The blue axis (=forward) points into the direction of the gun.

Now I wanted to rotate the gun in such a way that it is shown like in the original RE4 inventory.

To do that, I apply a rotation of Y = -90.

The gun looks correctly now:

However, the blue axis now faces the wrong direction in my opinion. Why does it not rotate along with the rotation of the gameobject?

This really confuses me because now when I want to move the gun left or right, I have to change its X position value instead of changing the Z position value.

This just seems wrong to me.

Can somebody tell me what I'm missing here?

Thank you.

# Answer
I will try to answer my question. Please correct me if I'm wrong with anything!

To check what is going on here I did some experiments:

I created a cube in Blender and exported it with 2 different export settings:

```
1) "x is forward"

2) "-z is forward"

```

In the below screenshot it can be observed that this export option has absolutely no effect on the Unity axes. The red arrow always points sideways, the green arrow always points up, and the blue arrow always points forwards.

Even if the objects are rotated in Unity or in Blender, it has no effects on the Unity arrows. In fact, the arrows are more or less useless in my opinion and should ONLY be used to inspect LOCAL rotation values. For the "Global", the arrows seem to be confusing and also useless.

I have then imported a model which has the rotation set incorrectly in Blender. As one can see, this affects the rotation of the model, but not the Unity arrows:

For double-checking I created a scaled cube and exported it with different axes export settings. One can see that it affects the rotation of the model, but again not the Unity arrows:

So it's safe to say that one can never change the direction in which the X, Y and Z values move an object. One can only change the "local" rotation.

I'm not sure if that's a good explanation, but for me it was the only way to understand it.

Again, please anybody just correct me if he spots anything wrong in my explanation.

Thank you.
> 0 votes

# Answer
Looks like you have your Gizmo Display Toggles set to global mode instead of local.

You can find these in the toolbar here:

Screenshot from Unity documentation

When set to Local mode, the gizmo arrows / rings will match the object's local orientation.

When set to Global mode, they'll always match the world axes.

Your object and its local directions are still rotating either way, it's just the display of the gizmo that's affected.
> 4 votes

---
Tags: unity
---


# Question
Title: How to retrieve the text of a text label placed in a TileMap (.tmx)
TiledMapEditor supports the placement of text-labels nowdays, but I'm not able to load the text in a String.

I've tried iterating through the `MapProperties` of a `MapObject`, but the text is not part of them.

```
for(MapObject object : map.getLayers().get("id of textlabels").getObjects())
{
  MapProperties props = object.getProperties();
  Iterator<String> valueIta = props.getValues();
  while (valueIta.hasNext()){
   String currentValue = String.valueOf(valueIta.next());
   sout(currentValue); //prints id,x,y,width,height
  }
}

```

I also looked at the usages of the MapObject interface if there is anything like a ''TextLabelMapObject'' (like `RectangularMapObject`), but found none.

Looking in my .tmx file I can find this description of my object, but I have no idea how to parse that text attribute.

```
<object id="1594" x="1512.5" y="7170.5" width="83" height="19">
 <text wrap="1">Hello World</text>
</object>

```

My idea was to iterate through the layer's objects, parsing the current object to a TextLabelMapObject (which not exists) that implements a method getText() that returns the String inside `<text>`.

I'm a missing something here?

Any hint is greatly appreciated.

---

**EDIT**:

So, as @bornander suggested I've created the following classes:

```
public class CustomMapLoader extends CustomBaseTmxMapLoader<TmxMapLoader.Parameters> {

```

https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/maps/tiled/TmxMapLoader.java

```
public abstract class CustomBaseTmxMapLoader<P extends AssetLoaderParameters<TiledMap>> extends AsynchronousAssetLoader<TiledMap, P> {

//added to loadObject(TiledMap map, MapLayer layer, XmlReader.Element element)
...
} else if ((child = element.getChildByName("ellipse")) != null) {
   object = new EllipseMapObject(x, flipY ? y - height : y, width, height);
} else if ((child = element.getChildByName("text")) != null) {
   object = new TextLabelMapObject(child.getText(), x, flipY ? y - height : y, width, height); //this line will create a text object with position data
}

```

https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/maps/tiled/BaseTmxMapLoader.java

so that I can load my map like this:

```
gameWorld = new CustomMapLoader().load(Constants.MAP);

```

Ans here is the `TextLabelMapObject`

```
import com.badlogic.gdx.maps.MapObject;
import com.badlogic.gdx.math.Rectangle;

public class TextLabelMapObject  extends MapObject {

    private Rectangle rectangle;
    private String text;

    /** @return rectangle shape */
    public Rectangle getRectangle () {
        return rectangle;
    }
    /** @return text as string */
    public String getText () {
        return text;
    }

    /** Creates a rectangle object which lower left corner is at (0, 0) with width=1 and height=1 */
    public TextLabelMapObject () {
        this("", 0.0f, 0.0f, 1.0f, 1.0f);
    }

    /** Creates a {@link Rectangle} object with the given X and Y coordinates along with a given width and height.
     *
     * @param x X coordinate
     * @param y Y coordinate
     * @param width Width of the {@link Rectangle} to be created.
     * @param height Height of the {@link Rectangle} to be created. */
    public TextLabelMapObject (String text, float x, float y, float width, float height) {
        super();
        rectangle = new Rectangle(x, y, width, height);
        this.text = text;
    }
}

```

In my B2DWorldCreator I do

```
for (MapObject object : GameEngine.mapLoader.gameWorld.getLayers().get(Constants.LAYER_TEXTLABELS).getObjects()) {
  Rectangle rect = ((TextLabelMapObject) object).getRectangle();
  String text = ((TextLabelMapObject) object).getText();
  infoList.add(new InfoSign(main, text, rect.getX()/ Constants.PPM, rect.getY() / Constants.PPM));
}

```

with the InfoSign (thats later going to be a `Sprite`) being

```
public class InfoSign  {
    private String text;
    private float x;
    private float y;

    public InfoSign(String text, float x, float y){
        this.main = main;
        this.text = text;
        this.x = x;
        this.y = y;
    }

    public void draw(Batch batch){
        main.assets.infoFont.draw(batch, text , x,y);
    }
}

```

**Thanks a bunch!**

# Answer
> 1 votes
If you're using the `TmxMapLoader` that comes with **libGDX** then you won't get a `TextLabelMapObject` for your *Text*s, this is because that implementation does not cater for *Text*.

`TmxMapLoader` derives from `BaseTmxMapLoader` which reads objects in object layers using the `loadObject` method, which looks something like this:

```
protected void loadObject (TiledMap map, MapObjects objects, Element element, float heightInPixels) {
    if (element.getName().equals("object")) {
        MapObject object = null;

        float scaleX = convertObjectToTileSpace ? 1.0f / mapTileWidth : 1.0f;
        float scaleY = convertObjectToTileSpace ? 1.0f / mapTileHeight : 1.0f;

        float x = element.getFloatAttribute("x", 0) * scaleX;
        float y = (flipY ? (heightInPixels - element.getFloatAttribute("y", 0)) : element.getFloatAttribute("y", 0)) * scaleY;

        float width = element.getFloatAttribute("width", 0) * scaleX;
        float height = element.getFloatAttribute("height", 0) * scaleY;

        if (element.getChildCount() > 0) {
            Element child = null;
            if ((child = element.getChildByName("polygon")) != null) {
                String[] points = child.getAttribute("points").split(" ");
                float[] vertices = new float[points.length * 2];
                for (int i = 0; i < points.length; i++) {
                    String[] point = points[i].split(",");
                    vertices[i * 2] = Float.parseFloat(point[0]) * scaleX;
                    vertices[i * 2 + 1] = Float.parseFloat(point[1]) * scaleY * (flipY ? -1 : 1);
                }
                Polygon polygon = new Polygon(vertices);
                polygon.setPosition(x, y);
                object = new PolygonMapObject(polygon);
            } else if ((child = element.getChildByName("polyline")) != null) {
                String[] points = child.getAttribute("points").split(" ");
                float[] vertices = new float[points.length * 2];
                for (int i = 0; i < points.length; i++) {
                    String[] point = points[i].split(",");
                    vertices[i * 2] = Float.parseFloat(point[0]) * scaleX;
                    vertices[i * 2 + 1] = Float.parseFloat(point[1]) * scaleY * (flipY ? -1 : 1);
                }
                Polyline polyline = new Polyline(vertices);
                polyline.setPosition(x, y);
                object = new PolylineMapObject(polyline);
            } else if ((child = element.getChildByName("ellipse")) != null) {
                object = new EllipseMapObject(x, flipY ? y - height : y, width, height);
            }
        }
        if (object == null) {
            String gid = null;
            if ((gid = element.getAttribute("gid", null)) != null) {
                int id = (int)Long.parseLong(gid);
                boolean flipHorizontally = ((id & FLAG_FLIP_HORIZONTALLY) != 0);
                boolean flipVertically = ((id & FLAG_FLIP_VERTICALLY) != 0);

                TiledMapTile tile = map.getTileSets().getTile(id & ~MASK_CLEAR);
                TiledMapTileMapObject tiledMapTileMapObject = new TiledMapTileMapObject(tile, flipHorizontally, flipVertically);
                TextureRegion textureRegion = tiledMapTileMapObject.getTextureRegion();
                tiledMapTileMapObject.getProperties().put("gid", id);
                tiledMapTileMapObject.setX(x);
                tiledMapTileMapObject.setY(flipY ? y : y - height);
                float objectWidth = element.getFloatAttribute("width", textureRegion.getRegionWidth());
                float objectHeight = element.getFloatAttribute("height", textureRegion.getRegionHeight());
                tiledMapTileMapObject.setScaleX(scaleX * (objectWidth / textureRegion.getRegionWidth()));
                tiledMapTileMapObject.setScaleY(scaleY * (objectHeight / textureRegion.getRegionHeight()));
                tiledMapTileMapObject.setRotation(element.getFloatAttribute("rotation", 0));
                object = tiledMapTileMapObject;
            } else {
                object = new RectangleMapObject(x, flipY ? y - height : y, width, height);
            }
        }
        object.setName(element.getAttribute("name", null));
        String rotation = element.getAttribute("rotation", null);
        if (rotation != null) {
            object.getProperties().put("rotation", Float.parseFloat(rotation));
        }
        String type = element.getAttribute("type", null);
        if (type != null) {
            object.getProperties().put("type", type);
        }
        int id = element.getIntAttribute("id", 0);
        if (id != 0) {
            object.getProperties().put("id", id);
        }
        object.getProperties().put("x", x);

        if (object instanceof TiledMapTileMapObject) {
            object.getProperties().put("y", y);
        } else {
            object.getProperties().put("y", (flipY ? y - height : y));
        }
        object.getProperties().put("width", width);
        object.getProperties().put("height", height);
        object.setVisible(element.getIntAttribute("visible", 1) == 1);
        Element properties = element.getChildByName("properties");
        if (properties != null) {
            loadProperties(object.getProperties(), properties);
        }
        objects.add(object);
    }
}

```

As you can see, the method tries to load `polygon`s, `polyline`s, `ellipse`s and texture regions, and if it's not one of those it falls back to assuming the object is a rectangle.

One way to solve this would be to create a new version of `TmxMapLoader` and have it derive from a new version of `BaseTmxMapLoader` and in that class extend the `loadObject` method to handle *text*s, possibly by adding a class called `TextMapObject` and modify the new version `BaseTmxMapLoader` to include something like this:

```
} else if ((child = element.getChildByName("text")) != null) {
    object = new TextMapObject(x, flipY ? y - height : y, width, height, child.getText());
}

```

BaseTmxMapLoader on GitHub

---
Tags: libgdx, tiled
---


# Question
Title: The 'speed' value of the Nav Mesh Agent component does not seem to affect speed at all (Unity3D/C#)
The speed value of the Nav Mesh Agent component doesn't seem to have any effect whatsoever on the speed of my game object. Actually none of the motion values seem to have any effect. I've attached photos of how I've set up my Nav Mesh Surface Plane and how I've set up the Nav Mesh Component attached to my game object. I followed an online tutorial to use the Nav Mesh Agent component via a C# script. The object moves randomly just fine except that the speed and other values on the Nav Mesh Agent component don't seem to do anything. You will notice that there is a commented out 'randSpeed' public float variable that I experimented with. Changing that variable also did not affect the speed.

Any ideas about this problem are appreciated. Thank you.

```
public class  RandomMovement2: MonoBehaviour
{
    UnityEngine.AI.NavMeshAgent navMeshAgent;
    public float timerForNewPath;
    private bool inCoroutine;
    //public float randSpeed;

    // Start is called before the first frame update
    void Start()
    {
        navMeshAgent = GetComponent<UnityEngine.AI.NavMeshAgent>();
        //randSpeed = navMeshAgent.speed;
    }

    Vector3 getNewRandomPosition()
    {
        float x = Random.Range(-40, 40);
        float z = Random.Range(-40, 40);

        Vector3 pos = new Vector3(x, 0, z);
        return pos;
    }

    IEnumerator doSomething()
    {
        inCoroutine = true;
        yield return new WaitForSeconds(timerForNewPath);
        GetNewPath();
        inCoroutine = false;
    }

    void GetNewPath()
    {
        navMeshAgent.SetDestination(getNewRandomPosition());
    }

    void Update()
    {
        if (!inCoroutine && (Reaction2.stopMoving==false))
        {
            StartCoroutine(doSomething());
        }
    }
}

```

# Answer
Nevermind. I solved it.

The problem was the order in which I assigned the speed to the Nav Mesh Agent component in code. (The code that is commented out in the code above)

I had it written as `randSpeed = navMeshAgent.speed;`

It should have been `navMeshAgent.speed = randSpeed;`

Also, since it is in the Start function, make sure that you've set the speed before you hit start on the game. You could also put it in the Update function and then you can adjust it whenever you want during the game. And of course there are other ways in code you could configure it to update the speed during the game.

---

Although I still don't understand why we can't change the speed and other motion settings from directly within the Nav Mesh Agent component UI.
> 0 votes

# Answer
You're problem is that your try to change a value-type object and expect to change something.

It's the same when you want to change the position. See this example:

```
// this wouldn't work
Vector3 position = gameObject.transform.position;
position = new Vector3(position.x + 1, position.y, position.z);

// this would work
Vector3 position = gameObject.transform.position;
position = new Vector3(position.x + 1, position.y, position.z);
gameObject.transform.position = position;

```

This is a kind of basic mistake but pretty common and lightly overseen.

---

Also you can change the speed value on a NavMeshAgent easily in the inspector and see the agent move faster. Just try it yourself.
> 1 votes

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


title: Static Camera on Endless Runner

text:
# Question
Title: Static Camera on Endless Runner
I am developing a mobile game in ue4. For this project, I need to have a "static" camera so that the player can move within the frame not affecting camera location and rotation. But as this is an endless scroller I also need to have the camera move at a constant pace limiting the player's area of movement. Does anyone know how to do this?

# Answer
> 1 votes
I could think of two ways on how to solve your problem.

* **Player-centered approach:** Update the position of the static camera based on the position of the player pawn

e.g. in pseudocode assuming the player moves into the x direction:

```
Vector3 cam_to_player_distance = {0, 100.0f, 100.0f};
cam_position = player_pawn.getActorLocation() + cam_to_player_distance;

```
* **Camera-centered approach:** (my choice)

Make the camera the controlled pawn and add the runner as a child actor. Now you can freely move the runner to the left and right and without the camera being affected

# Answer
> -3 votes
Greatings, the trick is not moving the player but the level.

---
Tags: camera, unreal-4, unreal
---


# Question
Title: How do I use images with copyright in my game?
Our game requires to show images from movies, cartoon characters, etc. but we don't know how we can include them.

We have seen that games like **QuizUp** and other guess the pic like games have images from Disney characters, Pokemon or company logos, etc.

How does it work? Is this usage considered fair use?

# Answer
Disclaimers:

* I am not a lawyer, this answer does not constitute legal advice
* I am not familiar with QuizUp, have never used it

---

For what I can find QuizUp allows users to create questionnaires on which the users can upload images. Some user could upload images that are under copyright without having a license to use them.

Note: there is also the trouble of trademarks. Some images are not only under copyright, but are also trademarks of companies. And yes, copyright and trademark are two different things. Usually companies allow the use of their trademark as long as some guidelines are followed, which usually include but are not limited to mentioning they are a trademark.

---

Now, there are two parts to this:

1. QuizUp does not own the copyright to the uploaded content. Instead, when the user uploads a picture, the user is licensing it to QuizUp so they can distribute it. Note: this is a common practice for social networks. For example, you have image rights over pictures of you (plus, you as photographer generate copyright), a social networks - say, Facebook - could not distribute them without you granting them a license.
2. Furthermore, when the user is uploading a picture, the user is claiming to have the right to use it. Either, the user is claiming to the author of the picture or have a license. Note: depending on the jurisdiction QuizUp could be required to cooperate with copyright holders to take down illegal uses, or even be required to check for them automatically.

How do they do that? Each user did agree to it when they signed up (even if they didn't read). So, let us read, we can find it in their Terms of Service, under "Rights in User Content Granted by You":

> (...) By posting User Content to the Services, you grant Plain Vanilla a non-exclusive, transferable, sublicenseable, worldwide, royalty-free right and license to use, modify, publicly perform, publicly display, reproduce, and distribute such User Content on and through the Services. (...)
>
> You represent and warrant that: (i) the User Content is yours (you own it) or you have the right to use it and grant us the rights and license as provided in these Terms, and (ii) the posting of the User Content on or through the Services does not violate the privacy rights, publicity rights, copyrights, contract rights or any other rights of any person. (...)

That is, they expect that the user that uploads images, say of a Disney character, has right to that Disney character (for example the user is a Disney employee tasked to do this on behalf of the company).

---

How can they use those images?

The user that upload them is granting them a license, and they are - as far as I can tell - shifting responsability to the user.

The Terms of Service, under "Rights in User Content Granted by You" say:

> (...) We are not responsible or liable for the removal or deletion of (or the failure to remove or delete) any of your User Content.

And under "QuizUp IP Guidelines":

> (...) Plain Vanilla Corp is not responsible for your illegal use of a third party’s intellectual property.

Under "My QuizUp Topic Terms":

> You are responsible for the Topics you create, including their legality, reliability, and appropriateness. You represent and warrant that the user content is yours or you have the right to use it and grant us the right and license and that your are not violating any privacy rights, publicity rights, copyrights, contract rights or any other rights of any person. Do not upload any images that the copyright holder disagrees with e.g. images identified with a copyright notice, you are responsible for all uploaded images and material. We have the right to decide at our sole discretion that the material you have created is inappropriate and therefore not allowed and removed. (...)

Note: I am not familiar enough with QuizUp to know if they do any kind of checks, or take down under copyright claim.

---

Is this fair use?

No. It isn't. They depend on a license. There is a chance that individual users could claim fair use, and whatever or not that applies would have to be decided case by case.

In fact, the Terms of Use, under "QuizUp IP Guidelines", say:

> If a legal claim is brought against us that is related to your material you will have to pay our legal fees and costs related to this lawsuit, attorney’s fees, settlement or judgment amount that we are required to pay as a result.

That means that if somebody sues them because of the content that a user uploaded, they make the user pay.

---

How do I use images with copyright in my game?

> Our game requires to show images from movies, cartoon characters, etc.

If you are going to include any assets with your game, you will need a license to them. If want to use third party intellectual property and cannot license it, I would suggest to just don't.

You have other options such as:

* Use content under public domain.
* Use content under a loyalty free license (with proper attribution). For example, everything (unless a mistake did happen) you can find on Wikipedia has a license attached to it that allows free distribution.
* Create something, as the author you would have full rights over it.

And of course, you can ask a lawyer about fair use in your jurisdiction. There are guidelines online about copyright exceptions and limitations, however the truth is that it changes from place to place (in fact, the term "fair use" is not applicable worldwide). You should really ask a lawyer in your area.
> 1 votes

# Answer
I think that you need his explicit permission to use their content. So you should send an email, call, ... and get very lucky to be able of use those contents.

However, the law is different in every country/region of the world, so if you want to do it fully legal you should check for the law in every country where you are going to publish the app.

Another option that you could consider is searching for Creative Commons content. If I'm not wrong you can use those content without any problem.
> 0 votes

---
Tags: image, copyright
---


# Question
Title: How to take collision from only a gameobject and discard others?
My player in unity2D has a system to check whether it has collided with any harming substances such as fire, villains etc. When it is true that condition, it Re-Spawns to a certain position. It also decreases the amount of life that the player has. for eg:- At start my player has 15 such lives and each time any harming object as I have mentioned before, collides with my player, it decreases to 14 and so on.

But, In certain places I have fire along the way which is made up of many object as the image shows :-

And, when the player collides with this fire, it decreases the lives 4-5 more because it has collided with more than one object. So, how can I make such that my player's life will only be deducted by 1 in this condition?

# Answer
> 0 votes
Do you mean respawn as in re-spawning at a point earlier in the game? Or re-spawning as in the player gets thrown back upon collision as in being hit, but not dying?

A quick fix would be to lock the player collision detection upon collision. You'd simply introduce a bool, which is checked upon collision and if it's false, you enter the code and set it to true immediately so the next checks all fail. Once you respawned the player, you'll set the bool back to false and "enable" collision detection again.

Alternatively, instead of creating a wall of flame with many gameobjects, each with their own collider, you could create a wall of flames with just one collider and just make it look like there are many single flames.

---
Tags: unity
---


# Question
Title: How can I create online leaderboards for iOS and Android?
I'm developing a racing game for iOS and Android phones/tablets and I want to implement online leaderboards. My game has a singleplayer mode(no multiplayer features) but I want to implement online leaderboards to encourage people to beat other player's score and time.

I want to save the score and time(the time that you need to finish the race) in an online leaderboard. In addition, the name of the player and if possible his country are also saved in the leaderboard. The leaderboards don't need to be cross platform, I can create two leaderboards, one for iOS and one for Android.

Is it possible to create online leaderboards without MySQL and PHP knowledge? In addition, I don't have a server to save the data.

I use MonoGame to develop my game. Do you know a step by step tutorial for implementing online leaderboards because I don't know where to start.

# Answer
> 1 votes
You can take a look at globalstats.io (https://globalstats.io). It is a hobby project I am running for some time now that offers free leaderbords for your exact use case.

---
Tags: c#, android, monogame, ios
---


# Question
Title: God rays shader - Trouble with sun position
I have found a shader that I like here: https://www.shadertoy.com/view/4dyXWy

The code for the fragment shader from the link above is:

```
#define DITHER          //Dithering toggle
#define QUALITY     0   //0- low, 1- medium, 2- high

#define DECAY       .974
#define EXPOSURE    .24
#if (QUALITY==2)
 #define SAMPLES    64
 #define DENSITY    .97
 #define WEIGHT     .25
#else
#if (QUALITY==1)
 #define SAMPLES    32
 #define DENSITY    .95
 #define WEIGHT     .25
#else
 #define SAMPLES    16
 #define DENSITY    .93
 #define WEIGHT     .36
#endif
#endif

void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
    vec2 uv = fragCoord.xy / iResolution.xy;

    vec2 coord = uv;
    vec2 lightpos = texture(iChannel0, uv).zw;

    float occ = texture(iChannel0, uv).x; //light
    float obj = texture(iChannel0, uv).y; //objects
    float dither = texture(iChannel1, fragCoord/iChannelResolution[1].xy).r;

    vec2 dtc = (coord - lightpos) * (1. / float(SAMPLES) * DENSITY);
    float illumdecay = 1.;

    for(int i=0; i<SAMPLES; i++)
    {
        coord -= dtc;
        #ifdef DITHER
            float s = texture(iChannel0, coord+(dtc*dither)).x;
        #else
            float s = texture(iChannel0, coord).x;
        #endif
        s *= illumdecay * WEIGHT;
        occ += s;
        illumdecay *= DECAY;
    }

    fragColor = vec4(vec3(0., 0., obj*.333)+occ*EXPOSURE,1.0);
}

```

That is in GLSL, but I am using DirectX 11. I've been able to port it across quite easily, but I feel like I have some knowledge gaps that are making it hard for me to get correct. For example, I don't understand the difference between `texture(iChannel0, uv).x` and `texture(iChannel0, uv).r` if someone wouldn't mind explaining ( I understand sampling the colour channels but xyz while sampling?). I also do not understand the channel resolution. Is it the dimensions of the 2D texture that I'm rendering to? Or perhaps the ratio of the texture?

Here is what I have come up with so far, just the bare minimum of changes to get it working:

```
SamplerState g_samSampler   : register( s0 );
Texture2D g_texInfo         : register( t0 );

#define DITHER
#define DECAY       0.974f
#define EXPOSURE    0.24f
#define SAMPLES     64
#define DENSITY     0.97f
#define WEIGHT      0.25f

struct PixelInput
{
    float4 vPosition : SV_POSITION;
    float2 vTexCoord : TEXCOORD0;
};

float4 PS( PixelInput input ) : SV_TARGET
{
    float2 uv = input.vTexCoord;

    float2 coord = uv;
    float2 lightpos = g_texInfo.Sample( g_samSampler, uv ).zw; //TAKE NOTE OF THIS LINE

    float occ = g_texInfo.Sample( g_samSampler, input.vTexCoord ).g; //light
    float obj = g_texInfo.Sample( g_samSampler, input.vTexCoord ).b; //objects
    float dither = g_texInfo.Sample( g_samSampler, uv/float2( 4.f, 3.f ) ).x;

    float2 dtc = (coord - lightpos) * (1.f / float(SAMPLES) * DENSITY);
    float illumdecay = 1.;

    for(int i=0; i<SAMPLES; i++)
    {
        coord -= dtc;

        #ifdef DITHER
            float s = g_texInfo.Sample( g_samSampler, coord+(dtc*dither) ).g;
        #else
            float s = g_texInfo.Sample( g_samSampler, input.vTexCoord ).g;
        #endif

        s *= illumdecay * WEIGHT;
        occ += s;
        illumdecay *= DECAY;
    }

    return float4(float3(0.f, 0.f, obj*.333f)+occ*EXPOSURE,1.f);
}

```

Please note that my green channel of the passed in texture `g_texInfo` stores the light texture (the white circle for the sun) and the blue channel stores the light occluders. I am doing this as a post processing effect on a screen quad. (Is this correct?) My suspicion is the line `float2 lightpos = g_texInfo.Sample( g_samSampler, uv ).zw;` is causing the trouble - I don't really understand this part - how can I find the position of the sun?

Here's what I'm receiving from my current shader, it appears that the light rays are being emitted in the wrong direction.

When I shift the camera so that the sun is in the top left, it gives the correct effect, it is also occluded properly when putting an object in the way.

# Answer
In GLSL (like HLSL), a vec4 (float4 in HLSL) has three different ways to access its four values. You can use (rgba), or (xyzw), or (stpq). They're all identical to each other; Asking for `vector.r` gets you the same value as `vector.x` or `vector.s`, so use whichever you prefer. (General best practices suggest using 'rgba' if it's a color, or 'xyzw' if it's a position in 3D/4D space, or 'stpq' if it's texture coordinates.. which amusingly we refer to as 'uv' coordinates even though you can't use either `u` or `v` to get the individual components from it. But do what makes you happy; they're all interchangeable!)

In the original code, you had this:

```
    vec2 lightpos = texture(iChannel0, uv).zw;

    float occ = texture(iChannel0, uv).x; //light
    float obj = texture(iChannel0, uv).y; //objects

```

The obvious issue I see with your port is that you have converted the above to:

```
    float2 lightpos = g_texInfo.Sample( g_samSampler, uv ).zw; //TAKE NOTE OF THIS LINE

    float occ = g_texInfo.Sample( g_samSampler, input.vTexCoord ).g; //light
    float obj = g_texInfo.Sample( g_samSampler, input.vTexCoord ).b; //objects

```

You've moved the channels around! 'zw' (which is equivalent to 'ba') is the same, but you've moved the 'x' ('r') channel to 'g', and the 'y' channel to 'b', re-using the channel you're otherwise using for the lightpos.

That's probably the source of your troubles. (along with the identical issue a few lines further down, when sampling light values inside the loop)

Regarding your other question, about `iChannelResolution`, that's a custom ShaderToy thing. It's a uniform variable which holds the width and height of a texture, in pixels. Here, it appears to be being used to grab the individual pixels of a texture that holds a dithering pattern. You can easily create your own version of that, but it isn't there for you by default in either GLSL or HLSL.

By contrast, `iResolution` (another custom ShaderToy thing) is the resolution of the destination image. By default, ShaderToy shaders receive a `fragCoord` input which tells them the coordinates of the pixel being rendered (measured in pixels). Dividing the fragCoord by iResolution gives you a \[0,0\]-\>\[1,1\] value which is useful for sampling from textures. Most ShaderToy shaders do that near the start of their code, and this one is no exception.
> 3 votes

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


# Question
Title: XInputDotNet not working when building for UWP in Unity
I am working on a game where a controller has to vibrate. I have found the XInputDotNet plugin which worked very well in the editor and a normal windows build, but if I build for UWP (both Xaml and D3D) the controller doesn't vibrate.

When building in unity for UWP it also gave me an error saying this:

```
Plugin 'XInputInterface.dll' is used from several locations:
Assets/Plugins/x86/XInputInterface.dll would be copied to
<PluginPath>/XInputInterface.dll
Assets/Plugins/XInputInterface.dll would be copied to
<PluginPath>/XInputInterface.dll
Plugin 'XInputDotNetPure.dll' is used from several locations:
 Assets/Plugins/x86/XInputDotNetPure.dll would be copied to
<PluginPath>/XInputDotNetPure.dll
 Assets/Plugins/x86_64/XInputDotNetPure.dll would be copied to
<PluginPath>/XInputDotNetPure.dll
Please fix plugin settings and try again.

UnityEditor.Modules.DefaultPluginImporterExtension:CheckFileCollisions(String)
UnityEditorInternal.PluginsHelper:CheckFileCollisions(BuildTarget) (at
C:/buildslave/unity/build/Editor/Mono/Plugins/PluginsHelper.cs:25)
UnityEditor.HostView:OnGUI()

```

The only way I found to remedy this is by deleting one of the plugin folders.

I tried manually copying the ddl's to the build folder, but this didn't help. I tried using the 32 bit dll's and the 64 bit dll's, I tried building for x86 and x64 and I tried all three modes in visual studio(Debug,Master,Release).

I found some links to the Windows.Gaming.Input namespace, but I dont't know if it is possible to add this namespace to unity and if so how.

Does anybody have an idea how to fix my problem?

# Answer
> 1 votes
Libraries for UWP must be compiled separately, they must be assigned to UWP only and configured correctly.

So I have ported XInputDotNet library for UWP apps.

You can download prebuilded binaries from Unity Forum by this link. Also there is an instruction how to use it.

Using ported library you can continue using same code for different platforms.

---
Tags: unity
---


title: Tile draws pixels from adjacent tiles

text:
# Question
Title: Tile draws pixels from adjacent tiles
Whenever I try to draw from the tile palette, this is the result. why does this happen? I have tried messing around with the palette, how the sprite editor has sliced the tiles and played around with the anchors and cell sizes, but to no avail. I found a few threads about offset tiles in the tile map, but it doesn't help at all. Any leads as to why this happens?

# Answer
Somehow fixed it by tweaking the Tilemap's anchor to X: 0.5, Y: 0.5. Unsure as to why, but it worked. Sprite resolution was 4000x2400 and pixel per unit 100. Slicing was centered to 100x100.
> 0 votes

---
Tags: unity, tilemap
---


title: Nvidia RTX ray tracing OpenGL extension

text:
# Question
Title: Nvidia RTX ray tracing OpenGL extension
I can't seem to find any OpenGL headers for the RTX ray tracing extension, seems like they only want you to use Vulkan and optix with RTX

# Answer
> 4 votes
Is your question whether or not OpenGL headers exist for the RTX extension?
It appears it can only be accessed through NVIDIA OptiX, DXR, and Vulkan.

From the website:

> Developers can access NVIDIA RTX ray tracing through the NVIDIA OptiX application programming interface, through Microsoft’s DirectX Raytracing API (DXR) and Vulkan.

# Answer
> -1 votes
There's an extension already, though I'm not sure how finished it is: **GLSL\_NV\_raytracing**.

---
Tags: opengl, raytracing, nvidia
---


# Question
Title: How to use motioncontroller thumbstick move (not press) to teleport motion controller pawn in UE4
To clarify the title: I'm using the built in VR blueprint, Oculus Touch controllers as my MotionControllers, and I'm trying to replicate the teleport style that RoboRecall uses (which should be possible given that RoboRecall was made in UE4 by EPIC themselves).

The blueprint does have a teleport feature built in, but it's activated by pressing the thumbsticks in (as in pressing the thumbstick down until you hear the button click), what I'm hoping to do is instead activate it on thumbstick push (as in just tilting and move the thumbstick around, but not clicking it down).

So I can actually get it half working by just changing the input in the `game settings > inputs` section, but when you release the stick it loses the rotation data (though it does actually move your charecter to the right xyz).

So it would seem that the first part (activating the teleport blueprint stuff) activates when the thumbstick is moved, it requires the thumbstick to fully return to centre in order to move the player, which by then has lost rotation. I'm new it UE4 and it might be a simple fix, so any pointers appreciated!

# Answer
I'm trying to do the same, I want a teleportation system that works like Robo Recall. Better yet, like the Oculus Home, which is almost identical, but Oculus Home is faster to open up when trying to figure out how it works, and I believe has some more functionality than Robo Recall.

I didn't go much farther than you on developing this system, but perhaps we can help each other; do you have a 360 or 180 degrees setup?

The way the teleport on Robo Recall and Oculus Home works is like this: it has a deadzone on thumbstick push for activating the gizmo, and a smaller deadzone on releasing the stick for the actual execution of the teleport. This way it allows you to teleport before the stick re-centers, keeping it's direction. The bigger deadzone on pushing the stick for showing the gizmo is also important so you don't teleport right away when pushing it.

So the gizmo display action shouldn't run right after the stick input action, but after the stick axis value is bigger than the deadzone1 and the teleport action shouldn't run on input release, it should be also on the action, but happen when the axis value is smaller than the deadzone2.

I managed to make it work. I used my gamepad stick and a print string just to debug, should work with the motion controllers too. Check this out:
> 2 votes

---
Tags: oculus
---


# Question
Title: Game artist computer workstation set-up – is this overkill?
I'm part of a small business (so very limited constraints) working with a very talented, professional game artist and will need to provide all necessary equipment. The artist has asked for the following setup (which to me seems super expensive):

* Latest graphics targeted high-end laptop with matching keyboard
* Large drawing tablet
* Ergonomic mount for the tablet
* Vertical ergonomic mouse

Do they really need all of this? Why?

# Answer
> 68 votes
First of all, saving on work equipment is often saving at the wrong end. Giving your employees suboptimal equipment does not just hamper their productivity physically, it also hampers their productivity psychologically because they do not feel valued.

But on the other hand, if you just ask your employees to pick out any equipment they want and don't give them a budget, then it is to be expected that you get a Christmas wish list with everything they ever dreamed of working with.

> what are some budget-friendly and reasonable substitutes for these?

Ask them. We do not know what your artist really needs. Maybe they are working with software and techniques which require that much equipment. Maybe not. "Game art" can mean anything from low-fi pixel art (which you can do on a 10 year old office PC) to cinema-quality pre-rendered 3d movies (which might require a million dollar render farm in the basement).

So asking them "Do you really need all that stuff or could you do with less?" Or "We got a buget for your equipment of $xxxx, would it be possible to stay within that range?" can't hurt. But if the answer is "no, I really need all that stuff", then you should trust their judgment. They know best what equipment they need to give you their peak performance. If you don't provide them with the tools they need to give you their best work, then you can't expect to get their best work.

# Answer
> 30 votes
Laptop is a waste of money, everything else is acceptable.

Ergonomic mouse and mount for tablet is a must. If he is going to be drawing for 8 hours a day, he will need it for health reasons.

Large drawing tablet is also acceptable. It's easier to work with a large canvas.

In regards to the laptop? Why? High end laptops are 4 times the cost of a high end desktop. Explain this to him and show a cost comparison.

As others have said, employees need to be able to work at their best, but at the same time they need to understand the realities of the business budget. Ask the artist to draft a cost comparison between the cheapest and most expensive items he wants. Once he returns the comparison, draft a budget and then return both to the the artist and let him choose where he wants to allocate his resources.

# Answer
> 4 votes
When making graphics you, usually, want to be able to layer a lot of assets. The more you can layer the richer the image is likely going to be and the more exciting it usually is.

How much power one needs depends *a lot* on style, user and art direction. However, I would like to point out that you do not want your artist to be hardware constrained under any circumstances. At the end of the day, your artist easily costs you more money than your hardware. If your artist is sipping coffee all day waiting for his tools to respond, then it's not money well spent. You are literally "saving" money from productivity, which actually even more costly.

Now artists, usually really need screen estate. So having a big screen or 2 is actually a productivity increase. Personally, I wouldn't supply artists with laptops, because big power laptops are not really portable. So any benefit you'd get from a laptop is lost. I would supply them with a good ergonomic desk and monitors though. And a separate laptop if they need to work from outside the office.

A tablet is a highly personal thing. Some need it others don't . Ask what tablet the artist is using now for his art. This lets you gauge whether or not they actually use a tablet at all or just thinks he needs one. Only an artist that is currently working on a tablet needs one. Acclimatizing to using one is a very slow process so unless artist already has a tablet workflow i would not get one. This said you should still have a tablet for those that do and for ones that need to transition due to workload.

At the end of the day you need to trust your artist. That also means trusting what they request is a really needed. You can negotiate cheaper or let them spend the budget. Just remember at the end of the day art is expensive.

# Answer
> 2 votes
The additional cost of the mouse is unlikely to be significant compared to the drawbacks of having one with poor ergonomics. That, and the tablet stand, are definitely not worth questioning unless they are *crazy* expensive (at least $300 each with obviously comparable models available for significantly less money). The tablet is in much the same boat; depending on what sort of "art" we're talking about¹, this is likely the single most critical tool your artist will be using (note: I have some experience here).

Depending on the artist, they may or may not want some form of tablet/screen combination. Even though that could get quite pricey, my inclination would still be to go with whatever they are most comfortable using. (The flip side is if they're just trying to leverage you to get "shiny hardware". You could guard against this by asking if they have prior experience with the hardware they are asking for, or, as others have suggested, just give them a budget and ask if it's possible for them to work with that. BTW, this is basically how my own employer works; we get so much $$ to buy hardware and can more or less spend it however we think is most appropriate.)

(¹ Painting of *any sort* is best done with a tablet. Someone doing level design might not need a tablet, and a modeler may or may not, depending if they also do texturing or if the "modeling" involves "sculpting"/"3D painting". However, *any* sort of raster graphics is likely to benefit from a good tablet, and if they're doing something whose analog equivalent would involve hand-held tools, a tablet is almost certainly going to be worth it.)

As noted... the real question should be about the laptop. If they don't need portability, a desktop is going to be a better value. That said, depending on what they're doing, art work is pretty good at hogging resources, so it's not unreasonable to want a respectable system.

---
Tags: art, business
---


# Question
Title: Unity WebGL player just shows black screen
I built my Unity project with WebGL. After load the resources, I can hear the music and player sounds(movements etc), but it just display black screen only. I found some similar situation in google, but couldn't find the way to fix.

Here's the console result: https://drive.google.com/open?id=14Uhd6SBbDHdPN39TurY9H7QPGhPLfb\_X

Used Unity 2018.2.1f1, tested with Chrome 73.0.3683.86.

# Answer
> 0 votes
Try with 2017.x works fine. Might be issue of 2018.x or higher.

# Answer
> 0 votes
It says "Missing shader in Camera (FXAA)" So guessing you have some issues with your anti aliasing post processing.

Look at "Anti-Aliasing" and "WebGL 2.0 support" in https://docs.unity3d.com/Manual/webgl-graphics.html

Or maybe try to verify that the post processes you have setup on the camera are not missing: https://forum.unity.com/threads/missing-shader-in-main-camera-error.113929/

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


# Question
Title: Physics.IgnoreCollision not working right after invoked
When invoking Physics.IgnoreCollision in Unity, it seems work but it still have collision detection right after creation.

I have this issue with ejecting empty case after gun fire, it's spawning position located inside of character controller(collider), so when ejecting case created, it immediately hit to my character controller and makes my character slows.

First I thought that it's coming from something else, but it's not, because when I just not spawning the empty case, it never happens.

This is the code:

```
GameObject ejectedCase = Instantiate(emptyCasePrefab, caseSpawnPoint.position, caseSpawnPoint.rotation);

Collider caseCollider = ejectedCase.GetComponent<Collider>();
Physics.IgnoreCollision(caseCollider, playerCollider);

```

Note that playerCollider is Collider. I also tried with CharacterController(because it's extended from Collider class) but result was same.

Why I said something like "it's not working right after invoked" because it's actually working after passed some time. If it's not work, character controller step on the empty case and makes camera jittering issue on vertical axis. This is totally gone after ignoring collision detection with above code, however it still works right after creation and makes my character really slow.

How do I avoid this weird glitch, makes IgnoreCollision works right after it invokes?

In addition: I don't want to fix this issue with using Layer Collision Matrix. I didn't tried but it will work sure, however I don't want to spend Layer for this purpose only, because it's number is limited and already using lots of layers in other logics so it makes game logic more complicated if I use Layer to avoid collision detection. I want to know why "Physics.IgnoreCollision" not works because literally it saids "ignore collision" but it wasn't.

# Answer
This problem was fix by attaching collider to parent, not a child. Colliders in child keep trigger this problem even I access the child's collider.
> 0 votes

---
Tags: unity, collision-detection, physics, collider
---


title: FXAA Shader turns image upside-down

text:
# Question
Title: FXAA Shader turns image upside-down
I'm trying to use an existing FXAA shader for anti-aliasing, which works, but when I try to run it, the filtered image is upside-down (vertically flipped)

```
[Vertex_Shader]
varying vec4 posPos;
uniform float FXAA_SUBPIX_SHIFT = 1.0/4.0;
uniform float rt_w; // GeeXLab built-in
uniform float rt_h; // GeeXLab built-in

void main(void)
{
  gl_Position = ftransform();
  gl_TexCoord[0] = gl_MultiTexCoord0;
  vec2 rcpFrame = vec2(1.0/rt_w, 1.0/rt_h);
  posPos.xy = gl_MultiTexCoord0.xy;
  posPos.zw = gl_MultiTexCoord0.xy -
                  (rcpFrame * (0.5 + FXAA_SUBPIX_SHIFT));
}

[Pixel_Shader]
#version 120
uniform sampler2D tex0; // 0
uniform float vx_offset;
uniform float rt_w; // GeeXLab built-in
uniform float rt_h; // GeeXLab built-in
uniform float FXAA_SPAN_MAX = 8.0;
uniform float FXAA_REDUCE_MUL = 1.0/8.0;
varying vec4 posPos;

#define FxaaInt2 ivec2
#define FxaaFloat2 vec2
#define FxaaTexLod0(t, p) texture2DLod(t, p, 0.0)
#define FxaaTexOff(t, p, o, r) texture2DLodOffset(t, p, 0.0, o)

vec3 FxaaPixelShader(
  vec4 posPos, // Output of FxaaVertexShader interpolated across screen.
  sampler2D tex, // Input texture.
  vec2 rcpFrame) // Constant {1.0/frameWidth, 1.0/frameHeight}.
{
/*---------------------------------------------------------*/
    #define FXAA_REDUCE_MIN   (1.0/128.0)
    //#define FXAA_REDUCE_MUL   (1.0/8.0)
    //#define FXAA_SPAN_MAX     8.0
/*---------------------------------------------------------*/
    vec3 rgbNW = FxaaTexLod0(tex, posPos.zw).xyz;
    vec3 rgbNE = FxaaTexOff(tex, posPos.zw, FxaaInt2(1,0), rcpFrame.xy).xyz;
    vec3 rgbSW = FxaaTexOff(tex, posPos.zw, FxaaInt2(0,1), rcpFrame.xy).xyz;
    vec3 rgbSE = FxaaTexOff(tex, posPos.zw, FxaaInt2(1,1), rcpFrame.xy).xyz;
    vec3 rgbM  = FxaaTexLod0(tex, posPos.xy).xyz;
/*---------------------------------------------------------*/
    vec3 luma = vec3(0.299, 0.587, 0.114);
    float lumaNW = dot(rgbNW, luma);
    float lumaNE = dot(rgbNE, luma);
    float lumaSW = dot(rgbSW, luma);
    float lumaSE = dot(rgbSE, luma);
    float lumaM  = dot(rgbM,  luma);
/*---------------------------------------------------------*/
    float lumaMin = min(lumaM, min(min(lumaNW, lumaNE), min(lumaSW, lumaSE)));
    float lumaMax = max(lumaM, max(max(lumaNW, lumaNE), max(lumaSW, lumaSE)));
/*---------------------------------------------------------*/
    vec2 dir;
    dir.x = -((lumaNW + lumaNE) - (lumaSW + lumaSE));
    dir.y =  ((lumaNW + lumaSW) - (lumaNE + lumaSE));
/*---------------------------------------------------------*/
    float dirReduce = max(
        (lumaNW + lumaNE + lumaSW + lumaSE) * (0.25 * FXAA_REDUCE_MUL),
        FXAA_REDUCE_MIN);
    float rcpDirMin = 1.0/(min(abs(dir.x), abs(dir.y)) + dirReduce);
    dir = min(FxaaFloat2( FXAA_SPAN_MAX,  FXAA_SPAN_MAX),
          max(FxaaFloat2(-FXAA_SPAN_MAX, -FXAA_SPAN_MAX),
          dir * rcpDirMin)) * rcpFrame.xy;
/*--------------------------------------------------------*/
    vec3 rgbA = (1.0/2.0) * (
        FxaaTexLod0(tex, posPos.xy + dir * (1.0/3.0 - 0.5)).xyz +
        FxaaTexLod0(tex, posPos.xy + dir * (2.0/3.0 - 0.5)).xyz);
    vec3 rgbB = rgbA * (1.0/2.0) + (1.0/4.0) * (
        FxaaTexLod0(tex, posPos.xy + dir * (0.0/3.0 - 0.5)).xyz +
        FxaaTexLod0(tex, posPos.xy + dir * (3.0/3.0 - 0.5)).xyz);
    float lumaB = dot(rgbB, luma);
    if((lumaB < lumaMin) || (lumaB > lumaMax)) return rgbA;
    return rgbB; }

vec4 PostFX(sampler2D tex, vec2 uv, float time)
{
  vec4 c = vec4(0.0);
  vec2 rcpFrame = vec2(1.0/rt_w, 1.0/rt_h);
  c.rgb = FxaaPixelShader(posPos, tex, rcpFrame);
  //c.rgb = 1.0 - texture2D(tex, posPos.xy).rgb;
  c.a = 1.0;
  return c;
}

void main()
{
  vec2 uv = gl_TexCoord[0].st;
  gl_FragColor = PostFX(tex0, uv, 0.0);
}

```

I'm still new to shaders - how can I modify this shader so the filtered image is displayed the correct way up?

# Answer
> -1 votes
```
gl_FragColor = PostFX(tex0, vec2(uv.x, 1.0 - uv.y), 0.0);

```

---
Tags: opengl, 3d, glsl, antialiasing
---


title: Money Every Minute System?

text:
# Question
Title: Money Every Minute System?
I'm making a 2D sandbox tycoon in UE4. I haven't started the money system yet, but I was wondering how I could make a money system that gives you a certain amount of money per real-life minute. Then, I want to connect this system up to some text so that the digits go up by whatever amount each minute.

# Answer
> 3 votes
If you only want to do this while the game is running you can use the timers the engine provides.

Here is an example from the docs.

Brief summary (Current UE Version 4.22):

* Create a method which should be called after the timer ends (e.g. rewardCallback)
* Add a Blueprint node called 'Set Timer by Function Name'
* Set the function name in the blueprint node to be the name of the method created in the first step (i.e. rewardCallback)
* Adjust the other parameters to your needs
* Make sure the node gets called at least once (or more often if you don't loop the execution of it)

---

If you want to extend it such that offline time also gets taken into account then you might want to simulate the time the player was away.

E.g. In an extremely simple case:

```
Delta_away = time_now - last_logoff_time //in minutes since 1970
Reward_away = reward_per_minute * Delta_away

```

# Answer
> 0 votes
Unreal offers several built in timers and, depending on your needs, I'd suggest either GetTimeSeconds and GetRealTimeSeconds. Both do the same job but GetTimeSeconds gets paused when the game is paused whereas GetRealTimeSeconds does not.

Unreal Links:
GetTimeSeconds
GetRealWorldSeconds

You'll need to set up two more variables. One to compare the time since money was last added (reset every 60 seconds or however often you want more money added) and a value for the total money.

HUD's are hard to explain in writing so I'd suggest finding a YouTube (or similar) video but essentially, create a HUD Blueprint (found in Add Blueprint-\>User Interface-\>Widget Blueprint) and add a Text (or Text Block) to your creation. In the details tab, where you enter what text you want, you'll see a button labelled "Bind". Click this and select "Create Binding".

Inside the binding, you now need to CAST to wherever you set the money variable and hook the output node up to the money variable. Unreal should convert it to Text automatically but you might need to do this yourself.

---
Tags: unreal-4
---


# Question
Title: Algorithm for finding edge vertex points on a tilemap
I have a 2d tilemap array contains 1 or 0. 0 corresponds empty tile, 1 corresponds solid tile. If tile is 1 I draw a texture.

I have to find edge vertices and coordinates that 1's grouped.

I couldn't find a way to implement this algorithm. Is there a algorithm or approach I could use?

Red dots are the vertices I want their coordinates.

# Answer
> 0 votes
I solved problem with implementing using wall following algorithm. First find a starting point which is 0 in tilemap and it has to have only one adjacent tile as 1. After finding starting point I implemented a direction system. In my case it is following left hand wall(1 in tilemap). But whenever you turn left the front tile changes. This is the tricky point.

---
Tags: mathematics, algorithm, tilemap, tiles
---


# Question
Title: Timed Events in a Unity WebGL game with a PHP / MySQL Server
I want to make an online WebGL game with Unity with button based interaction.

So far I have my login and registration system, with some tables in MySQL to deal with that kind of stuff.

Next I need to deal with timed events.

In the game, you will start a mission just by pressing a button then you will wait a bit, like ten minutes.

How can I implement this wait?

Should I write a waiting routine in PHP, or use MySQL scheduled events? If using events, how many scheduled events can MySQL handle? Or should I use another server-side solution for that?

# Answer
> 0 votes
Unless you want your server to initiate some immediately-observable action at the end of the 10 minute wait while the player is offline, then there's no reason to track the timer on the server side at all.

Instead, just save a timestamp of when the button was pressed.

If the game later tries to perform an action that they're not supposed to be able to do while waiting (eg. collecting mission rewards early, or pressing the button a second time), first check the current time versus the last-pressed timestamp, and abort if the attempt is too early.

Now any realtime timer-tracking can be done in your Unity game. When you press the button, start a timer in your client-side script. When that timer completes, you know it's time to update the game state or call the server to ask for the result of the action.

If the player closes the game/browser while the timer is running, no problem: on start-up, just ask the server for any outstanding actions. It can report back the time left on any timers, or any actions that completed while you were away, and you can update the in-game state accordingly.

This helps your game scale better to large numbers of users, because your server is only ever storing/comparing/reporting data on request — it doesn't need to do any continuous background processing for every active player.

The exception is if the game action needs to trigger a result that's observable without the player running your game — like sending a push notification to their phone, or modifying the state of someone else's game who might be online now. So, to ensure your game can scale to large numbers of players, ensure you limit your use of features like this, or find ways you can process them in batches so you don't have to run independent simulations for everyone.

---
Tags: unity, timer, php, mysql
---


# Question
Title: How to load game resources correctly regardless of the working directory?
I am writing a resource manager for a hobby game project that reads textures/fonts etc.

Up to now, I was giving the location of the files relative to the executable path, like:

```
my_texture.loadFromFile("textures\\my_texture.png");

```

However, now I realized that the relative path I'm giving is relative to the working directory of the game. So, for example, if I run the executable from my IDE (which sets the working directory to the project directory instead of executable directory), the game fails to load the texture and crashes.

I was thinking about using the main's `argv[0]` and did some research on it, but apparently it is not reliable (it might just give the name of the exe).

So, how can I get the path to my resource files reliably? How does the professionals do it?

I'm using the SFML and C++17. I would like a portable solution if possible, otherwise Windows.

I checked this question but it wasn't helpful.

# Answer
> 3 votes
Give the resource management API an understanding of what the input paths are relative *to*. Depending on your underlying OS, there are a variety of ways to get the full path to the running executable, independent of working directory. On Windows, for example, one function you could use for this is `GetModuleFileNameA`.

Once you've got that full path and trimmed the executable name from it (if needed), you can store it someplace and append you relative resource paths to it every time you are about to load. This gives you an absolute path to the resource.

SFML may have a portable wrapper equivalent to `GetModuleFileNameA`, although I'm not sure what it is offhand and a very quick search through the API reference didn't reveal anything.

---
Tags: c++, sfml, assets
---


# Question
Title: Is BDD (Behavior Driven Development) used in games?
I have been reading about BDD - Behavior Driven Development for a while, and I find it really easy and usefull to convert features into code. BDD users often call it TDD done right.

BDD is a tool for software design, from outside to inside, from the bussiness value (or gameplay value) to code.

Dan North introducing BDD

Do you know any resources about BDD and Games other than this?

# Answer
It's probably safe to say that BDD, like TDD, or (insert trendy development buzzword-paradigm here) is used by some game developers somewhere, but they probably don't know they are nor would they neccessarily be able to identify what BDD actually means. The question is really *how much* they use it and how much do they *have* to use it for it to matter to you?

For example, where I work, all our unit test names are "sentences" like Dan North suggests in that article you linked. That alone isn't sufficient to say that we use BDD, of course, but maybe it's what you really care about?

The focus, in my opinion, should not be on which buzzword you apply at a studio, but rather which productivity and development process techniques you employ overall. I find that the most productive teams are mixing and matching techniques from a variety of "buzzword-paradigms" rather than committing, dogmatically, to every bit of rigid doctrine some internet study says comprises one particular buzzword-paradigm.

I see this most often with the Agile trend: teams that identify themselves as "doing Agile" tend to be more inflexible (ironically) about the process than teams that are organically incorporating the bits of Agile that make sense for them. The former teams almost always end up being less productive, in my experience.

A development team is made up of humans, who are not interchangeable cogs in a machine. They operate uniquely as individuals and as the unique combination of themselves. The way to effective development is not to bend your humans into the {BDD, Agile, WhateverIsNext} mold but to be constantly re-assessing how the team is progressing and shoring up deficiences in the process, replacing broken techqniues, and reinforcing things that are working. In short, to focus on shipping a title and not on "being Agile (or whatever)."
> 14 votes

# Answer
I think BDD is appropriate in every in environment. As others mentioned you are developing software and as a result you should test it. I do like bdd for some of the random semantics mentioned like test names as sentences. I also like grouping certain tests together while still being able to test 1 class.

To combat other messages here I'd like to point out that on a larger project it is MUCH harder to refactor code without tests. If you refactor some code you are flying blind as to whether everything will explode in a blaze of glory or not. The tests help you catch things early. So you write your test, fail, code just enough to pass and continue. When you refactor you should do the same thing, but rather than write you revise the test. In most cases you run the test it will fail, you go change what you think should change and it STILL fails. At which point you realize that some other piece of code relies on this function/method a completely different way. You can then fix your test and the resulting code. Without that sort of code coverage you'd be stumbling around for days trying to find where stuff is broken, bugs are not easy to find or track, and moreover you REALLY can't refactor code and you start fearing your code base.

Go read about "Contracts" in the Pragmatic Progammer's book. Testing helps you achieve code contracts. This code does X and nothing more than X and don't expect it to do anything about Y or try to adapt it to do Z. It ensures code cleanliness and expects everyone to not be a dick and muddy up the code base.

There are more reasons to BDD. The main one for me is that I would do the same amount of testing to validate my assumptions anyways so I might as well formalize it.

On the point of "how" it really depends on your environment. I am writing a java game now and using robolectric. You should always attempt to "expect" something. I've heard that spies/mocks/stubs are not as useful since you need to have equivalent on the other side, but sometimes you have no choice especially with APIs. You can assume that the other side of the API is not terrible though and it is usually your code that sucks.

If for example you are testing movement. Well you expect when "Up" is pressed that the user moves forward by some measurement.

If for example you are testing graphics rendering... well don't test that too much because are you really doing that? A good test framework might handle this part for you. Reflection is not super trivial I'd say for these sorts of things. You may need to check buffers etc etc. I'd simply just check for what you are actually doing. Character is here, now he is there after some action.

You should have plenty of tiny little functions/tests and together they will sum up to something useful.
> 2 votes

# Answer
Is it? Maybe. My opinion would be that it would make for a very poor fit for entertainment software generally, although it might work well for the low level libraries.

EDIT: Here's some justification for my opinion.

Wikipedia defines BDD as a technique that *"encourages collaboration between developers, QA and non-technical or business participants in a software project."* This already sounds like a bad idea because games differ from most software in that they are not designed as tools to meet a specific need for a 'non-technical or business participant', but are cohesive works broadly designed to entertain. There is an emphasis on "desired software behaviour" but games rarely have 'desired software behaviour' except at the technical level. There is definitely merit in checking that part of the code, but not with the end user, because they will never see it.

But let's assume that you want to throw out that human stakeholder stuff and just use BDD to enforce contracts between different code modules, which as far as I can see doesn't differ much from normal test-driven development, which I also consider poorly-suited to games, for the following reason.

Tests are useful for checking that discrete events happened when expected. This works well in event-driven programming, ie. most of the software world, where an action is performed, some output is generated, and then you just verify that the action and the result match up. However, game software is typically a simulation, where an action does not have a discrete result but a continuous change in the world state. If my hidden player makes a noise, I might want to check that the AI hunts me down. So, I can create a test to make sure that the AI is in 'hunting' state after a noise is created, and that's great. But how do I know the hunting even works? You can't check that instantly - you can only observe it over the passage of time. You can hack in various tests to test certain aspects but this is not well-suited to a typical testing approach.

Additionally, a test-first approach can create a false sense of security, and lead people to believe code is better than it really is.

```
def check_dice_roll_in_range():
    d = new Dice()
    assert(d.roll() between 1 and 6)

class Dice:
    def roll():
        return 4

```

Since a test result can give a false positive, you can never escape the basic need to check the code itself. But if the code itself is checked adequately, the test takes on secondary importance. This is why, in my opinion, tests are best used after the event, to test bug fixes.

I wouldn't argue that there's never any benefit in testing that, when objects X and Y work together, the result you get is as expected. The issue is whether you are using the most effective way of verifying this. Methods could include formal verification, a code review, test-first methods, test-last methods, traditional QA black-box testing, or simply using the code as expected and observing the results. The last two options are surprisingly effective most of the time, because despite sounding like they lack rigour, most bugs are found during the course of typical use, and understanding a bug in its natural context can sometimes be easier than understanding it in an artificial test harness. On top of this, formal testing and verification often fails to find problems because (by definition) you can only test for the scenarios you expect - and it's not the expected scenarios that are typically the cause of poor software quality.

So, in summary, I think that test driven development is not necessarily a great choice for software, that tests alone are never sufficient to ensure software quality (and thus the time spent writing them must be compared against alternative uses of that developer time), that games are an especially poor match for automated test cases, and that games are an especially poor match for development methods that look to emphasis 'business value' and 'acceptance testing'.

(Hopefully that is a better answer, even if you don't agree with my points.)
> 1 votes

# Answer
I feel there's a misconception about what BDD is. BDD is not a TESTING technique or process. BDD is a development model and process. It goes WAY beyond testing and it goes way beyond programming.

As such, I don't know of any major AAA studio working with this model (I have friends working for some of them around the world as programmers). As someone else pointed out, it may be that some project manager or team somewhere incorporates some of the practices BDD encompass, but I don't know of any studio applying pure-BDD (from business value definition, to specification by example, to writing feature files, to validating them with stockholders, to automating the feature files as tests).
> 0 votes

---
Tags: testing, methodology, behavior, test-driven-development
---


# Question
Title: Unity Animation Curve to change value over time
I am trying to learn how to use AnimationCurve to change a float value over time.

However i am not really sure how to do it

Say i have the following class:

```
    public class SpiritAway : MonoBehaviour
{
    public List<SkinnedMeshRenderer> MeshList;
    public List<Material> DissolveList;
    public float percentage = 0.0f;
    public bool IsDissolveing;
    public AnimationCurve Curve;

    private void Start()
    {
        percentage = 0.0f;
        for (int i = 0; i < MeshList.Count; i++)
        {
            for (int j = 0; j < MeshList[i].materials.Length; j++)
            {
                if (MeshList[i].materials[j].shader.name == "Dissolve")
                {
                    DissolveList.Add(MeshList[i].materials[j]);
                }
            }
        }
    }

    // Update is called once per frame
    void Update()
    {
        if (IsDissolveing)
        {
            if (percentage < 1)
            {
                    percentage += 0.01f;
                    for (int i = 0; i < DissolveList.Count; i++)
                    {
                        DissolveList[i].SetFloat("_alphaClipDissolve", percentage);
                    }
            }
        }
    }

```

Now i wish to incrase the percentage value with the percentage of the animation curve to get a more smooth and controlled transition of the value.

Could anyone explain how this is possible?

# Answer
> 0 votes
It looks to me like you can replace this with:

```
public float speed = 1f/30f;
public Renderer[] renderers;
public AnimationCurve curve;

struct MaterialSlot {
    public readonly Renderer renderer;
    public readonly int index;

    public MaterialSlot(Renderer renderer, int index) {
        this.renderer = renderer;
        this.index = index;
    }
}

private IEnumerator Start()
{
    // Define a material property block for modifying alpha
    // without copying materials (lighter on allocations/garbage).
    var properties = new MaterialPropertyBlock();

    // Cache an ID for our parameter, to avoid lots of string lookups.
    int id = Shader.PropertyToIndex("_alphaClipDissolve");

    float perecentage = 0f;

    // Read our alpha value from this position on the curve
    // and apply it to our property block.
    properties.SetFloat(id, curve.Evaluate(percentage));

    // Find all materials that need this alpha adjusted, and cache them.
    var slots = new List<MaterialSlot>();
    foreach(var renderer in renderers) {

        // Look at the renderer's materials without copying them.
        var materials = renderer.sharedMaterials;

        for(int i = 0; i < materials.Length; i++) {
            if(materials[i].shader.name == "Dissolve") {
                // Initialize the alpha value for this material.
                renderer.SetPropertyBlock(properties, i);

                // Cache a reference to its slot so we can iterate it later.
                var slot = new MaterialSlot(renderer, i);
                slots.Add(slot);
            }
        }
    }

    // Keep updating the alpha on subsequent frames until we're done.
    while(percentage < 1f) {
        // Wait a frame, then resume.
        yield return null;

        // Advance the animation at a fixed rate over time.
        percentage += Time.deltaTime * speed;

        // Read our alpha value from this position on the curve
        // and apply it to our property block.
        properties.SetFloat(id, curve.Evaluate(percentage));

        // Apply this modified property block to every "Dissolve" material slot.
        foreach(var slot in slots) {
            slot.renderer.SetPropertyBlock(properties, slot.index);
        }
    }

    // percent >= 1f, we're done! End this coroutine.
}

```

---
Tags: unity, curves
---


# Question
Title: Should damage calculation in a competitive multiplayer game be done client-sided or server-sided?
I'm interested in creating a moba style game like League of Legends and need help with a situation. More exactly: I have an item that gives the player 50 Attack Damage or an ability that does 50 Attack Damage. Is the information about how much damage the items/ champion abilities do kept in client side of the game or the server.

Option 1: I hit the enemy and the client tells the server to deduct 50HP from the enemy i hit
or
Option 2: I hit the enemy and the client tells the server only that I hit the enemy, then the server looks at the item I have/ ability used and based on code on the serves side deducts the 50HP

# Answer
Rule number one for multiplayer netcode design: Anything that matters for gameplay should be calculated server-sided. Never trust the client. The client is in the hands of the enemy. You can not efficiently prevent players from modifying their game client to gain an advantage.

The only reasons why you would do damage calculation on the client are:

* Your game is completely deterministic, so cheating can be detected by the other clients (but this usually only applies to turn-based games - with real-time games, the network latency alone will introduce a certain degree of randomness which makes remote cheat detection difficult)
* You do it both server-sided and client-sided so you can show the player the results the server is very likely going to conclude as well without latency (but the server-sided results count when there is a disagreement).
* You don't care about cheaters ruining your game and consider it more important to minimize your server cost.
> 12 votes

# Answer
Option 3: The client sends a click event to the server, the server decides where this click event has landed, decides if there is a hit or a miss, then applies the damage and sends the updated world state back to the client.

Don't even trust the client to tell if there is a hit or a miss.
> 11 votes

# Answer
It depends on what security level you want to implement. The games you mentioned surely have all that code on the server side to make the game more secure against hackers. Because now the hackers have to attack the server, which are highly guarded against attacks instead of hacking the client, which would be much easier.
> 2 votes

# Answer
## Calculate everything on the server

That is: you tell the server where you want to move and who you want to attack (if abilities are targeted, as many are with MOBAs) or in which direction (if the ability is aimed directionally, like in most first-person shooters on PC). The server will then calculate whether your move is valid (i.e. it's actually possible to move that far) and whether your attack hits, how much damage is done (including critical hits) and whether anything else needs to happen (e.g. an attack could freeze the target or push them away).

Why?

* **Cheating**

People might try to cheat by telling the server they're doing a lot more damage than possible. The server keeping track of this information is required to prevent this.
* **Multiple clients doing their own calculations would be messy**

Let's say I try to attack you, but I have latency of a few seconds. You moved out of range a while ago, but I still see you next to me, so that attack would be valid from my point of view.

Now I tell the server to subtract some of your health. Now what? Should the server do that and suddenly you take a bunch of damage despite no-one being around you any more? Or should the server realise the attack isn't valid any more and send back to me that you suddenly regain the health I already subtracted? Neither option would be a good user experience (you shouldn't be playing with that much lag, but lag spikes happen, and the problem also exists with lower latency).

The above applies to whether or not you hit, but a similar problem happens with regard to how much damage is done: We're attacking each other and I see you lose all your health while I still have a bunch. So I won that fight, right? But you, on the other hand, see the same (due to the update delay between us, and each of us only know about the damage we're dealing). So you also won? There isn't a good way to resolve that either.

---

**Footnote regarding calculating on both the client and server:**

In some cases in these games, some calculations happen on the client as well as the server, to reduce lag (so the client can update without waiting for the server). The states would then be synchronised between the two (which sometimes results in "desync", where you jump backwards to where you were a few seconds ago - you may have seen this in one of many popular games).

For your own movement, this could make sense, as you know where you're currently busy moving and there isn't (much) probabilities involved in how that happens. It would only a big problem when there's a significant delay, which is assumed to be an exception rather than the norm, and the alternative would having a very irritating delay on every single move you make (even if your latency is fairly low).

Damage, on the other hand, needs to consider where the target is, whether they're still alive, whether you actually hit them (if I generate a number, or roll some dice, which says I hit and the server does the same to determine that I miss, there is a problem), or did a "critical hit" , any modifiers that might be affecting how much damage is done and possibly other factors. If you try to do the calculation on both the client and server, health counters would constantly jump up and down when the client guesses some of these things wrong, which would arguably be a much worse experience than just having the damage take a little while to show up on the target.

That's not to say it's completely nonviable to do the calculation on both in some scenarios, it's just quite a bit harder in a lot of cases than doing the same for movement (which is already nontrivial).
> 2 votes

# Answer
Option 4: Send the individual input events to the server to let it make **authoritative** decisions, but also process and display those actions locally so the local user doesn't see any lag. Both client and server messages about this stuff need time stamps, mostly so the client can fudge things to make it look smoother.

(it turns out this is just a combination of things others have already mentioned... bah!)

The client and server code should be shared to the degree possible. Any time the client and server come to different decisions, it should be due to lag, not code.
> 2 votes

---
Tags: networking, rts
---