title: Tips on a Turn Based Strategy AI

text:
# Question
Title: Tips on a Turn Based Strategy AI
I have been working on a game for a while now, and it is going to be a TBS(Turn based strategy) in space.

And now I have come to the point where I am creating an AI for the game. I have no experience when it comes to designing AI's, the first one I ever made was based on random int's and getting the target out of an array.(not exactly a real AI)

On this topic I have a few questions:

* How can an AI assess what is the best move to do next? Several units can move every turn.
* How does a common AI consider what to do?(Example: Civilization, StarDrive 2, and similar)
* How do I manage all the possible outcomes and the moves the AI can/should do?

# Answer
> 1 votes
For the tactical AI of our turn based strategy game we use an approach inspired by utility-based decision making. Here is a simplified explanation:

Each AI Action (i.e. Attack, Advance, Hide) has a list of Considerations and an Execute routine.

Each Consideration is a relatively simple function that takes some parameters (i.e. the tested position, the unit that is tested, etc.) and returns a normalized floating point score (from zero to one). Some example Considerations are ConsiderDamage, ConsiderAnyTargets, ConsiderAdvanceImprovement, ConsiderUnitsSpread, ConsiderSafePath, ConsiderSafeSpot etc.

The AI evaluates all possible Actions at all available positions (i.e. in movement range) by invoking all Considerations for each Action/Position pair, and combining Consideration results by multiplying them. This product is the score for the Action/Position pair.

A boost can be applied to pair scores by multiplication, so some actions are preferred to others. For example in our game the MoveThenAttack action has a boost value a few times higher than the Roam and Advance actions, so MoveThenAttack is almost always preferred by the AI if there is an opportunity for an actual attack at a given position.

Finally the AI picks the Action/Position with the highest score and invokes the Action's Execute routine at Position.

Here are some talks on utility-based game AI:

http://www.gdcvault.com/play/1021848/Building-a-Better-Centaur-AI

http://gdcvault.com/play/1012410/Improving-AI-Decision-Modeling-Through

http://www.gdcvault.com/play/1018040/Architecture-Tricks-Managing-Behaviors-in

# Answer
> 0 votes
You have many options:

1) State machine based on global values, preferences, and location.

2) Machine learning and neural networks.

3) Decision tree.

4) Value map (every tile has its value).

5) Different AI layers that calculate their own behavior, some layers can depend one on another.

6) Combine them all.

7)....

I recommend you watching GDC AI as was stated above in the comments. - this will help you not only create the AI that will beat everyone in the game but to create a real AI that is fun to play against and that you can relax playing vs him - then player won't be tired of the game. And ofc try to make the AI as smart as it can be at the moment and make it more stupid from there if he is easy to beat, but it's only when you have AI - by that I mean don't try to make it super smart in the beginning. I recommend first watching this talk Less is More: Designing Awesome AI for Games \- in my opinion, it's the best talk about AI I have ever seen.

Also, this question might be a duplicate of this: AI

**EDIT:**

(If you haven't already)

I recommend you to learn some Algorithms and Data structures before diving into AI. Understand big O() notation and use the most efficient way to implement AI. Good AI should work fast as well, especially if it's TBS, it will take forever to calculate the things if you did something not efficiently.

Also, learn OOP, programming patterns and code design (architecture). AI without them would be hard to handle.

---
Tags: java, game-design, ai, turn-based-strategy
---


title: Does GLSL support multitexturing?

text:
# Question
Title: Does GLSL support multitexturing?
I am using LWJGL libraries to code myself a game. I want to be able to import a project from blender to my game. I have the wavefront .obj reader and it works perfectly for my needs. Although because my model uses multiple images I do not know how to set that up in my game engine. All it does is stretch the first image I send to the shaders across the entire model. Then I ran across a couple videos that makes me doubt that GLSL can support multiple images. Also, I found a couple solutions but they were depreciated because I use LWJGL 3 with slick-util 3 to load the image.

So I would first like to know, does GLSL support rendering multiple images on a single object?

If GLSL can support rendering multiple images on a single object, how would I proceed conceptually to perform this feat?

P.S. Let me know if want images or anything to better understand my question. **Thank you all!**

# Answer
"Multitexturing" is an OpenGL feature from before programmable shaders; shaders pretty much made the concept obsolete, and it was quickly deprecated. Any websites you read which talk about "multitexturing" probably predate programmable shaders.

With programmable shaders (GLSL), you can just define multiple texture samplers in your fragment shader and use them however you want.

To do something like what OpenGL's "multisampling" used to do, you'd just create two or more texture samplers in your fragment shader, bind textures to each of them from your engine, and then have your shader read color values from them and combine those color values however you want. Add them together, subtract them, mix between them, or whatever else you want. You can even sample multiple times from the same texture using different texture coordinates, if you want.

There's really nothing fancy to it; it's an awful lot simpler and more flexible than multisampling ever was. Read any tutorial on GLSL and you'll get the gist of it. If you know how to do texture mapping, just do that twice inside the same shader and you've got your equivalent of multitexturing.
> 2 votes

---
Tags: fragment-shader, image, lwjgl3
---


# Question
Title: How to edit the alpha channel of an existing specular map?
I am working with a third party model and need to change the specular map. The model material is using the spec map's alpha channel information. I have opened the spec map in Photoshop and if I go to the Channels tab I can see the Alpha 1 channel with the alpha information that I need to change.

What I would like to do is make a copy of this original and drag it into the Layers tab, so that I can revert back to this if need be. I can then duplicate this again and paint over it to create the new alpha map. Once done I can then copy and paste it as the new alpha channel, keeping the original preserved in the Layers tab.

The problem is how do I get the Alpha 1 channel into the Layers tab to make the edits? I cannot click and drag it there; and if I do Select All, Copy and Paste into a new layer nothing is pasted. How can this be done?

If I'm not using the best workflow for editing an existing specular map please suggest an alternative way. I basically just want to edit the alpha channel but keep the original as well.

# Answer
I have managed to work this out. It is actually quite a strange process:

1) Go to the Channels tab

2) Hide all the Channels except Alpha 1

3) Do Select All to highlight the entire canvas

4) Select the Alpha 1 channel ***only***

5) Edit \> Copy

6) Go to the Layers tab and create a new blank Layer

7) This will hide the Alpha 1 channel and show the other channels

8) Go back to the Channels tab and again hide all the Channels except Alpha 1

9) Back in the Layers tab select the new empty layer and do Select All to highlight the entire canvas

10) Edit \> Paste

This will basically convert the Alpha 1 from a channel into a layer. So now you can duplicate this Alpha 1 Layer and preserve it. You can also use any of Photoshop's tools to edit it into a new spec map. Once you're done, copy and paste the new spec map back into the Alpha 1 Channel to override the existing alpha with the new one. Hopefully this helps someone.
> 0 votes

---
Tags: textures, alpha
---


# Question
Title: Assign type to an entity in Entity-Component System (super entity - syntactic sugar)
I have created ECS framework from scratch using C++.

Everything works fine, but I think my code is not so cute (at `#1`):-

```
class RocketComponent{
    Entity mainBodyGraphic;
    Entity topGraphic ;
};
//inside some system (script-like)
void createRocket(){
    Entity mainBodyGraphic = graphicFactory->createCylinder();
    Entity topGraphic = graphicFactory->createCone();
    //^ internally create entity (with graphic component and others),
    //         then attach together
    Pointer<RocketComponent> rocket  = create<RocketComponent>();
    rocket->mainBodyGraphic = mainBodyGraphic;
    rocket->topGraphic = topGraphic;
    //.... other logics ....
}

void showDamage(Entity rocket){
     Pointer<RocketComponent> rocket  = rocket->get<RocketComponent>();
     systemGraphic->setColor(rocket->mainBodyGraphic,RED);   //#1
}

```

`#1` is ugly.
In my dream (Object-oriented style), `#1` could be :-

```
rocket->mainBodyGraphic->setColor(RED);                      //#1

```

The above line is far easier to read and code. It is also less error-prone.

## The Change (super entity)

I plan to change my code to support it, but I don't want to lose any disadvantage of ECS.
Therefore, I will create **super entity**.

For example:-

* I create a new **super Entity** class named `GEntity` (graphic entity).
* I provide a converter (`operator=()`) between `Entity` and `GEntity`.
* Whenever a function just want `Entity`, I can pass `GEntity` instead, and vice versa!
* `graphicFactory->createCone()` and similar functions will return `GEntity` instead of `Entity`.
* The field in `RocketComponent` will be `GEntity mainBodyGraphic;`.
* `Entity` has no access to game logic like before, but `GEntity` can access all game logic/system.

Here is my adoption (future plan / promise to myself):-

* In `GEntity`, I can add all syntactic sugar functions e.g. `setColor()` as much as I want.
* I will use `GEntity` only when logical type of entity is very obvious.
* I will also create `PEntity` = Physic body, because its type is also obvious.
* I may also create other types of **super entity** if its type is very obvious && I want the syntactic-sugar.

Here is the result (change marked with `$`):-

```
class RocketComponent{
    GEntity mainBodyGraphic;      //$
    GEntity topGraphic ;          //$
};
void createRocket(){
    GEntity mainBodyGraphic = graphicFactory->createCylinder(); //$
    GEntity topGraphic = graphicFactory->createCone();          //$
    Pointer<RocketComponent> rocket  = create<RocketComponent>();
    rocket->mainBodyGraphic = mainBodyGraphic;
    rocket->topGraphic = topGraphic;
    //.... other logics ....
}
void showDamage(Entity rocket){
     Pointer<RocketComponent> rocket  = rocket->get<RocketComponent>();
     rocket->mainBodyGraphic->setColor(RED);                    //$
}

```

## **Concern (my fear)**

I feel that I am violating some ECS rules.
I am probably destroying good ECS abstraction and design pattern in favor of my indolence.

I have already refactored some of my code to the new way.
It looks nice and neat. I think I am biased.

## **Question**

* What are disadvantage of this approach?
* What are things (potential issue) that I should concern and prevent?
* What is the name of this technique/design-pattern (if any)?

# Answer
> 1 votes
I would actually consider your rocket as a single entity.

That single entity holds a reference to a `MeshComponent` that is designed to hold a base mesh and zero or more sub meshes. If we think about how meshes are separated to draw them with different materials, this is pretty common. So that component would look like this:

```
struct mesh_t {
  string meshName;
  // other stuffs
};

struct MeshComponent {
  int entityId;
  mesh_t baseMesh;
  vector<mesh_t> subMeshes;
};

```

The next question to ask is whether the graphics system's renderable representation should be exposed at all in your component. I've seen some examples where developers do this:

```
struct MeshComponent {
  int entityId;
  mesh_t baseMesh;
  vector<mesh_t> subMeshes;
  GraphicsRenderable* baseRenderable;
  vector<GraphicsRenderable*> subRenderables;
};

```

This works, but I prefer encapsulation and abstraction. The `GraphicsRenderable` is the graphics system's scene graph representation of those meshes and I prefer that not to be immediately accessible by anyone who can get my `MeshComponent`.

Instead, the graphics system maintains an internal mapping between its scene graph *renderables* and the external `MeshComponent` instances. The system knows when the component is destroyed, it has to cleanup the appropriate *renderables* or perhaps when state changes on the component, the system replicates those changes to the *renderables* internally.

So I end up with something like:

```
// external to ecs users

struct mesh_t {
  string meshName;
  // other stuffs
};

struct MeshComponent {
  int entityId;
  mesh_t baseMesh;
  vector<mesh_t> subMeshes;
};

// internal to graphics system

struct Renderable {
  MeshComponent* component;
  vector3 position;
  vector4 rotation;
  scene_ptr node;
  ...
}

```

To specifically mention your use case about color, I would expose that on the `mesh_t` struct and your code becomes this to change it:

```
MeshComponent& mesh = entity.getComponent<MeshComponent>();
mesh.baseMesh.color = Colors.RED;
mesh.subMeshes[0].color = Colors.RED;

```

The next time the graphics system updates, it will replicate the color changes from the `MeshComponent` to the associated `Renderable` and then on the next draw, the meshes will be the color red.

At the end of the day, treat your ECS as a bridge between game code and base/core systems of your game engine. Your game code interacts with components, systems take those interactions and manipulate internal models and structures to achieve the goal.

This separation of concerns will make refactoring code much easier too.

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


# Question
Title: The object can't rotate around z axis in SceneKit
I am doing an app with a functionality like a 3D compass, it can point to the direction where I want. The code is

```
extension AR: CLLocationManagerDelegate{
    func locationManager(_ manager: CLLocationManager, didUpdateHeading newHeading: CLHeading) {

        heading = Float(newHeading.trueHeading)

        motionManager.deviceMotionUpdateInterval = 1.0/60.0
        if motionManager.isDeviceMotionAvailable {
            motionManager.startDeviceMotionUpdates(to: OperationQueue.main, withHandler: { (devMotion, error) -> Void in
                self.node.orientation = self.orient(q: (self.motionManager.deviceMotion?.attitude.quaternion)!,angle: self.heading)

        })}

    }

```

}

```
func orient(q:CMQuaternion,angle:Float) -> SCNQuaternion{
    let gq1: GLKQuaternion = GLKQuaternionMakeWithAngleAndAxis(GLKMathDegreesToRadians(-angle), 0, 0, 1)
    // add a rotation in z axis
    let gq2: GLKQuaternion = GLKQuaternionMake(Float(q.x), Float(q.y), Float(q.z), Float(q.w))
    // the current orientation
    let qp: GLKQuaternion = GLKQuaternionMultiply(gq1, gq2)
    // get the "new" orientation
    var rq = CMQuaternion()
    rq.x = Double(qp.x)
    rq.y = Double(qp.y)
    rq.z = Double(qp.z)
    rq.w = Double(qp.w)
    return SCNQuaternion(Float(rq.x), Float(rq.y), Float(rq.z), -Float(rq.w))
}

```

At first I got the device's orientation to apply to my object ("node") in z axis so that it can point to the right direction. However, I figure out there is gimbal lock coming. When I rotate the device in x & y axis, the object can rotate in x & y axis as well. But if I rotate the device in z axis, there are two situations:

one, the device is holding up, the object still rotates in y axis (Seems rotation in z axis disappears).

two, the device is lying down, the object rotates in z axis.

How can I avoid first situation?

# Answer
Actually there is no gimbal lock. The reason is that if I rotate the device around z axis, the direction data comes out continuously. As a result, I can't use CLLocationManagerDelegate to achieve my goal. This thread is what I want.
> 0 votes

---
Tags: ios, quaternion, swift, scenekit
---


# Question
Title: How should one component "trigger" another one in a component system?
In my game I have a `MoveComponent` and a `ClimbComponent`.

Some characters can only move around on one level, others are able to climb to the next floor.

My intention is to have characters randomly be able to climb if the are about to bounce into a wall.

How would I manage this? Should the `ClimbComponent` be added dynamically and also be removed again, or should random characters always have the `ClimbComponent` and it would be activated and deactivated dynamically?

# Answer
> 0 votes
I would recommend you consolidate your two concepts into one.

Instead, I would consider a `MovementComponent` or better yet a `ControllerComponent`. This one component controls movement both on a single level and the act of being able to climb when appropriate.

Be mindful that you aren't creating components just to create components. There are cases where using a marker component makes sense but in a lot of cases, a simple boolean does the job well.

# Answer
> 0 votes
I don't think there's a clear winner between the 2 approaches you mention.
I'd probably go for a component always present on the entities that can be activated dynamically, and have some game logic component (a "higher level" one) that switches them on/off.

---
Tags: entity-system, entity-component
---


# Question
Title: Entity interaction in a component design with events
My components are 100% isolated. No component knows about anything outside of itself in any way. Components have functions that operate on their internal state, and events to inform what's happening to their internal state.

I then create a script on my game object called `CommHub` where I hook up all the component events to component functions. This works really well and I love it. I love having completely decoupled components and one central place to see how the communications between them are setup. It gives me a high level, while being functional, view of said game object, and some game objects can have a lot of components.

My question is now entity to entity interaction and how to do that while keeping this idea of 100% decoupled components.

Say we have the player game object and a zombie game object. Each is made up of components. The high level idea is the zombie looks in a radius around itself for all entities and if one is the player it'll walk towards it. When in a certain range it'll start a struggle with the player. This is the first interaction between 2 entities. The zombie controller component is the one that checks if it's in range of the player (its target found from the search component) and if so needs to communicate with the player to tell it to start a struggle with this zombie.

A system for communication between the entities is what I'm interested in talking about, while still keeping the rule of components not being aware of other components directly (ie. no component knowledge from within another component). I can't think of a good way to do it like I have with inter-entity components.

How can I approach this?

# Answer
> 1 votes
I would have designed it so that the `StruggleComponent` holds a reference to the target entity id.

For the zombie, it would determine the target entity id when an unknowingly hostile entity enters the aggressive radius of the zombie. When the AI check detemines an entity has entered that space, it raises an event and sets the target on the `StruggleComponent`. This causes the zombie to move to the target and start attacking.

The way the player entity is notified of the attacks would be to use that target entity id to dispatch an event to that entity directly, like as follows:

```
// somewhere in the struggle component's code for attacks
Entity target = getEntity()->getEntitySystem()->findEntityById( targetEntityId );
target.sendEvent( new Attack( 25 ) );

```

In this case, the zombie used the target entity id to get the entity reference from the entity manager and then send it a direct event of an attack of 25 damage.

Internally, the target entity may likely distribute that event to all its components allowing each component to handle that event as it needs to. The most notable would be that the `Health` related component would reduce its HP by 25.

---
Tags: software-engineering, entity-component, entity-component-system
---


# Question
Title: How can I make a random function generate a specific integer more often without using arrays and vector?
I was making a ludo game and there's a rule that your pieces will only open when the 6 will shows up on a dice.

How can I make my dice generate the number 6 more often, without using arrays or vectors? I'm using c++.

# Answer
> 5 votes
Generate a random number between 1 and some number higher than 6 (7, 8, 9, etc). If the result is higher than 6 treat it as a 6.

# Answer
> 0 votes
First thing that came up on my mind without using array is re-generating a random number again if it is not 6. You can arrange chances with iteration over re-generation.

But this solution does not perform well if random generation function costs high.

---
Tags: c++, board-game
---


# Question
Title: How to solve this card game turn requestes clashing issue
So I am developing a poker card game using JS +node.js + socket.io.

It is turn-based game. There will be a host and 4 other players.The flow is the players need to make a yes/no choice, then the host need to make a yes/no choice upon players' move, then players will need to make another yes/no choice, then the server will determine who wins.

Put simply,

1:Host set up the hand -----\>2: inform all players----\> 3:A player make a move(ticking yes or no) --\> 4:this move will show up on the host's screen---\>5:the host need to make his/her move(ticking yes or no)---\>6: the host's move show up on players' screen, they make another yes/no choice----\> 7:the server determine who wins.

**The issue lies on step 5.**

There will be multiple moves waiting for the host to process. Now the current design is all moves are shown by the form of a custom confirm box. It has yes/no button. It works perfect when there is only one host and one player. But when there is more than 2 players, there is a serious clashing problem.

If player A makes a move, it shows on the host's screen, and before the host ticking anything, player B makes a move and then player B's move (confirm box) will replace player A 's confirm box. In this case the host will not be able to process player A's move and the game cannot finalise.

How to get this clashing issue sorted? I hope I am not making this issue sound too complicated but I have been scratching my head.

# Answer
Have a queue of decisions to make which is processes first-in-first-out. You can easily implement it as an array in JavaScript.

When an event happens which requires a decision and the decision window is already open, that new decision is pushed to the end of the decision queue.

When the player made the decision, the current decision window is closed. You check if there are elements in the decision queue, and if there is you remove the oldest decision from the queue and reopen the window with that decision.
> 0 votes

---
Tags: javascript, turn-based, node.js, socket, poker
---


title: Changing color of only one gameobject

text:
# Question
Title: Changing color of only one gameobject
So i have this script the checks if my mouse cursor is over the block and if it is i want the block to change color

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

public class BasicBlockFunction : MonoBehaviour {

public GameObject Block;
public Color StartingColor;
public Color HighlightColor;
Color color;
Ray ray;
RaycastHit hit;

// Use this for initialization
void Start () {

}

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

void MouseOver()
{
    ray = Camera.main.ScreenPointToRay(Input.mousePosition);

    if (Physics.Raycast(ray, out hit))
    {
        print(hit.collider.name);
        Block.GetComponent<Renderer>().material.color = HighlightColor;
    }
    else
    {
        Block.GetComponent<Renderer>().material.color = StartingColor;
    }

 }

}

```

I want to change the color only for the gameobject i have my mouse on.

# Answer
If your block objects each have their own colliders, you can do this with a script you attach to each block, leveraging Unity's built-in OnMouseEnter / OnMouseExit events:

```
[RequireComponent(typeof(Renderer))]
public class HoverHighlight : MonoBehaviour {

    public Material highlightMaterial;

    Renderer _renderer;
    Material _originalMaterial;

    void Start() {
       _renderer = GetComponent<Renderer>();
       _originalMaterial = _renderer.sharedMaterial;
    }

    void OnMouseEnter() {
       _renderer.sharedMaterial = highlightMaterial;
    }

    void OnMouseExit() {
       _renderer.sharedMaterial = _originalMaterial;
    }

}

```
> 3 votes

# Answer
Instead of changing the material color, you could change the material.

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

public class BasicBlockFunction : MonoBehaviour {

public GameObject Block;
public Material StartingMaterial;
public Material HighlightMaterial;
Color color;
Ray ray;
RaycastHit hit;

// Use this for initialization
void Start () {

}

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

void MouseOver()
{
    ray = Camera.main.ScreenPointToRay(Input.mousePosition);

    if (Physics.Raycast(ray, out hit))
    {
        print(hit.collider.name);
        Block.GetComponent<Renderer>().sharedMaterial = HighlightMaterial;
    }
    else
    {
        Block.GetComponent<Renderer>().sharedMaterial = StartingMaterial;
    }

 }

}

```

This would give you more control over the highlight material.
> 0 votes

# Answer
You are referring to a Block game object not the object being hit by the array. To change the object the raycast hits use the hit variable. This stores all info about the object including its material and colour.
> 0 votes

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


# Question
Title: How do I avoid using the wrong texture2D function in GLSL?
I was developing a small engine running on a combination of SDL and OpenGL, and I want to use that engine for a school project, so I needed to test it on a school PC to see the performance. This resulted in a shader compile error:

> `Shader compile ERROR`
> `DEBUG INFO: ERROR: 0:12: 'texture' : no matching overloaded function found (using implicit conversion)`
> `ERROR 0:12: '=' : cannot convert from 'const float' to '4-component vector of float'`
> `Failed to load uniform`

This is my fragment shader, where the error occured:

```
    #version 130

in vec4 fragmentColor;
in vec2 fragmentUV;

out vec4 color;

uniform float time;
uniform sampler2D mySampler;

void main(){
    vec4 textureColor =  texture(mySampler, fragmentUV);

    color = textureColor * fragmentColor;
}

```

I solved it by using the `texture2D` function, instead of `texture`. However, the older function is not recommended in newer code. This leaves me with two questions:

1. Why did this happen? Could it had been because of older drivers being installed on these PCs?
2. What should I do when I want to follow the new guidelines, and also to make it runnable on older machines? I thought about using two different shader,s and letting the program decide on the version, but I´m not sure.

# Answer
> 8 votes
You could use a macro:

```
#if __VERSION__ < 130
#define TEXTURE2D texture2D
#else
#define TEXTURE2D texture
#endif

...

vec4 textureColor =  TEXTURE2D(mySampler, fragmentUV);

```

I found this answer, that seems to have a compatibility include that handles more than just `texture2d`.

# Answer
> 7 votes
Your home PC probably has a higher shader version than the school PC, because the GPU is older. Older glsl versions used the `texture2d` function, while newer ones simply use `texture`.

You don't need to have 2 different shader codes, you can make it dynamic with preprocessors:

```
#if __VERSION__ > 120
    color = texture(sampler, texCoord);
#else
    color = texture2D(sampler, texCoord);
#endif

```

When the code gets compiled, opengl will decide which version to use.

---
Tags: opengl, glsl
---


# Question
Title: How can I boost cache performance when storing objects in a scene with managed languages?
So, for reasons that I won't go into (has to do with my team more so than a good objective reason, unfortunately), I'm building a soft game engine in C# on top of SharpDX. C++ wasn't an option. I can't store objects contiguously in C# when it comes to reference types like classes, so I'm thinking about taking a data-oriented-design approach to storing objects in my scene. Thus, my scene looks a bit like this right now (all of the fields are structs because I can store them by value type, and thus contiguously):

```
public delegate void UpdateMethod (ref ModelData md, ref Transform t, ...)

class Scene
{
    ModelData[] models;
    Transform[] transforms;
    //...some other fields here
    UpdateMethod[] updateMethods; //delegate array

    void UpdateAll()
    {
         for (int i = 0; i < NUM_GAME_OBJECTS; i++)
        {
            if (updateMethods[i]!= null)
            {
                updateMethods[i](ref models[i], ref transforms[i], ...);
            }
        }
    }
}

```

The idea being that I can now store the objects contiguously as opposed to just an array of contiguous references to the data if I made each component a class.

Is this even a viable technique, or am I abusing the DOD paradigm? I'm storing all of my objects like this, not just my dynamic ones. Perhaps I could split it up into two sets of arrays for dynamic and non-dynamic, so I'm not tempting branch-predictor slow-downs on the if statement for `UpdateAll()`?

Will an approach like this create more issues than it attempts to solve? I will note that, while updating occurs here, I outsource the actual carrying out of the component functionality to other systems. For example, an input subsystem determines keys pressed, so an object could check in its unique update method denoted by the delegate; the update doesn't do everything, just behavior specific to that bundle of game object data.

This seems analogous to operating over columns in a row-major language, in that I'm killing performance gain of data locality; am I correct in concluding it would it be beneficial to wrap all of these fields into some `GameObjectData` wrapper struct, and just store those in an array?

# Answer
This is a viable technique in general, but as with any decision it comes with downsides. Most of them are related to ease of use: consider that your example `updateMethods` call is (probably) wrong, since you're *copying* `models[i]` and so on. Updating the instance of `ModelData` you get inside `updateMethods` won't change the one in `models[]`. You'll end up passing around a lot of `ref` parameters, or passing arrays-and-indexes to refer to individual objects.

It looks to me like you are worrying too much about the theoretical performance implications instead of the practical ones. That is, engage your profiler and determine where and when (or even *if*) you need to resort to this kind of approach.

It's *very possible* to make a game that performs well in C# without resorting to making everything a struct in a giant contiguous array so long as you also understand the implications of reference types on the garbage collector and the behavior of the garbage collector. Understanding how-and-when to avoid the garbage collector just as important as understanding how-and-when it's a good optimization to stuff a bunch of structs into a contiguous array (or understanding how-and-when to avoid, or not, allocation of memory in C++).

Also:

> Secondly, this seems a lot like operating over columns...

That's true. Since your apparent "update method" takes one instance from each array, you don't actually gain a ton from the contiguous nature of each array, since you're reading from many very distant locations every iteration of the loop.

You don't necessarily need to wrap up everything in one big structure and store an array of those, though; you need to consider which data will benefit the *most* from being contiguously iterated over and pack that together. It's impractical to make *everything* perfectly cache coherent in any complex project, so it's a matter of picking and choosing when you get the most bang for your buck and dealing with other cases differently. This is another place where a profiler can help you.
> 1 votes

# Answer
Ordering the data is going to depend on existing data access patterns for your application. Profile first, and see what areas of execution are taking the longest as a result of cache misses.

Once you've done that, interleaved data (array of structs) will almost certainly be better than splitting into massive arrays of a single element type. *How* you interleave the data is going to depend on your profiling research, and experimentation.

It is possible that in some cases you may want *repeat* data across different interleaved arrays. For example, while AI processing may fit transform, physics, inventory and character stats data into a cache line, the rendering pipeline may want transform, lighting state, and colour information. That means you may be better off having the transform interleaved into two different arrays, each element of which contains the appropriate goodies as just mentioned. Otherwise memory access is scattered, and cache performance suffers.

As for where your logic sits... it's mostly an illusion. I've worked in pure C for long enough now to see just how irrelevant it is. It is just an organisational tool. You can write a single monolithic class to perform all logic, you can split into subsystems, you can have entities with methods or leave that method logic to a super-controller... what matters is only that you get your flow of control right. I tend to favour an approach of "the next controller up, creates, controls and destroys that which sits below it."
> 1 votes

---
Tags: performance, storage, asset-management, data-oriented
---


title: Unity, manual culling

text:
# Question
Title: Unity, manual culling
Is there a way to for example in vertex shader cull current vertex? I have my own grass system and I would like to cull straws that are further away than some distance but I can't use camera culling because grass is drawn in chunks and it hides a whole chunk.

# Answer
> 1 votes
You cannot discard a vertex. You can discard a fragment but at that point in the pipeline you would get little to no performance benefit for discarding pixels.

You will likely need to use some sort of level of detail system for your grass. Far away grass is drawn in larger and less detailed patches with near grass being drawn in smaller more detailed patches.

---
Tags: unity, shaders, culling
---


# Question
Title: Is this Code saving performance ? It is kind of a Occlusion Culling
I wanted to do Occlusion Culling on my Scene but I just get a bunch of Errors like "Couldn't load geometry..." etc. I tried to do like another way but the same thing, the Occlusion Culling just disables the Objects the Camera dont see. I tried it with OnTriggerEnter and Exit.

I have 2 Areas one is on the left and one on the right, when the Player is walking in the first Area the Box Collider checks it and disables the Objects in Area2 but when Player is walking into Area2, Objects in Area1 disables and Different. Got the Script on both Areas that it disables a list of arrays as GameObjects.

My Question is, does this save performance ?

---

```
public GameObject[] deactivatingModels;
bool playerEntered = false;

void OnTriggerEnter (Collider other)
{

    foreach(GameObject envis in deactivatingModels)
    {
        if(other.gameObject.tag == "OcclusionCuller")
        {
            envis.SetActive(false);
            Debug.Log ("Player has entered Occuling Zone");
        }
    }
}

void OnTriggerExit(Collider other)
{
    foreach(GameObject envis in deactivatingModels)
    {
        if(other.gameObject.tag == "OcclusionCuller")
        {
            envis.SetActive(true);
            Debug.Log ("Player has left Occuling Zone");
        }
    }
}

```

# Answer
An inactive object isn't not just not rendered anymore. All other components on the game object are deactivated as well. Inactive objects aren't rendered, don't get checked for collisions and aren't updated anymore. So this should save even more performance than "normal" occlusion culling.

But you can even go a step further: Destroy the game objects in the inactive areas of your game world and re-Instantiate them at their initial positions when the player comes back. That way they don't just stop using CPU and GPU resources, but stop consuming memory as well. The drawback is that you lose the state of left areas. When world persistence is important for your game, you might want to write any information worth persisting to a file.

Keep in mind that destroying and instantiating objects are expensive operations. So you should avoid doing it every frame. You might want to place the trigger areas which cause some areas to unload and other areas to load in passageways where not much action is going to happen. If you still have visible stutter from it, you might want to do the deleting and instancing in packets in a coroutine.
> 3 votes

---
Tags: unity, c#, performance, occlusion
---


title: Simulating air pressure

text:
# Question
Title: Simulating air pressure
I am working on a space orientated game, and I have done some research on the best way to simulate gas with traditional physics technologies (Creating a lots of circles)

The only obstacle I have is how to simulate pressure. For example, if one corner of the room has lots of these little circle physics bodies, how can I make them evenly distribute? If I have a huge vacuum, what is the best way to have the particles get sucked out through the corridors etc of a room into space?

I can't think of any way to do this without iterating over every single particle against every singe other particle. Obviously, I cannot do this in a real-time simulation.

Maybe I could do this on a tile-based level?

The specific technologies I am using are Java and Dyn4j.

Thanks,

# Answer
> 1 votes
A simulation is always a number of degrees off from reality. So the question you need to first have an answer to is what degree of reality needs to be mimicked?

I could imagine a simple simulation to basically just apply a force on objects near the vacuum opening where air is whooshing out and have that force increase as the distance decreases and as the size of the hole increases. Done. For some visual flair, Animate particles whooshing out (just near the opening)

# Answer
> 5 votes
The pressure of a gas is a direct result of its particles colliding with each other and their environment, which means you can simulate pressure simply by modeling those collisions.

Particles obviously only collide with things in their immediate vicinity and so you can leverage spatial optimization techniques (simple grid, quadtree, bsp etc.) to avoid quadratically testing each pair.

# Answer
> 2 votes
I'd propose a **simplification**, where any single room in the ship (building, whatever) always carries one single air pressure only.

This should be close to reality, since if you have a room with air and

* open a door to vacuum, all air will escape instantly
* drill a small hole in the wall, it will escape slowly

In practice, there will in both cases be one single pressure in the room at any time. Air is fast, the bottlenecks (size of hole) will slow down the escaping, but not for example the mass force of air (or it will, but too little to be relevant).

The data model would be a node graph, ie. connected vertices. In the middle of each room there would be one vertex, and at each door (or hole) one. Perhaps at each corner (for example in a corridor) as well. If a door opens into a corridor, the door vertex would apparently connect to two nodes in the corridor. Imagine having these "lines" going through the entire area, potentially also through air channels etc.

Some of the vertices would have a resistance, telling how much air can pass per time unit, and ofc depending on the pressure in connected neighbour nodes. Those that have no resistance would simply be measuring points.

Then do some recursive magic to walk through the entire graph. Remember that even if it models a physical space, it is still only a data set - the graph doesn't know what the space ship looks like, it only has vertices (indeed with positions, that's how you map to physical locations), nodes and weights. The graph need not "look like" the physical room distribution! It doesn't look like anything, it's just a bunch of numbers.

The action would start by any vertex beginning to leak air, so nullify it's pressure. The next vertex (say a door vertex) would not get zeroed completely, as it has a resistance. Calculate how much it can take and remove that much from it's neighbours. Etc, you get the point.

Take "time" into the equation, to make it framerate-independant.

Maybe a few dozen, a few hundred, or less than 1000 vertices would do?

---
Tags: 2d, physics, fluid-dynamics
---


# Question
Title: Hide client-server communication from HTTP debuggers
I'm developing a mostly off-line game. However, it'll communicate with the server for the following:

* Collect data, statistical purposes (Yup, players will be notified and can opt-out).
* Trigger and generate resources for daily gifts, events, etc...

The problem is, if I used any HTTP debugger (Say, Charles Proxy) I can see everything (No encryption is being used).

I want to hide the data about daily gifts, events, etc... or else any player with malicious intent can tamper with the requests/responses as s/he sees fit (which can affect other players as well).

**Seems far-fetched?**

Actually, I wanted to apply some kind of encryption, however, I came across few games that managed to hid their activity altogether. Doing a quick research, it seems they use *SOCKS* and not *HTTP*, A thing I have a lack of experience in. Example of such games includes Clash of Clans.

So is there a practical way to achieve the desired results?

# Answer
> 1 votes
Use HTTPS. It will handle the encryption layer for you. Most networking frameworks will have some way to do HTTPS. However, setting up the certificates will be the tricky part. This article shows how to do this in java https://developer.android.com/training/articles/security-ssl.html

You can disable certificate validation making ssl much easier but that opens you up to man in the middle attacks meaning someone could point your game to their own server using dns spoofing and pretend to be your server and thier server could then talk to your sever pretending to be the game. Their sever would be getting all the traffic unencrypted breaking the purpose of encryption in the first place.

# Answer
> 0 votes
Generally speaking HTTPS should be enough against most people.

However there are tools out there which can hook the calls that do the actual encryption/decryption and render it useless in some circumstances.

You can add small encryption algorithms like blowfish on top. (Just take your messages and wrap them up there are tons of examples on the internet).

Even a totally normal XOR might protect you from casual hackers.

If you really want to do it hardcore, use different algorithms for different events (and change them every release).

Sophisticated hackers will still know their way around it. (Finding out where the web requests get sent out, using IDA for example to get the structure, hook at the right place to get the decrypted content).

To avoid this being done easily you can do crazy stuff like saving your Networking Interface encrypted in your binary and decrypting it on runtime (similar to a packer) and blocking debuggers.

It's always a question of which kind of hacker you want to stop ;)

EDIT: Also using SOCKS doesn't mean that their content is encrypted. It probably is, but it only means it isn't relying on HTTP as a protocol for communication.

---
Tags: networking, client-server, security
---


# Question
Title: Difference between "texture" vs "texture2d" in OpenGL ES?
I see many example in shadertoy use `texture`, but in the cocos2d-x, only `texture2d`.

Does `texture` use normalized coordinate and `texture2d` doesn't?
Because when I use `texture2d`, it returns wrong result.

# Answer
`texture2D` is the same as `texture`, but it's used in the older versions of glsl.

Between glsl 120 and 130 they changed the function to `texture` and made it accept every kind of samplers, not just a `sampler2D`.

There's no difference between them, so the problem is probably in your code.
> 7 votes

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


# Question
Title: What is the best (or a good) approach to "code" difficult level
I've to decide how to code enemy spawn: quantity and time. What's a good approach to do that ?

Maybe a class like this ?

```
class Level {
   int   levelNr ;
   int   soldierQty; // number of enemy soldier
   int   aircraftQty; // number of aircraft
   float maxTimeToComplete;
   ...
   ...
}

```

Then, in main code

```
   Level[100] levels;

   levels[0].levelNr = 1;
   levels[0].soldierQty = 5;
   levels[0].aircraftQty = 3;
   levels[0].maxTimeToComplete = 10; // 10 seconds
   levels[1].levelNr = 2;
   etc etc etc

```

Is it a good approach ? Is there a different way I haven't thought ?

Thanks

# Answer
> 2 votes
There isn't a perfect answer here. But one thing to note is that it isn't great to put 'magic numbers' in the code.

This is also referred to as hard coding. It would be better to get the values for the number of enemies etc from a data file by deserialising it. That way you don't need to change the code each time you need to make a change, you can just update the data file.

This makes your code more maintainable and more easily extended.

# Answer
> 1 votes
You might want to look if it is possible to calculate the numbers for each level at runtime. That's likely far less typing, less prone to errors and has the advantage that you can have infinitely many levels.

I would then have a constructor for Level which just takes the level number and calculates all the variables from it. Something like this:

```
class Level {
    int   levelNr ;
    int   soldierQty; // number of enemy soldier
    int   aircraftQty; // number of aircraft
    float maxTimeToComplete;

    public Level (int number) {
        this.levelNr = number;
        this.soldierQty = number * 2 + 3;
        this.aircraftQty = number / 2 - 5;
        this.maxTimeToComplete = 600.0f / (number + 9);
    }
}

```

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


# Question
Title: How are minimaps rendered for open worlds?
When I've created minimaps for smaller to medium levels before I would use a large texture mapped to a plane for the minimap and world map. The minimap/world map camera would then view this texture from a top down view.

For larger, open world style environments though I'm facing a performance vs fidelity issue. For example, a large environment requires a large texture to fit everything in, but at the same time the texture also needs to be a high enough resolution for when the player decides to zoom in onto a specific point in the map. I can make the map high resolution with enough detail up close but this creates quite a large texture size. Or I can make a lower res map which is more efficient but it becomes blurry/pixelated when zooming in.

Is this just a balance that I have to play with, or is there a better way to handle this? For example, creating a simple 3d mesh whose shape would act as the map. Or instead of using a texture using a vector graphic. How is this usually done?

# Answer
> 2 votes
You hit on the main two options.

1. Use a texture, and make the appropriate choices concerning trade-offs between texture size and resolution. Remember you can tile the texture so only nearby image data is loaded, as well.
2. Render the map as simplified geometry approximating 2D vector art. The balancing act you tend to run into with this approach is geometry management (particularly for curve resolution), although you can alleviate that with more modern rendering techniques designed at representing splines and other curves, in some cases.

# Answer
> 1 votes
For Night Call I had to display 105 squared kilometers in a mini map.

I chose to use a tiled based map, the map is displayed using smaller textures put together.

This technique is pretty simple to understand and not really complex to execute. Also, if used with an efficient pooling, it can be very efficient.

Example:

---
Tags: textures, sprites, vector, maps, mesh
---


# Question
Title: How to render an animated gif to the screen using SDL2?
So, I have an animated gif that is 5 frames (not the same as what is seen in this tutorial). Upon opening, my gif is already animating, unlike the png in the above tutorial. How can I render it to the screen using SDL2?

The code I have now only renders the gif when I close out the window, and even then, it is only for a split second and I can only see one frame. How can I improve my code?

This is the code that implements the game's main loop:

```
#include "game.h"

int main( int argc, char* argv[])
{
    init();

    SDL_Texture* texture = IMG_LoadTexture(renderer, "male_base-test-anim.gif");
    SDL_Rect base;
    base.x = 0;
    base.y = 0;
    base.w = 948;
    base.h = 335;

    bool quit = false;

    SDL_Event e;

    while( !quit )
    {
        //Handle events on queue
        while( SDL_PollEvent( &e ) != 0 )
        {
            //User requests quit
            if( e.type == SDL_QUIT )
            {
                quit = true;
            }
        }
    }

    SDL_RenderClear(renderer);
    SDL_RenderCopy(renderer, texture, NULL, &base);
    SDL_RenderPresent(renderer);

    SDL_DestroyTexture(texture);
    texture = NULL;
    exit();
    return 0;
}

```

# Answer
First of all, you want to move your rendering inside the game loop:

```
while( !quit )
{
    //Handle events on queue
    while( SDL_PollEvent( &e ) != 0 )
    {
        //User requests quit
        if( e.type == SDL_QUIT )
        {
            quit = true;
        }
    }

    SDL_RenderClear(renderer);
    SDL_RenderCopy(renderer, texture, NULL, &base);
    SDL_RenderPresent(renderer);
}

```

Now the first frame of the animation should be visible always when the window is visible.

SDL doesn't support playing animations from .gif files. You want to either follow the advice in this SO answer which addresses the issue or split your .gif frames into separate image files that contain a single frame (or into a spritesheet) and write your own animation system on that, either display a new texture if you choose to use separate images or modify the source rectangle if you went with the spritesheet approach.
> 4 votes

---
Tags: animation, rendering, sdl2
---


# Question
Title: What is GPU instancing and what are its differences in comparison to standard instancing?
I have been reading a lot of debate on a new feature that will be in Unity 5.4: GPU instancing. I understand the importance of instancing in general, both in terms of saving memory and draw calls.

However, even after doing some reading, I still couldn't understand what exactly are the differences between GPU instancing and non-GPU instancing - and, more importantly, where the alleged GPU advantages in terms of performance come from.

Thanks for your knowledge and for any references.

# Answer
Very simple: "non-GPU" instancing doesn't exist. Doing more work on the GPU is the whole point of instancing.

Moreover, instancing improves performance by reducing the amount of data that has to be pushed to the GPU and hopefully by reducing CPU computations, at the price of doing more work on the GPU: it doesn't have "alleged GPU advantages".
> 2 votes

---
Tags: performance, gpu, instancing
---


# Question
Title: How can I get rid of "missing DLL" problems?
I made some games with Visual C++ 2015 and OpenGL. When I ran it on my machine there was no problem, but when I ran it on other machines it shows that some DLLs are missing. I want to know how to make sure that it won't happen next time and what things should I consider so that I can avoid file missing problems?

# Answer
> 21 votes
You need to install the redistributables for the version of Visual Studio you used on any machine that wants to run the executables, e.g. https://www.microsoft.com/en-us/download/details.aspx?id=48145 for VS2015. You may also need redists for DirectX or other components.

Applications' installers generally install all the redistributables for any of their dependencies. You can make such an installer with InnoSetup, NSIS, WIX, or various other tools.

It's possible to make executables that don't need any redistributables, but you're then limited to a subset of core Windows functionality, which generally is not enough to make any kind of meaningful game or large application. The installers themselves are an example of applications that don't need any dependencies to run.

# Answer
> 7 votes
I use Dependency Walker to track down missing DLL's:

> Dependency Walker is also very useful for troubleshooting system errors related to loading and executing modules. Dependency Walker detects many common application problems such as missing modules, invalid modules, import/export mismatches, circular dependency errors, mismatched machine types of modules, and module initialization failures.

---

There is also a compile-time option in VS to statically link DLL's:

* Statically linking means the DLL's are included in the EXE file.
* Statically linking increases the size of the EXE file.
* Statically linking means this version of the DLL will always be used.
* However, statically linking also means you will never have a problem with missing DLL's.

# Answer
> 6 votes
For Visual C++, you have a few choices of how to handle the redistribution: run an EXE from your installer (with admin rights), use a MSM merge module with your MSI installer, or even side-by-side DLLs. See MSDN for the details.

The bigger issue is OpenGL. The only version of OpenGL that's included with Windows is a OpenGL 1.5 software renderer. Anything else requires a third party ICD to be installed.

> This is one of the reasons why so many Windows games use DirectX instead since it's included with the operating system. See Direct3D 11 Deployment for Game Developers and Not So Direct Setup.

# Answer
> 1 votes
Disclaimer: This is a *workaround*, not a *solution* to your answer, but still, a very viable possibility.

If you want to be absolutely sure there are no dependencies from VS itself - but it comes with its own drawbacks - in the code generation settings you can choose to go with Multi Threaded (MT) / Multi Threaded Debug (MD) (for debug builds) instead of MT DLL (MTd) / MT Debug DLL (MDd).

What are the drawbacks?

* It does increase your executable size and your binary (although if you are making a game this is probably negligible)
* compiled in this way won't benefit from the runtime dlls updates. (e.g. if Microsoft releases VC++ 2015 SP2, SP3, SP4 etc..) But that's up to you.
* More RAM usage (also negligible) because you don't re-use existing/loaded code (DLLs)
* You need to be sure all libraries you link are compiled against the same runtime, else linking might fail, or interesting runtime errors might occur (probably not, but it did happen to me once in a lifetime in a legacy project that has been updated to the newest VS)

And what are the pros?

* your executable won't have "external" dependencies from VS itself (no msvc\*.dll requirement).
* some people see this as a performance increase because you are eliminating DLL call overhead, while this is theoretically true, the improvements are negligible in practice

Check this link for a more elaborate explanation and for the pit- and downfalls you might encounter with using a static runtime.

Another *workaround* would be to put all the required DLL's where your binary is. Your application won't benefit from updates (to the runtime libraries) but that's it.

The real solution is to distribute the application in release/non debug dll mode (MTd) and supply the correct VC++ redistributable installer (and any other library installers that you might use, e.g. OpenAL, DirectX9, PhysX), and let the user run that before running your application (as other answers pointed out).

Also make sure to let the user know he/she possibly needs to update his/her GPU drivers (as those contain multiple runtimes for many applications too, e.g. OpenGL, Vulcan).

# Answer
> 0 votes
My solution was to copy and paste the DLL that caused the error into the folder where the .sln file is located in visual studio. After the `#include` section, I wrote `#pragma comment (lib, "lost DLL name with .dll")` and resolved it!

Note: I solved the problem that I encountered with a third party library (vulkan api) DLL. Maybe it's not known but 90% will work good luck :)

---
Tags: c++, visual-studio
---


# Question
Title: How to fix stretched splash image in Unity?
I'm trying to add my own splash on my Unity project. However, when I implement it, the splash is stretched vertically, real bad.

Here is the screenshot:

While the original splash is:

I'm not altering the settings for the sprite that much:

How to fix that problem? I'm using a 1080x1080 PNG file for the splash and Unity 5.5.0f for building the application. Altering the resolution of the PNG results no luck. Am I missing something important here?

EDIT: Sorry for the late mention, but I've made the border on the sprite editor. Still no luck.

# Answer
> 6 votes
Alright. So I just stumbled across the Import Settings, and found that the solution to this problem is just by setting the *Mesh Type* into **Full Rect**, nothing to do with the Sprite Editor. Newbies can miss this, because by default, Unity set the *Mesh Type* into **Tight** instead.

Actually, my bad I didn't experimenting with the Import Settings last time, so I apologize for this. But I guess it's a bit worth mentioning anyways.

---
Tags: unity
---


# Question
Title: Clean code structure for dynamically rendering strings & numbers
I am currently working on the rendering aspect of my game. The code is currently organized in this manner:

Classes: G\_Texture:

```
class G_Texture
{
public:
    G_Texture();
    G_Texture(SDL_Texture*);

    ~G_Texture();

    virtual void render(SDL_Renderer*);
        //Render

    SDL_Rect dst; // Destination rectangle to render the texture

};

```

G\_Text:

```
    class G_Text : public G_Texture
    {
    public:
        G_Text();
        G_Text(std::string, G_BitmapFont*);
        ~G_Text();

        G_BitmapFont*  font;
        std::string text;

        void render(SDL_Renderer* renderer);
    };

G_Image:

class G_Image : public G_Texture
{
public:
    G_Image();
    G_Image(SDL_Texture* text);
    ~G_Image();
    void render(SDL_Renderer*);

    SDL_Texture* texture; // Texture source
    SDL_Rect* clip; // Sub-section of texture to draw
    SDL_RendererFlip flip;
};

```

What I want to do now is add three features: 1) Dynamically changing string I want to dynamically render a changing string. If for example I have a character in my game with a continuously changing name, what approach should I take to render that changing name? Do I create a new class for dynamic string, which holds a string pointer?

2) Dynamically changing number So this is the same as (1), except now I want to update a number (int, double, etc...) into a string. Do I create a new class specifically for holding an int pointer? I feel like making all these classes wouldn't be very elegant. If I wanted to display anything other than an int I would have to make a new class...

3) Dynamically changing image width (Ex health bars) If I want to create a health bar whose size depends on the health of a character, what is the best approach. My current thought is to create another class for health bars, which would have a pointer to the character. Once again this doesn't seem very elegant or reusable, as I would have to create new classes for each different component requiring different pointers.

I apologize if this is confusing. I'm new to game development and stack exchange.

# Answer
There are two significant issues that I'd like to point out with your approach. One is separating concerns; the other is retaining state.

First, `G_Texture` is a resource class. It links a file in the filesystem to a representation of a texture in memory.

If you look at the example `G_Texture` class you have proposed, what does `render` do? Does it draw the whole texture at a given coordinate on the screen? Can you pick a part of the texture to render? Can you rotate or scale it? You picked some default behavior for `G_Texture::render`, and while you picked a reasonable and common behavior, it's arbitrary. What does it mean to render a texture, when a texture can be used so many ways?

What I'm saying is that your `G_Texture` class should be responsible for holding onto an `SDL_Texture *` and destroying it at the right time, and that's it. There are lots of ways to use a texture; don't pick one and stick it in the class and then override it in lots of confusing ways in other classes. Let other classes *use* a texture however they want to. Maybe they use two textures. Maybe they use a texture and a text file (a list of frames in an animation).

`G_Text` and `G_Image`, and e.g. `G_DynamicString`, `G_DynamicNumber`, `G_ResizeableImage` are all behavior classes. They describe special ways to draw a `G_Texture`. They could inherit from an interface, `G_Renderable`, instead of `G_Texture`.

I think you're finding this subclassing messy because you see that the "is-a" relationship isn't right. `G_Text` is not a special case of `G_Texture` -- rather, it uses a texture. What if your `G_Text` requires multiple images for all the glyphs? What if you want a `G_ResizeableAnimatedImage`?

A better approach is a "has-a" relationship. The classes that define behaviors have a reference (or a shared pointer, or a resource handle) to the resources that they need.

There are lots of different ways to work with textures, like most resources. If you separate resources and behaviors, by

* making the resource "just a container" that is concerned with its own lifecycle -- handling its own creation/destruction and properties (width, height), and
* making other classes that accept resources and know how to do things (e.g. draw text)

your code will be easier to work with in the long run.

Now, retaining state:

A game fills the screen every frame, and the contents of the screen are thrown away. The game doesn't know or care whether a string is dynamic or static; at some level, a graphics API still has to say "draw this string" every frame.

There are definitely optimizations to be made, but I don't really understand your distinction between "Text" and "DynamicString" at this point. If you have a class that knows what to do when you call `setText`, that covers both cases. Since you mentioned a pointer, I am guessing that you want to pull the game data in, every frame; a simplistic way to do this would be to supply a method that takes a lambda `const string&(){}`. That function can pull data from anywhere and you can make it take an integer, a string or whatever else from the closure.

Hope this helps.
> -1 votes

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


title: Unity2D: Click to move Snake Game

text:
# Question
Title: Unity2D: Click to move Snake Game
I'm trying to create a click to move snake game on mobile but I'm having problems with the whole click to move functions and adding a body part every time my snake eats an apple. I want to make the click to move smooth you know like an actual snake is slithering around and when the snake eats an apple, I want to add another body part to my snake (maximum of body parts should be 5). Can anyone point me into the right direction or give me an example of what to do, thank you!

# Answer
The "smooth slithering" could use some more explanation, but assuming you want more gradual turns than the normal 90 degree snake game, you could instead deal with simply a *turn left* and a *turn right* event from the player input. This would apply a rotation to the velocity vector of the head, such as one degree per update. This is different from your typical snake game where input determines the absolute direction, not the change in direction.

This control setup may be the best for mobile where you can simply track tap/hold events on each half of the screen. If I press my left thumb to the left side of the screen, the snake will turn left. If I press the right side with my right thumb, the snake gradually turns right. If I lift both my thumbs, the snake goes straight.
> 1 votes

---
Tags: unity
---


# Question
Title: Instantiate and launch prefab that's overlapping player?
I’m very new to Unity and C#. I’m trying to create my first game and I have now invested about 15+ hours trying to find solutions to this issue...I’m stumped!

My player sprite (blue square) needs to launch a prefab sprite (red circle) of similar size ‘appearing’ to originate from itself. Here is a GIF of what I have so far...I **don’t want** the blue cube to collide and go flying.

After clicking and dragging on Player (drag-to-aim) via OnMouseDrag to set the target vector, I’m trying to Instantiate a prefab sprite (Dynamic RigidBody2D, CircleCollider2D) using the Player sprite’s position (a Dynamic RigidBody2D, BoxCollider2D) and have it APPEAR to be originating from inside the Player object. Launch is triggered via function called in OnMouseUp. Both objects should immediately come under control of Physics to collide with the environment which will include other moving RigidBody2D objects later. Targeting should allow 360 degrees to include straight into an obstacle allowing rebound effect.

Here is some excerpts of my code:

```
using System.Collections;
using UnityEngine;

public class Teleportation_Grenade : MonoBehaviour {

/*
    This script is attached to Player and requires_
    projectile prefab.

    tested with thrust set between 100 and 200.
*/

    public float thrust;
    public Transform prefab;
    public LineRenderer playerShotLine;

    private Vector2 playerToMouse;
    private Vector2 targetVector;

//...

    void OnMouseDrag()

    {
        Vector3 mouseWorldPoint = Camera.main.ScreenToWorldPoint (Input.mousePosition);
        Vector2 playerToMouse = mouseWorldPoint - transform.position;
        mouseWorldPoint.z = 0f;

        playerShotLine.SetPosition (0, transform.position);
        playerShotLine.SetPosition (1, mouseWorldPoint);
        playerShotLine.sortingOrder = 3;

        //opposite direction of line renderer
        targetVector = -playerToMouse;

    }

    void OnMouseUp()

    {
        SpawnPrefab ();
    }

    void SpawnPrefab()

    {
        Instantiate(prefab, new Vector3(transform.position.x, transform.position.y, 0), Quaternion.identity);

        prefab.GetComponent<Rigidbody2D> ().AddForce (targetVector * thrust, ForceMode2D.Impulse);
    }
}

```

This is only one of many, many iterations. It's the gist of it though. I appreciate any insight from the community.

# Answer
Ughh!...Facepalm!

As several comments pointed out, I was indeed **misusing the Physics2D layer collision matrix** and WAY, WAY overthinking the solution! As I pointed out, I'm very new to Unity so I didn't realize the extent to which you can manipulate layers.

**Here's what I did:**

1. Created new layers (not "sorting layers") for each object type, background, platforms, player and projectile
2. Updated my projectile prefab to use the "projectile" layer (drag into hierarchy \> on object Inspector...change layer on object \> Apply \> Delete object from hierarchy)
3. Assigned each object to it's appropriate layer (same as prefab but don't delete)
4. Open the Inspector panel with the Physics2D Collision Matrix Physics 2D Settings (menu: Edit \> Project Settings \> Physics 2D)
5. In the Inspector Collision Matrix, set all NEW layers to collide by placing a checkmark in the intersecting boxes, making sure that "Player" and "Projectile" layers would not collide (leave unchecked)
6. Save scene, Play, test

This produces the desired affect!
> 3 votes

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


title: Applying voronoi to a 2D tile map

text:
# Question
Title: Applying voronoi to a 2D tile map
I'm planning to use Voronoi cells to break up an infinite 2D (procedurally-generated) tile map into biomes. I've been reading a bunch of tutorials and introductions to voronoi, and I understand how cells are calculated based on points, but I'm failing to understand how to apply this to an infinite 2D tile map.

1. Voronoi cells are calculated from a series of points, but given a 2D tile map, how do I consistently generate a list of points? I can randomly choose points but this has to be completely reproducible with the given RNG seed.
2. How can I calculate cells for an infinite map when every Voronoi implementation I can find requires a bounding rectangle?

# Answer
> 1 votes
Break up the world into chunks or larger areas. They should have a uniform size, they should store their positions with a short, and each of them should contain some points.

Let's convert it to a seed to give to the random function. Every variable has a minimum value, for signed types this is negative. For example the minimum value of an integer is -32768. If you add this to the coordinates of the chunk, you'll always get a positive value.

You'll now have 2 coordinates, one on the x axis and one on the y axis, and both of them are positive.

You can concatenate this into an int by doing some bitwise operations:

```
x << 16 & y

```

This is your seed. This'll be unique for every chunk. Now you can set `Random.seed` to this and get the same results every time.

When you generate your biomes in a chunk, you need to generate the points in the chunks next to the current one, and use the resulted points to calculate the biomes in the current chunk.

I'll leave it to you how you generate your points, but a possible solution would be to first generate how many points there are in that area, then generate the position of the points and the type of the point (what chunk it resembles).

The only problem with this is that it only allows you to have 65536 chunk in each direction. You can solve this by using ints and you concatenate them into a long, but I haven't found a way yet to use a long as a seed.

---
Tags: unity, c#, procedural-generation
---


# Question
Title: A more data oriented design approach to Entity Component System game engine
I'm creating my first c++ game engine project (for learning purposes) and in it I've attempted to implement an entity/component system utilizing some data oriented design principles while also not fully giving up my object oriented way of thinking. I have data only component structs:

(Example)

Position.h

```
struct Position
{
    Vector3D position{ 0.0f, 0.0f, 0.0f };
};

```

which are stored in arrays within my SceneManager class:

SceneManager.h

```
class SceneManager
{
    //Some other code....

private:
    //So only systems have access to component arrays
    friend class BGraphics::RenderSystem;
    friend class BInput::InputSystem;
    friend class BPhysics::MovementSystem;
    friend class BPhysics::CollisionSystem;
    friend class BAudio::AudioSystem;

    //Component arrays. Each index of the arrays represents an entity.
    //So positionComponents.at(1) represents entity 1's position.
    Array<Position, 10> positionComponents;
    Array<Velocity, 10> velocityComponents;
};

```

As you can see, my engine's system classes are the only ones who have access to the component arrays and so every system can process components. There are some other things involved in this setup that I don't want to get too deep into for simplicity's sake. My issues are as follows:

Each system accepts a SceneManager reference in an Update function like so:

```
RenderSystem::Update(SceneManager& scene)
{
   //Use scene component arrays necessary for processing...
}

```

What I'm struggling with is right now my components seem like global variables in that every system has access to them and can change their state. Though it seems like a lot of data oriented design involves structs like these with public data for which other functions can operate on, changing their state. With that being said, is there something I'm missing with my implementation that would make my component data more encapsulated and safer? How am I suppose to think about handling data in a safe way when utilizing data oriented design? Any clarity is appreciated.

# Answer
> 10 votes
## What's an object?

What we call an object or an entity depending on the model is, fundamentally, made of two parts: data, and behaviour. Game objects *have* properties and *do* things.

Let's take a simple, free-falling ball as an example. A ball's data is:

* Its current position
* Its current speed

Our ball can do a **single** thing: fall. When a ball falls, it does the following (let's assume simple Euler integration here):

* Integrate the global gravity field vector into its speed (accelerate)
* Integrate the resulting speed into its position (actually move)

Now let's model this ball, first with OOP, then with an ECS.

## OOP

In object-oriented programming, instances contain their data as members:

```
struct Ball {
    vec2 _position, _speed;
};

```

Then comes the principle of encapsulation. Encapsulation is about simplifying the interface of an object: the single behaviour of our ball will be modeled by a member function, which contains the code described above. Users of the class will then be able to make the ball fall (enact its behaviour) without meddling with its data. The `fall` function knows what it's doing, and all is fine.

```
struct Ball {

    void fall() {
        _speed += global.gravity * global.deltaTime;
        _position += _speed * global.deltaTime;
    }

    vec2 position() const { return _position; }

private:
    vec2 _position, _speed;
};

```

So this is our (contrived) API: users can query a ball's position, and make it fall. Note:

* There is no getter for `_speed`. Not all of an object's data (what it needs to be able to function) is part of its API (what its users need to know about it).
* There are no setters. Teleporting or receiving impulses are *not* behaviours of our ball according to our spec, only falling is.

Yes, that makes it quite a useless ball, especially since I omitted the constructors. But it's fine for an example :)

## ECS

Let's move on to the Entity Component System model of our ball. This will be fuzzier, since unlike OOP, C++ does not provide native syntax for ECS concepts. But we'll make do with pseudocode.

Our ball, again, is made of two components, position and speed:

```
entity Ball {
    comp::Position;
    comp::Speed;
};

```

As you know, the components are only modifiable through systems. So let's add a system.

```
system Fall {
    updateEntity(comp::Position &pos, comp::Speed &spd) {
        spd += global.gravity * global.deltaTime;
        pos += spd * global.deltaTime;
    }
};

```

Voilà! once you have transcoded that into your ECS's syntax, you can create a ball and make it fall. This time the speed of the ball is readable from the outside -- I've not seen any ECS framework include restrictions on that so far. But only a `system::Fall` can modify the ball's state.

Did you notice? This is encapsulation. The system looks very much like a member function: it knows what to do, and it does it with a simplified API. The user of the system who calls it upon the entity still does not modify the data himself.

The difference between the function and the system is:

* The `Ball::fall` function says "I know how to make a ball fall";
* The `system::Fall` system says "I know how to make anything with a position and a speed fall".

ECS modeling essentially enables creating duck-typed objects dynamically. An object's data is inside its components, and its behaviour is inside the systems that you call upon it. You can add and remove components and systems as if you could add and remove member variables and member functions, at runtime.

## Wrap-up

So the answer to your question is **no**: the ability for systems to access the components is **not** a breach of encapsulation.
While instances of different C++ classes *are* accessing each other's states, none of them are separate "objects": the actual, conceptual *game object* (a.k.a entity) we're caring about is made of the *union* of its data (components) and behaviour (systems), which interact much like member data and member functions in a traditional OOP class.

---
Tags: c++, architecture, component-based, data-oriented
---


# Question
Title: Rule based procedural terrain generation
How one generates procedural terrain is pretty straight forward. But once you setup your terrain you don't really have a fine level of control where which details will go.

One solution I can think of is to store rules as functions, i.e. Square, circle, etc., which will override rules in the area. For example, in mountains terrain we could place a function which will make them flat or terraced.

What I have trouble figuring out is how to store those functions (assuming terrains can be in principle infinite or at least planetary scale). Should they be placed within existing coordinate system, or stored locally to terrain ?

I seen something like that done in Star Wars Galaxies, but it's really hard to find any details about implementation of system.

# Answer
> 1 votes
I would recommend you to use a functional and hierarchical model. Have terrain generator functions which either generate a requested chunk of terrain geometry themselves or delegate parts of it to other terrain generator functions.

A terrain generator function should take these parameters:

* `parent`: terrain it is generated from
* `seed`: the random number generator seed for the sub-terrain it should generate
* `quad`: the three-dimensional chunk the terrain is supposed to fill.

The root `generateTerrain` function for the whole world would determine the type of terrain for each chunk, and then call the appropriate function to generate it, like `generatePlainTerrain`, `generateMountainTerrain`, `generateOceanTerrain`, etc.

Those functions would then either generate the requested quad of terrain geometry according to their own rules, or could also delegate parts of the terrain to further terrain generation functions. So the `generatePlainTerrain` function could choose to delegate a small part of it to `generateVillage` which then delegates to `generateHouse` which then delegates to `generateBedroom`.

---
Tags: procedural-generation, terrain
---


# Question
Title: What are things that you look for when hiring a composer to make music for your games?
When you are looking to hire a composer to make music for your games, what should you look for?

There is a large library of “stock” sounds that anyone/everyone has access to. So what values and skills would a composer need to provide to a team in order to compete with just using music and sound effects from stock websites?

# Answer
> 3 votes
The problem with stock audio is that they are often overused. It can be very confusing for a player when they hear a piece of music in your game which they recognize from media related to a different IP. This can be a real immersion-breaker, because they will immediately wonder "where did I hear this before?" instead of staying concentrated on your game. Background music is supposed to increase immersion, not break it, so this is very counter-productive. They might even assume you stole the track from the other media, even if you just got it from the same source for the same price as they did. So hiring a composer who creates exclusive music can often add a lot of value to a game.

Every development team is different and would have different criteria about who to hire. But some aspects nearly every team would put value on are:

* **Understanding the unique needs of game music:** Game music must be subtle and not distract from the gameplay. It must (usually) loop flawlessly. It must not become annoying even if listened to for hours. And many more aspects which would be material for a new question.
* **Versatility:** Games often have very diverse soundtracks with lots of different kinds of music for different situations. A composer who can only produce one genre of music will usually not do.
* **Being open to changes:** Game music needs to fit the visuals, the narrative and the gameplay. All can change over the course of a project. That means a good composer must be able and willing to change their work in order to better work with the rest of the game. I once worked with a composer who had their "artistic vision" and weren't willing to compromise in any aspect of it. So they insisted that their background track for a menu where the player rarely spent more than 20 seconds must have a 40 second long intro. Needless to say that we went separate ways soon.
* **Reliability and Commitment:** You don't want your composer to stop delivering the missing tracks when your are almost finished with your game.
* **Price:** No reason to deny it. Many games are developed on tight budgets and are limited in what they can pay for music.

---
Tags: sound, music
---


# Question
Title: Unity application freezes on ios at pause
When I play my game made with Unity on iOS device, and press the home button or let the screen close by time or by pressing the power button and then try to come back to the game, the game freezes immediately. This does not happen always, only when there's certain things happened in the game in the current session. I have found nothing in common in between these situations. If those events have not happened in the current session, I can go to home screen and play other games and come back to the game and continue where I left without issues.

I have tried debugging on xcode, with no output whatsoever in the console regarding this issue. XCode reports 200mb memory usage and Unity profiler reports roughly 300mb memory usage when going to the pause state, and nothing happens when coming back to the game. We have had memory issues previously which we have been optimizing a lot lately, but this particular crash is still persisting. Android works fine, whaterver the device memory capacity is.

I have been trying to google for this type of iOS crash, with no luck. I'm asking here if someone might have some advice or direction for me to go to.

EDIT: I updated the question to match my current situation. I previously had some code in this question and talks about memory issues, which I have found out to have nothing to do with the problem at hand.

What happens according to the debug console in XCode:

1. Home button is pressed
2. OnApplicationPause(true) gets called
3. One Update() gets called
4. GameAnalytics detects a status change (headingToBackground event) and ends session
5. User is at home screen, resuming game by tapping on the game icon
6. GameAnalytics gets a headingToForeground event and restarts the session
7. Nothing else happens after that

This makes me want to point my finger at GameAnalytics, but why it works sometimes, just not after these specific events?

# Answer
> 1 votes
By disabling Facebook application event sending the problem went away, so it was Facebook SDK for Unity 7.9.0 that was causing the freeze.

Edit: That was for Unity 5.5.1f1. When building on Unity 5.5.2f1 Firebase 1.1.0 seems to be causing similar problems, while Facebook SDK 7.9.0 works fine.

---
Tags: unity, ios, mobile, xcode
---


title: Creating character for lumbaryard

text:
# Question
Title: Creating character for lumbaryard
What I need to do if I want to create character for cryengine/lumbaryard?

# Answer
Well, the easiest way to create a character to import into CryEngine or Lumberyard is to create a 3d model in Blender, put in a skeleton, animate it, and then import it into CryEngine or Lumberyard.

If you intend to create a humanoid character, you can check out MakeHuman.

There are a number of great tutorials on YouTube, which I suggest you search instead of asking here on StackExchange.

Hope this helps you!
> 1 votes

---
Tags: character, 3d-modeling, character-development
---


# Question
Title: How can I stop certain keys from being prioritized in a 2D platformer?
I am currently working on a 2D platformer in Monogame. I have implemented WASD and arrow keys control, but because of the ordering of the if statements, the D key is always executed last if down, making the character flip the wrong direction.

```
if (Keyboard.GetState().IsKeyDown(Keys.Left) || Keyboard.GetState().IsKeyDown(Keys.A))
{
    if (Velocity.X > -MaxVelocity)
        Velocity.X -= Acceleration.X * time;
    spriteEffect = SpriteEffects.None;
}
else //Deceleration
{
    if (Velocity.X < 0)
        Velocity.X += Acceleration.X * time;
}

if (Keyboard.GetState().IsKeyDown(Keys.Right) || Keyboard.GetState().IsKeyDown(Keys.D))
{
    if (Velocity.X < MaxVelocity)
        Velocity.X += Acceleration.X * time;
    spriteEffect = SpriteEffects.FlipHorizontally;
}
else //Deceleration
{
    if (Velocity.X > 0)
        Velocity.X -= Acceleration.X * time;
}

```

Is there a way to prioritize the key that is pressed last, as well as only performing one every update cycle?

# Answer
> 1 votes
Have the key pressed specify a target velocity then use that value to determine the direction facing and acceleration.

```
float targetVel = 0.0f;
// accumulate the user input
if (Keyboard.GetState().IsKeyDown(Keys.Left) || Keyboard.GetState().IsKeyDown(Keys.A))
{
    targetVel -= MaxVelocity;
}
if (Keyboard.GetState().IsKeyDown(Keys.Right) || Keyboard.GetState().IsKeyDown(Keys.D))
{
    targetVel += MaxVelocity;
}

// only change movement direction if a single directional key is pressed
if (targetVel != 0.0f) {
    spriteEffect = targetVel > 0 ? SpriteEffects.FlipHorizontally : SpriteEffects.None;
}

if (Math.Abs(targetVel - Velocity.X) <= Acceleration.X * time) {
    // if accelerating would move past the target velocity, then just set it directly
    Velocity.X = targetVel;
} else {
    // Move the velocity towards the target velocity
    Velocity.X += Accleration.X * time * Math.Sign(targetVel - Velocity.X);
}

```

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


title: Power regenerate after 3 seconds?

text:
# Question
Title: Power regenerate after 3 seconds?
I work on script that makes an object with a "sprite" power moves faster. Like "Dark souls". Here is my script:

```
private float sprit = 100.0f;
public float spritTime;
public bool spritsBool;

void Update() {

    if (Input.GetKey(KeyCode.D) && spritsBool == true) {
        spritTime --;
        Debug.Log(" run ");
    }

    if (spritTime >= sprit) {
        spritTime = sprit;
    }

     if (spritTime <= 0) {
        spritsBool = false;
        spritTime = 0;
    }
    else {
        spritsBool = true;
    }

    StartCoroutine("wait_sprit");

} // end update

IEnumerator wait_sprit() {
    yield return new WaitForSeconds(3);
    spritTime ++;
}

```

It's counting over 100, not waiting for 3 seconds to regenerate. Help me please to solve this ?

# Answer
I'm guessing you want something that allows the object to move faster for a short period of time, then must wait before it can move faster again. The below script would allow you to move faster for 10 seconds, then require 3 seconds wait before again moving fast for 10 seconds.

```
private float maxSprint = 10f;
public float sprintTime;
bool resetting = false;

void Update() {

    if (Input.GetKey(KeyCode.D) && sprintTime > 0) {
        sprintTime -= Time.deltaTime;
        Debug.Log(" run ");
    }

    if (sprintTime <= 0 && !resetting) {
        resetting = true;
        StartCoroutine(wait_sprint());
    }

    sprintTime = Mathf.Clamp(sprintTime, 0, maxSprint);

} // end update

IEnumerator wait_sprint() {
    yield return new WaitForSeconds(3);
    spritTime = maxSprint;
    resetting = false;
}

```
> 1 votes

# Answer
You start that co routine every update meaning that, after a 3 second delay, you will be increasing spritTime once every frame. Perhaps you mean to be that coroutine in the first if statement after you decreased spritTime
> -2 votes

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


# Question
Title: Adding components to the correct game object
I created a `MonoBehaviour` with a `LineReader`, to draw multiple lines. I'm attaching radius indicators for when I debug enemies in my game.

The circle is rendered around my Enemy as expected; however, I've noticed that the `LineRenderer` is attached to my `Enemy` game object. It seems like `AddComponent` binds to the parent `gameObject`, which in this case is `Enemy`.

Is there any way to attach the `LineRenderer` to my `RangeIndicator` instance?

---

This is my `Enemy` script:

```
[System.Serializable]
public struct RangeIndicatorData
{
    public Color RangeColor;
    public float Radius;
    public string Name;
}

public class Enemy : MonoBehaviour, IMovable, ITargetable
{
    public RangeIndicatorData[] RangeIndicators;
    public bool DisplayRangeIndicators = true;

    void Start()
    {
        if(DisplayRangeIndicators)
        {
            for(uint i = 0; i < RangeIndicators.Length; i++)
            {
                gameObject.AddComponent<RadiusRenderer>();
            }
        }
    }

    void Update()
    {
        if(DisplayRangeIndicators)
        {
            RadiusRenderer[] renderers = gameObject.GetComponents<RadiusRenderer>();

            int i = 0;
            foreach(RadiusRenderer renderer in renderers)
            {
                RangeIndicatorData indicator = RangeIndicators[i];
                i++;
            }
        }
    }
}

```

---

This is my `RadiusRenderer` class:

```
public class RadiusRenderer : MonoBehaviour
{
    public LineRenderer lr;

    public void RenderPoints(float radius, Color32 c1, Color32 c2)
    {
        lr = gameObject.GetComponent<LineRenderer>();

        if(lr == null)
        {
            lr = (LineRenderer)gameObject.AddComponent<LineRenderer>();
        }

        // ...

    }
}

```

# Answer
> 1 votes
`gameObject` points to the game object of which `this` instance of the script is attached to. In short, your adding `LineRenderer` to the game object associated with the `RadiusRenderer` script, which you have added to the game object associated with the `Enemy` script. There is no parent association, in this context, except for the association you provide in your logic.

---

The simplest solution is to create a hard reference to the game object for which you wish to attach your component. You can not necessarily do this directly from your `RadiusRenderer` script, as you may instantiate it by code, and thus do not have access to that instance via the Inspector.

Instead, provide the reference in `Enemy`, and pass it to `RadiusRenderer`. Ensure the instances that *are* created in the Inspector have their `rangeIndicatorInstance` set via the Inspector, too.

```
public class Enemy : MonoBehaviour
{
    // link this reference up via the Inspector.
    public GameObject rangeIndicatorInstance;

    void Start()
    {
        if(DisplayRangeIndicators)
        {
            for(uint i = 0; i < RangeIndicators.Length; i++)
            {
                // We need to make reference to each instance..
                RadiusRenderer radiusRenderer
                    = gameObject.AddComponent<RadiusRenderer>();
                // so we can pass our reference.
                radiusRenderer.rangeIndicatorInstance = rangeIndicatorInstance;
            }
        }
    }
}

public class RadiusRenderer : MonoBehaviour
{
    public GameObject rangeIndicatorInstance;

    public void RenderPoints(float radius, Color32 c1, Color32 c2)
    {
        // Now, all we have to do is add the component to our range indicator
        // game object, instead of our radius renderer game object.
        lr = rangeIndicatorInstance.GetComponent<LineRenderer>();

        if(lr == null)
        {
            lr = (LineRenderer)rangeIndicatorInstance.AddComponent<LineRenderer>();
        }
    }
}

```

---
Tags: unity, gameobject
---


title: How should I archive public chats?

text:
# Question
Title: How should I archive public chats?
I am wondering about how public chats can be saved and archived for future reference by developers? Let's say I was a developer for a game with a public chat system and I wanted to make sure I could look up and read a chat from ten years ago?

# Answer
The actual archiving is the same as with any other data. Find a format to serialize it in, convert it to that format, then write it to disk. This could be just writing it out as text, or writing it out in some structured way. A few things to keep in mind:

1. Ensure you have unique user IDs or a corresponding backup of account data to go with the chat log, so you can associate a message with whoever posted it, even across a user renaming their account or changing their e-mail address.
2. If you need to keep statistics, maybe record them when you write out the data, so you don't need to recalculate them for the whole archive every time.
3. Familiarize yourself with the data protection, data retention and required disclosure laws of the countries your game is used in. In particular, keep in mind that even in-game chat may contain information that could be security relevant (even if it's just someone accidentally posting their password).

So make sure you encrypt your logs appropriately and restrict access to them. The easiest way to avoid data leaks is usually to *not* keep data very long. I.e. keep data for a week or so (whatever is enough time for you to access abuse/fraud/harassment reports), and then get rid of it if it is not flagged as involved in a dispute. Alternately, anonymize your data after a while so it is still usable for your statistics, but doesn't contain any e-mail addresses or user IDs anymore.
4. Make backups of data you need to keep. It's easy to lose a server or whatever.
> 0 votes

# Answer
Simply dump the chat records to a text file and archive them like you would any other important piece of system data. This probably means rotating and redundant backups of decreasing temperature - maybe the last month of logs stays resident in a SQL database (that is backed up), but the logs are eventually dumped to text or some other format and then archived to tape which is "cold stored" in an off-site location.

Text is the most-basic form the chat logs can be archived in, although if you want to retain the ability to perform complex queries on them it may be better to keep them in a structured, database-like format (perhaps going as far as storing them in a separate actual SQL database).

Your strategy will ultimately depend on the scale of the data (how much chat volume you get on an average daily basis) and how much you *actually* care about being able to go back and cherry-pick a random conversation from a decade ago at a moment's notice. Realistically speaking I doubt you'll need to do that on-demand very often.
> 1 votes

---
Tags: mmo
---


title: How to make 3D characters that grow?

text:
# Question
Title: How to make 3D characters that grow?
I am creating a game in LWJGL with Java that will feature growing animals that will be imported as OBJ files from Blender.

If I wanted these animals to grow, would I create a full sized 3D model and then shrink it via code and have it grow up, or would I have a small sized 3D model and have it expand in the game to full size?

# Answer
The nice thing about 3d models is that you can scale them fluently. So whether you model them on fully grown scale and then scale them down or model them as foals and scale them up is left to your personal preference.

However, you might want to take into account that most animals change proportions while growing. Young animals tend to have stubbier legs and larger heads compared to their torsos. Or in other words, younger animals are "cuter". If you want to simulate that, you need an individual scaling factor for each bone of your 3d models.

Another option is to have multiple growth stages per animal and use a different 3d model for each. That gives you the most control over how the animal looks in each stage. That's especially appropriate for animals which look very different in different growth stages (most birds, for example). The aesthetic disadvantage is that animals will go into the next growth stage with a visible "pop". But that clear visual distinction can also be an advantage if it is important for your players to see quickly which animal is in which growth stage (for example if you want the player to look at their herd of cows and to immediately realize "I got 6 baby cows which consume milk, 4 adolescent cows which produce milk and 3 old cows which should have been slaughtered ages ago - why is my butcher not working?").
> 2 votes

---
Tags: 3d
---