# Question
Title: ECS in MMOs - How to handle IDs for different object types?
Using a DOD approach, what is the typical way to handle dealing with the actual IDs of game objects?

Obviously, each entity has a unique `entity_id` that is generated in-game. And using the component system, the game (server side at least) can determine if the entity is an item, an NPC, a player, etc. My question concerns handling the 'data' ID, as in the ID of the item/npc stored in the database.

The first approach I can think of, is just having one gigantic 'entities' table, with columns that can represent what that entity actually is. In this approach, all entities will have a unique ID (ie, the primary key in the database).

The second approach is to have an Items table, an NPC table, a Vegetation table, etc. But assuming on how one designs the table, there can be an item with an ID of 1, and NPC with an ID of 1, and a Tree with an ID of 1.

Because its an MMO, its inefficient to send all data concerning the entity to the player through a packet. Instead, the client side would have the same data set, so that when one of these pre-defined entites spawns in, the packet can simply tell the ID and location, then the client can look up the ID and construct the entity itself.

Would it then be best to have seperate packet types per entity type? This would be necessary if using the second approach, as there can be entities with the same 'data ID'; IE, a 'NPC spawned' packet, an 'Item spawned' packet. But at the same time, I would also need to include a bit of extra data, the entity\_id generated in-game, so the server can confirm which entity the player attacked/picked up, etc. This of course means slightly more bandwidth usage.

The first approach would simply mean I have a single packet type, 'entity spawned', with the data ID and location. Because the first approach is guaranteed to have 'unique' data IDs, would I even need to send the 'entity\_id', assuming the entity\_id is the same as the data ID?

Sorry if this question isn't too clear. I guess the tldr version is: Whats the best way to design the data tables to hold entities, and whats the best way to design the packets that 'send' that entity to the client?

# Answer
> 3 votes
I would generally not put entity IDs and type IDs into the same number-space. That just leads to confusion about whether a specific ID refers to an entity type or an unique instance of that type.

The entity with the ID 1831347 can be the player with the ID 157 ("Bob"), a mob of type 157 ("Goblin Elite Archer"), an NPC of type 157 ("Potion vendor") or a resource node of type 157 ("Acacia Tree"). The same applies to the entity with the ID 1831348 which appears on the map a second later.

So when you spawn a new entity, then the client doesn't know what kind of entity it is. So the "New entity spawned" packet would include:

* EntityID
* Type
* TypeID
* All the information relevant to an entity of this type (cosmetic options for player-characters, hit points for mobs, resources left for resource nodes...)

You could also go a bit further with the Entity - Component - System philosophy and also expose components in the netcode. In that case the packet would still begin with the entity ID, but instead of having just one type ID it would have a list of components with their component IDs and component-specific data. So for example a player-spawned packet would look like this:

* EntityID
* Position component:
    + x
    + y
* Combatant component:
    + HP
    + MP
* PlayerCharacter component:
    + Name
    + Class
    + Level
* Cosmetics component:
    + hair type and color
    + armor type and color
    + pants type and color
    + ...

While a mob would look like this:

* EntityID
* Position component:
    + x
    + y
* Combatant component:
    + HP
    + MP
* Mob component
    + Mob type ID

Or a resource node would look like this:

* EntityID
* Position component:
    + x
    + y
* Resource Node component
    + Resource type ID
    + amount left

# Answer
> 1 votes
> The first approach I can think of, is just having one gigantic 'entities' table, with columns that can represent what that entity actually is. In this approach, all entities will have a unique ID (ie, the primary key in the database).
>
> The second approach is to have an Items table, an NPC table, a Vegetation table, etc. But assuming on how one designs the table, there can be an item with an ID of 1, and NPC with an ID of 1, and a Tree with an ID of 1.

You could also use a hybrid approach where you leverage the discriminator pattern. This idea is heavily biased around the notion of Discriminated Inheritance from JPA.

The idea is you have a base table, called `entities` that holds several key columns and all attributes that are shared across all entity-types. That table could look something like:

```
ENTITY_ID (PK) | DISCRIMINATOR (INDEXED) | ATTRIB1 | ATTRIB2 | ATTRIB3 | ...

```

The discriminator is basically a special column that designates which join is applicable for that row, such that if the value equates to `NPC`, then that row joined with the `npcs` table based on the `entity_id` would yield a complete snapshot of what that entity is composed of.

Since most queries are often interested in a very specific type of entity given the context, this separation of the in this way could offer great performance.

So you can imagine a query for all items with a given id would yield

```
SELECT e.*, i.*
  FROM entities e, items i
 WHERE e.entity_id = ?
   AND e.discriminator = ?
   AND i.entity_id = e.entity_id

```

> Instead, the client side would have the same data set, so that when one of these pre-defined entites spawns in, the packet can simply tell the ID and location, then the client can look up the ID and construct the entity itself.

I think that depends on the game & context to some degree.

Lets assume the server sends the client some `archetype_id` that the client can use to lookup in its data files and determine exactly how to spawn that entity. The archetype defines the model, components, and other static attributes that describe how the entity should be constructed.

But what happens if the definition of that archetype is wrong under certain conditions? Is it permissible to ask the client to apply a patch to fix such things as a "hotfix" or does company policy mandate that a full build and release cycle be involved for that type of change?

The benefit of the server sending the archetype definition in the packet is that the client is simply a renderer of that information. If a specific entity is being rendered as an Orc but should be an Elf, a quick server hotfix can be made and immediately the client will update how it renders the entities accordingly without ever having to ask the client to update.

# Answer
> 0 votes
Typically what is done is the server creates an entity in game and assigns it a unique ID (you could just start counting from 0). Upon its spawning, the server then sends a packet to its clients, instructing them to create this new entity with all its attributes and with this ID. After that, packets can just use the entity's ID to reference actions that happen to the entity and what not. The clients and server can easily just keep track of data tables as you said. Perhaps one that dynamically grows and is indexed by id, or use a hashmap as entities and their IDs are destroyed. (:

---
Tags: entity-system, mmo, dod
---


# Question
Title: How to find the closest point on multiple colliders within a box?
I need to find the position of the closest point from the bounds of multiple colliders. Right now I'm using `OnTriggerStay` and `collider.ClosestPointOnBounds()`.

This works great for one collider, but as when I add a new collider, it doesn't update.

I've drawn a quick picture to illustrate what I'm trying to say. The black box is the area I want to check in, the red boxes are the colliders with numbers representing the order they entered the black box. The green star is what the code currently says the closest point is, and the blue star is the expected result. The purple star is the position I'm checking for, the blue star should be the closest point to the purple star.

I found this answer to a similar question on answers.unity3d.com. However, I feel like that could be very inefficient because there will be many, probably up to 50 of these box checking scripts running at the same time.

I've also tried using `Physics.BoxCast` but that gave very wild results. The area it was checking was very different to what I wanted, and also what I was visualizing with gizmos. Also, the whole idea of boxcasts are very very confusing so I would rather something else.

**What is the best way to find the closest point on the bounds of multiple colliders within a certain area?**

# Answer
I ended up using `Physics.OverlapBox` and sticking with `ClosestPointOnBounds`. Here is the successful code I used:

```
Collider[] cols = Physics.OverlapBox(position, scale, rotation, layerMask);
Vector3 bestPoint = Vector3.zero;
float closestSqrDistance = Mathf.Infinity;

for (int i = 0; i < cols.Length; i++)
{
    Vector3 pos = cols[i].ClosestPointOnBounds(centerPosition);
    Vector3 direction = pos - centerPosition;
    float sqrDist = direction.sqrMagnitude;

    if (sqrDist < closestSqrDistance)
    {
        closestSqrDistance = sqrDist;
        bestPoint = pos;
    }
}

```
> 0 votes

# Answer
When I needed to do the same, I've used an approximation which worked well. Here is what I do, given two colliders `A` and `B` (any form and complexity, but must be convex):

1. Find the closest point between center of `A` and collider surface of `B` =\> `ptA`.
2. Find closest point between center of `B` and collider surface of `A` =\> `ptB`.
3. Find the middle point between `ptA` & `ptB` =\> `ptM`.
4. Now find the closest point from `ptM` and the both collider surfaces. That's your answer.

Here is pseudo-code:

```
  Vector3 ptA = B.ClosestPoint(A.transform.position);
  Vector3 ptB = A.ClosestPoint(B.transform.position);
  Vector3 ptM = ptA + (ptB - ptA) / 2;
  // Answers:
  Vector3 closestAtA = A.ClosestPoint(ptM);
  Vector3 closestAtB = B.ClosestPoint(ptM);

```

This solution is rather expensive since you do 4 checks, but with simple colliders the performance hit is negligible.

P.S. Don't ask me for the formula proves. This solution was purely intuitive, and I'm not even sure it's geometrically correct. It simply worked for me :)
> 3 votes

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


# Question
Title: Decreasing distance for a Configurable Joint at run-time | Unity
I have written a script that uses ConfigurableJoint to connect a ball to a hing so that it moves in a fixed circular path around the hinge. The problem is that I want to decrease the distance between hinge and ball with time. In other words, I wamt to reduce the radius of circular path on which the ball is moving.

I have created a rough image to demonstrate what I'm trying to do

And below is the code that I am using to create the joint:

```
     joint = gameObject.AddComponent<ConfigurableJoint>();

     joint.anchor = transform.transform.InverseTransformPoint(closestHinge.position);

     joint.xMotion = ConfigurableJointMotion.Locked;
     joint.yMotion = ConfigurableJointMotion.Limited;
     joint.zMotion = ConfigurableJointMotion.Locked;

```

# Answer
> 1 votes
You need to adjust the anchor(s). Note, that they are defined in the local coordinates, relative to the owner object. There are two anchors: `ConfigurableJoint.anchor` and `ConfigurableJoint.connectedAnchor`. You can adjust either one, but if you create the bodies in `autoConfigureConnectedAnchor` mode, then it may be challenging to figure out how to adjust which anchor.

I'd suggest to no rely on the automatic behavior and set both anchors manually when creating the joint. This way you'll know exactly how and what to adjust.

Setup the joint like this:

```
  // Given:
  GameObject hingeObject;
  GameObject ballObject;

  // Then:
  var joint = hingeObject.AddComponent<ConfigurableJoint>();
  joint.autoConfigureConnectedAnchor = false;
  ballObject.transform.LookAt(hingeObject.transform);  // Optional.
  joint.connectedBody = ballObject.GetComponent<Rigidbody>();
  joint.anchor = Vector3.zero;
  var initDistance = Vector3.Distance(hindgeObject.transform.position,  ballObject.transform.position);
  // ATTENTION! It's important to know what axis your joint uses!
  // If doesn't work, try to move initDistance to X or Y.
  joint.connectedAnchor = new Vector3(0, 0, initDistance);

```

Now changing the distance is trivial:

```
  // Don't forget about axis.
  joint.connectedAnchor = new Vector3(0, 0, newDistance);

```

---
Tags: unity, joints
---


# Question
Title: What's the best practice to use the pbo to upload multi textures?
I have a basic model to upload textures as shown in the following picture.

I design this for several reasons:

1. Only the primary thread owns the OpenGL context, so I choose to create buffers, map buffers and unmap buffers in the primary thread.
2. I have many pictures to load and I don't want them to block the primary thread, so I use the subthread to load images and copy the memory.

Here are my questions:

1. Is my model correct?
2. Is my model the best practice?
3. Should I create a PBO for each picture or create two PBO for all pictures and use them in turn?
4. Should I use a shared context?

Thank you for helping me out

# Answer
Why would 3 need to wait on 2? As soon as you know the size of the image you can go ahead and create the buffer. So make sure you know the size early on (by putting it next to the other meta data that led you to load it in the first place or having a max size and using that always) and let the subthread load the image data directly into the PBO.

It is perfectly fine to create a few PBOs and cycle through them.
> 0 votes

---
Tags: opengl, textures, multithreading, efficiency
---


# Question
Title: Interpreting focal length in units of pixels
I am working on a renderer of sorts and I have some fundamental questions. Let's say I have a vector in a 3D virtual world space which is unitless, and I want to project it onto a 2D screen, so I need its pixel position.

My background is in computer vision, so this is how I would model the problem.

`p = K * [R | t] * v`

where `v` is my 3D vector in homogenous coordinates. `R` is a 3x3 rotation matrix, `t` is a 3x1 translation vector, and `K` is a 3x3 "camera matrix". The camera matrix takes the following form

```
f 0 cx
0 f cy
0 0 1

```

`f` is the "focal length" of the virtual camera and `cx, cy` is the "principal point" in pixels (usually the center of the screen).

So, assuming my camera is at the origin (and static), `[R | t]` moves the 3D vector `v` somewhere in front of the camera and I get some `v'`. Now, I want to project 3D vector `v'` onto the screen.

`v' = [x' y' z']^T`

`Kv' = [fx*x'+cx fy*y'+cy z']^T`

Now, dividing by the perspective `z'` I get `p`.

`p = [(fx*x'+cx)/z' (fy*y'+cy)/z' 1]^T`

This certainly works in code and I'm getting favorable results in my renders.

But I fundamentally don't understand what it means to express focal length in terms of pixels. In a real camera it's the physical distance between the imaging plane and the focal point of the lens, but there's no such analog in 3D graphics.

Furthermore, I don't really see why the dimensional analysis works out, and why `p` is indeed in units of pixels.

Thanks for reading!

# Answer
> 1 votes
> In a real camera it's the physical distance between the imaging plane and the focal point of the lens

Well, where's our image plane? The monitor's surface.

Where's the focal point, the place where the rays connected our image plane converge/cross over at a point? The player's eye.

So the distance here relates to the distance of the (idealized) viewer's face from the monitor.

Here the direction of those rays is reversed - instead of light flowing from the focal point onto the image plane where it hits a sensor/film to be detected & recorded in an image, instead light shines *from* the image plane on the monitor *into* the focal point of the viewer's eye. But the trigonometry works out similarly in each case.

Why is it measured in pixels? Because that's the dimension you've chosen to measure your image plane. A monitor with square pixels of a particular resolution also has a particular dimension in real-world space, giving us an exchange rate between image units like pixels and real-world spatial units like cm. So you can think of the distance between the viewer & monitor being measured in cm and *converted* to pixels using assumptions about a typical monitor.

---
Tags: 3d, mathematics, camera, geometry
---


# Question
Title: Godot: What options are there for removing the filtering or anti-aliasing from text
If I were to start making a pixel-art game with the Godot engine, what options do I have for removing the filtering or anti-aliasing from text?

EDIT:

I want to know how to remove the AA from rendered text in a label node.

# Answer
Disabling anti-aliasing in DynamicFont isn't supported in Godot 3.0, but it's possible in 3.1 beta (which also makes it possible to tweak font hinting).

To do so, you need to create a DynamicFont as usual, load a TTF or OTF file into its Font Data property, edit the Font Data resource, set the desired anti-aliasing/hinting settings then save the font data resource as a `.tres` file. (Otherwise, those settings won't be preserved when you exit the editor or launch the project.)
> 1 votes

# Answer
You can customize your image import setting in godot 3.0+. Here is how from the Godot documentation :

Godot Docs 3.0+ : Importing Images

In the basic UI, when you select an image you can change tab to the import settings :

*(Taken from the doc)*

Here you can change several options to customize how your images are imported into Godot.

For pixel art, you can disable **Filter** and **Mimaps** for example.

PS : This solution works for Godot 3.0+, for Godot 2.1+ you can go to the corresponding documentation : Godot Docs 2.1+ : Managing image files. As you are stating you want to start a new game, it is recommended to use the latest (3.0+) version of Godot.
> 3 votes

---
Tags: text, antialiasing, godot, pixel-art
---


# Question
Title: Custom shadow mapping in Unity. Works with preservative Light view but not with Orthographic
So about a week ago I decided to make my own shadow mapping technique in Unity based on my understanding of the whole thing. The entire experience was somewhat successful. I learned a lot and I get to correct a lot of things such as the MVP matrix and the math behind it. One thing though didn't work as planned and I don't know why.

First lets talk about what worked. I wrote a replacement shader that will show the depth of every object based on the Light Position/perspective. Therefore I made a custom Light GameObject that act as a camera/light with that replacement shader attached to it, and I record everything the Light sees into a render texture.

Then I made a second Camera which is basically a child of the main camera, and sees what the main camera see with the exception of the replacement Shader that I attached previously to the Light gameobject. again I recorded everything from the camera to a render texture as well.

After that, I wrote a basic Shader that does a basic light calculation and make a the shadow comparison between the two textures, and determines whether a fragment in a shadow or light. Also, I added a shadow Bias as well to eliminate any artifacts.

```
            struct appdata {
            float4 position : POSITION;
            float3 normal : NORMAL;
            float2 uv : TEXCOORD0;
        };

        struct v2f {
            float4 position : SV_POSITION;
            float2 uv : TEXCOORD0;
            float3 normal : TEXCOORD1;
            float3 worldPos : TEXCOORD2;

        };

        float4 _Tint;
        sampler2D _MainTex;
        sampler2D  SahdowMap_Light, SahdowMap_View;
        float4 _MainTex_ST;
        float4x4 WorldToCamera, WorldToLight;
        float3 _LightDir1;

        v2f VertexProgram(appdata v) {
            v2f i;
            i.position = UnityObjectToClipPos(v.position);
            i.worldPos = mul(unity_ObjectToWorld, v.position);
            i.normal = UnityObjectToWorldNormal(v.normal);
            i.uv = TRANSFORM_TEX(v.uv, _MainTex);
            return i;
        }

        float Shadow_Cal(v2f i, sampler2D DepthMap,float4x4 space) {

            float4 projected2 = mul(space, float4(i.worldPos, 1.0f));
            float2 uv = (-projected2.xy / projected2.w) * 0.5 + 0.5;
            float Shadow = tex2D(DepthMap, uv).r;

            if (uv.y > 1.0)
            Shadow = 0.0;

            return Shadow;
        }

        float4 FragmentProgram (v2f i) : SV_TARGET {

            float LightDepth = Shadow_Cal(i, SahdowMap_Light, WorldToLight);
            float ViewDepth = Shadow_Cal(i, SahdowMap_View, WorldToCamera);
            float bias = max(0.05 * (1.0 - dot(i.normal, _LightDir1)), 0.015);
            float Shadow = LightDepth + bias < ViewDepth ? 0 : 1;

            float4 Texture = tex2D(_MainTex, i.uv);
            float3 lightpos = _LightDir1 - i.worldPos;
            return saturate(dot(lightpos, i.normal)) *_Tint * Texture * Shadow;
        }

```

The problem is when the Light is on perspective, this works perfectly fine as shown above, but when I switch the light camera to Orthographic this happen:

I tried many different things to fix it but I failed. I would love your insight in this whole thing, your thought, solution or even a suggestions.

You are free to download the whole project as a package here Download

Special thanks to DMGregory.

# Answer
Ok I have figured it out. This is what the fragment shader should look like:

```
            float4 FragmentProgram (v2f i) : SV_TARGET {

            // transform a point from world space to uv coord to sample the depth map from the light perspective
            float4 projected = mul(WorldToLight, float4(i.worldPos, 1.0f));
            float2 uv_Light = (projected.xy / projected.w) * 0.5 + 0.5;
            float LightDepth = tex2D(SahdowMap_Light, uv_Light).r;
            if (uv_Light.y > 1.0)
            LightDepth = 1.0;

            // transform a point from world space to uv coord to sample the depth map from the view perspective
            float4 projected2 = mul(WorldToCamera, float4(i.worldPos, 1.0f));
            float2 uv_View = (-projected2.xy / projected2.w) * 0.5 + 0.5;
            float ViewDepth = tex2D(SahdowMap_View, uv_View).r;

            float bias = max(0.05 * (1.0 - dot(i.normal, _LightDir1)), 0.005);
            float Shadow = LightDepth + bias < ViewDepth ? 0 : 1;

            float4 Texture = tex2D(_MainTex, i.uv);
            float3 lightpos = _LightDir1 - i.worldPos;
            return saturate(dot(lightpos, i.normal)) *_Tint * Texture * Shadow;
        }

```

it turns out if the Light camera mode is on Orthographic, uv\_Light should be

```
                float2 uv_Light = (projected.xy / projected.w) * 0.5 + 0.5;

```

but in a case we are using perspective, uv\_Light should look like this:

```
                float2 uv_Light = (-projected.xy / projected.w) * 0.5 + 0.5;

```

I'm in the process of trying to figure out the exact reason behind this.

Spotlight Shadow

Directional Light shadow
> 0 votes

---
Tags: unity, unityscript, shadow-mapping, shadowmap
---


# Question
Title: "Failed to fetch the following dependencies: com.google.games:gpgs-plugin-support:0.9.50 " when force resolve GooglePlayGamesPlugin-0.9.50
Ive been stuck with this problem for the last few days and really need some assistance.

Iv created an android app and im trying to set up google play services as i want to use the leader board etc..

I downloaded and imported the latest plugin "GooglePlayGamesPlugin-0.9.50 " no errors during the import.

I then go to assests/ play service resolver/android/force resolve and run that.

After running I end up with the following error:

---

---

Resolution failed

Failed to fetch the following dependencies:

com.google.games:gpgs-plugin-support:0.9.50

UnityEngine.Debug:LogError(Object)

Google.Logger:Log(String, LogLevel)

GooglePlayServices.PlayServicesResolver:Log(String, LogLevel)

GooglePlayServices.ResolverVer1\_1:LogMissingDependenciesError(List\`1)

GooglePlayServices.c\_AnonStorey18:\<\>m\_26(List\`1)

GooglePlayServices.c\_AnonStorey14:\<\>m\_1F(Result)

GooglePlayServices.c\_AnonStorey15:\<\>m\_28()

GooglePlayServices.PlayServicesResolver:PumpUpdateQueue()

UnityEditor.EditorApplication:Internal\_CallUpdateFunctions()

---

---

If i ignore the error and complie the app it works fine but does not connect to the google service. I can publish and use the app without crashes etc but i cant log on to google or view leaderboards.

Can any one assist me as im really desperate to get this up and running.

Im using : unity 2017.1.1f1 personal 64bit

Windows 10 64 bit

jdk1.8.0\_162

# Answer
> 1 votes
There seems to be an issue with the resolver, I "solved" this by disabling auto resolve in the resolver and having android studio download the packages from me then copying the aar files to the Android directory in my unity project.

not the cleanest way but it worked

they get downloaded to `sdk\extras\google\m2repository\com\google\android\gms\` see which ones you need and copy the aar file into your android project

# Answer
> 1 votes
Open you GooglePlayGamesPluginDependencies.xml file and make sure that path mentioned for `"com.google.games:gpgs-plugin-support:x.x.xx"` exists and is valid.

---
Tags: unity, android, google-play-services
---


# Question
Title: Should I wrap a template function with another template function, or...?
I'm currently making an Entity System, using C++, and I've questioned myself about how I should interface some methods. Specifically in my Entity and ComponentManager classes.

The ComponentManager, manages all components for all entities in a specific world. It can add/remove/determine if a Component exists, etc. Now to retrieve a component, I was thinking of using a template function, that way it looks neater and it doesn't have as many casts (outside the method). But then I want quick access to components through an Entity object. e.g.

```
entity.getComponent<VelocityComponent>().x = 30;

```

(and yes I know an Entity is just an ID, that's why I have my components in the ComponentManager class, and each Entity is represented by an ID).

i.e.

ComponentManager's get function: (Components are stored as a 2d array, with the first element being the ID of an entity and the 2nd element being the ID of a component's class type)

```
template <typename Comp> // Comp = Component
Comp* getComponent(Entity& e)
{
    return (Comp*)_components[e.getId()][Comp::GetClass().getId()];
}

```

And the Entity's get function:

```
template <typename Comp>
Comp* getComponent()
{
      return getWorld().getComponentManager().getComponent<Comp>(*this);
}

```

So if I was to use template functions I would just have 2 duplicates of template functions. Now of course, this goes the same for adding components to an Entity. So basically, *is it a good idea to wrap a template function with another template function*?

I can, alternatively make the the methods in the Entity system templates and make the methods in the component managers non-template functions, i.e.

```
Component* ComponentManager::getComponent(Entity& e, const Component::Class& componentClassType) const
{
     return _components[e.getId()][componentClassType.getId()];
}

```

I'm confused on what I should do.:

# Answer
> 1 votes
There's nothing wrong with calling a templated routine within another templated routine, but you may want to just have one function that will give you a component instance from an entity ID so the interface is small and consistent (why have two routines that do the same thing?)

It's probably worth noting though that it's not safe to do things like this:

```
entity.getComponent<VelocityComponent>().x = 30;

```

unless all entities are guaranteed to have an instance of all components. You probably want to design your interface so that users do something like this.

```
VelocityComponent* velocity = entity.getComponent<VelocityComponent>();
if(velocity)
{
    // only do the lookup once and make sure this component exists.
    velocity->x = 30;
}

```

The component lookup that you're using now is pretty fast, but you may need to change it in the future to avoid the (numEntities * numComponentTypes) storage requirement.

# Answer
> -2 votes
yes its fine to do that. You have just discovered compile-time polymorphism.

---
Tags: c++, software-engineering, entity-system
---


# Question
Title: XNA 4.0 How to change GraphicsDevice Default DepthStencilState Value
I want to change one of the deafult values of my GraphicsDevice to that:

```
GraphicsDevice.DepthStencilState.DepthBufferEnable = true;

```

But I know only to change it on runtime in the Draw method by putting this code (which means it's changing the value everytime that the compiler is running the draw method!):

```
DepthStencilState state = new DepthStencilState();
state.DepthBufferEnable = true;
GraphicsDevice.DepthStencilState = state;

```

Does someone know how to change it once in an officient way?

# Answer
> 0 votes
Unless you have something that 'resets' the `DepthStencilState` you only have to set it once. For example in your `LoadContent` method (because the `GraphicsDevice` should be initialized there).

A typical method that resets some of these states is using the `SpriteBatch` which uses its own set of states to draw things. So in the event you mix the spriteBatch to draw 2D with primitives/models in 3D there is nothing you can do about that, because these methods require different states to function.

It then best to set the correct states as efficient as possible. So instead of making the DepthState everytime, create a global variable for it so you don't have to recreate it every draw call. The GraphicsDevice.DepthStencilState checks if the new value equals to the one that is already set, to prevent overhead.

---
Tags: c#, xna, graphics, xna-4.0, depth-buffer
---


# Question
Title: If statements seem to act as though the condition is always true
I have other scripts in the same project using boolean if statements that work fine, but I've tried multiple methods of testing if the if statements below are working and none of them worked!

I don't really know what to ask because I don't know whats going on. I've tried placing theae statements in Update and Start, and in both instances the if statement completely ignored the check and just executed the contents of the block as though the check evaluated to true.

```
void OnTriggerEnter(Collider other) {
    if(other.gameObject.CompareTag("Player")); {
        working = true;
    }

    Extremity = false;
    if(Extremity); {
        Instantiate(Cannon, transform.position, transform.rotation);
        Extremity = !true;
    }
}

```

The false statement is only in there to show that even when the bool is set to false immediately before the check, it still runs the Instantiate method inside as though it were true.

# Answer
> 5 votes
Remove the semicolon at the end of your if statements.

That semicolon tells the compiler "I'm done with this" and whatever comes next is a new, unrelated statement

So this (note semicolon at the end of the if):

```
if (condition);
{
    DoStuff();
}

```

is the same as

```
if (condition)
{
    ;  // Empty statement, do nothing.
}

{ // New block, unrelated to the prior if.
    DoStuff();
}

```

so it says "check `condition`, but do nothing with the result. Then `DoStuff()`"

But this (note no semicolon before the opening braces):

```
if (condition)
{
    DoStuff();
}

```

Says "check `condition`, and only if it's `true` should you execute the stuff in the braces and `DoStuff()`"

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


title: Sprite won't change with direction

text:
# Question
Title: Sprite won't change with direction
I am making a top down Pacman game. I have two sprites: one for facing up and one for facing left.

When I press W, the sprite showing is still the one for when Pacman is moving left, but I want to see the up sprite instead.

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

public class pacman : MonoBehaviour
{
    public int speed;
    Vector2 dest;
    public Transform[] points;
    // Start is called before the first frame update
    void Start()
    {
        dest = transform.position;
        speed = 25;

    }

    // Update is called once per frame
    void FixedUpdate()
    {
        //Vector2 p = Vector2.MoveTowards(transform.position, dest, speed);
       // GetComponent<Rigidbody2D>().MovePosition(p);

        // Check for Input if not moving
        if (Input.GetKey("w"))
            transform.position = Vector3.MoveTowards(transform.position, points[0].position, speed * Time.deltaTime);

        gameObject.GetComponent<SpriteRenderer>().sprite = GameObject.Find("up").GetComponent<SpriteRenderer>().sprite;

        if (Input.GetKey("d"))
            transform.position = Vector3.MoveTowards(transform.position, points[2].position, speed * Time.deltaTime);

        if (Input.GetKey("s"))
            transform.position = Vector3.MoveTowards(transform.position, points[1].position, speed * Time.deltaTime);

        if (Input.GetKey("a"))
            transform.position = Vector3.MoveTowards(transform.position, points[3].position, speed * Time.deltaTime);

        gameObject.GetComponent<SpriteRenderer>().sprite = GameObject.Find("left").GetComponent<SpriteRenderer>().sprite;
    }
}

```

# Answer
You need to use curly braces { } to group together statements that you want to execute only when the condition of the `if` statement is met.

```
if (condition)
   DoActionA();

DoActionB();

```

This says "Do action A only if `condition` is `true`, but always do action B no matter what"

```
if (condition)
{
    DoActionA();
    DoActionB();
}

```

This instead says "Do action A then action B only if `condition` is `true`, otherwise skip them both"

So, specific fixes:

1. Don't call GetComponent every frame. That's just wasteful. Instead, call it during start-up and cache the result.
2. Put the sprite assignments inside braces to bundle them with the `if` statements that should control them.

Like so:

```
// You could just make these public variables and assign the sprite in the inspector.
Sprite upSprite;
Sprite leftSprite;

SpriteRenderer myRenderer;

void Start()
{
    dest = transform.position;
    speed = 25;

    // Cache our sprites & renderer.
    myRenderer = GetComponent<SpriteRenderer>();
    upSprite = GameObject.Find("up").GetComponent<SpriteRenderer>().sprite;
    leftSprite = GameObject.Find("left").GetComponent<SpriteRenderer>().sprite;
}

void FixedUpdate()
{
    if (Input.GetKey("w")) {
        transform.position = Vector3.MoveTowards(transform.position, points[0].position, speed * Time.deltaTime);
        myRenderer.sprite = upSprite;
    }
    if...

```
> 1 votes

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


# Question
Title: In Unity C#, how can I change weapon a few frames later?
I have this Input code to change weapon:

```
if (d_left)
    {
        if (!p_d_left)
        {
            states.inventoryManager.ChangeWeaponToNextWeapon(true);
            p_d_left = true;
        }
    }
    if (d_right)
    {
        if (!p_d_right)
        {
            states.inventoryManager.ChangeWeaponToNextWeapon(false);
            p_d_right = true;
        }

```

And in the InventoryManager I have the weapon changed by this:

```
public void ChangeWeaponToNextWeapon(bool isLeft)
{
    if (isLeft)
    {
        if (l_index < r_l_weapons.Count - 1)
            l_index++;
        else
            l_index = 0;
        EquipWeapon(r_l_weapons[l_index], true);
    }
    else
    {
        if (r_index < r_r_weapons.Count - 1)
            r_index++;
        else
            r_index = 0;

        EquipWeapon(r_r_weapons[r_index]);
    }

    states.actionManager.UpdateActionsOneHanded();
}

```

Then equip the weapon along with animation and other stuff :

```
public void EquipWeapon(RuntimeWeapon w, bool isLeft = false)
{
    if (isLeft)
    {
        if (leftHandWeapon != null)
        {
            leftHandWeapon.weaponModel.SetActive(false);
        }

        leftHandWeapon = w;
    }
    else
    {
        if (rightHandWeapon != null)
        {
            rightHandWeapon.weaponModel.SetActive(false);
        }

        rightHandWeapon = w;
    }

    string targetIdle = w.instance.oh_idle;
    targetIdle += (isLeft) ? "_l" : "_r";
    states.anim.SetBool(StaticStrings.mirror, isLeft);
    states.anim.Play(StaticStrings.changeWeapon);
    states.anim.Play(targetIdle);

    UI.Slot uiSlot = UI.Slot.singleton;
    uiSlot.UpdateSlot(
        (isLeft) ?
        UI.QSlotType.lh : UI.QSlotType.rh, w.instance.icon);

    w.weaponModel.SetActive(true);
}

```

But the problem is the weapon changes immediately after pressing the button. How can I switch my weapon a few frames later while playing the animation?

# Answer
I assume you don't really need to postpone the weapon change for some frames. Instead, you need to postpone the change until *some condition is met*. If this is a right assumption, then simply use a coroutine to check the condition and do the change accordingly. E.g. if you want to change the weapon when all the animations ended, here is you coroutine function:

```
IEnumerator WaitAndChangeWeapon(Animation anim, String targetIdle,
                                UI.Slot uiSlot, UI.QSlotType slotType, RuntimeWeapon w) {
  // Wait till the animations complete.
  while (anim.IsPlaying(StaticStrings.changeWeapon) || anim.IsPlaying(targetIdle)) {
    yield return null;  // Skip this frame.
  }

  // Update the weapon.
  uiSlot.UpdateSlot(slotType, w.instance.icon);
  w.weaponModel.SetActive(true);
}

```

Now, in your `EquipWeapon` method instead of updating the slot and activating the model, simply do:

```
// Given your module is a descendant of MonoBehaviour.
StartCoroutine(WaitAndChangeWeapon(states.anim, targetIdle, UI.Slot.singleton,
                                   (isLeft) ? UI.QSlotType.lh : UI.QSlotType.rh, w));

```

There are caveats, though. Since the execution is delayed, the state of the objects can change at the moment of the animations end. You will need to handle it to ensure the game doesn't crash if, for example, the owner of inventory is killed before the animation ends :)
> 1 votes

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


# Question
Title: Inflating a balloon while the user touches & holds the screen
I'm trying to create a simple balloon which will enlarge as the user touches and holds the screen.

So I wrote something like this:

```
while ( Input.GetMouseButtonDown(0) ) {
        transform.localScale += new Vector3(1, 1, 1);
        yield return new WaitForSeconds(1);
}

```

It causes a compiler an error:

> The body of 'enlargeBalloon.Update()' cannot be an iterator block because 'void' is not an iterator interface type

How can I fix this?

# Answer
It looks like you're trying to use Update as a Coroutine - a procedure that can suspend itself midway-through and pass control back to the game loop to keep updating/rendering frames, then resume where it left off later.

You can tell something is a Coroutine if it uses the `yield return` construct to pause itself like this anywhere.

To make a method a coroutine, you need to change its signature from:

```
void MethodName() {
    ...

```

to:

```
IEnumerator MethodName() {
    ...

```

The reason is that under the hood, running a Coroutine is actually creating an object called an iterator that implements the IEnumerator interface — something we can call `MoveNext()` on to make it step through a sequence of values/actions. That's how the engine pumps the coroutine each time it needs to be resumed. Instead of returning nothing (`void`), calling the method returns this new iterator object, so the return type needs to match this.

---

Now, there's a bit of a danger in calling Update as a coroutine: Update is already called every frame!

So if some of those calls don't end in the same frame, but continue/suspend for some time, they could pile up very quickly. In this example, if the player rapidly tapped their mouse button for a second at 60fps, you could have increased your size 30 times over and have 30 copies of the coroutine waiting to resume.

Fortunately, the engine knows what a disaster this would be, and won't let us do it. Many MonoBehaviour messages are allowed to be marked as IEnumerator and called as coroutines, but Update is not one of them.

MonoBehaviour messages that can't be Coroutines include:

* Initialization: `Awake`, `OnEnable`
* Core update loop: `Update`, `LateUpdate`, `FixedUpdate`, `OnGUI`
* Shutdown: `OnDisable`, `OnDestroy` (Obviously, after calling one of these, the object is likely not eligible to keep running a Coroutine the next frame)

---

So, what can we do instead?

Well, since Update is already running every frame, we don't need a `while` loop to keep iterating. We can do that with the game loop itself, changing our `while` to a simple `if`:

```
public float inflationSpeed = 1f;

void Update() {
    if (Input.GetMouseButton(0)) {
        Vector3 newScale = transform.localScale;
        // Use deltaTime to grow smoothly, a little each frame.
        newScale += inflationSpeed * Time.deltaTime * Vector3.one;
        transform.localScale = newScale;
    }
}

```

Or, if you really want to do it in Coroutine style, growing in steps of 1 every second rather than smoothly every frame, you can do it like so:

```
public Vector3 growthPerStap = new Vector3(1,1,1);
public float stepDuration = 1f;

Coroutine inflation;

// Define a Coroutine method that inflates periodically.
IEnumerator Inflate() {
    while(true) {
        transform.localScale += growthPerStep;
        yield return new WaitForSeconds(stepDuration);
    }
}

// Check input each frame and stop/start the coroutine as needed.
void Update() {
    // Stop the coroutine if it's running and the mouse button is released.
    if(inflation != null && Input.GetMouseButtonUp(0)) {
        StopCoroutine(inflation);
        inflation = null;
    }

    // Start the coroutine if it's not running and the mouse button is pressed.
    if(inflation == null && Input.GetMouseButton(0))
        inflation = StartCoroutine(inflation);
}

```
> 1 votes

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


# Question
Title: Using Rigidbody.AddForce() twice seems to interfere with logic
So I created a magnetic effect, where objects are "sucked" into my player. It works great.

Now I want those same objects to get a little Impulse force when they spawn. This has somehow reversed my magnetic effect? The objects are now pushed away from the player...

All I did was add this Line in `Start()`:

```
_rb.AddForce(_forwardThrust, _upThrust, _forwardThrust, ForceMode.Impulse);

```

Full Script here:

```
public class RandomMagneticForce : MonoBehaviour
{
    private bool _inside;
    private Transform _magnet;
    private Rigidbody _rb;
    private SphereCollider _sphere;
    float radius = 5f;
    [SerializeField]
    private float _delay;
    [SerializeField]
    private float _force = 70;
    [SerializeField]
    private float _upThrust, _forwardThrust;

    void Start()
    {
        _magnet = GameManager.instance.ActivePlayer.gameObject.transform;
        _rb = GetComponent<Rigidbody>();
        _sphere = GetComponent<SphereCollider>();
        _inside = false;
        _rb.AddForce(Random.Range(-_forwardThrust, _forwardThrust), _upThrust, Random.Range(-_forwardThrust, _forwardThrust), ForceMode.Impulse);
    }

    void OnTriggerEnter(Collider other)
    {
        if (other.gameObject.CompareTag(Constants.TAG_PLAYER))
        {
            _inside = true;
        }
    }
    void OnTriggerExit(Collider other)
    {
        if (other.gameObject.CompareTag(Constants.TAG_PLAYER))
        {
            _inside = false;
        }
    }

    private void Update()
    {
        if (_delay > 0)
            _delay -= Time.deltaTime;

        if (_inside)
        {
            if (_delay <= 0)
            {
                Vector3 magnetField = _magnet.position - transform.position;
                float index = (radius - magnetField.magnitude) / radius;
                _rb.AddForce(_force * magnetField * index);
            }
        }
    }
}

```

# Answer
> 2 votes
Here's what your attraction force's signed magnitude looks like as we vary the distance to the magnet, using positive to show force toward the magnet and negative for force away:

So it looks like you might just be missing a `Max` or a check to ensure your `index` (really an intensity) doesn't go below zero and turn your attractive force into a repulsive force for objects outside of `radius`:

```
Vector3 magnetField = _magnet.position - transform.position;
float index = (radius - magnetField.magnitude) / radius;
if(index > 0f)
    _rb.AddForce(_force * magnetField * index);

```

If you were previously spawning these objects only inside the radius of 5, you would have seen only the attractive part of this curve. Now, by adding some initial movement, they sometimes drift outside the radius into the repulsion field, making it look like the new `AddForce` call changed the behaviour of the attraction when it really just revealed behaviour that was already there.

---
Tags: unity
---


# Question
Title: Canvas Infinite Map: How to have reappearing objects at static X,Y even when looping
I made a html canvas example of an infinite scrolling map with objects in static places. As you can see in the Fiddle below, when you move left with the Arrow Keys, you can see that the map does not show the other ends tiles and the objects do not appear either.

After the position is changed to the opposite edge of the map, the tiles appear and the object from that side of the map appears.

I made this Fiddle by modifying another Fiddle but it gets my point across. https://jsfiddle.net/n8d5kbau/

Is there any way to duplicate the one edge of the map or am I approaching this the right way? I have been searching for this all over the place, finally deciding to ask here.

Thanks in advance.

# Answer
To ensure you don't see popping in a wraparound map, one of the following needs to be true (assuming your viewport and all objects are smaller than the world's wrapping interval):

1. `Wrapping Interval - Object Size > Viewport Size`

This way, the object disappears off one side of the screen completely before being re-positioned to the far side, and the pop is completely invisible.

This seems to already work for your white square. Chopping your checkerboard up into quadrants might be enough to satisfy this constraint.
2. You draw up to 4 copies of the object at a time, at the corners of a square of size `Wrapping Interval`

This way, as one copy begins to slide off the left side of the view, a new copy starts to slide in from the right, and appears to exist continuously rather than popping in only once the left-hand copy disappears completely.

You can recycle these same 4 copies, leapfrogging the left copy over to become the new right copy as the view continues sliding rightward.
> 1 votes

---
Tags: html5, game-loop, html-canvas
---


# Question
Title: Multiple errors on brand new C++ project
I've just started a brand new project and created a created a new C++ Character class. However Visual Studio 2017 shows 140 errors. The project still builds fine, however the syntax highlighting and errors are very intrusive.

Here are some examples of the errors:

on the BaseCharacter.cpp class I just created:
`class "UObject" has no member "BeginPlay"`
`class "UObject" has no member "Tick"`
`class "UObject" has no member "SetUpPlayerInputComponent"`

on multiple '.h' files:
`this declaration has no storage class or type specifier`

for all '\*.generated.h' files:
`cannot open source file "[ClassName].generated.h"`

Is this a problem with my intellisence or the project itself? I haven't changed any of the code that was generated by Unreal.

# Answer
If you go to your Unreal Engine launcher and click the drop down arrow next to your installed engine version, one of the check boxes you could enable for your UE4 build is the "C++ Symbols". If you check that box, it'll download a lot of stuff but for situations like this it'll really help out.

There are many tabs at the bottom of the Visual Studio window when you try to compile and build the project. One of them is the "Call Stack", and if you have those C++ Symbols installed then it will give you all sorts of extra details about what exactly is going wrong so that you can see exactly what the problem is.

As for the actual error message you're getting, it looks like your `BaseCharacter.cpp` file has a `: public UObject` as it's parent for some reason near the top of the file? If so, you might want to replace that with `: public ABaseCharacter` and then it should work fine.

Here's an example of how that line should look in the `.h` header file:

```
class ATP_FirstPersonCharacter : public ACharacter

```
> 1 votes

# Answer
This has been a problem in the Unreal world for a while now. However, recently things have been getting a little better. This solution worked for me.

> Workaround:
> 1. Open the project solution
> 2. Inside Visual Studio go to Project -\> Properties
> 3. In configuration select "All Configurations"
> 4. In the Configuration Properties tree select NMake
> 5. Click the dropdown for the "Include Search Path" item and select "Edit..."
> 6. Click the "New Line" button at the top right of the window and add this path "..\Build\Win64\UE4Editor\Inc\YourModuleName" without the quotes.
> 7. Repeat step 6 for each c++ module in your project

However there are still sometimes when errors show up and the code compiles just fine. Its no where near how bad it was before though. Another option, that I'm not fond of is disabling intellisense completely but I don't like that option as it slows down development a lot.
> 1 votes

---
Tags: unreal-4, unreal, visual-studio
---


title: What is the purpose of glScissor?

text:
# Question
Title: What is the purpose of glScissor?
I know that it is more efficient than stencil test, but am I right assuming that the same functionality could be achieved using projection transformations with viewport?

# Answer
> 60 votes
They are more complementary than alternatives to each other. You almost always want to set the scissor rectangle to the same values as the viewport.

glViewport() specifies a transformation from normalized projection space to screen space. Polygons are clipped to the edge of projection space, but other draw operations like glClear() are not. So, you use glViewport() to determine the location and size of the screen space viewport region, but the rasterizer can still occasionally render pixels outside that region.

That's where scissor in comes in. glScissor() defines a screen space rectangle beyond which *nothing* is drawn (if the scissor test is enabled).

So for example, the following code will clear the whole screen, even though the viewport is set to a small portion of the larger window:

```
glViewport(200,200,100,100);
glClear(GL_COLOR_BUFFER_BIT);

```

Adding glScissor() and enabling the scissor test (which is disabled by default) restricts the clear.

```
glViewport(200,200,100,100);
glScissor(200,200,100,100);
glEnable(GL_SCISSOR_TEST);
glClear(GL_COLOR_BUFFER_BIT);

```

Occasionally you come across an implementation that automatically scissors to the viewport region, but that violates the GL specification.

Beyond that, the scissor rectangle can be used to temporarily restrict drawing to a sub-rectangle of the viewport, for special effects, UI elements, etc.

# Answer
> 21 votes
I like this kind of things explained visually.

In OnpenGL we have 2D coordinates that go from -1 to +1 for both the X and Y axis.

Then this image needs to be mapped to window coordinates.

Let's imagine that we have window that has a dark color as back ground, and we have white as the clear color.

The most common case is having viewport and scissor cover the whole screen.

But we can set them to be a smaller region of the screen.

These regions can be different. In the following example the viewport covers the whole screen, while scissor is the smaller box.

And in this last case scissor covers the whole screen, while viewport is the smaller box. Notice that `glClear` affects the whole screen, since that's determined by scissor region.

# Answer
> 16 votes
They operate at two completely different parts of the graphics pipeline.

glViewport actually specifies a transformation, and it's a transformation that happens after the vertex shader but before the fragment shader. If it helps to see where it conceptually fits in, think in terms of it being part of the transforms that are used to get your vertex data from world space to screen space (i.e. it's relatively closely related to modelview and projection).

Scissor test happens after the fragment shader, together with all of the other per-fragment operations that happen at that time, such as blending, depth/stencil, etc. When a fragment is tested by the scissor test, it has therefore already been through the viewport transformation.

Yes, scissor test can be faster can stencil because it's a simple accept/reject based on a fragment's screen space coords, whereas stencil needs to compare with the current value in the stencil buffer, possibly increment or decrement that current value, also take into account the results of the depth test, and so on.

So putting all of that together you can see why scissor test exists. It gives you the ability to constrain per-fragment ops to a rectangular portion of the screen, but without actually modifying the current viewport transform.

# Answer
> 6 votes
glScissors accomplishes clipping of geometry against a portion of the screen.

You would want this, for example, if you were rendering a GUI box that had smoothly scrolling text inside it. You want to clip all geometry outside the portion of the screen covered the by the GUI, but keep partial text or polygons which are still inside.

glViewport maps the projection coordinates to device coordinates, but does not clip.

glStencil is used to mask individual pixels in more complex patterns, such as irregular shapes. Thus, glScissors is faster.

# Answer
> 3 votes
glScissor is more simple than projection transformations with viewport.

glScissor test specifies what pixels to be changed when rendering, while glViewport changes how gl should map from device coordinates to window coordinates.

Then what's the difference with setting the viewport to the rectangle you want to render to and adjusting the projection matrix to undo the scaling done by the viewport.

---
Tags: opengl, opengl-es
---


title: Setting shader by script?

text:
# Question
Title: Setting shader by script?
I make s shader file and drop it on object with material. I wrote this script to run shader when press Space button. All is good except that script not load shader when run the game !! I have to do it manually only !

```
public Material _shader;
public float timer = 0;

// Start is called before the first frame update
void Start()
{

    _shader = gameObject.GetComponent<Material>(); // Not setting shader !!
    _shader.SetFloat("Vector1_F92326F1", timer);

}

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

    if (Input.GetKeyDown(KeyCode.Space))
    {
        timer += 0.1f;
        _shader.SetFloat("Vector1_F92326F1", timer);
    }

}

```

# Answer
> 2 votes
A Material is not a Component, so you can't get it with GetComponent.

Did you mean to ask the attached Renderer component for (a local copy of) the material it's using to render?

```
 Material material = GetComponent<Renderer>().material;

```

Don't forget to Destroy() this copy of the material when you're done with it, or it leaves extra garbage for the engine to clean up during scene loads.

Also, watch out that a Material and a Shader are two different things. A Shader is the GPU code — you might draw lots of different materials with one set of GPU code. A Material is a bundle containing a reference to a shader together with the collection of parameters (textures, colours, intensities etc) that describe its its unique look.

---
Tags: unity, shaders
---


title: cutting part of object

text:
# Question
Title: cutting part of object
How to cut part of the object if it is inside a specific area? like showed on attached image.

PS

Looks like stencil should be used, but I am not really sure how to do it.

# Answer
> -2 votes
This was achieved using stencil. case closed.

# Answer
> 0 votes
If the area is a rectangle you can use a scissor rectangle. It sets that only part of the viewport gets drawn while everything outside of that is not drawn.

---
Tags: opengl, stencil
---


# Question
Title: Server-side real time position calculation based on destination position
What I want to achieve is to calculate the real object position based on its speed and a destination position. In my server, I have a `MapInstance` that have a list of `MapLayer` that have `MapRegion`s.

To resume we have:

* 1 `MapInstance`
    + N `MapLayer`s
    + X `MapRegion`s

Each `MapInstance` will update in an asynchronous task all his map layers and the common object such as NPCs and the `MapLayer` will update his regions of entities (monsters/items).

On the client side, when I click somewhere on the map, it sends a packet to the server with the destination position. Then, on the server-side I receive the position and set the `entity.Movable.DestinationPosition` property.

As I said earlier, each map instance are updated in an asynchronous task and updates the map layers and common entities. My problem is, my realtime position calculation formula is wrong somewhere, and I can't find where.

To understand the problem, there is some inputs:

* Entity speed: 0.08 (8%)
* `Position` and `DestinationPosition` are `Vector3` (class) instance, where `X`, `Y` and `Z` are properties.

This is my code:

```
public void StartUpdateTask(int delay)
{
    Task.Run(async () =>
    {
        const double FrameRatePerSeconds = 0.66666f;
        double previousTime = Environment.TickCount;

        while (true)
        {
            if (this._cancellationToken.IsCancellationRequested)
                break;

            double currentTime = Environment.TickCount;
            double deltaTime = currentTime - previousTime;
            previousTime = currentTime;

            this.GameTime = (deltaTime * FrameRatePerSeconds) / 1000f;

            lock (SyncRoot)
            {
                foreach (var entity in this.Entities)
                    Walk(entity);

                foreach (var mapLayer in this._layers)
                     mapLayer.Update();
            }

            await Task.Delay(delay, this._cancellationToken).ConfigureAwait(false);
        }
    }, this._cancellationToken);
}

```

`mapLayer.Update()` method:

```
public override void Update()
{
    this.GameTime = this.Parent.GameTime;

    foreach (var entity in this.Entities)
        Walk(entity);

    foreach (var region in this._regions)
    {
        if (region.IsActive && region is IMapRespawnRegion respawnRegion)
        {
            foreach (var entity in respawnRegion.Entities)
            {
                Walk(entity);
            }
        }
    }
}

```

And the calculation formula:

```
private void Walk(IMovableEntity entity)
{
    if (entity.MovableComponent.DestinationPosition.IsZero())
        return;

    if (entity.MovableComponent.DestinationPosition.IsInCircle(entity.Object.Position, 0.1f))
    {
        entity.MovableComponent.HasArrived = true;
        entity.MovableComponent.DestinationPosition.Reset();
    }
    else
    {
        entity.MovableComponent.HasArrived = false;
        double entitySpeed = entity.MovableComponent.Speed * entity.MovableComponent.SpeedFactor;
        double speed = ((entitySpeed * 100f) * entity.Context.GameTime);
        float distanceX = entity.MovableComponent.DestinationPosition.X - entity.Object.Position.X;
        float distanceZ = entity.MovableComponent.DestinationPosition.Z - entity.Object.Position.Z;
        double distance = Math.Sqrt(distanceX * distanceX + distanceZ * distanceZ);

        // Normalize
        double deltaX = distanceX / distance;
        double deltaZ = distanceZ / distance;
        double offsetX = deltaX * speed;
        double offsetZ = deltaZ * speed;

        if (Math.Abs(offsetX) > Math.Abs(distanceX))
            offsetX = distanceX;
        if (Math.Abs(offsetZ) > Math.Abs(distanceZ))
            offsetZ = distanceZ;

        entity.Object.Position.X += (float)offsetX;
        entity.Object.Position.Z += (float)offsetZ;
    }
}

```

With this current formula, my players and monsters arrive to destination between 1-2 seconds sooner on the server side compared to the client-side... Do you have any idea what I'm doing wrong ? Appriciate if someone could guide me and explain me how to solve my problem. :-)

Thank you

# Answer
> 0 votes
What is the FrameRatePerSeconds supposed to accomplish in the main task update? Game time is independent of the framerate refresh cycle and your server most probably doesn't even have display frames in the first place. It looks like every update you're multiplying in the framerate, unless I read that wrong...

---
Tags: c#, multiplayer, mmo, server
---


# Question
Title: Should components in Entity Component System pattern have logic?
Is often read that in entity component system pattern we should treat components just as a passive data structure with no logic at all, this way we follow to a data oriented design approach with efficient usage of cache memory and gain performance.

I was developing a simple game using this rule and when the game was getting bigger I start facing some serious code smells such as repeated code in systems, let's suppose its a shooter to illustrate an example. In this shooter I had bullets being fired so I created a BulletComponent and a BulletSystem that handles when it collides and make some damage and if don't collide with anything the bullet dissapear in five seconds. Then I wanted some explosives so I created the ExplosiveComponent and ExplosionSystem, once the explosive is placed it explodes in ten seconds. At this point we can notice the first repeated code between systems then we can make an abstraction and we create a DurationComponent and a DurationSystem so the bullet and the explosive contains it with the time it should last.Then I realized that when the explosive should explode I want to create some particle effect in the area so this abstraction is no longer valid as I want to perform differents actions when time runs out, but if I do as at the beginning I have the repeated code between systems (ugh!). This example is simple but I'm facing this with more complex things like AI, or reacting to collisions.

One solution I came to this is that I really wanted an ActionComponent with a ActionSystem that executes the action contained in the component but this way I'm breaking that components only contains data and they should not have logic! this is more an 'hybrid' approach. But if you start thinking deeply the ActionSystem is very generic and you can almost do anything with it so it's hard to determine whether a system is necessary or not. The same can be applied to collisions, instead of having lots of systems with logic for different entities colliding, you can just have a CollisionHandlerComponent with the logic on it for each entity.

I found the following advantages making generic systems like this:

* Higher flexibility (you can customize each entity easily)
* No repeated code
* Less systems (more performance?)

But as I said the main disadvantage is that is really confusing if a system is needed as you can stick logic to components.

Is it wrong to follow this sort of hybrid ecs? If yes, what would be your approach to the example without repeating code in systems?

# Answer
I was considering voting to close this question as opinion-based, but I think there are a couple of misunderstandings about Entity-Component Systems and Data-Oriented Design here that are worth addressing.

1. **ECS is just a tool**

Like any programming pattern or principle, it exists to help you write good software. It is not an unbreakable law of physics or a straight jacket meant to inhibit you from doing your work.

If you find that for your particular needs, adding logic to your component makes your game perform better or more reliably, or helps you write clearer or more maintainable code, or helps you improve your development and iteration speed, then that might very well be a worthwhile exception to make to the rule.

There's no absolute standard to which every component system must adhere, so make yours work for you. Games get no points for compliance to X or Y's definition of what its code "should" do, only for shipping and offering a great play experience.

(This is the reason I normally consider "am I allowed to/do I have to do X in an ECS" questions to be opinion-based)
2. **Not everything has to be a component or system**

We wouldn't search for every instance of `+` in our codebase and replace it with an `AdditionComponent` processed by an `AdditionSystem` — that would be just silly.

A duration isn't much more complicated than that. You're checking a time against a threshold, something you can do in one line. So you don't gain any particular utility, clarity, or simplicity/reduction in code by packing this up into a `DurationComponent`

If you really want, you could make a simple `Expiration` struct that's just a wrapper around a timestamp, computing an expiration date `duration` seconds in the future upon construction, and exposing an `IsExpired` predicate to check the stored timestamp against the current time. This packages up this small amount of time-related code for reuse, without making it a whole new component & system.

Then your bullet component, explosive component, etc can store an `Expiration` as part of their data, and their respective system updates can check the expiration and do the appropriate thing for bullets or explosives respectively.

Far from unnecessarily duplicating code, you can gain advantages from doing it this way — for instance, your bullet system can recycle expired bullets as it runs through its batch, saving any cost of a separate removal by doing it as part of the iteration it's already doing anyway.
3. **Fewer systems does not necessarily mean better performance**

The major factor in how data-oriented ECS systems aim to boost performance is *cache*.

When you have a system that does one consistent set of operations repeatedly on a contiguous array of similar data, the code you need stays hot in the instruction cache, and the data access patterns are predictable so pre-fetching keeps your data cache full, so your processor can hum along at full speed.

As soon as you throw in indirection, like firing some arbitrary "On Expiration" or generic "Action" callback/delegate/function pointer that might point to something different for every item in the batch, that goes out the window, and you risk cache misses costing hundreds of processor cycles for each hop.

So no, reducing the amount of unique code won't necessarily make it perform better, and it can in fact make it slower if you're counting on data-oriented batching to push your cache to its limits.

It's also not necessarily good for development iteration. Although ostensibly you have less code to write and keep track of, that code ends up being a lot more generic and ambiguous about what it's doing than a group of systems each focused on doing their one job. The latter gives you much more predictable code that's easy to follow and debug than chasing data triggers all over memory.

So, the upshot is: you can adapt your version of a component system to work however you want. Just be sure you understand the reasons you're making the choices you're making, and the reasons the recommendations that caution against them exist, so you can weigh those considerations and make the call that's right for your game's needs.
> 6 votes

---
Tags: entity-system, component-based, logic, data-oriented, entity-component-system
---


# Question
Title: How can I slowdown the characters to speed 0?
```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class AnimatorController : MonoBehaviour
{
    public Animator[] animators;
    public Transform target;
    public float speed = 1f;

    // Use this for initialization
    void Start()
    {
        for (int i = 0; i < animators.Length; i++)
        {
            animators[i].SetFloat("Walking Speed", speed);
        }
    }

    // Update is called once per frame
    void Update()
    {
        float distanceFromTarget = Vector3.Distance(animators[2].transform.position, target.position);
        if (distanceFromTarget < 15)
        {
            float speed = (distanceFromTarget / 15) / 1;
            for (int i = 0; i < animators.Length; i++)
            {
                animators[i].SetFloat("Walking Speed", speed);
            }
        }

        if(distanceFromTarget < 1)
        {
            for(int i = 0; i < animators.Length; i++)
            {
                animators[i].SetFloat("Walking Speed", 0);
            }
        }
    }
}

```

This part of the slowdown is working fine:

```
float distanceFromTarget = Vector3.Distance(animators[2].transform.position, target.position);
            if (distanceFromTarget < 15)
            {
                float speed = (distanceFromTarget / 15) / 1;
                for (int i = 0; i < animators.Length; i++)
                {
                    animators[i].SetFloat("Walking Speed", speed);
                }
            }

```

I tried to add this part to make the characters stop:

```
if(distanceFromTarget < 1)
            {
                for(int i = 0; i < animators.Length; i++)
                {
                    animators[i].SetFloat("Walking Speed", 0);
                }
            }

```

But they never stop. They are slowing down then continue walking slow and then the speed moving up again once they are getting away from the target.

I want them to slowdown when the distance is 15 and less and once animators\[2\] distance is 1 from target stop.

Screenshot of the Animator: The two soldiers have the same animator controller the other character have it's own controller all of them have the same states and parameters and same settings:

# Answer
## Distances and bounding boxes

I think that the problem is that the if-statement of the second part of your script is not getting triggered.

For `distanceFromTarget < 1` to become true, the distance between `animators[2].transform.position` and `target.position` has to become less than 1. The problem is that these positions are actually two *points*. Most likely, they are the coordinates of the cores of the objects. **You are checking the distance between these position values of the objects, not the actual distance between them.** If you have some game-logic that detects colliding, it could be that the bounding boxes of the objects don't allow the two objects to ever come closer than 1. Because of that, the if-statement's condition never becomes true and therefore the code that stops your characters movement never runs.

### For example

Imagine two perfect spheres (Fig-1). These represent the bounding boxes of two objects. In their centre is a point, this is their `position`. If they would somehow move in to each-other, the game engine would detect this colliding and revert the movement. This way, the actual distance between these two spheres could become equal to 0, but their cores will never get closer than 4. Some code that gets activated by the distance becoming less than 3 would thus never run.

*Fig-1: Two objects with a circle as bounding box and a point as `position`:*

### The solution

The solution for your problem would than be to simply increase the minimum distance for the code to become triggered. Alternatively, you could write or implement a method that detects the actual distance between the two bounding boxes, but if these bounding boxes don't follow common shapes that could be quite a challenge.

**Note**

By adding `Debug.Log("I should stop moving...")` to the code inside the if-statement, you can check if it gets run.
> 1 votes

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


# Question
Title: Creating multiple levels in Unity without duplicating scripts
I'm trying to create a falling word typing game like z-type.

I have used the code provided here

I want to create multiple levels in the game, and it seems like I need to make some changes in the code for each level.

For example, in the word display file, I want the active word to be changed to red for level 1 and blue for level 2.

So I created a copy of my level 1 scene, created a duplicate `WordDisplay` script file, changed the code for active word to blue....

```
public class WordDisplay : MonoBehaviour {
    public Text text;
    public float fallSpeed = 1f;

    public void SetWord (string word)
    {
        text.text = word;
    }

    public void RemoveLetter ()
    {
        text.text = text.text.Remove(0, 1);
        text.color = Color.red;
    }
    //...

```

Here's the duplicate script I made:

```
public class WordDisplay1 : MonoBehaviour {
    public Text text;
    public float fallSpeed = 1f;

    public void SetWord (string word)
    {
        text.text = word;
    }

    public void RemoveLetter ()
    {
        text.text = text.text.Remove(0, 1);
        text.color = Color.blue;
    }
    //...

```

Then I made a copy of the `WordSpawner` as well because I was getting an error: I had to change the method's return type to to `WordDisplay1` and then got one more error which was in the Word file, leading to more changes...

```
public class WordSpawner : MonoBehaviour {
    public GameObject wordPrefab;
    public Transform wordCanvas;

    public WordDisplay SpawnWord()
    {
        //...

public class WordSpawner1 : MonoBehaviour {
    public GameObject wordPrefab;
    public Transform wordCanvas;

    public WordDisplay1 SpawnWord1()
    {
        //...

```

Then I created a duplicate of the word prefab and selected the appropriate word spawner file...

All of this seems like too many changes for a simple colour.

Is there a better way to have multiple levels without having to create a duplicate of all these files and the word prefab?

# Answer
In programming we have a principle called DRY: Don't Repeat Yourself.

If you ever find yourself copying and pasting a big chunk of code, DRY says "**Stop.** Is there another way we can share this functionality, without repeating the code?"

In particular, you should never copy a whole script file just to change a *value* used inside it. That's what *variables* are for.

So, step 1: add a variable to control the colour at the top of the class, and make it public so we can set it in the inspector.

```
public class WordDisplay : MonoBehaviour {

    public Text text;
    public float fallSpeed = 1f;
    // New variable! You can even initialize it to a default colour if you want.
    public Color color;

```

Step 2: use the variable instead of a hard-coded colour.

```
    public void RemoveLetter ()
    {
        text.text = text.text.Remove(0, 1);
        // No more hard-coded value - we just use whatever the level designer set in the Inspector.
        text.color = color;
    }

```

Step 3: select the prefab instance in level 1 and set the colour you want there.

Step 4: select the prefab instance in level 2 and set the colour you want there.

You can now have as many different levels and colours as you want, with no further script changes, and no need to duplicate all your files.
> 1 votes

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


# Question
Title: Should I use dependency injection in Unity?
As learned about dependency injection on the internet, I found that it's something that can be done simply by the Singleton Pattern.

But there are 2 completely different views on this issue:

* Some people say it just adds complications to project
* Others say it is a great tool to decouple classes and code

In particular there is Zenject that is made specifically for doing dependency injection in Unity.

With this in mind, should I use dependency injection in my Unity game?

# Answer
> 2 votes
I think Unity is already pretty dependency-injection compatible out-of-the-box.

What are the usual ways to obtain dependencies to other behaviours in a MonoBehaviour?

* The `GetComponent` method, either on the object itself or on objects it references
* Public variables which reference components and can be assigned in the inspector

Both of these features can be used with interfaces or abstract classes instead of implementing classes (In that case `GetComponent` will return the first component which implements said interface/class).

When you have an object which creates other objects, then the DI-compliant solution would be to pass a Factory to that object instead of having it do `new ClassName()`. But when you have an Unity GameObject which creates other Unity GameObjects, then the usual way to do this is by using the `Instantiate` method with a prefab which you assign to a public variable in the inspector. This is also a case of dependency injection because the code which calls `Instantiate` doesn't need to know anything about the prefab in order to instantiate it.

---
Tags: unity, c#, software-engineering, dependency-injection
---


title: RPG quest system

text:
# Question
Title: RPG quest system
So I have made a small RPG where you can create char, update skills, buy items, fight other users etc. Now to make the game more extended I need quests. And I need a little bit of help here.

Right now I have these tables:

`Quests`: `id` `title` etc

`ActiveQuests`: `id` `quest_id` `user_id` (this table fills when user starts a quest)

`QuestBosses` `id` `quest_id` (Quests bosses)

Now I need somehow to develop `goals` like I should have a `quest_goals` table and there store `goals` by `quest_id` I believe ? But then again every goal shuold be coded seperately and if I would want to make new quest through let's say admin panel this approach won't work. Maybe someone have any experience? I'm using NodeJS and Mongoose for this project

# Answer
I far too often used to start making tables before taking the time to really design. I'd recommend taking some time to make a wide variety of examples of quests. Quests that link to other quests, quests that have more than one goal, multiple goals, goals in sequence etc. Then parameterize them in a way that would allow you to programmatically define them. Once that feels solid, return to actual schema design.
> 1 votes

# Answer
> But then again every goal shuold be coded seperately

I *guess* this means the engine needs to understand the difference between, say, `Slay Boss X` and `Fetch 10 Carrots`.

Sticking to these examples, the game world needs the boss character and 10 carrot objects. We don't know how you create them and add them to the world, if they respawn, if they are part of static map data, if they are part of a central object database -- but all that doesn't matter much if you worry about how to connect a quest to either the boss or all these carrot objects, because:

One possible abstraction I want to suggest are *events* that change *flags*.

* "When this enemy is killed, post event to set flag with UUID 123456789 to 1."
* "When this carrot is picked up, post event to increase flag with UUID 45678 by +1."
* "When this carrot is dropped, post event to decrease flag with UUID 45678 by -1."

When

Then your quests can be encoded as:

* "Kill Boss X" == `flag[123456789l] > 0`
* "Fetch 10 Carrots == `flag[45678] = 10`

The engine has to support events like character.onKilled, item.onPickedUp, item.onDropped, etc., but this scales rather well. All you need is a database of flags for each user (which are just hash tables or a variable array or siliar), and a database of quests that check a condition.

In this example, flags always are numbers. The default is 0 (e.g. when the flag is not stored in the database yet) and events can change the values. That's simple, but it works for a lot of things and doesn't take much space.
> 0 votes

# Answer
Although I had to make assumptions on how your quest system would function, it feels this is doathat the fact that MongoDB supports a dynamic schema.

How about the following sample schema?

```
User: {
    id: ObjectId,
    username: string,
    coins: integer
}

Character: {
    id: ObjectId.
    name: string,
    exp: integer,
    level: integer,
    hp_capacity: integer,
    hp_current: integer,
    attack: integer,
    defence: integer,
    spawned: boolean
}

UserOwnedCharacter: {
    ...Character,
    user_id: ObjectId
}

// Can be embedded as an array in the user collection.
UserOwnedQuest: {
    id: ObjectId,
    user_id: ObjectId,

    // either
    discovered: boolean,
    in_progress: boolean,
    completed: boolean

    // or
    state: string
}

Quest: {
    id: ObjectId,

    quest_boss_id: ObjectId,

    // either
    on_begin_gameplay_prerequisite_id: ObjectId,
    on_begin_gameplay_effect_id: ObjectId,
    on_complete_gameplay_prerequisite_id: ObjectId,
    on_complete_gameplay_effect_id: ObjectId,

    // or
    on_begin_gameplay_prerequisite: {data},
    on_begin_gameplay_effect: {data},
    on_complete_gameplay_prerequisite: {data},
    on_complete_gameplay_effect: {data},

    title: string
}

Gameplay Prerequisite: {
    id: ObjectId,
    "mechanicType": [mechanicPrereq1, mechanicPrereq2, ..., mechanicPrereqN],
    ...
}

Mechanic Prerequisite: {
    id: ObjectId,

    equal: {
        attribute: any,
        ...
    },

    greaterThan: {
        attribute: numeric,
        ...
    }
    greaterThanOrEqual: {
        attribute: numeric,
        ...
    },

    lessThan: {
        attribute: numeric,
        ...
    },
    lessThanOrEqual: {
        attribute: numeric,
        ...
    }
}

Gameplay Effect: {
    id: ObjectId,
    "mechanicType": [mechanicEffect1, mechanicEffect2, ..., mechanicEffectN]
}

Mechanic Effect: {
    id: ObjectId,

    set: {
        attribute: any,
        ...
    },
    add: {
        attribute: numeric,
        ...
    }
}

```

Example:

```
User 1: {
    id: "User1",
    coins: 100,
    ...
}

User Early Level Prerequisite: {
    id: "UserAtEarlyLevel",
    greaterThan: { "level": 2 },
    lessThan: { "level": 5 }
}

User Has Coins 100: {
    id: "UserHasCoins",
    greaterThanOrEqual: { "coins": 100 }
}

User Add Coins 500 Effect: {
    id: "UserAddCoins500",
    add: { "coins": 500 }
}

User Remove Coins 100 Effect: {
    id: "UserRemoveCoins100",
    add: { "coins": -100 }
}

Boss 1: {
    id: "Boss1",
    ...
}

User1 Good Guy 1: {
    id: "GoodGuy1",
    ...
}

User1 Good Guy 2: {
    id: "GoodGuy1",
    ...
}

Character Spawned Prerequisite: {
    id: "CharSpawned",
    equal: { "spawned": true }
}

Character Kill Prerequisite: {
    id: "CharKill",
    equal: { "hp_current": 0 }
}

Character EXP Effect: {
    id: "CharGainExperience100",
    add: { "exp": 100 }
}

Character Damage Effect: {
    id: "CharDamage50",
    add: { "hp_current": -50 }
}

Character Kill Effect: {
    id: "CharKill",
    set: { "hp_current": 0 }
}

Gameplay Prerequisite: {
    id: "Boss1Spawned",
    character: {
        "Boss1": [Character Spawned Prerequisite]
    },
    user: {
        "this": [User Early Level Prerequisite, User Has Coins 100]
    }
}

Gameplay User Consume Coins Effect: {
    id: "Boss1Killed",
    user: {
        "this": [User Remove Coins 100]
    }
}

Gameplay Boss1 Killed Prerequisite: {
    id: "Boss1Killed",
    character: {
        "Boss1": [Character Kill Prerequisite]
    },
    user: {
        "this": [User Early Level Prerequisite, User Add Coins 500]
    }
}

Quest {
    id: "FirstQuest",

    quest_boss_id: "Boss1",

    on_begin_gameplay_prerequisite: Gameplay Prerequisite 1,
    on_begin_gameplay_effect: Gameplay User Consume Coins Effect,

    on_complete_gameplay_prerequisite: Gameplay Boss1 Killed Prerequisite,
    on_complete_gameplay_effect: User Add Coins 500 Effect,

    title: "Kill the boss to get the bounty"
}

```

It can be expanded to get as complex as you want to.

Now for this to work, you will need to:
\- query the DB for the data
\- Glue them together in memory and run the prerequisites and effects
\- update the in-memory objects in the DB when necessary

You will have to take care of caching those data into memory and saving when necessary.

Good luck!
Wow, that was long...
> -1 votes

---
Tags: javascript, rpg
---


# Question
Title: can you release a game made by unity free on google play store
do i need to pay for anything in this situation : i m making mini games to raise money and cant afford unity pro or plus(don't think its worth it)for my original idea/game.i am also thinking about using unity ads(is that free to use as well).

# Answer
It's all on the website.

> If your company currently makes more than $100k in annual gross revenues or has raised funds in excess of $100k, you are not permitted to use Unity Personal, for prototyping or otherwise, as defined in our EULA Agreement. You may use Unity Plus for up to $200k in annual gross revenues, or Unity Pro with an unlimited revenue or fundraising capacity.

So yes, you can release your game made with the free Unity Personal Edition. You only need to upgrade to the next version after you made more than $100,000.
> 2 votes

---
Tags: unity, publishing, google-play, unity-ads
---


# Question
Title: How can I set random speeds once inside Update?
```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Spin : MonoBehaviour
{
    [Range(1, 500)]
    public float[] speeds;
    public bool randomSpeed = false;

    private GameObject[] objectsToSpin;
    private bool randomSpeedInUpdate = true;

    // Start is called before the first frame update
    public void Init()
    {
        objectsToSpin = GameObject.FindGameObjectsWithTag("ClonedObj");
        if (objectsToSpin.Length > 0)
        {
            speeds = new float[objectsToSpin.Length];
            for (int i = 0; i < objectsToSpin.Length; i++)
            {
                if (randomSpeed == true)
                {
                    speeds[i] = Random.Range(1, 500);
                }
                else
                {
                    speeds[i] = 100;
                }
            }
        }
    }

    // Update is called once per frame
    void Update()
    {
        if (objectsToSpin.Length > 0)
        {
            for (int i = 0; i < objectsToSpin.Length; i++)
            {
                objectsToSpin[i].transform.Rotate(Vector3.down, speeds[i] * Time.deltaTime);

                if (randomSpeed == true && randomSpeedInUpdate == true)
                {
                    speeds[i] = Random.Range(1, 500);
                    randomSpeedInUpdate = false;
                }
                else
                {
                    speeds[i] = 100;
                    randomSpeedInUpdate = true;
                }
            }
        }
    }
}

```

I tried to use a helper flag variable name randomSpeedInUpdate but still when I'm changing the randomSpeed flag to true while the game is running it keep changing the speeds all the time. I want it will change the speeds to random only once when changing it to true.

# Answer
> 1 votes
Rewrite your Update function to

```
void Update()
{
    if (randomSpeed && randomSpeedInUpdate)
    {
        for (int i = 0; i < speeds.Length; i++)
        {
            speeds[i] = Random.Range(1, 500);

            if (i == speeds.Length - 1)
                randomSpeedInUpdate = false;
        }
    }
    else if (!randomSpeed)
    {
        for (int i = 0; i < speeds.Length; i++)
        {
            speeds[i] = 100;
        }
        randomSpeedInUpdate = true;
    }

    for (int i = 0; i < objectsToSpin.Length; i++)
    {
        objectsToSpin[i].transform.Rotate(Vector3.down, speeds[i] * Time.deltaTime);
    }
}

```

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


# Question
Title: Generate a HexMap where each tile has a different tile on each edge
I’m trying to generate a 7\*13 hexmap, with 9 different types of tiles, numbered 0 through 8. I need the map to be randomly generated on each run and it has to be so that each tile has a different numbered tile on each edge.

I’m having trouble with this algorithm. I can generate my map just fine, but there will always be many tiles where they’ll have the same number on multiple sides.

Any tips would be appreciated. Currently, I’m think I’ll have to iterate through the 2d grid, picking my first tile, let’s say 1. And then make sure there is no other 1 spawn in a two block distance. Any better ideas I can use?

Thanks

# Answer
Here's a simple scanline algorithm you can use:

1. Work through your grid row by row: left to right, top to bottom.
2. As you come to each cell, the two cells adjacent above it and the one cell adjacent to its left in the same row have already had tiles assigned. The rest aren't assigned yet, so we won't worry about them.
3. Our three already-assigned neighbours have used at most three of the available tiles (sometimes two, if they alternate A-B-A or at the start of a narrow row, or one for cells at the top & leftmost edges, or zero for the top-left cell)

Mark those tiles forbidden, and count how many tiles you marked. Subtract that from 9 to get the number of options for this cell.
4. Generate a random number `i` between 0 and this number of options. Take the `i`th non-forbidden tile from your list and assign it to this cell.
5. Clear the forbidden marking from the tiles used by the left & top-left neighbours and proceed to the next cell.

Since we only ever forbid at most 3 tiles at a time, we always have at least 6 options for the next tile. And because we never place a tile that matches an adjacent tile that's already placed, we're guaranteed to produce a valid colouring with no identical tiles side-by-side.

We only have to read 3 neighbours at each step, and in fact you can exploit the pattern of travel to slim this down even further - the top-right neighbour of this cell is also the top-left neighbour of the next cell, and the cell we just assigned is the left neighbour of the next cell, so we don't need to check them again. Apart from a little set-up at the start of a row, we only actually have to check one new neighbour for each cell we want to assign. How's that for magic? :)
> 1 votes

---
Tags: unity, game-design, algorithm, hexagonal-grid
---


# Question
Title: Why Godot over Cryengine, UE4, Armory3d or Unity3d?
Godot have a low performance in linux systems and lack of functionalities? This appear not been in account when peoples vote for him over other engines and i wonther whi. I know it is under MIT lisence, but the others engines have a very permisive licences and in some cases they help you with funding for your games. I ask this because i have maded survey on google plus about a selection of engines, and people still bote for godot over other engines. I want to select an engine for my future games, and when i compared, godot's not get a good place.

# Answer
Although usually questions like "what software is better" are off-topic, because the answer is almost always "try them all, and pick your favourite", I think this one could be an exception so I'll attempt to answer it.

* From my experience, Godot does not have low performance on Linux. I have one of the cheapest laptops on the market, and run Arch Linux, and Godot runs fine (far better than Unity - I haven't tried the other engines you mentioned).
* Being open source is a massive plus for Linux users. It doesn't automatically make the software immune to malicious behaviour, but it's better when the developer says "You don't believe me? Check the code!" instead of "You don't believe me? I tell the truth, I promise!", especially since companies have taken advantage of that in the past.
* MIT license is another plus, you make a game using Godot, you own it. There is nobody to cause you legal trouble, nobody to take part of your profits (As far as I remember that's how MIT license works).
* Having tried Godot, I enjoy the C++ inheritance-oriented design, as it's closer to traditional game design before using engines (at least for me). I find Unity's component-based system a "it just works" kinda system. On Godot, if I want to do something the language didn't intend me to do, it feels like I can do it, on Unity I always end up going to the forums, and there's been times that the feature I seek is not supported "By design".
* Personally I enjoy Godot's attitude. They are more like "We made an engine, feel free to use it, and if you want, donate back to us". Although I can't blame other engines for asking profits, since the people work hard on them. This also allows people that can't afford much money, to experiment with Godot. Having said that I'm aware that lately some engines moved to a different model where you only pay if you make enough profit.

Having said all of that, I use Unity at work, and I'm more used to it than any other engine. I've used Godot on my free time but not to the same extend. Also the points I made do not say that Godot is any better than other engines, it simply states I would understand why a person would choose to support it over other engines.
> 5 votes

---
Tags: unity, unreal-4, godot, cryengine
---


# Question
Title: Implementing score relative to total game time
How would one create score dependent on total time in game? I would like the score to count by 1000+ each second the game is running for. Later I am going to add some coins which will give my total score +1000 also.

How would one create this functionality? This is all I have right now:

```
  let scoreDisplay = UILabel()
    scoreDisplay.text = "Score: \(self.score)"
    scoreDisplay.textColor = UIColor.red
    scoreDisplay.frame = CGRect(x: mainWidth / 2 - 200, y: mainHeight - 400, width: 247, height: 100)
    self.view.addSubview(scoreDisplay)

    let delay = SKAction.wait(forDuration: 0.25)
    let incrementScore = SKAction.run ({
        self.score = self.score + 1
        self.scoreDisplay.text = "\(self.score)"
    })

```

I'm pretty new to Swift, so sorry for my basic question!

# Answer
First you need to have a timer variable that only starts counting when the game has started.
Some programming languages have build-in timers, but those usually already starts when the application is running, so these aren't useful if you're using a startup screen or reset button. But you can use these timers to calculete the time spend in a timer variable. Once you've that timer variable, you can use that to count up the score.

I'm not familiar with Swift, So I cannot give you a working example. nor do I know if a build-in variable is available.
But you can set a `timer` variable on your own, similair as how you've defined your scoreDisplay, then add +1 everytime the code gets past the `timer` variable. problem is however that it calculates in code-ticks, instead of seconds, and it may not be accurate in case of a frame drop.
Other possibilities are to set the current date and time at the moment your game starts, and set the current date and time when the game ends. then substract the ending datetime with your first datetime to get the total time spend.
> 0 votes

---
Tags: swift
---


title: Check if client is alive

text:
# Question
Title: Check if client is alive
I am having client/server application and i want to detect if client is alive.

So i know that `send()` will return me `null` but it will not inform my server that client has been disconnected.

Way i came up is each N seconds send "Are you alive" message from server to client but is that good solution?

# Answer
This is a good solution, since it allows both sides to know that their partner is alive.

Call it "keepalive" or "hearbeat".

Added benefit, when done frequently (1/sec) you can monitor lag / ping.
> 2 votes

---
Tags: multiplayer, socket
---


# Question
Title: Does putting non power of 2 sprites in an atlas makes them a power of 2?
A lot of my UI sprites are not power of 2 so Unity might not compress them. However I put them inside a sprite atlas which is 1024x1024. So are they now considered a power of 2 and will Unity compress them? Or should I still convert them manually one by one?

# Answer
> 2 votes
When it comes to compressing, you only care about the atlas size. If the atlas is a power of 2, that should be enough. The individual UI sprites do not need to be compressed separately, so as long as they are part of an atlas, they can have any dimensions.

---
Tags: unity
---