# Question
Title: Input.GetAxis Vertical - Unity - can i force it to zero upon certain circumstances/event?
I am trying to make my own tetris clone. I have actually got very far into it without running into major problems, but I am now stuck and can't find the answer after searching.

Basically I have used Input.GetAxis("Vertical") so that when player is holding down on controls the piece drops rapidly (else it goes back to normal drop speed). It all works great but in my memory of Tetris after the block is frozen at the bottom, even when the player is holding down on controls it still doesn't make the new block move fast until they let go of the down key and then press it again.

I have some ideas on how to do it, but i think i might have to delete much of my code and to be honest, I'm scared of breaking it. I am kinda hoping there is some nice elegant solution that I just don't know about yet.

I am posting the code now in case you'd like to look through it all. Its all in one big messy file, but I actually felt maybe making more class files would be unnecessary (perhaps when I am finished I will attempt to encapsulate it all properly and section it into logical classes as another exercise for myself):

```
using UnityEngine;
using System.Collections.Generic;

public class GameBoard : MonoBehaviour
{
const ushort CELL_COUNT_X = 10;
const ushort CELL_COUNT_Y = 24;
const ushort CELL_SIZE = 1;

GameObject brick;
List<GameObject> bricks = new List<GameObject>();
private Sprite brickSprite;
private Sprite wallSprite;
GameObject[] debugWallBricks = new GameObject[CELL_COUNT_X * CELL_COUNT_Y];
TetrisPiece fallingPiece;
const ushort BLOCKTYPE_COUNT = 7;

const short DEFAULT_POSITION_X = CELL_COUNT_X / 2 - 2;
const short DEFAULT_POSITION_Y = CELL_COUNT_Y - 4;

//bool[,] frozenCells = new bool[CELL_COUNT_X, CELL_COUNT_Y]; // ill use this to store record of all fixed/settled blocks no longer falling
FrozenPiece[,] frozenCells = new FrozenPiece[CELL_COUNT_X, CELL_COUNT_Y];
List<GameObject> frozenCellBricks = new List<GameObject>();

float dropTimer = 0f;
float dropTimerBaseSpeed = 1f;
float dropTimerSuperSpeed = 15f;
float dropDelay = 0.7f;
float moveTimer = 0f;
float moveToDropSpeedFactor = 5f;
float moveDelay; // this value depends on what value the dropDelay is and is set in Update
float rotTimer = 0f;
float rotDelay = 0.15f;

private void Start()
{
    brickSprite = Resources.Load<Sprite>("Tex/tetris_brick");
    wallSprite = Resources.Load<Sprite>("Tex/border_rounded");

    CreateDebugWall();
    MakeNewFallingPiece();

    for (int y = 0; y < frozenCells.GetLength(1); y++)
    {
        for (int x = 0; x < frozenCells.GetLength(0); x++)
        {
            FrozenPiece f = new FrozenPiece(Color.grey, false);
            f.isFilled = false;
            frozenCells[x,y] = f;
        }
    }
}

// i clear the visual board every frame and re-create a new brick, spriterenderer etc every frame (probably a shit way !) todo
void ClearBoard()
{
    foreach (GameObject go in bricks)
        Destroy(go);
    foreach (GameObject go in frozenCellBricks)
        Destroy(go);

}

void CreateDebugWall()
{
    int i = 0;
    for (int x = 0; x < CELL_COUNT_X; x++)
    {
        for (int y = 0; y < CELL_COUNT_Y; y++)
        {
            brick = new GameObject();
            brick.name = "Debug_Wall_Brick";
            brick.AddComponent<SpriteRenderer>();
            brick.GetComponent<SpriteRenderer>().sprite = wallSprite;
            brick.transform.position = new Vector2(x * CELL_SIZE, y * CELL_SIZE);
            brick.GetComponent<SpriteRenderer>().color = Color.grey;
            debugWallBricks[i] = brick;

        }
    }
}

void MakeNewFallingPiece()
{
    TetrisPiece.BlockType blockType = (TetrisPiece.BlockType)Random.Range(0, BLOCKTYPE_COUNT);
    dropTimer = 0f;
    fallingPiece = new TetrisPiece(blockType, DEFAULT_POSITION_X, DEFAULT_POSITION_Y);
    DrawFallingPiece();
}

void DropDown()
{
    // check cell directly below a block:
    for (int y = 0; y < fallingPiece.GetCurrentOrientation().orientations.GetLength(0); y++)
    {
        for (int x = 0; x < fallingPiece.GetCurrentOrientation().orientations.GetLength(0); x++)
        {
            if (fallingPiece.GetCurrentOrientation().orientations[y, x] == 1)
            {
                if (fallingPiece.pos_y + y == 0)
                {
                    Debug.Log("HIT FLOOR!");
                    ConvertFallingPieceToFrozenBricks();
                    return;
                }
                if (frozenCells[fallingPiece.pos_x + x, fallingPiece.pos_y + y - 1].isFilled == true)
                {
                    Debug.Log("HIT FROZEN CELLS!");
                    ConvertFallingPieceToFrozenBricks();
                    return;
                }
            }
        }
    }
    fallingPiece.pos_y--;
}

void MoveLeft()
{
    // check cell directly to left of a block:
    for (int y = 0; y < fallingPiece.GetCurrentOrientation().orientations.GetLength(0); y++)
    {
        for (int x = 0; x < fallingPiece.GetCurrentOrientation().orientations.GetLength(0); x++)
        {
            if (fallingPiece.GetCurrentOrientation().orientations[y, x] == 1)
            {
                if (fallingPiece.pos_x + x == 0)
                {
                    Debug.Log("hit side wall");
                    return;
                }
                if(frozenCells[fallingPiece.pos_x - 1 + x, fallingPiece.pos_y + y].isFilled == true)
                {
                    Debug.Log("tried moving left but there was a frozen brick");
                    return;
                }
            }
        }
    }
    fallingPiece.pos_x--;
}

void MoveRight()
{
    // check cell directly to left of a block:
    for (int y = 0; y < fallingPiece.GetCurrentOrientation().orientations.GetLength(0); y++)
    {
        for (int x = 0; x < fallingPiece.GetCurrentOrientation().orientations.GetLength(0); x++)
        {
            if (fallingPiece.GetCurrentOrientation().orientations[y, x] == 1)
            {
                if (fallingPiece.pos_x + x == CELL_COUNT_X - 1)
                {
                    Debug.Log("hit side wall");
                    return;
                }
                if (frozenCells[fallingPiece.pos_x + 1 + x, fallingPiece.pos_y + y].isFilled == true)
                {
                    Debug.Log("tried moving right but there was a frozen brick");
                    return;
                }
            }
        }
    }
    fallingPiece.pos_x++;
}

void RotatePositive()
{
    for (int y = 0; y < fallingPiece.GetCurrentOrientation().orientations.GetLength(0); y++)
    {
        for (int x = 0; x < fallingPiece.GetCurrentOrientation().orientations.GetLength(0); x++)
        {
            if (fallingPiece.GetNextOrientation().orientations[y, x] == 1)
            {
                if (fallingPiece.pos_x + x < 0)
                {
                    Debug.Log("tried rotation but hit a wall");
                    return;
                }
                if (fallingPiece.pos_x + x >= CELL_COUNT_X)
                {
                    Debug.Log("tried rotation but hit a wall");
                    return;
                }
                if (fallingPiece.pos_y + y == 0)
                {
                    Debug.Log("tried rotation but hit floor");
                    return;
                }
            }
        }
    }
    fallingPiece.GotoNextOrientation();
}

void ConvertFallingPieceToFrozenBricks()
{
    for (int y = 0; y < fallingPiece.GetCurrentOrientation().orientations.GetLength(0); y++)
    {
        for (int x = 0; x < fallingPiece.GetCurrentOrientation().orientations.GetLength(0); x++)
        {
            if (fallingPiece.GetCurrentOrientation().orientations[y,x] == 1)
                frozenCells[fallingPiece.pos_x + x, fallingPiece.pos_y + y] = new FrozenPiece(fallingPiece.color, true);
        }
    }
    fallingPiece = null;
}

void DrawFallingPiece()
{
    if (fallingPiece == null)
        return;

    for (int y = 0; y < fallingPiece.GetCurrentOrientation().orientations.GetLength(0); y++)
    {
        for (int x = 0; x < fallingPiece.GetCurrentOrientation().orientations.GetLength(0); x++)
        {
            if (fallingPiece.GetCurrentOrientation().orientations[y, x] == 1)
            {
                brick = new GameObject();
                brick.name = "TetrisPiece_" + fallingPiece.blockType;
                brick.AddComponent<SpriteRenderer>();
                brick.GetComponent<SpriteRenderer>().sprite = brickSprite;
                brick.transform.position = new Vector2((fallingPiece.pos_x + x) * CELL_SIZE, (fallingPiece.pos_y + y) * CELL_SIZE);
                brick.GetComponent<SpriteRenderer>().color = fallingPiece.color;
                bricks.Add(brick);
            }
        }
    }
}

void DrawFrozenBricks()
{
    for (int x = 0; x < frozenCells.GetLength(0); x++)
    {
        for (int y = 0; y < frozenCells.GetLength(1); y++)
        {
            if (frozenCells[x, y].isFilled == true)
            {
                brick = new GameObject();
                brick.name = "Frozen Cell Brick";
                brick.AddComponent<SpriteRenderer>();
                brick.GetComponent<SpriteRenderer>().sprite = brickSprite;
                brick.transform.position = new Vector2(x * CELL_SIZE, y * CELL_SIZE);
                brick.GetComponent<SpriteRenderer>().color = frozenCells[x,y].color;
                frozenCellBricks.Add(brick);
            }
        }
    }
}

void HandleMovementAndBlockCreation()
{
    float input_x = Input.GetAxis("Horizontal");
    float input_y = Input.GetAxis("Vertical");
    bool rotateButton = Input.GetButtonDown("Rotate_Positive");
    moveDelay = dropDelay / moveToDropSpeedFactor;

    moveTimer += Time.deltaTime;
    rotTimer += Time.deltaTime;

    if (fallingPiece != null)
    {
        if (input_y < 0)
            dropTimer += dropTimerSuperSpeed * Time.deltaTime;
        else
            dropTimer += dropTimerBaseSpeed * Time.deltaTime;

        if (dropTimer >= dropDelay)
        {
            DropDown();
            dropTimer = 0f;
        }
        else
        {
            if (moveTimer >= moveDelay)
            {
                moveTimer = 0f;

                if (input_x < 0)
                    MoveLeft();
                else if (input_x > 0)
                    MoveRight();
            }
            if (rotateButton)
                RotatePositive();
        }
    }
    else
    {
        MakeNewFallingPiece();
    }
}

private void Update()
{
    ClearBoard();

    HandleMovementAndBlockCreation();

    DrawFallingPiece();
    DrawFrozenBricks();

}
}

public class TetrisPiece
{
public enum BlockType { A, B, C, D, E, F, G };
public BlockType blockType;
private Orientation[] possibleOrientations;
private int currentOrientationIndex = 0;
public short pos_x, pos_y;
public Color color;

public TetrisPiece(BlockType blockType, short PosX, short PosY)
{
    pos_x = PosX;
    pos_y = PosY;

    this.blockType = blockType;
    switch (blockType)
    {
        case BlockType.A:
            color = Color.red;
            possibleOrientations = new Orientation[2];
            possibleOrientations[0] = new Orientation(new int[4, 4] { { 0, 1, 0, 0 }, { 0, 1, 0, 0 }, { 0, 1, 0, 0 }, { 0, 1, 0, 0 } });
            possibleOrientations[1] = new Orientation(new int[4, 4] { { 0, 0, 0, 0 }, { 1, 1, 1, 1 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 } });
            break;
        case BlockType.B:
            color = Color.blue;
            possibleOrientations = new Orientation[1];
            possibleOrientations[0] = new Orientation(new int[4, 4] { { 0, 0, 0, 0 }, { 0, 1, 1, 0 }, { 0, 1, 1, 0 }, { 0, 0, 0, 0 } });
            break;
        case BlockType.C:
            color = Color.green;
            possibleOrientations = new Orientation[4];
            possibleOrientations[0] = new Orientation(new int[4, 4] { { 0, 0, 0, 0 }, { 0, 1, 0, 0 }, { 1, 1, 1, 0 }, { 0, 0, 0, 0 } });
            possibleOrientations[1] = new Orientation(new int[4, 4] { { 0, 0, 0, 0 }, { 0, 1, 0, 0 }, { 1, 1, 0, 0 }, { 0, 1, 0, 0 } });
            possibleOrientations[2] = new Orientation(new int[4, 4] { { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 1, 1, 1, 0 }, { 0, 1, 0, 0 } });
            possibleOrientations[3] = new Orientation(new int[4, 4] { { 0, 0, 0, 0 }, { 0, 1, 0, 0 }, { 0, 1, 1, 0 }, { 0, 1, 0, 0 } });
            break;
        case BlockType.D:
            color = Color.cyan;
            possibleOrientations = new Orientation[2];
            possibleOrientations[0] = new Orientation(new int[4, 4] { { 0, 0, 0, 0 }, { 0, 0, 1, 0 }, { 0, 1, 1, 0 }, { 0, 1, 0, 0 } });
            possibleOrientations[1] = new Orientation(new int[4, 4] { { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 1, 1, 0, 0 }, { 0, 1, 1, 0 } });
            break;
        case BlockType.E:
            color = ColorTools.Color255(128f, 41f, 11f); // brown
            possibleOrientations = new Orientation[2];
            possibleOrientations[0] = new Orientation(new int[4, 4] { { 0, 0, 0, 0 }, { 0, 1, 0, 0 }, { 0, 1, 1, 0 }, { 0, 0, 1, 0 } });
            possibleOrientations[1] = new Orientation(new int[4, 4] { { 0, 0, 0, 0 }, { 0, 0, 1, 1 }, { 0, 1, 1, 0 }, { 0, 0, 0, 0 } });
            break;
        case BlockType.F:
            color = ColorTools.Color255(255f, 255f, 0f); // yellow
            possibleOrientations = new Orientation[4];
            possibleOrientations[0] = new Orientation(new int[4, 4] { { 0, 0, 0, 0 }, { 0, 0, 1, 0 }, { 0, 0, 1, 0 }, { 0, 1, 1, 0 } });
            possibleOrientations[1] = new Orientation(new int[4, 4] { { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 1, 1, 1 }, { 0, 0, 0, 1 } });
            possibleOrientations[2] = new Orientation(new int[4, 4] { { 0, 0, 0, 0 }, { 0, 1, 1, 0 }, { 0, 1, 0, 0 }, { 0, 1, 0, 0 } });
            possibleOrientations[3] = new Orientation(new int[4, 4] { { 0, 0, 0, 0 }, { 0, 1, 0, 0 }, { 0, 1, 1, 1}, { 0, 0, 0, 0 } });
            break;
        case BlockType.G:
            color = ColorTools.Color255(128f, 0f, 128f); // purple
            possibleOrientations = new Orientation[4];
            possibleOrientations[0] = new Orientation(new int[4, 4] { { 0, 0, 0, 0 }, { 0, 1, 0, 0 }, { 0, 1, 0, 0 }, { 0, 1, 1, 0 } });
            possibleOrientations[1] = new Orientation(new int[4, 4] { { 0, 0, 0, 0 }, { 0, 0, 1, 0 }, { 1, 1, 1, 0 }, { 0, 0, 0, 0 } });
            possibleOrientations[2] = new Orientation(new int[4, 4] { { 0, 0, 0, 0 }, { 1, 1, 0, 0 }, { 0, 1, 0, 0 }, { 0, 1, 0, 0 } });
            possibleOrientations[3] = new Orientation(new int[4, 4] { { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 1, 1, 1, 0 }, { 1, 0, 0, 0 } });
            break;
    }
}

public Orientation GetCurrentOrientation()
{
    return possibleOrientations[currentOrientationIndex];
}

public Orientation GetNextOrientation()
{
    Debug.Log("index = " + currentOrientationIndex);
    if (possibleOrientations.Length == 1)
        return possibleOrientations[0];
    if (currentOrientationIndex == possibleOrientations.Length - 1)
        return possibleOrientations[0];
    else
        return possibleOrientations[currentOrientationIndex + 1];
}

public void GotoNextOrientation()
{
    currentOrientationIndex++;
    if (currentOrientationIndex >= possibleOrientations.Length)
        currentOrientationIndex = 0;
}
}

 public struct Orientation
 {
public int[,] orientations;

public Orientation(int[,] Orientations)
{
    orientations = Orientations;
}
}

public class FrozenPiece
{
public Color color;
public bool isFilled = false;

public FrozenPiece(Color Color, bool IsFilled)
{
    color = Color;
    isFilled = IsFilled;
}
}

public static class ColorTools
{
public static Color Color255(float r, float g, float b)
{
    return new Color(r / 255f, g / 255f, b / 255f);
}
public static Color Color255_Alpha(float r, float g, float b, float a)
{
    return new Color(r / 255f, g / 255f, b / 255f, a / 255f);
}
}

```

# Answer
> 1 votes
You can use a boolean flag. Whenever a new piece spawns, set it to true and in the update method, check if the down key is pressed and if it isn't, set the flag to false.

This way you'll have a boolean, that'll only become false after a new piece, when the down key gets released. If the boolean is true, don't speed the falling up.

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


# Question
Title: What is the exact unit in LibGDX if it says "private static final float WORLD_SIZE = 480"?
In the code I see that the WORLD\_SIZE variable was initialized with 480 private static final float WORLD\_SIZE = 480;

What exactly the 480 means, are they pixels, cm or meters?

# Answer
> 1 votes
A unit by itself is just a unit. It doesn't represent anything until you know the context of what it is used for.

If for example the WORLD\_SIZE is used with Box2D to represent the size of the world then it is likely to be meters as Box2D works in meters.

If WORLD\_SIZE is used to define the width/height of a world map texture then the units would be pixels.

---
Tags: libgdx
---


# Question
Title: What are my options for building a centralized server architecture for a Unity game?
I have made in the past multiple offline game, and would like to make my first online game. I have very basic knowledge of server structure.

The game is a multiplayer RTS game, with ONE server (If possible in c#), where player can build base, attack other player and move around a world. it is in real time, but slow paced, so not many actions, and every time a user make movement it take let's say an hour to move. The game is planned for Android/iOS and (maybe) but not at all for the moment, web.

The game itself is easy, but the server I don't know where to start and I have been struggling in the last 3 days to find a informations and answer to my question. Most of the example I found are P2P/client-hosted server, this do not apply to my case, I want a single server that runs outside of Unity and that I can run on a computer as stand-alone. My question problems are.

1) for a mobile game, I have seen in some post that UDP TCP/Socket are not available in 3g? is this true ? If so, what should I Use ? I was thinking of websocket since MAYBE i make a web version, but I don't know if it's a good idea, and apparently it is not built in in Unity.

2) Related to my 2) is there any c# library that work in Unity and would fit my game needs? a user would probably load a map, and interact around 20 times with the server during the gameplay. I believe a simple server that get and send message only is largely enough, but I don't know what to use. Start from scratch? then what should I use, TCP ? Socket? WebSocket ?

3) Should I use photon ? I've seen is free to test until 20CCU, and since for probably the next 6month I will be alone on it it's OK, then at release let's say I have 100 player, is not that expensive. Is it a viable solution? I found it a bit overkill for my needs, but it looks documented and easy to start. Will I still learn stuff if I "cheat" like this?

Thank you for your time

# Answer
> 1 votes
Some of what you ask will fall on opinion based. And know that asking for what technology to use and where to start are off-topic here.

---

However...

> 1) for a mobile game, I have seen in some post that UDP TCP/Socket are not available in 3g? is this true ?

Not true.

Note that we are probably talking of running on a mobile operating system that will require the user to set permissions to the application to use the network. It possible that the user has restricted the use of the network because the ISP is charging based on the amount of transferred data.

Also, these are common:

* The IP can change beyond user control.
* The device will likely be connected behind a bunch of NATs (and you will not be able to use UPnP to punch through).

These are bypassed simply by having a traditional client-server architecture, where the client sends a request to the server, and the server responds. Since you are not trying to do P2P, these should not be issues for you (except, perhaps for push notifications).

---

> 2) is there any c# library that work in Unity and would fit my game needs?

Plenty, try them, they may not all work for you. See BenchmarkNet.

> Start from scratch? then what should I use, TCP ? Socket? WebSocket ?

Sockets. You build everything ontop of sockets. UDP will give you more flexibility, TCP is easier to start with.

---

> 3) Should I use photon ?

Don't know. I am only vaguely familiar with photon, I am not familiar with your requirements, I am not familiar with your skills.

> Will I still learn stuff if I "cheat" like this?

Using services, engines, middleware, libraries, etc... created by third parties is not cheating. It is to stand in the shoulders of giants.

Please, reuse code.

Yes, there is value in understanding the technical and low level aspects, yet that does not mean you have to start there.

Will you still learn? Yes! Even when it comes to networking, you will learn the high level architecture you need in order to have a big scary thing called "Internet" breaching in the middle of your system.

With that said, if your goal is to learn how do those libraries work, and you are motivated to start from scratch, then go ahead. In fact, I think there is room for more libraries (for C# in particular), if you think you have something to apport, please do.

---
Tags: unity, client-server, server
---


# Question
Title: Voxel traversal for parabolic projectile arc under constant gravity
For linear polynomials, there's a bunch of algorithms for efficiently determining which voxels to test for collision (eg. A Fast Voxel Traversal Algorithm for Ray Tracing ). I'm having troubles though, searching for algorithms that work for any other case, such as a parabolic projectile arc under constant gravity.

Are there any algorithms for that case, or am I stuck just trying to sample at a high enough frequency that only rarely will a projectile travel though a wall without getting detected.

# Answer
> 2 votes
If your gravity vector is purely vertical (let's call this the Y axis) and there's no sideways wind to account for, then the projectile's XZ position follows a straight line. If you don't have air resistance, then it moves along this line at a constant rate - just like our nice friendly linear raycasts!

So we can cast a "shadow" of the projectile straight down onto the XZ plane. We can work out which squares of the grid on this plane this line passes through using your ordinary raycasting/marching algorithm in 2D (or another line rasterization algorithm like Bresenham's). I show an example of this type of raymarching in this answer.

With this, we can work out the time-of-flight when the shadow crosses into each new square along its path. This tells us when the 3D projectile itself enters a new column of voxels.

By computing the height at each column-entry timestamp, using:

$$\vec p(t) = \vec h\_0 + \vec v\_0 \cdot t + \frac {\vec a} 2 \cdot t^2$$

...then we can get the height at which the projectile enters and exits each column.

The one other height we need is the height at the apex of the parabola. This is the one point where the projectile might touch voxels in a column outside the range from its entry to exit height. We can find this point with:

$$t\_\* = \frac {-v\_y} {a\_y}$$

Now we can walk through each of these key timestamps in sequence, from the entry into a new column of voxels, and up/down that column to the next timestamp in sequence (be it the apex or the entry into the next column over). This ensures we visit every voxel touched by the parabola, with only a small amount of work beyond the basic 2D raycast.

---
Tags: collision-detection, voxels
---


# Question
Title: Ensuring a Recursive method completes in one update tick?
OK so I have a method that calls itself as this was the only way I could think to get the behaviour I needed. Its a tetris clone i am making and this method is for checking for full lines across X axis.

```
    void CheckForFullLine(int starting_Y)
{
    for (int y = starting_Y; y < frozenCells.GetLength(1); y++)
    {
        for (int x = 0; x < frozenCells.GetLength(0); x++)
        {
            if (!frozenCells[x, y].isFilled)
            {
                CheckForFullLine(starting_Y + 1);
                return;
            }

            if (x == CELL_COUNT_X - 1)
            {
                tetrisLinesThisTick++;
                Debug.Log("lines this tick: " + tetrisLinesThisTick + "on tick: " + tick);
                ClearLine(y);
            }
        }
    }
}

```

but when i test the game, most of the time (more than 9/10 times) when you get multiple lines, the debug log says we only got 1 line in that 'tick'.

Here is the update method where at the top I set tetrisLinesPerTick to 0 at the start of each frame.

```
    private void Update()
{
    tick++;
    // reset the tetris-lines this tick value:
    tetrisLinesThisTick = 0;

    ClearScreen();
    CheckForFullLine(0);
    HandleMovementAndBlockCreation();
    DrawFallingPiece();
    DrawFrozenBricks();
}

```

For example if I get 2 lines in one go, I get the debug log saying '...linesPerTick 1' twice in quick succession.

Strangely , occasionaly I do get the 2 or even 3 lines and it says the correct amount, but this is rare and i don't know how i reproduce that yet.

Another very strange thing (the relevant code might not be here for this part..) ...quite rarely one of the frozen blocks will turn grey after falling, then I can still 'use' it in game to make more lines, but it doesnt disappear like the others, then make a couple more lines using this grey block and it disappears as normal :S (well just in case you feel like helping me with this part, he is more code :P):

```
    void ClearLine(int line)
{
    // TODO: Add score

    // remove complete line
    for (int x = 0; x < frozenCells.GetLength(0); x++)
    {
        frozenCells[x, line].isFilled = false;
    }

    //shift all lines down        // todo: figure out if its a multi-line tetris to give better scores...
    for (int y = line; y < frozenCells.GetLength(1); y++)
    {
        for (int x = 0; x < frozenCells.GetLength(0); x++)
        {
            if (frozenCells[x, y].isFilled)
            {
                if (y > 0)
                {
                    frozenCells[x, y].isFilled = false;
                    frozenCells[x, y - 1].isFilled = true;
                }
            }
        }
    }

}

```

For some reason, I feel it may be the recursive method i made and the fact that 'linesPerTick' value is getting set back to zero prior to the other lines being removed (in the same move), is what is causing my problem but i could be completely wrong about it!

The whole project is just one .cs file and a block texture i made in GIMP, I could paste the whole script here if you want to try it please let me know. Cheers for any help!

# Answer
> 4 votes
This is almost certainly an XY problem -- I can't imagine that it makes sense to use a recursive function for this.

If I'm reading your code right (it's late) then you're trying have it stop processing each row as soon as it finds the first empty square instead of processing the whole row, which makes sense. Instead of calling your function again, how about simply `continue`ing on to the next step in your outer Y loop?

I think you've probably also got a logic problem where you call `ClearLine` upon finding a full row, and that shifts everything down *while you're still in the middle of looking for full rows*. If your code finds that row 3 is full, then it increments the score counter AND shifts row 4 down into row 3, and then continues checking at row 4. Since you've already shifted 4 to 3, that row never gets checked. Personally, I'd be tempted to move all of the rows *after* doing all the score calculation, but there are lots of solutions (including just re-checking the same row IF you've called clearline).

Often, I find that working through these problems on some scratch paper can give you a lot of insight into what your code is *actually* doing when you think it should be doing something else. This is a small enough problem that working though a loop or two shouldn't be *too* painful ;-)

FWIW, since you're really only copying one row to another regardless of whether it's filled or not, you could probably simplify your ClearLine to something like this pseudocode:

```
void ClearLine(int line) {
  int topRow = frozenCells.GetLength(1)-1
  for (int y=line; y<topRow; y++) {
    for (int x = 0; x < frozenCells.GetLength(0); x++) {
      frozenCells[x,y].isFilled = frozenCells[x,y+1]
    }
  }
  // The new top row should be empty
  for (int x = 0; x < frozenCells.GetLength(0); x++) {
    frozenCells[x,topRow].isFilled = false
  }
}

```

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


# Question
Title: Gameobject stops moving or gets stuck when colliding with another GameObject
I'm currently making a brick breaker style game. My issue comes when the ball is launched off the pad it gets stuck in between two blocks. I have all the blocks on a "Foreground" layer with an "Order in Layer" set to 0. The Ball is on the "Foreground" with an "Order in Layer" set to 1. But the ball will get stuck and quit moving. I've tried changing the orders of the players and it didn't help. Any thoughts?

# Answer
After messing with it, I found that I needed to change the collision detection on the Rigidbody2D on the ball to "continuous".
> 0 votes

---
Tags: unity, 2d, collision-detection, physics
---


# Question
Title: Objects World Matrix Issue in Direct3D11
I have an issue with the transform matrix of my cube. When I change its position (world matrix) and rotate the camera, it is getting deformed.

Here's my shader update code:

```
void IShader::UpdateShader()
{
    XMMATRIX view= XMLoadFloat4x4(&m_viewMtx);    //The camera's view matrix (using XMMatrixLookAt())
    XMMATRIX persp = XMLoadFloat4x4(&m_perspMtx);    //The camera's perspective matrix
    XMMATRIX world = XMLoadFloat4x4(geo->GetWorldMatrix());    //Here, get the cube's world position (it is updated using keyboard input in another class)
    // GetWorldMatrix() returns m_worldMtx

    XMMATRIX m = view * persp * world;

    m = XMMatrixTranspose(m);

    VERTEX_BASIC_CONSTANT_t k;
    k.mWorldViewPersp = m;    //The vertex shader only contains one float4x4 in the cbuffer...

    D3D11_MAPPED_SUBRESOURCE map;
    memset(&map, 0, sizeof(map));

    ID3D11Buffer* context = sh->GetVSCBuffer();
    m_pD3DCtx->Map(
        context,
        0,
        D3D11_MAP_WRITE_DISCARD,
        0,
        &map
    );

    memcpy(map.pData, &k, sizeof(k));

    m_pD3DCtx->Unmap(
        context,
        0
    );
}

```

Here is how I update the cube's position:

```
void Geo::UpdatePos(VEC3 offset)
{
    XMMATRIX t = XMMatrixTranslation(offset.x, offset.y, offset.z);

    XMStoreFloat4x4(&m_worldMtx, t);
}

```

This deformation issue only affects the cube, not the floor.

# Answer
> 0 votes
Tldr: debug if your cube is where you expect it to be, then check your mvp multiplication order. And make sure to first rotate and then translate the viewmatrix as it seems to be an orbiting rotation around identity.

General guide on debugging transformations and colours:

1. Start local Verify your cubes expected world only transformation by translation transforming it from identity to a known location like 2,3,3. If the cubes transformed matrix matches your expectation you can rule that out as a problem.
2. Know your expected SRT order If you plan to use more than translations the order of operations starts to matter because only translation is a commutative operation. Scale first, then rotate, and last translate.
3. Know your matrix layout aka handedness Is it row major or column major order matrices that you work with? In opengl it's column major P*V*M with right handedness, positive z towards screen. In DirectX it's row major M*V*P with left handedness, positive z further away from screen.
4. Sketch an easy scene on paper that consists of 3 cubes Each cube has a unique colour like r,g and b. Place every cube from left to right but the middle one a bit further along z. Is the middle cube further or nearer to your screen? Do the colours match the order of the cubes? Is it rgba, argb or bgra colours that you're dealing with?

---
Tags: directx, directx11, matrix
---


# Question
Title: Why do some games show lights shine through walls?
In some games, I see lights shining through walls, even if I set video quality on high levels.

A couple of examples of games I recently played are Borderlands 2 (missile explosions) and Call of Cthulhu (lanterns; the game even uses Unreal Engine 4).

Is this a bug or there are performance reasons?

Example Borderlands 2: https://youtu.be/9bV83qA6\_mU?t=419 (few times, but quickly)

Bonus question: in the latter case, is there any way ray tracing could be cheaply used to solve the problem? I guess that expensive RT definitely solved the problem, but I wonder if it can also be used in a "cheap" form to solve this specific problem.

# Answer
Expanding on TomTsagk's correct answer, I thought it might help to describe a bit more about why games work like this.

Light in games doesn't really "travel" from the source, to the surface, to the camera, getting obstructed along the way.

To figure out how bright to draw each pixel of a surface based on a given light, we use (or approximate) a math formula that uses the facing direction of the surface and the direction from this point on the surface to the light source. That's it, just the direction it's shining from — we don't typically cast a ray to check if the light actually reaches this pixel, because doing that for every pixel on the screen and checking the ray against all the detailed geometry in the scene is usually still too expensive for realtime games.

So, by default, no game lights cast shadows. The direction to a light stays the same even if there's a shadowcaster in the way, so the math gives us the same brightness value.

If we want to simulate shadows, we have to do that separately. One common way is with what's called a Shadow Map. In this version, before we shade our scene, we first render the scene from the perspective of each light, as though that light were a camera, storing the depth of each pixel it sees into an off-screen texture.

Then, when we shade the scene, we can compare the mathematical distance of this pixel from the light source vs the depth we recorded at the corresponding pixel in the shadow map. If the shadow map depth is smaller, then it means there's another surface between here and the light, and we draw this pixel in shadow instead.

There's a whole lot of cool techniques to make these map-based shadows look nicer, with fewer artifacts/aliasing, but I'll gloss over them for now. Suffice it to say, they're generally not free either.

Because this requires rendering (up to) the whole scene again from each light's perspective — up to six times if it's a point light that shines in all directions {north, south, east, west, up, down}, and we need to re-render the shadow map anytime something moves, this can get very expensive.

So games will often focus their rendering budget on the most important lights in the scene — like the directional sun light — to ensure they have good-looking shadows. Small, short-lived, minor lights like the flash of an explosion are often forgivable if they leak past occluders a little. Often this is more palatable to players than a hitch in the framerate due to a sudden increase in rendering cost from all the extra shadow map rendering and calculation. Especially if it's a busy action scene where fluidity matters more than pixel perfection.
> 44 votes

# Answer
Long story short, this happens for performance reasons.

When there's a light on the screen, by default it shines on all objects (obstructed or not), so the game would need to make extra calculations to see which object is affected by what.

This is easier to solve on static objects by using static and baked lighting, but this is not the same on dynamic lights, like explosions as you noted.

For your bonus question, ray tracing and cheap do not go together on the same sentence. The only reason ray tracing hasn't been mainstream up until now is performance. Assuming all lights use ray tracing, then this problem would be "solved", but at the expense of performance.
> 23 votes

---
Tags: lighting, shadows, raytracing
---


# Question
Title: Mouse drag rotation script doesn't work when attached to OBJ model
I am new to Unity. I imported an OBJ model and assigned materials to it.

I want to rotate it using the mouse in the game, using this script:

```
using UnityEngine;

public class MouseDragRotate : MonoBehaviour {
    float rotationSpeed = 0.2f;

    void OnMouseDrag()
    {
        float XaxisRotation = Input.GetAxis("Mouse X")*rotationSpeed;
        float YaxisRotation = Input.GetAxis("Mouse Y")*rotationSpeed;
        // select the axis by which you want to rotate the GameObject
        transform.RotateAround (Vector3.down, XaxisRotation);
        transform.RotateAround (Vector3.right, YaxisRotation);
    }
}

```

I tried to apply this rotation script to the OBJ asset in my Project folder, but I wasn't able to find an Add Component option in its Inspector.

So I dragged it to the Hierarchy panel to create an instance of the object in my scene. I applied my materials again to this instance.

Then I added the rotation script using the Add Component button in the Inspector.

But when running the game in play mode, I can't rotate it.

I verified that the script above works perfectly for the default Cube or Plane primitives in Unity, but not for this imported object.

How can I make this script work with my OBJ model?

# Answer
> 2 votes
Unity's OnMouseDown / OnMouseDrag / etc MonoBehaviour messages only work when the object has a collider attached.

This is because when you use these methods, under the hood, the engine fires a physics raycast each frame from the main camera, through the position of the mouse, to find out what object is under it, so it knows what object to fire these messages on.

Only colliders will be hit by that raycast — it ignores rendered meshes and such (otherwise the performance cost could get extreme: physics colliders are usually much simpler than detailed display geometry). This also gives you the ability to control which objects should block that raycast — like a solid wall — versus not — like a puff of smoke particles or a translucent glass window.

---
Tags: unity, c#, rotation, input
---


# Question
Title: Unity Collider2D - Know the collider type ob the object collider with the other object
I have my GameObject which represents a soldier in my game. It has the following colliders:

* 1st BoxCollider2D in child named "sword". Is Trigger checked. Tag = Sword. This collider is enable when player attacks and disabled otherwise.
* 2nd BoxCollider2D in parent GameObject. Is Trigger unchecked, since it's the body. Always enabled.

When the sword (1st) collider collides with the the body (2nd) collider, damage happens. Until now everything works fine. Here is the `OnTriggerEnter2D` function I have:

```
void OnTriggerEnter2D(Collider2D collision)
{
    if (collision is BoxCollider2D)
    {
        Debug.Log($"{this.name} collided with {collision.name}");

        if (collision == null || collision.tag == Constants.TAG_WEAPONS
            || collision.tag == Constants.TAG_SIGHT)
        {
            return;
        }

        if (collision.GetComponent<LivingObjects>().AreEnemies(this))
        {
            Debug.Log($"{this.name} attacked with {collision.name}");

            Attack(collision.GetComponent<LivingObjects>());
        }
        else
        {
            return;
        }
    }
}

```

Now I want my unit to search for enemies within a said range. I added a new collider:

* 3rd CircleCollider2D in child named "sight". Is Trigger checked. Tag = Sight. Always enabled.

Now, when the sight (3rd) collider collides with the body collider, damage is trigger into the unit colliding with the sight collider. That is because I block damage one way around with the condition `if (collision is BoxCollider2D)` but not the other collision happening at the same moment.

If i can discrimate collision from CircleCollider2D into BoxCollider2D, I can remove the attack function. However, I cannot see how to do it. My question is how do I know what Collider2D type is my object colliding with the other ?

I'm open to other suggestion if this is impossible.

# Answer
I think you should use a layering system of unity and kept the relevant colliders in the same layer as your no. 3rd collider used for searching make a new layer name it "searching" and then player collider and enemy collider keep both in that layer("searching") and then go to Edit-\> project settings -\> physics2d settings that will show layer collision matrix then uncheck all other irrelevant layers I hope it will solve your problem.
> 1 votes

---
Tags: unity, collision-detection
---


# Question
Title: What is the best and simplest way to get input text from user in an OpenGL app?
I have an OpenGL game and and I want to implement a simple way for the user to enter data/text in an input box. What is the easiest method to do this?

# Answer
> 4 votes
OpenGL is a rendering system. Rendering has nothing to do with getting text input. If you want text input, then you're going to have to use a library or OS system that provides it.

SDL, Allegro, SFML, and most of the other "multimedia" libraries all have some means of getting input from the user. They're also cross-platform, if you're into that sort of thing. Even the "toy" libraries like GLFW and FreeGLUT have ways of getting basic input.

As for the "text box" part, that's going to be more interesting. Generally, if you're making a game, you don't really interact with the native windowing GUI. So you either have to use a specialized GUI library like CeGUI, or you have to write the text box code yourself. I would personally suggest investigating game-GUI libraries, as writing a GUI yourself is not particularly fun.

# Answer
> 1 votes
I have a 20-year old GLUT program. I need to support command line entry. My solution is epically nasty: I edit the text in the window title bar.

I used the ESC key to toggle a command-line mode. In this mode, the mouse symbol became the text entry bar, and the the current prompt and text was displayed using `glutSetWindowTitle()`. You can only get the conventional ASCII 7-bit printing characters. I support the printing characters, DEL, and RETURN. I have command history using the arrow keys. There is no cursor symbol, so the only way of moving back is to delete.

The default centres the text. I got left justification of the prompt by appending a lot of spaces.

Postscript:

The title bar supports ASCII 20-7E and unicode on my Mac. I guess the title bar is rendered by the OS, so there is a good chance unicode will work most systems.

FreeGLUT lets you exit the render loop and get back in again, so you can edit strings in the terminal and submit them to the render. My build already had GLUT in the Nvidia tools, so it was easier to use that, but YMMV.

# Answer
> 0 votes
I don't know, if you want to use just OpenGL or it's also possible to use other libraries. If you can use others, you can try AntTweakBar \- gui library for OGL. I have never used it for text input, but there is also string type for variables, so it should work.

You just create bar, add there variable of type string and set callback. When data are changed, you store them to your own variable. Then you add there button. When user presses it, you will just use stored text to whatever you want.

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


title: if rotation < -45 && > -140 issue

text:
# Question
Title: if rotation < -45 && > -140 issue
I have a problem with this if statement.

If the rotation is \< -45. And \> -140

Then this statement would be true when the rotation is = -90?

And it would be false if the rotation is = -170?

I'm using the negative values because unity rotation goes from -180 to +180.

I tried using a full 360 scale, that also didnt work. that Statement looked like:

if the rotation is \> 245 & \< 325

Then do stuff

If you can change where the 0 value of the rotation is from the West point to a different one would also be a useful option

Thanks for any help

Code that is being executed:

```
        if (transform.rotation.z > -140 && transform.rotation.z < -45)
    {
        if(rotationSpeed < 150f)
        {
            rotationSpeed += 150f * Time.deltaTime;
        } else
        {
            rotationSpeed = 150f;
        }
        print("135");

    } else
    {
        if(rotationSpeed > 70f)
        {
            rotationSpeed -= 150f * Time.deltaTime;
        } else
        {
            rotationSpeed = 70f;
        }
        print("246");
    }

```

# Answer
It turns out that Transform.rotation is a Quaternion. This is why I can't use the `z` value from it.

The Transform.localEulerAngles does use 0 to 360, so changing the parameters of the `if` statement will solve any issues:

```
if (transform.localEulerAngles.z > 250 && transform.localEulerAngles.z < 325)
{
    if(rotationSpeed < 150f)
    {
        rotationSpeed += 150f * Time.deltaTime;
    } else
    {
        rotationSpeed = 150f;
    }
    print("135");

} else
{
    if(rotationSpeed > 70f)
    {
        rotationSpeed -= 150f * Time.deltaTime;
    } else
    {
        rotationSpeed = 70f;
    }
    print("246");
}

```
> 0 votes

---
Tags: unity, c#, mathematics, rotation
---


title: Peer-to-peer Multiplayer Game

text:
# Question
Title: Peer-to-peer Multiplayer Game
I built a casual game where the user answer the right word in random question. Now I want to make this game multiplayer (4 players) working on smartphones and tablets (Androird & iOS) where all the players are clients but one of them is Host/Client who receives the in-game answers to check who won and answer-back to the other three players (Clients) with the score.

However, I'm confused about HLAPI, LLAPI, dedicate server, PUN, Standalone, Local, LAN... I'm a mess right now. What should I choose? having on mind I only send/receive strings, and the game should work with and without Wi-Fi connection.

# Answer
> 1 votes
While asking for what technology to use is off-topic here... I can tell you what not to use.

First of all, you want the game instances to be able to work as clients or servers. There will not be an stablished server to which everybody connects. That is, you want a peer-to-peer network architecture. Please note that while we are talking P2P, that does not mean there will not be hosts.

See How can I make a peer-to-peer multiplayer game?.

---

The issue is that if you want smartphones to connect without Wi-Fi. Which often would mean mobile telecommunications technologies (3g, 4g, etc.) - As I was explaining in What are my options for building a centralized server architecture for a Unity game? that has a lot of limitations for P2P.

So, you have three main paths:

* Stick with mobile networks.
* Use something else. You could use Wi-Fi which is Local Area Network (LAN). alternatively consider Bluetooth, which is a Personal Area Network (PAN).
* Have a server. Clients could access the server over the Internet either from a mobile network or Wi-Fi (via a gateway).

To be clear, Wi-Fi could be used to connect directly, since it is a Local Area Network (LAN), or to access a geteway to the internet.

---

If you want to stick with mobile networks, these won't help you (they are still useful over Wi-Fi):

* HLAPI. Won't work because it relies on knowing the IP.
* LLAPI. Won't work because it works via web requests, which imply a web server.
* UPnP hole punching will probably not work either. It requests the router to Open and Forward a port. Just don't count on it on a mobile network. *You didn't mention it*

*By the way, I do not think Standalone means what you think it means.*

---

You might also be interested in:

* STUN: NAT traversal. There are some free public STUN servers. They are used to try to stablish a direct connection
* TURN: Relay servers.
* ICE: "A standardized set of methods" built ontop STUN and TURN.

*You might also be interested in WebRTC, which uses the above and also provides audio and video transmision via RTP and SDP, although I do not think there is - at the time of writing - a WebRTC solution you can use from Unity. I guess it is worth to have a look.*

I suppose another solution is a Virtual Private Network (VPN). The clients connect to a VPN server over the internet which relays the connections in such way tha they appear to be on a LAN. *Although, I do not know how you would do that programatically on smartphones. If it is possible at all. Usually end-users will acquire a VPN service when they need it. And I mean a true VPN, no a "hide my IP via retransmission while I enter this website" thingy (web proxy).*

---

If you are considering a server, you might be able to use Amazon Lambda, Cognito and DynamoDB, instead of having a fully fleged server. There are also inexpensive hosting solutions that are useful for low traffic.

See: Can Cloud Functions be used for a multiplayer game server?.

---

See also:

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


title: Making my characters modular

text:
# Question
Title: Making my characters modular
I'm making a school-based sandbox adventure game in Unity. I need a lot of NPCs with different apperances. I dreaded this since I don't have fun doing art and it is usually the reason I end up becoming burnt out of projects.

My solution for this was to segregate parts of the characters by color. The skin being green, hair being blue, shirt being red and trousers/leg wear being yellow. Then, I would use a shader to change these colors to something else.

The result is this sprite sheet:

and the ability to easily change the apperance of my NPCs to make them look different from eachother but there's still an issue.

A lot of the characters have the same hair style etc. Not to mention when I make a new hair style for a female, I have to then draw that style 3-4 more times for the different combinations of clothes.

The solution for this that would work ideally would be a modular apporach. I would only need to draw the sprite once and just swap out different clothing combinations. I have attempted this before but the main issue that kept on coming up was the different sprites not lining up, especially when changing the different sprites.

The art style is pixel art so they have to line up perfectly to look nice. How should I go about doing this to ensure I can fit every sprite together perfectly, no matter the combinations I choose?

# Answer
> 3 votes
In order to solve the problems of parts not lining up, you would need a way to specify where the joints are. That is, you will need to build an kind of tree, where each node is a part of the body and specifies the positions of the other parts. It would soft of a...

**Skeleton**

Unity has a system of skeleton bones and joints that - although it is intended for 3D - should be useful for this purpose. And if they weren't, there are third party solutions such as Sprites and Bones which is intended for 2D.

You *rig* the skeleton to your sprites, which allows you to animate it. Sure, you won't be doing skeletal animation - at least not to begin with - yet having joints and having parts be transformed (translated, etc.) at those joints is precisely what you need.

---

Alright, alright, you do not have to use those tools. If you want to stay close to the code, you can specify the joints and pass them to the shader either as part of a texture or a uniform array, and then in the shader you will be able to use the coordinates to offset the positions of the parts.

---
Tags: unity, 2d, sprites, spritesheet, art
---


title: Drag 3D camera with mouse cursor

text:
# Question
Title: Drag 3D camera with mouse cursor
I have a camera that is moved by changing its X and Z coordinates. However, the camera is rotated, so when an object moves by 1 unit in the world, the number of pixels it moves by isn't trivial to determine.

How could I move the camera so that if the pointer is at a set point, that point will be under the cursor after the cursor moves?

I have a PerspectiveCamera and the number of pixels that the pointer was dragged in each direction (X and Y) on the screen.

# Answer
Here is a fiddle hopefully demonstrating the effect you want to achieve. It can get quite jittery on different machines - likely because of javascript nuances I'm not familiar with - but I think it's close to what you're looking for.

https://jsfiddle.net/chaosed0/b4cqktan/37/

---

Here is an explanation of the math involved. We have two constraints:

* Keep the camera at a constant height.
* While the mouse cursor is down, "move" the ground to keep the same location under the cursor at all times.

"Move" is in quotes because we don't want to move the ground, we want to move the camera. Thing is, moving the camera in the opposite direction we would move the ground has the exact same effect, and I find it more intuitive to picture it as if the ground were moving.

With this knowledge, we move on to solving **problem #1: what ground position is the mouse is over**? First, we get the location of the mouse in world-space:

```
var mouseScreenPos = new THREE.Vector3();
mouseScreenPos.x = ( event.clientX / window.innerWidth ) * 2 - 1;
mouseScreenPos.y = - ( event.clientY / window.innerHeight ) * 2 + 1;

var rayOrigin = (new THREE.Vector3(mouseScreenPos.x, mouseScreenPos.y, 0.0)).unproject(camera);

```

Then we obtain the direction of the ray under the mouse by adding a bit of depth to get a point "more under" the mouse, and subtracting that from the world position:

```
var rayPos1 = (new THREE.Vector3(mouseScreenPos.x, mouseScreenPos.y, 1.0)).unproject(camera);
var rayDirection = rayPos1.sub(rayOrigin);

```

Finally, we can use these two points to get the location in space we want to hold constant. For my purposes I'm calculating where the ray intersects the XZ plane at `y = -5`, but this may differ for you depending on where your objects are located.

```
var ySlope = (planeY - rayOrigin.y) / rayDirection.y;
var xIntersect = rayDirection.x * ySlope + rayOrigin.x;
var zIntersect = rayDirection.z * ySlope + rayOrigin.z;

return new THREE.Vector3(xIntersect, planeY, zIntersect);

```

Now, we solve **problem #2: how much to move the camera?** This ends up being fairly easy now that we have the above formula for obtaining the ground position under the mouse. The algorithm goes like this:

* When mouse down is detected:
    + Record `mouseDownPosition`, the current ground position under the mouse
    + Record `mouseDownCameraPosition`, the current position of the camera
* When a mouse move is detected:
    + Obtain the new ground position under the mouse and subtract it from `mouseDownPosition`.
    + Subtract that from `mouseDownCameraPosition`.
    + Set `camera.position` to this final result.

---

As a final note, I think the Raycaster can aid in the case where there's variable-height terrain, i.e. where we don't know what `planeY` above should be upon `mousedown`. However, we still need to calculate the ray/plane intersection when the mouse moves, with `planeY` set to the Y of the point the raycaster found. Otherwise, our first constraint (keep camera at constant height) will be broken.
> 1 votes

# Answer
What you want to achieve is called camera panning.

When you use your mouse you are working with a 2d vector in screen space pixels. In order to correctly transform mouse 2d to world 3d coordinates you can use the well known viewport Project method (should be available at your camera object) or you can even use it the other way around and Unproject your 3d position to 2d screen space position. That's also how raycasting for object selection works. Unproject is used for mouse rectangle selection in RTS games. The 3d coordinates get unprojected into screen coordinates and checked if inside the mouse 2d rect.

A 3d camera usually consists of a viewmatrix and a projectionmatrix. The cameras orientation and position is stored inside the viewmatrix. In order to move your camera to the right or left independent of it's current rotation you have to do the translation relative to the cameras forward vector.

So for panning the camera relative to mouse drag works as follows:

1. Save click position as initialMousePos.
2. Ondrag save mouse position as currentMousePos
3. Project both positions via camera.screenpointtoray to 3d vectors
4. Calculate delta = currentMousePos-initialMousePos
5. Translate camera with delta vector. Your camera is rotated which means you want to translate relative to it's forward vector by calculating the cross product of camera forward with delta first. Correct me if I'm wrong on this one.
6. Set initialMousePos=currentMousePos
7. Repeat on next update
> 1 votes

---
Tags: camera, mouse, three.js
---


# Question
Title: Problem with making camera follow player in Javascript
So I'm testing a few things in Javascript and something I was testing was making the camera follow the player. When I move the player, instead of the dots going away from the player, they follow the player and it looks very strange.

Here is the code: https://codepen.io/anon/pen/wLgEPO?editors=0010

Move the player using the arrow keys.

Thanks.

# Answer
You just inverted the signs. The player's position should be the negative one and the canvas position, the positive one:

```
c.translate(-p.x, -p.y);
c.translate(canvas.width/2, canvas.height/2);

```

The reason for this is that `canvas.translate` makes a given point be considered `(0,0)` for all other drawing operations. The player is going to be rendered at position `p.x` and `p.y`. So if you want to make the player always stay at the point `(400, 400)` or `(canvas.width/2, canvas.height/2)` you need to make `(0, 0)` become a value that added the current player position it will become `(400, 400)`. That value is: `(400 - p.x, 400 - p.y)`. You were previously subtracting 400 from the player position when the right is to subtract the player position from 400. A more consize code would be to replace those 2 lines with this one:

```
c.translate(canvas.width/2-p.x, canvas.height/2-p.y);

```
> 1 votes

---
Tags: javascript, camera, html
---


# Question
Title: x coordinates resets after changing speed?
I wanted to change the speed of a soldier when he enters a barbed wire texture.
Since I have multiple soldiers and multiple barbed wires I just iterate with two for-loops through all of them.

```
for(int j = entityWalkingRightArray.size() - 1; j >= 0; j--) {
  final entity_walking_right entity_walking_right = entityWalkingRightArray.get(j);
  for(int i = barbedWireArray.size() - 1; i >= 0; i--){
    final barbedWire wire = barbedWireArray.get(i);
    //Checks if the entity is inside the barbed wire
    if(  entity_walking_right.getX() >= wire.getX()
      && entity_walking_right.getX() <= wire.getX() + wire.getWidth()
      && entity_walking_right.getY() >= wire.getY()
      && entity_walking_right.getY() <= wire.getY() + wire.getHeight()) {

      entity_walking_right.changeSpeed();
    } else {
      //entity_walking_right.changeSpeed2();
    }
  }
}

```

In the class of the soldier the speed is set to 500 and the positionX is set to 200 when he is first created. I also have these two functions:

```
public void changeSpeed(){
    speed = 50;
}

public void changeSpeed2(){
    speed = 500;
}

```

In the `render()` function of the soldier's class the position is determined.

```
runningTime += Gdx.graphics.getDeltaTime();
positionX = speed * runningTime;

```

When he now enters the barbed wire and the speed is set to 50 then the positionX changes to 200 and he runs with a speed of 50. When I activate `entity_walking_right.changeSpeed2();` then he runs with normal speed (500) through the barbed wire and starts blinking rapidly while another version which also blinks rapidly on positionX 200 with a speed of 50. I looked at the positionX value and he just "teleports" again and again between those two positions. When the "500 speed version" of him reaches the end of the barbed wire everything is normal again. I have absolutely no idea why this is happening.

# Answer
> 2 votes
This code is what is responsible for making your soldier blink/teleport:

```
runningTime += Gdx.graphics.getDeltaTime();
positionX = speed * runningTime;

```

Once the soldier hits the barb wire, it will change speed every frame: frame 1 it will go slow because it hits the barb wire, so the `positionX = speed * runningTime;` will then bring him to an earlier position, frame 2 "ah! I'm no longer in the barb wire, they're far up ahead, so let's go fast again!", so the speed is now fast, and so this line will make it go straight into the barb wire again.

We generally don't move entities based on "running time", as you're using; we move them based only on the delta time and their speed/acceleration.

What you want is probably something like this:

```
positionX += speed * Gdx.graphics.getDeltaTime();

```

Instead of setting the position based on the total running time, you move the entity based on what happened since last frame. This will take their new speed into consideration, with their current position.

---
Tags: java, libgdx
---


# Question
Title: how to reset etsa function GetJoystickNames in unity?
the problem is that if I connect a command the array GetJoystickNames increases an index but if you disconnect it does not reduce the index and continues counting as if it were connected

# Answer
> 2 votes
You don't. As per the GetJoystickNames documentation (version 2019.1):

> Note that some entries in the array may be blank if no device is connected for that joystick number.

As such, the length of the array is not intended to correspond to the number of connect joysticks.

---
Tags: unity, unityscript
---


# Question
Title: How to reference a GameObject from the Scene Hierarchy in C#?
I am a novice in Unity. I have a Game Object named 'courtsuit'; you can see it in my Scene Hierarchy panel here:

I added that object instance to my scene by dragging an OBJ file from my Project Assets folder into the Scene Hierarchy panel.

Now I want apply a material `man` to the game object at runtime. That is, when I click a button, that game object needs to change its material.

I tried and succeed by attaching a script to game object itself:

```
Material SphereMaterial;

// Use this for initialization
void Start()
{
    SphereMaterial = Resources.Load<Material>("Materials/man");
    if (SphereMaterial == null) Debug.Log("mat null");
    else Debug.Log("mat not null");
    Debug.Log("new Material: " + SphereMaterial.name);
    MeshRenderer meshRenderer = GetComponent<MeshRenderer>();

    // Get the current material applied on the GameObject
    Material oldMaterial = meshRenderer.material;
    Debug.Log("Applied Material: " + oldMaterial.name);
    // Set the new material on the GameObject
    meshRenderer.material = SphereMaterial;
}

```

But I don't know how to do this from an OnClick script on a different object, because I don't know how to locate the object in my Scene Hierarchy using C# script.

I want to do something like this:

```
public class ButtonHandler : MonoBehaviour {

    public void ButtonInteract()
    {
        Debug.Log("changing matriel ");
        // Change the material of the game object here

    }
}

```

How can I change the Game Object `courtsuit's` material to a material named '`man`' from my `Resources/Material` folder using C#?

# Answer
The simplest way is to expose a public variable of the types you want to work with:

```
public class MaterialChangeButtonHandler : MonoBehaviour {

    public MeshRenderer rendererToChange;
    public Material materialToChangeItTo;

    public void ButtonInteract()
    {
        rendererToChange.sharedMaterial = materialToChangeItTo;
    }
}

```

This will add two editable fields to the Inspector interface for this script. One for a MeshRenderer - you can drag your scene instance of your object into this field, or click the circle next to the field to choose a MeshRenderer from a list of scene objects. The other for the material to apply - you can similarly drag your material from the Assets folder, or click the circle to choose it from a list.

Referencing GameObjects and their components is covered in just about every Unity tutorial out there, so please take the time to work through some beginner's training material to get a hang of the basics of the engine. This will help you form more focused questions when you come across something the tutorials didn't cover.
> 2 votes

# Answer
I successfully changed material at runtime

```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ButtonHandler : MonoBehaviour {
    GameObject manObj;
    MeshRenderer m;
    // Use this for initialization
    void Start () {
        manObj= GameObject.Find("courtsuit/g_CMan0205_HD2_O01P01_S_CMan0205_HD2_O01P01_S");
        if (manObj== null) Debug.LogError("game obj null");
        else Debug.Log("game NOT null");

        m = manObj.GetComponent<MeshRenderer>();
        if (m == null) Debug.LogError("mesh obj null");
        else Debug.Log("mesh NOT null");
    }

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

    }

    public void ButtonInteract()
    {
        Debug.Log("Hello chaning matrieal ");
        Material SphereMaterial = Resources.Load<Material>("Materials/man");
        if (SphereMaterial == null) Debug.LogError("mat null");
        else Debug.Log("mat not null");
        Debug.Log("new Material: " + SphereMaterial.name);
        m.material = SphereMaterial;
    }

}

```
> 0 votes

---
Tags: unity, c#, gameobject, materials
---


# Question
Title: How to enable antialiasing for SVG Images?
My game has vector icons and sprites, like this one:

Its quality disappoints me. I guess that antialiasing is disabled here for some reason, but have no idea how to turn it on.

The problem is only with UI component **SVG Image**. **Sprite Renderer** seems to not have this issue:

Regular **Image** does not support vector icons. I tried this approach.

MSAA is enabled on **Camera** and in **Quality** settings. When it's disabled, second sprite becomes exactly the same as first.

---

Unity version: 2018.2.7.f1 for Linux
Vector graphics package version: 1.0.0-preview.23

---

I will accept a solution or an optimal workaround of any complexity. But please don't suggest using raster images.

Why?

* I have to compress them because the game is for WebGL and I already had problems with memory because of textures. Vector sprites take less memory.
* Without mipmaps icons are pixelated. With mipmaps, they look blurry. They are all power of two, but at different scales. They are even blurred different, some more, some less. I can't use fixed-sized sprites because there's an animation that changes zoom, and canvas will rescale in fullscreen.

Vector guns are to the left, raster ones with mipmaps - to the right. Thin black border lines are gone.

# Answer
> 5 votes
Antialiasing in overlay canvas is broken and won't be fixed. However, there's a workaround that worked for me:

## Set the canvas Render Mode to Screen Space - Camera, and then set its Render Camera to your main camera.

Antialiasing will work. It breaks some features, spotlight masks for example, but it's okay because I don't use them. More info in this thread on Unity forum.

If you have a separate canvas for background, you will need to change it too, because overlay canvases are rendered over other canvases.

---
Tags: unity
---


# Question
Title: Handling non-automatable, repetitive, game tasks
A problem I'm currently having with a project of mine is deciding how to handle repetitive, but important, in-game tasks.

As an example (Though there will be many other instances of this), earlier in the game, the player must smelt and shape iron without modern tools. After iron ore has been smelted, it must be shaped into tools, this requires manual labor.

So how are some ways I could handle the shaping process (A repetitive, time consuming, task)?

Having the player sit in a GUI until the shaping process is complete is obviously not a great idea.

I don't want to make the process instant and simply rely on the speed of the smelting process to cull production, as the player could just utilize a huge number of furnaces to bypass that.

For other reasons, it would be incredibly difficult and time consuming to create a short mini-game for each of these situations.

Is there an easy way to solve this?

# Answer
Since you don't want to make a mini game I'll recommend a leveling system for blacksmith or similar skill.

Leveling is a great way to reward players for doing a tedious task over and over again. When a play levels you can upgrade their abilities. As in your case you could decrease the time the player has to shape the metal. This is similar to the real life counterpart where you are doing something new it would take you more time to accomplish something. Sooner or later you will progressively get better at it.

Here are some abilities I can think of currently:

* Some percentage of faster speed
* Increased chance of doubling ore
* Increased chance of sharper tools / more durabilty
> 2 votes

# Answer
Repetition and waiting are often by far the least fun game design choices you can make as a designer. If it's in any way possible, avoid mechanics which aren't fun. You as the designer decide what's "important" and what the player is "required" to do. There is nothing wrong with one-click instant crafting iron ore into ingots and ingots into equipment. No player ever complained about a game making them spend too little time looking at progress bars.

But I could think of two examples where mechanics like that are actually used in a smart way.

There are games which use repetition and waiting mechanics in an evil way: Freemium games which use them as a nagging mechanic to encourage the player to pay money to skip the waiting and repetition. This is an example of hostile design: You make parts of the game intentionally bad, so the player pays you money to get to the good parts. If you want to create such a skinnerbox game designed to extract microtransactions from your players, sure, go ahead. I'm not judging you. I am just not going to play it.

But I also know at least one game which usees such mechanics in a good way: *Factorio*. In the beginning it forces the player to craft things manually and wait for the crafting process to be completed. But it does so for solely one purpose: To encourage the player to automatize crafting. Automatizing things is the primary gameplay theme of Factorio. They are punishing the player for doing it the simple way (hand-crafting) instead of the smart way (building a factory to do the crafting for them). This is a pretty good way to push the player into the direction where they get the most fun out of the game. But this only works for one reason: The game gives the player the tools they need to automatize the tedious tasks away. If you want to use drudge work as a way to teach the player to explore more efficient ways to perform these tasks, make sure that these more efficient ways actually exist and are within the player's reach.

If you can pull that off well, then I am looking forward to playing your game.
> 3 votes

# Answer
# Let it take some time, but happen in the background

Some survival games allow the player to move around and do other things while crafting. The GUI is there and has all the usual inputs and progress bars, but it can be closed and will keep "working" in the background. This serves the purpose of limiting production (as long as only one item can be made at a time) without forcing the player to just sit around idly, which is especially important in these kinds of games since you usually need to craft *a lot*.

This approach might seem counterintuitive at first ("Why can my character pick berries and build a shovel at the same time?") but don't forget that the typical 10-minute day/night cycle represents an entire 24 hours in which the character probably does dozens of things not depicted in the game specifically *because* they are boring and repetitive.

Let's stick with the survival game example. Those games don't present the player with a cutscene or progress bar for every time they eat, poop, wash their hands, do the dishes. They let them worry about *what* to eat and *how to procure it*, and then imply that the rest is taken care of. The same can be done for shaping your iron. Let the player worry about *where to get it from* and *planning what to craft*, including how long it'll take and what tools they need in what order, then imply that the character will set apart a portion of their day to get the manual labour done.
> 1 votes

---
Tags: game-design
---


# Question
Title: 2D game background art and assets, sketch / drawing size and resolution for a 1080P PC Console game?
I am a new game developer, working on a 2D platformer game.

I am working with my friends who can make sketches on paper and import them to Photoshop to paint, as none of us have worked on an actual game before we have no idea as to what scale /dimension to use while sketching (the background image for eg.).

I have always been a programmer and have only worked with blocks as placeholders while learning. So I have no idea how to communicate with the artists on what resolution or scale they should use or what type of assets I want.

My Required result is:

* I want a game which should look good on a 1080p screen.
* I want a 16:9 ratio for the game, with black bars at the bottom and top like movies.
* It should be scalable to fit all resolution screens(I am targeting PC and console (future)release for the game).
* You can imagine Guacameele as a reference for the art style.

My Specific questions are:

1. How should I communicate the technical aspects of the art to the artists for character sprites / background images and items?
2. Is sketching out an image and taking a photograph and importing to photoshop a good way to work on the assets? If not what should be done?
3. Should all the assets be of the same size, as I want a 1080p game and suppose if the background is 1xsize should the character be 1/6xsize or the same size as the background asset and scaled down in Unity(I am using unity for development)?
4. What is the correct way of working with sprites in such a case, which image format should I use, some other tools I should be using or some guide or guidelines that everyone follows will be helpful.

Thanks !

# Answer
> 1 votes
1. In pixels. Do not discuss DPI, and if your artists ask you about DPI, tell them *We are working in pixels. This is not going to print. Use your rulers.* The reason is that device displays are counted in pixels and you generally need to have an idea of what size your graphics are going to look crisp at, on the typical device you are targeting. You could use photos of whiteboard sketches; I find this enjoyable as you have the ease of a whiteboard plus easy import with modern phones. Unity supports pixel scales by allowing you to create pixel-perfect 2D game graphics / UIs.
2. It's perfectly fine. You can then scale it up or down according to your desired pixel size, and flesh it out further in Photoshop. (See caveat below these 4 points, however.)
3. The relative sizes are yours to decide (you will probably need to experiment to get the right feel)
4. PNG for irregularly shaped sprites, JPG for backgrounds or other completely rectangular shapes. This is the standard rule. You can improve the compression using either Photoshop's `Save for Web`, or e.g. ImageMagick on the command line (this can be easier if you want to e.g. batch process all images before a build - all depends how your production pipeline is set up).

I strongly suggest you put NO serious effort into the graphics until you have determined the sizes that makes the game *playable* and the UI *usable* on target devices. This is how a lot of time is wasted on a good many amateur game projects. You will want to wait as long as you possibly can before you start refining the graphics; usually this is a key difference between *pre-production (code prototyping)* and *production* phases (where code has generally crystallised and content is the primary focus). For that matter, get used to lolfaces for now as that is all you'll be seeing for a while, if you're wise.

Remember also that just because you created your graphics to display pixel perfect on one device, doesn't mean it has to do so on all. Perhaps you are more interested in always having the player character be, say, 1/6th of the screen height in landscape mode. In that case, you may have an ideal device like the iPad 3 where the player sprite is indeed exactly 1/6th of 1536 pixels; but on other devices, in order to be 1/6th of the screen high, it may need to be scaled up or down. That is fine, and Unity's 2D capabilities suppor this, although learning that process is going to be down to you.

# Answer
> 0 votes
To Dear Rangot,

May I say something about 2D Sprite in Game Art?

512x512px is a single piece of a Character/ a small asset/ a terrain for 2D Android Game Art Sprite excluded Animation and Multiple sprites.This is default starting sprite size for Junior Game Artists.

For Art, The character if on the single Sprite, the foot need to touched the ground. If you want to draw multiple sprites in 1 .png, that will be in another option...

More: Senior Game Artists may know more proffesional techniques. And, different Game Company may have different setting, you can ask Art Director for the sprite size setting. If you are doing for your own Indie Game, or For educational purpose or Self-Learning, 512×512px for a single sprite is common size for Android Games.

...

I'm not Game Programmer, I'm very admire you and them. For technical... :

If you want to saves Bytes, KB and MB, then you can use what you had Learned, or User: Engineer's Answer or DMGregory's Technical Scale Technique, more proffesional in Program technique. Game Programmers more sensitive and more advance in controls the Game Art fit Technical Design Part of Game Development. Here's DMGregory Technique link: What sprite size should I use for 2D game?

And, for me, Game Artist, Seniors always told me a Android Game Size need to not larger than 150MB (basic). If it is a High-End game or MMORPG game, the game size will absolutely used maybe 1GB space or more than 150MB. And, Senior told me leave this to the Technicians or Programmers.

Thank you.

From, Junior Android Game Artist

---
Tags: 2d, sprites, pipeline
---


# Question
Title: how to make UI material ignore scene lighting, have same brightness as albedo?
I have a material on a quad surface object that is parented to a canvas for a pause menu. The material is animated (materials on UI elements such as canvases cannot be animated because of \[reasons\], so I had to use a quad surface). Even though it is parented to the canvas, it gets lit by lights in the scene. So I set the lights up to ignore it. But now the quad surface appears darker than other UI elements (which are as bright as their default textures).

How do I make the material brightness for this quad object as bright as its albedo texture?

# Answer
Oh. So I tried applying an emission before and it didn't work because I assumed I couldn't use the albedo texture for emission.

But this is exactly untrue.

Using the same texture you used for the albedo as an emission map gives the material the same brightness you have in a picture viewer (assuming all other scene lights ignore the material).

EDIT: a wrinkle: If you dare to adjust the multiplier, it is very difficult to be sure when you've returned to a default setting.

@DMGregory reminded me that there is a thing called an "Unlit" shader that fits this purpose exactly. Thanks to him.
> 1 votes

---
Tags: unity, shaders, lighting, gui, materials
---


title: Unity Round (Circle) Buttons

text:
# Question
Title: Unity Round (Circle) Buttons
I have been using Unity and C# scripting now for the past 2 or 3 weeks. So yeah I am very new to Unity and C#.

I wanted to know if there is a way to make a round (circle) button without using a rect.

The problem I have now, I am using a 2d sprite to make the button appear round, however when you hover or click within the rect, it still works.

I saw this asset in the asset store called Alpha Raycaster.

I cannot afford to pay for it right now so I was wondering if there is a free alternative to the Alpha Raycaster for now.

Does anyone know how we can solve this issue? I obviously only want the button to function when the user hovers or clicks within the sprite and NOT on the alpha surrounding the sprite.

# Answer
> 3 votes
This is much simpler than it seems. Unity has functionality built in for this.

```
theButton.alphaHitTestMinimumThreshold = 0.5f;

```

Documentation

What this does is only register hits from the raycast if the pixel hit has an alpha of 0.5 or greater.

# Answer
> 2 votes
There is one easy way that only works for round Shapes. In your Button callback you could test the distance of the mouse from the center of the button against the radius of the button and only trigger the click or hoover effect when it is within the buttons radius.

But since you are new, maybe focus on making some gameplay rather than the button design. While a good look and feel are important, i believe a working game will motivate you more. Try focusing on what you can do, instead of what you can't.

# Answer
> 1 votes
YES! THANK YOU @trollingchar.

I added the code to a script and attached the script to the button. that is exactly the functionality i was looking for.

check out the link to the code: https://forum.unity.com/threads/none-rectangle-shaped-button.263684/#post-2146709

```
using UnityEngine;
using UnityEngine.UI;

[RequireComponent(typeof(RectTransform))]
[RequireComponent(typeof(Image))]
public class RaycastMask : MonoBehaviour, ICanvasRaycastFilter
{
    private Sprite _sprite;

    void Start ()
    {
        _sprite = GetComponent<Image>().sprite;
    }

    public bool IsRaycastLocationValid(Vector2 sp, Camera eventCamera)
    {
        var rectTransform = (RectTransform)transform;
        Vector2 local;
        RectTransformUtility.ScreenPointToLocalPointInRectangle((RectTransform) transform, sp, eventCamera, out local);
        // normalize local coordinates
        var normalized = new Vector2(
            (local.x + rectTransform.pivot.x*rectTransform.rect.width)/rectTransform.rect.width,
            (local.y + rectTransform.pivot.y*rectTransform.rect.height)/rectTransform.rect.width);
        // convert to texture space
        var rect = _sprite.textureRect;
        var x = Mathf.FloorToInt(rect.x + rect.width * normalized.x);
        var y = Mathf.FloorToInt(rect.y + rect.height * normalized.y);
        // destroy component if texture import settings are wrong
        try
        {
            return _sprite.texture.GetPixel(x,y).a > 0;
        }
        catch (UnityException e)
        {
            Debug.LogError("Mask texture not readable, set your sprite to Texture Type 'Advanced' and check 'Read/Write Enabled'");
            Destroy(this);
            return false;
        }
    }
}

```

for those that are too lazy to follow the link :) here is the code snippet.

It was posted by @senritsu

if i could hug you right now i would :)

---
Tags: unity, c#, collision-detection, gui, mouse
---


# Question
Title: Art Guide Theory: Lighting an Game Environment (Objectives, approach/workflow and mood) in PBR
What's the theory behind the Lighting an Game Environment in a Physically Based Renderer?

As far my research, lighting an scene is done with different Rules and Different Ways of Lighting an Scene depending upon the scene.

For an Interior scene - Omni Lights, Area Lights, point Lights and Spot Lights with baking is used to give proper amount of illumination.

whereas for an Outdoor Scene - Directional Lights, Area Lights, Point Lights are used to illuminate the scene with baking Lightmaps.

Usually to Light Individual Objects, 3 point Lighting is used and colors signify the Mood of the Scene.

But, the 3 point lighting is unfavorable for Game Environment, So, what's the Good way to start and what are the main objectives in Lighting an Scene?

How Lighting an Scene Contributes to the mood of the scene? like here -

# Answer
> 0 votes
**Lights in Game Render by Game Engine**, e.g. Unreal Engine, SnowDrop Game Engine and more.A Game World is as huge as a Big Land included many 3D Assets. Here's PBR study for game. And, **Peachpit, Lighting Principle in Game Design.** Retrieved on http://www.peachpit.com/articles/article.aspx?p=174370

**3 Point Light is rarely seen in Game...** Because 3 Point Light called "Studio Light", where can be seen in Photography Studio when a Photographer want to shoot a Fashion, Portrait, Product Photography.

**What makes Game Environment different...Theory of Game Design:** Because of the **Game Mechanics, Game Design (Rules), Level Design** and more.**Game Lighting Technique in Game Design is used to Direct & Attract Players' Eyes about: Where is the Game Objective, Mission, Quest will be on. Where is the direction on Next Level will be.** So, at the end, the Lighting of Game Environment is different than 3-Point Light. The Game Environment will included both Indoor and Outdoor. These Lighting Technique completely been controlled by Level Design matched "game objective, features, Game Mechanics, Game Art-styles, game Flow, levels, and more" at Pre-Production until Production Process. For example, Kratos in God of War 3, he saw a Sun Light surrounding a Treasure (**Light direct Player's eyes look at the point**). Plural Sight. Lighting for Games. Retrived from https://www.pluralsight.com/blog/film-games/understanding-the-importance-of-lighting-for-games

---
Tags: 3d, lighting, level-design, art
---


# Question
Title: What would be the benefit of placing all of a room's textures on an object outside of the camera's view?
*Pokémon XD: Gale of Darkness* does an odd thing with textures. As described in this video, all textures for a room are placed on an object outside of the camera's view:

> This kind of caught me off-guard. I wasn't really expecting anything to be on the other side of this room, but when I turned the camera around, it was all the textures that were inside this room plastered into one spot. Now I can't explain this whatsoever; I've never seen this in any other game that I've covered. But what's really odd is that this isn't an isolated case, this happens periodically throughout *Pokémon XD*. Now it's not in every room and city, but from time to time, you will see its textures on some type of object in an area that's off-camera.

What would be the benefit of doing this? The scene is shown to the player all at once after loading, so I'm not seeing how it would help with loading times or anything.

# Answer
Even though the scene is presented to the player “all at once,” a well-known dummy object that has all the textures mapped to it could *conceivably* be part of a technique to pre-load the texture data as part of a streaming load phase in parallel with loading the geometry or other data.

However in the specific case of these screenshots, it’s probably simply that the surfaces were known to not normally be visible and as such have “default” texture coordinates that cover the whole atlas otherwise used by the room. The fact that it doesn’t always show up and that the objects or surfaces affected are part of existing geometry would, I’d say, also indicate that this is the case.
> 4 votes

---
Tags: textures
---


# Question
Title: How can I execute a C# script even if my game is closed?
I've made a game with Unity and I want to execute a C# script that runs even the game was closed.

I searched a lot but didn't find anything.

# Answer
> 2 votes
I have not seen a way to do this in Unity, which makes sense. Unity is not developed to run as a service. However, it has something close. Look up Unity Application.runInBackground. You can couple this with the OnApplicationFocus event to determine the state. Normally a game just pauses in the background.

But for clarity, you are specifically asking about running code after the program has been **closed**. This is typically not done with Unity, but what most applications do, is pair the installation with a service that will run in the background. In general, it is considered a bad practice for user interest.

> When user's discover your application is eating battery, bandwidth and processing cycles when not in use, they will assume it is for spying on them.

What more places might choose to do, is just execute something at the start or end of the programs execution. To capture the ending event, even when not done from a close button, use OnApplicationQuit. Then, using a timed event to announce things to a user, such as this one for Android.

> Events are how many apps give notifications on mobile when not running. On exiting, the games will usually understand based on timing, when an event will occur. Such as building X will complete in 3 minutes and 41 seconds, or the next online game cycle starts at midnight.

---
Tags: unity, c#, c++, dll, dependency-injection
---


title: Architecture of networked game engine

text:
# Question
Title: Architecture of networked game engine
So after working on my game engine for 2 years, I've decided to step into the networking environment. I just don't know if it's a good idea to rewrite the engine, or how much work it will take (but still want to try it). I'm little bit confused by some approaches, so that's why I'm here.

In short I have an architecture like this: There is a main object, that controls the whole engine world (physics steps, rendering, audio, input, entities). Then there is a Game instance that is running inside the loop and "creating the content of the game".

I already started with ENet, created a small console chatting app - but packets were just strings. But I'm not sure if I understand the concept of game networking, so here is my idea:

There is a server and clients. Server is controlling everything. Client sends messages.

So basically: When client connects to the server, server creates new entity. Now, for example, when client presses `A`, packet is sent to a server containing this information. Server will process it, moves the entity.

Am I right?

So basically, clients does not have anything, except input controller and keyboard. So when they press keys, action is done. And rendering for the scene render, but all they receive is just a "image" of the scene from the server? Or is there something I miss?

Thanks in advance.

**Edit1** And also wondering, everything, like physics manager, or whole scene with entities, are present only on the server machine?

# Answer
> 7 votes
**TLDR** \- start simple and build up. Getting to AAA quality networking in an action game is complicated but may not even be necessary for your game.

> So basically: When client connects to the server, server creates new entity. Now, for example, when client presses 'A', packet is sent to a server containing this information. Server will proccess it, moves the entity.
>
> Am I right?

Basically, yeah. There are multiple networking architectures, but the common server-authoritative model used in most real-time action games follows that model.

As Bram noted in comments, though, the client typically does have more work to do to overcome network latency even for non-twitch games. The simplest version is to make sure the client *acknowledges* input before waiting for the server response. Even your Web browser does this (clicking a link animates right away even though it might take some time for the new page to load).

Likewise, the server might have to do a lot of work to overcome the latency as well, depending on the type of game. The server has to keep in mind that by the time it receives any input from the client(s), the player had actually entered that input many milliseconds ago. A common approach is to use object history buffers so the server can simulate "back in time" based on its estimate of when the input was actually pressed on the client.

Going back to the client, some deeper prediction can be required for inputs. For example, a client might immediately respond to input and move, but then adjust that movement based on the *eventual* response from the server. Various techniques can be applied to smooth over the times when the server response contradicts the client prediction.

Further, the client can't *just* apply movements from the server for other objects, because that would cause objects to only move when packets come in. A client might have its own small history buffer of positions from the client and smoothly interpolate between them; or the client might *extrapolate* and predicate movement (though this will result in frequent rubber-banding in many games).

When local player A observes remote player B, local player A can see their own inputs immediately. However, remote player B's movements will be delayed by the time it takes for B's input to get to the server and then back down to player A's client. Every player sees a very stale version of every other player, which can be problematic for games where players are meant to interact at close range frequently. This often just relies on the actual game design avoiding creating situations where this can matter much, as well as on history buffers and the like.

There's a whole 'nother topic about timing and syncing of certain kinds of action, where you might want all players see an ability activate simultaneously despite network latency. Actions might have a warmup animation that is compressed on remote clients so that everyone sees the action happen at near the same instant despite the network latency.

I recommend that you look at the classic Halo GDC talk https://www.youtube.com/watch?v=h47zZrqjgLc.

> Edit1 And also wondering, everything, like physics manager, or whole scene with entities, are present only on the server machine?

That depends a bit on what you mean by "physics."

Typically, the server is only going to do physics on objects that *affect gameplay*. This is both to cut down on server processing costs (physics is CPU intensive) and to cut down on bandwidth costs (synchronizing every little piece of rubble would use a lot of bandwidth).

Depending on the game, the server might do almost no real physics (just very basic capsule movement and ray casts); or the server might do full physics on a small class of objects (set pieces that can move and players can stand on or hide behind); or the server might do full physics on a variety of objects (for games where the environment is highly interactive and can be used against other players).

All the rest of the physics will be done purely on the client. Small debris, background objects, VFX physics, etc. The result will be physics objects that will interact naturally with each other but will be non-collidable or weightlessly pushed around by any server-authoritative objects (like players).

The short version of that being that both server and client need to do "physics" of some variety, but typically on different sets of objects. The client will still apply positions/velocities from server objects into its local sim but can't apply any counter-force (these are typically called "kinematic" objects in most physics libraries/toolkit).

# Answer
> 1 votes
If the client has a 100ms ping to the server, then there would be a delay of at least 6 extra frames between the user pressing a button, and seeing the result, probably more.

Even adding 1 frame from double-buffered rendering causes perceivable delay.

This means that client/server gaming is a lot more complicated than this, and prediction is involved.

---
Tags: c++, architecture, networking
---


title: Way to store object reference?

text:
# Question
Title: Way to store object reference?
I have a project where a minion overlaps the tower.

Needless to say, the problem occurs when more than one minion overlaps the tower at the same time.

It turns out I've figured out how to go through this problem, or at least ways.

It is only to condition a certain event/function once and define a loop.

I can cause the damage to be applied to the tower correctly if I make the code in the tower (adding an information about the amount of minions overlapping the tower).

**Blueprint:**

The problem is that the overlap oscillates. This disrupts the reception of variable information, since the minion at some point stops overlapping the tower.

**I tried to fix this by adding a parameter to the event, but using it I can not reference the tower variable:**

Not even using the construction script:

I thought of something like a variable receive the reference of the tower, and if at the time of receiving the variable the reference of the tower fails, use it.

*But all that I tried in this sense, something similar happened to that shown in figure 2.*

# Answer
> 0 votes
**Finally. To store the information of the tower that is colliding with the minion, just create a parameter with the type of the tower object, and not as an actor:**

That way, since the event is called only once because of the boolean variable, everything works out. The reference does not fail and the damage to the tower is applied correctly regardless of the amount of minions.

---
Tags: unreal-4, blueprints, overlay
---