# Question
Title: Nonsense error in the overlap between 2 warriors and a tower
I have a project where 1 warrior is generated every 5 seconds. This warrior as it is generated tries to follow a path that contains 4 target points. **Between the target point 1 and the target point 2 there is a tower.**

Then the warrior is going to meet the target point 2, but as soon as he hits the tower, he fails to reach the target point 2 and goes to meet it until it is destroyed.

The part of the code circled in pink was to be executed only after the destruction of the tower (when the life of the tower reaches 0), which does not happen, but the worst thing is that when it executes, it does not execute completely, the tower is not destroyed, but the warrior moves toward target point 2.

**Result in game:**

Look that the impression occurs for the two warriors.

**Maybe the message log will help:**

I decrease the delay time of the loop to 0.1 and as there is no time for the second warrior to overlap the tower along with the first warrior, everything works correctly.

The problem occurs when more than one warrior reaches the tower simultaneously.

# Answer
> 0 votes
The overlap between the warrior and the tower swings when more than one warrior is overlapping the tower.

To solve this, just add a Boolean variable that prevents (in the case of the question) the loop being called more than once.

In order for the reference to the tower not to be lost, the ideal is to add an event with a parameter to store the tower and within it execute the loop.

**Something like that:**

**To help you understand what I did, if any questions remain, I recommend taking a look at the answer to another question I asked:**

Way to store object reference?

# Answer
> 4 votes
The error message you're getting is that the game is trying to cast to the tower and failing. The Destroy part of your code is also getting run because of the text on screen says so.

You need to make sure that after the tower is not being cast to after it has been destroyed. The easiest way to do this is to set up a new boolean (bTowerIsDestroyed) and set it to false at run time.

When the tower is destroyed, set it to true and put in a branch in before casting to only run if it is still false. If it's true, then you can send your warriors to the next target point.

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


# Question
Title: Error detecting collision with another instance of the same actor?
I have a project where after a certain time interval 2 NPCs are generated in different locations on the map.

**Each of them collides with a collision box that defines its "class" (red or blue):**

**When 2 NPCs collide it was to be verified a condition (if the "class" of the involved ones is different) and from there both are destroyed, but nothing happens:**

I put a print right after the **Cast To NPC** to see if it was happening and when they are generated the impression appears four times.

**Blueprint:**

**Result in game:**

I'd like to know how to set a cast only between two instances of the same actor.

**Image showing that nothing happens when it (two instances of the same actor) collide:**

*I did the test with both codes (printing and destroying both).*

---

**EDIT 1 (I was being redundant)**

**In the code of destruction, I can simply put it to destroy itself only, because as it will run in both instances, the two will destroy themselves:**

I'd still like to know how to correctly detect the collision between two instances of the same actor, but now I know that the code will be running twice, once in instance A and again in instance B.

# Answer
As I've said before, it's important to be careful about redundancies.

**At generation time it is only to define a warrior variable in two different ways:**

**And make this comparison so that the overlapping is only detected when desired:**
> 0 votes

---
Tags: collision-detection, unreal-4, blueprints
---


# Question
Title: In pixel art, should i keep the same color palette for every sprites?
The question may sounds weird (and very noobish but i'am :p) but i can't find any answer. When making pixel art, it is often said that a color palette could be 2, 4, 8, 16 or even 256 colors, through it is not recommended. When it comes to the palette choice, is it for a single sprite (like a character, and another palette for the landscape for example) or for an entire game (and in this case i must stick to the same palette for every sprites) ?

*Honnestly i think it is for an entire game, but my mind is stuck with the second question implied by this answer: how could i do everything (characters, trees, rocks, explosions, sky...) with only - let's say - 8 colors ? All my sprites looks flat because of this, i can't find a suitable color to make a nice shading.*

# Answer
The thing is, it might be either.

256 colors is not recommended mostly due to it being simply overkill for pixel art, since all we need is usually as fewer colors as possible to imitate visual style of the old consoles.

Considering how limited some consoles were, 8 colours for an entire game might be a realistic choice, but in the end it all boils down to the art direction and that is up to you to decide.

> my mind is stuck with the second question implied by this answer: how could i do everything (characters, trees, rocks, explosions, sky...) with only - let's say - 8 colors ?

If you decide to go with a minimal amount of colors, there are techniques like dithering to create an illusion of a gradient, but it depends on the resolution of the image.
> 3 votes

# Answer
Pixel art is a stylistic choice. **How many colours you want depends on the style that you are going for**.

You might want to limit yourself to 8 or 16 colours through the game to mimic the style of retro-consoles, or you might want to match the 16-bit colours of the Amiga days. You may even want to limit yourself to the exact set of colours these systems allow. Alternatively you might just want the visual look of pixelated art and be happy to use as many colour as you want, or choose a happy medium where you limit yourself to 16 colours but allow lighting effects to use more, or introduce occasional exceptions to the rule.

Either way, choosing a colour palette for your entire game is likely to produce a more harmonious look that picking palettes on a per-sprite basis, while choosing on a per-sprite basis will make those sprites look more distinct.

It's all down to what your aim in producing pixel art is at all.
> 4 votes

---
Tags: pixel, pixel-art
---


# Question
Title: When should MRT (Multiple Render Targets) be used?
I had a question about exactly when I should use the MRT. This is not about rendering models, but about post processing. For example, I need to draw some cubic textures (something like skybox rendering). And how much will drawing in one pass be faster than in several? And will it be faster?

**EDIT**: My shaders looks like this:

vertex:

```
#version 330 core

layout(location = 0) in vec3 inPos;

out vec3 texCoords;

uniform mat4 transform;

void main() {
    vec4 pos = transform * vec4(inPos, 1.0);
    gl_Position = pos.xyww;
    texCoords = inPos;
}

```

fragment:

```
#version 330 core

#define vecout vec3
#define OUT_COLOR_COMPONENT 0

in vec3 texCoords;

layout(location = OUT_COLOR_COMPONENT) out vecout fragColor;

uniform samplerCube cubemap;
uniform vecout color = vecout(1.0);

void main() {
    fragColor = vecout(texture(cubemap, texCoords)) * color;
}

```

# Answer
The use of MRT comes from the need to save bandwidth between multiple draw calls. Yes, it will be somewhat faster, but the difference depends on various factors such as how good your hardware is and how complex your rendering pipeline is.

A quick example of a good MRT usage is G-Buffer acquirement for deferred rendering. It is way more cheap to write to multiple buffers in one pass than calling different state resets/changes to fill them one by one.
> 0 votes

---
Tags: opengl, glsl, multiple-render-targets
---


title: OpenGL textures look poor

text:
# Question
Title: OpenGL textures look poor
I'm having some issues loading in textures in OpenGL, as my textures keep rendering incorrectly or coming out looking muddy. For instance, here I tried to load a 256x256 color spectrum image. On the left is how it looks in OpenGL and on the right is how it looks in an image viewing program:  As you can see, while the left image resembles the right image, the left image appears to squish the blues, and greens, and extend the pinks.

I also tried loading in this 512x512 image of a dog and the result came out like this (again, left is OpenGL, right is image viewer):  For this image, the image looks like it has lost a lot of its color, resulting in something that looks white washed and like it came out of a 1970s camera. (the fact that is flipped is fine however since the cube that I am drawing this on has some texture coordinates flipped to accommodate for a different image).

I load in these .BMP textures using SOIL, as such: glEnable(GL\_TEXTURE\_2D);

```
GLuint texID = 0;
glGenTextures(1, &texID);

int height = 0, width = 0;
unsigned char* imgData = SOIL_load_image(filePath.c_str(), &width, &height, 0, SOIL_LOAD_AUTO);

glBindTexture(GL_TEXTURE_2D, texID);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, imgData);
// set texture filtering, gen mip map

```

Then in my fragment shader I do the following to apply the texture:

```
#version 330 core
in vec2 TexCoord;

uniform sampler2D textureSampler;

void main() {
    gl_FragColor = texture2D(textureSampler, TexCoord);
}

```

# Answer
This has been solved in the comments, but for everyone comming here: I had the same problem that textures appeared washed out on certain (Intel?) GPUs. It turned out that OpenGL had enabled `GL_FRAMEBUFFER_SRGB` by default on some hardware. Calling `glDisable(GL_FRAMEBUFFER_SRGB)` right after context creation fixed it for me.
> 2 votes

---
Tags: opengl, textures, rendering
---


# Question
Title: Texture2D GetPixels - Finding pixels that are not transparent. Problem as finding more than expected
I am trying to make a level design system where I use a low resolution png file with certain pixels filled. My code will turn this location of the pixel in the image into placement of platforms in my game.

But I test the following code with a png i made with only 1 pixel in it (the rest are transparent). But the result is it finds 4 every time. Is it possible there is a discrepancy between the Gimp png and the texture that Unity sees. (In GIMP I used pencil 100% hardness 1px width. There are also settings for 'resolution' of the image, which i left at defaults):

```
public class LevelBuilder : MonoBehaviour
{
public Texture2D sourceTex;
Color32[] pixels;
int pixelsFound = 0;

private void Start()
{
    pixels = sourceTex.GetPixels32();
    for (int i = 0; i < pixels.Length; i++)
    {
        if (pixels[i].a != 0)
        {
            Debug.Log("found colored pixel. total: " + ++pixelsFound);
        }
    }
}
}

```

# Answer
I solved it. I was going to delete the question but just in case somebody else needs the same help, all I had to do was set the Textures Import Settings in Unity Inspector. It needed Read/Write enabled, and Non-power of 2: None.

Now it finds the pixels correctly for my purposes

Heres the full code to get just basic (one type of pixel is recognised right now, either empty or not, but i intend to add color coding to add many varients of objects using one texture):

```
public class LevelBuilder : MonoBehaviour
{
public GameObject platform_prefab;
public float spacing;

public Texture2D sourceTex;
Color32[] pixels;
int pixelsFound = 0;

Color32[,] pixels2d;

private void Start()
{
    pixels = sourceTex.GetPixels32();
    int width = sourceTex.width;
    int height = sourceTex.height;
    pixels2d = new Color32[width, height];
    for (int y = 0; y < height; y++)
    {
        for (int x = 0; x < width; x++)
        {
            pixels2d[x, y] = pixels[x + y * width];
        }
    }

    for (int y = 0; y < pixels2d.GetLength(1); y++)
    {
        for (int x = 0; x < pixels2d.GetLength(0); x++)
        {
            if (pixels2d[x,y].a != 0)
            {
                GameObject platform = Instantiate(platform_prefab);
                platform.transform.position = new Vector3(x * spacing, y * spacing, 0);
            }
        }
    }

}
}

```
> 2 votes

---
Tags: unity, level-design, levels
---


title: Storing user input into a queue

text:
# Question
Title: Storing user input into a queue
I am currently creating a small game using C#, and I am having some trouble working out how to handle user input. I can move my model around the map normally, however I am looking to implement a system where the user can input a number of different commands, and then when they hit enter, the string of commands will be executed. I have tried to implement a queue system to take the user input, and pass them to the model, but I haven't been able to get it to work. My input handler class:

```
class InputHandler
{

    Queue<int> userCommands;

    /*
     *  FORWARD     = 1
     *  REVERSE     = 2
     *  RIGHT TURN  = 3
     *  LEFT TURN   = 4
     */

    public InputHandler()
    {
        //userCommands = new Queue<Keys>();
        userCommands = new Queue<int>();

    }

    public void EmptyQueue()
    {
        userCommands.Clear();
    }

    public Queue<int> GetUserCommands()
    {
        KeyboardState ks = Keyboard.GetState();
        int move;

        while(ks.IsKeyUp(Keys.Enter))
        {
            if(ks.IsKeyDown(Keys.W))
            {
                move = 1;
                userCommands.Enqueue(move);
            }
            if(ks.IsKeyDown(Keys.S))
            {
                move = 2;
                userCommands.Enqueue(move);
            }
            if(ks.IsKeyDown(Keys.D))
            {
                move = 3;
                userCommands.Enqueue(move);
            }
            if(ks.IsKeyDown(Keys.A))
            {
                move = 4;
                userCommands.Enqueue(move);
            }

        }
        return userCommands;

    }
}

```

The Update method for the model:

```
   public void Update(GameTime gametime, BoundingSphere bounding, int move)
    {
        KeyboardState ks = Keyboard.GetState();

        oldModelYaw = modelYaw;
        oldModelPosition = modelPosition;

        if (!isMoving)
        {
            if (move == 1)
            {
                isMoving = true;
                moveType = FORWARD;
            }
            if (move == 2)
            {
                isMoving = true;
                moveType = REVERSE;
            }
            if (move == 3)
            {
                isMoving = true;
                moveType = RIGHT_TURN;
            }
            if (move == 4)
            {
                isMoving = true;
                moveType = LEFT_TURN;
            }

        }

        if (isMoving)
        {
            switch (moveType)
            {
                case FORWARD:
                    if (count <= 100)
                    {
                        modelPosition += modelRotation * velocity;
                        count++;
                    }
                    else
                    {
                        count = 0;
                        isMoving = false;
                    }
                    break;

                case REVERSE:
                    if (count <= 100)
                    {
                        modelPosition -= modelRotation * velocity;
                        count++;
                    }
                    else
                    {
                        count = 0;
                        isMoving = false;
                    }
                    break;

                case RIGHT_TURN:
                    if (count <= 180)
                    {
                        modelYaw -= MathHelper.ToRadians(0.5f);

                        modelRotation = Vector3.Transform(modelDirection, Matrix.CreateFromYawPitchRoll(modelYaw, 0.0f, 0.0f));

                        count++;
                    }
                    else
                    {
                        count = 0;
                        isMoving = false;
                    }
                    break;

                case LEFT_TURN:
                    if (count <= 180)
                    {
                        modelYaw += MathHelper.ToRadians(0.5f);
                        modelRotation = Vector3.Transform(modelDirection, Matrix.CreateFromYawPitchRoll(modelYaw, 0.0f, 0.0f));

                        count++;
                    }
                    else
                    {
                        count = 0;
                        isMoving = false;
                    }
                    break;
            }

            modelPosition.Y = GetHeight();
            translation = Matrix.CreateTranslation(modelPosition);
            rotation = Matrix.CreateRotationY(modelYaw) * GetModelNormal();
            bounding.Center = modelPosition;

            if (scenery.TestCollision(bounding))
            {
                modelPosition = oldModelPosition;
                modelYaw = oldModelYaw;

                modelPosition.Y = GetHeight();

                translation = Matrix.CreateTranslation(modelPosition);
                rotation = Matrix.CreateRotationY(modelYaw) * GetModelNormal();

                bounding.Center = modelPosition;

            }
        }
    }

```

The Update method in the game class

```
protected override void Update(GameTime gameTime)
    {
        if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
            Exit();

        if(commandQueue.Count <= 0)
        {
            commandQueue = input.GetUserCommands();
        }

        else
        {

            model.Update(gameTime, rock.GetBoundingSphere, userCommands.Dequeue());

            camera.Update(gameTime, m_model.GetPosition, m_model.GetDirection);

            base.Update(gameTime);
        }
    }

```

If anyone could give me some help with this, or point me in the right direction, I would greatly appreciate it.

# Answer
1. The general answer to your question is: use a state machine for character movement to get rid of those deep nested if and switches.
2. If you need to perform special actions on input combinations like in fighting games you need a system that records your inputs and each stored input has a timestamp. In order to trigger a combo state! Two conditions must be true: the order of input and datetime.now - firstTimestamp must be lower than whatever timeframe is allowed to trigger the combo.
3. Flush your expired inputs from the queue.
4. Test your command queue by using high expiration times and drawing the commands to screen, also draw which move6state is current and which was last.

A great explanation of state machines for game so can be found in the book "programming game so by example "
> 1 votes

# Answer
There are many approaches for your situation. Below is one possible way (using `GetPressedKeys` method):

Initialise: `string stringCommand = string.Empty;`

In your Update() method:

```
var keyboardState = Keyboard.GetState();
var keyString = keyboardState.GetPressedKeys();

if(keyString .Length > 0)
{
    var keyValue = keyString[0].ToString();
    stringCommand += keyValue;
}

```

Then you compare this string with whatever you want to achieve your desire result.

I think you can create a command line windows to show what users are typing after they press Enter (for example). Another method is that you create a textbox (or a GUI if needed) then read the input of your textbox then do your comparison things.
> 0 votes

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


# Question
Title: Unity3d CarController character positioning issue
I use the unity standard asset components CharacterController and Car and put an empty gameobject onto the car where the camera should be placed when i am inside the car. The empty gameobject is called "Driver". The character controller has an empty called "Head" where its head is.

When i get in the car i perform the following operation

```
GameObject car = GameObject.Find("Car");
transform.position = car.transform.Find("Driver").transform.position + Vector3.up*1;
transform.parent = car.transform.Find("Driver").transform;
Camera.main.transform.position = car.transform.Find("Driver").transform.position;
Camera.main.transform.rotation = car.transform.Find("Driver").transform.rotation;

```

and to get out of it, i use the following

```
GameObject car = GameObject.Find("Car");
transform.position = car.transform.position;
transform.parent = null;
transform.rotation = Quaternion.identity;
Camera.main.transform.position = transform.Find("Head").transform.position;

```

My problem is when i get into the car and out again, the character is positioned at the position where i have entered the car, so it doesnt seems to update its position with the car movement.

What am i doing wrong?

Thanks in advance

# Answer
> 1 votes
Maybe it's simpler if you put Driver object as child of Car in the Hierarchy.

---
Tags: unity
---


# Question
Title: System.Runtime.Serialization.SerializationException while trying to deserialize List
I'm trying to serialize / deserialize a class that holds inventory items.

The code is attached below.

First I call `AddOne()` void a few times, then I call `SaveFile()`, then I call `LoadFile()`.

In `LoadFile()` the following error occurs :

> **ex = "System.Runtime.Serialization.SerializationException: End of Stream encountered before parsing was completed.\r\n at System.Runtime.Serialization.Formatters.Binary.\__BinaryParser.Run () \[0x00288\] in \<1f0c1ef1ad524c38bbc5536809c46b48\>:0 \r\n at System.Runt...**

Does anybody see my mistake?

Thank you for the help!

```
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using UnityEngine;

public enum Type
{
    undefined = 0,
    Pistol = 1,
    Magnum = 2,
    Grenade = 3,
    BlendGrenade = 4,
    FireGrenade = 5,
    PistolAmmo = 6,
    MagnumAmmo = 7,
    Rifle,
    RifleAmmo,
}

[System.Serializable]
public class Inventory : MonoBehaviour
{
    public class InventoryItem
    {
        public int Amount = 0;
        public int Row = 0;
        public int Col = 0;
        public int Rotation = 0;
        public Type ItemType = Type.undefined;
    }
    public List<InventoryItem> Items;

    public void Start()
    {
        Items = new List<InventoryItem>();
    }
    public void AddOne()
    {
        InventoryItem n = new InventoryItem();
        this.Items.Add(n);
    }
    public void SaveFile()
    {
        string destination = Application.persistentDataPath + "/save3.dat";

        if (File.Exists(destination))
        {
            File.Delete(destination);
        }
        using (Stream stream = File.Open(destination, FileMode.Create))
        {
            BinaryFormatter bin = new BinaryFormatter();
            bin.Serialize(stream, this.Items);
        }
    }

    public void LoadFile()
    {
        string destination = Application.persistentDataPath + "/save3.dat";

        using (Stream stream = File.Open(destination, FileMode.Open))
        {
            BinaryFormatter bin = new BinaryFormatter();

            try
            {
                this.Items = (List<InventoryItem>)bin.Deserialize(stream);
            }
            catch (Exception ex)
            {
                Debug.Log(ex.ToString());
            }
        }
    }
}

```

# Answer
I found the error:

The Serializable attribute needs to be on the InventoryItem, not on Inventory.

The correct code looks like this:

```
public class Inventory : MonoBehaviour
{
    [System.Serializable]
    public class InventoryItem
    {

```

I found the error by adding Try Catch statements. Unfortunately, the Unity Console doesn't display C# runtime errors. At least I don't see them.
> 0 votes

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


title: Dynamic Game Server Architecture

text:
# Question
Title: Dynamic Game Server Architecture
I'm trying to find a way to design a game server architecture for a real time mobile game. The design should be cost effective but still to some extend scaleable (later on).

**Mobile client flow:**

Connects to a distributor server which was given by DNS LB and gets grouped with x players. If y players are reached, the distributor server needs to contact a control server, which starts or uses a already running game server. The control server sends back the ip and port to the distributor server which then sends it to the grouped players. The players then connect to the given game server. After the game the players will be send together to a new or same distributor server.

I wonder how the real server (VMs) for the game servers can be managed in a dynamic matter. I have looked at AWS EC2 instances, but if we have 500 players with 6 players per group that play 6 hours per day, we would need ~84 EC2 t3.small (2 vCPU, 2GiB RAM) instances running. This will cost ~1,160.00 USD monthly. With this price it would be favorable to have real VMs and not dynamic cloud instances I guess?

## **Explanation of the components**

**Distributor:**

Mobile clients will connect to these to get grouped with other players. It's like a lobby where players will sit until X players are reached or eg. a countdown ran out.

**Control Server:**

Need to take care of started server (VMs) and handle game server start requests from the distributors.

**Game Server:**

Is an authoritive like server client with physics etc. One game server (software) for X players in a group. Players will connect to these from the distributor after the lobby "phase".

## **Question:**

How can this be dynamic scaleable/cost effective and is this a useable architecture? I see one problem with the control server because it must take care of N game server vms and N distributors. But if we scale the control server, then every control server needs to know the same as every other.

(If anything is missing or can be improved, please let me know. English is not my native language so it's a bit challenging to express my goal in such a complicated topic like this)

# Answer
Do you really need a full-fledged VM for every 6 player game session? This is going to generate a lot of overhead. It might be far more efficient to run multiple server processes on the same virtual server and even more efficient to let your game server software handle multiple games in parallel in one process.

* You are saving the overhead of running multiple full-fledged operating systems and runtime environments as well as the overhead of spinning up and shutting down AWS instances all the time (Yes, Amazon got pretty good at this, but still...)
* You are saving RAM and inter-server network load because the games can share data when they are running on the same process.
* You are utilizing CPU time more efficiently because a more powerful server running multiple games can handle CPU load spikes generated by a single game far more gracefully than a small server running only that one game.

In order to allow horizontal scaling on multiple physical servers, the control server should be able to handle multiple gameserver hosts which each handle multiple sessions and be capable of load-balancing between them.
> 0 votes

---
Tags: architecture, networking, multiplayer, client-server, server
---


title: OpenGL performs very bad on laptop

text:
# Question
Title: OpenGL performs very bad on laptop
I'm trying to write a game using C and OpenGL, I wrote some rendering code and camera, but the game is very laggy, framerate is so low (probably around 10-15fps), however, if I launch the game through Steam as a non Steam game my framerate jumps up to 800 immediately after Steam Overlay loads. The game works fine on my computer and my friend's laptop even without launching with Steam.

And I'm running Windows 10 Pro, 8GB ram, Nvidia GTX 1050 4GB, Intel Core i5-7300HQ

# Answer
Reinstalling Windows fixed my problem.
> -2 votes

---
Tags: opengl, performance, windows, nvidia
---


title: Using a setTimeout to Jump

text:
# Question
Title: Using a setTimeout to Jump
I am trying to make a jump function.

I am making a game in html5 canvas with Javascript. I have gotten the player to move. When making the jump function I decided to use a timeout to reverse the coordinates back to the original after a set time.

The error is after the character moves up he does not return to the original position the character just stays there, and then upon clicking the jump (arrow key) again the player goes the other way e.g (down).

```
class Character {
  constructor() {
    this.x = 50;
    this.y = 400;
    this.posX = 0;
    this.posY = 0;
    this.width;
    this.height;
    this.hitPoints = 1;
    this.directionFace = "right";
    this.jump = false;
    this.jumpHeight = 23;
  }

  move(e) {
    this.x += this.posX;
    this.y += this.posY;

    if (e.keyCode == 37) {
      console.log('left');
      this.posX -= 10;
    }
    else if (e.keyCode == 38) {
      console.log("UP");

      if (!this.jumping) {
        this.posY -= this.jumpHeight;
        this.jumping = true;

        setTimeout(function() {
          this.posY = this.jumpHeight;
          this.jumping = false;
        }, 500);
      }
    }
    else if (e.keyCode == 39) {
      console.log("right");
      this.posX += 10;
    }
    e.preventDefault();
  }
}

```

# Answer
> 0 votes
Your `setTimeout` is not bound to context of class you need to either bind callback

```
setTimeout((function() {
  this.posY = this.jumpHeight;
  this.jumping = false;
}).bind(this), 500);

```

or use arrow function

```
setTimeout(() => {
  this.posY = this.jumpHeight;
  this.jumping = false;
}, 500);

```

---
Tags: javascript, html5
---


# Question
Title: Strange problem with rotation missile | unity3d - c#
I have a vertical missile with launcher that should find closest target and fire it's rocket to hitting target!

I use complete code of this 12min tutorial for launching my rocket, and the different between mine and its about the direction of rocket, mine is vertical and its horizontal!

```
homingMissile.velocity = transform.forward * missileVelocity;
Quaternion targetRotation = Quaternion.LookRotation(target.position - transform.position);
homingMissile.MoveRotation(Quaternion.RotateTowards(transform.rotation, targetRotation, turn));

```

After running the code, the rotation of my rocket change from (0,0,0) to (-8 .3,-4.7,0)!!!! and just change a little while hit target and explosion do.

In fact my rocket move to target in right path, but in wrong rotation!, in **STRANGE**!

Standby Rocket

Moving to Target

**Anyone can help me for this problem?**

# Answer
> 2 votes
The reason it is not rotating correctly is because the forward vector or z axis of the modal is not pointing to the tip of the rocket.

To solve it, either set the forward vector in some 3D modelling software or just create empty gameobject and assign the script to it, then make rocket as the child of empty object and rotate it in a way that the tip points to the z axis of empty object, also swap the collider and rigidbody to the empty gameobject as well.

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


# Question
Title: How can someone make 3D tiles not looking like perfect cubes?
Here are the graphics an artist did for me:

While the texture is nice when seen as image file, I think the tile is somewhat flat.

The problem is:

If he bevel the cube, then there will be tiling problems (not to mention seams between cubes). How can he make tile looks less flat?

If he make the 3D model to act like 2D isometric Tiles (which have very irregular outline) there will be so much polygons that will be a nightmare for him to model dozen of Tiles.

Of course keep in mind that for occluding reasons (each cube project 6 planes that are used to occlude hidden geometry) the overall shape should be actually bigger than a cube volume, but not smaller (anyway I can loose the height requirement, cubes can be made of any height).

# Answer
Usually to render a large quantity of gird aligned cubes is to use a method known as "Marching cubes".

***Note****: the main alternative is to use ray casting and voxels (point cloud data), which is less common in video games, however it is the standard in medical imaging. See also: A Fast Voxel Traversal Algorithm for Ray Tracing.*

You will see "Marching cubes" come up often when people talk about improving the performance of "voxels". The idea is that you will be iterating over the array of cubes and merging them into a single mesh in such way that hidden faces are removed, and also merges co-planar adjacent faces.

However, what I have described so far is simply Meshing.

---

Marching cubes (no quotes this time) goes a step further. In a similar way to how you can pick a tile from a tilemap based on its neighbors (Autotiling), Marching cubes will pick polygons depending on the neighbor cubes.

*See also Combinations for tiling two textures together.*

The original paper on Marching Cubes describes 15 configurations:

For each cube, you will pick a mesh from these configurations using a lookup table based on what vertices are hidden or visible. Since each cube has eight vertices, we have 256 entries on the table, which are reduced to the ones above by considering symmetries.

See Marching Cubes Animation | Algorithms Visualized.

*See also Nvidia GPU Gems 3 - Chapter 1.*

You do not have to use the same set of cases as described here. Hopefully you can see how you could edit this to match what you want.

---

Finally, if we do Marching cubes minus the Meshing, you would not be merging the cubes into a single mesh... instead you would simply identify what vertices are hidden and what vertices are visible and pick/modify the meshes depending on that.

*Wait, that is what you are doing. Huh.*
> 4 votes

# Answer
Seems I finally found a solution on my own. It is still not perfect, but looks much better! :) If you have further suggestions I'm open to everything. Basically on corners I need to "decorate" with additional geometry corners that are still part of a cube but with different normals.

I think it is actually more performant than correcting normal maps and to remove seams I just have to remove the "decoration" around the cube faces. Still I'm a bit in hunger with blender for having to resort to this trick instead of manually placing my normals (I could have used a shape different from a cube instead of trickin the smooth shading).
> 1 votes

# Answer
You don't need that extra geometry to apply a bevel effect via normal map. Just bake the normals of a high-res beveled cube to a simple cube in Blender (free software). There are many tutorials for this on Youtube.

I don't think it will look incredibly realistic but it will not look worse than what you have with more geometry, and require only 6 faces.
> 1 votes

---
Tags: tiles, art, 3d-modeling
---


title: How can I restart an animation?

text:
# Question
Title: How can I restart an animation?
The first time the player clicks a button, my animation plays properly.

The problem is that when the player presses the button a second time, the animation does not play.

Here is the code I'm using to control my animation:

```
public Animator anim;

public Animator animsfirst;
public Animator animssecond;
public Animator animsthird;

public Animator reanimsfirst;
public Animator reanimssecond;
public Animator reanimsthird;
public Animator closeinstruct;

public void instructionpanel()      //(instruction panel open animation)
{
    anim.enabled = true;         //when button click instruction panel open
    animsfirst.enabled = true;
    animssecond.enabled = true;
    animsthird.enabled = true;
}

public void closeinstructionpanel()  //(instruction panel close animation)
{
    Debug.Log("animationrun");   //when button click instruction panel close
    reanimsfirst.Play("freverse");
    reanimssecond.Play("srevese");
    reanimsthird.Play("lreverse");
    closeinstruct.Play("clreverse");
}

```

Here is the animator controller setup for the `animsfirst` object:

And for the `reanimsfirst` object:

How can I resolve this issue?

# Answer
> 2 votes
On your animator controller, create a new(empty) state, and set it as your default layer, now make a transition from your animation clip to the empty clip. The goal is to let the animator return to it's original state after it has played thereby allowing you to play again as many times possible.

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


# Question
Title: How minecraft manages interactable blocks (Chest)?
I am wondering, how does minecraft handle blocks like chest?

I guess normal blocks are ids in simple array, but how does it store and references blocks with special behaviour?

# Answer
> 1 votes
Both Mark Mueller and Ratchet Freak have part of the full answer.

1. Minecraft blocks are singleton instances: there is only one instance of the `BlockDirt` class, one instance of the `BlockChest`, only one `BlockStone`, and so on. There are a few exceptions due to relatively one-off effects (such as redstone ore and furnaces casting light "sometimes"), but not important here.
2. Because there's only one instance all block functions are passed: A `World`, a position, and any other information necessary (such as the `Entity`, `Hand`, or `ItemStack` involved). This information is all that is needed by the block class to do pretty much anything under the various conditions that a block is subject to (which ranges widely across multiple aspects of the game, including rendering).
3. Blocks that have extra data or extra functionality use `TileEntities` to store it or process it (as Ratchet points out). This includes the Chest, Furnace, Daylight Sensor (iirc), Hopper, and others. Any block that can "hold" an item in it has an associated tile entity.

* Same goes for blocks that "tick" (such as furnace smelting) as regular non-TE blocks only get random ticks (this is why wheat does not all grow at the same speed, despite identical conditions). Note that while a TE is required for ticking and a TE is required for an inventory (or other extra data), TEs do not *need* to do both (but frequently will).
    * The Crafting Table does *not* have a TE however: when the UI is closed all of its "contained" items pop back into your inventory because there is no 'container' to store them in. Blocks themselves declare whether or not they have a TE and if so, create it.
    * The `BlockContainer` class is not actually relevant. It was just a intermediate class to override a few methods that "all" container blocks are likely to need (but this actually messes up modders because it does things some container blocks *don't* need...such as completely disabling rendering because the chest is rendered in special edge-case code, but that disabling was done in `BlockContainer` irrationally and re-overriden in the non-chest blocks). Mark alludes to this class, but its purpose is contrary to what he actually said.

From here we have everything we need: as Mark said, blocks do a sort of "background check" when their functions are run (bullet 2) although what that logic is varies from block to block. For blocks like Chests (Crafting Table, Hoppers, Enchanting Table and so on) when they are right clicked the code says, "Hey, we need to open a UI" and that's all that's in the block code. Essentially:

```
SomeBlock extends Block {
    public void onRightClick(World w, BlockPos p, EntityPlayer player) {
        player.openUI(w, p, Constants.CHEST_UI);
    }
}

```

Not exactly what vanilla does, but close enough. Vanilla essentially says "hey, open the Chest UI" and the server goes "cool, I know what bits I need (player, world, and position) and I also need to send a packet to that player's client and then the client will do what it needs to." Forge adds a similar method for mod code that includes *what mod* is making the call so Forge knows where to find the right classes to invoke.

The hidden underlying background code that gets called some were along the way is `world.getTileEntity(world, pos)` and this is what converts from a "location in the world" to "that specific tile entity that is stored at that location." Blocks are stored in a massive array-of-arrays-of-arrays-of-arrays of integers (exact implementation varies by Minecraft version), which is why worlds can be so huge without actually taking up that much ram/hard drive space. TileEntities by contrast are stored in a hashtable (for each chunk) mapping position to TE instance as relatively few block positions contain a TE (and things go *really really bad* when they do! I've done it by accident).

So when a Block (a singleton) has a method called that needs to interact with the extended data held in a TE, that block can get that TE from the world and position parameters it gets from its own function call. If a UI is involved, then the player parameter comes into play, and from there network communication gets triggered in order to display the GUI on the client.

For blocks like the chest, there are two additional classes involved: a `Container` class and a `GuiContainer` class (thought that name is a bit misleading as the TE may not actually store items). The container holds information about the inventory of the block (TE) and one deals with actually *displaying* that information to the player. As such there are two *instances* of the `Container` present: one on the server (to track changes coming from the client and apply them to the TE) and one on the client (in order to know how to display the TE's data and send any changes to the server). How these classes work is incredibly complicated and I don't even know all of it. Even some of the functions like "player shift-clicks an item stack" is a convoluted mess that I don't fully understand. I just know that it's needed and that those 60 lines work correctly (and don't know why it isn't in the vanilla parent class, but instead implanted new in each of the `Container` subclasses that deals with inventories).

And that should give you at least a broad understanding of how it works in general and how incomplete even my answer is.

# Answer
> 2 votes
There is a separate "TileEntity" list per chunk which store the data for blocks that don't have enough with the id+metadata that is available for all blocks in the chunk.

When the chunk gets loaded or the block placed the id of the block maps to a class that knows whether it needs that special data and will load and parse it.

# Answer
> 1 votes
It's been a while since I have looked at the minecraft source code but I think the block extended a container handler. Whenever you right clicked it will search if the right click happened on the block and if it had a functionality it will run that code.

So it basically does a background check for the object you right clicked on and ran that blocks code.

---
Tags: minecraft-modding
---


title: PyBox2D car moves uncontrollably

text:
# Question
Title: PyBox2D car moves uncontrollably
I am trying to program TopDown Car using python and Box2D (similar to this tutorial: http://www.iforce2d.net/b2dtut/top-down-car ) The steering is so far limited to thres states of wheel rotation, that I will need to solve later, now I have problem with controlling the car velocity.

The problem is that the vehicle moves rather uncontrollably, I press "W" to move forward, "A" or "D" to steer, but then I ofttimes need to press "S" key to keep going in forward direction (which is of course counter-intuitive).

EDIT: I tried to convert world/object coordinates, it helped partially because now my car is moving from the beginning in straight line (it was always going slightly obliquely to the right, but now it has problems with turning, it turns uncontrollably and there is still the problem with messed-up directions (when I need the car to go forward after turning i have to press S

This is the main game loop: it should be updating PyGame frame 60 times per second, in Every frame I am cancelling lateral velocity of a body and then I am trying to controll the body

```
while running:
# Check the event queue
    screen.fill((255, 255, 255,0))
    for body in world.bodies:
        for fixture in body.fixtures:
            fixture.shape.draw(body, fixture)

        # Cancelling lateral velocity
        for wheel in Wheels:

            if wheel in range(2):
                continue # Rear wheels are not powered
            else:
                Current_Normal = wheel.GetWorldVector((0,1))
                Current_N_Squared =  b2Dot(Current_Normal, wheel.linearVelocity) * Current_Normal

                Right_Normal = wheel.GetWorldVector((1,0))
                Right_Normal_Squared = b2Dot(Right_Normal, wheel.linearVelocity) * Right_Normal

                Impulse = -Right_Normal_Squared * wheel.mass
                if Impulse.length >max_lateral_impulse:
                    Impulse *= max_lateral_impulse/Impulse.length

                wheel.ApplyLinearImpulse(Impulse, wheel.worldCenter, True)

                # Allowing skidding

                aimp = 0.05 * wheel.inertia * -wheel.angularVelocity
                wheel.ApplyAngularImpulse(aimp, True)

                current_forward_speed = Current_N_Squared.Normalize()

                drag_force_magnitude = -2 * current_forward_speed
                wheel.ApplyForce(drag_force_magnitude * Current_N_Squared,
                                        wheel.worldCenter, True)

        # Moving forward/backward
    if event.type == KEYDOWN and event.key == K_w:
        Left_Wheel.ApplyLinearImpulse(impulse=Left_Wheel.GetWorldVector((0, 10)), point =Left_Wheel.GetWorldVector((Left_Wheel.position)),wake = True)
        Right_Wheel.ApplyLinearImpulse(impulse=Right_Wheel.GetWorldVector((0, 10)),point = Right_Wheel.GetWorldVector((Right_Wheel.position)),wake = True)

    elif event.type == KEYDOWN and event.key == K_s:
        Left_Wheel.ApplyLinearImpulse(impulse=Left_Wheel.GetWorldVector((0, -10)), point =Left_Wheel.GetWorldVector((Left_Wheel.position)),wake = True)
        Right_Wheel.ApplyLinearImpulse(impulse=Right_Wheel.GetWorldVector((0, -10)),point = Right_Wheel.GetWorldVector((Right_Wheel.position)),wake = True)

```

If you want to play with my code in order to better see where the problem is I can give you the whole script (270 lines in total)

I know that to move more realistically I need to play with the aimp or max\_lateral\_velocity values. But first I need the car to be controlled better

EDIT 2: I am sorry, I was probably able to solve this problem by applying this:

```
Left_Wheel.ApplyLinearImpulse(b2Vec2(Left_Wheel.GetWorldVector((0, 10))), Left_Wheel.position,True)
Right_Wheel.ApplyLinearImpulse(b2Vec2(Right_Wheel.GetWorldVector((0, 10))), Right_Wheel.position,True)

```

This seems to be working, many thanks to Aleš Koblížek for patience Now my problem seems to be solved

# Answer
The KEYDOWN event is fired every time the key is pressed down, so the impulse is applied only then. Instead, you should remember the state of the key and apply force in every iteration of the main loop if the key is pressed down.

See this article for example code: https://www.iforce2d.net/b2dtut/forces

Also to make sure the speed is framerate-independent, you should multiply the applied force by frame time.

EDIT: The error with the force directions is that the function *ApplyLinearImpulse* takes direction in world coordinates, not in object coordinates.

EDIT2: You can use *getWorldVector* method to convert a vector from object coordinates to world coordinates, or *getWorldPoint* to convert points. There are also inverse methods *getLocalVector* and *getLocalPoint*.
> 1 votes

---
Tags: 2d, box2d, python, pygame
---


# Question
Title: How to set keys for emission on/off for a prefab?
I am making a prototype for a Mario game and am having difficulty completing a canned animation for a prefab. There is an item box asset that has 3 materials and an "ItemGet" animation. One of these materials has an active emission property that is supposed to turn off during a specific frame of the "ItemGet" animation. These boxes will have an "Active" and "Inactive" state.

* While "Active", the item box just bobs up and down and IF Mario hits the trigger, the "ItemGet" animation plays (and the player gets a unique item). The box then becomes "Inactive".
* While "Inactive", no animations play, the emission effect is gone and the trigger cannot be reactivated.

Challenges:

* finding the correct property to set a keyframe for in the Animations panel.
* Making sure Active versions of the prefab remain Active after any ItemBox becomes Inactive and that all materials don't change when GetItem plays.

Ideas:

* Instead of keying the emission on/off property (assuming that exists and does what I think it does; trouble finding it), swap the materials.
* ( . . . ), swap the mesh.

Can somebody please help me find a viable way to finish this animation that fits this object's intended use-case?

# Answer
If it were me, working on Unity or not, I would have two classes/prefabs and swap. The idea is that the active object will be replaced with a different object that is inactive. Simple.

To do that, in the event that handles the interaction with the object, you can instantiate a new object of the inactive kind, copy the transform properties (parent, location, rotation, scale) and destroy the old object.

You would not have to worry about the animation frame which the object is. You would not have to worry about modifying the object, or affecting other objects of the same kind. And you would not have to worry about changing materals, et. al.

---

*I have no idea on turning off emissions, et. al. I have only a passing knowledge of Unity.*
> 1 votes

---
Tags: unity, animation, materials, objects
---


# Question
Title: How do you write Texture2DContent and read it as Texture2D in the XNA content pipeline?
I'm trying to create a custom Monogame content pipeline extension that packs a bunch of individual sprites into a single sprite. I need help figuring out how to write and read the texture in the pipeline.

My writer outputs a `Texture2DContent` (wrapped in `SpriteSheetContent` model object) that contains a single `BitmapContent`. My reader then attempts to create a `Texture2D` from the serialized data, but encounters an exception when setting the data. I cannot make heads or tails of the exception since it's so cryptic.

Where am I going wrong?

### Models

```
public class SpriteSheetContent
{
    public Texture2DContent Texture { get; } = new Texture2DContent();
}

public class SpriteSheet
{
    public Texture2D Texture;
}

```

### Processor

```
    public override SpriteSheetContent Process( SpriteSheetDeclaration declaration, ContentProcessorContext context )
    {
        var spriteSheetContent = new SpriteSheetContent();

        BitmapContent sprite = <omitted code that creates a single bitmap content>;
        spriteSheetContent.Texture.Mipmaps.Add( sprite );

        return spriteSheetContent;
    }

```

### Writer

```
[ContentTypeWriter]
public class SpriteBoxWriter : ContentTypeWriter<SpriteSheetContent>
{
    protected override void Write( ContentWriter writer, SpriteSheetContent spriteSheetContent )
    {
        BitmapContent bitmapContent = spriteSheetContent.Texture.Faces[0][0];
        bitmapContent.TryGetFormat( out SurfaceFormat format );

        writer.Write( (int)format );
        writer.Write( bitmapContent.Width );
        writer.Write( bitmapContent.Height );

        byte[] pixelData = bitmapContent.GetPixelData();

        writer.Write( pixelData.Length );
        writer.Write( pixelData );
    }

    public override string GetRuntimeType( TargetPlatform targetPlatform )
    {
        return typeof( SpriteSheet ).AssemblyQualifiedName;
    }

    public override string GetRuntimeReader( TargetPlatform targetPlatform )
    {
        return "Monogame.SpriteBox.SpriteSheetReader, Monogame.SpriteBox";
    }
}

```

### Reader

```
public class SpriteSheetReader : ContentTypeReader<SpriteSheet>
{
    protected override SpriteSheet Read( ContentReader reader, SpriteSheet existingInstance )
    {
        SpriteSheet spriteSheet = existingInstance == null ? new SpriteSheet() : existingInstance;

        var format = (SurfaceFormat)reader.ReadInt32();
        int width = reader.ReadInt32();
        int height = reader.ReadInt32();

        var graphicsDeviceManager = (GraphicsDeviceManager)reader.ContentManager.ServiceProvider.GetService( typeof( IGraphicsDeviceManager ) );
        spriteSheet.Texture = new Texture2D( graphicsDeviceManager.GraphicsDevice, width, height, mipmap: false, format: format );

        int pixelDataLength = reader.ReadInt32();
        byte[] pixelData = reader.ReadBytes( pixelDataLength );

        spriteSheet.Texture.SetData( pixelData ); // this line results in the exception

        return spriteSheet;
    }
}

```

### Exception

```
SharpDX.SharpDXException
  HResult=0x80070057
  Message=HRESULT: [0x80070057], Module: [General], ApiCode: [E_INVALIDARG/Invalid Arguments], Message: The parameter is incorrect.

  Source=SharpDX
  StackTrace:
   at SharpDX.Result.CheckError()
   at SharpDX.Direct3D11.Device.CreateTexture2D(Texture2DDescription& descRef, DataBox[] initialDataRef, Texture2D texture2DOut)
   at Microsoft.Xna.Framework.Graphics.Texture2D.CreateTexture()
   at Microsoft.Xna.Framework.Graphics.Texture2D.PlatformSetData[T](Int32 level, T[] data, Int32 startIndex, Int32 elementCount)
   at Microsoft.Xna.Framework.Graphics.Texture2D.SetData[T](T[] data)
   at Monogame.SpriteBox.SpriteSheetReader.ReadTexture(ContentReader reader, SpriteSheet spriteSheet) in D:\Projects\Game Development\Monogame.SpriteBox\SpriteBox\SpriteSheetReader.cs:line 45
   at Monogame.SpriteBox.SpriteSheetReader.Read(ContentReader reader, SpriteSheet existingInstance) in D:\Projects\Game Development\Monogame.SpriteBox\SpriteBox\SpriteSheetReader.cs:line 14
   at Microsoft.Xna.Framework.Content.ContentTypeReader`1.Read(ContentReader input, Object existingInstance)
   at Microsoft.Xna.Framework.Content.ContentReader.InnerReadObject[T](T existingInstance)
   at Microsoft.Xna.Framework.Content.ContentReader.ReadObject[T]()
   at Microsoft.Xna.Framework.Content.ContentReader.ReadAsset[T]()
   at Microsoft.Xna.Framework.Content.ContentManager.ReadAsset[T](String assetName, Action`1 recordDisposableObject)
   at Microsoft.Xna.Framework.Content.ContentManager.Load[T](String assetName)
   at Game1.Game1.LoadContent() in D:\Projects\Game Development\Monogame.SpriteBox\Game1\Game1.cs:line 48
   at Microsoft.Xna.Framework.Game.Initialize()
   at Game1.Game1.Initialize() in D:\Projects\Game Development\Monogame.SpriteBox\Game1\Game1.cs:line 35
   at Microsoft.Xna.Framework.Game.DoInitialize()
   at Microsoft.Xna.Framework.Game.Run(GameRunBehavior runBehavior)
   at Microsoft.Xna.Framework.Game.Run()
   at Game1.Program.Main() in D:\Projects\Game Development\Monogame.SpriteBox\Game1\Program.cs:line 18

```

### Other approach I've tried already

I thought simply doing `writer.WriteObject<Texture2DContent>( spriteSheetContent.Texture )` in the writer, and then doing `spriteSheet.Texture = reader.ReadObject<Texture2D>()` in the reader would work. However, this results in the same type of exception.

I even came across Monogame's Texture2DWriter and Texture2DReader, but using their examples leads to the same exception.

# Answer
> 1 votes
Well, the answer was simple and something else entirely. It dawned on me that maybe I was packing too many individual textures into a single texture; it turns out I was.

I'm not sure what the texture size limit is in this context, but I must have been exceeding it. I removed a bunch of textures that were being packed to a safe amount, and the code worked as expected.

**Edit**

Confirmed... HiDef profile max texture size is 4096x4096 and Reach profile is 2048x2048. I was using Reach profile for my tests, and my single texture was larger than the limit.

---
Tags: monogame, xna-4.0, xna-content-pipeline
---


# Question
Title: stats or profit give away result of game
Think of a coinflip game, whose logic looks as follows:

* Server sends websocket message (RESULT\_MESSAGE) to frontend with result of a game (won/lost)
* Server sends websocket message to frontend with updated aggregated stats (STATS\_MESSAGE) (think all-time profit after the new coin flip, or updated all-time stats)
* Frontend reacts to RESULT\_MESSAGE by playing an animation (coin flipping). It also updates the all-time stats and profit in response to STATS\_MESSAGE

The problem with this logic is, responding to STATS\_MESSAGE (updating profit and stats) gives away the result of the coin flip before the animation finishes.

Solutions I cannot use:

* Merging RESULT\_MESSAGE and STATS\_MESSAGE together, and only updating the stats/profit after animation finishes. Because those 2 messages are produced and sent by different services.
* Linking a particular RESULT\_MESSAGE to a STATS\_MESSAGE and only reacting to a STATS\_MESSAGE when its corresponding RESULT\_MESSAGE has been processed and its animation completed. Because in reality I have several kinds of STATS\_MESSAGES (trophies updated, stats updated, profit/balance updated, etc), and it's just not practical for the frontend to hold onto all those messages until their respective RESULT\_MESSAGE is processed

Solutions I've tried successfully before, but I'm trying to avoid:

* Having the backend send STATS\_MESSAGE with a delay, to make sure it doesn't reach the frontend before the coinflip animation has finished. This sort of encodes frontend behavior (animation) on the backend.

All ideas and suggestions appreciated. Thanks a lot!

EDIT: I made the coin-flipping example for simplicity, but it's not precisely con-flipping. It's a multiplayer game where dozens of games/animations per user per seconds are going on. So queuing a bunch of stuff on the frontend might be less than ideal (I'm still looking into performant versions of this solution though).

Pulling the STATS data via an API call when the animation finishes (instead of using websockets data) is another alternative that I've considered, but for the same reason described above it might not be feasible (dozens of API calls per user per second). Plus there's a chance that an API call is triggered by `game-1` finishing, but while `game-2` animation is still going on, giving away the result of `game-2`

# Answer
You are actually dealing with two gamestates models here: The actual model representing the current state of the game (where the player has already won/lost) and the virtual gamestate model representing what the player should be aware of (where the coin is still spinning). If you are aware of this and separate these two game-states on the server side, you can solve the problem as follows:

1. Player clicks on "spin the coin"
2. Server receives the coin spinning message and updates the actual game state
3. Server starts a timer of x seconds
4. The timer finishes and triggers an event to update the virtual game state
5. The change to the virtual game state triggers a message to the player, informing them that the coin stopped spinning, the result of the spin and their new game state.

I know you said you want to avoid to "encode frontend behavior (animation) on the backend". But if that frontend behavior actually gives the player a gameplay disadvantage (having delayed access to information which is already known to the server) and you want the game to be cheat-proof (you wrote it's a multiplayer game, so I assume that's a priority), then you can't trust the frontend to implement that disadvantage. You must make sure that the client only receives the information it is supposed to tell the player. That means you have to implement some of the presentation logic server-sided.
> 2 votes

---
Tags: game-design, architecture, statistics
---


title: unity 3d loading data from json problem

text:
# Question
Title: unity 3d loading data from json problem
i am trying to practice on loading data from json files my problem is about when i try to load the sprite path from the json file to load the image icon from the floder that contain it, i manged to do that but by hard code the path but when i try to use variable to hold the path its failed to load any one can help me in that please

i post the code here

```
public class InventoryItemDataBase : MonoBehaviour
{
    public allitemData itemsData = new allitemData();
    // Start is called before the first frame update
void Start()
{

    TextAsset asset = Resources.Load("ItemData/ItemDataBase") as TextAsset;
    itemsData = JsonUtility.FromJson<allitemData>(asset.text);

}
public ItemBase itembyid(int id)
{
    for (int i = 0; i < itemsData.ItemBase.Count; i++)
    {
        if (itemsData.ItemBase[i].id == id)
            return itemsData.ItemBase[i];
    }
    return null;
}
}

[System.Serializable]
public class allitemData
{
    public List<ItemBase> ItemBase = new List<ItemBase>();
}

[System.Serializable]
public class ItemBase
{
    public int id, Value;
    public string name, description;
    public static string path;
    public static Sprite Icon = Resources.Load<Sprite>(path);
    public Sprite sprite = Icon;
public ItemBase()
{
    this.id = -1;
}
}

&& json Data

{
  "ItemBase": [
    {
      "id": "0",
      "Value": "7",
      "name": "Teddy Bear",
      "description": "Teddy",
      "path": "IconS/Teddy/"
    },
    {
      "id": "1",
      "Value": "5",
      "name": "UFO",
      "description": "ufoos"
    }]
}

```

# Answer
> 1 votes
First thing, in this circumstance, static is not going to work (Follow the link if you don't know what static does exactly). Although in this case the compiler gives you this error without the static keyword:

> CS0236 A field initializer cannot reference the non-static field, method, or property 'ItemBase.path'

I'm answering this under the assumption that this is the reason why you made it static in the first place, if you had a different reason to do that, because you want it to be static, please notify me and explain your reasons behind that. This error doesn't mean that you should make it static. Because static variables are tied to a Type (ItemBase in your example) instead of the instance of that type. Meaning that if you change it, you change it for all ItemBases, not just the one you want. Also, JSON doesn't (de)serialize it, so that won't work.

As to why you get the above error, see the documentation. This documentation tells you that you should set this value in a method, preferably the constructor. However, because we are Deserializing the constructor is called before the values (id, value, path, name etc.) are overwritten by the JSON values. Meaning we can't use the constructor for this.

There are multiple options to overcome that problem. I'll list 2 simple ones here, although there might be better ones, especially in other JSON libraries that might support things like calling a constructor.

* Initialize your sprite yourself after deserialization

```
itemsData = JsonUtility.FromJson(json);
foreach (var item in itemsData.ItemBase)
{
    item.sprite = Resources.Load(item.path);
}

```

```
public class ItemBase
{
    public string path; // Set by JSON

    [NonSerialized] public Sprite sprite; // Set by us
}

```
* Use a property, that loads the reasource the moment you ask for it. This can have the added advantage/disadvantage that the loading of resources is done at the point when you actually need it, possibly spreading out the load on your cpu.

```
public class ItemBase
{
    public string path; // Set by JSON

    [NonSerialized] private Sprite _cachedSprite; // Set by us

    public Sprite Sprite
    {
        get
        {
            if (_cachedSprite == null)
                _cachedSprite = Resources.Load(path);
            return _cachedSprite;
        }
    }
}

```

---
Tags: unity, c#, unityscript, json
---


# Question
Title: How can a variable have two values at the same time?
Just to clarify, I do not want to know how to make a variable display 2 values at the same time.

I want to know how this is happening in my project.

**In the Level Blueprint I have a timer that every 5 seconds generates 2 warriors in different places. This in order to distinguish them. One is from the blue team and the other from the red team:**

The team of each one I can define correctly, the problem happens with the whole variable.

The value of the blue warrior variable should be 5. The value of the red warrior variable should be 1.

**I have a Text Render that displays the time and value of the variable I have quoted:**

**In the Event BeginPlay I have a loop that prints the value of this integer variable I have quoted:**

**Game picture:**

**Game picture:**

How can one place show that the variable is 0 and in the other show that it is 1/5?

---

**EDIT 1 (verification of some information)**

Some time after posting this question, I wondered about the value of the warrior team being correct or not, and through an impression I noticed that there was also an error.

**On printing right after the event I was able to confirm the error:**

**In game:**

**Default value of the string variable:**

**Default value of the integer variable:**

From what I've noticed, I can not change the default value of the variables in the warrior generation. Even with the pin coming out of the spawn.

# Answer
Begin play called before you are setting the variable. On dynamically spawned actors begin play will be called instantly before any other bp node will be executed.
> 1 votes

# Answer
The reason this isn't working is that you're spawning an actor of the class but not referencing a specific instance of it.

After you've spawned, cast to your AI Character reference then from that reference, set your variables.
> 0 votes

---
Tags: unreal-4, spawning, blueprints
---


# Question
Title: AudioClip generated by an external process and loaded into the editor has no samples
I'm working on a custom `ScriptedImporter` -- let's call it `LmmsImporter` -- that loads project files from the LMMS sequencer as `AudioClip`s. I don't parse the project file; instead, I expect users to install LMMS, configure its location, then store their project files inside their `Assets` directory. After the asset settings are configured, the import process looks like this:

1. Create command-line arguments based on the properties offered by `LmmsImporter`
2. Get a temporary path inside the project's `Temp` directory (not the OS's equivalent)
3. Spawn an LMMS process that renders the imported project file to the path given by (2), with the arguments given by (1).
4. Wait for the process to complete.
5. Load the `AudioClip` at "runtime" (i.e. in an editor script, not as an imported asset) with `UnityWebRequestMultimedia.GetAudioClip`
6. Clone the `AudioClip`.
7. Set the cloned `AudioClip` to be the LMMS project asset's main object, as described here.
8. Save the imported asset, then delete the original audio file generated by (3).

**Everything up to but not including step 7 works as expected.** In fact, even step 7 *appears* to work as expected. But when I open up the imported `AudioClip`, it has no samples. When I try to play the preview in the editor, I get this error in the editor console:

```
Error: Cannot create FMOD::Sound instance for resource , (Error loading file. )
UnityEngine.GUIUtility:ProcessEvent(Int32, IntPtr)

```

What makes this weird is that:

* The sound is properly rendered by LMMS and saved to the filesystem. Nothing unusual happens here.
* Playing the `AudioClip` inside the importer script **immediately after it's loaded** (i.e. while still in `OnImportAsset`) with `AudioSource.PlayAtPoint` works as expected.
* The data is properly cloned; I checked, the arrays are equal.
* I do not receive any errors or exceptions except those that I've already described, not even from LMMS.

This is an excerpt of my code with the parts I think are most relevant:

```
using System;
using System.Diagnostics;
using System.IO;
using UnityEngine;
using UnityEngine.Networking;
using UnityEditor;
using UnityEditor.Experimental.AssetImporters;

[ScriptedImporter(1, new[] { "mmp", "mmpz" })]
public class LmmsImporter : ScriptedImporter
{
    // Properties omitted for brevity

    public override void OnImportAsset(AssetImportContext ctx)
    {
        var relativeTempPath = FileUtil.GetUniqueTempPathInProject();
        var projectDir = Path.GetDirectoryName(Application.dataPath);
        var absoluteAssetPath = Path.Combine(projectDir, assetPath);
        var tempPath = Path.Combine(projectDir, relativeTempPath);

        try
        {
            using (Process lmms = new Process())
            {
                // Process invocation details and error handling omitted for brevity
                // ...one successfully rendered WAV, OGG, or MP3 file later...

                using (var request = UnityWebRequestMultimedia.GetAudioClip(new Uri(tempPath), audioFormat))
                {
                    var handler = request.downloadHandler as DownloadHandlerAudioClip;
                    handler.compressed = false;
                    handler.streamAudio = false;
                    request.timeout = LOAD_MEDIA_TIMEOUT;

                    var operation = request.SendWebRequest();

                    while (!(request.isHttpError || request.isNetworkError || handler.isDone)) ;
                    // Let the request finish, unless we get an error (possibly including a timeout)

                    var clip = DownloadHandlerAudioClip.GetContent(request);

                    clip.LoadAudioData();

                    var assetName = Path.GetFileNameWithoutExtension(assetPath);
                    var clone = AudioClip.Create("Clip", clip.samples, clip.channels, clip.frequency, false);

                    using (var so = new SerializedObject(clone))
                    {
                        var samples = new float[clip.samples * clip.channels];

                        clip.GetData(samples, 0);
                        clone.SetData(samples, 0);

                        // Everything above this line works fine

                        ctx.AddObjectToAsset("AudioClip", clone);
                        ctx.SetMainObject(clone);

                        so.ApplyModifiedProperties();

                        EditorUtility.SetDirty(clone);
                    }
                }
            }
        }
        catch (Exception e)
        {
            ctx.LogImportError($"Failed import with {e.GetType()}: {e.Message}");
        }
    }
    private const int LOAD_MEDIA_TIMEOUT = 5; // seconds
}

```

I'm using Unity 2019.1.7f1 Personal, on Ubuntu 19.04. Is this a bug, or am I doing something wrong?

# Answer
> 1 votes
It appears that this is a bug. I've reported this to Unity and they have reproduced it. The ticket can be found here.

---
Tags: unity, asset-management, editors, importing
---


# Question
Title: OpenGL Textures: Texture contains color lines when object is further away that some distance
I tried searching on the web but couldn't find a reason for this. When I render an object close to the camera, the object and texture renders fine. But further away from a fixed distance, it starts showing weird color lines on the texture.

Close to the camera, no lines:

Further away, color lines appear on texture:

My shaders are pretty simple.

```
#version 330 core

layout (location = 0) in vec3 pos;
layout (location = 1) in vec2 tex;

uniform mat4 projMatrix;
uniform mat4 viewMatrix;

out vec2 uvCoord;

void main()
{
    gl_Position = projMatrix * viewMatrix * vec4(pos.xyz, 1.0f);
    uvCoord = tex;
}

```

---

```
#version 330 core

out vec4 FragColor;

uniform sampler2D texture1;

in vec2 uvCoord;

void main()
{
    FragColor = texture(texture1, uvCoord);
}

```

My texture parameters are:

```
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

```

Any help would be appreciated!

Edit: I have generated mipmaps using `glGenerateMipmap(GL_TEXTURE_2D)`

# Answer
> 1 votes
You forgot to actually use the generated mip maps. You need to pass `GL_LINEAR_MIPMAP_LINEAR` (or any of the 3 alternatives) as the third argument when setting the min filter.

---
Tags: opengl, shaders, textures
---


# Question
Title: Overlap detection does not work correctly when there is more than one warrior colliding with the tower
I have a project where warriors are generated and they follow a route. In this route has a tower, when a warrior overlaps that tower, it takes 5 of it life, and he does it every 1 second.

**Code of the moment of the collision of the warrior with the tower (Warrior Blueprint): *Call Even Lose Life***

Look that the moment he overlaps the tower, he starts to move towards it. After that he calls an event that is present in the blueprint of the tower.

**Event that was called (Tower Blueprint): *Execute Event Lose Life and call Event Attack Tower***

This event causes the life of the tower to be shortened by 5. Soon afterwards it is called an event in the warrior that is colliding with the tower.

**Event called by the tower (Warrior Blueprint): *Execute Event Attack Tower and Call Event Lose Life***

This event is only to be given a 1 second interval between each attack by each warrior. At least that was the idea.

I could simply loop in the blueprint of the tower and multiply the damage (5) by the amount of warriors colliding, but it does not seem right to me.

I imagine the problem is because the event in the tower (**image 2 of question**) is being called multiple times without even being finalized.

**In the game, when there is only one warrior overlapping the tower, everything happens correctly:**

1 second interval between images.

**With more than one warrior overlapping the tower, tower life only decreases with the arrival of a new warrior. While a new warrior does not come to life he remains intact:**

**When in reality what should happen was each of them take 5 life per second. Then 3 warriors, 15 life per second.**

The way I did these 15 lifetimes will not be taken away at the same time, as the warriors have come at different times.

**Exemplifying:**

* Warrior 1 arrived in the tower at 15.2 seconds.
* Warrior 2 arrived in the tower at 21.5 seconds.
* Warrior 3 arrived in the tower at 32.8 seconds.

**Then in the second 33 (moment where the three warriors have already arrived):**

* Warrior 1 will take 5 life from the tower at 33.2 seconds.
* Warrior 2 will take 5 life from the tower at 33.5 seconds.
* Warrior 3 will take 5 life from the tower at 33.8 seconds.

*How to make the damage to the tower correctly applied, regardless of the amount of warriors?*

---

**EDIT 1 (Attempt made based on Stephen's answer)**

**Warrior Blueprint:**

It works perfectly when it is colliding with only one warrior, when it reaches 1 more, life stops to decrease and decreases 5 for each new warrior that overlaps.

---

**EDIT 2 (getting deeper into the tests)**

**Pretty much the same code as the first edition, with the difference that I added a print at the end of the loop (when it is finalized) and added another condition to take the test:**

In the print will appear the actor's name + the word "acabou" + condition value.

**In Game:**

As soon as the second warrior overlaps the tower, the loop of the first and second warrior ends. This happens with both conditions.

***The loop is ending incorrectly and I do not know why. Something is making the condition false.***

**Message Log:**

# Answer
Variables that prevent the event from being called more than once. That's the secret.

So when calling the event you impose conditions that (visually) the overlap never closes.

In fact, it will be oscillating.

To solve this, as soon as the warrior overrides the tower, have him try to go towards it (simple move to location/actor) until he dies or the tower is destroyed.

**The code is very simple:**

You use a loop with conditions (see in the image).

Unfortunately I had to use two variables, instead of using only the life of the tower, because it was giving error.

Basically, because Event Tick of the tower, which destroys her as soon as her life arrives. Then I gave the reference error...

Being straightforward, before the tower is destroyed, it defines this Boolean variable as true, thus closing the loop.
> 0 votes

# Answer
The overlap event is working correctly. Your tower doesn't know how many warriors are attacking it, just that something is inside the detection area.

You could try moving the -5 logic to after the branch of your loop where you check for a warrior but I'm not certain if that would work.

The easiest way would be to put the damage inside the warrior blueprint, casting to the tower so they each (after checking the tower still exists so you don't get nullptr errors) do damage rather than having the tower do all the work. This way, it doesn't matter if you've got 1 warrior or 1000 attacking.
> 1 votes

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


# Question
Title: Unity Colliders - How do I detect nearby objects without my detection ranges detecting each other
How can I get both colliders' types in a trigger overlap message like `OnTriggerExit2D(Collider2D other)`?

Example:

* `objects A and B` both have a `BoxCollider2D` and `CircleCollider2D` components.
* Then, `object A` enters one of the trigger colliders of `object B`.
* I can get `object B`'s collider type with the `is` operator.

How can I get A's collider type?

The reason I want this is that I want only collisions where `object A`'s `CircleCollider2D` touches `object B`'s `BoxCollider2D`.

```
void OnTriggerExit2D(Collider2D other)
{
    if (other is BoxCollider2D)
        //Do Code
}

```

Here is a table of what I want: I want only to register trigger overlaps from `CircleCollider2D to BoxCollider2D`. With the `is` operator, I can safely remove all collisions to `CircleCollider2D` but collisions between two `BoxCollider2D` stay, which I do not want.

```
+------------------+---------------+------------------+
|  Row to Column   | BoxCollider2D | CircleCollider2D |
+------------------+---------------+------------------+
| BoxCollider2D    | No            | No               |
| CircleCollider2D | Yes           | No               |
+------------------+---------------+------------------+

```

**Edit** The real questions was to detect nearby objects without the detection range dectecting each other.

# Answer
With `Physics2D.OverlapCircleNonAlloc`, you can set an area around a point (my gameobject) and then saving the results in a `Collider2D[]` array which contains all objects nearby from the range I want.
> 0 votes

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


# Question
Title: How to set the delay based on the number of attacks performed in 1 second?
I would like the delay that defines the interval in which the warrior deals damage to an enemy, was calculated based on a number of attacks per second and not a delay.

**Explaining best, I'd like to define how many times the loop executes per second, not the time interval:**

**Something like no LOL:**

# Answer
> 0 votes
**Edition made based on a very relevant comment from Bilkokuya.**

Before doing any research, I tried to deduce the formula, and I did. It's quite simple.

The formula I had made, was (for the interval of 1 second) divide the number (x) by itself squared (x²):

* x / x² \<= example =\> 2 / 2² == 2 / 4 == **0,5 delay interval**

**In the blueprint of unreal (that I'm doing the game) it looked like this:**

**With the comment from Bilkokuya I understood that it is only to reverse the number:**

* 1 / x \<= example =\> 1 / 2 == **0,5 delay interval**

**And this calculation for attack speed works for any time interval:**

* 2 / x \<= example =\> 2 / 2 == **1 delay interval**

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


# Question
Title: Bullet is not instantiating properly in Unity
So I'm trying to make a simple weapon where I just instantiate a bullet at the Shoot Point's gameobject position. For some reason when I press down on my mouse the bullet just flies up. Any ideas on why this could happen?

```
Vector3 velocity = bullet.transform.forward * 1000 GameObject bulletGameObject = Instantiate(bullet, shootPoint.transform.position, Quaternion.identity);
Rigidbody bulletBody = bullet.GetComponent<Rigidbody>();
bulletBody.velocity = velocity;
Destroy(bulletGameObject, 4f);

```

# Answer
> 1 votes
Here `bullet` is referring to the bullet prefab you're copying to make your new instance to fire. (I like naming my prefab variables things like `bulletPrefab` to make this extra-obvious)

So you're assigning its velocity based on *the prefab*'s forward direction, not on the direction the gun is pointing. If you happened to save your prefab pointing straight up, then that's where every bullet will go, regardless of the gun's facing direction.

You probably want something more like:

```
Vector3 velocity = shootPoint.transform.forward * firingSpeed;

```

Assuming your `shootPoint` transform is oriented with its local z+ axis pointing in the direction you want to shoot.

The other thing you'll want to watch for is if both the player/gun and the bullet have colliders, and they overlap when the bullet is spawned at `shootPoint`. The physics engine might see this and try to apply an impulse to separate the overlapping colliders, knocking your bullets off-course. To fix this, you can...

* Use physics layers so the player does not interact with their own bullet colliders
* Use IgnoreCollision to selectively ignore collisions between the gun and its bullets, as you fire each bullet
* Make the bullet collider a trigger so it doesn't participate in collision resolution (but can still *detect* collisions with `OnTriggerEnter` etc)

# Answer
> 0 votes
Check the local z-axis of your prefab. When you assign velocity value to a gameobject it will move in local `Vector3.forward` (constant value) direction.
The best solution is to create empty object and assign your model as child, rotate child to line up with parent's z-axis.
Make that new object (parent of you bullet's model) as new prefab and instantiate it. Additionally to be sure that bullet goes the same direction as the gun is pointing instead of `Quaternion.identity` use `transform.rotation`.

---
Tags: unity
---


# Question
Title: Getting notified about a change of a public variable in a script
I have a script attached to a GameObject.

In this script I have the variable `public int Rotation`

If this value is changed, I need to do some calculations.

I know that I can be notified when this value is changed in the Inspector (for example if somebody enters a different number), but I would like to be notified if this value is changed by another script.

Is that possible, or do I need do introduce a `void ChangeRotation(int uNewValue)` or similiar?

Thank you!

# Answer
> 2 votes
You can do this with a property:

```
[SerializeField]
private int _rotation;
public int rotation {
    get { return _rotation; }

    set {
        // Act on the change here.
        _rotation = value;
    }
}

```

# Answer
> 0 votes
You can also combine property and event:

```
private float _rotation;
public event Action <float> OnRotationChange;
public float Rotation {
    get { return _rotation; }
    set {
        _rotation = value;
        OnRotationChange?.Invoke (value);
    }
}

```

Subscribe to event:

```
scriptInstance.OnRotationChange += Handler;

```

where `Handler` is a method with one `float` parameter. When rotation changes, the event fires, and all its handlers get called.

When you no longer need the object that reacts to the event, **unsubscribe** from it:

```
scriptInstance.OnRotationChange -= Handler;

```

### Be careful!

If you don't unsubscribe, it's a performance and memory leak, because the event remembers the handler and calls it, and prevents GC from collecting the object that is no longer in use.

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


# Question
Title: Is it possible to avoid global data in a Multi User Dungeon (MUD)?
I am currently designing a Multi User Dungeon (MUD). For those who do not know what it is, they are the ancestors of MMORPGs. There is no graphics, everything is played in a console by typing commands. Players move into rooms, fight monsters, earn xp, and so on.

I am programming in C++ and use Boost. I am inspired by several examples of MUD that I found on the internet whose source code is available.

In each of the examples I found, global variables are often used: the list of players, the list of connected players, the list of rooms, etc. Indeed, these data are used absolutely everywhere in the program. They are at the heart of the game. 80% of the code consists in manipulating these data. I understand that others have been tempted to declare these data as global variables.

But I understand the danger of global variables and the problems that their use raises.

The problem is that I cannot imagine a viable solution that would prevent me from using global data.

I will try to give you a description of my architecture to illustrate my problem:

* a class Server (linked to a list of sessions)
* a class Session (linked to a connection instance)
* a class Connection Instance (linked to a Player, a Session and a Context)
* a class Player (linked to a Room)
* a class Area (contains Rooms)
* a class Room
* a class Context (used to differentiate the different contexts: normal play, or when the player types his name and password, etc)
* a class Command (for example, “kill a mob”)
* many others…

I am not sure to know how I can have an access to every room/player/npc/object in the game in all these classes without passing everywhere a reference or a pointer to an object containing the whole game as parameter.

For example, a player might have a "kill every player in the world" command. "KillEveryoneCommand" that would inherit "Command". But where would this list of players be stored? How could it be accessed from the "Player" class or from the "KillEveryoneCommand" class?

Theoretically, a player could also have a command to ignite all the rooms of an area, or to communicate with another player from a distance... All these things are done without any problem with global data.

Would an online game with such central and shared data be a good exception for using global data?

# Answer
> 1 votes
## How to do Globals

Perhaps you are trying to avoid global variables out of dogma. It is common to have a class with static methods (or a global instance when that is not possible) that can be interrogated about objects. I'll give you two examples:

You can do something similar. Have an object that holds the model of the game and that has query methods. These query methods will return some sort of iterator that hides the data structures actually used, in such way that they can change independently of client code.

---

## "Design Patterns"

Perhaps you think that what I mention above is not not satisfactory. Certainly, there must be a way to do this without globals. And a way that makes sense (and is not passing a huge model object around)...

That would be a form of Dependency Injection. If a Command needs some objects to run, and `injector` system must provide them.

That means that instead of having the command query the global state (as it would do if implemented as I said in the first part of this answer), it must publish a description of what it needs to run (perhaps as an interface) and then depending on that (perhaps as a template) what it needs will be injected into it as parameters when doing the call to run it.

To inject that information, it must come from somewhere... hmm... The whole `injector` thing is overcomplicating things. Keep it simple.

---

## OOP

Now, should you pass this huge model object around to everything? Not necesarily. You might have encountered the argument that the solution for globals is OOP.

This is how it ends up like: On program entry, you create an object, and call a method on it. Inside that method you do your program logic. And now, instead of global variables, that object has fields, and everbody reads those fields.

*OOP, whoopty doo.*

---

## A real architecture

**You isolate external systems.**

Standard input? That is an external system. Have a class deal with them and give you meaningful data. I suppose it gives you Commands. Whatever it is, it should have value semantics. *In fact, I would argue it should not give you objects.* Yes, you will have a single object of that class, created on the entry point.

Next, you have to deal with the Commands. I understand the urge to make commands smart (the commands knows how to execute itself). However, not, that is not right...

This is a MUD. There is a network. The network is an external system. We need to deal with sending these Commands to the server. You need to have an Observer pattern, so that you can have a class that deals with networking, it takes Commands, and you subscribe it to the class that deals with the console.

*See, if Commands weren't values, there would be a problem to send them over the network.*

Alright, the server will also have a class that deals with the network, and it will output these Commands. Here is where you need a system that knows how to execute the Commands (Note: nothing wrong with a `switch` based state machine to deal with Commands). This will be class that you instantiate passing the model object, and it also gets Commands. Observer pattern again. The class will update the model and generate Notifcations.

Of course, you need communication both ways. From server to client is different... since the client will - I am assuming here - have a limited view of the world, it does not have to get Notifcations of every executed command. Instead, there must be commands the client send that subscribe or unsubscribe from certain Notifcations. For example, entering a room subscribes the channel to the Notifcations from that room. *You figure it out, it is your game.*

Alrigh, so you got Notifications. And some clients are subscribed to some Notifications. You need another class that deals with figuring out what Notification goes to what client. And that has to talk to another class that sends reponses over the network. Finally on the client side, another one takes the Notifications from the network and *renders* (writes to standard output).

---

Why is that good? Because you can swap parts. Did you decide you will no longer have a console, but instead a GUI? You can do that. Did you decide that the network code will run on its own thread? You can do that. Did you decide that the game is persistent and you will be storing everthing to a database? You can do that.

I am, of course, ingoring handling user accounts et. al. So, you probably will not plug the system that takes commands from standard input right away, instead you will deal with connecting to the server and authenticating the user first... afterwards you instantiate that system (see, it makes sense to make it a class).

Bonus: You can deal with releasing resources in destructors. For example, the destructor of the network system will release the connection. I hear they call it RAII? *Naming, whoopty doo.*

# Answer
> 1 votes
One option is to build an **event-based architecture**. In such an architecture, objects communicate via an event queue. They can post events to that queue and register themselves as receivers for specific events. But the reaction to these events is implemented in the receivers.

For example, the Kill Everyone command would be implemented by having all killable entities (or other objects which want to know about that event for some reason) register themselves as receivers for the Kill-event. The entity which performs the command then posts a Kill event for everyone to the global event queue. The other entities receive that event and do what needs to be done in order to die.

Receiving event can either happen as a push-logic (the event queue calls a method on the receivers) or as pull-logic (the receivers ask the event system for events during their update-method).

The advantage of this architecture is that the only data you need to share between entities is the event queue object itself. You will be able to avoid sharing most data about the global game state. You also have a very loose coupling between entities, because event senders and event receivers don't even need to know of each other's existence.

Usually you have at least one global event queue in such an architecture, but it is quite common to also have local event queues. In a MUD it would be quite usual to have an event queue for each room which handles events which are only relevant for entities which are in that room right now or for systems which only operate inside a specific room. When you have a component-based architecture where each entity in the game is a composite of multiple objects, you can also use entity-internal event queues to implement the communication between the components.

However, this architecture doesn't come without cost. The event dispatching logic can become pretty complex, and a complex system which is invisible to the end-user is a breeding ground for bugs and performance bottlenecks. So be careful not to overengineer. Some pitfalls you need to watch out for are:

* Inefficient event dispatching eating too many CPU cycles. Make sure you use appropriate data structures for your event queues and receiver lists.
* Event spam. Objects posting unnecessary events or receivers registering for too many events they don't need to know about.
* Insufficient garbage collection. Make sure that objects always get removed from event queues when the object is deleted or no longer needs to listen to that queue for some other reason. It wastes resources in the best case and crashes your server by dereferencing a pointer to a deleted object in the worst case.
* Relying on the order in which events arrive or in which they are processed by other entities. Avoid such dependencies whenever possible. They will lead to nothing but pain and misery in the long run.
* Event loops. Two events from two different entities which keep triggering each other in an infinite loop.

# Answer
> 0 votes
The issue with global variables is that they can be hard to test and reason about as they can be modified everywhere.

To avoid the issue of having them modified everywhere, what may work well is to create an interface to manage this data in order to deal with these lists in a clean way. This could be another class which contained this data privately and did not allow anything outside the class to modify it. This way you know your lists can are only being modified in the ways you explicitly made clear within this one place. You avoid the issue of having a program with changes to the global variables sprawling throughout it.

Nonetheless, for something like a MUD where you want to keep data persistent you can mostly avoid the issue by using a database to store your global data. Still, you‘ll likely want a specified manner to access the data, this way you know where and how it’s being changed, so an interface to help work with your database would work well too!

Hope this helps and good luck with your game!

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


# Question
Title: How can I play and stop a Visual Effect Graph effect through script?
Can anyone please give an example lines of code one could use to play/stop a VFX through C# script.

# Answer
> **Visual Effects API**
>
> https://docs.unity3d.com/2018.3/Documentation/ScriptReference/Experimental.VFX.VisualEffect.html
>
> Stop Send a stop event to all Spawn systems.
>
> Play Sends a stop event to all Spawn systems. If VisualEffect.resetSeedOnPlay is true, this methods recomputes a new random seed for the random value generator and resets internal total time to zero.
>
> **C# API**
>
> https://docs.unity3d.com/Packages/com.unity.visualeffectgraph@6.7/manual/index.html

```
using UnityEngine;
using UnityEngine.Experimental.VFX;

public class VFXTest : MonoBehaviour
{
    public bool IsPlaying = true;
    void Update()
    {
        if(Input.GetKeyDown(KeyCode.Space)){
        IsPlaying = !IsPlaying;
        }

        if(IsPlaying){
        GetComponent<VisualEffect>().Play();
        }else{
        GetComponent<VisualEffect>().Stop();
        }
    }
}

```
> 4 votes

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


title: Detect collision point

text:
# Question
Title: Detect collision point
I'm writing a 3D rigid body physics engine, I am using **OpenGl** for simulation.

Only convex objects are considered.

My question involves how to detect the `point` of collision, so that when I apply a response force, I can also calculate torque.

I have used **SAT** algorithm to detect collision according to this reference,

Everything seems to be work fine , But as i get `SAT` only gives for objects `are they colliding?` as well as `by how much?`, it does NOT give you a reference point at which to apply the response force (and thus calculate torque).

I have looked at

Resource 1

Resource 2

Resource 1

None of them seems to be an answer

# Answer
In 2D rarely you have only one point of contact. I never played with collision resolution in 3D, but i guess this case will be even more rare.

As for the answer, take a look at Erin Catto's (creator of Box2D) GDC 2006 slides (GDC2006 Catto Erin Physics Tutorial). If i remembered it correctly, you should apply force (impulse) to *all vertices* of contact manifold. In 2D it is the overlapping part of two objects (some clipping allowed).

Use SAT to check if two objects are colliding. Then, select one face on one object as reference. Then, remove all points that are not inside the clipping planes (take the face and pull it up, along its normal vector - border of resulting figure is clipping plane). Then, remove all points that are outside of the reference object. Apply the response force to points that are left.

I really recommend looking at Box2D's source code. It's fairly easy to understand, and it's really well written and commented.

Ps. If you used only one point of contact, stacking boxes would be similar to stacking needles on each other... vertically.
> 3 votes

---
Tags: physics, collision-resolution, physics-engine
---