# Question
Title: How can I move number of objects between two points with random speed?
In the Hierarchy I have a Cube and the script is attached to the cube. And I also have in the Hierarchy two spheres as waypoints.

```
public class WP : MonoBehaviour
{
    public Transform[] waypoints;
    public float movingSpeed;

    GameObject[] allLines;
    GameObject[] duplicatedPrefabs;

    private void Start()
    {
        allLines = GameObject.FindGameObjectsWithTag("FrameLine");

        DuplicatePrefabEffects(allLines.Length);
        duplicatedPrefabs = GameObject.FindGameObjectsWithTag("Duplicated Prefab");
    }

    private void DuplicatePrefabEffects(int duplicationNumber)
    {
        for (int i = 0; i < duplicationNumber; i++)
        {
            var go = Instantiate(prefabEffect);
            go.tag = "Duplicated Prefab";
            go.name = "Duplicated Prefab";
        }
    }

    private void MoveDuplicated()
    {
        for (int i = 0; i < duplicatedPrefabs.Length; i++)
        {
           duplicatedPrefabs[i].transform.position = Vector3.Lerp(pointA.position, pointB.position, movingSpeed *Time.deltaTime);
        }
    }

    void Update()
    {
     MoveDuplicated();
    }
}

```

The duplicatedPrefabs are moving very very fast no matter what value I put for movingSpeed and then they are all stuck in the second waypoint and seems like moving on very specific small area on the second waypoint.

What I want to do is to move them smooth slowly between the two waypoints and with random speed range from each object. For example one will move at speed 1 the other on speed 20 third on speed 2.

# Answer
It looks like you're trying to use Lerp as though it were MoveTowards. Lerp just picks a point between two extremes, it doesn't automatically move that picked point unless you change its inputs.

Try this instead:

```
for (int i = 0; i < duplicatedPrefabs.Length; i++)
{
   duplicatedPrefabs[i].transform.position = Vector3.MoveTowards(
                duplicatedPrefabs[i].transform.position,
                pointB.position,
                movementSpeeds[i] * Time.deltaTime
            );
}

```

Two things to note here:

1. This moves the prefabs toward `pointB` from wherever they happen to be. Make sure you're spawning them at `pointA` so they start from the right place.
2. This assumes a parallel array of movement speeds for each object that you've populated in advance, using something like `Random.Range()`
> 3 votes

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


# Question
Title: How can I create a cel-shaded, comic book appearance in Unity?
I am working in Unity, I have imported the post-processing stack and I own a license to Amplify. But I'm having trouble making my models appear cel-shaded enough to make them appear as if they are from a comic book. I'd specifically like to achieve a result similar to that of Telltale's games like Wolf Among Us and Game of Thrones.

Here is a in-editor screen capture of the effect + shader values:

How can I get effects such as below?

# Answer
I've played with this in the past, and the answer to your question is two-fold:

1. You need appropriately designed assets. If you look at the big bad wolf from the Wolf Within Us, you will see that the texture for his model is stylised in cartoon form, as opposed to going for photo-realism. This is your first step.
2. Secondly, you need to change your rendering cycle. This is done by doing two render cycles: one for back facing polygons with thick lines, and a second normal rendering cycle using your cartoon textures, and using your attenuated light value to step the shading into three steps, instead of a continuous function. See https://en.wikipedia.org/wiki/Cel\_shading for some general information on this.
> 2 votes

---
Tags: unity, cel-shading
---


# Question
Title: Improve opengl drawing with less calls as possible
I'm looking to render rectangle primitives as performant as possible, here's what I did so far:

```
int main() {
    Window window("OpenGL", 800, 600);

    Shader shader("./file.shader");

    float vertices[8];
    glGenVertices(vertices, 200, 150, 400, 300); // return coords for a square
    const GLshort indices[6] = { 0, 1, 2, 2, 3, 0 };

    GLuint vao, vbo, ebo;
    glGenVertexArrays(1, &vao);
    glBindVertexArray(vao);

    glGenBuffers(1, &vbo);
    glBindBuffer(GL_ARRAY_BUFFER, vbo);
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);

    glEnableVertexAttribArray(0);
    glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, 0);

    glGenBuffers(1, &ebo);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);

    while(window.isOpen()) {
        window.clear();

        shader.use();
        glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, NULL);
        shader.setUniforms(..);
        glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, NULL);

        window.update();
    }

    glDeleteBuffers(1, &vbo);
    glDeleteBuffers(1, &ebo);
    glDeleteVertexArrays(1, &vao);

    return 0;
}

```

So far what I'm doing to fix my problem and seems to work:

1. Created vao, vbo and ebo to make a basic indexed rectangle.
2. Made a function that will returns vertices coordinates based position and sizes(x, y, w, h)
3. Create one single shader and set uniforms like position offsets, sizes and eventualy colors/textures after every draw call to be able to render shapes in different places ( that makes the coordinates function useless)

I'm pretty sure that's not the way to do it, but can't find something else, so this is what I'm thinking.

1. Heard that switching shaders is expensive, but I'll require shapes that won't share the same shader..
2. Also heard that setting uniforms is slower than switching shaders, so probalby switching shaders will be better here, need to profile the code to see.
3. Currently drawing one by one with glDrawElements seems hardcoded and inefficient to me, need something like a `vao` that could store multiple rectangular like indexed`vbo` all preloaded before drawing and when it goes to drawing, draw all the data with one call.
4. Not sure if I can load shaders between drawing, some of them will require changing while drawing like a hover or click effect, maybe there's better practices here too.

At the end, if you've been through this issue or having some tips/docs/source codes to read, it'll be excellent, thanks!

BIG NOTE: Mostly looking for 2d support, no 3d needed in case this could make it harder.

# Answer
> 1 votes
So, if I understand your question, correctly, you are trying to draw multiple rectangle objects as efficiently as possible... like sprites?

You are on to the right idea when you think about how to best optimize calls to openGL. The bottleneck in openGl is almost always with calling objects with your CPU faster than it can transmit them across the bridge to the GPU. There are a few tools that openGL comes with to facilitate resolving this issue.

You can use SubBufferData to inject data into your VBO at specified places. This works well if you create a larger buffer and then add multiple objects to it.

You can map your Buffer, so that you can inject new data into it. With this method, you update the contents of the buffer. This method is similar to SubBufferData, and depending on hardware, one or the other might have a better performance.

There is Index Drawing, if multiple objects use the same vertex data, you can submit them and GLSL has a function to let you derive an index from each set of data. You can then operate based on the index value in the shader to differentiate the results.

There is indirect calling. I'm less familiar with this one, but from my understanding is that you create a storage that is then manipulated by a shader before being stored again to be used by OpenGL again later.

There might be more that I'm not aware of, however, if it was me, and you're drawing similar rectangles, i'd use Index drawing, supplying the TexCoords and Position to the shader, referencing it's Index. You can then use a Sprite sheet texture and one VBO to draw your whole scene.

# Answer
> 0 votes
Any OpenGL state change does indeed carry a cost, but like all things, your algorithm is what will decide performance, not small optimisations.

That being said: If you are going to draw many quads (which, to OpenGL is actually two triangles), and by many, I mean thousands+, you can use a technique called instanced rendering. The idea goes like this:

1. Enable shader of choice
2. bind textures
3. compute transforms for each quad and store in a contiguous array.
4. Bind the array data to a uniform buffer object (UBO)
5. Use the buffer.
6. Send any additional data you need to the shader via uniforms
7. Call one of the following:

`void glDrawArraysInstanced(GLenum mode,GLint first,GLsizei count,GLsizei instancecount);`

`void glDrawElementsInstanced(GLenum mode,GLsizei count,GLenum type,const void *indices,GLsizei instancecount);`

Then, continue your rendering as normal.

---
Tags: opengl, c++, 2d
---


# Question
Title: Separating Axis Theorem and rotated objects
Quick question which hopefully won't require thralling through my code.

I have a working implementation of SAT for 3D collision detection but I'm having some problems with dealing with rotated objects. So what I have done, is every frame I rotate every point in both objects by their rotation quaternions. This feels excessive, especially if I am going to be translating/scaling/rotating every vertex in every object on every frame for the collision detection.

I would hope there's a way of implementing my SAT implementation to work with rotated normals only, and not need the rotated projections to compensate, but that doesn't seem to be working.

Could anyone provide me with a brief explanation with how SAT should be expected to handle rotations? Can we rotate certain points, or perhaps get some sort of post-projection rotation value to skew our projections like we can with translations?

Thanks

# Answer
> 3 votes
The key to any optimisation, is identifying where the bulk of the work is being done.

A simple analysis of your problem reveals the following:

1. A cuboid shape has 8 vertices, three perpendicular axes, and a position.
2. The same cuboid can be rotated around any of these axes.

At the moment, your algorithm is transforming the vertices, then presumably computing resultant axes from the vertices, to perform SAT computations.

You are correct in surmising that there is a computationally less expensive way to do it.

In your cuboid data structure, you only require 3 floats, called half extents. Each value is the distance from the centre of the cuboid, to the edge of it, along one of it's principle axes.

You take the three principle axes, x (1,0,0), y(0,1,0), and z(0,0,1), and rotate them by the objects' transform. (3 vector rotations instead of 8)

Then, you compute the vertices, using the rotated axes and half extents. this is mostly vector addition multiplication, which is inexpensive. This will result in the vertices being rotated, but not translated yet.

Finally, you add the position of the object to each vertex (again, cheap) to get your final translated vertices, in world space.

There are other optimisations that can be done, but this is a good start for you.

---
Tags: collision-detection, 3d, rotation, separating-axis-theorem
---


# Question
Title: Giving data to gameObjects without referencing self
Before I start on the problem, I would like to clarify a bit on the design of the system that I have issue with.

I have made a `StatusEffectController` and a `StatusEffectBaseClass` which uses the `IStatusEffect` interface. I make derived classes of `StatusEffectBaseClass` and add them as components to items that apply that status effect.

There is another script `WeaponMaster` which is a baseclass that contains a \**List of "IStatusEffect\`. On starting, it finds the status effects *(which are on the same game object as the script itself)*

When the weapon fires, it instantiates a projectile that contains a reference to the status effects of the weapon. This projectile, upon colliding with an object that has `StatusEffectController`, runs a function inside the `StatusEffectController` that accepts `IStatusEffect`. The function stores the `IStatusEffect` in its own list and runs the effects stored in the `StatusEffectBaseClass` 's derived class script.

---

The problem is, when the Projectile script gives the `StatusEffectController` its status effects, it gives them a reference to the one inside the weapon *(the original script that is a component on the weapon)*.

As I wrote this summary, I got a hint that I should Instantiate a new derivation of `StatusEffectBaseClass` ON the object I want to be affected and have the `StatusEffectController` reference that one instead of the one on the weapon.

Would that be a proper solution to the problem?

The following are portions of my scripts for:

WeaponMaster.cs:

```
public List<IStatusEffect> statusEffects = new List<IStatusEffect> ();

public GameObject projectile; // Irrelevant to this topic, it was just in the way.

float cooldown;

public void OnStart (){ // This is not called by itself, a derived class calls it instead.
    statusEffects.AddRange (gameObject.GetComponents<IStatusEffect> ());
    Debug.Log ("Got " + statusEffects.Count + " status effects on this weapon.");
}

```

ProjectileScript.cs:

```
public List<IStatusEffect> statusEffects;

//////////////////////////////////////
//IRRELEVANT STUFF HERE.
//////////////////////////////////////

    if(col.gameObject.GetComponent<StatusEffectController> () != null){//Deal status effects if the victim can process it. I should add a check to ignore this if the projectile has no status effects.
        StatusEffectController fX = col.gameObject.GetComponent<StatusEffectController> ();

        for(int i = 0; i < statusEffects.Count; i++){
            fX.ActivateEffect (statusEffects[i]);
        }
    }

    Die ();
}

```

StatusEffectController.cs:

```
//Gameobjects without this can not simulate status effects, but they may carry them.
//Weapons are an example, they can carry a status effect on them to apply to its victims but it can't be affected by it.

public List<IStatusEffect> activeEffects = new List<IStatusEffect>(); //Relevant.
public UnitStatum unit;

void Start () {
    unit = gameObject.GetComponent<UnitStatum> ();
}

void FixedUpdate(){
    if(activeEffects.Count > 0)
        UpdateEffects ();

}

public void ActivateEffect(IStatusEffect effect){ //Relevant.
    activeEffects.Add (effect);

    for(int i = 0; i < activeEffects.Count; i++){
        if(activeEffects[i] == effect){
            Debug.Log ("Status effects applied!");
            activeEffects [i].master = this.GetComponent<StatusEffectController> ();
            activeEffects [i].order = i;
            activeEffects [i].Activate ();
        }
    }
}

void UpdateEffects(){
    //Run down effect timers, check for expired effects and remove them.
    for(int i = 0; i < activeEffects.Count; i++){

        activeEffects [i].duration -= Time.deltaTime;
        if (activeEffects [i].duration <= 0){
            EndEffect (i);
        }
    }
}

public void EndEffect(int order){ //Relevant.
    //Remove the effect.
    activeEffects[order].Deactivate();
    activeEffects.RemoveAt (order);
    //Bring down the order of items that come after the removed object.
    for(int j = 0; j < activeEffects.Count - order;j++){
        activeEffects [order + j].order--;
    }

}
}

```

---

I have used @DMGregory 's method and got the system working. But I have encountered a couple of problems now.

First, the component that gets added is brand new and doesn't copy any modified variables in the weapon(I have tried a method to set all variables by code but it doesn't work as expected.

Second, I have replaced the `List<>` with a `Dictionary<>` to allow ease of organization/detection of existing effects. But I get a *"Collection was modified"* warning everytime I run a `foreach` loop through the `Dictionary<>` while another status effect is being applied.

Here is the latest `StatusEffectController` script:

```
public UnitStatum unit;

//Gameobjects without this can not simulate status effects, but they may carry them.
//Weapons are an example, they can carry a status effect on them to apply to its victims but it can't be affected by it.

Dictionary<string, IStatusEffect> activeEffects = new Dictionary<string, IStatusEffect>();

void Start () {
    unit = gameObject.GetComponent<UnitStatum> ();
}

void FixedUpdate(){
    if (activeEffects.Count > 0)
        UpdateEffects ();
}

public void AddEffect(IStatusEffect effect){
    Type typus = effect.GetType ();

    if (activeEffects.ContainsKey (effect._name)){
        if (activeEffects [effect._name]._stackable) {
            activeEffects [effect._name]._stack++;
        }
    } else {
        gameObject.AddComponent (typus);

        activeEffects.Add (effect._name, DuplicateEffect (effect, typus));
        activeEffects [effect._name].Activate ();
    }
}

void UpdateEffects(){
    //Run down effect timers, check for expired effects and remove them.
    foreach (KeyValuePair<string, IStatusEffect> effect in activeEffects){
        effect.Value._duration -= Time.deltaTime;
        if(effect.Value._duration <= 0){
            if (effect.Value._expireType == "Kill")
                EndEffect (effect.Value._name);
            else if (effect.Value._expireType == "Decay") {
                effect.Value._stack--;
                effect.Value._activeDuration = effect.Value._duration;
            }
        }
    }
}

IStatusEffect DuplicateEffect(IStatusEffect effect, Type ofType){
    IStatusEffect duplicant = (IStatusEffect)gameObject.GetComponent (ofType);

    duplicant.master = gameObject.GetComponent<StatusEffectController> ();
    duplicant._name = effect._name;
    duplicant._description = effect._description;
    duplicant._duration = effect._duration;
    duplicant._activeDuration = effect._activeDuration;
    duplicant._delay = effect._delay;
    duplicant._tickRate = effect._tickRate;
    duplicant._power = effect._power;
    duplicant._range = effect._range;
    duplicant._affects = effect._affects;
    duplicant._type = effect._type;
    duplicant._expireType = effect._expireType;
    duplicant._stack = effect._stack;
    duplicant._maxStack = effect._maxStack;
    duplicant._dispellable = effect._dispellable;
    duplicant._refreshable = effect._refreshable;
    duplicant._stackable = effect._stackable;

    return duplicant;
}

public void EndEffect(string effectName){
    //End the effect.

    activeEffects [effectName].Deactivate ();
    activeEffects.Remove (effectName);
}
}

```

In the `DuplicateEffect` function, using a `Debug.Log()` returns the correctly applied values, but looking at them in the inspector shows the default initialized values.

Thanks for your assistance!

# Answer
> 1 votes
It sounds to me like you have up to three different jobs these IStatusEffect components may be serving:

* Marking a weapon as "I can deal this status effect" (and possibly an amount/intensity or other configuration?)
* Marking a recipient as "I can receive / react to this status effect" (and possibly tracking a resistance or vulnerability amount?)
* Processing the effects of the status effect on an afflicted recipient (eg. dealing damage periodically when poisoned / on fire)

These seem to me to be sufficiently distinct functions that they might not need to coexist in the same component.

I'd be inclined to introduce a StatusEffectType to express the shared "status effect identity" concept we need in all three roles.

* this could be an enumeration if you have a controlled list of status effects that should only grow occasionally in development / in major game updates.
* or, if you need to add custom status effects frequently, this could be a type of ScriptableObject, so you can create new status effects as data Assets frequently. This can hold a reference to the type or prefab of a component to apply the status effect when needed.

Now your weapon can contain a list of StatusEffectTypes that it can deal (possibly paired with intensity or other flavour attributes), and your recipients can contain a list of StatusEffectTypes they can receive (possibly paired with resistance/vulnerability attributes, or dormant components to act on those status effects)

Once you identify a match between a status effect a weapon deals and a struck recipient receives, you look up the appropriate behaviour component to activate / instantiate on the recipient.

If the component isn't already on the recipient or identified inside the StatusEffectType, you can also include a StatusEffectType on your status effect component prefabs, and search the list of those prefabs for one with a matching StatusEffectType.

This lets us get rid of the concept of an "inert" status effect component — the only ones we need are the ones actually inflicting effects on a recipient. This seems cleaner to my style of coding, and removes overhead of instantiating/storing/messaging script instances where we're not actually using their script behaviours.

---

If you'd prefer to keep these inert instances, then it sounds like you want `StatusEffectController.ActivateEffect` to activate the matching script of the same type on its own GameObject, rather than the one it got passed from the weapon's list. We can do that like so:

```
public void ActivateEffect(IStatusEffect effect) {
     var type = effect.GetType();

     if(activeEffects.Find((e) => { return e.GetType() == type;}) != null) {
         // Already active. Refresh it? Early-out?
     }

     // Look for a matching component on our own object.
     var match = gameObject.GetComponent(type);

     if(match == null) {
         // Dynamically add the component if it's missing?
         // match = AddComponent(type);
     }

     activeEffects.Add (match);

     // Activate component...
     // etc
}

```

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


# Question
Title: Don't understand how paddle location is tracked; using XNA tutorial
Wanting to learn how to make games, decided to use Monogame. Have pretty light programming knowledge, so I apologize beforehand for my ignorance to this surely obvious oversight.

Following a beginner's tutorial on XNA game development. It's a simple ball and paddle game that has a game class, paddle class, and ball class.

Now my problem lies in the code for the ball class.

```
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;

    using Microsoft.Xna.Framework;
    using Microsoft.Xna.Framework.Graphics;

    namespace BreakingOut
{
class Ball
{
    Vector2 motion;
    Vector2 position;
    float ballSpeed = 4;

    Texture2D texture;
    Rectangle screenBounds;

    public Ball(Texture2D texture, Rectangle screenBounds)
    {
        this.texture = texture;
        this.screenBounds = screenBounds;
    }

    public void Update()
    {
        position += motion * ballSpeed;
        CheckWallCollision();
    }

    private void CheckWallCollision()
    {
        if (position.X < 0)
        {
            position.X = 0;
            motion.X *= -1;
        }
        if (position.X + texture.Width > screenBounds.Width)
        {
            position.X = screenBounds.Width - texture.Width;
            motion.X *= -1;
        }
        if (position.Y < 0)
        {
            position.Y = 0;
            motion.Y *= -1;
        }
    }

    public void SetInStartPosition(Rectangle paddleLocation)
    {
        motion = new Vector2(1, -1);
        position.Y = paddleLocation.Y - texture.Height;
        position.X = paddleLocation.X + (paddleLocation.Width - texture.Width) / 2;
    }

    public bool OffBottom()
    {
        if (position.Y > screenBounds.Height)
            return true;
        return false;
    }

    public void PaddleCollision(Rectangle paddleLocation)
    {
        Rectangle ballLocation = new Rectangle(
            (int)position.X,
            (int)position.Y,
            texture.Width,
            texture.Height);

        if (paddleLocation.Intersects(ballLocation))
        {
            position.Y = paddleLocation.Y - texture.Height;
            motion.Y *= -1;
        }
    }

    public void Draw(SpriteBatch spriteBatch)
    {
        spriteBatch.Draw(texture, position, Color.White);
    }
}
}

```

When I run the game, it functions properly. Player moves the paddle, and when the ball collides with the paddle, it bounces off. I don't understand how the Ball class knows the paddle location though. It's not like paddleLocation is a public variable in the paddle class.

# Answer
> 0 votes
The position is actually stored in `Vector2 position;`

The reason it is accesible without `public` is because it is modified within the class. The three access modifiers are `public` `private` `protected` and `Vector2 position` by default is `private`

I suggest you learn C# first before delving into XNA to not have problems like these.

# Answer
> 0 votes
I know this is an old question, but it's also an old problem that most new programmers run into at some point. Thought I'd give it a more extensive answer.

Assuming you wrote as the tutorial wrote, You'll have this function in your ball class. Note that it's a public function, which means that it can be accessed outside the class. Secondly it takes the paddleLocation as an argument, meaning when this function is called it requires a Rectangle to be passed along with it.

```
public void PaddleCollision(Rectangle paddleLocation)
{
   Rectangle ballLocation = new Rectangle(
   (int)position.X,
   (int)position.Y,
   texture.Width,
   texture.Height);
   if (paddleLocation.Intersects(ballLocation))
   {
     position.Y = paddleLocation.Y - texture.Height;
     motion.Y *= -1;
   }
}

```

That is how you ball class knows of the paddleLocation. In Game1 update there is a function call to the ball class

```
ball.PaddleCollision(paddle.GetBounds());

```

Which does just that. Each time this line gets called it will pass the rectangle bounds to the PaddleCollision funtion in your ball class.

It can do this because there is a GetBounds function in the paddle class.

```
public Rectangle GetBounds()
{
   return new Rectangle(
   (int)position.X,
   (int)position.Y,
   texture.Width,
   texture.Height);
}

```

The ball class knows nothing of the paddle class, vice versa, but the game1 class initiates both of them, so it knows of them both. Which is why it can access the public functions in both of them.

This is a fairly common way to pass data around, hope this cleared it up for anyone with a similar problem.

---
Tags: monogame
---


# Question
Title: UE4 "get" and "set" component without using an actor specific reference
i'm using Unreal Engine 4 and I want to get the variable mode from some actors by referencing them but the only option that i can find in the menu is actor specific like this.

So what i want is a version of the component in my image that is not "Target H1" specific. And i also need the same thing for the "set" component please. and if this is not possble can someone tell me please.

# Answer
If I'm understanding your question correctly it sounds like you need to create a base class for all actors that you want to reference this way.

For example say you had an Actor of type Chair, and an Actor of type Table, and you wanted to be able to access a variable that stores the Actors color. If you create a base Actor called Furniture that holds this color variable, you can extend child Actors from this blueprint to be able access the variable regardless of whether the target is a chair or a table or any other child of the base class.

To extend a blueprint from a base actor, simply right click on the blueprint you have created and select 'Create Child Blueprint Class' for each Actor you wish to access the variable from. The important thing is to make sure the variable is stored in the base Actor blueprint, and not the child blueprints.
> 1 votes

---
Tags: unreal-4
---


# Question
Title: How to check if a pipe placed on a fixed grid size is connected correctly to a neighbor pipe?
Am looking for a solution (algorithm) to check if an object in a neighbor tile can be connected (i.e transfer power). Best example I could come up with to make this more clear, is pipes.

I am using a fixed 1 x 1 grid size. So only one object can occupy that space. I do not store where objects are in the world, as there could be a lot of them placed down by the player.

Let's say you can place down 4 different types of pipe connectors. Straight, Right angle, Cross, and T. These can all be rotated by 90 degrees each rotation on the Y (up) axis.

Like in this example I put together quickly:

In that case above, they all connect correctly, but how do I check that when a pipe is placed down in its final position, it is a valid connection?

So in this image, the Straight pipe is not connected correctly to the T pipe to the right or the Straight pipe above it. So in a pipe example that might be transferring power, the Straight pipe would not be powered.

If it helps because it's Unity. I added the directions (I tested by drawing a ray to the direction that it can connect).

Spent some time playing with the "pipe" prototype a bit more.

Each pipe has 4 booleans. Forward, Back, Left, Right. These indicate which side the pipe can be connected too. So for example, a straight pipe that hasn't been rotated can connect left and right. If the straight pipe gets rotated, then forward and back becomes true, and left and right become false. This is applied to all pipe types.

When placing a pipe down, a raycast is done in all 4 directions to see if there is another pipe nearby. So I have access to the neighbor pipes to see which side they can be connected on. My problem now, is the logic to do the check.

Note: The 4 raycasts are a one time deal. It's just to check the neighbors on placement.

# Answer
Forget `GameObject`s and pretty colours for now. Let's deal with this in the abstract, as pure data.

Your most notable finding is discovering that each tile has 4 booleans noting whether that side is "open" to connections or not. OK, so...

```
struct Tile
{
   bool[] directions; //if all 4 are false i.e. "closed", this is an empty tile; skip it.

   //any other members like colour, rotation status, or whatever

   void Tile()
   {
       directions = new bool[4];
   }
}

class Game()
{
    Tile[,] tiles = new Tile[WORLD_WIDTH, WORLD_HEIGHT];

}

```

Why do I use a bool array of directions as above, rather than 4 members like this?...

```
struct Tile
{
    bool north;
    bool south;
    bool east;
    bool west;
}

```

...Because we could not then iterate over those members (well, we could, using C# reflection, but that would be slow and painful).

Instead we can give our directions name like this, above all existing code:

```
public const int NORTH = 0;
public const int EAST = 1;
public const int SOUTH = 2;
public const int WEST = 3;

//...or...

enum Direction
{
   NORTH, //0
   EAST, //1
   SOUTH, //2
   WEST //3
}

```

Now we can cycle through the directions, like this:

```
for (int z = 0; z < WORLD_HEIGHT; z++) //use z rather than y for unity's axes
    for (int x = 0; x < WORLD_WIDTH; x++)
    {
        for (int d = 0; d < 4; d++) //cycle clockwise around compass: N,E,S,W
        {
            if (tile.directions[d] == true)
            {
                //...do something important...
            }

        }

        //..or...

        int startDir = SOUTH;
        for (int d = 0; d < 4; d++)
        {
            int dd = (startDir + d) % 4; //gets back into the 0-3 valid range: 4=0, 5=1...
            if (tile.directions[dd] == true)
            {
                //...do something important...
            }
        }
    }
}

```

Obviously, end goal is to see whether any neighbours are connected to the currently-evaluated tile. Change the `Tile`:

```
struct Tile
{
   bool[] directions; //if all 4 are false, this is an empty tile.
   bool[] connections; //reflects directions, but stores whether hooked up.
   //any other members like colour, rotation status, or whatever

   void Tile()
   {
       directions  = new bool[4];
       connections = new bool[4];
   }
}

```

Then:

```
class Game
{
    Tile[,] tiles = new Tile[WORLD_WIDTH, WORLD_HEIGHT];

    bool DetermineConnectionsAt(int xSelf, int zSelf)
    {
        Tile tileSelf = tiles[xSelf, zSelf];

        //now we walk west/east neighbours
        for (int xo = -1; xo < 2; xo +=2) //skips 0, goes from -1 -> +1
        {
            Tile tileNeighbour = tiles[xSelf + xo, zSelf];

            if (tileSelf     .directions[SOUTH - xo] == true &&
                tileNeighbour.directions[SOUTH + xo] == true) //opp. side of neighbour
            {
                tileSelf     .connections[SOUTH - xo] = true;
                //you could set neighbour's connection on opp. side = true
                //as well, but not much point as you will evaluate neighbour
                //later as you loop through the xz grid.
            }
            //...you will also have to make sure you are not checking outside
            //the grid's indices here (e.g. < 0, or > WORLD_WIDTH).
        }
        //...and walk North/South neighbours exactly the same way, but in z.
        //...instead of SOUTH, use EAST. This is to avoid negative modulo.
    }
}

```

This leaves several things up to you; for example, how you want to store / manage rotated representations of the same "glyph"; store them all in one large enum or something else? Have a method on Tile `Rotate(+1)` or `Rotate(-1)` to adjust `directions` / `connections` arrays accordingly? That's all up to you.

There are more graph-like ways of doing this (such as your comment about dictionaries, or pure reference linkage as in linked-lists) than using a 2D array. They are more efficient in some ways (smaller memory footprint) but less efficient in others (cache access, typically). But I'll leave that one for you, now that you understand the basic principle you can do whatever pleases you. :)
> 4 votes

# Answer
> This solution assumes that your pieces are not locked to a grid and can move around freely. When your game uses a grid where each piece occupies exactly one tile and can only be placed exactly on the center of a tile, then this solution is overengineering.

Add a "Connector" child-object to each connection-point of your piece-prefabs. Add sphere colliders to these "Connectors". This collider represents the area in which it snaps together with the "Connector" child objects of other pieces. Rotate the connector child-objects to face into the correct direction.

When you move a piece, use `Physics.OverlapSphere` or the `OnTriggerEnter` event to find out if one of its connectors overlaps with a connector of another piece. When you detected such a collision, check if the rotations of the connectors are in opposite directions. When the orientations match too, then the two objects connect.

You might want to adjust the position of the placed piece so the positions of the Connectors are at the same point. In other words, have the new object "snap" into place.
> 0 votes

---
Tags: unity, algorithm
---


# Question
Title: How to "place" object in a 3d world without overlapping them ?
I would like to place object in a 3d world "like minecraft player can do".

What I'm trying to do is to allow the user to place objects, without overlapping them (like in minecraft you can do).

So if the player try to place an object partially over another, my game automatically "move and place" the object in the allowed position.

What can be the right approach ?

# Answer
> 4 votes
**Checking collision**

OK, let's backtrack here for a second. Let's stop talking about colliders, raycasting, `GameObject`s, `Transform`s etc. It's overkill. `VOXELS != UNITY`. Voxels existed long before Unity, and will long after.

What is a voxel space (as in Minecraft)? Fundamentally, it is this:

```
Voxel[,,] voxels = new Voxel[VOLUME_WIDTH, VOLUME_HEIGHT, VOLUME_DEPTH];

```

...a 3D array. THAT array is the basis on which you perform logical checks, NOT colliders.

Yes, you will need to raycast where the user is looking. There are algorithms like 3D DDA that can do this incredibly cheaply without the need for fancy, costly Unity physics-based raycasting.

**Alternative placement**

Having gotten that out of the way, let's look at alternative placement. You can set whatever criteria you like. I would suggest limiting it, step by step. For example, the first constraint I would put on the location the user is trying to place at is

> We can move back, forward, left and right - but we MUST place at the *same height*.

Already there we've simplified the problem greatly. Now deciding whether we can place for example a 2x2x2 cube into a space looks at the next step: Given a space where the user is pointing at a given height Y at position XZ, does X+1 (or X-1) and Z+1 (or Z-1) accommodate a 2x2 shape. We are now working with *planar* logic, which is to say working on a flat plane. If there is no 2x2 flat plane in the immediate region (and by plane, I mean area with all the same Y) then we need to look elsewhere nearby, or give the user no alternatives at all.

Another crucial thing is where the ray strikes a surface. If you hit a ground surface (i.e. planar in XZ, such as what you may stand on) cool, let the above apply. However if there is a wall or cliff right in front of you, clearly you cannot place there. You now need to determine if the space directly below that is available for placement. So,

> If we are looking at a vertical wall, we must check the placement area directly below it, that is, the first horizontal section below that vertical face, for potential placement.

Gradually, by introducing these rules one by one (and in particular order) you will end up with the behaviour for placement that you desire.

# Answer
> 2 votes
There are two parts to this question.

1. Determine if an object can be placed in a given position.
2. Find the nearest valid location for an object to be placed.

## 1. Validating Location

This one is fairly simple and ultimitely I feel it's the best.

When the user wants to place an object spawn it in their hands. So they can move it around to determine a position to place it.

In a script on the object respond to the OnCollisionEnter and OnCollisionExit calls. In these methods keep a list of what the object is colliding with. When OnCollisionEnter is hit, store the colliding object in a list and remove it from the list when you see it in the OnCollisionExit call.

Note: while the object is being placed you probably don't want a solid collider for it. So set it's collider to trigger. If you do this then you need to use the OnTriggerEnter and OnTriggerExit methods instead.

While there is an item in the list then the object is colliding with something and can't be placed. Consider swapping the objects material in this state to indicate it.

Then you can simple let the user move it around to a valid location. Letting a user place the object anywhere then "correcting" it for them could cause a disconnect between what the user is trying to do and what the game is doing.

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

[RequireComponent(typeof(Renderer))]
public class ObjectPlacer : MonoBehaviour
{
    private List<GameObject> _collidingObjects = new List<GameObject>();
    private Material _material = null;
    private Color _startingColor = Color.black;

    public Color invalidPlacementColor = Color.red;

    void Start()
    {
        _material = GetComponent<Renderer>().material;
        _startingColor = _material.color;
    }

    void Update()
    {
        if (IsPositionValid())
            _material.color = _startingColor;
        else
            _material.color = invalidPlacementColor;
    }

    void OnTriggerEnter(Collider other)
    {
        if (!_collidingObjects.Contains(other.gameObject))
        {
            _collidingObjects.Add(other.gameObject);
            print("Colliding");
        }
    }

    void OnTriggerExit(Collider other)
    {
        if (_collidingObjects.Contains(other.gameObject))
        {
            _collidingObjects.Remove(other.gameObject);
        }
    }

    bool IsPositionValid()
    {
        return _collidingObjects.Count == 0;
    }
}

```

Please note that for this sample code to work I made the colliding object a kinematic rigid body with a trigger collider. The OnTriggerEnter is only triggered if one of the two objects touching is a rigid body and the object the behaviour is on has a collider with "isTrigger" set to true.

## 2. Finding the best location

This part of the problem is fairly hard. The simplest method I can suggest is to use the method in part 1 to determine if you need to do anything. Then iteratively call a method that moves the object away from the collision and check that position.

To check if the object is in a good position you can use a call to physics.spherecast/physics.boxcast/physics.capsulecase and provide parameters that encompass the object being placed. This will give you a RaycastHit if there is a collision. Move the object along the normal and repeat.

Here's some pseudo code

```
        RaycastHit hit;
        // while the object is colliding move the object by x distance along the normal of collision.
        while (Physics.CapsuleCast(sphereTopPosition, sphereBottomPosition, radius, transform.up, out hit))
        {
            rigidBody.MovePosition(rigidBody.position + hit.normal * someDistance);
        }

```

The problem with this solution is that you can definitely end up in a situation where the object is just caught in the loop bouncing back and forth between two objects crashing the game.

# Answer
> 0 votes
Try

```
RaycastHit hit;
if(Physics.Raycast(transform.position, transform.fowards, out hit)){
GameObject item = Instantiate(prefabOfObject, hit.point);
bounds b = item.getComponent<typeofcolliderobjecthas>.bounds;
item.transform.position -= bounds.extents*transform.fowards;
}

```

I didn’t test this, and it was written in an iPad, but it could work. Note that it should be placed on the camera, and some fields must be replaced.

# Answer
> -1 votes
In Unity Only Child objects have relative Position to Parent. Otherwise All Global Objects have Position Relative to Origin (0,0,0). Each Child despite having Relative Position have Absolute world Position too, you can assign and use that too. Hope it helps.

# Answer
> -1 votes
You could check if it is touching the ground with colliders and if it's not you can make some kind of roll function. Just an idea!

What about raycast themselfs? If you have a 2x2x2 and in this case just to simplify. 5 raycast for each possible direction but -z since we are on a plane and want to check above. Lets say that all your raycast have a length of 1 on all faces. if they come in contact with something you know that this direction isnt an option and you could suggest valid path that have at least 1 unit available for your cube. Just another idea. Of course this is all very linear and i dont have your vision of the project.

---
Tags: unity, algorithm
---


title: How to develop a PBBG?

text:
# Question
Title: How to develop a PBBG?
I enjoy playing a lot of text-based PBBGs (Persisent Browsing Based Games). A good example of the style of game I'm referring to is lyrania. I would like to work on developing this style game but have had a hard time researching everything required to create such a game from scratch.

The front-end development I know how to do or can easily learn.

The first specific thing that I am unsure how to do is:

1) Hooking up to a server that would allow constant updates of player data as well as retrieve data from the server. Finding information on how to create a server proves difficult because every guide seems to assume I have knowledge of things that I don't, I'm completely self-taught.

I would like to do as much of this in Javascript as possible but am willing to learn other languages and have some experience with Python, Java, C#, C++, PHP, mySQL

# Answer
> 1 votes
I'm not a professional game developer myself (developing my first game) but I would like to just give my opinion on some points here as I'm a web application developer as professional.

1. Well that straight comes to my suggestion. You need to create a frontEnd and a Backend part for your game. Meaning you create an application in Java,ASP.NET,PHP or whatever floats your boat. It will handle all business logic as authorization, registering, the game itself etc. The frontend will just display and request data. You can find informations about this structure under terms like **RESTful API** and searching for backend and frontend development. ( Full-Stack Web Development ).

1.1. The way this works is that the backend offers points to request data like asking for the current task when calling this server url: `/game/{player-ID}/activeTask` ( just a example. There are best practies on how to style the URL's ) The client ( Browser, mobile whatever ) just has to interprete the data and show it correctly. You will divide responsibilitys, which will have an additional pro explained in point 4.
2. That's really hard to answer. There are a lot of possible ways to design/structure this. However it depends on the kind of requirements you have for such an system. Maybe this is a good starting point. Generally get to know what system there are and then decide on which to use and study it.
3. Very difficult point in generall. I will only scratch it to give you a starting point because I would need to write a blog article to answer it. You need to use existing components and librarys. Don't. **Don't** invent your own. That will likely be a security hole more than an improvement. Store the user with all informations you like in the database and then store the password encrypted, so it can never be decrypted to cleartext again. A good starting point for this are the keywords. bcrypt,scrypt, and PBKDF2. With these you will garuanteed find everything needed. ( I prefer to use bcrypt and pbkdf2 )
4. And voilá. When you decide to create the game in a backend and frontend style you can easily create an application for any device that will just call the url's as the website and interprete the receiving data. Sounds great doesn't it?

**Notes:** So I maybe made it sound pretty easy but it's going to be a heavy task. You need to take a lot into consideration and it's a lot of work to make your backend hardened so nobody can just request the URL's manually and cheat or worse...Hack your server. You need to sanitize every input from users and **never trust their data**. Optionally but recommend is **additionall encryption of the data** before it leaves the client or the server. ( **Keyword:** private/public Key communication encryption ) And very essential is a correctly set up SSL communication/certificate for your server so all communication is over HTTPS.

I wish you best of luck and more over fun in developing that game!!

# Answer
> 2 votes
I would recommend taking a look at Flask, a web framework for Python that's fairly easy to set up and comes with a development server you can run locally. The code snippets below are from a Flask based browser RPG.

The two most pouplar methods of exchanging data between the frontend and backend in a web application are

* Templates and forms
* Asynchronous requests fom JS (AJAX)

These are typically used in combination, each serving a different role.

# Templates

A template is, put simply, a HTML page with placeholders that the server replaces with data before the page gets sent to the client. Flask uses Jinja2 for this task.

Assuming you want to go to http://servername/character/1 and see a list of the first character's items, a basic Jinja2 template could look like this:

```
<body>
  Your inventory:<br/>
  <div>
    {% for item in pc.inventory.items %}
      <a href="/items/{{loop.index}}">{{item.name}}</a>
    {% endfor %}
  </div>
</body>

```

And the Python code to serve the page:

```
app = Flask(__name__)

@app.route('/character/<int:index>')
def show_character(index):
    chara = party.characters[index-1]
    return render_template('character.html', pc=chara)

```

# POST Requests

I'll assume you're familiar with forms. If you set method="post", the form will forward the data entered to the web server. Flask extracts this data into a dictionary. The following code reads data from an input field named "description" and forwards it to a template to display it back to the user. Note that in practice, you'll probably want to save that data somewhere, ideally in a database.

```
@app.route('/profile/description', methods=['POST'])
def set_description():
    description = request.form['description']
    return render_template('profile.html', description=description)

```

# AJAX

Asynchronous requests work basically the same, except that they are called from JavaScript and you usually don't want to return a template but rather a string containing JSON, which JavaScript can easily digest and turn into an object, if needed. The idea is that the "consumer" of an AJAX/REST call is not the user but your script, which will process the data and add it to the DOM.

If you want to exchange complex objects or even object hierarchies between front- and backend, I recommend jsonpickle. However, keep in mind that any AJAX requests eat up bandwidth, while filling out a template server side is free from a bandwidth standpoint.

Use Ajax when you need to refresh data without reloading the entire page, for example for a chat window.

# Things to look out for

* Client side (i.e. JS) input validation is good for the user experience, but *never* trust any data that comes from the client, *always* validate server side.
* A database is recommended for storing your data.
* Look into session handling. The server side code is "global", by default there is one scope for all users. You'll probably want an encrypted session cookie or at least a session ID so people can't just login as someone else. I can add examples later if you need them.
* Keep in mind that some users don't allow scripts for every domain. If some core functions absolutely require JS, that's ok, just communicate that. If you can make it work without, even with less functionality, that's better.

Hope that serves as a good starting point. Feel free to ask more specific questions if you get stuck somewhere, that's what the site is for :)

---
Tags: client-server, server, browser-based-games, text-based
---


title: Android Studio libgdx multiplayer

text:
# Question
Title: Android Studio libgdx multiplayer
Does anyone know **if it's possible to setup a multiplayer game using libgdx in Android Studio?**

I've been trying to convert my game to multiplayer using all kinds of tutorials on libgdx & multiplayer but I'm guessing it's just not possible with android Studio. Seems it's only possible to add leaderboard and achievements?

If someone managed to get multiplayer working with libgdx in Android Studio please let me know. And perhaps explain how to get it working?

If someone knows it's **impossible** please let me know as well.

If impossible, is it worth trying eclipse? Since it's not supported by Google anymore...???

Thnx in advanced

# Answer
> -1 votes
Well since it's very hard to get documentation about multiplayer setup all i should say is try IntelliJ IDEA you'll get better doucmentation on there official page only drawback is if you're working on creating a cross platform game then only exception will be for iOS. You'll need to visit official website & if there is any plugin available for simple integration for networking for intellij. It's far more better solution than android studio or eclipse since the documentation is not enough.I hope you'll do further research on you're own.

---
Tags: android, libgdx, multiplayer, turn-based, realtime
---


# Question
Title: CreateShaderResourceView fails because of plane slice
I'm trying to write a wrapper for the CreateShaderResourceView method inside my `Texture` class, which shouldn't be any problem at all since everything was working fine outside the class. But the debug layer reports an error when assertion is called at the creation of the pipeline state:

```
D3D12 ERROR: ID3D12Device::CreateShaderResourceView: The PlaneSlice -858993460 is invalid when the resource format is B8G8R8A8_UNORM and the view format is B8G8R8A8_UNORM.  Only Plane Slice 0 is valid when creating a view on a non-planar format. [ STATE_CREATION ERROR #344: CREATEUNORDEREDACCESSVIEW_INVALIDPLANESLICE]
D3D12 ERROR: ID3D12Device::CreateShaderResourceView: The Dimensions of the View are invalid due to at least one of the following conditions. MostDetailedMip (value = -858993460) must be between 0 and MipLevels-1 of the Texture Resource, 0, inclusively. With the current MostDetailedMip, MipLevels (value = 1) must be between 1 and 0, inclusively, or -1 to default to all mips from MostDetailedMip, in order that the View fit on the Texture. [ STATE_CREATION ERROR #31: CREATESHADERRESOURCEVIEW_INVALIDDIMENSIONS]
D3D12: Removing Device.

```

The wrapper function is simple and operates on a map:

```
void Texture::CreateSRVFromTexture(const Textures::ID & id, CD3DX12_CPU_DESCRIPTOR_HANDLE & cpuHandle)
{
    auto found = m_textures.find(id);

    //Create SRV with the CPU handle
    D3D12_SHADER_RESOURCE_VIEW_DESC srvDesc;
    srvDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
    srvDesc.Format = found->second.textureDesc.Format;
    srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D;
    srvDesc.Texture2D.MipLevels = 1;
    m_device->CreateShaderResourceView(found->second.textureBuffer, &srvDesc, cpuHandle);
}

```

And calling this function looks like this:

```
CD3DX12_CPU_DESCRIPTOR_HANDLE srvHandle1(m_textureDescriptorHeap->GetCPUDescriptorHandleForHeapStart(), 0,
        m_device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV));
m_texture->CreateSRVFromTexture(Textures::ID::Fatboy, srvHandle1);

```

Now I don't understand why it worked perfectly fine before (no errors reported) when I didn't have the wrapper method and simply accessed the texture with a Get method. What could be the cause of this, since the error message is a bit vague and doesn't help very much?

# Answer
> 1 votes
`D3D12_SHADER_RESOURCE_VIEW_DESC` is a structure; it has no constructors to default-initialize any fields.

Thus, when you create an instance of one on the stack, the values of all fields are essentially randomly garbage. You then proceed to assign values to *some* of the fields. However, you don't assign values to *all* of them. You leave several of the members of the nested `Texture2D` member alone, including `PlaneSlice` and `MostDetailedMip`, which are two that the API is complaining about.

You should initialize all fields of the structure, either explicitly or *at least* (when valid) using something like `D3D12_SHADER_RESOURCE_VIEW_DESC srvDesc = {0};`

---
Tags: c++, directx, directx12
---


# Question
Title: RTS Lockstep: How to deal with high latency and packet drops?
In the lockstep RTS model, I understand how games can be made deterministic by sending across commands to run at designated frames in the future. Then, to keep everyone in sync, confirmations are sent back to confirm that the commands were properly received. If the confirmations wasn't received, the command wouldn't run and the game would pause.

My question is how do I keep the confirmation frames in sync? Given at least 2 players i.e. Player\_A and Player\_B:

It's entirely possible that Player\_A might receive confirmation from Player\_B but Player\_B wouldn't from Player\_A, so Player\_A would run the command while Player\_B would pause and be out of sync. How can this be dealt with? Confirmation for the confirmations?

# Answer
> 2 votes
I highly recommend you study the TCP model; it is very mature and has many features built in over the years, making it a jack-of-all-trades networking protocol. It will likely have features that address any follow-up concerns you may have.

The scenario you describe is also known as *packet loss*; Player\_A has sent a confirmation to Player\_B but Player\_B hasn't received it; it may have been lost or delayed. There are a few ways to solve this; the method TCP uses (and is described in this SO question) is *retransmission*. Since Player\_B is expecting a confirmation but hasn't received it, after a while it assumes that its original message was lost, so it retransmits that message. Player\_A will see a duplicate message, and send the confirmation (a.k.a. acknowledgement). This process will repeat until the confirmation makes it to Player\_B and the world can continue.

The specifics can be quite complex; for example, the amount of time Player\_B waits until retransmission - the *retransmission timeout* \- loosely depends on *round-trip time*; retransmission rates aren't constant, as TCP has a mechanism to throttle back in case the problem is congestion, and retransmitting duplicate packets would worsen the problem. You don't have to worry about any of this if your game uses TCP, but if you don't then it's helpful to look at TCP and how it solves these problems. Just be aware that you may end up re-inventing TCP.

# Answer
> 1 votes
It's been a while but I thought I'd answer for posterity.

The algorithm is simply:

* Each player sends his commands to all other players every turn. (If they have nothing to order in particular, the message could just say "I have 0 commands for turn X".)
* Each player waits for all other players' commands before executing the current turn.

So in the described scenario where PlayerA receives PlayerB's commands, but PlayerB does not receive PlayerA's commands, PlayerA executes the current turn, and then waits for PlayerB's commands before executing the next turn. Meanwhile, PlayerB is still waiting on PlayerA before executing the current turn. Since he is stuck at this turn, he won't be sending commands for the next one, and PlayerA will have to wait. The game is effectively paused for everyone until PlayerB gets the commands it is missing.

As this scenario illustrates (PlayerA is done executing the current turn, PlayerB hasn't), it is possible players aren't executing the same turns simultaneously; the synchronicity does not consist in *simultaneity* but that *all players execute the same commands on the same turns*.

The Baldur's Gate manual (Baldur's Gate is based on what was designed as an RTS engine originally) stated this:

> Baldur’s Gate is an asynchronous game. If you happen to be playing with some body whose system is very close by, you still might see slightly different things happen on each system. The point to remember is that while things happen somewhat differently, the result of the actions is always the same.

---
Tags: networking, rts, synchronization, latency
---


# Question
Title: Is a sequential update method really acceptable and is there a sane alternative?
A sequential update method is the update method pattern (e.g. as described here) where all game entities have their update methods called sequentially, even if this means the order of the entities ends up impacting the end result.

This has two obvious downsides (simplified, of course):

1. Order matters, which also makes its results technically incorrect (since you're meant to be simulating simultaneous action).
2. Because it is sequential it can't be parallelized very easily.

Simplicity is always good, and it really does shine on that front. Still, is it really acceptable? Do real-world games actually use this?

As far as finding a more acceptable solution (which thus far I haven't): The previously linked article mentions Double Buffering as a possible solution, and most alternatives I've thought up thus far seem to boil down to some form of that.

Based on my own research and experimentation, alternatives to the sequential update method have problems of their own:

1. Simple double buffering isn't enough in practice. Changes from multiple sources end up overriding each other, so some way to cumulate them is needed (incrementing a value in the next buffer instead of just writing to it). At best this means a tiny bit of extra complexity, at worst it ends up being order-dependent again.
2. Complexity spirals out of control. Say you seperate out the physics into its own series of order-independent updates (e.g. move entities, check collisions, adjust positions), it quickly follows to do the same thing for every mechanism, which ends up becoming unmanageable.

Physics seem to want to be order-independent the most, though - and maybe I just haven't looked in the right places - I wouldn't know of good way of seperating physics from other updating logic. I've been going in circles on this for a while now. Maybe I'm missing something really obvious here.

My problem boils down to how to deal with update ordering. **More specifically, is there a way to structure a game update that is order-independent (and parallelizable if possible) that doesn't drastically escalate complexity?** If not, is there some reasonable middle ground? E.g. doing only the physics in a seperate order-independent update and everything else in a naive order-dependent sequential update.

# Answer
> Still, is it really acceptable? Do real-world games actually use this?

Absolutely. Almost every game does, in some fashion.

Only simple games will actually put "every object" into a single list and update that in one big go. As you (and the book) notes, that can scale poorly, and doesn't handle some things, such as physics, that are going to want to deal with the simultaneous interactions.

The GPP book is describing patterns at a conceptual level, not documenting implementation (except when providing a specific implementation as a simplified example). Real-world games do use the described method all over, but often in slightly different, more-specific ways.

For example, most games will put objects into buckets based on object type (actors, physics bodies, particle systems, renderables). The buckets will be processed sequentially. Within each bucket, objects may be processed sequentially. Both the objects and the buckets are using the "update method" pattern, but at different levels of abstraction.

In cases where order doesn't matter, the pattern is fine. In cases where it could (like physics), variations on the technique are used. Concerns about parallel updates can be handled by sorting the objects as well, either into independent "islands" within an above-described bucket or because one knows that the update of two different buckets can be done at the same time because they don't depend on one another.

But all of those are built upon the basic idea of "telling each object in a set to process one frame of behavior." The pattern is just the name we give the basic shape of that solution.

> I haven't seen a good way of seperating physics from other updating logic. Do you do physics first, then everything else? Or the other way around? Do you do some things before physics and some after?

Generally input drives some game logic which may drive physics which may drive additional game logic which drives rendering. You can do some (or all) game logic before physics, or after, or a combination of both. Each approach produces slightly different results; whether or not it matters depends largely on the nature of the game and what game systems are in there, doing stuff.

It's true that all objects don't *actually* get updated at the same time. But it doesn't matter: the user does not *see* the results of that update until the frame is drawn, at which point all objects *are* updated, so it *looks like* they were all updated at the same time. This is generally good enough.

> I've been going in circles on this for a while now. Maybe I'm missing something really obvious here. Eitherways any help would be appreciated.

It seems to me like you're just stuck overthinking it. It's not a perfect system, it's true, but it's generally good enough that it works. Do you actually have a *specific problem* a sequential update is causing you, in your game? There may be a solution for it -- and if you asked a question specifically about that, I'm sure you'd be able to find people here who could help you with it. But if you're just worried about the abstract, theoretical idea that the technique has downsides, I'd try to push past that. All techniques will, and accepting that -- learning to pick which downsides impact your specific game the least -- is part of the whole process of making games.
> 2 votes

---
Tags: architecture, design-patterns
---


title: C4d or 3DS-like matrix rotations

text:
# Question
Title: C4d or 3DS-like matrix rotations
I have a rotation 4x4 matrix to generate a model matrix, but I would like to be able to control it like cinema4D or 3ds Max with three separate angles that are always perpendicular to each other, and so far I've had no luck...

Currently, every time I change one of the angles, I call a function containing the following code:

```
self->rot_matrix = mat4();
self->rot_matrix = mat4_rotate(self->rot_matrix, 1, 0, 0,
    rot.x);
self->rot_matrix = mat4_rotate(self->rot_matrix, 0, 0, 1,
    rot.z);
self->rot_matrix = mat4_rotate(self->rot_matrix, 0, 1, 0,
    rot.y);

```

This doesn't work though, because when I rotate around z or x, the y axis should change, but not the y angle... I'm terrible at this sort of mathematics, and would appreciate a simple explanation of what to do.

One idea I've had would be to have two vectors define the rotation system, and then use rodrigues rotation to update them, this I can do with ease, but I have no idea how to transform those two vectors back to a rotation matrix.

Thanks in advance!

# Answer
> 0 votes
> One idea I've had would be to have two vectors define the rotation system, and then use rodrigues rotation to update them, this I can do with ease, but I have no idea how to transform those two vectors back to a rotation matrix.

You're in luck! This part ends up being simpler than you might expect.

Let's say you're keeping track of a vector called X pointing along the object's local x axis, and a vector Y pointing along the object's local y axis, and you're carefully keeping them perpendicular and unit length after each transformation.

Now we can form the third vector Z along the object's local z axis using the cross product:

$$Z = X \times Y$$

Now we have an orthonormal basis for the rotated coordinate system, and your rotation matrix is simply these three vectors, stacked side-by-side as columns to make the top-left 3x3 block of the matrix.

$$R = \begin{bmatrix} X.x & Y.x & Z.x & 0 \\ X.y & Y.y & Z.y & 0 \\ X.z & Y.z & Z.z & 0 \\ 0 & 0 & 0 & 1 \\ \end{bmatrix}$$

(Assuming your multiplication convention puts the vector to the right of the matrix. Otherwise, take the transpose of the matrix above, so each of your basis vectors is a row.)

---
Tags: mathematics, rotation, angles
---


# Question
Title: State manager in Unity with coroutines not calling a function
I'm not sure why, but the FadeIn\_Enter function just doesn't get called with this code. No errors or anything and I can step over the line it should call the function but it doesn't. No debug statement is printed and it steps over it even if I try to step in. Any ideas why?

State.cs

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

public class State
{
    public Func<IEnumerator> Enter;
    public Func<IEnumerator> Update;
    public Func<IEnumerator> Exit;
}

```

StateManager.cs

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

public class StateManager
{
    MonoBehaviour mainObj;
    Dictionary<string, State> states = new Dictionary<string, State>();
    string currentState = "";
    string nextState = "";

    public StateManager(MonoBehaviour obj)
    {
        mainObj = obj;
    }

    public void AddState(string name, State state)
    {
        states.Add(name, state);
    }

    public void SetState(string name)
    {
        nextState = name;
    }

    public IEnumerator Update()
    {
        while (true)
        {
            if (nextState != "")
            {
                if (currentState != "")
                    states[currentState].Exit?.Invoke();

                currentState = nextState;
                nextState = "";
                //states[currentState].Enter?.Invoke();
                var func = states[currentState].Enter;
                func();
            }

            states[currentState].Update?.Invoke();

            yield return null;
        }
    }
}

```

Dungeon.cs

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

public class Dungeon : MonoBehaviour {

    public GameObject[] Battles;
    private StateManager stateMgr;

    // Use this for initialization
    void Start ()
    {
        // hide all enemies under all battles but the first
        for(var b = 1; b < Battles.Length; b++)
        {
            for( var i = 0; i < Battles[b].transform.childCount; i++)
            {
                Battles[b].transform.GetChild(i).gameObject.SetActive(false);
            }
        }

        stateMgr = new StateManager(this);

        stateMgr.AddState("fade.in", new State
        {
            Enter = FadeIn_Enter,
            Update = FadeIn_Update
        });

        stateMgr.AddState("player.turn", new State
        {
            Enter = PlayerTurn_Enter,
            Update = PlayerTurn_Update,
            Exit = PlayerTurn_Exit
        });

        stateMgr.AddState("enemy.turn", new State
        {
            Enter = EnemyTurn_Enter,
            Update = EnemeyTurn_Update,
            Exit = EnemyTurn_Exit
        });

        stateMgr.SetState("fade.in");

        StartCoroutine(stateMgr.Update());
    }

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

    }

    private IEnumerator FadeIn_Enter()
    {
        // todo:
        Debug.Log("FadeIn_Enter");

        yield return new WaitForSeconds(5);
    }

    private IEnumerator FadeIn_Update()
    {
        Debug.Log("FadeIn_Update");
        // todo: fade the screen in over time

        // todo: when complete change the state to have the player go first
        stateMgr.SetState("player.turn");

        yield return null;
    }

    // the players turn enter state
    private IEnumerator PlayerTurn_Enter()
    {
        Debug.Log("PlayerTurn_Enter");
        // show ui
        // pick which players turn it is

        yield return null;
    }

    private IEnumerator PlayerTurn_Update()
    {
        Debug.Log("PlayerTurn_Update");
        yield return null;
    }

    private IEnumerator PlayerTurn_Exit()
    {
        Debug.Log("PlayerTurn_Exit");
        yield return null;
    }

    // the enemies turn state
    private IEnumerator EnemyTurn_Enter()
    {
        Debug.Log("EnemyTurn_Enter");
        yield return null;
    }

    private IEnumerator EnemeyTurn_Update()
    {
        Debug.Log("EnemyTurn_Update");
        yield return null;
    }

    private IEnumerator EnemyTurn_Exit()
    {
        Debug.Log("EnemyTurn_Exit");
        yield return null;
    }
}

```

# Answer
> 1 votes
To call your State functions you use Invoke() which is akin to calling a coroutine like a normal method (e.g. "RunCoroutine()"), it does nothing. Instead of using Invoke() use yield return FUNCTIONNAME.DynamicInvoke(). In short change StateManager.Update() to something like this:

```
public IEnumerator Update()
{
    while (true)
    {
        if (nextState != "")
        {
            if (currentState != "")
                if(return states[currentState].Exit != null)
                    yield return states[currentState].Exit.DynamicInvoke();

            currentState = nextState;
            nextState = "";

            if(states[currentState].Enter != null)
                yield return states[currentState].Enter.DynamicInvoke();
        }

        if(states[currentState].Update != null)
            yield return states[currentState].Update.DynamicInvoke();

        yield return null;
    }
}

```

---
Tags: unity
---


title: Axis Aligned Bilboards in shader

text:
# Question
Title: Axis Aligned Bilboards in shader
Hi I need to implement following effect using vertex shaders. Basically its a shader for particle laser beam that rotates to particle along its own y axis till its "best" visible (Roughly).

My idea was:

1. Take "y" axis of particle model (its a rectangle) and transform it to view space ("vy").
2. Calculate the vector orthogonal to "vy" and eye vector ("w"), to get the direction on the screen which "x" of partilce should be oriented.
3. Change particle vertices model coordinates using "w" instead of x.

# Answer
> 0 votes
It seems I've did the shader I was hoping too, its complicated though for a such simple thing to do and maybe i've missed something.

```
#version 120
// simple vertex shader
uniform mat4 viewMatrix;
uniform mat4 gl_ModelViewMatrix;
uniform mat4 gl_ProjectionMatrix;

const vec4 ex = vec4(1.0,0.0,0.0,0.0);
const vec4 ey = vec4(0.0,1.0,0.0,0.0);
const vec4 ez = vec4(0.0,0.0,1.0,0.0);

void main()
{

  // for rotation matrices this is inverse
  mat4 tvm = transpose(gl_ModelViewMatrix);
  vec3 up = gl_ModelViewMatrix[1].xyz; // ey na to przechodzi

  // question is what the direction in model space is transformed
  // onto x-y view plane and is orthogonal to beam direction
  vec4 w = vec4(normalize(cross(ez.xyz, up.xyz)), 0.0);
  // cool now invert it to get direction in model space
  vec3 invW = (tvm*w).xyz;

  vec3 pos = vec3(gl_Vertex.x * invW, gl_Vertex.y, gl_Vertex.z);

  gl_Position    = gl_ModelViewProjectionMatrix * vec4(pos, 1.0);
  gl_FrontColor  = gl_Color;
  gl_TexCoord[0] = gl_MultiTexCoord0;
}

```

# Answer
> 0 votes
Axis Aligned billboards can be done through a simple technique.

steps 1 to 4 can be done in CPU as it will be used by all boards.

1. Firstly, create your billboard in a plane XY. The normal will be assumed to be Z (or in this case vector 0, 0, 1.
2. Secondly, calculate the camera direction and negate this (normalise also), this will be the target direction for your billboard.
3. Calculate the angle between the starting normal, and the camera direction normal. Using a Dot product and a cross (to get the axis).
4. Using the angle and the axis, you can create a rotation matrix.
5. Apply the billboard matrix to align to the direction of the camera, then apply your WVP matrix to bring it into the perspecitve and world locations.

I've attached my C# SHarpdx code for your inspection. This creates the matrix.

```
        //======================================================================================================================//

    void CalculateBillboardMatrix(Vector3 a_targetDirection, ref Matrix a_billboardMatrix)
    {
        Vector3 veca = a_targetDirection;
        Vector3 vecb = new Vector3(1, 0, 0); // this is always the direction the particle is initially created in.
                                             //      veca.Normalize();
        VectorExt.Normalise(ref veca);

        if (Vector3.Dot(veca, vecb) != 1.0f)
        {
            Vector3.Cross(ref veca, ref vecb, out Vector3 axis);
            VectorExt.Normalise(ref axis);

            float angle = VectorExt.AngleBetweenVectors(ref vecb, ref veca, ref axis);

            a_billboardMatrix = Matrix.RotationAxis(axis, angle);

        }
        else
        {
            Vector3 offcentre = new Vector3(0.01f, 1, 0.01f);

            a_billboardMatrix = Matrix.RotationAxis(offcentre, 0.0f);
        }

    }

```

There are more advanced versions of this which I can give you to randomise the orientation.

You should do these in the Geometry shader though. Excerpt from my shader. This sample allows you to pass a random up vector in, I also pass in the size of the geometry I want also. You need to create up and right vector to create the geometry, I mult by the billboard matrix, as it ends up saving 2 matrix mults.

```
    randomUp = (Random updirection in the XY plane).

    float4 startup = float4(randomUp , 1);
    float4 startright = float4(cross(startup.xyz, float3(1, 0, 0)), 1);

    look = mul(startup, AirBillboardMatrix).xyz;
    right = mul(startright, AirBillboardMatrix).xyz;
    //
    // Compute triangle strip vertices (quad) in world space.

    float4 geometry = inputVertex.geometry;
    float4 v[4];
    v[0] = float4(inputVertex.pos.xyz + geometry.x * right - geometry.y * look, 1.0f);
    v[2] = float4(inputVertex.pos.xyz + geometry.x * right + geometry.y * look, 1.0f);
    v[1] = float4(inputVertex.pos.xyz - geometry.x * right - geometry.y * look, 1.0f);
    v[3] = float4(inputVertex.pos.xyz - geometry.x * right + geometry.y * look, 1.0f);

```

Ask away. I will also direct you to the answer I have done in another thread -\> Orientating billboards

---
Tags: shaders, particles
---


# Question
Title: How to efficiently keep the player from moving outside the gameobject he is colliding with?
I am developing a game with Unity 2017. The game mechanics are as follow:

* Classic top-down RPG;
* Movements are: UP, DOWN, LEFT and RIGHT;
* Player evolves in a 16\*16 map;
* He can dig in the direction he wants to make his way through the map one tile at a time;

At first I was using a very classical approach using tilemaps, **RigidBody2D** and **BoxCollider2D** on tiles and the player **GameObjects**.

Collision detections went fine and my tilemap looked pretty much like that (red being the walls and white the empty spaces):

The problem with this approach is that I have to keep in memory the state of 256 tiles in a `List<Vector2f>` and to create the 256 expected GameObjects representing either my walls (which a totally black), or my floor (the empty space).

Creating a black **GameObject** with its own **BoxCollider2D** for each of the tile seems a little bit overkill. And this brings me to the second iteration of my game: to keep in memory only the tiles the player digged.

What I would like to achieve efficiently, is to let the player evolve as long as he is colliding with an underlying tile, but stop moving as soon as he doesn't.

This is ok:

This isn't, and player should be placed to previous state.

I could take advantage of `OnTriggerEnter2d` and handle custom collision and response, but I have the feeling that something more simple and more optimized may exists somehwhere in the wild!

Thanks to any help provided!

# Answer
> 3 votes
About what you consider "elegant":

* Every single `GameObject` & associated `Transform` component incurs overhead.
* Every single `Collider` component incurs overhead. Concave mesh colliders are VERY costly.
* Save your *limited* `GameObject` budget for those things that really need it, like characters, missiles, triggers, etc. Exceeding a certain number of `GameObject`s, things get slow, *real* fast.
* There is a ton of custom code in every Unity project under the sun, that does *not* need these.

...They are excellent for more complex cases where you need flexibility. In your case that does not apply *AT ALL*. In fact, yours is the simplest case of collision detection & resolution in existence:

```
struct Tile
{
    bool isOpen;
    //whatever else you need, like terrain type etc.
}

Tile[,] tiles = new Tile[WIDTH, HEIGHT];

Vector2 north = new Vector2(0, -1);
Vector2 south = new Vector2(0, +1);
Vector2 east  = new Vector2(+1, 0);
Vector2 west  = new Vector2(-1, 0);

void HandleMoveAttempt(Vector2 direction)
{
    Vector2 proposedPos = playerPos + direction;
    Tile proposedTile = tiles[proposedPos.x, proposedPos.y];
    if (proposedTile.isOpen)
        playerPos += proposedPos;
    //else leave them where they are.
}

void Update()
{
    if (Input.GetKey(KeyCode.LeftArrow))
       direction = west;
    if (Input.GetKey(KeyCode.RightArrow))
       direction = west;
    if (Input.GetKey(KeyCode.UpArrow))
       direction = north;
    if (Input.GetKey(KeyCode.DownArrow))
       direction = south;

    HandleMoveAttempt(direction);
}

```

You'll notice that `HandleMoveAttempt()` either performs an instant move to the new cell, or does not even *try* to go there (`else`). Your setup may not require instantaneously moving from the centre of one cell to the centre of another (which is the simplest use case and hence why I supplied it here) but rather, the player may move in small increments via keys, mouse or gamepad, to gradually try to cross tile boundaries. That's OK: this style of collision detection and resolution still suits.

But in that case let me know so I can update the answer if still not clear.

# Answer
> 0 votes
Per the comments...

```
movePlayer();

bool collision = false;

for (i in numTiles)
{
    If (player collides with tile i) collision = true;
}

if (!collision) movePlayerBack();

```

I still recommend calculating the index of the tiles around you, and doing your collision detection with just the tiles around you.

# Answer
> 0 votes
This is going to be a code-less answer, but there should be enough here for you to write the code yourself.

So, rather than trying to use colliders to keep the player *inside* the collider volume, use colliders to do what colliders do best: keep the player out.

Instead of having *every block* have a collider (as this would be performance intensive for having hundreds of colliders that could never be collided with), only add colliders to the block adjacenet to empty spaces. When the player mines out a tile, destroy it, loop over the 8 adjacent tiles, and for each that a) still exists as a wall and b) does not already have a collider: add a box collider component. You may even only need to check the 4 orthogonally adjacent tiles, if your player can't move diagonally through a gap.

This will keep the performance low as well as keeping the complexity of your own code low.

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


# Question
Title: Rotating a vector by another vector in shader
I have a terrain surface with a normal for each point on the terrain.

I have a second detail normal map to be applied to the terrain.

* These normals are in 3-space.
* The Y value of both normals is **always** positive.
* The X,Z values of both normals can be positive/negative/zero.
* The 1st normal vector (blue) that we are rotating the 2nd vector (orange) by, can be almost horizontal.

I am okay with an approximate solution if it makes it easier/faster to compute.

In the above image, you see the blue surface normal (from the 1st normal map), the orange normal map normal (from the 2nd normal map), and the green desired result normal.

The amount that the orange vector is rotated should be roughly (or if possibly exactly) equal to the angle that the blue normal vector forms with the XZ plane (where Y is up, like the DirectX coordinate system).

Here is a second scenario:

In the above image, the blue surface normal is almost horizontal, so the 2nd normal map is being applied to an almost vertical surface, thus the orange normal map vector is rotated further.

The rotation is being implemented in a HLSL shader.

How do I rotate the 1st orange normal based on the direction of the 2nd blue normal?

Edit: Maybe I need a tangent and bitangent as well as the normal?

Here's how I get the normal:

```
float4 ComputeNormals(VS_OUTPUT input) : COLOR
{
    float2 uv = input.TexCoord;

    // top left, left, bottom left, top, bottom, top right, right, bottom right
    float tl = abs(tex2D(HeightSampler, uv + TexelSize * float2(-1, -1)).x);
    float  l = abs(tex2D(HeightSampler, uv + TexelSize * float2(-1,  0)).x);
    float bl = abs(tex2D(HeightSampler, uv + TexelSize * float2(-1,  1)).x);
    float  t = abs(tex2D(HeightSampler, uv + TexelSize * float2( 0, -1)).x);
    float  b = abs(tex2D(HeightSampler, uv + TexelSize * float2( 0,  1)).x);
    float tr = abs(tex2D(HeightSampler, uv + TexelSize * float2( 1, -1)).x);
    float  r = abs(tex2D(HeightSampler, uv + TexelSize * float2( 1,  0)).x);
    float br = abs(tex2D(HeightSampler, uv + TexelSize * float2( 1,  1)).x);

    // Compute dx using Sobel filter.
    //           -1  0  1
    //           -2  0  2
    //           -1  0  1
    float dX = tr + 2*r + br - tl - 2*l - bl;

    // Compute dy using Sobel filter.
    //           -1 -2 -1
    //            0  0  0
    //            1  2  1
    float dY = bl + 2*b + br - tl - 2*t - tr;

    // Compute cross-product and renormalize
    float3 N = normalize(float3(-dX, NormalStrength, -dY));

    // Map [-1.0 , 1.0] to [0.0 , 1.0];
    return float4(N * 0.5f + 0.5f, 1.0f);
}

```

How might I get the tangent and bitangent vectors then?

Is it enough to take the cross product of the normal with the Z axis unit vector to find the tangent vector? (Since the normal.Y is always positive, where Y is up, and Z is pointing into your screen).

And then take that tangent vector and cross it with the normal to obtain the bitangent?

And then take the normal, tangent and bitangent together to form a rotation matrix to rotate the orange normal map vector?

Even if that works, this seems like a lot of computation for a pixel shader. Does this work, and is there a more efficient way?

Edit:

This image may help you understand what I'm trying to do:

If you know what normal mapping is, then this should be straightforward, I think.

I'm trying to take the normal map, which contains various normals, and apply them to a surface. The surface has it's own normals. The normal map will contain many more normals than the surface, so several normal map normals are sampled across a single part of the surface that has only a single normal.

# Answer
> 4 votes
I think I get your question, although the title and the 2 first pictures are confusing.

The problem is, there is a normal-map to be mapped on a xz-plane (the orange vector). Now the actual plane described by the blue normal is not necessarily in the xz-plane, so one must find a rotation from the xz-plane to the actual plane, in order to rotate the orange vector to map it on the actual plane.

Now how can we do that? Bacially we must find the rotation, that rotates the xz-plane to the plane described by the blue normal.

1. Find the rotation-axis by taking the cross-product of the blue normal and the normal from the xz-plane {0, 1, 0}, the orange vector must be roatated around this axis.

```
axis = N_xz cross N_blue

```
2. Find the rotation angle by taking arccosine of the dot-product of both normals

```
angle = acos(N_xz dot N_blue)

```
3. Now create a rotation-matrix from those values and transform the orange normal with that matrix.

# Answer
> 2 votes
I believe you're over thinking your problem.

To get back to standard normal mapping, you normally have 3 vectors: the surface normal, a tangent vector perpendicular to that one, and a cotangent perpendicular to both of those. Together, these form the tangent space in which the normal map describes a direction. With this setup, you just have to multiply each component read of the normal map with its respective tangent space axis, and sum the results.

So you have a terrain, and a normal map you'd like to apply to it. You've already worked out how to take the delta height and generate a surface normal. You're now looking for the tangent and cotangent.

So what IS a tangent? Well, from the description above, it's actually the 3D direction described by one of the UV axes in your texture mapping. After all, that's what it gets used for, right? So how do you find this direction? Well, given an arbitrary mesh, it's a little tricky; but given a regular grid terrain, it's self evident: if you have a regular grid with regular UVs, then the tangent and cotangent directions are just the two axis aligned edges leaving your vertex.

So, you know what the heights of points around you are. You can pass in how far away these points are on the plane. Subtract those from the point you're on, normalize, and there you go: instant tangent space.

# Answer
> 0 votes
If you do have the tangent also, you can use this function to generate the bumped normal you are after. Otherwise, feel free to plagiarise in future!

```
//------------------------------------------------------------------------------
// Transforms a normal map sample to world space.
//------------------------------------------------------------------------------

  float3 NormalSampleToWorldSpace(float3 normalMapSample, float3 unitNormalW, float3 tangentW)
    {
        // Uncompress each component from [0,1] to [-1,1].
        float3 normalT = 2.0f * normalMapSample - 1.0f;

        // Build orthonormal basis.
        float3 N = unitNormalW;
        float3 T = normalize(tangentW - dot(tangentW, N) * N);
        float3 B = cross(N, T);

        float3x3 TBN = float3x3(T, B, N);

        // Transform from tangent space to world space.
        float3 bumpedNormalW = mul(normalT, TBN);

        return bumpedNormalW;
    }

```

# Answer
> -1 votes
You can use the LERP function, this will linearly interpolate between the two vectors. Giving you a nice 'averaged' normal.

http://msdn.microsoft.com/en-us/library/bb509618(VS.85).aspx

(Of course this is not really rotating, but given the orange and blue vector this will get you the green vector)

---
Tags: mathematics, hlsl, vector, linear-algebra, shaders
---


# Question
Title: (Unity) Shortest way to instantiate an object and obtain it script
Normally I use

```
ScriptName script = ((GameObject)Instantiate(
        Resources.Load("Prefab"),
        new Vector3(x, y, z),
        Quaternion.identity
    )).GetComponent<ScriptName>();

```

It is a little too long and too much of brackets, so I wondering if there is any other way to get instantiated object's script without break it in two statements.

# Answer
> 3 votes
Whenever I can, I try to hold a reference to the prefab(s) I might want to use, rather than use Resources.Load - that way they can be pre-fetched when I load the content that might use them, so I never have a hitch when spawning a new thing. It also helps me avoid accidental build bloat from having files in a Resources folder that I'm no longer using anywhere. With direct references, unused assets can be detected and stripped out at build time.

Here I'd have a member variable in the class that needs to do the spawning (or in a "dynamically spawnable objects catalog" that it can access) that's already typed as the kind of script I want out of it. That helps advertise intent in the Inspector, and prevents errors where I accidentally assign a prefab without the needed script.

```
public ComponentTypeIWant prefab;

```

Then when I want to spawn it, I write:

```
var spawn = Instantiate<ComponentTypeIWant>(
                 prefab,
                 new Vector3(x, y, z),
                 Quaternion.identity
            );

```

No GetComponent required - Instantiate returns the desired component directly (while still spawning the whole GameObject with all its scripts and child hierarchy intact).

# Answer
> 2 votes
The only thing you can do to make it shorter is to write a generic wrapper of some sort, with some overflow functions. This way you can just write:

```
    TestScript testScript = GenerateObject<TestScript>("cube", Vector3.zero, Quaternion.identity);
    TestScript testScript2 = GenerateObject<TestScript>("cube", Vector3.zero);
    TestScript testScript3 = GenerateObject<TestScript>("cube");

```

And the wrappers would look like:

```
public static T GenerateObject<T>(string name) where T : MonoBehaviour{
    return GenerateObject<T>(name,Vector3.zero,Quaternion.identity);
}

public static T GenerateObject<T>(string name, Vector3 position) where T : MonoBehaviour{
    return GenerateObject<T>(name,position,Quaternion.identity);
}

public static T GenerateObject<T>(string name, Vector3 position, Quaternion rotation)  where T : MonoBehaviour{

    // Verify object exists at load location
    UnityEngine.Object obj = Resources.Load(name);
    if (obj == null){
        Debug.LogError("Object does not exist within resources");
    }

    // Verify GamObject type when loading from Resources
    GameObject objToSpawn = obj as GameObject;
    if (objToSpawn == null){
        Debug.LogError("Loaded resource was not a GameObject");
    }

    GameObject gameObj = GameObject.Instantiate(objToSpawn,position,rotation);

    // Verify desired component is attached
    T component = gameObj.GetComponent<T>();
    if (component == null){
        Debug.LogError("LoadedResource did not have required component");
    }
    return component;

}

```

That being said, you should probably create a resource manager for your game that stores references to prefabs in some fashion so you aren't doing a ton of loading from Resources, or only load from resources once and reuses that reference whenever that asset is called for again. It is especially important for larger files, like textures.

# Answer
> 1 votes
I...think that's about as succinct as you can get.

Nominally you can exclude the position and rotation parameters from `Instantiate()` and you could use the Generic form of `Resources.Load<>()`, but it doesn't save you a whole lot:

```
ScriptName script = (Instantiate(
        Resources.Load<GameObject>("Prefab")
    )).GetComponent<ScriptName>();

```

This, of course, assumes you don't care where your GameObject ends up and what rotation its facing, but it is, technically, shorter. `Quaternion.identity` is a default, so if you do need the position, but not rotation, you can omit that line entirely:

```
ScriptName script = (Instantiate(
        Resources.Load<GameObject>("Prefab")
        new Vector3(x, y, z),
    )).GetComponent<ScriptName>();

```

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


# Question
Title: Unity: Render only select objects but show previously rendered objects
I am making an RTS game which is having performance issues.

Is it possible to render the ground and units separately so I can only render the ground when the camera moves but keep the result displaying the units over the top?

I'm not sure what details to include but:

\*The camera is fixed angle and orthographic

\*The profiler says drawing takes up about 50% of CPU when units are moving.

\*All the logic is done by a c# script outside of monoDevelopment but called through a gameobject each frame, (takes 2% of cpu in tests).

\*Units are put in place using the "transform.position" command each frame.

\*Units and tiles are instantiated and destroyed when the Camera passes them.

\*The game is using rigged .3ds models for the units.

\*The units have disabled rigidbodies.

\*Each tile in the game is a separate sprite.

\*The performance drops with ~100 low poly units without animation or ~20 higher poly units with animation.

# Answer
Well, from your list, I can tell you somethings that may be the cause of lag:

* Destroying and creating objects:

I think this is what is overkilling your performance. Creating and destroying them over and over, especially in large count, usually drops your performance (this is from experience). One fix would to be to simply place the objects in the scene and moving the camera via script.

* Setting the position via transform.position.

This could be causing the lag also. As far as I can tell, it seems pretty pointless to do so *every single frame* (unless there is something I am missing). You should only change their position that way only when you need to.

Another thing that may help a little is instead of having all of those ground tiles, create a tiling material and apply it to a very large plane. This should create the same effect (unless you have other tile types that wouldn't fit with that).
> 2 votes

---
Tags: unity, rendering, optimization
---


# Question
Title: Are references between entities in Entitiy Component System allowed?
I've got a player entiy in my game that can pick up weapons when colliding with item entities. The player can hold and use the weapon in their hand (the weapon sprite is rendered relative to the carrier).

I'm wondering how to design weapons and items in an ECS approach. Should the weapon be an entity the whole time so that the player entity has a weapon-component which holds a reference to the weapon-entity?

# Answer
There is no Council of Entity System Design that is going to fine you if have references between your entities. If that's how you want to build the system so it works for you, go for it. There isn't a single "correct" way to create an entity system.

For your specific situation, I'd probably expect to see something where you have an entity for the player, and that entity has an "inventory" component. You also have entities for the weapons that are placed around the world, and they have an item component that indicates what they are.

However, the item component and the inventory component both refer to a third structure, called `ItemDefinition` or whatever. That third structure contains *data* for items or weapons, describing their non-instanced properties (name, what model they use, bullet type, damage, weight, et cetera). However this `ItemDefinition` *is not a component*.

There's no need to make *everything* a component when you are building a component-based entity system, and it can get confusing and create a complex hierarchy of sloppy organization.

In summary:

* Give the player entity an `InventoryComponent`, which has a list of `ItemDefinition` references (and possibly additional information like how much of each definition is carried, which "slot" in the inventory they take up, and so on).
* Give the items on the ground a `PickupComponent`, which has an `ItemDefinition` reference indicating which item will get picked up. When entities with inventories interact with an entity with a pickup, add the referenced item to the inventory.
* Store the actual data for the items outside the component system, because there really isn't a reason to entangle them and if you do you potentially start getting into silly situations involving deep hierarchical attachments of components.
> 3 votes

---
Tags: architecture, entity-system, component-based, design-patterns, ashley
---