# Question
Title: How to use SyncVar/Command/Rpc in Unity to set the AnimSpeed for each player in the scene separately
Im making a simple as possible scene in Unity for mulitplayer game. The character has a walking animation of which the speed is to be set exactly the same as the Z velocity relative to the object.

I have Unity Network Manager etc on the object and they spawn fine on multiple computers. They move fine also in terms of transform position, rotation etc.

On the screen that I am currently moused onto and active with, the animation speed also does work and stops at zero etc. But for the inactive screen, the walking animation is always at 1.00 default.

I've been trying to use a SyncVar to control the animSpeed. But I read that this is incorrect because Im sending the change to it via a call in the Client instance and not the server. It says I should use COMMAND but I am unsure if this needs to be within a script on my Player Object or do I need to make a script that attaches to the Network MAnager or something and would hold all the animSpeeds for each player object? (I kinda feel Unity Networking will do that, it says that SyncVars are handled automaticallly and updated when they change to all clients. - This implies to me I should be putting the COMMAND on the script for my Player object.)

Here is the script I have now that doesn't work correctly:

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

public class Player_mp : NetworkBehaviour {
CharacterController characterCont;
Animator anim;
public float walkSpeed, sideSpeed, turnSpeed;
Vector3 movementInWorldSpace;

[SyncVar] float animVelZ;

public override void OnStartClient()
{
    characterCont = GetComponent<CharacterController>();
    anim = GetComponentInChildren<Animator>();

}

void FixedUpdate () {
    if (!isLocalPlayer)
    {
        return;
    }

    float mouseX = Input.GetAxis("Mouse X");
    transform.SetPositionAndRotation(transform.position, Quaternion.Euler(transform.eulerAngles.x, transform.eulerAngles.y + (mouseX * turnSpeed * Time.deltaTime), transform.eulerAngles.z));

    Vector3 movement = new Vector3(Input.GetAxis("Horizontal") * walkSpeed * Time.deltaTime, 0, Input.GetAxis("Vertical") * sideSpeed * Time.deltaTime);
    movementInWorldSpace = transform.TransformVector(movement);

    Vector3 velLocalised = transform.InverseTransformVector(characterCont.velocity);
    //if (velLocalised != Vector3.zero)
    //    Debug.Log("Vel = " + velLocalised);

    animVelZ = velLocalised.z;
    if (animVelZ < 0)
        animVelZ *= -1;
    anim.speed = animVelZ;
}

private void LateUpdate()
{
    if (!isLocalPlayer)
    {
        return;
    }

    characterCont.Move(movementInWorldSpace);
}

}

```

I've also tried this version with a method CmdSetAnimSpeed():

```
public class Player_mp : NetworkBehaviour {
CharacterController characterCont;
Animator anim;
public float walkSpeed, sideSpeed, turnSpeed;
Vector3 movementInWorldSpace;

[SyncVar] float animVelZ;

public override void OnStartClient()
{
    characterCont = GetComponent<CharacterController>();
    anim = GetComponentInChildren<Animator>();

}

void FixedUpdate () {
    if (!isLocalPlayer)
    {
        return;
    }

    float mouseX = Input.GetAxis("Mouse X");
    transform.SetPositionAndRotation(transform.position, Quaternion.Euler(transform.eulerAngles.x, transform.eulerAngles.y + (mouseX * turnSpeed * Time.deltaTime), transform.eulerAngles.z));

    Vector3 movement = new Vector3(Input.GetAxis("Horizontal") * walkSpeed * Time.deltaTime, 0, Input.GetAxis("Vertical") * sideSpeed * Time.deltaTime);
    movementInWorldSpace = transform.TransformVector(movement);

    CmdSetAnimSpeed();
}

private void LateUpdate()
{
    if (!isLocalPlayer)
    {
        return;
    }

    characterCont.Move(movementInWorldSpace);
}

[Command]
void CmdSetAnimSpeed()
{
    Vector3 velLocalised = transform.InverseTransformVector(characterCont.velocity);
    //if (velLocalised != Vector3.zero)
    //    Debug.Log("Vel = " + velLocalised);

    animVelZ = velLocalised.z;
    if (animVelZ < 0)
        animVelZ *= -1;
    anim.speed = animVelZ;
}

}

```

Could anyone tell me how exactly I can make it so the 'animVelZ' speed can be set properly on the network and so they all stop their feet if not moving on every screen of the game? Thanks for any help

# Answer
> 0 votes
Ok, well almost by trial-and-error I seem to have fixed this. I will post what I did here in case it ever helps anyone, but hopefully it is correct. All I know is the speed of the animation is now syncing on all screens (ie. The Host server-client and all other remote clients)

I had to use ClientRpc instead of Command, and then in Update i put if isServer, then a call to the Rpc I made:

```
public class Player_mp : NetworkBehaviour {
CharacterController characterCont;
Animator anim;
public float walkSpeed, sideSpeed, turnSpeed;
Vector3 movementInWorldSpace;

float animVelZ;

public override void OnStartClient()
{
    characterCont = GetComponent<CharacterController>();
    anim = GetComponentInChildren<Animator>();
}

void FixedUpdate () {
    if (isServer)
    {
        RpcSetAnimSpeed();
    }

    if (!isLocalPlayer)
    {
        return;
    }

    float mouseX = Input.GetAxis("Mouse X");
    transform.SetPositionAndRotation(transform.position, Quaternion.Euler(transform.eulerAngles.x, transform.eulerAngles.y + (mouseX * turnSpeed * Time.deltaTime), transform.eulerAngles.z));

    Vector3 movement = new Vector3(Input.GetAxis("Horizontal") * walkSpeed * Time.deltaTime, 0, Input.GetAxis("Vertical") * sideSpeed * Time.deltaTime);
    movementInWorldSpace = transform.TransformVector(movement);

}

private void LateUpdate()
{
    if (!isLocalPlayer)
    {
        return;
    }

    characterCont.Move(movementInWorldSpace);
}

[ClientRpc]
void RpcSetAnimSpeed()
{
    Vector3 velLocalised = transform.InverseTransformVector(characterCont.velocity);
    //if (velLocalised != Vector3.zero)
    //    Debug.Log("Vel = " + velLocalised);

    animVelZ = velLocalised.z;
    if (animVelZ < 0)
        animVelZ *= -1;
    anim.speed = animVelZ;
}

}

```

animSpeed , nor any of the variables used, needed to by a SyncVar

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


# Question
Title: While loop running in thread, but not doing anything [C++]
I am trying to multi-thread my game so that one thread updates and renders the player, while the other listens for inputs. I used a while loop to keep my detached thread running in the background, which is working, but my player isn't moving even though the code tells it to do exactly that. If I put `MessageBox(NULL, "Testing", "Alert", NULL)` in Player::update or Player::draw in Player.cpp, the window spams message boxes, which means the code IS running, but the player is NOT moving. Is it a problem with one of the Player functions or with the thread itself?

**Window.cpp**

```
#include <windows.h>
void quit();
void setup(HDC, PAINTSTRUCT, HWND);

const char g_szClassName[] = "myWindowClass";

LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
    switch (msg)
    {
    case WM_CLOSE:
        DestroyWindow(hwnd);
        quit();
        break;
    case WM_DESTROY:
        PostQuitMessage(0);
        break;
    case WM_PAINT:
        PAINTSTRUCT ps;
        HDC hdc;
        hdc = BeginPaint(hwnd, &ps);

        setup(hdc, ps, hwnd);

        EndPaint(hwnd, &ps);
        break;
    default:
        return DefWindowProc(hwnd, msg, wParam, lParam);
        break;
    }
}

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
    LPSTR lpCmdLine, int nCmdShow)
{
    WNDCLASSEX wc;
    HWND hwnd;
    MSG Msg;

    wc.cbSize = sizeof(WNDCLASSEX);
    wc.style = 0;
    wc.lpfnWndProc = WndProc;
    wc.cbClsExtra = 0;
    wc.cbWndExtra = 0;
    wc.hInstance = hInstance;
    wc.hIcon = LoadIcon(NULL, IDI_APPLICATION);
    wc.hCursor = LoadCursor(NULL, IDC_ARROW);
    wc.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
    wc.lpszMenuName = NULL;
    wc.lpszClassName = g_szClassName;
    wc.hIconSm = LoadIcon(NULL, IDI_APPLICATION);

    if (!RegisterClassEx(&wc))
    {
        MessageBox(NULL, "Window Registration Failed!", "Error!",
            MB_ICONEXCLAMATION | MB_OK);
        return 0;
    }

    hwnd = CreateWindowEx(
        WS_EX_CLIENTEDGE,
        g_szClassName,
        "Testing!!!",
        WS_OVERLAPPEDWINDOW,
        CW_USEDEFAULT, CW_USEDEFAULT, 800, 600,
        NULL, NULL, hInstance, NULL);

    if (hwnd == NULL)
    {
        MessageBox(NULL, "Window Creation Failed!", "Error!",
            MB_ICONEXCLAMATION | MB_OK);
        return 0;
    }

    ShowWindow(hwnd, nCmdShow);
    UpdateWindow(hwnd);

    while (GetMessage(&Msg, NULL, 0, 0) > 0)
    {
        TranslateMessage(&Msg);
        DispatchMessage(&Msg);
    }
    return Msg.wParam;
}

```

**Main.cpp**

```
#include <iostream>
#include <thread>
#include <windows.h>
#include "Functions.h"
#include "Player.h"
using namespace std;

void draw(HDC);
void startThreads();
void checkForInput();
bool Quit = false;
HDC hdc;
PAINTSTRUCT ps;
HWND hwnd;
Player player(50, 50);

void setup(HDC hDC, PAINTSTRUCT pS, HWND hWND)
{
    hdc = hDC;
    ps = pS;
    hwnd = hWND;
    startThreads();
}

void checkForInput()
{
    while (!Quit)
    {
        if (GetKeyState(27) & 0x8000)
        {
            Quit = true;
        }
    }
}

void quit()
{
    Quit = true;
}

void draw(HDC hdc)
{
    while (!Quit)
    {
        player.draw(hdc);
        player.update();
        Sleep(16);
    }
}

void startThreads()
{
    thread mm(draw, hdc);
    thread input(checkForInput);
    input.detach();
    mm.detach();
}

```

**Player.cpp**

```
#include <windows.h>
#include "Player.h"
#include "Functions.h"

Player::Player(int xx, int yy)
{
    x = xx;
    y = yy;
}

void Player::update()
{
    x++;
}

void Player::draw(HDC hdc)
{
    rect(hdc, x, y, 50, 50);
}

```

**Player.h**

```
#pragma once
#include <Windows.h>

struct Player {
public:
    int x;
    int y;

    Player(int, int);
    void update();
    void draw(HDC hdc);
};

```

**Functions.cpp**

```
#include "Functions.h"

void rect(HDC hdc, int x, int y, int w, int h)
{
    Rectangle(hdc, x, y, x + w, y + h);
}

void ellipse(HDC hdc, int x, int y, int w, int h)
{
    Ellipse(hdc, x, y, x + w, y + h);
}

```

**Functions.h**

```
#pragma once
#include <windows.h>

void rect(HDC, int, int, int, int);
void ellipse(HDC, int, int, int, int);

```

# Answer
> 1 votes
In Windows, you're only supposed to draw, or at least you're only allowed to use the HDC from BeginPaint, in the WM\_PAINT handler. Drawing anywhere else usually won't work properly.

To trigger a repaint, call `RedrawWindow` or `InvalidateRect`.

Then do all the painting inside the WM\_PAINT handler.

# Answer
> 1 votes
The `while` loop you have above is what is called a 'busy-wait' which chews through CPU resources but does no useful work. You can do that for very short periods, but you've effectively tied up 100% of a CPU core doing nothing. A better way to do this kind of input-checking is to use a timer to regularly check for input but that yields the CPU the rest of the time. You should also make your 'quit' flag a event so that other threads can check to see if you are quitting since you need to ensure all your threads can shutdown properly to avoid crashes on exit.

On Windows, the best option is using `WaitForSingleObject` or `WaitForMultipleObjects` with a timeout. You can of course use older Win32 message-loop style timers with `WM_TIMER`, but using events, semaphores, mutexes, etc. are much more efficient.

```
HANDLE g_quitEvent;

// Should be created before you start up your threads
// We use ``CREATE_EVENT_MANUAL_RESET`` because once signaled, all threads
// that check for the quit event should get the event once it's fired.
g_quitEvent = CreateEventEx(
    nullptr, nullptr,
    CREATE_EVENT_MANUAL_RESET,
    EVENT_MODIFY_STATE | SYNCHRONIZE);
if (!g_quitEvent)
    // Error

```

```
while (!Quit)
{
   switch (WaitForSingleObject(m_quitEvent, 16 /* check at around 60 fps */))
   {
   case WAIT_OBJECT_0:
       Quit = true;
       break;

   case WAIT_TIMEOUT:
       if (GetKeyState(27) & 0x8000)
       {
           SetEvent(g_quitEvent);
       }
       break;

    case WAIT_FAILED:
       //  GetLastError() will tell you more about the failure
       throw std::exception("WaitForSingleObject");
    }
}

```

You should read Coding For Multiple Cores on Xbox 360 and Microsoft Windows. It's a little old, but still useful information.

You may also want to look at Lockless Programming Considerations for Xbox 360 and Microsoft Windows, but you really need a good grounding on basic multi-threading before attempting to use lockless models.

> Accurate game-time can also be a challenge with multi-threaded designs, so be sure to read Game Timing and Multicore Processors.

---
Tags: c++, game-loop, multithreading
---


title: Gamemaker Multiplayer Game

text:
# Question
Title: Gamemaker Multiplayer Game
I'm trying to implement multiplayer into my game using the server client model. What is the best method of synchronozing the game between the clients? What I'm thinking is that the game runs on the client, where the clients send the inputs (keyboard input for example) to the server, and the server then passes that on to the other clients, which then process that information. To make this system more robust the game would also run on the server, and the server would send synchronization packets to synchronize all the instances in the room. I can already see some potential flaws in this design, so that's why I'm asking for a better implementation. Both the server and client run in gamemaker.

To give you some context: my game is a relatively simple rpg platformer, where you have an inventory and items, player stats like armor and physical damage (the stats are almost identical to those of league of legends). You move with the arrow keys or wasd, like a regular platform game. For now I want to implement pvp, but would like to set up networking in a way that allows for npcs. I want to have a maximum of say 4 or 5 players connected at a time.

I have read up on client prediction, server reconciliation, entity interpolation and lag compensation, but it seems overkill for my application (it might not be I'm not sure).

I guess there it is somewhat acceptable to have a pure authoritative server, other than the fact that the player movement will become unresponsive, which is a big issue. Also using items and switching between then will become less responsive, which will make pvp less intense, but I can't think of a reasonable workaround for that.

Also, I am not worried about cheating as I am making this game just to have fun with friends.

Thanks.

# Answer
Rather than sending key-presses, you may be better sending actions/results.

So, for moving a character, you can send Direction and Speed. If the client does not receive a new Direction and Speed for an NPC or another player , it attempts to extrapolate from the last values (e.g. it keeps trying to move the player instance in the same Direction, at the same speed, or adds the same acceleration, etc)

Every so often, you also send the Location (X/Y/Z) to resync instances across clients.

Similarly, the server and other clients don't need to know "You pressed `A`", they just need to know "you attack with your sword".

This allows you to have your Client make a decision based on *your* actions for responsiveness, then the Server ratifies it and distributes it based on *everyone's* actions, which may retcon your result:
\- Player 1 Attacks Player 2, and their Client show this as 8 damage.
\- The "Attack" command is sent to the server, which has also just received a "Defend" command from Player 2.
\- The server decides that Player 2 blocked in time, and tells everyone that Player 2 took 4 damage, and what the new health is.

> Player 2 sees that they loose 4 health
> Player 1 sees the 8 damage the dealt is changed to 4
> Everyone else sees that Player 1 attacks, and Player 2 blocks for 4 damage

(If you play MMOs that use this system when they are at high-load, you will sometimes encounter "rubber-banding", where you move but the server doesn't receive all of the commands - when the resync happens you snap back to a previous location, like a bungee cord.)
> 1 votes

---
Tags: game-maker
---


# Question
Title: Why is the alpha value of a Sprite in LibGdx 0.99607843 and not 1?
I'm developing a game in LibGDX and one of my problems is related to the alpha value of a Sprite object.

If I create a new Sprite sprite object then `sprite.getColor().a` is equal to 0.99607843 and not 1. If I try to set `sprite.setAlpha(1)` it still sets it to 0.99607843. I also tried doing `sprite.getColor().a = 1;` but it still didn't work. My question is why is that? Is this just a limitation in LibGDX or am I doing something wrong?

(I put an issue on the official lib gdx github page. As of now the issue has been solved just because it was a duplicate of another issue, from what I get this problem is because of lib gdx, but the alpha still gets corrected on the shader side.)

# Answer
> 0 votes
The answer can be found in NumberUtils. Storing a color in a Java float can result in NaN bits being used, which Java is free to mangle, see Float#intBitsToFloat. libgdx uses 0-254 for alpha, then scales it in the shader to get it back into 0-255 range.

---
Tags: java, libgdx, game-design, sprites
---


title: How to create an even gamescore?

text:
# Question
Title: How to create an even gamescore?
Currently I'm doing an android game. My problem is the score. The game speeds up in every round and currently I'm counting the score like this:

```
private static final const int MAX_SCORE = 150;
private int countdown = 0;

public void scoreUpdate(){

   if(countdown <= 0){
      score = 0;
   }

   score += countdown;

   countdown = MAX_SCORE;
}

```

`countdown` gets constantly decreased in my game loop so the less time you take to react the more score you get. Every Tap you do correctly will start the next round and call `scoreUpdate()`.

Problem now is, that the game is speeding up, so you only get good scores the further you play the game. Does anyone has a better method to count the score more evenly?

# Answer
> 1 votes
You could always base the score on the percentage of the starting countdown:

```
switch round(8*countdown/MAX_SCORE) {
    case 0:
        break; // bottom 1/16 gives no score, but you keep playing
    case 1:
        score += 10;
        break; //2nd and 3rd 1/16 are grouped together, etc
    case 2:
        score += 20;
        break;
    case 3:
        score += 40;
        break;  //Non linear scoring makes better reactions worth much more
    case 4:
        score += 60;
        break;
    case 5:
        score += 90;
        break;
    case 6:
        score += 120;
        break;
    case 7:
        score += 160;
        break;
    case 8:
        score += 250;
        break;  // top 1/16 has a big score bonus
}

```

---
Tags: java, android, android-studio
---


# Question
Title: storing map data as file in 3d roguelike games
I'm currently designing 3d roguelike game. I need to come up with a map storing system but I'm quite new to game programming so I don't really know how to design. The map will be relatively small, it's not open world. I think it would be just like 3d version of The Binding of Isaac with first-person perspective.

I want to store map data as a file(e.g txt) but I don't know how to order them and what is necessary to store.

Answers with some examples would be very appreciated.

# Answer
> 1 votes
Think of it this way. If you are reading the file that has the map, what data would you need to accurately re-create a map?

Is your map tile based? Then for each tile you have to define things like:

* What does it look like? (assuming you are using 10 different meshes as tiles, this could be a number from 0-9 that describes what tile it is using)
* What's its location in the world? This could be either `x` and `y`, but you can also add a `z` if your maps have height as well
* Does this tile have an enemy on top? Which enemy is it? (Similar to the meshes above, you can use IDs for enemies as well) You can also save information if the enemy is still alive (in case you want to save/load an already explored map).
* Is there any treasure on this tile? Etc etc

I think this gives you an idea of how to do it. You can follow almost the same procedure if your maps are not tiled, but it might be more cumbersome.

So based on all the information, organise them inside your file for example:

* An integer for mesh ID
* 2 floats for `x` and `y` (maybe a third for `z`)
* An integer for enemy ID (0 for no enemy)
* An integer for treasure ID (0 for no treasure)

When saving a map, iterate through all tiles, and put their information in a file like this, when loading a map, read the file the same way. This is the basic idea, hopefully you can use this information for your own game.

---
Tags: maps, roguelikes
---


# Question
Title: Why is permadeath essential to a roguelike design?
Roguelikes and roguelike-likes (*Spelunky*, *The Binding of Isaac*) tend to share a number of game design elements:

* Procedurally generated worlds
* Character growth by way of new abilities and powers
* Permanent death

I can understand why starting with permadeath as a premise would lead you to the other ideas: if you're going to be starting over a lot, you'll want variety in your experiences. But why do the first two elements imply a permadeath approach?

# Answer
> 47 votes
From a pragmatic standpoint..

If someone isn't going to be playing your game over and over again, but instead is going to play through once from start to end using checkpoints or free saves (like in most non-roguelikes), then why would you spend your time on implementing procedural generation for your world, instead of just making a single, static, well-balanced progression of maps?

I think the important concept is that if you're going to invest in procedural generation of your levels, then to get value from the procedurally generated levels, you really have to make someone want to play your game -- from the start of the procedurally generated content -- several times. And preferably, lots of times. Permadeath is one effective way to do that.

The Diablo games, on the other hand, accomplish this same goal by letting you start over again with your levelled-up character at a higher difficulty level, after winning. Their difficulty level scales up so that a single "playthrough" can wrap around the game several times, and so experiencing several variations of each level.

Lots of other games embed a repeatably-visitable procedurally built dungeon into a static, traditionally-created framing game (commonly an RPG of some sort. e.g.: Persona, Dark Cloud, Mystery Dungeon, etc). In this type of system, separate visits to a single dungeon generate different dungeon layouts. This also allows a single "playthrough" to wrap through your procedurally generated content several times.

These are both different game mechanics which achieve a similar net effect to permadeath, in terms of justifying the use of procedurally generated content.

Of course, permadeath makes more use of (and puts more pressure on) the procedural generation of your world than other approaches, since the user can easily wind up seeing variations on level 1 over and over and over again in close succession, if he dies and has to restart a lot. If your procedural generation of level 1 doesn't make the level unique enough to keep a player from getting bored with it after five or ten successive restarts, then maybe you should think about using a different mechanism to entice players into starting a new playthrough.

# Answer
> 32 votes
> But why do the first two elements imply a permadeath approach?

I don't think character growth or procedural world generation imply permanent death at all. In fact, there isn't a necessarily mechanical connection between any of those three elements (as evidenced by the fact that combinations of a *subset* of those elements in games exist).

I simply think that roguelikes have a tendency to include those design components because the original Rogue employed them, as did its early offshoots, and thus it became a trend.

In other words, to answer the title of your question as well, permadeath is "essential" only in that it is traditional.

# Answer
> 15 votes
Permadeath gives character building and world exploring decisions weight.

Permadeath makes it harder to abuse the random number generator (grinding).

These things help stop a roguelike feeling flat. Procedural content is rarely aesthetically pleasing, so roguelikes rely on creating interesting mechanical space; typically through risk/reward dynamics. The ability to take back mistakes softens the risk, and makes the mechanical space less exciting.

# Answer
> 7 votes
One of the major game-mechanical aspects of classic roguelikes such as Nethack is that you don't know what the potions, scrolls, and wands that you collect do until you try them (and sometimes not even then). There's therefore a big element of risk - is this potion poison or healing? Is this scroll Enchant Armor or Destroy Armor? Any "undo" or save-restore backtrack ability undermines this, and you'd lose the desperate "I'm gonna die on the next turn but maybe this last scroll will turn out to be Teleportation" moments that make roguelikes extra-exciting.

# Answer
> 5 votes
I like to think of "permadeath" as just part of the genre.

For instance, could you make a first-person shooter with no guns? Sure! You could replace them with swords, etc. But would people see it as a FPS? Probably not.

Roguelikes, by tradition (and arguably, by definition), include permadeath because that's the way the genre was defined.

# Answer
> 5 votes
I think one of the core concepts of roguelike games is the inherent humor of your history of failure.

For some people it is fun to look back and realize which decisions ultimately lead to their doom, "decisions" you often were not really at liberty to make at all. All this in a world that constantly tries to kill you with almost no knowledge about it. Also, a lot of these games are incredibly and deliberately unfair: There might be a high-leveled Lich behind the next door, even on the top level. That way *every* decision has unforeseeable consequences.

So in the end these games create a tragic hero whose doom is pretty much predetermined and the only question is: How? This inability to escape the forces that be might also be a sarcastic comment on life itself - and that's the humor in it.

# Answer
> 5 votes
> But why do the first two elements imply a permadeath approach?

They don't.

You can have perfectly functional gameplay without permadeath, while still allowing ability-based character progression and procedurally-generated worlds. Terraria's a good example of this.

What you've done is broken down the Roguealike "genre" too far. You've stripped out important elements.

Consider this. If you want the player to see your procedural engine, to really make use of it, does permanent death help. Yes... *provisionally*. That provision being that the player die. *A lot*. Permadeath in a game where death is not common doesn't aid seeing more procedural worlds at all.

Therefore, in order for "Procedurally generated worlds" and "Permadeath" to synergize, you need a third element: killing the player a lot. Roguealikes tend to employ methods to kill players that would generally be seen as brutally unfair ("here's a potion, but I'm not going to tell you what it does. It might kill you or save you. Drink it to find out.").

So the reason why you don't see the connection between the elements is because you're missing elements essential to the genre. You need to combine "permadeath" with "dies a lot" before it starts to connect with "procedural world generation".

# Answer
> 1 votes
It isn't "essential" and IMO is here only as tradition. Sizable amount of players circumvent it with backing up saves.

# Answer
> 1 votes
There are solid design reasons why this is a winning combination of factors, but I think they're missing the point for your question.

**These three factors are combined in a rogue-like because *that's what makes it a rogue-like***

That may seem tautological at first, but it's actually definitional. A rogue-like is a game that combines those three elements. A game without those three elements will be misleading potential players about its nature if it claims to be a rogue-like. It would be like billing your game as an FPS when, in fact, it only supports a third-person view; which won't make it a bad game but it does make it a misleading description.

You could then ask why "rogue-like" means these three things but we're then into a world of historical accident and etymology which ultimately doesn't matter for your question. However it got to mean that, that's what it means.

# Answer
> 0 votes
Permadeath and procedural generation are two sides of the same coin. Without each other, both are meaningless.

* Without permadeath, players will never see your procedural content. You may as well make static maps as in other RPGs, as many players may never even realize that the game was random to begin with. The most common alternative employed by modern rogue-ish games (such as Diablo and Starbound) is for the same character to explore multiple dungeons, essentially achieving the same effect under a different name.
* Without procedural generation, permadeath is pointless - there's no reason to force players to restart if they'll see the same thing every time. As you said, without variety there's no reason to keep playing. This ties into your observation of character growth through varied powers, adding variety to not just situation but to overall strategy.

The presence of these two features can also (partially) explain some other features common to traditional roguelikes that could otherwise seem quite unreasonable.

* Traditional roguelikes are strategy/turn-based rather than action-based so as to give the player some sense of control over permadeath and procedural content (or *real* control in the case of skilled players). You'll notice that realtime roguelikes are still slow-paced (ie. ToeJam & Earl), which leads to a similar playing experience.
* Traditional roguelikes are extremely difficult because otherwise permadeath would never occur, leading to the "never seeing procedural content" issue. This and the above amplify each other, as increased difficulty makes control more important, while the slower-paced genre makes difficulty more justified.
* Traditional roguelikes generally don't have stories because it would lead to the "no varied content" issue. The few exceptions rely on story structures very different from most RPGs, such as Dwarf Fortress with half-procedural and half-user-generated stories, or Cogmind with its story mostly contained within randomly-found and optionally-read lore entries.

---
Tags: game-design, procedural-generation, roguelikes
---


# Question
Title: Can you decompose a rotation into a rotation around an axis and a quaternion?
I have a rotation represented by a quaternion and I want to get a rotation angle around the forward axis together with another quaternion which will together represent the original rotation.

The reason for this is that I am interpolating the rotation along a path and I want to be able to interpolate the rotation around the path in such a way that it does not have any discontinuities or sudden flips.

# Answer
Avoiding discontinuities is a bit tricky for reasons outlined in this Q&A \- if we try to strictly control, say, the up direction to align as closely as possible with world up, then we'll have to flip somewhere if our rotation does a vertical loop-de-loop, reversing its relationship with the world up axis suddenly.

Instead, let's attach a reference "up" vector to each interpolated point, perpendicular to current local forward vector, and we'll try to align it with world up when we can.

You can choose your first point's reference "up" vector arbitrarily (eg. the local up vector of the initial rotation, so your twist angle starts at zero)

For each subsequent point, we can choose our reference vector as:

```
sourceUp = previousReferenceUp + untwist * dot(previousReferenceUp, worldUp) * worldUp;

referenceRight = normalize(cross(sourceUp, localForward));

referenceUp = cross(localForward, referenceRight);

```

Here I'm assuming left-handed coordinate system, with `untwist` being a small tuning coefficient (eg. 0.01) to to control how much our reference up seeks vertical in non-vertical sections.

Now we can compute an angular twist about the forward axis relative to this `referenceUp` direction as:

```
localUp = rotation * worldUp;
angle = atan2(-dot(referenceRight, localUp), dot(referenceUp, localUp));

```

Our twist quaternion can then be expressed as:

```
// Remember to convert to degrees if expected by your Quaternion library (eg. Unity's)
twist = Quaternion.AngleAxis(angle, worldForward);

```

We can compute its inverse (ie. negate the x, y, z components):

```
untwist = Quaternion.Inverse(twist);

```

And then compute our untwisted remaining rotation as:

```
untwisted = rotation * untwist;

```

Then for any vector v, the result of rotating that vector by our twist angle then by the remaining untwisted rotation is equivalent to rotating the vector by our original quaternion:

```
rotation * v == untwisted * twist * v;

```
> 0 votes

---
Tags: rotation, quaternion, interpolation
---


# Question
Title: trying to work out coords based collision
In this game I'm working on, both player and enemies are represented by 32x32 sprites(not using bounding boxes).

I'm trying to make a system where if the x and y coordinates of the player and enemies is less than 32, which would mean they're basically on top of eachother, to print out a message.

I store the enemies in a LinkedList. This is my collision detection code:

```
for (Entity entity : entities) {
            int deathByX = Math.abs(entity.getX() - player.getX());
            int deathByY = Math.abs(entity.getY() - player.getY());
            if (deathByX < 32 && deathByY < 32) {
                System.out.println("You died");
            }
        }

```

But as of right now, it does nothing, even if my player is right on top of my enemy. What could I do to make this code work?

# Answer
I looked at your code and I could not find any obvious mistake. It seems to me as if it should do what you want it to do. But as Donald Knuth once said:

> Beware of bugs in the above code; I have only proved it correct, not tried it.

Nevertheless, I believe that the most likely reason why this code does not work is outside of the code snippet you posted. Some possible reasons could be:

* This code section is in some method which doesn't get executed every tick
* The entity you see on the screen isn't actually in the `entities` list.
* The coordinates provided by `getX` / `getY` are not actually pixel-coordinates but use some other unit of measurement
* player and entity don't actually use the same coordinate system

If this were my project, then I would analyze the problem by running the game in the Java debugger. If you haven't concerned yourself yet with how the debugger of your development environment works, then you should do so. It is an invaluable tool for troubleshooting bugs in your programs.

I would move the player to intersect an enemy and then set a debugger breakpoint in front of that for-loop. When the breakpoint gets triggered, then I just eliminated the first point. I can then eliminate the second right away by checking the content of the entities array in the debugger's local variables window and see if I find the enemy I collided with. When it is there, then I would set a second, conditional breakpoint within the loop which triggers when `entity` is equal to the entity I am looking for and continue execution. When the break-point gets triggered, then I would keep executing step-by-step to check the return values of getX and getY of both the player and the entity, check if `Math.abs` does what I believe it should do, and why the if-statement doesn't get triggered.
> 1 votes

---
Tags: java, collision-detection
---


# Question
Title: RTS Style Game With Client-Side Prediction
So, I am currently working on an RTS-like multiplayer game. Units are not controllable by players (they attack-move to a location automatically).

I decided not to go full lockstep but instead do a state-based / prediction hybrid. The game is fully simulated on the client with a state packet for every unit distributed only once per second (Position, health etc.). I've read that this is quite a common method of doing things these days but i'm having major issues with it. One clear problem is with health syncing. Damage is dealt locally on every client machine and corrected via the state packet. This results in issues similar to this:

* Projectile hits a unit on a client machine, taking him from 100 health down to 50.
* Client only then receives a state packet from the server saying he is on 100 health which spikes it back up.

Of course he will receive another corrective packet later on taking him back down to 50 but this causes really bad visual spikes. This issue gets even worse if you consider the impact of ability damage and such.

Have I completely misunderstood what is required to create a client-predicted game or do I just need to treat every variable on a case-by-case basis? (I.E. Put in silly hacks to make the health not look bad).

# Answer
> 1 votes
Client prediction can be implemented by having:

* A known state: unit statistics and timestamp for when this state applies
* Events: actions which modify the known state. They also have a timestamp so we can order them

You client works by receiving states from the server, and then predicting the current state by applying the events that come after the state's timestamp.

Let's have an example moving through time:

```
T0: Initially
  Known state (100HP @ T0)
  Predicted events: []
  Predicted state: (100HP @ T0)

T1: Client simulation preditcs a hit for 35dmg
  Known state (100HP @ T0)
  Predicted events: [35dmg @ T1]
  Predicted state: (65HP @ T1)

T2: Client simulation preditcs a hit for 10dmg
  Known state (100HP @ T0)
  Predicted events: [35dmg @ T1, 10dmg @ T2]
  Predicted state: (55HP @ T2)

T3: Client recieves a new state from the server, 65HP at T1
  Known state (65HP @ T1)
  Predicted events: [10dmg @ T2] // Here we removed events that happened at or before T1
  Predicted state: (55HP @ T3)

T4: Client recieves a new state from the server, 55HP at T2
  Known state (55HP @ T2)
  Predicted events: [] // Here we removed events that happened at or before T2
  Predicted state: (55HP @ T4)

```

I know it's a bit vague, but I hope it can help you retool your predictions.

---
Tags: networking
---


title: GLSL - Efficient Point inside Box Check

text:
# Question
Title: GLSL - Efficient Point inside Box Check
I'm attempting to improve the performance of a shader that changes the colour of a region of the world that is inside a "zone".

I am using a deferred lighting system, so the colour and world-space position of each pixel on the screen are stored in two separate textures, gColor and gPosition.

* The zonePos uniform stores the two corners of each zone.
* The zoneColor uniform stores the colour of each zone.
* The totalZones uniform stores the amount of zones in the current game.

Here is the fragment shader:

```
out vec4 FragColor;

in vec2 texCoords;

layout (binding = 0) uniform sampler2D gColor;
layout (binding = 1) uniform sampler2D gPosition;

uniform vec3 zonePos[10];
uniform vec3 zoneColor[5];
uniform int totalZones;

void main()
{
    vec3 FragPos = texture(gPosition, texCoords).rgb;
    vec3 Albedo = texture(gColor, texCoords).rgb;

    vec3 j;
    vec3 k;

    for (int i = totalZones; i > 0; i--)
    {
        j = zonePos[i * 2];
        k = zonePos[i * 2 + 1];

        if (FragPos.x >= j.x && FragPos.x <= k.x &&
            FragPos.y >= j.y && FragPos.y <= k.y &&
            FragPos.z >= j.z && FragPos.z <= k.z)
                Albedo += zoneColor[i];
    }

    FragColor = vec4(Albedo, 1.0);
}

```

The changes I have made so far are:

* Using j and k, rather than accessing zonePos 6 times in the if statement
* Looping down from totalZones to 0, as a comparison against 0 is faster

Any suggestions are greatly appreciated.

# Answer
Your check method inside the loop doesn't have any obvious inefficiencies for the way you've chosen to set up the problem.

But, we can take advantage of the deferred strategy to set up the problem in a simpler way.

Think of how we handle lights in deferred shading: Rather than looping over a bunch of lights in one shader like we might do in forward rendering (doing redundant computations for fragments that happen to be outside a given light's range), instead we render each light as a bounding volume. That way the shape of the geometry and depth testing help us limit our drawing to just the fragments that might be illuminated.

We can do the same with these zones. Render each one as a cube, sized & positioned to match the desired volume. Z-testing should be enabled but z-writing disabled.

The shader can then be very simple: read the world position of the fragment drawn there and test it against this single cube's bounds. If it passes, output your zone colour, otherwise abort or output black, and let additive blending do the rest (no need to sample the albedo texture manually inside your shader).

You can still render all this in a single pass by combining your cube meshes into a single vertex buffer, and encoding each one's zone colour/bounds in the vertex colours / texture coordinates. Or use instancing for a similar effect.

This lets us use the geometry & depth culling powers of the GPU to handle a pile of our checks, excludes redundant checks outside the screenspace volume of our zones, and simplifies our shader. We break out of the serial loop and let the GPU do what it does best, attacking the problem in parallel.
> 1 votes

---
Tags: opengl, shaders, glsl, performance, fragment-shader
---


# Question
Title: How to get an axe chopping animation to stop on collision with tree and smoothly go back to idle state?
Been stuck on this one for a few days.

I have an axe that moves around with the mouse. When the mouse is in range of a tree, you can left click to start the axe swing animation. Once the animation is complete, it goes back to the idle state in the Animation Controller.

The problem with the current solution is the axe can clip through the geometry of the tree. I tried the 2 camera system (setting depth) to render the axe on top, but it didn't feel good.

The tree and axe has colliders on them. The axe has a rigidbody.

I then tried another idea. I disabled the animation controller for the axe on collision enter, and set the axe isKinematic to true. This worked, the axe would not clip the tree, however, once I enabled the animation controller, the axe animation would continue to playing. So I tried to switch the state back to idle and thought maybe cross fading would solve it, but it didn't work.

Is there a better way to do this?

# Answer
Changing the animation state based on collision is a good way to do it. You're on the right track. Chances are, if crossfading between states didn't work, you might have set it up wrong.

Here is how I would do it:

Firstly, create different states for Idle and Swing (you've already done this). When the axe hits a tree, instead of disabling the animation controller, you simply transition out of the swing state.

```
void OnCollisionEnter(Collision collision) {
    // do some check to see if we've hit a tree
    ...
    // if tree
    anim.SetTrigger("HitSomething");
    ...
}

```

In your animator setup, create a trigger of the same key and create a transition from your swing state to your idle state.

Now the important part is setting up the crossfade between the two animation states. Your original transition from the swing state to the idle state probably has an exit time to allow for the swing to transition to idle automatically when the animation is done. We can leave that and make a new transition from swing to idle (right click swing, make transition, drag to idle).

With your new transition selected, uncheck exit time, set transition offset to 0 (immediately crossfade), and set transition duration to however long you want the length of the crossfade to be (probably 1).

When you're done, your swing animation should stop and fade back to idle when you hit a tree. That's it!
> 4 votes

---
Tags: unity, animation-states
---


# Question
Title: HTML5 game pases when you go to another tab
I'm making a simple game and I use `requestAnimationFrame`. Now the problem is that each I change to another tab the game pauses and when I return the game continues.

This is really bad because the game is multiplayer and restarting the game each time a user switches to another tab doesn't seem like a great idea.

Do any of you have any idea how I can keep the game active, while the user change to another tab?

Thanks.

# Answer
> 1 votes
Separate your game's code into logic code and drawing code.

Put the logic code into a function which you execute at regular intervals with `SetInterval`. Intervals still get executed when the tab is inactive. Note that if you use SetInterval on the main `window` object, then most browsers will throttle it when the tab is inactive. When you are using a game loop with a variable time-step (you check how much time elapsed since the last update and take it into account when moving things) then this should not be a problem. But if you want to use a fixed timestep, then you can get around this by using a web worker. Web workers can use intervals which do not get throttled in inactive tabs.

Your drawing code should stay in the method you pass to `requestAnimationFrame`. You *can* do canvas drawing in your interval method, but using requestAnimationFrame is recommended. It should be easier for the browser's rendering engine (whether this translates to a tangible performance benefit is implementation-specific) and there is little reason to waste the client's resources on drawing frames nobody is going to see.

---
Tags: javascript, html5, node.js
---


title: How to do drag controls?

text:
# Question
Title: How to do drag controls?
I wanted to control my character with dragging controls (horizontally only) I currently have a code that controls the character with touching the left and right screen. I wanted the same controls as the game "Everwing" . I cannot find anything on youtube so I'm having a hard time with this. Please can anyone help me I'm still just a begginer.

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

public class meteorController : MonoBehaviour {
public float meteorSpeed;
public float maxPos = 2.2f;

Vector3 position;
public uiManager ui;
public AudioManager am;

bool currentPlatformAndroid = false;

Rigidbody2D rb;

void Awake() {

    rb = GetComponent<Rigidbody2D>();

#if UNITY_ANDROID
        currentPlatformAndroid = true;
#else
    currentPlatformAndroid = false;
#endif

    am.level1Music.Play();
}

// Use this for initialization
void Start() {
    position = transform.position;

    if (currentPlatformAndroid == true) {
        Debug.Log("Android");
    }
    else {
        Debug.Log("Windows");
    }

}

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

    if (currentPlatformAndroid == true)
    {
        //android specific
        TouchMove();
        //AccelerometerMove();

    }
    else
    {
        position.x += Input.GetAxis("Horizontal") * meteorSpeed * Time.deltaTime;

        position.x = Mathf.Clamp(position.x, -2.2f, 2.2f);

        transform.position = position;
    }
    position = transform.position;
    position.x = Mathf.Clamp(position.x, -2.2f, 2.2f);
    transform.position = position;
}

void OnCollisionEnter2D(Collision2D col) {
    if (col.gameObject.tag == "asteroid") {
        Destroy(gameObject);
        ui.gameOverActivated();
        am.level1Music.Stop();
    }
}

void AccelerometerMove() {

    float x = Input.acceleration.x;

    if(x < -0.1f){
        MoveLeft();
    } else if (x > 0.1f) {
        MoveRight();
    }
    else {
        SetVelocityZero();
    }
}

void TouchMove(){
    if(Input.touchCount > 0){

        Touch touch = Input.GetTouch(0);

        float middle = Screen.width / 2;

        if(Input.touchCount >= 2){
            SetVelocityZero();
        }

        if(touch.position.x < middle && touch.phase == TouchPhase.Began) {
            MoveLeft();
        }
        else if (touch.position.x > middle && touch.phase == TouchPhase.Began) {
            MoveRight();
        }

    }
    else {
        SetVelocityZero();
    }
}

public void MoveLeft(){
    rb.velocity = new Vector2(-meteorSpeed, 0);
}
public void MoveRight(){

    rb.velocity = new Vector2(meteorSpeed, 0);
}
public void SetVelocityZero(){
    rb.velocity = Vector2.zero;
}

}

```

Here is how my game looks like and I wanted the character (The meteor) to move left and right.

# Answer
I used a script that I got from "rudisky" in this post. It worked well for me

Here is the script:

```
using UnityEngine;
using System.Collections;

public class movimiento : MonoBehaviour {

 // Use this for initialization
 void Start () {

 }

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

 //Gets the world position of the mouse on the screen
 Vector2 mousePosition = Camera.main.ScreenToWorldPoint( Input.mousePosition );

 //Checks whether the mouse is over the sprite
 bool overSprite = this.GetComponent<SpriteRenderer>().bounds.Contains( mousePosition );

 //If it's over the sprite
 if (overSprite)
 {
     //If we've pressed down on the mouse (or touched on the iphone)
     if (Input.GetButton("Fire1"))
     {
         //Set the position to the mouse position
         this.transform.position = new Vector3(Camera.main.ScreenToWorldPoint(Input.mousePosition).x,
             Camera.main.ScreenToWorldPoint(Input.mousePosition).y,
             0.0f);
      }
    }
  }
}

```
> -1 votes

---
Tags: unity, control
---


# Question
Title: Error saying attempting to reference a deleted function while using a vector list
I’m making a 2d top down shooter game and I was working on shooting bullets. Im using a vector for the bullet in my player class: std::vector b; And I have coded a shoot function which shoots the bullet and deletes it if it is out of the screen:

```
void Player::shoot(float timer)
{
//Getting Key Press
if (Keyboard::isKeyPressed(Keyboard::Space))
{
    space = true;
}
else
{
    space = false;
}

Bullet b1;
b.push_back(Bullet(b1));

if (space)
{
    for (int i = 0; i < b.size(); i++)
    {
        b[i].setPos(pos);
    }

}
else
{
    for (int i = 0; i < b.size(); i++)
    {
        b[i].update(true);
        if (b[i].getPos().y < 0.0f)
        {
            b.erase(b.begin() + i);
            i--;
        }
    }
}
}

```

But I have encountered an error: Error C2280 'Bullet &Bullet::operator =(const Bullet &)': attempting to reference a deleted function

I don’t understand why this is happening can someone explain? Here is the bullet class Header:

```
#pragma once
#include <SFML/Graphics.hpp>

using namespace sf;

class Bullet
{
private:
Texture t;
Sprite bullet;
Vector2f pos;
public:
Bullet();
~Bullet();
void setPos(Vector2f pos);
void move(bool up);
Sprite getSprite();
Vector2f getPos();
};

```

Cpp file: #include "stdafx.h" #include "Bullet.h"

```
Bullet::Bullet()
{
//Setting Texture
t.loadFromFile("Graphics/bullet.png");
bullet.setTexture(t);

}

Bullet::~Bullet()
{
}

void Bullet::setPos(Vector2f pos)
{

//Setting Position
this->pos = pos;
bullet.setPosition(this->pos);
}

void Bullet::move(bool up)
{
if (up)
{
    bullet.move(0.0f, -10.0f);
}
else
{
    //TODO
}
}

Sprite Bullet::getSprite()
{
return bullet;
}

Vector2f Bullet::getPos()
{
return pos;
}

```

# Answer
*I'm going out of my usual path here with the more 'technical' c++ rules, so if there are anything wrong here, please point it out. Also, this is only based on what I understand from the provided code, the code from SFML and from knowledge available on the internet.*

---

# Why do you get this error?

According to a popular site,

> Deleted implicitly-declared copy assignment operator
>
> A defaulted copy assignment operator for class T is defined as deleted if any of the following is true:
>
> * T has a non-static data member of non-class type (or array thereof) that is const;
> * ...
> * T has a non-static data member or a direct or virtual base class that **cannot be copy-assigned** (overload resolution for the copy assignment fails, or selects a deleted or inaccessible function);

(Emphasis mine.)

Looking at your `Bullet`, it does not appear like there are any issues there, but we have to look at what it's using.

Apparently, the `Sprite` class that you're using is having a `const Texture*` which prevents it from being implicitly copy-assigned (i.e. the first bullet point).

The error you get is from the last bullet point in that quote: your `Bullet` class has not received an automatically copy-assignment operator because some of the classes that it uses has not received one.

C++ is *great!!* Although it's the greatest tool to shoot yourself in the foot, it's getting more and more 'new user friendly'!

It's preventing you from doing something you might not be aware you're doing.

# How do you fix this error?

I presume `b` is declared like this:

```
std::vector<Bullet> b;

```

I don't think you really intend to copy your object around.

Instead, use a vector of *pointers* to bullets:

```
std::vector<std::unique_ptr<Bullet>> b;

```

This way, the vector will most likely *move* the references instead of *copying* them.

---

Now you're having other issues with this code.

```
for (int i = 0; i < b.size(); i++)
{
    b[i].update(true);
    if (b[i].getPos().y < 0.0f)
    {
        b.erase(b.begin() + i);
        i--;
    }
}

```

Every time you modify a vector when you iterate over it like, \[insert you favourite god(s) vs kitten quote here\]. It not only makes the code hard to read, it opens up the door to shooting you in the foot.

Alternative ways are to use a `while` and an iterator, or better, use the `remove_if` function (see this answer on SO).
> 2 votes

# Answer
`T` of `std::vector<T>` must be *move-assignable* to call `erase()`.

That means `T` needs to have either a move assignment operator or a copy assignment operator defined. Your `Bullet` class has neither, and thus cannot be move-assigned as needed by the `vector` implementation, and thus you get this error.

You should define a copy assignment (or move assignment, but I'd suggest you start with copy assignment) operator in `Bullet` to fix this.
> 1 votes

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


title: Redux-like storage in GD

text:
# Question
Title: Redux-like storage in GD
**Some background**

I've come from the world of web development. And it's a real trending in web to keep whole app's state in single global store (see Redux, discussion about it's benefits).

* Basically the main idea it makes the state management more predictable.

**Question**

I have no ideas how Redux-like architecture would fit for a game development. My main fears it's about usage with main loop inside game and of course about performance.

*Did anyone use Redux-like store in GD, or it's a common anti-pattern*?

Thanks for opinions.

P.S. It's not really matter, but I use libGDX.

# Answer
> 1 votes
Yes, I'm currently making a game using React + Redux (check it out here). It would be better for a variety of reasons to using something like Unity in the long term, but for now, this is just my little experiment.

I was thinking the same thing as you and I come from web dev as well. And the Redux state management and debugger is pretty awesome once you start having a ton of things going on. Granted, my game works well with Redux because it's turn based. I've seen people do physics based games and whatnot, but the best games with Redux I've seen are either puzzles or mini RPGs.

---
Tags: java, libgdx, storage
---


title: Most efficient way to check collision

text:
# Question
Title: Most efficient way to check collision
For example, I have a player and a map, to check player collision with some block we need to check entire map tiles, but the bigger the map, the slower the framerate. What's most efficient way to check collision?

# Answer
> 1 votes
For maps with square tiles you don't actually need to check against every tile, instead you can perform a simple calculation that will give you the tile the player is currently on.

```
Xtile = (Player.X - Map.X) / Map.Tile.Width

```

You then do the same for the y and get the tile that the player is on.

Now if your player position is on the upper left hand you more than likely want to perform actions on all the tiles the player is currently over. To do that you would have to choose one of two options; If the players width is constant then you can simply iterate the couple tiles that are part of the square the player would represent.

For example if your tile width is the same as your player width, and same for the height then you could calculate the `Xtile` and `Ytile`, then also perform actions on the `(Xtile + 1, Ytile)`, `(Xtile, Ytile + 1)` and the `(Xtile + 1, Ytile + 1)`

On the other hand if your player has a variable width(or you want to use the same technique for all possible characters of various sizes) then you calculate the `Xtile` and `Ytile` and use loops to iterate on all things inside the rectangle.

For example your `Xtile` was calculated to be 3, your `Ytile` was calculated to be 4, your character is 3 tiles wide and 5 tiles high Then you could:

```
for(int i = Xtile; i <= (Xtile + Character.WidthInTiles); i++){
    for(int p = Ytile; o <= (Ytile + Character.HeightInTiles); o++){
        CurrentTile = Map[i][o];
        //Perform actions on CurrentTile here
    }
}

```

Edit: forgot to mention regular AABB collisions and speed; As a side note for your regular collisions you shouldn't be checking if there is a collision but rather if a collision is impossible.

By that I mean that you should be checking if `PlayerX + PlayerWidth` is less than the `ObjectX`, because that means that its too far off the right and so you don't need to check the rest of the possibilities which is faster.

The final version with all four sides checked looks like this:

```
if((Object1X + Object1Width) < Object2X || Object1X > (Object2X + Object2Width) || (Object1Y + Object1Height) < Object2Y || Object1Y > (Object2Y + Object2Height)){
    //There is a collision detected between Object1 and Object2
}

```

---
Tags: collision-detection
---


# Question
Title: After using Unity's Destroy() function, I see the Prefab Clones are now called "New Game Object" is this a problem?
I use a prefab to generate several gameobjects which I then get rid of with the Destroy() function.

I noticed the clones, when destroyed are replaced with **"New Game Object"**. Because of the nature of the game there would be thousands of these created throughout the course of the game.

Is this expected behavior, or is there something I'm perhaps doing wrong where the Destroy isn't really getting rid of it completely?

# Answer
> 1 votes
No, that is not a problem. That is just the default name for a run-time instantiated GameObject. If you want to name them, you can use `myGameObject.name = "Something else";`.

# Answer
> -1 votes
Maybe you are not destroying the object, instead you are destroying the script, so be sure that you are calling the game object inside the Destroy function.

---
Tags: unity, gameobject
---


# Question
Title: How is it possible to use Android libraries in libGDX?
I want to make an android application game that uses both android API like Location, even Google Maps API and also use libGDX framework as well. How is this possible?

I noticed there's an Android and a core folder created when making a libGDX project, where do all the classes go, but I'm very confused.

# Answer
Anything **Android** specific should be in your *-android* project and anything general goes in the *-core* project.

Normally you'd have an interface in the *-core* project that is implemented by classes in your *-android*, *-desktop* or web project and in your platform specific launcher (for example in AndroidLauncher.java) you'd inject the platform specific implementation of the interface.
> 3 votes

# Answer
> Android specific libraries may be added to the `android` module **only** in `build.gradle` for the overall project.

If your `core` module relies on **android specific modules**, you will need to use a **different solution** for the other modules.

Thus, if you want to use Google Maps API on both Android & Desktop, you will need to utilize a different library for your `desktop` module.
> 0 votes

---
Tags: android, libgdx
---


# Question
Title: Are there technical reasons to use short variable names in shader code?
I have been reading and writing both GLSL and CG for the past few years, and have noticed a trend. In programming, we are generally advised to be as meaningful and concise as possible with variable names, but I see this suggestion being ignored almost every time I look at shaders.

Here is a random example I grabbed off of Shadertoy:

```
vec3 tex_wmcs(vec2 p)
{
    float s=mix(0.2,1.2,sqrt(smoothNoise2(p*3.0)));
    vec3 col=mix(vec3(0.15,0.2,0.2)*0.4,vec3(0.2,0.15,0.11)*0.7*s,sqrt(max(0.0,sm...
    vec2 p2=p*vec2(4.0,10.0)+vec2(smoothNoise2(p*24.0),smoothNoise2...
    p2.x+=floor(p2.y)*0.5;
    float bh=pow(0.5+0.5*cos(floor(p2.y)*14.0)*cos(floor(p2.x)*1.0),2.0);
    float brick=brickt(p2);
    vec3 bn=normalize(vec3(brickt(p2+vec2(1e-3,0.0))-brick,b...
    ...
}

```

Is there a **practical reason** so many graphics programmers minify their code to such a point?

Is there a **technical downside** to spelling out `brickNormal` instead of leaving it as `bn`, or using `brick_tangent` or `brickTexture` instead of `brickt`?

# Answer
I've noticed the same trend, I've found the following reasons apply:

Shadertoy in particular is just that *a toy*. You will often find people don't bother with good coding standards and do what ever is quickest because typically you aren't collaborating with any one else and are just trying to show off a visual effect.

Code Golfing esque programming: lots of shaders pride themselves on being *short* to the extreme in order to show off "look what I can create with only 50 chars! The short nature of shaders makes this much more prevalent, which leads into my next point:

Shaders, by their nature, are meant to be very short. Due to the lack of built in ability to share code between shaders, and the single function typical use case of shaders (they are used to usually do one thing) shaders typically are shorter than most single source files in C and C++. You'll often find advanced shaders using very few lines of code (under 100). If you can see the whole code on your screen and it only fits in a couple of functions, it's going to be easier to reason about it no matter how small the variable names are.

And to bring this back around, you'll often find very large shaders on shader toy (because some of these things don't apply) but the legacy of how other shaders are programmed means that you are going to see people copying the very poor style of these other programmers.

Don't follow these practices. There is no reason you can't apply normal readability principles in shadertoy or in individual GLSL shaders. There isn't any practical justification for the shortness unless you're code golfing. There is no technical reason to shorten the names either.
> 8 votes

# Answer
Some possible reasons for using short variable names are:

* **Brevity:** short variable take less time to type.
* **Following Textbooks:** similar to the discussion in this software engineering SO post on short variable names, some shader code might be written using formulas from textbooks (physics, optics, math, etc) and it's common for such formulas to use abbreviations & established variables (such as often using theta for angles). Academic papers often share this trait as well (some cutting edge techniques often start research presented in places like SIG Graph). Some programmers may carry this style over to other parts of the code.
* **Historical Precedent:** originally, shaders were essentially written a GPU specific assembly language. Assembly code is very terse. It's possible that some of the this style has been adopted by subsequent generations.
* **(Perceived) Memory Efficiency:** As discussed here, in some cases (very old compilers, and certain interpreted languages), longer variable names take up more memory than shorter ones. Even if this doesn't apply to modern shaders, some programmers may be following cargo cult programming practices.

In my professional opinion, the only reason that holds up is the textbook/other source example and then only under certain circumstances. In the event that your developing code from other formulas presented elsewhere, using the same variable names can make it easier to compare your translation to the original. After having done that & in the other cases that come to mind, the correctness, clarity & maintainability should be focus for producing well crafted code.
> 6 votes

# Answer
Small scopes and math operations both "call" for short variable names:

1. Small scope means you have just a bunch of operations to do with just a few variables. Keeping variable names short allows for sense of compactness (which many programmers like).
2. Many of shader operations are following some math formulas. Math formulas are known for short var names (x, y, dt, etc.), hence shorter var names.

Both reasons are kind of justified to some extent, but once code surpasses few lines and a few variables, it's better to let go of compactness and spend some time to give variables proper names, write some comments.
> 1 votes

---
Tags: shaders, software-engineering
---


# Question
Title: What are some ways to keep the player engaged in an endless game?
An endless game consists of the same gameplay mechanics repeated over and over. You have to keep doing mostly the same things as long as you can.

So it is quite easy to make players bored of your game. What are some concepts that one could implement into the game design to keep the player engaged?

To be more specific, my game is an endless tapping game where you have to tap rockets to make them explode into fireworks, and sometimes on falling meteors too.

# Answer
Provide visible goals for the player to achieve. For example:

* **Levels:** If you click enough rockets, the game becomes more difficult. When you are ~~lazy~~ on a tight budget, then you can just tune some variables. Like Tetris, for example, where the only difference between levels is speed and score multiplier. This is easy to do, but requires a lose-condition so the game ends when the player reached the limit of their skills.
* **Content unlocks:** When the player taps enough rockets, new game features become available.
* **Story progression:** Have your game tell a story. When the player keeps playing, new parts of the story get revealed.
* **Achievements:** Acknowledge when the player did something good for the first time, like tapping 10000 rockets or tapping 100 rockets in just one minute.
* **Becoming better than other players:** Create an online leaderboard where users can compete with each other.

One important aspect is to make the player aware of what goals there are and what they need to do to achieve them.
> 57 votes

# Answer
I would suggest adding a mechanic that encourages emergent gameplay. Often emergent gameplay can be introduced by adding physics into your game.

For example, if a rocket explodes, it could launch fragments of itself across the screen, and if those come into contact with another rocket, it would also explode. Then the player could try to get the biggest chain-reaction they can, which wouldn't be a defined goal of the game, but rather one the player comes up with.

That may not be the best example, but I hope it helped.
> 27 votes

# Answer
You need to have something that keeps changing. Interest will be replaced by boredom if it is the **exact** same game over and over. But it doesn't have to be.

Many classic games are the same game, but you play them with different people. Chess or Go, for example, have zero randomness except for the people playing. That makes it interesting to keep playing the game.

Other games have elements of randomness that keep the game fresh. Card games or dice games. That means games never exactly repeat and while if you play long enough you will spot patterns, you never actually play the exact same game twice.

A third category is ongoing storytelling. If your game develops over time, even if the core game mechanics stay the same, it can provide interest. Real world wars (seen as games following James P. Carse definition) are not interesting because weapons change, but because they are part of the history of the world. Many roleplaying games fall into this category. The content can be created by players.

A fourth group is procedural content generation. You can make the game endless not just in time, but also in content. If there is always one more world to discover, one more level to explore. This is similar to randomness above.

What I found the strongest factor is human interaction. If you have a multiplayer game, the fact that players constantly adapt to each other, providing a constantly changing environment, you can draw people in a lot. My most successful game, which has been running without interruption for almost 20 years now, mixes the history and interaction elements and is still interesting to players (some of whom have been playing for more than a decade).

---

In your tapping game, obviously the aspects requiring other people are out. I assume that you already have some randomness, but this aspect is not strong enough to provide gameplay in itself the way that it does in card games (where playing good with the hand you were dealt is often exactly the challenge).

I would advise to play with randomness and procedural content. You can make levels more chaotic as the game progresses so that the skill a player requires slowly changes from prediction to reaction.

By nature, your game is probably most close to a card game. In this class, the successful games all have a very good balance between skill and randomness. While you get a random hand, the game is balanced so that a good player can win with almost any hand, while a bad player can absolutely lose with even the best hand. There are often also multiple ways to win so you can choose a different strategy based on your hand.

Your game may simply be too simple to have these elements that a game requires to be eternally interesting. You may have to add such elements.
> 9 votes

# Answer
A user will not play a game where they do the same thing over and over. It will get boring and they will leave. As such, you need to make it *feel* like they're doing something new, even if the underlying mechanic doesn't change.

The ultimate example of this is probably Candy Crush. The mechanics introduced in level 1 are basically the same mechanics you use in level 1800. So what changed? The big thing that changes is the difficulty. You have to do bigger and better chains and plan further ahead in order to win.

Another ultimate example of this would be the famous games of Chess and Go. Both of them introduce 100% of the mechanics in the first week of your playing the game, but those mechanics interweave into endlessly intriguing things which people devote their lives to mastering.

Chess and Go demonstrate one very powerful tool for keeping your game interesting: strategy. If the tactics are simple, but the strategy is vast, then players will keep going back for more.

In the end, the best answer is no gimick. If they feel their life is enriched because they play the game, they'll keep playing it. That is the true art of making a game that lasts. You can put as any gimicks in as you please, but its the users who invent the real reason they play.

Take fantasy football. There's almost nothing to it, mechanically. But it is incredibly popular. It's popular enough that if you search for it, the Wikipedia article on it isn't even on the front page! This popularity is because players feel that they are close to the real action. They create their own purpose for continuing to play the game.
> 8 votes

# Answer
Expanding Philipp's content unlocks category, add powerups/items that change up the gameplay. For example: You may tap to explode a rocket, but what if there was an item that made it so when you tapped, a "tower" would spawn that would help you. That kind of stuff is why Enter the Gungeon and The Binding of Isaac are so popular today
> 3 votes

# Answer
I feel that there are two important factors that would cause a person to keep playing a game like this. Extreme difficulty and quick, visible rewards. The ratio between these two is important to test out on an audience.

If the game is too easy, they'll get bored with it as it doesn't offer any challenge.

If the rewards are slow to come, then they won't be incline to continue because there isn't any gratification. The rewards could be as other have suggested (levels, power ups, achievements, a narrative)

Most of this is from my personal experience playing mobile games, many of which have no end state, are free to play, and rely on frequent restarts to generate ad revenue.
> 3 votes

# Answer
If you are too lazy to make an expansion, a new level or sth else, let the user do it:
Custom levels are always pretty hyped

OR:
Look at Minecraft that Game was released a century ago and is one of the most played games, because they had extra content (produced mostly by the users),
like custom server with different rules, custom games like Survival Games.

In your example you're limited to a 'piano tiles' like game, so you have options like:

reverting screen: Geometry dash does this too
Bosses: needs to be tapped 30 times, or must be encircled
Powerups: more damage, explosion damage, shield, extra heart, etc
Game mechanic change: instead of tapping, you slash now, like Fruit Ninja
> 2 votes

---
Tags: game-design, mobile, clicker
---


# Question
Title: How to reduce the total time spent checking against my world bounds?
I'm making a game engine and currently I use a function for checking a new position after movement to prevent game objects from escaping the world:

```
const boundary = function (min, max) {
    return Math.min( Math.max(this, min), max );
};

```

I've noticed that it consumes around 9-10% of my game loop (testing with 4500 objects). Is there a better way to handle this? Do I generally need to make my world finite?

To clear this up, this is not an object-object collision detection question. For that I have a grid, and this grid is based on the size of the world, which is why I check that objects don't escape the world size limits.

# Answer
Your code for checking the boundaries looks good enough, but the frequency of which you call this function might be brought into question. Do you really want to do this collision check every frame for every object?

Consider when you start to implement collision for individual game objects later on, would you want to check each object with every other object every frame? Your time complexity will shoot through the roof. Instead, you may want to consider implementing a Quadtree. I'm assuming you're writing a 2D engine since your boundary check is 2 dimensional. This would drastically limit the number of objects you have to call your boundary checks on.

Edit: If you already have a grid system, you could take advantage of that by only calling your boundary checks on objects in the edge rows and columns.
> 5 votes

---
Tags: javascript, bounding-boxes
---


title: Animation confusion - Unity

text:
# Question
Title: Animation confusion - Unity
Im pretty new to game dev in Unity, and thought I'd start off with a relatively simple game:

Im planning to make a game where 3 cups are shown on a table, and a ball is placed beneath one, the cups go down (concealing the ball) and move around. If the player selects the right cup, they win.

Not sure if I'm jumping in the deep end, but I'd like to make this dynamic in the sense that the animation shouldn't dictate the place of the cup on the table, as I want to code it so that the amount of cups can be set (as a difficulty).

After looking into the state machine stuff behind Unity's AnimationController but not sure how I should go about it.

I've identified various states as below:

* A cup can be down on the table
* A cup can be lifted
* A cup can be moved to a different position on the table (?)

You can see from the above that I dont know if I should include that as a state. When moving 2 cups, one cup should move forward to it's new position, and the other should move behind it as not to cause them to collide, but would also like to be able to code this in a way where cups on the far ends can be swapped as well.

Any advice?

# Answer
> 2 votes
This may be a little advanced for someone who is just starting out since what you're looking for is both procedural and involves avoidance, but it is definitely doable and will teach a lot if you go through with it.

Someone else may be able to come up with an easier solution, the following may be a good starting point.

---

### 1) Ditch the animator altogether.

Since you want to have a dynamic number of cups, the animator probably wouldn't work for you, at least not without lots of hacking.

### 2) Come up with an algorithm to decide on where the cups should go

You can consider the movement of the cups to be in *steps*. A complete shuffle may consist of *n* number of steps. In each step, you can do the following:

* Assuming you have 3 cups in total, you have 3 possible slots for the first cup.
* Pick a slot randomly, and store that as the target position for the cup.
* Move on to the next cup, and pick a slot randomly from the remaining slots.
* Continue until you have decided on a new position for each cup.

If you this step many times, you get a complete shuffle.

### 3) Avoidance

At each of our *steps*, after each cup knows its new target position, we would have to actually move the cups to their target position. We should do this in code. However, if we move each cup directly to their target positions, the cups would start clipping through each other.

If you're mathematically inclined, you could go into complex calculations of parabolas to determine the path for each cup such that there are no collisions. This, however, is not easy. A much simpler approach would be to find a way for each cup to *avoid* all the other cups as if it were sentient. I like to use steering.

---

With all that done, all you have to do is to fill in the rest of the code that makes the game playable.

Keep in mind, this is not the only way to do it. There are plenty of ways to create the same feature when writing a game. So don't worry about the details, start messing around with it and try getting something to work. Best of luck!

# Answer
> -1 votes
If your aim is to control the transitions on the Animator component via code, a simple way to use the Animator and have control via code is to:

1. Create a parameter (in the Animator Parameters tab), say called CupState.
2. Add a condition on the transitions concerning CupState.
3. Change CupState values via code like this:

MyAnimatorInstance.SetInteger("CupState", newState);

There are many ways to manage the controller via code (e.g. using Behaviours) but this is a simple way to start.

---
Tags: unity, animation
---


# Question
Title: How to spawn enemies after a certain amount of time?
I wanted to spawn different enemies(meteors) after a certain amount of time this is the script that I tried doing but it's giving me an error. I'm still just a beginner and I don't if I did something wrong with the script.

The error that I get is:

Assets/Scripts/meteorSpawner.cs(32,12): error CS1660: Cannot convert `lambda expression' to non-delegate type`bool'

and here is my current script

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

public class meteorSpawner : MonoBehaviour {

public GameObject[] meteors;
//int meteorNo;
public float maxPos = 2.4f;
public float delayTimer = 1.25f;
public float timeNeed = 10f;
public float time = 0f;
float timer;

// Use this for initialization
void Start () {
    timer = delayTimer;

}

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

    timer -= Time.deltaTime;
    if(timer <= 0) {
        Vector3 meteorPos = new Vector3(Random.Range(-2.2f, 2.2f), transform.position.y, transform.position.z);
        //meteorNo = Random.Range(0, 2);
        Instantiate(meteors[0], meteorPos, transform.rotation);
        timer = delayTimer;
    }
    time += Time.deltaTime;
    if(time => timeNeed){
        Vector3 meteorPos = new Vector3(Random.Range(-2.2f, 2.2f), transform.position.y, transform.position.z);
        //meteorNo = Random.Range(0, 2);
        Instantiate(meteors[1], meteorPos, transform.rotation);
    }

}
}

```

# Answer
Your immediate problem is just a typo:

* `>=` is a "greater than or equal" comparison
* `=>` defines a lambda expression, which is like creating a little function on the fly. The symbol is like an arrow pointing in the direction of the mapping `(input) => (output)`

Changing to the correct `>=` comparison for your use case will fix the compiler error.

But, this probably won't be what you want. Your old meteors will still continue spawning every `delayTimer` seconds, and your new meteors will start spawning *every frame*, because you keep incrementing `time` without resetting, so `time >= timeNeed` will be true for every subsequent frame.

If instead you want to change from periodic spawning of the first meteor type, to periodic spawning of the second meteor type, what you might want instead is a coroutine like this...

```
// Start a coroutine as soon as the object is spawned & enabled in the scene.
// This coroutine can suspend & resume itself so it continues running across
// multiple frames for the lifetime of the object.
IEnumerator Start() {
    // For the first portion of time, spawn basic meteors.
    for(float time = 0; time < meteorChangeDelay; time += meteorSpawnDelay) {
         Spawn(meteors[0]);
         // Wait until the next spawn time.
         yield return new WaitForSeconds(meteorSpawnDelay);
    }

    // Then switch to spawning advanced meteors for all future spawns.
    while(true) {
         Spawn(meteors[1]);
         yield return new WaitForSeconds(meteorSpawnDelay);
    }
}

void Spawn(GameObject spawnable) {
    Vector3 position = transform.position;
    position.x = Random.Range(-2.2f, 2.2f);
    Instantiate(spawnable, position, transform.rotation);
}

```
> 1 votes

---
Tags: unity, timer
---


# Question
Title: Unity order issue with TilemapRenderer.Render
I'm using unity, with 2D Tilemaps (I'm doing something like an RPG)

I want to have a Tile which should be rendered with a random sprite.

When I use a tile like a tree that is bigger than the tile size and RandomTile, the draw order seems to get confused. Even if the sort order on the Tilemap Renderer is set appropriately, some of the tiles are drawing on top of the other tiles with no consistent pattern.

After stepping through with the Frame Debugger, **it looks like all tiles with the same sprite are drawn at the same Draw Dynamic event under TilemapRenderer.Render.**

I'm using the following script:

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

#if UNITY_EDITOR
using UnityEditor;
#endif

using UnityEngine;

namespace UnityEngine.Tilemaps
{
    [Serializable]
    public class RandomTile : Tile
    {
        [SerializeField]
        public Sprite[] m_Sprites;

        public override void GetTileData(Vector3Int location, ITilemap tileMap, ref TileData tileData)
        {
            base.GetTileData(location, tileMap, ref tileData);
            if ((m_Sprites != null) && (m_Sprites.Length > 0))
            {
                long hash = location.x;
                hash = (hash + 0xabcd1234) + (hash << 15);
                hash = (hash + 0x0987efab) ^ (hash >> 11);
                hash ^= location.y;
                hash = (hash + 0x46ac12fd) + (hash << 7);
                hash = (hash + 0xbe9730af) ^ (hash << 11);
                Random.InitState((int)hash);
                tileData.sprite = m_Sprites[(int) (m_Sprites.Length * Random.value)];
            }
        }

#if UNITY_EDITOR
        [MenuItem("Assets/Create/Random Tile")]
        public static void CreateRandomTile()
        {
            string path = EditorUtility.SaveFilePanelInProject("Save Random Tile", "New Random Tile", "asset", "Save Random Tile", "Assets");

            if (path == "")
                return;

            AssetDatabase.CreateAsset(ScriptableObject.CreateInstance<RandomTile>(), path);
        }
#endif
    }

#if UNITY_EDITOR
    [CustomEditor(typeof(RandomTile))]
    public class RandomTileEditor : Editor
    {
        private RandomTile tile { get { return (target as RandomTile); } }

        public override void OnInspectorGUI()
        {
            EditorGUI.BeginChangeCheck();
            int count = EditorGUILayout.DelayedIntField("Number of Sprites", tile.m_Sprites != null ? tile.m_Sprites.Length : 0);
            if (count < 0)
                count = 0;
            if (tile.m_Sprites == null || tile.m_Sprites.Length != count)
            {
                Array.Resize<Sprite>(ref tile.m_Sprites, count);
            }

            if (count == 0)
                return;

            EditorGUILayout.LabelField("Place random sprites.");
            EditorGUILayout.Space();

            for (int i = 0; i < count; i++)
            {
                tile.m_Sprites[i] = (Sprite) EditorGUILayout.ObjectField("Sprite " + (i+1), tile.m_Sprites[i], typeof(Sprite), false, null);
            }
            if (EditorGUI.EndChangeCheck())
                EditorUtility.SetDirty(tile);
        }
    }
#endif
}

```

Is there any way to fix it?

# Answer
> 1 votes
**Solution: create a SpriteAtlas and put your tree sprites into it**. The tiles will technically become part of one spritesheet, so they will be drawn during the same Draw Dynamic event.
(If you want to see the result straight in play mode, go to *Edit —\> Projects Settings —\> Editor* and set *Sprite Packer Mode* to **Always Enabled**).

# Answer
> 0 votes
I found a solution to this problem. I don't know if you are using a sprite sheet for the trees or not. If not then create a sprite sheet with all your trees in that. Link these sprites from the sheet to your tiles.

Explanation : Since the frame debugger shows one sprite being rendered after the another. The solution should be to render them all at the same time which should be possible through a sprite sheet.

Let me know if this worked for you. It did for me.

---
Tags: unity, 2d, tiles, tilemap
---


# Question
Title: Wall collision response results in jittery physics
I have the following game loop :

```
while true {
    HandleInput()
    Update()
        PhysicsEngine.HandleCollisions()
        PhysicsEngine.Integrate()
    Render()
}

```

For now, `HandleCollisions` is simply negating the velocity vector of the player. The problem is that if I hold the button to walk forward this results in a jittery screen flashing between the render of the forward walk and the backward walk. How can I smooth it out so that it feels like the player has stopped even if I am still pressing the button ?

From what I have found on the internet, Unity's Rigidbody.MovePosition solves this problem, but I was not able to find its implementation online.

One thing that I thought about, but am not sure if it is the solution is the following.

1. Find distance of penetration in the `HandleCollisions` function
2. In the same function move object this much
3. Change velocity to (0,0,0)

The problem here is that from my understanding the *Integration* step should be the one doing the movement and I should only be changing velocity. If that is correct, then I have no idea how to solve it.

edit : removed architecture tag

# Answer
Without knowing specifically what your two physics functions do, I suggest checking for the collision first before moving your player.

Consider the following example:

* Move player.x by 1
* Physics check
* Move player.x by -1
* Result: flicker

As compared to

* Physics check with potential movement (player.x + 1)
* Realise that there is a collision
* Set players velocity to 0
* Result: no flicker.

In the second case, since you are predicting if the player will collide with the wall before moving the player, there is no longer a need to push the player back, hence eliminating the flicker.
> 1 votes

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


# Question
Title: ScriptableObject not saving data in PC Build
I am using ScriptableObject to save state of my game. Currently Saving: \- Selected object \- Object count

It works fine in editor, but when I make a PC build the data doesn't saves and everything I launch the PC build the game is in default state.

My GameConfig ScriptableObject is located in the Resources folder, can anyone help out exactly what the issue can be? The scriptable object is serialized and so are the fields in it.

Unity version: 2017.3.1p1

# Answer
Sorry, but ScriptableObject's don't work that way. They conceptually are game assets. You can modify and save assets in edit mode, but you can not do that in a built game executable. The executable does not even contain the code necessary for writing asset files. So you will have to find a different way to implement savegames.

When your save data is rather small or if you want to support platforms without a writable filesystem (like HTML5) , you can use `PlayerPrefs` for this, which allows you to read and write key/value pairs which get persisted in a platform-appropriate manner.

When your savegames are too large to be handled with PlayerPrefs, then you will have to invent your own savegame format and save data to the user directory using the standard C# classes for file access like `StreamWriter` / `StreamReader` (for text-based formats) or `FileStream` (for binary-based format).
> 4 votes

# Answer
I suggest you don't use .txt IO approach, It will not carry over to your build. use this code out test it out

https://github.com/comphonia/UnityAssetsandScripts/wiki/Read-and-Write-Data-to-a-Text-File-in-Unity

If you're looking for a scalable solution try Firebase(beta) or setup a server database.
> 0 votes

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


# Question
Title: Hinge joint is not firm, leaving connected anchor position
I have a hook with hinge joint which is working fine but as my object quickly move my hook leave its position for a while.

And here is the hinge joint settings with rigidbody:

Here is a short clip of the problem.

# Answer
> 1 votes
The parent object which was moving the Hook working through animation and by setting its animator update mode to **AnimatePhysics**, the problme has resolved. What Animate Physics property do is:

> **When turned on**, animations will be executed in the **physics loop**. This is only useful in conjunction with kinematic rigidbodies.
>
> An animated platform can apply velocity and friction to rigid bodies sitting on top of it. In order to use this, animatePhysics must be enabled and animated object must be a kinematic rigid body.

Now the animation is executing in same physics loop which has resolved the issue.

*Thanks to Chance Millar.*

# Answer
> 1 votes
It may depend if you're using animation for move parent object.

If you move the object using it's transform this could not happen.

---
Tags: unity, physics, rigidbody, hinge-joint
---


# Question
Title: Unity Physics.Raycast give false positive while using layer mask
I'm very new to Unity so please excuse my question if this sounds very basic to you.

I'm following various tutorials and I have a small question regarding `Physics.Raycast`:

```
if (Input.GetButton("Fire1")) {
        // check ground hit first
        RaycastHit hit;
        if (Physics.Raycast(ray, out hit, LayerMask.GetMask("Ground"))) {
            Debug.Log("[PlayerMotion]: Hit" + hit.collider.name + " " + hit.point);
            agent.SetDestination(hit.point);
        }
}

```

Here, even tough I expressively set the layer mask to `"Ground"`, I still get a hit with the Player game object itself (the ground hit is working fine). I thought ok maybe I put the "Ground" layer as well on the player by mistake but I checked several times and it's not the case.

I'm attaching a gif so you can see what's the issue exactly

There's an easy by checking the `collider.name` but I still find it odd that the `Raycast` gives me a false positive with the player hit. Any idea what's going on ?

# Answer
> 2 votes
Make sure you are not passing your layer mask into the `maxDistance` param.

The signature of `Physics.Raycast` (the one that accepts a ray as the first argument) is

```
public static bool Raycast(Ray ray, out RaycastHit hitInfo, float maxDistance = Mathf.Infinity, int layerMask = DefaultRaycastLayers, QueryTriggerInteraction queryTriggerInteraction = QueryTriggerInteraction.UseGlobal);

```

Notice that the third parameter is `maxDistance` and not `layerMask`. In other words, use

```
Physics.Raycast(ray, out hit, Mathf.Infinity, LayerMask.GetMask("Ground"))

```

instead of

```
Physics.Raycast(ray, out hit, LayerMask.GetMask("Ground"))

```

This is a common mistake as `LayerMask.GetMask` returns an `int` which will be implicitly cast into a float and thrown into `maxDistance` instead of `layerMask`.

---
Tags: unity
---


# Question
Title: How to allow a 2D game to work with all screen resolutions without only using Unity's Canvas Scaler
I know there's plenty of questions out there already, however it seems as though there's always an update or change to either the Unity platform, the phone screen sizes, etc.

I'm struggling with trying to get my game to look the same on an iPhone 7+, iPhone 8 (normal) and iPhone X. I set the canvas to scale with screen size and resolution to 1920 x 1080, match width or height, and ref pixels to 100 as many other posts have recommended. However the stretching and pulling really makes the game look horrible.

It is a landscape only card game with a few buttons and up to 4 players whose avatars are represented on each corner if all are playing. So I need the background to stretch but I would prefer the card of the avatars to be almost their exact size in terms of ratios as if they were customized for the device. Think of Hearthstone just with 4 players in each corner.

I know games such as Blizzard's Hearthstone has a huge dev team and they're probably developing different views for each resolution, but there has to be a better or more updated solution for small indy teams like mine.

Is there something we need to do with anchors or our canvases to make all of this look better on all popular phone resolutions? Any help greatly appreciated.

# Answer
> 1 votes
I order to make a game work in different screen sizes here are some tips:

* Unity has variables `Screen.width` and `Screen.height` to get the game's final size. Use this to position objects (2D or UI) on the screen. You want a `Sprite` to be displayed on the top right corner? Then it has `x = Screen.width -my_sprite.width` and `y = 0`.
* When placing UI elements using Unity's Inspector, this becomes easier as you can configure the `AnchorMin` and `AnchorMax` variables, which go from `0` to `1`, `0` being the left/top side and `1` being the right/bottom side.
* If you want an image to have a size influenced by the screen size (for example its `height` being half the size of the screen) then mark it as such. Such an image can have `y = 0` and `height = Screen.height/2`. A UI element can have `anchorMin.y = 0` and `anchorMax.y = 1` instead. Keep in mind UI Sprites have a "Keep aspect ratio" tick box, in case you don't want to distort it.
* When it comes to 3D scene, things are kinda simpler, although it is possible to calculate where a camera can be placed so that the left edge and the right edge of a scene are visible (for example) most games just add a zoom-in zoom-out button, so that players can accommodate the game to their taste.

---
Tags: unity, resolution
---


# Question
Title: how to set angle between points of a bezier curve
From the bezier curve image above, how can I set the angle `r` manually, so that changing it does not affect the distance between `A` and `B`?

# Answer
> 2 votes
```
// Form the direction the tangent should point when the angle is zero.
var zeroAngleDirection = (D - A).normalized;

// Compute a rotation by the desired angle, clockwise about the positive z axis.
var twist = Quaternion.Euler(0, 0, -angle);

// Set point B a desired distance away from A, in the rotated direction.
B = A + twist * zeroAngleDirection * desiredLength;

```

---
Tags: unity
---