# Question
Title: Clone gameobject on drag without having to click a second time
I have a standard Cube gameObject (with a BoxCollider and my CubeController.cs script) in my scene and I want to be able to click and drag on it to instantiate a new cube prefab (with a BoxCollider and my DragController.cs script) which then follows the mouse.

I have it nearly working but when the new cube prefab is instantiated at the same position as the clicked cube (but 10% bigger) you have to then click the new instantiated object again to begin dragging it. I have a debug line printing 'Prefab created' in DragController.cs so the prefab must be sensing that the mouse button is still down.

How can I do it so you click the original cube then the new prefab is created and draggable without having to click again?

**CubeController.cs** \- placed on original Cube gameobject

```
using UnityEngine;

public class CubeController : MonoBehaviour
{
    RaycastHit hitInfo;
    Ray ray;

    public GameObject CubePrefab;
    private bool canCreate = true;

    // Update is called once per frame
    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        }

        if (Physics.Raycast(ray, out hitInfo))
        {
            GameObject objectHit = hitInfo.transform.gameObject;

            if (objectHit.tag == "Cube")
            {
                createCubePrefab();
            }
        }
    }

    void createCubePrefab()
    {
        if (canCreate)
        {
            canCreate = false;
            GameObject newCube = Instantiate(CubePrefab, hitInfo.transform.position, Quaternion.identity);
            newCube.transform.localScale = new Vector3(1.1f, 1.1f, 1.1f);
        }
    }
}

```

**DragController.cs** \- placed on Cube prefab that is going to be instantiated

```
using UnityEngine;

public class DragController : MonoBehaviour
{
    private Vector3 screenPoint;
    private Vector3 offset;

    // Start is called before the first frame update
    void Start()
    {
        if (Input.GetMouseButtonDown(0))
        {
            Debug.Log("Prefab created");
        }
    }

    void OnMouseDown()
    {
        screenPoint = Camera.main.WorldToScreenPoint(gameObject.transform.position);
        offset = gameObject.transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z));
    }

    void OnMouseDrag()
    {
        Vector3 cursorPoint = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z);
        Vector3 cursorPosition = Camera.main.ScreenToWorldPoint(cursorPoint) + offset;
        transform.position = cursorPosition;
    }
}

```

# Answer
Since the clone didn't exist when the mouse was clicked, it wasn't in line to have its `OnMouseDown` method called by the engine, or follow-up `OnMouseDrag` calls on subsequent frames. So it's up to us to call it.

We can do this with a little Coroutine:

```
IEnumerator SyntheticDrag() {
    // Process the start of our drag, and then wait a frame.
    OnMouseDown();
    yield return null;

    // Keep updating our dragged position each frame
    // until the mouse button is released.
    while(Input.GetMouseButton(0)) {
        OnMouseDrag();
        yield return null;
    }
}

```

Now we need to start this Coroutine. Two places you could do that, depending on which suits you best:

1. Inside `DragController.Start()`, when you determine that the mouse was already pressed when the object was instantiated, do a raycast to verify that the mouse is pointing over this object. If so, call `StartCoroutine(SyntheticDrag())`.

(The raycast check avoids false positives in case you use this script in any other circumstances where the object could spawn away from the mouse pointer, and the user just happened to have the mouse button pressed for an unrelated reason - you wouldn't want to start dragging in that circumstance)

Or...
2. Add to DragController a public method like this:

`public void StartDrag() { StartCoroutine(SyntheticDrag);}`

Inside `CubeController.CreateCubePrefab()` (use PascalCase for method names for consistency), after you've spawned your clone, use `GetComponent<DragController>` to get a reference to the drag script (or use this type for your prefab variable so you get the right component back from `Instantiate()` in one go). Then call `StartDrag()` on it to initiate the mouse drag.
> 0 votes

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


# Question
Title: Flat Shading does not work correctly (openGL)
So currently I'm trying to implement flat shading into my engine using glsl's flat qualifier, and I have encounterd a really weird bug.

Somehow the lightning on terrain isn't spread correctly, I want to make the lightning to similar to this:

Here is the terrain generation code:

```
private RawModel generateTerrain(Loader loader, String
heightMap) {

    BufferedImage image = null;

    try {
        image = ImageIO.read(new File("res/textureMap/" + heightMap + ".png"));
    } catch (IOException e) {
        e.printStackTrace();
    }

    int VERTEX_COUNT = image.getHeight(); // this is the number of vertices along the size of the terrain
    heights = new float[VERTEX_COUNT][VERTEX_COUNT];
    int count = (VERTEX_COUNT * VERTEX_COUNT);
    float[] vertices = new float[count * 3];
    float[] normals = new float[count * 3];
    float[] textureCoords = new float[count * 2];
    int[] indices = new int[6*(VERTEX_COUNT)*(VERTEX_COUNT)];

    int vertexPointer = 0;
    for (int i = 0; i < VERTEX_COUNT; i++) {
        for (int j = 0; j < VERTEX_COUNT; j++) {
            vertices[vertexPointer * 3] = (float) j / ((float) VERTEX_COUNT - 1) * SIZE;
            float height = getHeight(j, i, image);
            heights[j][i] = height;
            vertices[vertexPointer * 3 + 1] = height;
            vertices[vertexPointer * 3 + 2] = (float) i / ((float) VERTEX_COUNT - 1) * SIZE;
            Vector3f normal = calculateNormal(j, i, image);
            normals[vertexPointer * 3] = normal.x;
            normals[vertexPointer * 3 + 1] = normal.y;
            normals[vertexPointer * 3 + 2] = normal.z;
            textureCoords[vertexPointer * 2] = (float) j / ((float) VERTEX_COUNT - 1);
            textureCoords[vertexPointer * 2 + 1] = (float) i / ((float) VERTEX_COUNT - 1);
            vertexPointer++;
        }
    }
    int pointer = 0;
    for (int gz = 0; gz < VERTEX_COUNT - 1; gz++) {
        for (int gx = 0; gx < VERTEX_COUNT - 1; gx++) {
            int topLeft = (gz * VERTEX_COUNT) + gx;
            int topRight = topLeft + 1;
            int bottomLeft = ((gz + 1) * VERTEX_COUNT) + gx;
            int bottomRight = bottomLeft + 1;
            indices[pointer++] = topLeft;
            indices[pointer++] = bottomLeft;
            indices[pointer++] = topRight;
            indices[pointer++] = topRight;
            indices[pointer++] = bottomLeft;
            indices[pointer++] = bottomRight;
        }
    }
    return loader.loadToVAO(vertices, textureCoords, normals, indices);
}

```

Here is how I generate normals:

```
private Vector3f calculateNormal(int x, int z, BufferedImage
image) {
    float heightL = getHeight(x - 1, z, image);
    float heightR = getHeight(x + 1, z, image);
    float heightD = getHeight(x, z - 1, image);
    float heightU = getHeight(x, z + 1, image);

    Vector3f normal = new Vector3f(heightL - heightR, 1f, heightD - heightU);
    normal.normalise();
    return normal;

}
private float getHeight(int x, int z, BufferedImage image) {

    if (x < 0 || x >= image.getHeight() || z < 0 || z >= image.getHeight()) {
        return 0;
    }
    float height = image.getRGB(x, z);

    height += MAX_PIXEL_COLOUR / 2f;
    height /= MAX_PIXEL_COLOUR / 2f;
    height *= MAX_HEIGHT;
    return height;
}

```

Here is the terrain vertex shader code:

```
#version 400

in vec3 position;
in vec2 textureCoordinates;
in vec3 normal;

out vec2 pass_textureCoordinates;
flat out vec3 surfaceNormal;
out vec3 toLightVector[4];
out vec3 toCameraVector;
out vec4 shadowCoords;
out float visibility;
flat out vec4 pass_colour;

uniform mat4 transformationMatrix;  // the entity's position
relative to the world [-1 1 1 -1]
uniform mat4 projectionMatrix;      // transform's
everything into a viewing frustum (farther away in -z the
smaller everything gets foreshortening)
uniform mat4 viewMatrix;            // camera's perspective
uniform vec3 lightPosition[4];          // location of the
light source (only one source of light so far)
uniform mat4 toShadowMapSpace;

const float shadowDistance = 100; // it has to be the same
value as the shadowbox shadow distance
const float transitionDistance = 10.0;

const float density = 0.0023;
const float gradient = 50.0;;

uniform vec3 lightColour[4];        //light source's color
(which can change)
uniform vec3 attenuation[4];        //one for each light
source
uniform float shineDamper;
uniform float reflectivity;

void main(void){

vec4 worldPosition = transformationMatrix *
vec4(position,1.0); // position is the position of the
current vertex
vec4 positionRelativeToCam = viewMatrix * worldPosition;
shadowCoords = toShadowMapSpace * worldPosition;

gl_Position = projectionMatrix * positionRelativeToCam;
// NOTE: viewMatrix must go in between the projectionMatrix
and transformationMatrix
pass_textureCoordinates = textureCoordinates;
surfaceNormal = (transformationMatrix * vec4(normal,
0.0)).xyz; //(swizzle it) convert from vec4 back to vec3

for(int i = 0; i < 4; i++) {
    toLightVector[i] = lightPosition[i] - worldPosition.xyz;
}
toCameraVector = (inverse(viewMatrix) *
vec4(0.0,0.0,0.0,1.0)).xyz - worldPosition.xyz;

float distance = length(positionRelativeToCam.xyz);
visibility = exp(-pow((distance*density), gradient));
visibility = clamp(visibility, 0.0, 1.0);

distance = distance - (shadowDistance - transitionDistance);
distance = distance / transitionDistance;
shadowCoords.w = clamp(1.0-distance, 0.0, 1.0);

vec3 unitNormal  = normalize(surfaceNormal);
vec3 unitVectorToCamera = normalize(toCameraVector);

vec3 totalDiffuse = vec3(0.0);
vec3 totalSpecular = vec3(0.0);
float lightFactor = 0.5;

for(int i = 0; i < 4; i++) {
    float distance = length(toLightVector[i]);
    float attenuationFactor = attenuation[i].x +
(attenuation[i].y * distance) + (attenuation[i].z * distance
* distance);

    vec3 unitLightVector = normalize(toLightVector[i]);  // pointing from the surface to the light source

    float nDot1 = dot(unitNormal, unitLightVector);
    float brightness = max(nDot1, 0.0);

    vec3 lightDirection = -unitLightVector;           // pointing from the light source to the surface
    vec3 reflectedLightDirection = reflect(lightDirection, unitNormal);

    float specularFactor = dot(reflectedLightDirection, unitVectorToCamera);
    specularFactor = max(specularFactor, 0.0);
    float dampedFactor = pow(specularFactor, shineDamper);

    totalDiffuse = totalDiffuse + (brightness*lightColour[i])/attenuationFactor;
    totalSpecular = totalSpecular + (dampedFactor * reflectivity * lightColour[i])/attenuationFactor;
}

totalDiffuse = max(totalDiffuse * lightFactor, 0.3);
pass_colour = vec4(totalDiffuse, 1.3) + vec4(totalSpecular, 1.0);

```

}

Here is the terrain fragment shader code:

```
#version 400

in vec2 pass_textureCoordinates;
flat in vec3 surfaceNormal;
in vec3 toLightVector[4];
in vec3 toCameraVector;
in float visibility;
in vec4 shadowCoords;

out vec4 out_Color;
flat in vec4 pass_colour;

uniform sampler2D backgroundTexture;
uniform sampler2D rTexture;
uniform sampler2D gTexture;
uniform sampler2D bTexture;
uniform sampler2D blendMap;
uniform sampler2D shadowMap;

uniform vec3 lightColour[4];        //light source's color
(which can change)
uniform vec3 attenuation[4];        //one for each light
source
uniform float shineDamper;
uniform float reflectivity;
uniform vec3 skyColour;

const int pcfCount = 0;
const float totalTexels = (pcfCount * 2.0 + 1.0) * (pcfCount
*
2.0 + 1.0);
uniform float usesNormalMap;

vec3 totalDiffuse;

void main(void){

float mapSize = 1024; // must be the same as the SHADOW_MAP_SIZE in the shadow masterRenderer
float texelSize = 1.0 / mapSize;
float total = 0.0;

for(int x=-pcfCount; x<=pcfCount; x++){
        for(int y=-pcfCount; y<=pcfCount; y++){
            float objectNearestLight = texture(shadowMap, shadowCoords.xy + vec2(x,y) * texelSize).r;
                if(shadowCoords.z > objectNearestLight + 0.002){
                    total += 1.0;
                }
    }
}

total /= totalTexels;

float lightFactor = 1.0 - (total * shadowCoords.w);

vec4 blendMapColour = texture(blendMap, pass_textureCoordinates);

float backTextureAmount = 1 - (blendMapColour.r + blendMapColour.g + blendMapColour.b);
vec2 tiledCoords = pass_textureCoordinates * 40;

vec4 backgroundTextureColour = texture(backgroundTexture, tiledCoords) * backTextureAmount;
vec4 rTextureColour = texture(rTexture, tiledCoords) * blendMapColour.r;
vec4 gTextureColour = texture(gTexture, tiledCoords) * blendMapColour.g;
vec4 bTextureColour = texture(bTexture, tiledCoords) * blendMapColour.b;

vec4 totalColour = backgroundTextureColour + rTextureColour + gTextureColour + bTextureColour;

out_Color = mix(vec4(skyColour, 1.0), pass_colour*totalColour, visibility);

```

}

# Answer
> 1 votes
I'm not sure about your normals. Taking Calculate Normals from Heightmap as reference, I'd say change it like this:

```
private Vector3f calculateNormal(int x, int z, BufferedImage image) {
    float heightL = getHeight(x - 1, z, image);
    float heightR = getHeight(x + 1, z, image);
    float heightD = getHeight(x, z - 1, image);
    float heightU = getHeight(x, z + 1, image);

    Vector3f normal = new Vector3f((heightL - heightR), -2f, (heightD - heightU));
    normal.normalise();
    return normal;
}

```

*Changed 1f to -2f.*

---

How do we get that?

Well, first of all, I will no use gradients, because I am not that confident in my vector calculus.

Instead, I will find the normal as the cross product of the tangents. Since the tangents follow the surface, and the cross product is perpendicular to its input vectors... the cross product of the normals is perpendicular to the surface.

We are taking the xtangent and ztangent (I think they are tangent and bitangent, I do not know which is which one, don't care) like this:

```
Vector3f l = new Vector3f(x - 1f, heightL, z);
Vector3f r = new Vector3f(x + 1f, heightR, z);
Vector3f d = new Vector3f(x, heightD, z - 1f);
Vector3f u = new Vector3f(x, heightU, z + 1f);

//Vector3f xtangent = d - u;
//Vector3f xtangent = new Vector3f(x - x, heightD - heightU, (z - 1f) - (z + 1f));
Vector3f xtangent = new Vector3f(0f, heightD - heightU, -2f);

//Vector3f ytangent = l - r;
//Vector3f xtangent = new Vector3f((x - 1f) - (x + 1f), heightL - heightR, z - z);
Vector3f xtangent = new Vector3f(-2f, heightL - heightR, 0f);

```

And we do cross product to get the normal:

```
//Vector3f normal = normalize(cross(ytangent, xtangent));
//Vector3f normal = normalize(new Vector3f
//          (
//              ytangent.y * xtangent.z - ytangent.z * xtangent.y,
//              ytangent.x * xtangent.z - ytangent.z * xtangent.x,
//              ytangent.x * xtangent.y - ytangent.y * xtangent.x
//          ));
//Vector3f normal = normalize(new Vector3f
//          (
//              (heightL - heightR) * (-2f) - (0f) * (heightD - heightU),
//              (-2f) * (-2f) - (0f) * (0f),
//              (-2f) * (heightD - heightU) - (heightL - heightR) * (0f)
//          ));
//Vector3f normal = normalize(new Vector3f
//          (
//              (heightL - heightR) * (-2f),
//              (-2f) * (-2f),
//              (-2f) * (heightD - heightU)
//          ));
Vector3f normal = normalize(new Vector3f
          (
              (-2f) * (heightL - heightR),
              (-2f) * (-2f),
              (-2f) * (heightD - heightU)
          ));

```

And since we are normalizing anyway, we can get rid of that common scaling factor of `-2f`:

```
Vector3f normal = normalize(new Vector3f
          (
              (heightL - heightR),
              (-2f),
              (heightD - heightU)
          ));

```

That is like what you have, right?

```
Vector3f normal = new Vector3f((heightL - heightR), -2f, (heightD - heightU));
normal.normalize();

```

Except, I have a `-2f`.

**Note**: fliping the vectors in the cross product, should flip the signs. However, that ends up meaning we remove a common scaling factor of `2f` instead. After that, the result is the same as above.

---

Let us compare with the result from link I had at the top:

So, because we are normalizing, we do not need that `1/4`, and we can simplify by `2`, and we end up with a `-2` (from the `-4`).

They have it on the `z` while we have it on the `y` because that is how the height map was oriented in space, I guess.

And I also notice they have `R - L` instead of `L - R`. Perhaps I should have flipped it? Or perhaps that is because of the coordinate system you use? Well, that is a simple test you can do. By the way, their `T` (top) is our `U` (up) and their `B` (bottom) is our `D` (down). So `B - T` is `D - U`, and that is the same we have.

Finally, I suppose that flipping it all makes sense if we are looking at the height map from the other side:

```
Vector3f normal = new Vector3f((heightR - heightL), 2f, (heightU - heightD));

```

---
Tags: opengl, java, lighting
---


# Question
Title: How can I implement versioning into a save system?
I currently have a crude save system in my game.

When my game is first launched after download, it checks for three directories in a certain location on the client computer, `user://save1`, `user://save2`, and `users://save3`.

If these directories don't exist, they are created with some empty files `player_data.save`, `level_data.save`, `persistence_data.save` and `meta_data.save`.

Then, at periodic points in my game, these files are updated. (Which base directory is used depends on which save slot the player chose when they selected a new game, or loaded.)

I have read a lot about the importance of versioning to protect compatibility with saves (for example, here and here).

**So, how I can implement versioning into this save system to protect myself from incompatibilities when I inevitably release updates and patches to the game?**

For example, is it advisable to create different save *directories* per game version, so that on boot you check if you have a save directory corresponding to your current game version? Or is it advisable to just have a single save directory and merely save a text file with the version number in the sub directories?

A structure like:

```
version_1_saves
    save1
    save2
    save3

version_2_saves
    save1
    save2
    save3

```

Or a structure like:

```
saves
    save1
        version.txt
    save2
        version.txt
    save3
        version.txt

```

And what do the checks look like when you do release an update and need to check for compatibility when a player boots the game or tries to load an old save?

# Answer
You could add a version number to your savegame file format itself. The savegame loader loads the savegame file as plain data, checks the version number which it expects in a specific position and then passes the data to the correct loading/upgrading strategy for parsing.

This, of course, means that you are no longer able to change your savegame format in a way which would break the version number detection. But that should not be an issue if you have that information relatively close to the start of the file.
> 4 votes

# Answer
The last example is the best way.

Pros

* There will only be 3 saves max.
* Easily read what version the save is.

Cons

* It will use unnecessary space on your player's system.
* Has to parse the file name to get the version number.

I would just create a json file that you can read into your save system to get the correct version files. Json file can store created date or even computer that was created on so you can verify that the user didn't download a save from someone else.

If the save file is from another version you could make changes that match with the latest version of the game/save file. Such as enemy1 doesn't exist in the game anymore.

Example:

```
If saveFile.version < 1.1.1 {
 //Remove enemy1 from save
}

```
> 1 votes

---
Tags: architecture, loading, savegame
---


# Question
Title: Why is transform.up behaving differently for different functions?
Can anyone please explain to me what i'm doing wrong here?

As I see it the raycast is the only one using transform.up correctly, though why not Debug.DrawLine() and \_lineRenderer.SetPosition(1, transform.up * maximumBeamLength);

```
using UnityEngine;

[RequireComponent(typeof(LineRenderer))]
public class LaserBeam : MonoBehaviour
{
    [SerializeField]
    private float maximumBeamLength = 5f;

    private LineRenderer _lineRenderer;

    private void Start()
    {
        _lineRenderer = GetComponent<LineRenderer>();
    }

    void Update()
    {
        _lineRenderer.SetPosition(0, transform.position);
        RaycastHit2D hit = Physics2D.Raycast(transform.position, transform.up);

        Debug.DrawLine(transform.position, transform.up * maximumBeamLength, Color.blue);
        Debug.DrawLine(transform.position, transform.up , Color.red);

        if (hit.collider)
        {
            _lineRenderer.SetPosition(1, new Vector3(hit.point.x, hit.point.y, transform.position.z));
        }
        else
        {
            _lineRenderer.SetPosition(1, transform.up * maximumBeamLength);
        }
    }
}

```

# Answer
Debug.DrawLine expects all coordinates to be in **world space**. So, instead of

```
 Debug.DrawLine(transform.position, transform.up * maximumBeamLength, Color.blue);
 Debug.DrawLine(transform.position, transform.up , Color.red);

```

it should be

```
Debug.DrawLine(transform.position, transform.position + transform.up * maximumBeamLength, Color.blue);
Debug.DrawLine(transform.position, transform.position + transform.up , Color.red);

```
> 2 votes

---
Tags: unity
---


# Question
Title: How can I send different contoller input to the different player avatars?
My apologies in advance for the vague question, since I don't understand the problem well enough to ask in finer detail.

I want to create a multi-player Unity application using the Oculus SDK. Let's say there are two players in the scene, A and B. The problem is this: When player A presses a button using his index finger, the hand avatar for player B also displays a moving index finger. In short, hand movements for one player are also observed for the other. Controller inputs are also read without any ability to distinguish whether they originate from player A or B.

What are the possible approaches for eliminating this problem, if it is mandatory that I continue using Oculus SDK?

# Answer
> 0 votes
I think the Illusion of multiplayer can be confusing sometimes. In the background there is only one input to feed and that is the 'localPlayer' clients, so all you really need to do is check

`if(!isLocalPlayer)return;` right above where you feed the input to just exit out of sending it.

Or you can wrap the input method in a `if(isLocalPlayer)` That way only the correct player feeds that input to the server.

Then the server will sync up all the clients actions so they still get to use input also it's just coming from their own client.

a simple example

```
void Update () {
    if (!isLocalPlayer) return;
    var h = Input.GetAxis("Horizontal");
    var v = Input.GetAxis("Vertical");
    TranslateMove(h,v);
}
void TranslateMove(float h, float v)
{
    transform.Translate(new Vector3(h, 0, 0) * 3 * Time.deltaTime);
    transform.Translate(new Vector3(0, 0, v) * 3 * Time.deltaTime);
}

```

above only the localPlayer can control the input otherwise it will exit out. the server handles syncing up the rest of the clients inputs and movements.

note : you would also want to check `if(isLocalPlayer)` on anything that handles remote actions or things like handling damage(if you get damaged you don't want every client to receive it), basically anything that only the localplayer should be considered.

---
Tags: unity, c#, multiplayer, oculus
---


# Question
Title: How to preserve Arcball rotation in c++ OpenGL?
*Firts of all want to say that I've already searched for other people's answers here as same as Google and didn't found anything about it there. Also tried some others arcball implementations but none of them worked as good as the one using at this moment or use older OGL versions.*

So I'm following this github page code by subokita to implement an arcball camera myself and got to the point where it works and noticed that whenever you release the mouse and click again the view comes back to the start position. I know that it happens because of the model rotation matrix obtained from prevPos and currPos comes back to the start whenever you click again since prevPos changes but can't see a clear solution to preserve the previous state without messing up the view.

I tried moving the model to the camera class and having two variables for it that gets exchanged depending on the mouse action as seen in the code below so that it calculate the state over a previous model value when dragging and use the result of it when no dragging being made. But even if it works it produces weird frames at the beggining of the cursor redrag(video) even though it success on preserving the previous state and I have no idea why.

**Arcball.cpp**

```
// Arcball.h > glm::mat4 model, smodel = glm::mat4(1.0);
glm::mat4 Arcball::createModelRotationMatrix(glm::mat4& view_matrix) {
    switch (mouseEvent)
    {
    case 0:
        return model = smodel;
    case 2:
        glm::vec3 axis = glm::inverse(glm::mat3(view_matrix)) * camAxis;
        return smodel = glm::rotate(glm::degrees(angle) * rollSpeed, axis) * model;
    }
}

```

**main.cpp**

```
glm::mat4 rotated_model = arcball.createModelRotationMatrix(view);
glm::mat4 mvp = projection * view * rotated_model;

```

How can I modify this arcball to preserve the rotation when a redrag occurs?

Thanks for your time.

# Answer
> 1 votes
What troubles me is you're not using quaternions for an Arcball camera.

My answer comes from some of my DirectX code so if you see some strange behavior, I probably messed it up for OpenGL ;)

1. it is far more simple to use quaternions, even if that sounds barbarian to you, it is easier to wrap ones mind around quaternions than matrices (of course in the end you will convert that quaternion into a matrix to use with opengl)

The quaternion basically define an axe and an angle around that axe, there is nothing special to manage unlike when you're using Euler angles (ok there is one problematic case only, which you will see in the code).
2. Quaternions interpolate nicely if you want to switch from one viewpoint to another
3. camera updates /computation are faster using quaternion (only 4 values instead of 16) but i guess most people will say it is inconsequent (but i don't like wasting cpu)

Some basic implementation: (note that I access one of my settings here that allow or not for totally free camera rotation, test with and without, to your taste)

```
Quaternion QuaternionFromVector(const Vec3& Vec1, const Vec3& Vec2)
{
    float norm_u_norm_v = (float)sqrt(Vec3Dot(Vec1, Vec1) * Vec3Dot(Vec2, Vec2));
    float real_part = norm_u_norm_v + Vec3Dot(Vec1, Vec2);
    Vec3 w;

    if (real_part < 0.000001f * norm_u_norm_v)
    {
        // If u and v are exactly opposite, rotate 180 degrees
        // around an arbitrary orthogonal axis. Axis normalisation
        // can happen later, when we normalise the quaternion.
        real_part = 0.0f;
        w = abs(Vec1.x) > abs(Vec1.z) ? Vec3(-Vec1.y, Vec1.x, 0.0f)
            : Vec3(0.0f, -Vec1.z, Vec1.y);
    } else
    {
        // build quaternion the standard way.
        w = Vec3Cross(Vec1, Vec2);
    }

    Quaternion Quat = QuaternionInit(w, real_part);
    QuaternionNormalize(Quat);
    return Quat;
}

    class Camera3D
    {
    public:

        int ViewWidth;
        int ViewHeight;
        float Distance = -500.0f; // set default distance here
        float ZNear = 1.0f; // closest view distance to focal point
        float ZFar = 30000.0f; // farthest view distance to focal point

        Vec3 VecPosition = { 0.0f, 0.0f, 0.0f };
        Vec3 VecFocalPoint = { 0.0f, 0.0f, 0.0f };
        Vec3 VecUp = { 0.0f, 0.0f, 1.0f };

        float TranslateH = 0.0f;
        float TranslateV = 0.0f;
        Vec3 CurrentTranslation = { 0.0f, 0.0f, 0.0f };
        Vec3 TrackingOffset = { 0.0f, 0.0f, 0.0f }; // camera's default tracking offset (typically, the center of the object)

        float AngleH = 0.0f;
        float AngleV = 0.0f;

        Quaternion OrientationQuaternion = { 0.0f, 0.0f, 0.0f, 1.0f };

        Camera3D(void)
        {
        }

        Camera3D(int ExplicitViewWidth, int ExplicitViewHeight)
        {
            // view width and height of the scene window, in pixels

            ViewWidth = ExplicitViewWidth;
            ViewHeight = ExplicitViewHeight;

            // reset the camera
            VecPosition = { 0.0f, Distance, 0.0f };
        }

        void Resize(int ExplicitViewWidth, int ExplicitViewHeight)
        {
            // call this when the scene window resizes

            ViewWidth = max(64, ExplicitViewWidth);
            ViewHeight = max(64, ExplicitViewHeight);
        }

        void Zoom(float ZoomFactor)
        {
            // zoom in/out of the scene. zoom factor as a magnitude factor. E.g "2" halves the distance to focal point.

            Distance = min(max(Distance * (1.0f / ZoomFactor), -20000.0f), 0.0f);
        }

        void TranslateCam(float HorizontalShift, float VerticalShift)
        {
            // translates the camera horizontally or vertically

            TranslateH += HorizontalShift;
            TranslateV += VerticalShift;
        }

        void RotateCam(float HorizontalShift, float VerticalShift)
        {
            // rotates the camera horizontally or vertically

            AngleH += HorizontalShift;
            AngleV += VerticalShift;
        }

        Matrix GetViewMatrix()
        {
            // computes and returns matrix of the camera

            Vec3 VecDistance = Vec3(0.0f, Distance, 0.0f);

            Vec3 PrePos = Vec3TransformCoord(VecDistance, FLT_MatrixRotationQuaternion(OrientationQuaternion));

            // recompute the up and right vector
            Vec3 VecDir = Vec3Normalize(PrePos - VecFocalPoint);
            Vec3 VecRight = Vec3Normalize(Vec3Cross(VecUp, VecDir));

            VecUp = Vec3(0.000001f, 0.000001f, 1.0f); // cheat
            Vec3 RealVecUp = Vec3Normalize(Vec3Cross(VecDir, VecRight));

            if (!Settings::Inst().getUserSettings()->getBoolValue("NoCameraRoll"))
                VecUp = RealVecUp;

            // has a camera rotation been requested ?
            if ((AngleH != 0.0f) || (AngleV != 0.0f))
            {
                // compute both angles and modify the orientation
                OrientationQuaternion *= QuaternionFromVector(VecUp + VecDir * -AngleV, VecUp);
                OrientationQuaternion *= QuaternionFromVector(VecDir + VecRight * -AngleH, VecDir);
                QuaternionNormalize(OrientationQuaternion);// renormalize

                AngleH = 0.0f; // rotation order was processed, clear the variables
                AngleV = 0.0f;
            }

            // has a camera translation been requested ?
            if (TranslateH != 0.0f || TranslateV != 0.0f)
            {
                // translate depending on the current orientation, i.e. adjust the CurrentTranslation vector depending on VecUp and VecRight
                CurrentTranslation += VecRight * TranslateH;
                CurrentTranslation += RealVecUp * TranslateV;

                TranslateH = 0.0f; // translation order was processed, clear the variables
                TranslateV = 0.0f;
            }

            // transform the position with the new orientation
            VecPosition = Vec3TransformCoord(VecDistance, MatrixRotationQuaternion(OrientationQuaternion));

            // and return the view matrix
            return MatrixLookAtRH(VecPosition + CurrentTranslation + TrackingOffset, VecFocalPoint + CurrentTranslation + TrackingOffset, VecUp);
        }

        Matrix GetProjectionMatrix()
        {
            // returns the projection matrix of the camera

            return MatrixPerspectiveFovRH(Constants::Pi / 4.0f, (float)ViewWidth / (float)ViewHeight, ZNear, ZFar);
        }
    };

```

Edit: added missing function, cleaned the code a bit.

---
Tags: opengl, c++, 3d, camera
---


# Question
Title: What is a proper way to handle player inputs based on different states?
So, I have two ideas how to do that:

* Use enum to define current state and check current state value before running certain method group in Update. Code:

```
void Update()
{switch(currentState){
    case 1:
        InputGroup1();
        break;
    case 2:
        InputGroup2();
        break;
    <...>
}

```

And so on. I don't think that this is a good idea because of possible performance drops.
* Same concept about current state, but instead of checking it and running method groups, "head" script will check current state and activate corresponding script, disabling others. For me it looks like best way in terms of performance and usability.

And also, is it better to keep all input checks in one giant script/component and call functions you need from it? Essentially creating centralized Input Manager.

# Answer
> 1 votes
You are prematurely optimizing and wasting precious time and brain juice.

Deciding *where* an `if`/`switch` should go when it's called only once or so per frame is irrelevant, most of the time.

Until you have your game quite developed, you should not worry about such optimizations. *Then* use a profiler to see where the bottlenecks are and fix and optimize actual issues.

Meanwhile, write the code that is the clearest for you and your team. In 6 months from now, you'll be glad you wrote clean and clear code because it will make it much easier to maintain.

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


# Question
Title: Unity Gyroscope orientation (attitude) "wrong"
I am using the Unity reference and example implementation here https://docs.unity3d.com/ScriptReference/Gyroscope.html

I struggle to fix an orientation problem. When my phone lies flat on the ground, screen facing upwards, unity thinks I am looking as if I'd take a photo of a landscape. When I actually hold the phone as if I'd take a landscape photo, the screen shows me the sky. Rotating then shows me an arc from sky to my left or right side.

What I want is: Holding the phone as if I'd take a landscape picture should do the same in Unity.

Here is a short video where the phone lies flat and then I pick it up and look left and right on a chair.

and this is the codesnipped responsible:

```
protected void Update()
{
    GyroModifyCamera();
}

void GyroModifyCamera()
{
    transform.rotation = GyroToUnity(Input.gyro.attitude);
}

// The Gyroscope is right-handed.  Unity is left handed.
// Make the necessary change to the camera.
private static Quaternion GyroToUnity(Quaternion q)
{
    return new Quaternion(q.x, q.y, -q.z, -q.w);
}

```

# Answer
> 2 votes
I solved the problem with another Quaternion multiplication (rotation). Keep in mind: The Quaternion multiplication order does matter.

The Code is the following

```
private Gyroscope phoneGyro;
private Quaternion correctionQuaternion;

// Start is called before the first frame update
void Start()
{
    phoneGyro = Input.gyro;
    phoneGyro.enabled = true;
    correctionQuaternion = Quaternion.Euler(90f, 0f, 0f);
}

// Update is called once per frame
void Update()
{
        GyroModifyCamera();
}

// The Gyroscope is right-handed.  Unity is left handed.
// Make the necessary change to the camera.
void GyroModifyCamera()
{
    Quaternion gyroQuaternion = GyroToUnity(Input.gyro.attitude);
    // rotate coordinate system 90 degrees. Correction Quaternion has to come first
    Quaternion calculatedRotation = correctionQuaternion * gyroQuaternion;
    transform.rotation = calculatedRotation;
}

private static Quaternion GyroToUnity(Quaternion q)
{
    return new Quaternion(q.x, q.y, -q.z, -q.w);
}

```

---
Tags: unity, orientation, gyroscope
---


title: How to make a car follow a path?

text:
# Question
Title: How to make a car follow a path?
I have a 2D game and my goal is to make a car follow a path (the road in the picture) and rotate in the same time. I tried a plugin in the assets store but it didn't work well for me and i had difficulties making work as intended. If you have any suggestions, i ready to listen. Thanks for help in advance.

# Answer
Thanks everyone for your help. I wanted to say that i achieved the steering behavior of a car by applying what i found in this video(https://www.youtube.com/watch?v=11ofnLOE8pw&t=423s) I edited the scripts furthermore to suit my needs and i added this script which i found also in another video in order to make the car rotate along with the road above(https://www.youtube.com/watch?v=mKLp-2iseDc):

```
  Vector3 targetInVec3 = new Vector3(targetPosition.x, targetPosition.y , 0f);
  Vector3 direction2 = targetInVec3 - transform.position;
  float angle = Mathf.Atan2(direction2.y, direction2.x) * Mathf.Rad2Deg;
  Quaternion rotation = Quaternion.AngleAxis(angle, Vector3.forward);
  transform.rotation = rotation;

```

Note: the angle variable can be changed to work with the initial rotation of your object. \- target is the position of the next point on the curve.

If you have any question feel free to ask me.
> 1 votes

# Answer
Best way I can think of for it to follow the path is use way points, my only guess for the rotation would be having it look at the next rotation in the line.
> 0 votes

---
Tags: unity, navmesh, car, path
---


# Question
Title: How to prevent/"reverse" displacement from a collision?
* In my game I can throw a hammer. The hammer moves based on physics in Unity.
* The hammer destroys the first object it touches. **I want it to continue moving as though it didn't touch anything when this happens.**
* To try and achieve this, I made it destroy objects **using a separate, larger trigger collider**, intending to destroy the object before the physical collision occurs.
* However, when **moving at very high speeds** (as in the GIF), **both colliders hit at once**, so the hammer moves and the object deletes.

How can I prevent the hammer from moving when/before the trigger occurs, or (I suppose more realistically) "reverse" the movement such that there's no perceptible collision?

I tried using the impulses from each of the contacts in the collision to apply forces in reverse, but didn't really understand what I was doing and ultimately failed.

NOTE: I cannot simply disable the physics collider, because it doesn't destroy everything.

# Answer
I assume you’re handling either OnTriggerEnter or OnCollisionEnter. Try capturing RigidBody.velocity in there, then set a flag to set the RigidBody.velocity to the captured Vector3 in the next FixedUpdate.
> 1 votes

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


# Question
Title: How do I use raycast to put a bullet hole on a curved surface?
EDIT: As of yet I have not been able to find a way to make the bullet hole wrap around the corner of a gameobject.

I am working on a fps game that uses raycast for shooting and so far it works, but the problem is with the bullet holes. So the script will generate bullet holes (not going to explain everything it does) like it is supposed to.

The problem is that if I shoot the corner the bullet hole will just generate on whatever side the impact was closest to. How do I get the bullet hole to spawn on curves and corners? Here is the script:

```
public class HitFXManager : MonoBehaviour
{

    [Range(1, 200)]
    public int decalsPoolSizeForEachType;

    public GameObject concreteDecal;
    public GameObject woodDecal;
    public GameObject dirtDecal;
    public GameObject metalDecal;

    [HideInInspector]
    public GameObject[] concreteDecal_pool;
    [HideInInspector]
    public GameObject[] woodDecal_pool;
    [HideInInspector]
    public GameObject[] dirtDecal_pool;
    [HideInInspector]
    public GameObject[] metalDecal_pool;

    void Start()
    {
        DecalsPool();
    }

    public void DecalsPool()
    {
        concreteDecal_pool = new GameObject[decalsPoolSizeForEachType];
        var decalsParentObject_concrete = new GameObject("decalsPool_concrete");

        for (int i = 0; i < decalsPoolSizeForEachType; i++)
        {
            concreteDecal_pool[i] = Instantiate(concreteDecal);
            concreteDecal_pool[i].SetActive(false);
            concreteDecal_pool[i].transform.parent = decalsParentObject_concrete.transform;
        }

        woodDecal_pool = new GameObject[decalsPoolSizeForEachType];
        var decalsParentObject_wood = new GameObject("decalsPool_wood");

        for (int i = 0; i < decalsPoolSizeForEachType; i++)
        {
            woodDecal_pool[i] = Instantiate(woodDecal);
            woodDecal_pool[i].SetActive(false);
            woodDecal_pool[i].transform.parent = decalsParentObject_wood.transform;
        }

        dirtDecal_pool = new GameObject[decalsPoolSizeForEachType];
        var decalsParentObject_dirt = new GameObject("decalsPool_dirt");

        for (int i = 0; i < decalsPoolSizeForEachType; i++)
        {
            dirtDecal_pool[i] = Instantiate(dirtDecal);
            dirtDecal_pool[i].SetActive(false);
            dirtDecal_pool[i].transform.parent = decalsParentObject_dirt.transform;
        }

        metalDecal_pool = new GameObject[decalsPoolSizeForEachType];
        var decalsParentObject_metal = new GameObject("decalsPool_metal");

        for (int i = 0; i < decalsPoolSizeForEachType; i++)
        {
            metalDecal_pool[i] = Instantiate(metalDecal);
            metalDecal_pool[i].SetActive(false);
            metalDecal_pool[i].transform.parent = decalsParentObject_metal.transform;
        }

    }
}

```

# Answer
You need the raycast to continue past the initial point of contact. Use RaycastAll for this. Then test if you hit your target object, however you’d like to test for that. Then, if you detect a hit, and if the next RaycastHit is also the target object and is within float maxBulletPenetration dist, just get the surface normal and hit.point from both hits and spawn your decals.
> 1 votes

---
Tags: unity, first-person-shooter
---


# Question
Title: How to calculate gravity with multiple bodies?
I'm looking at building something space-related, and trying to figure out how realistic gravity calculations would work.

The specific question I want to answer is, if I have a sun and an arbitrary number of planets in the system, and I know what the position and mass of each of them is, and I have a spaceship at position `P` trying to accelerate in direction `D`, how much thrust would that require if the same acceleration in purely gravitically "flat" space would require 1 unit of thrust?

For the sake of simplicity, assume that the entire solar system exists in a 2-dimensional plane.

# Answer
> 1 votes
Basically, you need to calculate gravitation force vectors (F = G * m1 * m2 / R^2) towards every massive body. Add them up and invert - that's additional force you need to apply to compensate for the gravity.

---
Tags: physics
---


# Question
Title: Handling Ctrl-<key> shortcuts in Unity, respecting user preferences
I am implementing some software with Unity that needs to support `Ctrl-<key>` shortcuts such as `Ctrl-c`. I want to do this in a way that respects the user's operating system keyboard preferences; for example, these shortcuts must still be recognized when the user uses sticky keys, or when the user has mapped caps lock as control.

Many of the solutions I found online for implementing keyboard shortcuts look something like this:

```
if ((Input.GetKey(KeyCode.LeftControl) || Input.GetKey(KeyCode.RightControl)) && Input.GetKeyDown("c")) UnityEngine.MonoBehaviour.print("C-c");

```

This solution is totally unacceptable to me because it "hard-wires" holding down a control key as the method for sending a control-key modifier, bypassing the operating system's possibly-customized handling of the control key modifier.

Most games don't support keyboard preferences properly, but I am hell-bent on making sure the software I write will do this properly. I'm particularly concerned about supporting sticky keys because this is an accessibility issue - some more complicated shortcuts will not be available to users with disabilities if sticky keys isn't handled correctly.

How can I support keyboard shortcuts properly in Unity?

# Answer
> 4 votes
Good news! This code:

```
bool ctrl = Input.GetKey(KeyCode.LeftControl)
         || Input.GetKey(KeyCode.RightControl);

```

*already* respects the user's OS settings for sticky keys and key remapping on Windows and macOS at least. And this works whether you specify the key by `KeyCode`, by a "Conventional Game Input" string, or by a remappable `GetButton("Some Custom Name")` alias you've defined in the Input Manager.

That's because Unity isn't talking to the keyboard directly; it's asking the OS "Is the left control key pressed?"

The OS, knowing that you've remapped your left shift key to act as the left control, and that you've enabled sticky keys and double-tapped that shift key, is then free to lie to Unity and say "why yes it is!" even if the physical key on your keyboard labelled "CTRL" says otherwise.

Give this a try. Set up a script with some public boolean values that you set in Update based on various key states. Or use them to toggle visibility of some rendered objects. Then enable Sticky keys in your OS, or remap some keys in your registry (and log out / back in to use the updated settings). Run your game, and watch how the values change in reaction to your key presses.

I've just done this in both Windows and macOS, and both sticky keys and registry remapping are correctly respected by Unity, without any changes to my code.

Now of course you can still do one better by allowing players to remap controls within your game, rather than relying on OS-wide/OS-specific settings, but it's good to know that Unity won't disregard those configurations when they're in use on Windows.

---
Tags: unity, keyboard
---


# Question
Title: How can I constrain the player's movement to horizontal or vertical?
This is one of my first coding projects, so apologies for beginner questions....

My player controller script uses the below code, but I want to limit movement to horizontal and vertical only. No diagonal movement.

Here's how it looks:

```
public class PlayerController : MonoBehaviour
{
    //I’m moving the rigid body to move the player
    public Rigidbody2D theRB;

    //lets me change player's move speed in unity editor
    public float moveSpeed;

    // Update is called once per frame
    void Update()
    {
        theRB.velocity = new Vector2( Input.GetAxisRaw("Horizontal")
                                    , Input.GetAxisRaw("Vertical")) * moveSpeed;

```

I've tried the below code to only accept one command at a time by using an if statement, however, with this new code, the player doesn't stop walking once the key is no longer pressed.

Just wondering if someone could point me in the direction of what I'm doing wrong?

```
// Update is called once per frame
void Update()
{
    if (Input.GetAxisRaw("Horizontal") == 1 || Input.GetAxisRaw("Horizontal") == -1)
    {
        theRB.velocity = new Vector2(Input.GetAxisRaw("Horizontal"), 0) * moveSpeed;
    }

    if (Input.GetAxisRaw("Vertical") == 1 || Input.GetAxisRaw("Vertical") == -1)
    {
        theRB.velocity = new Vector2(0, Input.GetAxisRaw("Vertical")) * moveSpeed;
    }

```

thanks!

# Answer
> 0 votes
Your second code doesn't work, because velocity doesn't decrease, when you don't hold anything. Change it to an if...else and set the velocity to zero, when nothing is held down:

```
    if (Input.GetAxisRaw("Horizontal") == 1 || Input.GetAxisRaw("Horizontal") == -1)
    {
        theRB.velocity = new Vector2(Input.GetAxisRaw("Horizontal"), 0) * moveSpeed;
    }
    else if (Input.GetAxisRaw("Vertical") == 1 || Input.GetAxisRaw("Vertical") == -1)
    {
        theRB.velocity = new Vector2(0, Input.GetAxisRaw("Vertical")) * moveSpeed
    }
    else
    {
        theRB.velocity = Vector2.zero;
    }

```

# Answer
> 0 votes
I've tested the code your shared and its working just fine. But I think you'v attached the physics material to one of the object it might the player or might be the ground and that physics material has 0 fraction.

I am sorry for totally guessing because you have not mention anything about physic material and nothing else is coming to my mind right now. hehe...

Plz let me know if i am Right....

Cheers!

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


# Question
Title: How to create a custom set of coordinates based on two points in Unity?
As the title says, I am having problems finding a way to create a new set of local coordinates based on two points. Here is an example:

Consider that the two gameObjects are not one parent of another, therefore I cannot use something like `transform.localPosition`, furthermore I tried using `transform.TransformPoint()`, however the latter works only if if I want to create it with respect to a single point. I think it is a silly question, yet I am not finding a way to solve it, so any help is greatly appreciated!

# Answer
Based on your comments, I understand you want the second point to be on the Y+ axis of the local coordinate system you're building, and the local Z+ axis to correspond to the world Z+ axis. We can get this like so:

```
Matrix4x4 GetCoordinateSystemFromPoints(
              Vector3 origin,
              Vector3 pointOnYPlusAxis)
{
    return Matrix4x4.TRS(
             origin,
             Quaternion.LookRotation(Vector3.forward, pointOnZPlusAxis - origin),
             Vector3.One
    );
}

```

You can transform a point from this local space to world space with:

```
var worldPoint = matrix.MultiplyPoint3x4(localPoint);

```

And transform from world space to local space with:

```
Matrix4x4 inverse;
Matrix4x4.Inverse3DAffine(matrix, ref inverse);

var localPoint = inverse.MultiplyPoint3x4(localPoint);

```

The downside of this is that it's somewhat more expensive to invert.

You could instead define your own `CoordinateSystem` struct that includes both the forward and inverse matrix, or an origin & quaternion pair, so you can transform both into and out of this coordinate system frequently without repeatedly computing a matrix inverse, something like this:

```
public struct CoordinateSystem {
    // 7 floats instead of 12-16 for a 3x4 or 4x4 matrix.
    public readonly Quaternion orientation;
    public readonly Vector3 origin;

    public CoordinateSystem(Vector3 origin, Vector3 pointOnYPlusAxis) {
        this.origin = origin;
        this.orientation = Quaternion.LookRotation(
                              Vector3.forward, pointOnYPlusAxis - origin);
    }

    public Vector3 TransformVector(Vector3 vector) {
        return orientation * vector;
    }

    public Vector3 InverseTransformVector(Vector3 vector) {
        // Quaternion inverse is cheaper than a matrix inverse: just 3 negations.
        // The compiler may be able to combine this with the multiplication below.
        var inverse = Quaternion.Inverse(orientation);
        return inverse * vector;
    }

    public Vector3 TransformPoint(Vector3 point) {
        return origin + TransformVector(point);
    }

    public Vector3 InverseTransformPoint(Vector3 point) {
        return InverseTransformVector(point - origin);
    }
}

```
> 2 votes

---
Tags: unity, transformation, coordinates, linear-algebra
---


# Question
Title: How do I make a MoveToward() GameObject jump without Rigidbody, CharacterController or Raycast?
I have a prefab that is moving from one point to another thanks to `MoveTowards().`

Currently, I am having trouble with a functionality where the player can press a button and make the object jump, affecting only the Y coordinate.

I tried doing the following before putting the `MoveTowards()` code down:

```
void Start()
{
    playerInstance = Instantiate(playerPrefab, startPos.position, Quaternion.LookRotation(endPos.position), null);
    speed = Random.Range(2f, 8f);

    currentPlayerInstancePositionY = playerInstance.transform.position.y;
    isGrounded = true;
}

void Update()
{
    if (isGrounded)
    {
        if (Input.anyKeyDown)
        {
            playerInstancePositionY = jumpForce;
        }
        else
        {
            playerInstancePositionY = currentPlayerInstancePositionY;
        }
    }
    else
    {
        playerInstancePositionY -= gravity * Time.deltaTime;
    }

    currentPlayerInstancePositionY = playerInstancePositionY;

    playerInstance.transform.position = Vector3.MoveTowards(playerInstance.transform.position, endPos.position, speed * Time.deltaTime);

```

I just used custom gravity to decide when the object falls. But the problem I found was that `MoveTowards()` takes a Start Position, an End Position and a Float in its method. But it cannot change individual coordinate values.

As the only control you have over the object is making it jump, I was wondering if there was another way to implement this since the Y value is not being inserted into the prefab before it is given the `MoveTowards()` function. I am trying to implement the jump mechanic without any RigidBodies, CharacterControllers or Raycasts.

Any help would be appreciated.

# Answer
> 1 votes
`transform.MoveTowards` makes the object move closer on all axis'. In this case you seem to only want to move it on the x-axis (and z-axis if this is a 3d game), but not on the y-axis, so MoveTowards is counter-productive here.

If you really want to keep using MoveTowards, then I would split this game-object into two, a parent and a child. The parent game object would representing the root-position on the floor which you move with MoveTowards. If you move the parent, you also move the child. The child-object would be used to handle the jumping offset. The jumping-script would change its `transform.localPosition` \- the offset from the parent. The child object would be the one with the renderer.

But what I would recommend is to stop using MoveTowards and only change the x-coordinate (and optionally z-coordinate) in the "move towards target" code.

---
Tags: unity
---


# Question
Title: How to handle player input with fixed rate variable fps time step?
I've made a system which uses the ideas from "Fix your Time Step" in order update physics. I'm having trouble finding standard methods for dealing with this when user input affects player movement outside of a time-step.

If we want to integrate player movement within the "fixed time step, variable fps" system, I guess I would have to queue up player actions somehow, when accumulation hasn't yet completed. But then how do I integrate several different player actions within said timestep? IE lets say within timestep of N milliseconds, the player executes a move forward, move right and move backwards, where there is an infinite collidable wall in front.

* I could always calculate the last input, but in this case, it wouldn't be correct to do so. The player actually should be blocked by the wall, and then moving right and back would move them to the right, and back, to the right of where only processing the last input would lead.
* Similarly, if all movement was accounted for together, it might result in a player having an impossible vector for the final position, but if all moves were taken independently, there might have been a valid path (ie around a corner).
* If I process all inputs then the player made during the time-step, it could conceivably be costly if they made a million tiny movements (collision check at each movement), though with exact physics (as far as a fixed time step simulation is concerned).
* Even if we thought the last bullet wasn't that bad, as soon as you add multiple players to the equation, it starts looking really bad, especially with a server.

Are my only options to process all actions or only process a subset of them?

# Answer
> 5 votes
I most often encounter this in the context of Unity, which has the following attributes:

1. Input is checked once per displayed frame, before any of that frame's fixed/variable timestep updates
2. Input is interpreted as one flat state for the entirety of the current display frame, not a queue of events

* Each logical button has three independent boolean states:

    + Is currently down as of this input check
        + Has transitioned from up to down since last input check
        + Has transitioned from down to up since last input check

    (These are independent because a button could have been pressed & released all in the span of a single long frame)
    * Each logical analog axis has a current value as of this input check
3. Zero or more `FixedUpdate` & Physics steps run to account for the game time passed

* Here we first compute new physics forces / velocities in `FixedUpdate` routines...
    * ...then ask the physics engine to tick the simulation forward one fixed time step, integrating accelerations & velocities into changes in position and resolving collisions
    * ...then handle any trigger/collision events that occurred as a result of that integration.
4. A variable-length `Update`/`LateUpdate` runs after the fixed steps & before rendering

* Here we do any last-minute/display-only updates before the frame is rendered - particularly VFX, animation, and UI changes to reflect the most recent simulation state.
5. The frame is rendered and presented

In a situation like this, my usual solution is this:

1. Introduce an `EarlyUpdate` method that runs once for each display frame, after the input check and before any of the fixed steps (if any) and any of the variable-length updates. (In Unity when not using the scriptable game loop, I emulate this behaviour)

Here, we process any **instantaneous** input events like button pressed / released - applying an upward impulse the moment the jump button is pressed is one common example. These are inputs that happen only for a moment: the button transitions from up to down in one specific frame. It doesn't keep happening on future frames, unless I release the button and press it again, in which case it's a new press.

This way we ensure these events are processed exactly once - so we don't miss inputs on frames that get no fixed updates, or double-process inputs on frames that get multiple fixed updates.

By handling this before the fixed steps, we minimize the perceived latency. In the example of a jump input, the outcome might be setting an upward velocity on the player. So doing this before the fixed steps gives the physics engine a chance to integrate this velocity change into a position change the player can observe when we render the frame. Even on frames where we get no fixed step, we can render a particle puff or change in the character's animation frame to give the player immediate feedback that their input was heard.

By processing this at the very beginning of the frame, rather than interleaved between fixed updates according to the timestamp on each input event, we're being maximally charitable to the player, potentially shaving fractions of a frame off their reaction time, for the sake of making the controls feel as tight & responsive as we can.
2. Process any **continuous** inputs in each `FixedUpdate` step. These are things like button holds (including holding a jump for extra upward force after the initial launch impulse), or holding a trigger / analog stick at a particular angle.

Here the input state is comparatively long-lived (the player will often hold it at a similar value for several display frames), so we don't miss out if we skip it on short frames where we have no fixed steps: we can safely resume handling the hold on the next frame's fixed step. And we can safely handle the same continuous value multiple times on long frames where we have multiple fixed steps - it's no worse than the player holding the trigger one fixed step longer.

By handling these in our fixed step, we ensure the simulation behaviour does not depend on the player's display framerate. I'll move at the same speed, and fall in the same arc, at 30, 60, or 120 fps. The display framerate just determines the sampling frequency of new hold values. As long as we're rendering at 30 fps+, this will be enough temporal resolution to pull off even fairly intricate analog control inputs sequences. (Keeping in mind that human reaction time is ~5x longer than a display frame even at a low of 30 fps)

This is an approximation, of course. Arguably, we could be more "accurate" by repeatedly checking for input, time-stamping each input event, and processing the inputs in a queue within the fixed step to which each one logically belongs. The upshot of doing that though is most often going to be delaying a user's input further (since it may well have arrived while we were doing rendering work for this frame, after our next fixed step logically ended, and will now be delayed until our second or third fixed step of the next frame instead of the first) and complexifying our code, for little to no benefit to the perception of accurate sequencing of events. So I think it's a simplification worth making.

# Answer
> -1 votes
While Fixing your time step, you should Free your draw step so that positions are interpolated between logic frames. Input runs at the logic rate, and drawing runs at the refresh rate. Separate drawing and logic. You can have an event queue for two timers that can be set to the refresh and logic rate then monitor it for events. If logic or rendering takes too long, skip visual frames as necessary, or force game time to slow down.

Edit3 What I was getting at was that there's nothing special you need to do to handle this other than handle events in the order they occur.

Run your logic timer at whatever rate you want within reason. This is when you update the game state based on dV or dA or however you want to integrate. With overlap based collision this is also when you run collision detection. Now the difficulty I believe you were having was with "when to apply input based state changes". I believe you were questioning whether to aggregate input per logic update. Logic usually runs fast enough that you don't get more than one input event but in the case of mouse input you might get several move events within a relatively slow logic update. It seems the real question is what to do with the input events in between logic updates. Do you feel it is necessary to apply the elapsed time to them? I have never in practice needed such precision that input events can't just be applied directly and consecutively and take effect on the next logic frame.

Are your logic updates so infrequent or so expensive that this actually caused problems in real life?

---
Tags: physics, game-loop, physics-engine, timestep, fixed-timestep
---


# Question
Title: How can I create a .ico file with all the various resolution sizes within one container?
I was looking at this GOG.ico in ffmeg, and was surprised to see all the streams for it...indicating it was holding multiple images in the .ico container or .ico has some kind of self-creation function where it generates the resolutions from a singular image based on condition? Or Maybe I'm overthinking it and its just a container with 7 different image variants stored inside?

Regardless I was curious on what the method of creation was for this many .ico in one hybrid, and how to replicate it. I'm already familiar with how to create a singular .ico image using gimp and/or ffmpeg....gimp is probably using ffmpeg itself. If its 7 images, those can be mapped to various streams of the .ico container using a tool like ffmpeg.

What's a more automated workflow people use to create these kinds of elaborate .iso though?

# Answer
Myself, I use the free program SimplyIcon for this. You run the program, drag the png of your highest-resolution icon onto the window (I usually start at 128x128), and it generates the downsampled versions for you and packs them all into a single .ico file.

It's just doing a basic downsample, so the small versions may not be as crisp as if you exported your vector art with pixel snapping at the smaller size directly, or hand-painted an icon for that size. But it's quick and the results have been acceptable for my needs.
> 2 votes

# Answer
.ico file indeed store a set of images in different resolutions and even different color depth. However, when Windows can't find an image of the desired resolution, it will try to scale down or up (ugly) the closest possible image. Fun fact: you can put totally different images for different resolutions. Fallout 1 original icon, for example, had Tim Cain's portrait for 48x48 resolution.

As for icon creating tools I personally prefer Paint.NET with icon file format plugin
> 2 votes

---
Tags: graphics, graphics-programming
---


# Question
Title: Friction using delta time returns inconsistent result
Slowing down a character using the following formula returns different results depending on the frame rate:

```
this.y += this.yVel * delta;
this.yVel *= Math.pow(0.99, delta);

```

Is there a better way to decelerate a player using delta time to allow for consistent movement across several framerates?

# Answer
> 0 votes
Normally, fixed delta time is used in physics simulation cause in this reason. On the other hand, frame base delta time is useful for rendering.

Of course, fixed delta base calculation result is make diff frame time object position. So you will need interpolation.

# Answer
> 0 votes
This line assumes that `yVel` is constant for the entirety of the duration `delta`:

```
this.y += this.yVel * delta;

```

But that's not true - we know by the end of duration `delta` that `yVel` has decreased to a fraction of \\$0.99^\text{delta}\\$ according to this line:

```
this.yVel *= Math.pow(0.99, delta);

```

So if we think of `yVel` as a function of time, \\$v(t) = v\_0 \cdot 0.99^t\\$, then the total displacement in `y` over the course of the interval delta is the integral:

$$\begin{align} \Delta y &= \int\_0^\text{delta}v\_0 \cdot 0.99^t dt\\ &= v\_0 \cdot \int\_0^\text{delta} e^{\ln (0.99) \cdot t} dt\\ &= v\_0 \cdot \left( \frac 1 {\ln(0.99)} e^{\ln(0.99) \cdot t}\right)\Bigg|^\text{delta}\_0\\ &= \frac {v\_0} {\ln(0.99)}\left(e^{\ln(0.99)\cdot \text{delta}} - 1 \right)\\ &=v\_0 \cdot \frac {0.99^\text{delta} - 1} {\ln(0.99)} \end{align}$$

In code:

```
var frictionFactor = Math.Pow(0.99, delta);
this.y += this.yVel * (frictionFactor - 1)/Math.Log(0.99);
this.yVel *= frictionFactor;

```

This will be smoother, but can still vary from one run to another due to limited precision and accumulation of rounding errors. So as Shin Dongho mentioned, your best bet here is to fix your physics timestep at a known value, so you get consistent, reproducible results.

---
Tags: physics
---


# Question
Title: How to convert Blender rotation angles to Unity rotation angles?
I add news cameras in my game. I have a problem with rotation, the result is **not alway the same** as in Blender. I tried lot of ideas but today I do not have anymore.

**Cameras 1, 2, 4 :** good rotation

**Cameras 3, 5 :** bad rotation

Cam 1 (Blender):

Cam 1 (Unity): the fov is different

Cam 4 (Blender):

Cam 4 (Unity): the fov is different

Cam 3 (Blender):

Cam 3 (Unity): rotation is very different

Cam 5 (Blender):

Cam 5 (Unity): rotation is very different

This problem appears if camera orientation is "vertical"

Do you have a turn arround, a solution for me?

My code:

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

public class rotation_cams : MonoBehaviour
{
    private Vector3[] cams_loc;
    private Vector3[] cams_rot;
    void Start()
    {
        cams_loc = new Vector3[5];
        cams_rot = new Vector3[5];

        cams_loc[0] = new Vector3(79.7771f, 21.7574f, 109.795f);
        cams_rot[0] = new Vector3(95f, -45f, -200f);

        cams_loc[1] = new Vector3(78.0048f, 21.9854f, 110.314f);
        cams_rot[1] = new Vector3(87.0958f, 1.34464f, -160.515f);

        cams_loc[2] = new Vector3(78.3154f, 18.9402f, 111.654f);
        cams_rot[2] = new Vector3(169f, 59.3947f, -110.242f);

        cams_loc[3] = new Vector3(78.023f, 18.7094f, 111.375f);
        cams_rot[3] = new Vector3(89.4105f, 16.7202f, -128.303f);

        cams_loc[4] = new Vector3(79.5798f, 19.7249f, 111.743f);
        cams_rot[4] = new Vector3(55.0461f, 74.0926f, -220.475f);

        int i = 0;

        foreach (Vector3 vector_loc in cams_loc)
        {
            string camName = "cam" + i.ToString();
            GameObject currentCam = AddCamera(camName);

            currentCam.GetComponent<Transform>().position = new Vector3(cams_loc[i].x, cams_loc[i].z, cams_loc[i].y);

            Vector3 objRotation = new Vector3(cams_rot[i].x * -1, cams_rot[i].z * -1, cams_rot[i].y * -1);
            objRotation.x += 90f;

            currentCam.GetComponent<Transform>().eulerAngles = objRotation;

            i += 1;
        }
    }

    void Update()
    {

    }

    private GameObject AddCamera(string name)
    {
        GameObject gizmoPhoto = GameObject.Instantiate(GameObject.Find("cam"));
        gizmoPhoto.name = name;

        return gizmoPhoto;
    }
}

```

# Answer
I solved my problem with this :

```
import bpy
from mathutils import Vector

object_name = "cam3"
cam = bpy.data.objects[object_name]
up = cam.matrix_world.to_quaternion() * Vector((0.0, 1.0, 0.0))
cam_direction = cam.matrix_world.to_quaternion() * Vector((0.0, 0.0, -1.0))

```
> 0 votes

# Answer
Unity and Blender use different coordinate systems. In Unity, y is up while in Blender, z is up. Also, rotations in Blender are counter-clockwise around the axis while they are clockwise in Unity. But you already got that correctly.

However, what you didn't get correctly is that when it comes to rotations, just switching the y-angle and the z-angle won't do. When you perform rotations in euler angles, then the order in which these rotations are performed does matter. And unfortunately Unity and Blender also disagree about that. `Transform.eulerAngles` creates the rotation by:

1. rotating z degrees around the z axis,
2. **then** x degrees around the x axis and
3. **then** y degrees around the y axis.

While Blender performs rotations, it does so in this order:

1. around z (which is Unity y)
2. around y (which is Unity z)
3. around x (which is Unity x)

To apply rotations on single axis' one at a time, start with an euler rotation of 0°:0°:0° and use `transform.Rotate` three times:

```
Transform camTransform = currentCam.GetComponent<Transform>()
camTransform.rotation.eulerAngles = Vector3.zero;
camTransform.Rotate(0.0f, cams_rot[i].z * -1, 0.0f);
camTransform.Rotate(0.0f, 0.0f, cams_rot[i].y * -1);
camTransform.Rotate(cams_rot[i].x * -1, 0.0f, 0.0f);

```

---

But there might also be a far easier solution for your problem which doesn't require any programming at all: **Just import the cameras from the Blender project**. Export your Blender project in .fbx format (if you aren't already - it's what Unity recommends) and when you drop it into Unity make sure "Import Cameras" is enabled in the import settings.
> 0 votes

---
Tags: unity, rotation, blender
---


title: Problem with IsKeyPressed 2 times

text:
# Question
Title: Problem with IsKeyPressed 2 times
i tried to make thing to show menu up by doing VK\_MULTIPLY and close it by doing VK\_MULTIPLY, but this does not work.. Anyone can help :) ?

```
        if (IsKeyPressed(VK_MULTIPLY))
        {
            Menu::MenuLevelHandler::MoveMenu(SubMenus::NOMENU);
        }
        else if (IsKeyPressed(VK_MULTIPLY)) //????
        {
            Menu::MenuLevelHandler::BackMenu();
        }

```

# Answer
> 1 votes
I think the `IsKeyPressed` check is checking if the key is pressed continuously. Therefor both conditions are met.

Look for a `IsKeyDown` or `IsKeyUp` implementation. This should met your requirements.

---
Tags: c++
---


title: Things disappear in front of Canvas

text:
# Question
Title: Things disappear in front of Canvas
I'm trying to add some text to my Canvas but it seems to disappear in front of it? So does particle systems and other things?

It is a child object of the canvas.

# Answer
> 1 votes
Try adding another Canvas component to the child object, and then Override Sorting:

If you rely on the default sorting order, it will use the same as the Canvas parent. This can cause issues with z-order fighting.

# Answer
> 0 votes
The children of a canvas are rendered in order. So it first renders the text, then overdraws the text with the image, then overdraws part of the image with the button. If you want the text to appear above the canvas, then drag the "DevBy" game object below the "Image" game object in the scene hierarchy.

> So does particle systems and other things?

If you want the image to be the background image of not just your user interface but of the whole game, then it shouldn't be part of the user interface canvas. A common method is to place it as a Plane or Sprite in 3d space.

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


# Question
Title: OnTriggerEnter With First Person Controller
I'm working on an FPS for my first time.

I'm creating a simple terrain and instatiating 15 cubes on my terrain. (This works fine). Each cube is named "cube" and has a static trigger collider.

Here's what my scene looks like:

When my first person controller collides with my cube (instantiated object) then I want the cube to deactivate and add 1 to my score, but nothing happens.

Code: I added this code in FirstPersonController.cs

```
void OnTriggerEnter(Collider other)
{
    if (other.gameObject.name == "cube")
    {

        other.gameObject.SetActive(false);
        // when the player touches my spawned object then I want to
        // deactivate my cube, but nothing happens

        Debug.Log("collidedwith:" + other.gameObject.name);

        score += 1;
        scoreText.text = score.ToString();

    }
}

```

# Answer
Advice I give to Unity developers is please never look up or compare GameObjects by name. It's a very brittle way to work and we have better options available to us.

In this case, your cube objects are *not* named "cube" or "Cube". They're named "Cube(Clone)" as we can see in your screenshot, so comparing the name to "cube" returns false and you always skip the inner code.

You can find this yourself by putting at the top of your method, before the `if`:

```
Debug.LogFormat("Collided with {0}", other.gameObject.name);

```

This will let you see how the name of what you're colliding with actually shows up in game.

So, better things we can do:

1. Make a `ScorePickup` physics layer that only collides with itself. Put all your score pickups on this layer, and give your player object a collider on this layer to detect them, with a `ScoreCollector` script on it to receive and act on the trigger messages.

Now you don't need an `if` check at all: only collisions with score pickups will fire the `OnTriggerEnter` message on this script, no filtering required.

Or...
2. Give the cubes a tag "ScorePickup" (name your stuff based on what it does, not what shape it is - shapes often change as you update your game's look) then change your `if` check to `if(other.gameObject.CompareTag("ScorePickup"))` to match the tag instead of the name. This is much more robust to scene changes than names, which are easy to change accidentally.

Or...
3. Create a `ScorePickup` MonoBehaviour script and put it on your score pickup prefab. You can then check if the object you've collided with is a score pickup like so:

```
var pickup = other.gameObject.GetComponent();
if(pickup != null) {...
```

The advantage of doing it this way is you can give the `ScorePickup` additional properties and behaviour. Like a variable to control how much score it's worth, so you can have little pickups and big pickups both using the same script. You could also include collection sounds & particle effects here.
> 0 votes

# Answer
When you instantiate an object then the name of the object will be "Object Name+(Clone)" for example in your case the object name you want to instantiate is "cube" but after the instantiation the name will be "cube(Clone)" so you have to compare with "cube(Clone)" instead of "cube".

```
void OnTriggerEnter(Collider other)
{
      if (other.gameObject.name == "cube(Clone)")
      {
            other.gameObject.SetActive(false);
            Debug.Log("collidedwith:" + other.gameObject.name);

            score += 1;
            scoreText.text = score.ToString();

       }
}

```

By the way the way you use to detect an object is not a perfect way so my suggestion is to use Tags and the check for specific tag instead of the name. Eg your code will become like this:

```
private void OnTriggerEnter(Collider other)
{
    if (other.gameObject.CompareTag("cube"))
    {
        other.gameObject.SetActive(false);
        Debug.Log("collidedwith:" + other.gameObject.name);

        score += 1;
        scoreText.text = score.ToString();
    }
}

```

So Now the object name does't matter any more And also i used "CompareTag("Tag")" instead of "Tag == Tag", its because this will provide better performance and also if the tag is not define unity will notify you So you will be having better control over you code.

I hop it helps...
> 0 votes

---
Tags: unity, c#, collision-detection, 3d, collider
---


title: Server game loop

text:
# Question
Title: Server game loop
I'm trying to setup a very simple multiplayer game that allows some users to join and walk around. The game is 2D and the players will have a position, the direction they are looking in (it's a top-down game) and their animation frame index (so they can be animated for all clients). This is my game loop that I have at the moment:

```
private void run()
{
    long lastTick = 0;
    long tickDelay = 33;
    int tps = 0;
    int ticks = 0;
    long lastTickCount = 0;

    List<Connection> toRemove = new List<Connection>();

    while (!shouldStop)
    {
        lock (connections)
        {
            if (connections.Count != 0)
            {
                foreach (Connection connection in connections)
                {
                    if (!connection.IsInitialized)
                    {
                        if (connection.Initialize())
                        {
                            BroadcastChatMessage(connection.Username + " has joined");
                        }
                        else
                        {
                            Console.WriteLine("Disconnected " + connection.IP + ": failed to authenticate");
                            connection.Close();
                            toRemove.Add(connection);
                        }
                    }
                    else
                    {
                        int cmd = connection.ReceiveCommand();

                        if (cmd == -1)
                        {
                            BroadcastChatMessage(connection.Username + " has left");
                            connection.Close();
                            toRemove.Add(connection);
                        }
                    }
                }
            }

            if (toRemove.Count != 0)
            {
                foreach (Connection connection in toRemove)
                {
                    connections.Remove(connection);
                }

                toRemove.Clear();
            }
        }

        ticks++;
        long now = CurrentTimeMillis;

        if (now - lastTickCount >= 1000)
        {
            lastTickCount = now;
            tps = ticks;
            ticks = 0;
        }

        int connectionsCount = 0;

        lock (connections)
        {
            connectionsCount = connections.Count;
        }

        Console.Title = "Top-Down Multiplayer Server [TPS: " + tps + ", Connected: " + connectionsCount + "]";

        lastTick = CurrentTimeMillis;
        Thread.Sleep(20);

        while (CurrentTimeMillis - lastTick <= tickDelay) { }
    }
}

```

I have a simple mechanism that makes the server run at 30 ticks per second with a `Thread.Sleep` to free up CPU. Should I be processing data from all the clients in the same thread like this? What should the ticks per second be determined by? Am I on the right track with this loop?

P.S: In the future I would process the game after I handle connections and before I do `ticks++` (after I receive client data and before I count the ticks per second).

# Answer
> Should I be processing data from all the clients in the same thread like this?

Yes, a single thread for all clients. *Although there is an argument for multiple server threads and even they talking among them, do not start there. That is what you do in preparation to moving one server to another machine. There is plenty to do before you worry about that.*

On the other hand, that does not mean you can't work with asynchronous operations in that single thread.

---

If I understand correctly, you have a `connection` per client and then you do `connection.ReceiveCommand` on each one. That looks like it would block if the client stops sending data.

I wonder why you do not have a single server socket. Anyway, if that makes no sense in your design, then making a `Task` to recieve from each `connection` does. Then you can use `WaitAny`.

---

> What should the ticks per second be determined by?

That is opinion based.

---

> Am I on the right track with this loop?

If it is working, then arguebly yes.

I would worry about that `lock`, who else is messing with `connections`?

---

> P.S: In the future I would process the game after I handle connections and before I do ticks++ (after I receive client data and before I count the ticks per second).

You probably do not want to use `Thread.Sleep(20);` then. If you are going to put the thread to sleep, first compute the time to the next tick and use that.

And avoid to busy loop:

```
while (CurrentTimeMillis - lastTick <= tickDelay) { } // <- do not do this

```

---

What is that `CurrentTimeMillis`? Please use an `Stopwatch`. That is how to measure time in C#.

> There's not much resources on the internet about the internal workings of a server game loop.

Try Awesome-Game-Networking.

---

If you just want something for reference... have some pseudo code:

```
while(Running())
{
    var begin = current_time();
    receive_from_clients(); // poll, accept, receive, decode, validate
    update(); // AI, simulate
    send_updates_clients();
    var elapsed = current_time() - begin;
    if(elapsed < tick)
    {
        sleep(tick - elapsed);
    }
}

```

**Note**: if you need to deal with other systems, you might put them in other threads. For example, if you are persisting the state of the world, that does not have to happen in the same thread... then in whatever other thread you do that, you can throttle it. And of course watch for thread safety. However, do better than `lock`. In fact, you can run simulation in another thread... then update here is about reading and sending data to that other thread. *Consider 0MQ.*

---

## On separating threads and the slow client

First of all. Yes, there is a way to do it all in a single thread, and it will work. Will come back to the problem of the slow client.

---

**Simulation Thread and Network Thread**

If the simulation is running on a separate thread it should not be dealing with connections. Instead it needs a way to get all the network input since last iteration.

---

One way to do that is to have the network thread write to an network update object that holds a datastructure where all the network events are stored (commands from clients, disconnections, and so on). Then, when the simulation thread wants to get them, it can swap the object for a new one (which can be done atomically).

That also means that the network thread cannot be allowed to cache the reference to the network update object. Thus, all access to the network update object will have to be volatile.

---

Another way to do that is to have "channel" objects. Either a `ConcurrentBag<T>` or a `ConcurrentQueue<T>` will work (they are not so different). *I would avoid using the `BlockingCollection<T>` for this purpose (because it is blocking).* Then the Network thread will push/add into the channel the network events, and the simulation thread can pick them up when it loops.

---

**Note**: just because you used one way to get input from the network, does not mean you have to use the same way to send updates. In fact, sending updates has extra considerations. However, I would recommend to start by making the communication between simulation and network symmetric (I mean, use the same approach).

---

**On the slow client problem**

Please note that the slow client problem can still have an impact even if you separate simulation and network, because if the network is waiting on a client, it will not take input from the other clients. **Errata**: This is only a problem if you are trying to listen from each client in a loop. However, the way it is done is to just listen on a port, not from any particular source.

Also note that you will inevitably open a socket to receive. Unless you are using a library designed for this, I recommend to stay in control of the socket.

With that in mind, you do not have to use a blocking API to receive. *Regardless of how many threads the server is using.* Ideally you use something like `ReceiveAsync` that gives you a `Task`.

Once you have a `Task` that will complete when you receives data from a client, you have a few options...

---

*First option:*

You can `Wait` (not `await`) with a timeout (and even a `CancellationToken`, useful to teardown the server). That way you know that regardless how slow the client is, the network thread will not be stuck for long.

You can then, each loop, `Wait`, check if the task completed. If it did, take the result, and recreate the task. That is how you do it in a single thread.

**Notes**:

* When you are not receiving, the socket is buffering.
* If you have multiple tasks, you can use `WaitAny`.

---

*Second Option:*

You can add a continuation, or better yet, wrap it all in an `async` method. *Yes, I said to not `await` the task, that is so you can pass parameters to `Wait`, but that does not mean you cannot wrap it in an `async` method.* \- then that continuation will take the input from the network, post it to whatever object you need it into (for example a channel object).

Each loop, you will take the posted data (yes, that could be in another thread), and check if you need to recreate the task.

---

*Third option:*

Following the same idea, you can recreate the task inside of the continuation. So that you do not have to worry about it each loop.

In fact, if you started with a single threaded solution and moved down this path. From this point, it just a matter of using a well placed `Task.Run` (if you did not do it already) and you have a separated thread for the network (if you are using `Task.Run` mark it `LongRunning`, so it is a dedicated thread and not one from the `ThreadPool`).
> 3 votes

---
Tags: c#, multiplayer, monogame, client-server, server
---


# Question
Title: In Monogame, can/should SpriteBatch be instantiated in the Initialize method as opposed to the LoadContent method?
By default the `SpriteBatch` instance used is instantiated in the `LoadContent` method of `Game1`.

For example see here

However a `SpriteBatch` only requires a `GraphicsDevice` object to be instantiated. Said `GraphicsDevice` is actually already available when the `Initialize` method is created, so my question is why is the `SpriteBatch` created in `LoadContent`?

I think that both methods are run only once per game, so don't see why you can't/shouldn't instantiate the `SpriteBatch` object in the `Initialize` method?

# Answer
> 0 votes
If your IDE has a decompiler, you may want to explore the base `Game` class. You will see:

```
protected virtual void LoadContent()
{
}

protected virtual void Initialize()
{
  this.applyChanges(this.graphicsDeviceManager);
  this.InitializeExistingComponents();
  this._graphicsDeviceService = (IGraphicsDeviceService) this.Services.GetService(typeof (IGraphicsDeviceService));
  if (this._graphicsDeviceService == null || this._graphicsDeviceService.GraphicsDevice == null)
    return;
  this.LoadContent();
}

```

So, `LoadContent` gets called *conditionally*, if graphics device has been setup correctly. If you want to preserve this logic, leave `SpriteBatch` initialization there.

But if you move it to `Initialize`, nothing horrible will happen.

---
Tags: c#, monogame, spritebatch
---


# Question
Title: Locking object access with Allegro's threading API
If I have a data structure for the Allegro threading API as shown in the example here:

https://wiki.allegro.cc/index.php?title=Allegro\_5\_Tutorial/Threads

And I lock the mutex, is there a way to have one of the members of that data structure be a reference to an entire object that has read/write access to its public member functions locked?

That is to say, if I have a member variable which is a reference to a non POD-type object in that data structure, will locking the mutex restrict access to all of the object's members in another thread, or will it simply lock the reference itself from being modified?

# Answer
Regardless of the use of Allegro, a mutex and threading is a set of agreements made between yourself, and the rest of your code to enforce "MUTual EXclusion" of the use of shared data.

Simply locking a mutex doesn't ensure the data will not be touched. It's not the data itself that's locked, it's the thread the mutex is running on.

What is necessary with the use of a mutex is to ensure your code only touches the shared data when a lock is actually acquired. This means hands off when you don't have a lock on the resource!

So to answer your question, it's not the struct the mutex is wrapped in, it's the data you mark as off limits to threads that don't have a lock. The actual enforcement is entirely optional, and up to you.

Thread 1

```
LockMutex(m);
my_vector.resize(my_vector.size()*2);
UnLockMutex(m);

```

Thread 2

```
LockMutex(m);
process_vector(&my_vector);
UnlockMutex(m);

```

Now no matter which thread is running, only one will be allowed to access my\_vector at a time.
> 1 votes

---
Tags: multithreading, c++, allegro
---


title: How to save game state in C in Allegro?

text:
# Question
Title: How to save game state in C in Allegro?
I'm developing my 1st board-game (go-game) in **C** with Allegro 5, for a course project. Part of my goal is to make a gamesave of the current gamestate. Let's say for 2 players if we exit the game, and log in the game, we want to reload the previous gamestate such that the position of the stones by 2 players to be preserved in their positions. How can I achieve this? I will appreciate any related reference, tutorial, or a git reference I can learn more about saving the states of the game.

P.S. I checked the old questions about saving game state, but there are guides only for other languages/libraries not in C/Allegro.

# Answer
> 1 votes
First, decide what information of your game describes a "game state". In other words, what is the difference between a "new game" and what state the user currently is?

Examples of that are:

* Character's stats (Name, level, experience, strength, intelligence, money, etc)
* Quests (What quests have the user completed? What progress do they have on active ones?)
* Maps (Has the player visited a place before? Do they have fog of war that is explored next time they visit it? After the user has killed enemies on one stage, do they respawn or remain permanently dead?)

Once you have all this information down, it's time to write a file that includes all that information, which is going to be saved on the disc, so it remains there until someone removes it manually. You can pick a simple format like `var=value` and save all data like this:

```
character_name=john
character_level=4

quest_kill_dragon=0 # assuming -1 is not started, 0+ started and current state
quest_find_jewel=-1

map_mountain_explored=0 # maybe if you go to a map for the first time a cinematic plays
map_mountain_enemy_2=-1 # -1 on enemy is that they are dead and won't respawn

```

Please note I used `#` to display comments, but normally you wouldn't need comments as this file is not meant to be readable by humans. What data you want to save is up to you and what game you are making.

Alternatively you can use JSON to save data on a file, there are plenty of libraries online that help you do that. Unfortunately I haven't used any in the past, so I can't recommend any.

In case its needed, the manual of how to open/close files in C: GNU - Opening and Closing Files

# Answer
> 2 votes
The name of the method you're looking for is called 'serialization'. Whether it is output to a text file or a binary file doesn't matter. What matters is that you store the data necessary to recreate a game state and that you read it back the same way you save it.

In Allegro 5, you can use the https://liballeg.org/a5docs/trunk/file.html (FILE I/O) routines to save your text or to save binary data.

As for your specific situation, you have a board (a 2D array) of stone types (an enum).

The value of a position on the board can be in one of 3 different states ; 1) empty 2)black 3)white.

So first, make an enum for your data :

```
enum PIECE {
   NONE = 0,
   WHITE = 1,
   BLACK = 2
};

const char[3] piecetypes = {'-' , 'O' , 'X'};

```

In GO, there are usually 19x19 pieces.

In serializing data like an array, we need to record its size somewhere.

First job is to open a file. Typical usage is of http://www.cplusplus.com/reference/cstdio/fopen/ fopen, or in Allegro 5, https://liballeg.org/a5docs/trunk/file.html#al\_fopen al\_fopen.

Once the file is open for writing (make sure to specify whether you're writing in text or binary mode!!!), write the board to the file.

Since we're using an enum with less than 8 values, and there aren't that many values (19x19 = 361), we'll represent our data in the file with a char (a single byte).

```
ALLEGRO_FILE* f = al_fopen("go.sav" , "w");/// Opening in text mode for writing
if (!f) {Bail();}
for (unsigned int y = 0 ; y < 19 ; ++y) {
   for (unsigned int x = 0 ; x < 19 ; ++x) {
      al_fputc(piecetypes[board[y][x]]);
   }
   al_fputc('\n');
}
al_fputc('\n');
al_fclose(f);
/// All done

```

Now our data should be saved something like this (open the text file in your favorite editor and verify the contents) :

```
-------------------
-------------------
-------------------
-------------------
-------------------
-----XX------------
------O------------
---------O---------
---------XX--------
----------OO-------
---------O---------
-------------------
-------------------
-------------------
-------------------
-------------------
-------------------
-------------------
-------------------

```

Now you need to be able to 'unserialize' the data, that is to say, to read it back from the file.

Open the file for reading and copy the data back into your board :

```
ALLEGRO_FILE* f = al_fopen("go.sav" , "r");
if (!f) {Bail();}
for (unsigned int y = 0 ; y < 19 ; ++y) {
   for (unsigned int x = 0 ; x < 19 ; ++x) {
      char c = al_fgetc(f);
      if (c == '-') {board[y][x] = NONE;continue;}
      board[y][x] = (c == 'O')?WHITE:BLACK;
   }
   al_fgetc(f);/// consume the newline
}
al_fclose(f);

```

---
Tags: c, allegro
---


# Question
Title: 2d Rectangle Collision Resolution: Find rollback point
I have a 2-part question:

1: I have 2 rectangles, A and B. B is a wall and A is moving. My simple logic here is every time A moves, it moves based on some (x,y) offset and then checks if it collided with something. If it is colliding with something, roll back bit by bit in the opposite direction until it is not colliding anymore.

The problem here is if A moves in large chunks, it might skip over B entirely.

The intended behavior is to find out where A should be when it first touched one of B's faces and then roll back to that point and apply collision resolution.

2: What if B is moving as well?

What I'm currently doing to side step this issue is to create large enough collision boxes and make sure moving objects do not exceed some maximum. This approach seems like it will be limiting in the future.

I assume there is a mathematical way to solve this but I wasn't able to find any answers from my searches. Any tips/suggestions are greatly appreciated.

Thanks!

# Answer
> 1 votes
What you're looking for is called swept or dynamic AABB collision detection.

When dealing with a static and a dynamic (moving) object, you need to take the velocity of the latter in both x and y axes and divide the distance from the static rectangle on the axes by them. Then choose the one that's lower and it should be the time it takes for the rectangle to reach the static one:

```
if moving.vel.x < 0 then
    distX = static.right - moving.left
else
    distX = static.left - moving.right
endif

if moving.vel.y < 0 then
    distY = static.bottom - moving.top
else
    distY = static.top - moving.bottom
endif

timeX = distX / moving.vel.x
timeY = distY / moving.vel.y

collisionTime = min(timeX, timeY)

moving.move(collisionTime * moving.vel.x, collisionTime * moving.vel.y)

```

For the dynamic-dynamic case you can use the same thing. You need to realize, that if we were to look at the collision from one of the moving rectangles' local coordinates, then we see that rectangle as a static one (it always stays in (0,0)), and the other is moving a lot faster. So replace the velocity in the pseudo code above with `moving1.vel - moving2.vel` where moving1 will act as the dynamic rectangle and moving2 is the static one

# Answer
> 0 votes
You have at least 3 basic options.

1) Overlap check (suffers from tunneling) 2) Sweep test (needs collision extraction) 3) Intercept test (finds exact intercept time)

Which one is right for you depends on a few things. One is how often you want to update your collision detection. Using 1) with high logic rates or low velocities is often acceptable. 2) works well for objects with static acceleration and 3) works best of the three but is most expensive computationally

Balint's answer is incomplete. While getting the intercept time on each axis is fine, and necessary for 3), it does not actually indicate the time of collision, as the other axis has to be overlapping during the collision time for it to be an actual collision.

---
Tags: 2d, collision-detection, collision-resolution, collision-prediction
---