title: Unity Geometryshader for one Vertex

text:
# Question
Title: Unity Geometryshader for one Vertex
Hy, I want to build some geometry with a geometryshader in Unity. I took a look at this. I want to create my geometry just in context of one point in 3D space (x,y,z). Can i somehow use the transform position vector as input value for the shader? Or is there Something like a one vertex mesh I could use? I tried this in Blender, but coulnd't import that single Vertex mesh into Unity. Thanks for your help!

# Answer
It worked. My Code:

```
    Mesh mesh = new Mesh();
    mesh.vertices = newVertices;
    mesh.uv = newUV;
    GetComponent<MeshFilter>().mesh = mesh;
    mesh.SetIndices(new int[] { 0 }, MeshTopology.Points, 0);

```

The last line creates was very important to create a trinagle. For saving the Mesh:

`AssetDatabase.CreateAsset(m1, "Assets/" + "oneVertexMesh" + ".asset"); // saves to "assets/"
 AssetDatabase.SaveAssets();`
> 1 votes

---
Tags: shaders, graphics, unity, geometry-shader
---


# Question
Title: Finding it difficult getting to grips with LibGDX
So I have spent about a week now learning libGDX and have made very little progress.

I started small and wanted to make a strategy game where there is a tiled map of squares and you control a ship, move it from tile to tile to take out enemy ships. After a week of troubleshooting I have only just managed to import and render the map and can barely get sprites to render in the right places. Having read the libGDX wiki multiple times I can still find very little documentation online about making strategy games with libGDX and I'm pretty stuck.

Did I pick the wrong framework ? or am I just not looking in the right places?

From what I have read online libGDX is not the best on documentation so is it right for a beginner like me or would something else be better? Thanks :)

# Answer
Try some video tutorials online.

LWJGL is several times more difficult to use than LibGDX and I got relatively good at it through ThinMatrix's video tutorials.

Hearing somebody explain *why* something is part of the library, as well as how to use it, with the example, is extremely helpful.

The following goes without saying but: don't copy or fully understand everything that you are copying.

The fact that it's a strategy game is pretty irrelevant - the LibGDX framework works for any sort of game you want.
> 0 votes

---
Tags: java, libgdx, strategy
---


# Question
Title: How do I highlight terrain around an object within certain radius?
In my project, a player is not allowed to place forces in a given radius around enemy defensive forces. I would like to distinguish this area using some sort of highlight.

Second, I want calculate the radius for each enemy when the player placing forces clicks to check whether this player can put it there or not. Is there a more optimized way to do this other than looping through each character?

# Answer
For the highlight, you can use an Orthographic projector to project a round (or whichever) texture. The X and Z position of the projector will be the same as the enemy's X-Z position, and the Y position will be `terrain.size.y + 1`.
> 1 votes

---
Tags: unity
---


title: Confused about arrays in C

text:
# Question
Title: Confused about arrays in C
Hey guys I am learning the basics of C language and I am a little bit confused about how to use arrays.

I mean what are they used for?

# Answer
Ever made a shopping list?

That's an array of type `std::string[]`. Or if you want to get really technical, it could be considered an array of type `ItemConsumable[]` (because "Steve" is a valid string, but you certainly can't buy him!)

In game programming, you would just arrays (or lists) to keep track of objects, actions, events, or other data. It entirely depends on the use. You might even have a (two dimensional!) array that your units use for pathfinding.
> 2 votes

# Answer
First of all. C is not the same as C++. (They are different programming languages)

Now, (trying to explain without making it too complicated), arrays are lists of variables.

**(The image has Numbers with capital letters, my fail, ignore that, shouldn´t have the starting letter in capitals)**

For example, `int numbers[10];` is an array that contains space for 10 ints (numbers).

You can access values from the array ("list"):

```
exampleIntVariable = numbers[1];

```

Our variable will have the value of the **2ND** number in our list **(The first one is numbers\[0\])**
> -1 votes

---
Tags: c
---


title: Libgdx rendering problems

text:
# Question
Title: Libgdx rendering problems
Have problems with rendering moving character using ShapeRenderer, it twitches while moving, and I don't understand where from comes the problem - bad game structure (do I need to override **draw** method from my actor,or just **draw** all entities in Stage's draw method) or troubles with movement logic.I'll add information if needed.

MainClass:

```
public class MFightGame extends Game {

@Override
public void create() {
    setScreen(new GameScreen());
}

@Override
public void render() {
    super.render();
}}

```

GameScreen:

```
public class GameScreen implements Screen {

private GameStage stage;

@Override
public void show() {
    stage = new GameStage();
}

public GameScreen() {

}

@Override
public void render(float delta) {
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
    stage.draw();
    stage.act(delta);
}

@Override
public void resize(int width, int height) {
    // TODO Auto-generated method stub
}

@Override
public void pause() {
    // TODO Auto-generated method stub
}

@Override
public void resume() {
    // TODO Auto-generated method stub
}

@Override
public void hide() {
    // TODO Auto-generated method stub
}

@Override
public void dispose() {
    // TODO Auto-generated method stub
}}

```

GameStage:

```
public class GameStage extends Stage {
private Creature creature;
private final float TIME_STEP = 1 / 300f;
private float accumulator = 0f;
private ShapeRenderer renderer;
private OrthographicCamera camera;

public GameStage() {
    creature = new Creature(100,100);
    addActor(creature);

    camera = new OrthographicCamera(800, 600);
    camera.position.set(camera.viewportWidth / 2f,
            camera.viewportHeight / 2f, 0);
    camera.update();
    renderer = new ShapeRenderer();
    renderer.setProjectionMatrix(camera.combined);
    Gdx.input.setInputProcessor(new InputHandler(creature));

}

@Override
public void act(float delta) {
    super.act(delta);
    accumulator += delta;
    while (accumulator >= delta) {
        accumulator -= TIME_STEP;
    }
}}

```

# Answer
Disabling **vertical synchronization** solved my problem, movement become smooth.
> 0 votes

# Answer
Usually, when you want to move an actor, you use an static value (speed) and delta together to calculate the distance move in that Loop/Frame.

I´ve never used Stage before, so I might be wrong, but I see you are using

```
accumulator += delta;

```

I would suggest using something like this:

```
accumulator = accumulator + (speed * delta); //speed being a pre-defined value.

```

"float delta" value can be totally different in each loop, with this method you reduce that difference effect on the movement.

I might be making a mistake, as I said, I´ve never used Stage, although I have used libGDX before, and that is how I always calculate movement on my games.
> 0 votes

---
Tags: java, libgdx, graphics
---


# Question
Title: How to make the inside of a cube accessible
I have a cube, it is made up of smaller cubes each making the big cube 8x8x8. The cube is the map. The player of the game needs to be able to appraise the entire map and understand it without having to zoom through the inside of the cube since he may need to see opposite ends and interior at the same time.

How can I make this cube easy for the player to access? Requirements:

* Player must be able to see any 2 cubes at the same time, including the interior.
* Player must be able to understand depth of cube
* Player must be able to click on interior cubes.
* Player must be able to differentiate between allied/enemy soldier, and soldier class.

if it helps at all, imagine if the rubiks cube had more cube inside it, obviously in the real world, we have no way to control them, but in a game, how would i allow someone to see and manipulate several at one time. Note: not a realtime game.

# Answer
You could try spreading the cubes out so there's space between them. Make a giant 3D grid of the cubes that the player can rotate around, with further ones being smaller to give depth. Since they're all spread out and rotatable, you can see any two cubes at a time and still click the interior ones. Differentiating between unit classes seems like a different question though.
> 2 votes

---
Tags: 3d, gui, simulations, turn-based-strategy
---


# Question
Title: How to convert velocity (Vector) to m/s (Scalar)
I have a variable called `velocity` which I get from a dynamic body in Box2D. It is the velocity of a pirate ship and when I add torque to the ship I want that to be proportional to the speed (m/s - 10px = 1m). My problem is that I can't divide/multiply a float (`proportionalTorque`) by the Vector2 quantity of the velocity so what I need is a way of getting the speed (m/s) from the velocity or if there's any other way of multiplying a float by a vector that'd be useful too.

# Answer
> 3 votes
Sounds like you're looking for the **vector magnitude**, also called (depending on context) its length, Euclidean norm, or Pythagorean Theorem.

ie. `speed = sqrt(dot(velocity, velocity));`

As Alexandre Vaillancourt points out, in libGDX the `len()` method does exactly this. Other environments will almost always have an equivalent (eg. in Unity it's `.magnitude`)

The units of this speed are the same as the units of your velocity, so if going 1 m/s along the x-axis is represented as...

* `velocity = (1m, 0, 0)` then your `speed` as calculated above is already in m/s and you're done. :)
* `velocity = (10px, 0, 0)` then your `speed` as calculated above is in px/s, and you'll need to divide by `pixelsPerMeter` value (10, as described in the question) in order to convert it into m/s

# Answer
> 0 votes
Generally, when using a vector2 to represent velocity, the length of the vector is the speed, while the coordinates represent the orientation (the direction of the speed).

To extract the length of your `velocity` vector, use the `.len()` method of your vector:

```
float speed = velocity.len();

```

This is described in the doc.

---
Tags: java, libgdx, vector
---


# Question
Title: Why do I not see the back of a model in the model
I have created a die in blender, that uses two materials. One material is transparent and the second is opaque.

When I look throught the die, I expect to see the opaque parts blocking the view, but I do not see them at all.

As you can see in the image above, the 6 dots on the back of the die are not shown, it just looks like it is empty.

What can I do to fix this?

# Answer
> 2 votes
You don't see the back faces of a model because the model's faces are one sided. By default, for most applications, faces are one sided. Some programs (such as Sketchup) render faces double-sided by default (I use Sketchup frequently, and also have to regularly flip the surface normals before importing into Unity). I do not know about Blender, but I suspect it double-side-renders by default as well.

I am not sure how to go about making the faces dual-sided (I am not a Blender expert) but an alternative solution would be to duplicate the model file, flip that model's normals, and use both the right-side-out version and inside-out version as one prefab.

---
Tags: unity, blender
---


title: OpenGL color overlay

text:
# Question
Title: OpenGL color overlay
I want to create a pause menu where everything in the background gets darker. I've looked up a bunch of possible solutions (even the second page on google) but it doesn't seem to work. I do already have something in my code that makes a single texture darker when hovered over, by calling: `GL11.glColor3f(alpha, alpha, alpha);` before drawing vertices. What I want to achieve is everything getting darker, so when hovering over a texture it should be even darker than before so it is still darker than the rest in the background when that has been made darker because of a pause menu that pops up.

Another thing I noticed is that `glColorMask(true, false, false, true);` does not get overridden and blends colours everywhere, so I was wondering if there is a version of this method that puts a transparent black overlay so everything becomes darker. I have enabled blending.

-Edit-

One solution I came up with (not just now) is multiplying `alpha` in every glColor3f function with a variable that is smaller than 1 so everthing gets relatively smaller, but I worry about this being uneffective and badly mantainable

# Answer
> 2 votes
`GL11.glColor3f(alpha, alpha, alpha);` won't work for 2 reasons:

1. It's opaque. You'd need `GL11.glColor4f(alpha, alpha, alpha,alpha);`
2. It affects the *next* object to be rendered, not everything *already* rendered.

It would be easier to render a semi-transparent quad over the whole screen (with a slightly higher z-depth) prior to drawing the menu. This will cut down on the amount of code necessary to achieve the effect, GPU-time its probably slightly worse, but only slightly.

---
Tags: opengl, java, lwjgl, transparency
---


# Question
Title: Z - Axis value is changing if I move the Game Object in X - Axis in Unity
I am on a small game project . Everything was just fine , but now I have some wired problem . That is Game Object movement . If I move the game object in X - Axis using the gizmo , the value of Z - Axis is changing . And if move in Z - Axis the value of X - Axis is changing . This is totally wired to me .

The game object is Empty Game Object and It is in the scene as a Child . Its position is as follow :-

```
One Game Object
      Another Game Object
           My Empty Game Object which is acting wired

```

Here are the screen shots :-

So why it is behaving so wired ? What is the problem ?

I hope you will help me to figure it out .

Regards

NB :)

# Answer
> 2 votes
One of the two parents is rotated 90 degrees around the Y axis. I can't be sure which way, but you can "fix" this by toggling Global/Local gizmos (its one of the two buttons in the upper-left corner, just above the "scene" tab).

That, or un-rotating the parent object.

---
Tags: c#, movement, unity, axis
---


# Question
Title: Gravity and Jumping in Clickteam Fusion 2.5
So I'm currently building a bare-bones functioning game that involves simple platforming. Quite literally a box moving left and right and jumping. I'm using Clickteam Fusion 2.5, and I know there's an option to assign platforming movement to an active object, but I honestly do not enjoy implementing that feature one bit.

So instead I'm opting for simply adding or subtracting from the X and Y coordinates of the player object while the left and right arrow keys are held down for side-scrolling movement.

However, I have yet to figure out how to use this same method for jumping and gravity. I know being able to jump would be running an event that occurs after hitting a certain key, which takes in the current Y-coordinate of the player and runs it through a parabolic formula. And then gravity would simply be constantly subtracting from (or I guess in Fusion's case, adding to) the current Y-value of the player object while the frame is running. So the question simply is where and how do I implement these things in order to create jumping and gravity. I figure there's a correct syntax for a parabolic formula when creating an event after "jump" is pressed, but for the life of me I can't figure it out. As for gravity, I'm completely lost. I have managed to get down stopping movement when colliding when another object so that is not an issue.

Thanks and appreciation in advance.

# Answer
> 2 votes
It sounds like you want to implement your own physics instead of using what's built in. Fortunately, you don't have do any kind of parabolic calculation when jumping (unless you want to project the path of the character or something like that). Instead, you let physics run its course which will naturally create parabolic shapes. Here is some example code for very simple physics:

```
Vector2 velocity = Vector2.new(0, 0);
Vector2 acceleration = Vector2.new(0, 0);
bool onGround = true;

function onJump() {
    velocity.Y = jumpVelocity;
    onGround = false;
}

function onLand() {
    velocity.Y = 0;
    onGround = true;
}

function update(delta) {
    if(!onGround) {
        acceleration = Vector2.new(0, -gravity);
    } else {
        acceleration = Vector2.new(0, 0);
    }

    velocity += acceleration * delta;
    character.position += velocity * delta;
}

```

What's fun is that you can use this same thing for your lateral velocity as well. Instead of merely shifting the character over by a set amount, you can just adjust the velocity in the X direction and the update loop will take care of updating the position.

This is by no means a complete physics system, but should be a good start if you want to implement physics yourself.

---
Tags: physics, mathematics, movement, platformer, clickteam-fusion
---


# Question
Title: In a 2D physics engine, how do I avoid useless collision resolutions when objects come to a rest?
In a physics engine I'm developing (for learning) using love-2d, I implemented collision resolutions in this way:

```
FixedUpdate(dt)  // I use fixed timestep
 foreach collide c1 in allNotStaticColliders
   c1.integartePhysic // i.e. apply gravitational force..
   foreach collider c2 "near" c1 // "near"= I use spatial hashing
      if collide(c1,c2)
        resolve collision (c1,c2)  // the heavy operation
        collison callbacks c1
        collison callbacks c2
        ...

```

As you can see at the end of the gif animation, there's a FPS decay when all colliders are almost grounded over a static object.

This because the number of collision resolutions grows as objects spend more time touching as they settle. However, many of the calculations are "useless" because objects have already settled into stable positions against each other.

What's the best practice (hopefully not requiring a physics degree) to avoid these "useless" collision detections?

Edit : accepted DMGregory hints and come to this result (not yet optimal)

(Red=static, Blue=active, Green=sleeping)

# Answer
I suspected OP already knew this approach so I mentioned it in a comment as just a starting point, but I'll try fleshing it out a bit more...

Most physics engines divide dynamic objects into two groups, "**awake**," and "**sleeping**."

**Objects sleep when they sit at rest, and wake when moved or accelerated by some outside influence.**

A **sleeping** object behaves like a static object in most respects - its movement isn't integrated over time (because it's at rest, so it has no movement) and the engine ignores collisions between objects that are sleeping or static.

A sleeping object sitting on a static floor doesn't fall through it, despite the lack of a collision response, because all movement integration is skipped for sleeping objects, including gravity.

So, only collisions involving at least one awake dynamic object need to be checked:

```
Collisions    Static          Sleeping           Awake
          ------------------------------------------------
Awake     |    Check        Check & Wake         Check
Sleeping  |     No               No
Static    |     No

```

This can dramatically reduce the number of objects that need active simulation, especially in piles which as illustrated in the question have a lot of mutual collisions to check for little to no net movement.

Sleeping only helps once the objects actually *reach* rest though, which might take a while.

Some things you can do to reach rest sooner:

* Have a nonzero minimum speed or momentum, and clamp anything that falls below it to zero. (This is basically an epsilon, commonly used in comparing floats)
* Use friction, damping, and inelastic collisions to sap energy out of the system and help it reach rest faster overall.
* Increase friction/damping/inelasticity *selectively* for slow-moving objects to give them that final nudge to rest, without affecting the behaviour of more energetic bodies.
> 11 votes

---
Tags: 2d, collision-detection, physics, optimization, love2d
---


# Question
Title: Normal matrix space has to be eye space?
I'm doing lighting in world space (not in eye space), so I set the normal matrix as follows:

```
modelProgram->setUniform( "NormalMatrix", inverse(transpose(mat3(modelMatrix))) );

```

Now I noticed that all the tutorials set the normal matrix as the inverse transpose of the **ModelView** matrix. This also means they do lighting in eye space, right?

Do I have to do lighting in eye space when using the normal matrix? I actually do normal mapping too if it matters.

# Answer
It's common for people to compute lighting in eye space because of how the specular component of lighting in the Phong model is calculated. Doing the calculation in view space, allows you to avoid a vector subtraction in the vertex shader, a basically negligible optimization.

If you were instead to do the calculations in world space, which you absolutely can, you would just additionally need to pass to your shader the eye's direction (or compute it from the view matrix within your shader).

It is certainly possible to do lighting in world space, and if you find that more intuitive you should go that route.
> 4 votes

---
Tags: shaders, normals, normal-mapping
---


# Question
Title: How to avoid Gimbal Lock on Rubik's Cube
I am making a Rubik's cube program. That will simulate a Rubik's cube. I am having problems with gimbal lock. I need to know how to avoid it. To my understanding I can either multiply the x, y, z rotation matrices in a specific order to acquire the rotation I am trying to get. Or I can use a quaternion which is like rotating around a single user defined axis instead of the axis x, y, or z. I can't really understand visually how I can get the resulting axis from two other axis. (x, y, z) How can I get the resulting axis for my quaternion from my Euler rotations? Will it just result in gimbal lock again?

One of the big problems is. I don't know what rotations are going to be made. I need to make it general purpose.

Edit: Little bit more documentation of my problem:

My Euler matrix multiplication looks like this

```
    rotate = XMMatrixRotationX(content.mesh[meshToRotate[i]].rotation.x) * XMMatrixRotationY(content.mesh[meshToRotate[i]].rotation.y) * XMMatrixRotationZ(radians);
    content.mesh[meshToRotate[i]].rotation.z = radians;

```

As a gimbal lock would suggest the last axis in the rotation gets the problem. When you attempt to rotate the front or back face you get problems.

# Answer
In the case of a puzzle like this you can animate the rotation then reset the model back to its original position but with the cube's stickers rotated.

Look at it like cheating with a real puzzle by **moving the stickers**.

You'll have to make it possible to change the stickers' colors. This can be done with material colors or a dynamic texture.

And this way you can reduce it to 2 animations: center 90' rotation & end 90' rotation.

You flip/rotate the cube and stickers to animate the opposite end or on a different axis, reverse the animation to turn in the other direction.

The model (Mesh) always comes back to its original position after animating the 90 degree rotation, it's the stickers that change places. This way we completely avoid gimbal locks.

---

Another way is to use rotation matrices.

Each cube cells (the 3x3x3 elements of the puzzle) have 6 faces, up to 3 of them with stickers and their own rotation matrix. Using the face normal multiplied by the rotation matrix of the cell you can figure out which sticker points where as only 1 axis in the normal will ever have a non-zero value +/- 1.0 in X, Y or Z.

And there will (should) only ever be 9 stickers pointing to the same direction.

You can use the cell's positions to figure out which ones to rotate.

Since the cube cells will only ever be rotated to 0, 90, 180, or 270 at the end of the animation we can fix the cumulative rotation errors by doing:

```
if (matrix[r][c] > 0.5) {

    matrix[r][c] = 1;

} else if (matrix[r][c] < -0.5) {

    matrix[r][c] = -1;

} else {

    matrix[r][c] = 0;

}

```

For each cell (r=row, c=column) to eradicate any rounding errors once the animation is done.

Usually comparing float values to exact values is a bad idea but in this case we're fixing the matrices to be exactly -1.0, 0.0, or 1.0, without any translation and anything (N) multiplied by those numbers always end up exactly -N, 0 or +N so we can safely compare them.
> 3 votes

---
Tags: mathematics, rotation, quaternion, gimbal-lock
---


title: Flexible projectile system?

text:
# Question
Title: Flexible projectile system?
Projectiles need to accommodate timed, homing, linear, and arced behaviours and have single, cone, and splash effects on hit. What is a good pattern to accommodate these different behaviours that require different parameters?

I want a system where I can call something like `ProjectileManager.Fire (*Projectile Parameters*)` from anywhere and have a projectile get fired. How would parameters like `timeToDetonate`, `coneAngle`, and `aoeRadius` be handled in a user-friendly way?

# Answer
> 1 votes
I see no problem. Just declare a multitude of Fire functions each of which calls respective projectile class constructor. More code on the inside, but simplest interface on the outside (easy to use):

```
ProjectileManager.FireA(param1, param2);
ProjectileManager.FireB(param1, param2_typeA, param3);
ProjectileManager.FireC(param1, param2_typeB, param3);
ProjectileManager.FireD(param1, param2, param3, param4, param5);

```

Alternatively, use constructors on the outside (less code inside):

```
ProjectileManager.Fire(TProjectileA.Create(param1, param2));
ProjectileManager.Fire(TProjectileB.Create(param1, param2_typeA, param3));
ProjectileManager.Fire(TProjectileC.Create(param1, param2_typeB, param3));
ProjectileManager.Fire(TProjectileD.Create(param1, param2, param3, param4, param5));

```

---
Tags: c#, design-patterns
---


# Question
Title: Delay in the middle of a script in Unity without calling a separate coroutine
```
using UnityEngine;
using System.Collections;

public class WaitForSecondsExample : MonoBehaviour {

    void Start() {
        StartCoroutine(Example());
    }

    IEnumerator Example() {
        print(Time.time);
        yield return new WaitForSeconds(5);
        print(Time.time);
    }
}

```

I don't like using functions in my code. Instead of the example above, I'd prefer:

```
using UnityEngine;
using System.Collections;

public class WaitForSecondsExample : MonoBehaviour {

    void Start() {
        yield return new WaitForSeconds(5);
        print(Time.time);
    }

```

I can easily use yield In javascript but why can't I use yield in c# without using a function?

```
// Prints 0
print (Time.time);
// Waits 5 seconds
yield WaitForSeconds (5);
// Prints 5.0
print (Time.time);

```

I have many problem with using functions in C#.

# Answer
You can do it in C# too. You can use `IEnumerator Start()` instead of `void Start()`.
> 2 votes

# Answer
from Unity Documentation :: StartCoroutine

> When using JavaScript it is not necessary to use StartCoroutine, the compiler will do this for you. When writing C# code you must call StartCoroutine.
> -2 votes

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


title: Unity Geometry Shader Compiles forever

text:
# Question
Title: Unity Geometry Shader Compiles forever
I am writing a shader to achieve a laser show effect example. For now I am just focusing on the lines. One line ist represented as one triangle. When I save my shadercode, unity gets inactive and I can see in the task manager that the shader compiler has 30% cpu -\> is compiling. But this takes forever, and when I restart unity, it isn't able to load the shader from the assets. I found out that this doesn't happen when I comment the line:

```
const int TRI_STRIP[TAM] = tmpTriStrip;

```

Obviously I then get an error that TRI\_STRIP is undefined, but the shadercompiler did its work and Unity is still running. Then I put the line back into the code and the above desribed behaviour appears. Thanks for any tipps and advices.

Here is the complete geometryshader code:

```
    void myGeometryShader(point gIn vert[1], inout TriangleStream<v2f> triStream)
{
    float f = _PointSize / 20.0f * sin(_Time * _Speed); //half size

    float4 vctmp[TAM];

    int i;
    float y;
    for (i = 0; i < TAM; i += 3) {

        y = sin(_Time * _Speed + _SinValue) * _MovHeight + _HeightOffset;
        vctmp[i] = float4(0.0f, 0.0f, 0.0f, 0.0f);
        vctmp[i + 1] = float4(_Distance, y, i / _MarginFactor - _EndWidth / 2.0f, 0.0f);
        vctmp[i + 2] = float4(_Distance, y, i / _MarginFactor + _EndWidth / 2.0f, 0.0f);
    }

    const float4 vc[TAM] = vctmp;

    float2 UV1tmp[TAM];
    for (i = 0; i < TAM; i += 3) {
        UV1tmp[i] = float2(0.0f, 0.0f);
        UV1tmp[i + 1] = float2(1.0f, 0.0f);
        UV1tmp[i + 2] = float2(1.0f, 1.0f);
    }

    const float2 UV1[TAM] = UV1tmp;

    int tmpTriStrip[TAM];

    for (i = 0; i < TAM; i++) {
        tmpTriStrip[i] = 1;
    }

    const int TRI_STRIP[TAM] = tmpTriStrip;

    v2f v[TAM];

    // Assign new vertices positions
    for (i = 0; i < TAM; i++) { v[i].pos = vert[0].pos + vc[i]; v[i].col = vert[0].col; }

    // Assign UV values
    for (i = 0; i < TAM; i++) v[i].uv_MainTex = TRANSFORM_TEX(UV1[i],_MainTex);

    // Position in view space
    for (i = 0; i < TAM; i++) { v[i].pos = mul(UNITY_MATRIX_MVP, v[i].pos); }

    // Build the cube tile by submitting triangle strip vertices
    for (i = 0; i < TAM / 3; i++)
    {
        triStream.Append(v[TRI_STRIP[i * 3 + 0]]);
        triStream.Append(v[TRI_STRIP[i * 3 + 1]]);
        triStream.Append(v[TRI_STRIP[i * 3 + 2]]);

        triStream.RestartStrip();
    }
}

```

# Answer
The looks like a compiler bug.

But in any case:

* You don't need the copy into a const array, just use the non-const one.
* You don't need those large arrays, from what I see everything in the shader can be done in a single `for (i = 0; i < TAM; i += 3)` loop with small arrays of 3.

That should work around the compiler bug and probably make the shader faster.
> 1 votes

---
Tags: unity, shaders, geometry-shader, shaderlab
---


# Question
Title: How do I set angular velocity/torque so that it's pointing to velocity/direction?
Right now, when I spawn a shootable object, it goes like this:

Because I just set it's angle to this:

```
float aimAngle = (float) Math.atan2(velocity.y, velocity.x);
bullet.setBodyAngle(aimAngle);

```

I want it to be like this:

I think I should use angular velocity or torque, but I have no idea how. I can't just set it's angle like in previous code every frame, because it makes physics collisions glitch.

# Answer
## Summary

My recommendation is to compute a restorative torque to apply to the object. This is physically more accurate than setting the velocity directly, and the simulation will be better behaved.

This solution should also work for *any* launch angle. Below is a gif of this method at work stabilizing arrows launched from a car.

## Restorative Torque

This video on the concept of control system stability describes exactly what you are trying to achieve. The video (and the series) is very well made, but the example of the dart at 2:35 is particularly informative.

In the example Brian describes, the dart (or projectile in your case), tends to orient itself with the velocity vector because of the air pressure on the flights of the dart.

## Implementation

When the projectile is created, there should be some `angularDamping` set for the body to damp out rotational forces. Then the *restorative torque* may be applied as follows:

```
//Get the velocity of the projectile
b2Vec2 projVel = projBody.GetLinearVelocity();

//Get the current angle of the body in the range 0,2*pi
double ang = projBody.GetAngle() % pi;
if(ang < 0){
    ang = ang + 2*pi;
}

//Compute the difference between the projectile angle and the angle of the velocity vector
double diff = atan2(-projVel.x, projVel.y) - ang;

//Need the absolute angle for a couple of tests
double absDiff = abs(diff);

//Test if the difference exceeds some very small threshold value (e.g. 10e-6)
if(absDiff > thresh){

    /*Test if the difference in angles is greater than pi
   (If so then the projectile has completely flipped around
   and the restoring torque needs to be applied in the opposite direction)*/
    if(absDiff > pi){
         diff = diff-2*pi;
    }

    /*Apply the restorative torque, scaled with the velocity so that
    the faster the object is moving, the greater its tendency
    to align with the direction of motion.

    The torqueCoeff is a tunable coefficient:
     - increase it if your body isn't aligning quickly enough
     - decrease if it's wobbling back and forth too much.
    You can also play with the angularDamping coefficient to produce the results you want*/
    projBody.ApplyTorque(diff*projVel.Length()*torqueCoeff);
}

```

Please be advised, this code is untested. I have translated it from some lua code I have written for a love2d project (the co-ordinate system in love2d is flipped about the horizontal axis so some of the angles are computed differently).
> 2 votes

# Answer
Stated that i agree with MickLH comments.

Assuming no Air resistance. The flight time of a parabola thorw is :

```
 T=2*V0 * sin(a) / g

```

where **V0** is launch velocity , **a** is launch angle and **g** is gravitational acceleration.

```
Th = V0 * sin(a) / g

```

is the time from ground to higher point. In higher point your desired angle is **0** so compute

`(0 - angle) / Th` as angular velocity
> 0 votes

---
Tags: physics, box2d, angles, direction, torque
---


title: Will Vulkan Kill the use of GLSL?

text:
# Question
Title: Will Vulkan Kill the use of GLSL?
After reading this link I am still unclear as to the shading language support in Vulkan.

As Vulkan only supports SPIR-V is it the case that GLSL is therefore being phased out? Are there any indication of what the next 5 years looks like in terms of the "hot" language to study in for graphics programming?

# Answer
No, but OpenGL might ;)

The base Vulkan specification only supports SPIR-V. However, Vulkan does allow for vendor extensions. And NVIDIA is already on-record on this matter; they will be providing a Vulkan extension to be able to shove GLSL into their Vulkan implementation.

That shouldn't be taken to mean everyone else will.

However, let's not forget that Vulkan is not going to magically appear everywhere, nor will OpenGL instantly vanish into the aether the moment the Vulkan spec ships.

First, there are entire classes of users who will gain virtually nothing from switching to Vulkan. Who are getting good enough performance for their problem domains from OpenGL, so they don't need to. Pretty much every 2D game you've ever seen has little to gain performance-wise from Vulkan. Even the CPU power consumption gains from VK are minimal for them.

Second, users who would benefit from Vulkan will still take several years to switch over.

Now, if you want to understand my cryptic comment, it is entirely possible for OpenGL to start being able to take *SPIR-V* as its shading language. SPIR-V contains virtually every feature of OpenGL 4.5, with the exception of shader subroutines (a feature so terrible I won't even link you to the OpenGL Wiki article for fear that you might try to *use* it).

Indeed, if SPIR-V were only intended to be used for Vulkan or OpenCL, there would be no reason for it to have so many GLSL-based decorators and such in the language. Vulkan uses descriptor sets, not binding points, so why does SPIR-V allow you to specify binding points for textures/images/etc? The same goes for many other GLSL-isms in SPIR-V.

All it would take is an OpenGL extension to allow SPIR-V to be fed to `glProgramBinary`, likely with a dedicated format enumerator for it.

Will Vulkan kill GLSL? No. But OpenGL and Vulkan might. Though even then, it'd take a long time for it to die.
> 13 votes

---
Tags: opengl, shaders, glsl, vulkan
---


# Question
Title: Why is my player unable to move when touching the ground?
I want to make a little platformer. I watched Shaun Spalding's tutorial but nothing seems to work. Everything was fine until I put in the collision detection. But the player can't move while he's on the ground.

Here's the code:

```
//Get the player's input
key_right = keyboard_check(vk_right);
key_left = - keyboard_check(vk_left);
key_jump = keyboard_check_pressed(vk_space);

//react to inputs
move = key_left + key_right;
hsp = move * movespeed;
if (vsp < 10) vsp += grav;

if (place_meeting(x,y+1,obj_wall))
{
    vsp = key_jump * -jumpspeed;
}

//horizontal collision
if (place_meeting(x+hsp,y,obj_wall))
{
    while(!place_meeting(x+sign(hsp),y,obj_wall))
    {
        x += sign(hsp);
    }
    hsp = 0;
}
x += hsp;

//Vertical collision
if(!place_meeting(x,y+sign(vsp),obj_wall))
{
    while(!place_meeting(x,y+sign(vsp),obj_wall))
    {
        y+=sign(vsp);
    }
    vsp=0;
}
y += vsp;

```

That's all in the step event for the player.

Thanks in advance!

# Answer
Ok so I have

```
//Vertical collision
if(!place_meeting(x,y+sign(vsp),obj_wall))
{
    while(!place_meeting(x,y+sign(vsp),obj_wall))
    {
        y+=sign(vsp);
    }
    vsp=0;
}
y += vsp;

```

but I should have

```
//Vertical collision
if(!place_meeting(x,y+sign(vsp),obj_wall))
{
    while(!place_meeting(x,y+vsp,obj_wall))
    {
        y+=sign(vsp);
    }
    vsp=0;
}
y += vsp;

```
> 0 votes

---
Tags: movement, game-maker, platformer
---


# Question
Title: How to test if procedurally generated level for infinite runner can be passed?
I have a 2D infinite runner platformer game built in Unity 5, where the level procedurally generates itself. I need to check if it is possible to pass the holes on the level.

How could I do that?

# Answer
> 4 votes
I understand you are dealing with both box obstacles and gaps. The way it was described, I can see three possible situations. Correct me if the game is designed differently.

With the first, there are no obstacles before the gap, at least no obstacles that the player can jump atop. In this case, you would need only a fix max width for the gap.

In the second, the player can jump atop an obstacle before the gap, increasing his jump distance. This means we can increase the gap width.

The final sketch shows what happens when two obstacles before the gap allow an even higher jumping elevation.

Here is a possible algorithm to use during generation:

```
When creating a new obstacle:
    If there is an obstacle before it and it is accessible:
        If newObstacle height - lastObstacle.y < jumpHeight:
            Mark the new obstacle as accessible.
    Else if newObstacle height < jumpHeight
        Mark the new obstacle as accessible

When creating a gap:
    gapWidth = minimum gap distance
    If there is an obstacle before that is accessible
        gapWidth += lastObstacle.y * someConstant

```

This way, no matter how high the random staircase is, you will know how wide you can make your gap.

# Answer
> 3 votes
Do it at the generator level: Always generate your level using a selection of passable gaps / obstacles section prefabs.

If two successive sections are not passable mark them as such so the generator does not put both in succession and/or adds some space between them.

These sections will also instruct the AIs on how to clear the obstacles.

# Answer
> 1 votes
A newbie's answer.

Suppose the orange marked place is the position for your enemy to jump,

you make a trigger on the orange x mark of the object on the prefab and tell the enemy ai to jump when the ai hits the trigger.

Simple Answer.

---
Tags: unity, 2d, platformer, testing
---


title: "Following" Object is acting Strangely?

text:
# Question
Title: "Following" Object is acting Strangely?
So I recently designed an enemy that will follow the player when he comes within a certain distance of the object. However, there are times when the player comes in range, only for the "follower" enemy to seemingly reverse before following, or almost kind of circle the player on the way towards him.

I can't quite put my finger on why this is happening, so I have attached my code. I hope someone can give me some advice on how to improve this:

```
    public class Follower : MonoBehaviour
{
// spawn position and other info of Follower
private Vector3 pos1 = new Vector3(-7f, 0.5f, -7f);
public float speed = 1.0f;
public int Range;
public GameObject target;
private Vector3 targetTran;
private Vector3 diffVec;
private float diffMag;

void Awake()
{
    transform.position = pos1;
    sourceCollFol = GetComponent<AudioSource>();
}
void Start ()
{
    target = GameObject.FindWithTag("Player");
    targetTran = target.transform.position;
}
void Update ()
{
    pos1 = transform.position;
    targetTran = target.transform.position;
    diffVec = (targetTran - pos1);
    diffMag = diffVec.sqrMagnitude;
    // check for range between Player and Follower Enemy
    if ( diffMag < Range)
    {
        transform.LookAt(targetTran);
        diffVec.Normalize();
        transform.Translate(diffVec.x * speed * Time.deltaTime, 0f, diffVec.z * speed * Time.deltaTime);
    }
}
}

```

# Answer
> 0 votes
It is happening because you are translating every coordinates with/without reason. To overcome this problem you should just use some geometry or built-in unity methods which only cares about the target and follows the target in straight path.

Well, the easy solution for now is to use `Vector3.MoveTowards`.

Modify your update code as following,

```
void Update ()
    {
        pos1 = transform.position;
        targetTran = target.transform.position;
        diffVec = (targetTran - pos1);
        diffMag = diffVec.sqrMagnitude;
        // check for range between Player and Follower Enemy
        if (diffMag < Range) {
            transform.LookAt (targetTran);
            transform.position = Vector3.MoveTowards (transform.position, targetTran, 0.1f);
        }
    }

```

---
Tags: unity, c#, game-mechanics
---


# Question
Title: libgdx(android) touchup triggers more than once?
I have a function I run inside the touchUp method but when I click with the mouse during emulation, it triggers my function multiple times. I don't think its an error with the called method itself because if I put the call in KeyUp then it triggers once as expected.

If it matters I am working in android studio.

# Answer
If you use polling, use Gdx.input.justTouched() rather than Gdx.input.isTouched().
> 1 votes

# Answer
Have you implemented the other methods in InputProcessor?
It seems to me that your touchUp method is called multiple times because perhaps your touchDown and touchDragged are never called correctly.
Be sure to return false in the unused methods if you don't want to use them.
Perhaps you could show us your code snippet.
> 0 votes

# Answer
I will presume you are using **InputListener** class. Because **Input** class don't have a **touchUp** method. You didn't mention this part in your question.

I'll assure you **touchUp** funciton will not be called twice. You are using an emulator, and in this case touch up function will be triggered by the mouse button. So as long as there is not a second mouse pointer(?), touchUp function is called once per click.

I also will presume you are using only one Listener.

What is happening is touchUp function is not the only function triggered by a mouse click. If you change the position of the mouse while holding it, touchDragged function will also be called. Maybe that's what is confusing you.

Try to put a `System.out.println("TOUCH UP");` into your touchUp function to be sure of how many times that function is called. And please don't put it in anywhere else.

If your problem insists on happening, please provide us with more information, so we could help you.
> 0 votes

---
Tags: android, libgdx
---


title: PHP browser game energy recover time

text:
# Question
Title: PHP browser game energy recover time
I would like to create something very simple. A browser game, where user can waste its energy and ability points. Unlike other games here there won't be no levels. So energy and ability points restore with the time.

How can I do that in the most efficient way? For example, i have 100 energy points, one point restores every 2 min.

I was thinking about cron-jobs, but that will be not so efficient.

Thank you in advance!

# Answer
Web php games usally uses 2 different ways to do this:

1- Daemon. You set up a "run forever" script that sleeps for 1 second and updates all data that needs update.

2- Time elapsed. you have to store the last conection somewhere and, in the next connection do CURRENTTIMESTAMP - LASTTIMESTAMP to get the seconds elapsed since last update, so you just have to multiply your resources by second by the seconds elapsed.

Depending on your needs you can use, one or another or both.
> 1 votes

---
Tags: php, browser
---


# Question
Title: What exactly are tool pipelines in the game industry?
I've been reading around online and through books and still can't quite figure out what exactly *tool pipelines* are within the game industry.

# Answer
> 12 votes
The tool pipeline is the set of tools that an asset has to go through from the original creation to the moment it's used in the game.

For example:

1. An artist makes a 3d model in 3dsmax
2. A converter transforms the 3dxmax format into something the game engine can use to render it
3. Script extracts the images data from the model, and place the image in a certain folder, while placing the model into another folder.

At the same time

1. A level designer imports the model into a home made level editor that can edit the 3dsmax model, and adds paths for AI in a separate file based on that model
2. Another converter loads the AI file and outputs it in binary format
3. A script places the binary file in the correct folder for the game to load it based on information in it

All of these tools have a purpose, and must be executed in the proper order on the assets.

Each company has its own unique set of pipelines for different purposes (e.g. one for 3d models, one for the audio, one for the AI, etc.): they evolve out of the needs of the company and the engineers who think about them.

---
Tags: terminology, pipeline
---


# Question
Title: C++ Opengl transforming a glm::vec4 with a glm::mat4
Its easy enough doing it on the gpu via GLSL, but how would I do this in c++? When I try it gives me an error telling me I cant cast a glm::mat4 to float, Which makes sense, but how should I do it?

EDIT

A little code example of my failed attempt:

```
glm::vec4 Off = glm::vec4(0, 0, 0, 1);
Off *= Util::createTransform(offset); // Util::createTransform(...) Creates a glm::mat4

for (int i = 0; i < Tvertex.size(); i++) {
    Tvertex[i] += glm::vec3(Off.x, Off.y, Off.z);
}

```

# Answer
> 2 votes
You get the error because there is no `operator*=` for `vec4` that takes a matrix as a parameter. It then tries to convert the matrix to a float, but just can't.

To work around this, you should try to not use the `operator*=` and write it all in the long form:

```
Off = Off * Util::createTransform(offset);

```

Also, as pointed out in the comments to the OP, what you need is probably this:

```
Off = Util::createTransform(offset) * Off;

```

---
Tags: opengl, c++, glm
---


# Question
Title: Synchronizing players and game objects in a server/client multiplyer game
OK guys, I have some experience with 2D game development (single player only), so that's fine no questions here.

The problem is with multiplayer games. I already read lots of other questions and articles to get my head around about peer-to-peer and server/client, and non-authoritative and authoritative game clients.

**What am I trying to achieve?**
Build a simple 2D multiplayer game with some physics involved and over 40 player per game, a good example is flapmmo. However my game concept will be completely different and the players and other game objects will actually interact/collide with each other.

**What technologies have I chosen?**
Client: Unity3d (easy to develop and cross-platform)
Server: Node.js + socket.io + express.js (easy to deploy and cheap to host)

**What I have done so far:**
I already have a test client and server running and the players connection/join game + spawning works just fine. Now I am stuck at how to synchronize all the objects + players.

Base on that:

1 - How do I simulate physics on the server, do I need to rewrite parts of client side on the server side using a JavaScript physics engine?

2 - Is it better to send action messages like "playerJumped" and broadcast it to the clients or send it's current position on every update (more bandwidth consumption I guess)?

3- I read the server needs to run on a lower frequency( E.g. 30hz) to better perform with latency issues. Is it FIXED\_TIME\_STEP that we are talking about?

Please feel free to add any other important point I should consider...
Tks

# Answer
Interesting Question! Let me try to answer some of your points:

> 1 - How do I simulate physics on the server, do I need to rewrite parts of client side on the server side using a JavaScript physics engine?

Yes, essentially, thats what you would do, *if* you want physics on the server. You have to ask you the question: Do I need the server to *validate* everything the user does? In your example-game I'd say no. Of course, someone could change the client-code and cheat himself through the level, but it doesn't really matter. It would not really hurt any other player, neither does he really get a benefit from it other than 'be the king' for a bit.

No, you don't need a full-baked physics engine. Lets say you have a floor and want the player to fall, but not fall through the floor. Thats simple to realize, I'd not call this check a physics-engine. Maybe you also have walls where the player can not walk through. I wouldn't call this a physics-engine either. Only when you want objects to collide and bounce of each other *physically correct* you'd use a real physics-engine.

> 2 - Is it better to send action messages like "playerJumped" and broadcast it to the clients or send it's current position on every update (more bandwidth consumption I guess)?

This heavily depends, but in most cases you send a mixture of both. In your example-game, a 'playerJumped' wouldn't be enough because latency matters. Every single nanosecond **could** change the outcome heavily, so that a 1ns-to-late-jump changes the position of the player 20 seconds a lot. Thats not what you want, so you'd send 'i jumped in frame 30' or something like this. In a fixed-timestep game this would be enough to get the same result on every client. Updates every frame are in this case not needed because every client can calculate your position and would have the same outcome.

> 3- I read the server needs to run on a lower frequency( E.g. 30hz) to better perform with latency issues. Is it FIXED\_TIME\_STEP that we are talking about?

I don't understand exactly what you mean with your last sentence, i hope i got it correct. Yes, thats a fixed timestep. 30hz means 30 updates per second, which gives us a timestep of 1/30 = 33.3 milliseconds per frame. The servers frequency doesn't really matter to better perform with latency issues, what matters is how you extrapolate and how you handle late-pakets. But, the frequency matters when you have a lot of players. The server might not be able to calculate 10000 * 60hz updates per second, but it might be able to calculate 10000 * 30hz. In a few cases you don't even need a frequency. With this I mean: you don't have a running game-loop in your server, but just handle the incoming packets and distribute them to the other clients. But this - again - depends on the game you write.
> 2 votes

---
Tags: unity, physics, multiplayer, node.js
---


title: RTS game unit structure

text:
# Question
Title: RTS game unit structure
I want a way to make a lot of different units without having to program stuff like moveTo and Attack actions more than once

The way I see it, there are 2 ways I can do this.

1. A single **generic Unit class** with flags that specifies what it can/can't do (then create instances in a static array and grab them when needed)
2. **Abstract unit class** with abstract methods for Unit-specific actions like (Attack, Harvest, Patrol), which then all need to be implemented in the **subclasses**, even if the unit can't actually harvest anything.

the first way of doing this seems the simplest, but i would end up having a lot of code being unused for the majority of the units.

the second way could also work. But if i decide to have two different units that can harvest resources, i'm gonna have the exact same code in two different classes, which doesn't seem like the right way to do it.

Is this even the right approach to this problem?
In a game like AoE, every unit has, what i presume is, some kind of List of Actions/Orders, I would really like to know how to achieve something similar to that, where i can just code each Action/Order once, and then give it to all the units that need said Action.

*If i'm unclear (highly plausible) or you need more information on what exactly i'm looking for, just ask me in a comment.*

# Answer
> 25 votes
A common approach is to have a component-based approach where the base-class "Unit" just implements the most basic aspects all units have in common, while each unit then has a list of multiple component-objects which say what it can do and how it does it.

For example, a tank might have the components `Mobile`, `Destructible`, `Attacker`, an immobile turret only `Destructible`, `Attacker` and a harvester `Mobile`, `Destructible`, `Harvester`. These classes would then include all the code which is needed to implement these behaviors. Interactions between components (an `Attacker` can only damage what is `Destructible`) can be implemented by having the component check if the other unit has the required component and then interact with that component directly.

The advantage over a classical class-inheritance is that you can easily combine abilities. For example, when you want to have a harvester which can also attack, transport infantry and fly, you just need to add the necessary components. You can also easily add and remove new features in form of new components without having to bloat the basic Unit class.

Unity supports you in such an architecture, because the whole engine already is component-based. So game-logical components like these can be added in form of scripts.

# Answer
> 4 votes
A lot of games use a component-based system for entities which is where a bunch of behaviours and abilities can be added to a more generic unit type rather than being coded as part of the entity's class (or equivalent).

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


# Question
Title: what is the best way to make a bunch of platforms appear randomly on a JFrame but close enough the player can reach them?
Hi I'm trying to make a screen that will have a bunch of platforms that will place themselves randomly around a JFrame. I know how to do the stuff to make the character jump and to deal with the collisions just not a way to place the platforms on the screen randomly so they are close enough together that the character could reach. Any help is appreciated.

# Answer
> 1 votes
Think of the problem in reverse. Instead of creating platforms that are randomly placed and then making sure they are withing jumping range of the player, instead create the platforms at the maximum jumping range of the player and then move them randomly. So long as all your random movements are done towards the player you are guaranteed that they will be in range.

# Answer
> 0 votes
Well it's not very well defined what kind of physics etc you have in your game. If the placement of the platform should simply be a random angle and a random distance below maxDistance, something like this could work:

```
    /**
     * Method that returns a 2D-coordinate, at a random angle and position relative to currentPosition.
     * The distance from the returned coordinate to the currentPosition is capped by maxDistance.
     *
     * @param currentPosition - A double[] array of length 2, with the first element containing the x-coordinate and the second element containing the y-coordinate.
     * @param maxDistance - Maximum distance from currentPosition to the returned coordinate.
     * @return - A double[] array containing the generated random coordinates, with the first element containing the x-coordinate and the second element containing the y-coordinate.
     */
    private double[] setRandomPoint(double[] currentPosition, double maxDistance){
        Random r = new Random();
        double distance = maxDistance * r.nextDouble(); // A random distance, capped at maxDistance.
        double angle = 2 * Math.PI * r.nextDouble(); // A random angle.
        double[] returnVector = new double[2];
        returnVector[0] = Math.cos(angle) * distance + currentPosition[0];
        returnVector[1] = Math.sin(angle) * distance + currentPosition[1];
        return returnVector;
    }

```

However, I would assume you want a more complicated allowed placement of the platform, given that you seem to have some gravity - lower platforms are likely allowed to be further away from the currentPosition. This would require knowledge of the physics that you have implemented. You could possibly use the method above and simply set the maxDistance to the "minimum maximum distance" that you allow, maybe the maximum distance you have when the platform is straight up from the currentPosition?

Another way to solve it would be to make a bunch of allowed platform locations and pick one of those at random.

---
Tags: java
---


title: What are interchange formats?

text:
# Question
Title: What are interchange formats?
I have been told to research up on *interchange formats*, only comes up with certain interchange formats without actually explaining what they are.

What are *interchange formats*, specifically in the context of game development?

# Answer
> 5 votes
Interchange formats are file types that are designed for - or commonly used for - transfer ("interchange") between tools.

For instance, artists will make models in Maya. Maya's native file format is the `.mb` format. This format is only really usable by Maya, so it is not consumable by other tools.

The 3DS `.fbx` format has a good SDK and even some mediocre documentation. Almost all 3D modeler packages, including Maya, can read and write `.fbx` files. Furthermore, additional tools and even game engines can easily read `.fbx` files, making them useful for working with a complete pipeline.

Game engines themselves usually prefer a custom file format, largely for speed reasons. While engines sometimes come bundled with exporters for packages like Maya to be able to directly save into the engine's preferred format, these plugins don't help when additional tools are needed as part of the artists' workflow. For this reason, many engines instead provide asset converters that can take `.fbx` files into the engine's native format, allowing artists to work in their preferred tools and easily get the work into the engine without manual conversion or import/export steps.

These qualities all make `.fbx` an example of an *interchange format*. It is not the only one, of course, but one of the most common.

As an artist working with source control, you may often see both the original tool-specific files (e.g. `.mb`) and the interchange formats (`.fbx`) checked in, though not always. You generally would not see the engine-specific format checked in as those would be generated on the fly by the engine's asset conversion pipeline.

# Answer
> 5 votes
They are file formats used to exchange data from one place (usually a program) to another (usually another program). You might also see them described as "intermediate" formats.

Their main goal as a format is to describe data in a fashion that is straightforward and easy to parse, or in a standard, almost least-common-denominator sort of way. This makes them useful as ways to connect various programs into a data pipeline or toolchain that don't otherwise know about each other.

(They're generally not suitable formats for consumption directly by a game as they usually aren't geared towards efficiency, although this is not always the case and may not matter in some scenarios.)

---
Tags: terminology
---


title: How can I fade in 3D foliage smoothly?

text:
# Question
Title: How can I fade in 3D foliage smoothly?
Take a look at this picture:

This is a picture of me diving down from a high height. As you can see, the world is a simple world with grass, snow, trees, etc.

The problem here is the 3D foliage. If is obviously just "jumping" into the scene. It also changes the scene dramatically - Instead of simply adding detail to the "current" scene, it's effectively overwriting the terrain underneath it and setting it's own colours/details.

Let's take a look at a popular game, such as war thunder:

Yes, you can see the 3D foliage appearing as the player gets closer to it. However, it is very hard to actually focus on how or where it is appearing. Also, the grass adds detail to the terrain, rather than completely overwriting it and providing a completely different picture.

The TL;DR on this is - My game has grass that "pops" into existence and creates an obvious change in the terrain, whereas professional games have unobtrusive hard-to-notice geometry gradually fading into view.

How do other games do this, and how can I implement it?

# Answer
You seem to just show the foliage at pre-determined distance.

Why don't you `lerp` foliage opacity between transparent and opaque across some distance range? Could be the simplest most noticeable improvement.
> 2 votes

---
Tags: opengl, java, 3d, lwjgl, geometry
---


# Question
Title: What is the best way to check for intersection of two bounding boxes, given a minimum and maximum Vector3 for each one
I have a BoundingBox object which holds two Vector3's (x, y, z), one for the minimum point and one for the maximum point. (-1.5 0 9 | 1.5 3 10)

What is the best way to check for any intersection or overlap of two BoundingBoxes?

The test for intersection will happen more often than not when there are no points actually intersecting, just faces.

The code that I currently am using is: `bb1.max_.x_ > bb2.min_.x_ && bb1.min_.x_ < bb2.max_.x_ && bb1.max_.y_ > bb2.min_.y_ && bb1.min_.y_ < bb2.max_.y_ && bb1.max_.z_ > bb2.min_.z_ && bb1.min_.z_ < bb2.max_.z_;`

However this leads to problems when points are, for example `-1.5 0 9 | 1.5 3 10` intersecting with `-0.5 0 8.5 | 0.5 1.8 10.5`... The Z minimum and maximum points for the second object laying entirely outside of the Z min and max for the first object.

# Answer
> 2 votes
The idea is practically the same for 1D, 2D or 3D or any other dimension. First let's talk about a 1D scenario:

We have two segments along x axis, and we know their start and their ends. let them be `s1,e1,s2,e2`. So what's the requirement for these two lines to overlap? well, we can say the first line should start before the second one ends, and vise versa. Meaning we have to check: `s1 < e2 && s2 < e1`. That's all the things we need to check.

Now to solve the problem in higher dimensions we are going to use the fact that a bounding box (a rectangle) is in fact axis aligned. Using this fact we can safely assume if two boxes are going to collied, their projections to axis lines should also overlap. With that in mind, no matter how many dimensions you have, you just have to check above statement (`s1 < e2 && s2 < e1`) for each and every dimension. Two boxes collied if and only if all these conditions are true.

---
Tags: collision-detection, mathematics, geometry, intersection
---


# Question
Title: How does UV mapping work for the spaces between vertices?
In UV mapping each vertex has a UV coordinate, but wouldn't that just make 1 pixel for every vertex? How do you find out the texture coordinate for the spaces in between the vertices? Am I not understanding UV mapping right?

# Answer
> 4 votes
Actually every face of your mesh has UV coordinates through which UV mapping works. Let take an example of cube.

Cube has 6 faces and every face has 4 coordinates. That means a Cube must have 24 coordinates for UV mapping.

Now second part is to map coordinates with texture. Let's take an example of a square texture image having 6 different color boxes ( for each face actually). This means texture has 2 rows and 3 columns of color boxes containing 6 different colours. Have a look

Now if I want to map red color on Cube's top face let say and I know that the coordinates at 0, 1, 2, 3 represents the top face of cube. Then I would map as

* Coordinate at **0** would map **0,1** of texture
* Coordinate at **1** would map **0.33,1** of texture
* Coordinate at **2** would map **0.33,0.5** of texture
* Coordinate at **3** would map **0,0.5** of texture

As texture's points lies between 0 and 1. And if **0.33** is not clear then it is **1/3** of total width because **1/3 + 1/3 + 1/3 = 1**

---
Tags: 3d, rendering, uv-mapping
---


# Question
Title: javascript efficient collision detection
I have a processing game where I am having serious lag problems with collision detection. I am using the most effective code I can think of however after about 9 levels in The game gets unbearably laggy. I would show you the code but site wont handle my less thans.

If you want to check the program out you can find it here: https://www.khanacademy.org/computer-programming/tanks-v1245/6637554186715136 under the tankMelee function ~line 160

# Answer
Most games use quadtree structures to manage the colisions, you should read about it.

Anyways, if you are having lag after X levels is possible that you are storing all the objects and checking them out every loop, and not just the object in the current scene or level.
> 1 votes

---
Tags: collision-detection, javascript, processing
---


title: Component arrays vs. entity structs?

text:
# Question
Title: Component arrays vs. entity structs?
Two of the main systems I've seen in entity system tutorials are:

* An `Entities` class with one array / \[hash\]map for each component, with indices corresponding to entity IDs.
* A list of `Entity` structs, which have the components as fields, and possibly a pointer to a "cold" struct for less used components.

What are the reasons I would use the former over the latter, considering that the latter seems much easier to implement? Is there some advantage to having each attribute laid out contiguously in memory?

# Answer
> Is there some advantage to having each attribute laid out contiguously in memory?

It's better for cache locality of data access. Memory access is slowest part of all modern computing systems. As memory buses pull in multiple bytes in "cachelines" and most modern CPUs will prefetch memory that it detects are being accessed contiguously, keeping data that is used sequentially laid out in memory contiguously can have a signficant ans positive impact on efficiency.

That said, performance fetishism is not as useful as one might think, even in games. Plenty of big AAA games use something closer to the other technique you mention. There are places where cache locality of data is super important and places where it has little meaningful impact. Sometimes, ease of implementation or ease of maintenance will be more important than raw performance. A particle system is a place where every little bit of performance matters, for example, but an entity or component that only exists on a few dozen actors doesn't need to be maximally efficient.

A component-based architecture can use some ES-like techniques (a System that operates on contiguously-allocated data associated with Entity ids) for some components and can use a simpler container of objects for other components. There's no reason that one has to shoehorn oneself into the ES pattern for everything. A well-designed simple component architecture lets you use the appropriate design methodology for each component.
> 9 votes

---
Tags: entity-system, data-structure
---


# Question
Title: Should texture regions sizes be power of two?
Is it advisable for my individual texture regions inside this texture to be power of two, or that won't make any difference?

*I've read on several places that it's recommended to use power of two sized textures (e.g. Should I use textures not sized to a power of 2?).*

# Answer
The texture regions inside don't need to be powers of two.

But texture compression cells are often 4x4 so you have to be careful when using compressed textures that the edges of two texture regions don't share the same cell or they'll be compressed together which will degrade the quality if they have different colors.

You should leave a N pixel border around your regions where you extend the colors outward. Where N is 4 for compressed textures and a multiple of that if you're going to be using mipmaps.

So the compression, interpolation and mipmap don't draw using neighbor texels that are the wrong color at the seams.
> 4 votes

---
Tags: opengl, android, libgdx, textures
---


# Question
Title: How to properly use prefabs with 2D game?
I have a concern about prefab's purpose.

When I create a npc like a monster with all it's animations, script etc, I then create a prefab to instantiate it.
When I want to insert different monster which are quite similar to the first one I created I wonder to understand what's the Unity base idea to deal with. My thought is that the prefabs should be kept the minimum essential numer possible and to call different functions to initialize time by time differently depending on specific needs.
But, how to deal with animators and animations in general? There is any shortcut of creating one prefab for each monster? I'm asking because I can't find any clear way to dinamically attach animators to a generic gameObject. Since I cannot have one Animator where I replace dinamically sprites involved the simplest (but not so smart) way I found is to create duplicates of prefab and attach editor side all these graphic components.

What would be the best approach to deal with this?

# Answer
> 1 votes
Prefabs work best when there will be multiple instances of any particular structure across your game. For example a Red Monster might have a red texture and do 10 damage to player via a `monsterDamage` variable (publicly exposed on a script). Another monster might be Green Monster, and it does 20 damage to the player, and also uses the same script as the red monster but with the `monsterDamage` modified via the inspector.

Prefabbing both of these means that whenever you want these monsters with their scripts attached in a scene you simply drag them in and they are good to go with the correct values set on their parameters and the correct components attached (such as scripts, Colliders etc).

Another really great benefit is that if you decide that for example that Green Monsters are doing too much damage, you can select the prefab in your folder and change this value to say 15. This will update any green monsters in your game to now do 15 damage instead of 20!

TLDR;

Prefabs reduce the need for repetitive work and allow you to make a change to an object which will be applied to all instances. Instead of going through every instance manually.

If you place an animator on a monster prefab then the animator will automatically be prefilled for all instances of that monster

---
Tags: unity
---


title: Heightmap terrain picking

text:
# Question
Title: Heightmap terrain picking
I've implemented an OpenGL based terrain unsing a tesselation-shader for dividing each 'terrain-cell' into the desired tiles. The heightmap is uploaded to the GPU and applied on the shader.

When it comes to picking, I don't really know what to do. Testing triangles on intersection with the pick ray is not possible because only the GPU 'knows' the mesh.

Is render to texture with an unique color the way to go? Or holding an additional mesh in RAM, only for picking/collision?

# Answer
> 1 votes
Ray-casting into the height map on the CPU will likely be much faster *with proper optimizations* and it wont unexpectedly fail (eg: due to some odd driver rounding issues on a rare-ish laptop chipset creating a few angry customers.)

Either of those solution would work but reading a texture or frame (or any data) from GPU RAM is extremely slow (relatively speaking).

You could also use a Transform Feedback to get the result from a geometry shader https://www.opengl.org/wiki/Transform\_Feedback

## The pipelining issue:

With either texture or transform feedback you'll need to implement pipelining to have the GPU do the picking without incurring a stall making sure you wait to get the result 1 to 4 frames later.

OpenCL might make it easier to get asynchronous results but that's potentially adding a lot of compatibility/timing/driver issues.

There can be multiple frames "in flight" being rendered/queued by the GPU which in most case needs to be finished before you get your data back so every time you ask the OpenGL driver for data it has to wait for everything to be done.

During that time no GPU render commands are queued so you're waiting (for example) for 2 frames for the GPU to finish its queue then waiting to get the data off the PCIe bus back into system RAM then the GPU sits idle for another frame while the CPU fills the render command queue back up, then it takes another frame for the GPU to finish drawing and display it so you've incurred a huge stall of 4-5 frames worth of rendering.

(This is an example, different GPUs and drivers will incur different penalties.)

All this just to get a coordinate on a height map.

---
Tags: opengl, terrain, picking
---


title: Tile tilemapping render error

text:
# Question
Title: Tile tilemapping render error
I'm having rendering issues in Tiled with a border tile I'm applying to shapes.

In Tiled:

In game:

I'm using Tile Flipping to reduce work. I thought this may be the issue, so I tested out a few tiles by themselves:

Tiled:

In game: They render as expected

What may be the cause of this?

My game engine is Melon JS

# Answer
It is possibly a bug in the renderer. Try with and without WebGL. Also file a ticket on the issue tracker, providing the library version and minimal example to reproduce: https://github.com/melonjs/melonJS/issues
> 1 votes

# Answer
Looks like the rendering is off by 1 pixel (texel) for the flipped tiles or the source copy isn't flipped properly and catches most the next/previous tile in the tileset.
> 2 votes

---
Tags: tilemap, rpg, tiles
---


# Question
Title: Relation between game systems and components in a component-based architecture?
Based on a question I previously asked here regarding to decoupling input from other components of an entity I developed a small component architecture on top of XNA to understand how everything works and plays together. Basically, my architecture has the following components/services/systems:

**Game**

This is the root of any game, responsible for ticking the game loop (updating, drawing) as well as instantiating all systems.

**GameModule**

A game module responsible for a certain aspect of the game, such as UI (*UIModule*), input (*InputModule*), animations (*SpriteAnimationModule*), scenes (*SceneStackModule*) etc.

**Scenes**

Holds the current state of the game. Basically an entity manager. :)

**Entity**

Entity which only holds a collection of components and very basic world space information such as position, rotation etc.

**Component**

A component of an entity, which can be anything (*SpriteComponent*, *ScriptComponent*, *ControllerComponent*)...

---

However now I seem to have a problem of the responsibilities between my game systems (modules) and the components, which are not aware of each other. For instance, I have an **UIModule** instantiated in my game, which I need to update/render before any other systems in order to appropriately handle input events on the UI. For this, I'd need to loop through all **UIComponents** \- which are unfortunately encapsulated within the current scene. Which in turn is only accessible via the **SceneStackModule** (LIFO collection for scenes). So I have to either make my **UIModule** aware of the concept of scenes (by making the **SceneStackModule** a dependency of the **UIModule**), create an **UIModule** for each scene or make the **UIModule** a dependency and register the **UIComponent** twice (once in the entity, once in the module).

---

**Approach 1**

```
public class UIModule : GraphicalModuleBase {
    public UIModule(SceneStackModule sceneStack) { }

    public void Draw(GameTime gameTime) {
        var uiComponents = SelectUIComponentsFromEntities();
        uiComponents.Draw(gameTime);
    }
}

```

**Approach 2**

```
public class MainScene : Scene {

    public UIModule UIModule { get; } = new UIModule();

    public void Draw(GameTime gameTime) {
        var uiComponents = SelectUIComponentsFromEntities();
        uiModule.Draw(gameTime, uiComponents);
    }
}

```

**Approach 3**

```
public class UIComponent : ComponentBase {
    public UIComponent(UIModule uiModule) {
        uiModule.RegisterComponent(this);
    }
}

```

All three approaches are not very nice (why does the UI need to be aware of scenes, why no components need modules as dependencies or why do I have to declare my 'main render logic' (UI before everything else) a part of every scene?). So I either clearly missed something here or that's another nasty part of game development. :/

# Answer
> 1 votes
The typical approach one - and the one taken to an extreme end by the "ECS" pattern that's hyped these days - is to have your module itself manage the components.

That is, `UIModule` shouldn't have to iterate through the scene to find all `UIComponent` instances. Instead, the module should just have a list of the components it cares about. It can easily then loop through those components.

There are many ways that the `UIModule` could find out about those components. One popularized in many ECS frameworks relies on there being a global event when a component or an entity is created. The `UIModule` could then listen for that event and register the components/entities it cares about.

Another way is to actually move component creation outside of the core entity manager. In this approach, a module would tell the entity manager about *component factories*. The `UIModule` would create a `UIComponentFactory` and then register that with the core entity manager (possibly in response to a `RegisterComponentFactories` event so there isn't a hard dependency). The `UIComponentFactory` identifies the type of component it knows how to create. Since `UIModule` creates and owns the factory, it's trivial to let the two objects share access to the list of live `UIComponent` instances.

Sample pseudo-code implementation of the factory approach (my preferred approach for simpler architectures):

```
clsss UIComponent;
class UIComponentFactory;

class UIModule
{
  unique_ptr<UIComponentFactory> _factory;
  vector<UIComponent*> _components;

public:
  UIModule(GlobalModule& global)
  {
    _factory = make_unique<UIComponentFactory>(this);
    global.Listen<RegisterFactoriesEvent >(&UIModule::OnRegisterFactories);
  }

  void OnRegisterFactories(RegisterFactoriesEvent& ev)
  {
    ev.factories.register(_factory.get());
  }

  void UpdateUI()
  {
    for (auto component : _components)
      Draw(component);
  }
};

class UIComponentFactory : AbstractFactory<UIComponent>
{
  UIModule& _module;

public:
  UIComponentFactory(UIModule& module) : _module(module) {}

  unique_ptr<UIComponent> Create() override
  {
    auto component = make_unique<UIComponent>(_module);
    _module._components.push_back(component.get());
    return component;
  }
};

```

Obviously there's a bit more to a real implementation, but that's the gist of it. Someone has to tell the core entity manager which components actually exist and how to create them. The factory pattern is perfect for the job. The factory can also register components with associated modules. You'll also want the factory involved in component death and such to make sure they get deregistered too, of course.

A variant of the above that's also used by ECS patterns a lot is to have a "Component Mapper" that owns the actual components. The `UIModule` can then query the `UIComponentMapper` to efficiently grab a list of all `UIComponent` instances.

Now, the idea of a `SceneStack` doesn't directly fit in here, but I'm not at all a fan of such a stack. Just let there be a list of active scenes without any stack notion; a scene is a scene and there could be one, many, or even no active scenes. Useful for picture-in-picture modes, background views, editors, complex menus, etc.

You can give each "scene" its own list of registered component factories, such that a module has to re-register a factory for each scene created. The module might choose to register a different factory instance per scene or it might share a factory across scenes. It might even register different types of factory for the same components depending on the scene, e.g. whether the scene is being created in "editor mode" or not.

That can even go so far as to have completely separate set of modules for each scene. That turns into the `Space` and `Subspace` approach used by a number of engines. A scene/space can itself be composite, after all; not all scenes need physics, for instance (e.g. if your menus are scenes composed of UI objects).

Part of what I'm getting at above is that component-based design is not just for your "entities". Your entity manager itself can be a composite of factories. Your scenes are already composites of entities and can also be composites of modules. Your engine is a composite of modules. Quite a few other concepts in a game can be (usefully) built as composites. You can go overboard and need to be mindful of whether you actually *need* a particular thing to be composite (it's not even a universal fact that your entities need to be composable!), but certainly be mindful that composition is a general software pattern and not just a trick for game objects.

---
Tags: c#, xna, architecture, entity-system, component-based
---


# Question
Title: Unity associated game object is null when running
I am just starting with Unity. I have two UI Text game objects, Atext and Btext. I have associated them by drag-dropping with my PlayerController script public variables, say public Text atext and public Text btext. Before running, the Unity editor correctly shows that Atext and Btext are correctly associated with the public variables. When running with debug, I get a null reference exception with btext and even the Unity Editor shows the association as None (Text). After stopping, the association turns to Btext as it is supposed to be. The script is very simple and I don't set btext to null at any point.

When I create a new UI Text object by duplicating Atext, it works correctly after associating it with some new variable. When I create a new UI Text object by Create-\> UI -\> Text, it doesnt work

Might be a stupid question but what am I forgetting?

Edit: Here is the problem again with code:

Before running with debug, the editor shows

```
PlayerController2 (Script)
Script: PlayerController2
Speed: 7
Countboxref: Countbox(Text)
Winboxref: Winbox (Text)
Brokenboxref: Text (Text)

```

where Countbox, Winbox, and Text are Canvas/UI/Text objects which I have drag dropped into place. Winbox object has been created by duplicating it from Countbox, Text has been created by Create -\> UI -\> Text.

```
enter using UnityEngine;
using UnityEngine.UI;
using System.Collections;

public class PlayerController2 : MonoBehaviour {

public float speed;
public Text Countboxref;
public Text Winboxref;
public Text Brokenboxref;
private Rigidbody rb;
private int boxit;

void Start ()
{
    Countboxref.text = "count";
    Winboxref.text = "winner";
    Brokenboxref.text = "broken";
}

```

When the program breaks on line Brokenboxref.text = "broken”, the editor shows

```
Brokenboxref: None (Text)

```

and when the execution is stopped completely, it again returns to

```
Brokenboxref: Text (Text)

```

Note 1: In this project, every Text object created with Create-\>UI-\>Text is broken. A new Text object works only when I select Countbox or Winbox and duplicate it. Thus it is not possible that the object would be explicitly destroyed in the code. I can create as many Text objects as I wish by copying (all don't work) and as many Text objects as I wish by duplicating (all will work).

Note 2: when I create a new project from scratch, of course everything works as expected. I assume the project is somehow corrupted.

Edit 2: No prefabs or such. Just the basic roll a ball tutorial. But this was my son's project so I am not sure what he has done when following the tutorial.

Note 3: The problem went away when I deleted the Library folder and forced Unity to rebuild it. Don't know yet if I caused any other problems by doing that. I saw that somewhere as a suggestion for corrupted projects. I don't know if there is a proper way to refresh.

Also, this project was originally started with Unity 4.6 and upgraded to 5.02

# Answer
> 0 votes
As requested, I am adding my own note 3 as an answer as it solved the problem.

The problem is solved when the Library folder is deleted and Unity is forced to rebuild it. This did not seem to cause any other problems

# Answer
> 0 votes
This is very strange. I've heard of MonoBehaviour null checks not be consistent but an object just becoming null? Strange.

A few first bases to cover:

* You're not destroying Brokenboxref
* Brokenboxref is serialized in the inspector, or at least exists when you use it
* You're not assigning Brokenboxref as anything else

I'm not sure what could be wrong if all these things are right. If creating a new project works, that's what you should do.

---
Tags: unity
---


title: find Vector2 libgdx

text:
# Question
Title: find Vector2 libgdx
I need to get coorinates of **red** point. Coordinates are just for example, it would be better to see the common formula. Found code like this, but it gains wrong result.()

```
Vector2 o = new Vector2(6f,2f);
Vector2 n = new Vector2(1f,4f);
Vector2 v = new Vector2(3f,2f);
Vector2 A = n.sub(o).nor();
float t = A.dot(v);
Vector2 result = A.scl(t);

```

# Answer
> 1 votes
From you code I can't tell what the `ownerv` vector is so I can't tell you why it's giving you the wrong result.

But to do it from scratch, according to Wikipedia's article on vector projection, you can do the following;

1. Create a vector **a** that is the direction from **o** to **v**.
2. Create a vector **b** that is the direction from **o** to **n**.
3. Let **d** be the *dot product* of **a** and **b** divided by the length of **b** (this will give you a scalar that is the distance from **o** in the direction of **b**).
4. Create the result, **target**, by adding a vector of length **d** to **o**.

In code those steps could look like this;

```
Vector2 o = new Vector2(6f, 2f);
Vector2 n = new Vector2(1f, 4f);
Vector2 v = new Vector2(3f, 2f);

// The direction from o to v
Vector2 a = (new Vector2(v)).sub(o);

// The direction from o to n
Vector2 b = (new Vector2(n)).sub(o);

// d is the length along b where the project a will fall.
float d = (new Vector2(a)).dot(b) / b.len();

// Take the vector that is the normal of b, scale it by d and add it to the start point o,
Vector2 target = (new Vector2(o)).add(b.nor().scl(d));

```

(Note that you probably don't want to new up as many `Vector2`s as I do in this example in your actual game code).

---
Tags: java, 2d, libgdx, vector, linear-algebra
---


# Question
Title: Unity - Problems with scene object orientation and rotation after updating my project from 5.0.0 to 5.2.2
Last year I made a large project on Unity 5.0.0, today I re-opened it on 5.2.2 to do some work on it. I was given the message that the project needed to be updated, I allowed it to do the update. Now when I open up my scenes, many of my scene objects are misplaced, the rotation is completely wrong and positioned in the wrong place. My scenes are of a refinery and the most commonly broken object is the pipework, something that would take hours to correct manually.

My pipework is created this way...

* All pipes are made in blender and each scene's pipes are saved as a single blender model (with each pipe make from a bezier curve and left as a separate object).
* Once imported into Unity (as a single .blend file), I've then dragged and dropped coloured materials onto all the individual pipes, so they are all coloured correctly.

This has all been fine until updating the project to 5.2.2 - now some of the pipes are in the right place, but many are rotated in completely the wrong direction, leaving it looking a mess. If I delete the pipes from Unity and reimport the pipe model back in, this would solve the problem, but then all the materials/colours will be gone. Due to the sheer amount of pipes throughout the whole project, to re-colour them all again would be an extremely problematic task, especially as it's critical that the pipes are the right colour.

I am confused how some of the pipes within the same pipe model are fine and the others are wrong, it would be so much easier to sort if they had all changed rotation together, then I could just switch them all back in 1 go. I have a total of 13 scenes and so far all of them have suffered the same problem.

Nothing whatsoever has been changed on any of the scenes, assets or indeed anything in the project folder. In fact I haven't touched a single file within the project since October last year, so it is certainly to do with updating to 5.2.2. Is there anything I can do to fix the problem without having to re-import the models back in or manually rotate everything back?

I have attached some screenshots to show the issue - See how in the blender image, all the pipework is placed correctly and then in the Unity image, half the pipes have flipped and are facing the wrong way. I have removed the ground so this can be seen clearer. Any help would be much appreciated.

Many thanks

# Answer
**RESOLVED** \- I have resolved the problem by going back to the blender scenes and applying 'Rotation & Scale' to everything, then when it updates in Unity everything is back in place. It appears the values had changed after doing the Unity update, resetting the values in Blender has corrected the issue. To fix -

* Open up the blender file
* Select everything (or just the broken objects if you wish) in Object Mode
* CTRL + A \> Select 'Rotation & Scale'
* Save
* Allow model to update in Unity
* All is well!
> 2 votes

---
Tags: unity
---