title: Action replay in unity 3d

text:
# Question
Title: Action replay in unity 3d
I'm trying to record an action replay for the last 5 seconds. I'm building a bowling game and want to perform an action replay for when the ball strikes the pin by capturing with camera's with different angles. I'm unaware of how this thing could be done. Do i have to record a clip at run time for that and play it at the right time to display action replay? or something else?

Below is the code. Please refer to it.

**Replay.cs**

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

public class Replay : MonoBehaviour
{

    public Text timertext;

    public GameObject pin1;
    public GameObject pin2;
    public GameObject pin3;
    public GameObject pin4;
    public GameObject pin5;
    public GameObject pin6;
    public GameObject pin7;
    public GameObject pin8;
    public GameObject pin9;
    public GameObject pin10;

    static int count = 50;

    Vector3 pin1po;
    Vector3 pin2po;
    Vector3 pin3po;
    Vector3 pin4po;
    Vector3 pin5po;
    Vector3 pin9po;
    Vector3 pin10po;

    List<Vector3> PinsPosition1;
    List<Vector3> PinsPosition2;
    List<Vector3> PinsPosition3;
    List<Vector3> PinsPosition4;
    List<Vector3> PinsPosition5;
    List<Vector3> PinsPosition6;
    List<Vector3> PinsPosition7;
    List<Vector3> PinsPosition8;
    List<Vector3> PinsPosition9;
    List<Vector3> PinsPosition10;

    List<Quaternion> PinsRotation1;
    List<Quaternion> PinsRotation2;
    List<Quaternion> PinsRotation3;
    List<Quaternion> PinsRotation4;
    List<Quaternion> PinsRotation5;
    List<Quaternion> PinsRotation6;
    List<Quaternion> PinsRotation7;
    List<Quaternion> PinsRotation8;
    List<Quaternion> PinsRotation9;
    List<Quaternion> PinsRotation10;

    public static bool start;

    // Use this for initialization
    void Start()
    {

        start = false;

        pin1po = new Vector3();
        pin2po = new Vector3();
        pin3po = new Vector3();
        pin4po = new Vector3();
        pin5po = new Vector3();
        pin9po = new Vector3();
        pin10po = new Vector3();

        PinsPosition1 = new List<Vector3>();
        PinsPosition2 = new List<Vector3>();
        PinsPosition3 = new List<Vector3>();
        PinsPosition4 = new List<Vector3>();
        PinsPosition5 = new List<Vector3>();
        PinsPosition6 = new List<Vector3>();
        PinsPosition7 = new List<Vector3>();
        PinsPosition8 = new List<Vector3>();
        PinsPosition9 = new List<Vector3>();
        PinsPosition10 = new List<Vector3>();

        PinsRotation1 = new List<Quaternion>();
        PinsRotation2 = new List<Quaternion>();
        PinsRotation3 = new List<Quaternion>();
        PinsRotation4 = new List<Quaternion>();
        PinsRotation5 = new List<Quaternion>();
        PinsRotation6 = new List<Quaternion>();
        PinsRotation7 = new List<Quaternion>();
        PinsRotation8 = new List<Quaternion>();
        PinsRotation9 = new List<Quaternion>();
        PinsRotation10 = new List<Quaternion>();

        pin1po = pin1.transform.position;
        pin2po = pin2.transform.position;
        pin3po = pin3.transform.position;
        pin4po = pin4.transform.position;
        pin5po = pin5.transform.position;
        pin9po = pin9.transform.position;
        pin10po = pin10.transform.position;

    }

    public void Checktime(bool time)
    {
        start = time;

    }

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

    }

    private void FixedUpdate()
    {
        if (start == true)
        {
            count = count - 1;

            if (count < 1)
            {

                PinsPosition1.Add(pin1.transform.position);
                PinsRotation1.Add(pin1.transform.rotation);

                PinsPosition2.Add(pin2.transform.position);
                PinsRotation2.Add(pin2.transform.rotation);

                PinsPosition3.Add(pin3.transform.position);
                PinsRotation3.Add(pin3.transform.rotation);

                PinsPosition4.Add(pin4.transform.position);
                PinsRotation4.Add(pin4.transform.rotation);

                PinsPosition5.Add(pin5.transform.position);
                PinsRotation5.Add(pin5.transform.rotation);

                PinsPosition6.Add(pin6.transform.position);
                PinsRotation6.Add(pin6.transform.rotation);

                PinsPosition7.Add(pin7.transform.position);
                PinsRotation7.Add(pin7.transform.rotation);

                PinsPosition8.Add(pin8.transform.position);
                PinsRotation8.Add(pin8.transform.rotation);

                PinsPosition9.Add(pin9.transform.position);
                PinsRotation9.Add(pin9.transform.rotation);

                PinsPosition10.Add(pin10.transform.position);
                PinsRotation10.Add(pin10.transform.rotation);

            }

        }
        if(count<-100)
        {
            return;
        }

    }

}

```

Thanks!

# Answer
> 2 votes
Rendering the scene from multiple angles at once in case the player wants to see a replay might be quite performance-intense. Also, you won't have enough memory to do that. 1920px * 1080px * 3 byte per pixel * 5 seconds * 60 frames per second * 10 perspectives = 17 GB of memory. Well, you could try to compress the videos in real-time, but that will make it even slower and will impair quality.

What I would suggest instead is to add a script `Recorder` to each replay-relevant game object which saves the `transform.position` and `transform.rotation` of the game object on each `Update` to a `List`.

In "Replay Mode", you disable all components which control the position of these objects and replace them with a script `Replayer` which then processes the list of transforms the `Recorder` saved update-by-update.

You can then replay the clip as often as you want with the camera in any position you like. You can even let the player control the camera during replay.

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


# Question
Title: How can I efficiently make a solid Texture2D?
I am trying to programmatically make an `Image` to cover the entire screen. I create the Texture2D, then create a Sprite from the `Texture2D`, then apply the `Sprite` to my `Image`. This works, but it is slow.

I suspect the issue is that I am setting each pixel individually for my `Texture2D`:

```
private static Texture2D CreateSolidTexture2D(Color color)
{
    var texture = new Texture2D(Screen.width, Screen.height);
    for (int y = 0; y < texture.height; y++)
    {
        for (int x = 0; x < texture.width; x++)
        {
            texture.SetPixel(x, y, color);
        }
    }
    texture.Apply();
    return texture;
}

```

I have tried creating the `Texture2D` by resizing a `Texture2D` of a single pixel, but the color comes out as a translucent white, instead of the color passed:

```
private static Texture2D CreateSolidTexture2D(Color color)
{
    var texture = new Texture2D(1, 1);
    texture.SetPixel(0, 0, color);
    texture.Resize(Screen.width, Screen.height);
    texture.Apply();
    return texture;
}

```

Why doesn't my second approach work? How can I *efficiently* create a screen-sized `Texture2D` of a solid color?

# Answer
> 5 votes
Instead of texture.SetPixel, use `texture.SetPixels`

```
var texture = new Texture2D(Screen.width, Screen.height);
Color[] pixels = Enumerable.Repeat(color, Screen.width * Screen.height).ToArray();
texture.SetPixels(pixels);
texture.Apply();
return texture;

```

Using `texture.LoadRawTextureData` might be even faster, but this requires that you know more about your texture format.

Alternatively you could use the hard-coded `Texture2D.whiteTexture`, stretch it to the size of the screen and set the color through the shader (this is what I would really recommend you to do if you plan to show a lot of different colors in quick succession).

---
Tags: unity, textures, gui, pixel, per-pixel
---


title: Sketching designs

text:
# Question
Title: Sketching designs
"A picture is worth a thousand words"

In the project I'm currently working I have the designer roll, and by designer I mean to mechanics and **not art**, so in the process of writing ideas such as the main features of a character or an enemy, the layout of a room or dungeon etc... I think that a quick sketch would be more clear than four paragraphs of text, but, I know nothing about drawing or sketching and I cant find anything that is not art-related.

What is the name of the technique used to illustrate this concepts?

To be more specific I looking for the technique that allow me to explain design concepts by drawing them, in the case of a character it would be something like a stickman with the key details.

Finally to not run in opinion based or to abroad issues I just want the name of the technique or a way to google it, (I'm assuming that there is not a ton different valid technics or they can be merged in a group)

# Answer
> 1 votes
Generally you could search for "diagrams". As one comment suggested UML which is a framework for diagramming some business and engineering concepts, but maybe not quite suited to what you're looking for.

Reality is that there may not necessarily be a specifically named type of diagram you would want. However, there exist many diagramming tools Visio, Draw.io, Realtimeboard, etc. that can let you build diagrams however you'd like. I'd recommend just getting into one of those (draw.io is free and easy, real time board is easier to collaborate in) and just building a simple diagram however you think describes your concept best.

Some references:

**Boss Keys**
Mark Brown has a series of videos on the layouts of Zelda dungeons. Through the series he actually develops his own framework for diagramming the dungeons to better communicate his concepts.
https://www.youtube.com/playlist?list=PLc38fcMFcV\_ul4D6OChdWhsNsYY3NA5B2

**Machinations**
Joris Dormans created a tool for diagramming and prototyping economics in games. Or any economics really, but geared for games.
http://www.jorisdormans.nl/machinations/

**Google Searches**
A quick google search for "game level flow diagrams" gave me this image: https://goo.gl/images/P6QzCg

* game level flow diagrams
* character progression diagram
* character stats diagram

Most of these that you find fall into a broad category of diagram types (flow diagrams, charts, etc.). So if you see one you like, it may be worth researching what type of diagram it is. Google "types of diagrams".

# Answer
> -1 votes
Maybe **Game Flow Diagram** ?

You can find plenty of documentation refering to this name, but here is a Gamasutra article about the subject: http://www.gamasutra.com/blogs/JasonBakker/20090604/84211/A\_GDD\_Template\_for\_the\_Indie\_Developer.php

---
Tags: game-design, terminology
---


# Question
Title: In Unity3D (and PhysX), how do I calculate the products of inertia?
Since uses underneath the surface, obviously they share the same features.

One of the features is the moment of inertia tensor - Unity3D one, PhysX one.

Though, they use the diagonal of the tensor, or in other words, only the moments of inertia excluding products of inertia.

Now, how would I calculate the products of inertia... I have to recalculate the whole tensor, or I can somehow extract the products?

I have checked around, but couldn't find a derivation solution (nor I know whether it is possible).

# Answer
> 3 votes
It is a general property of rigidbodies that theier inertia tensor can be diagonalised. This means it can be reduced to a form

```
[I1 0 0]
[0 I2 0]
[0 0 I3]

```

This is why unity and physx do not deal with the products of inertia.

It is likely that, for whatever problem you are trying to solve, it is simpler to do some rotations of your axes (in order to obtain this diagonal form) than to calculate and use all 9 elements of the tensor. Likely, this is what unity and physx do under the hood anyway.

Source: http://www.physics.arizona.edu/~varnes/Teaching/321Fall2004/Notes/Lecture34.pdf

---
Tags: unity, physics, rigid-body-dynamics, physx
---


# Question
Title: Unity5 How can I create this particle effect
I have been trying to replicate this particle effect that moves with the mouse:

https://my.pottermore.com/patronus

I have got close with the following settings

but I can't get the movement of the particles to be the same or to have to same intense white glow. It's like they have random direction from the center of the cursor but depending on the mouse speed it's like they have spread out more instead of being clustered on the mouse (hard to explain).

Does anyone know how I would achieve this effect?

# Answer
It is really difficult to say from just looking at only the settings, but from looking at what you want versus what you've set up, I think your issue is the `force over lifetime`.

Try using negative values instead of positive values. If you pay really close attention to the particle effect on the website the particles suck inward to a center point and then blow out from the other side. I think that change will get you closer to what you want.
> 1 votes

# Answer
As a Shape use Cone and than play with the Angle and Radius till you get the result you need
> 0 votes

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


# Question
Title: Using AR measuring techniques to allow free movement in a VR room
I am a Game Design student currently working on my graduation project. For this project, I want to develop a VR room, which can be walked through freely by using a smartphone. I already made a 1:1 scale replica of a meeting room (in Unity 3D) in the office I am currently working.

So I have been exploring different technologies that allow distance measuring techniques using markers and AR applications to measure distance between physical objects.

for example: https://www.youtube.com/watch?v=Tk31uGo7xHo https://www.ourtechart.com/augmented-reality/augmented-reality-tutorial-47-shapes-combined-trackers-unity3d-vuforia/

Now is it possible to use these methods to translate the measured distance into a vector 3 movement in a VR room? Also, is this relatively easy to do for a beginner programmer?

To be clear: The goal is to allow free movement through a pre-built 1:1 scale 3D room in VR by using a smartphone and markers in the physical room. Which hopefully will create some cool VR experience for the players.

Could anyone give me some advice? For example; is there anyone who already tackled this problem and is willing to share knowledge with me?

Thanks in advance

# Answer
This is possible, but not easy. Here's the things that are very difficult:

1. The monocular camera standard on smartphones. Ideally you'd want a 3D camera to provide depth information to assist in tracking movement. Markers can help with this, but you'll have very little flexibility in how you move around the room.
2. Position tracking with a smartphone. Smartphones are OK with rotation, and they can do GPS just fine. However, small movements and movements inside a structure are exceptionally difficult to accurately track with existing smartphone technology. Again, markers can help with this, but there's going to be a major issue with continuity of markers. You'd likely need to have one or more markers in view of the camera at all times for somewhat reasonable tracking.
3. This is not a beginner level project. Nor is it a game. If your major is in game design, perhaps you should be designing a game, instead of creating underlying technology?

SLAM algorithms are currently the best bet for something like this. People are working on this for mobile. Essentially you'd analyze the frames coming in from the camera to find key points, paired with the rotation of the device, you can calculate lateral movements.

Combining multiple sensors and averaging can help with drift. Check out this project for an example of that. The video contains links for the SLAM library and Android application. You can likely improve on the tracking with the use of carefully placed markers.
> 1 votes

# Answer
I've given some thought to this problem in the past, and while this probably isn't going to be a top scoring answer, it should at least help you think about the problem.

If you plan to use just markers, and a monocular camera, then you have to have some other known in order to dead-reckon your position.

One way is to use markers of a known size, and to help account for spatial drift, use square markers. You can then do some math on the distortion of the shape to calculate your relative position to the marker. Tagging each marker with a unique icon or color can help you discern which specific marker is in the view in cases where there is only one in your frame.

This method doesn't require any special sensors, as all your measurements are geometrically calculated from the shapes in your view.

Hope this helps.
> 0 votes

---
Tags: unity, virtual-reality, augmented-reality
---


title: 2D Skier physics looks very artificial

text:
# Question
Title: 2D Skier physics looks very artificial
I am creating a ski slalom game and I coded a new physics routine, because I was told the rigidbodies are pure "not overly good thing" to use by my boss. With my physics routine it indeed looks much better, but I have no idea how could I make the skier look less plastic. Which means I want to achieve similar level of control like in Skiing Yeti Mountain, because there the physics is quite enjoyable, though still arcade. Basically the requirements are that I need to set up acceleration, top speed and the amount of grip to use when turning, but it somehow bites me back

```
    [SerializeField]
    private Vector2 slopeDirection = -Vector2.up;

    var dt = Time.fixedDeltaTime;
    var dirVector = Vector2.zero;

    dirVector.x = Mathf.Cos( radianOrientation );
    dirVector.y = Mathf.Sin( radianOrientation );

    float actualAcceleration = Mathf.Abs(Vector2.Dot(dirVector, slopeDirection));
    actualAcceleration = Mathf.Lerp(maximumAcceleration, 0, actualAcceleration) * Mathf.Pow(maximumAcceleration, accelerationSmoothing);

    velocity.x += actualAcceleration * dirVector.x * dt;
    velocity.y += actualAcceleration * dirVector.y * dt;

    Vector2 velocityDirection = velocity;
    velocityDirection.Normalize();

    float actualFriction = Mathf.Abs(Vector2.Dot(dirVector, slopeDirection));
    actualFriction = Mathf.Lerp(minimumFriction, maximumFriction, actualFriction) * Mathf.Pow(actualFriction, frictionSmoothing);

    // Simulate friction
    velocity *= actualFriction;
    Debug.Log(velocity);

    if(!_isFinished)
    {
        this.transform.position += new Vector3(velocity.y, -velocity.x, 0);
    }

```

why it is overly odd is that when I turn to the side it has a very abrupt power loss and when I turn the skis to 45 degrees to the slope. how could I achieve that the skier will slow down when he turns his skis, but after a little while it will accelerate again like in Skiing Yeti Mountain?

# Answer
> 2 votes
I find a friction value of 0.98-0.99 is ideal in most cases. Try that as your `actualFriction` value to start with, adjusting it in increments of 0.005 or so, till you hit the sweet spot. Consider just how quickly that deficit is applied - we multiply by this factor 60 times per second. So keep close to 1.0.

Also eliminate use of `frictionSmoothing` until you have the aforementioned value closer to what you want. I fear this secondary factor is making things harder rather than simpler to fix, right now. In fact, get rid of those `Pow` statements altogether for now, and work it from there. I can almost guarantee that whatever problems you're having, `Pow` is quite literally compounding them.

Then gradually - step by step - work your formulae back to a sane solution.

# Answer
> 1 votes
Not sure if it will help, but maybe try scaling the game up or down, and re tweaking the physics. I was having problems setting physics variables in a 2D game I'm making because my game was so small that each unit in the game was relatively large, so I didn't have as much precision. Coulda been a fluke though; mixed with my beginner lvl programming skills.

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


title: Quake Physics ported to Unreal Engine?

text:
# Question
Title: Quake Physics ported to Unreal Engine?
My eSport mod needs the Quake 3 physics -- as well as some modern engine features.

Options are either:

1. Quake Engine: Upgrade/develop new rendering,etc component(s)
2. Unreal Engine: Port physics.

Going with the latest Unreal Engine 4 is clearly superior and logical. It seems adapting basic functions would be simple, like what has been done with maps. So, has it been done?

If not, is there any technical reason? Ideally, it's a matter of importing functions, coalescing to paradigm, scaling geometry, and that's about it. I cannot imagine the physics component of a modifiable engine not to be robust enough to extend its base set. Welcoming any wisdom before I need to take it on myself. :)

# Answer
This was a comment, but it's really an answer.

You're not going to get Quake 3's peculiarities in Unreal. Strafe jumping, grenade jumps, rocket jumps, etc. Here's me doing a combination grenade/rocket jump in Quake 3. That's not going to happen in Unreal unless you really mess around with how it works. https://youtube.com/watch?v=i6rqumD-9Hk

It totally does not make sense to use Unreal if Q3 physics is a core requirement. Much of Q3 physics either is, or arises from, bugs in the physics over the course of the series. If you must have Q3 physics, the only thing that makes sense is to use the Q3 engine.

Here are some more references on Q3 strafe jumping. You really, really don't want to have to set this system up yourself; it's pretty complex, and if you don't get it just right, your players will know.

https://www.youtube.com/watch?v=1g24fe4bwu0

https://www.youtube.com/watch?v=SAxPgIv4Q8s

The green zones in the latter video get narrower and wider apart as your speed increases. This is why in the first video the guy keeps looking further left and right from the trajectory as he goes.
> 3 votes

---
Tags: physics, unreal-4, udk, physics-engine, quake3
---


# Question
Title: What Blender or Unity features do I need to apply to the box to make it a single, rigid unit, like all the edges are nailed together?
I created a hollow box, in Blender, and imported it into Unity. The problem is, when the game starts in Unity, and gravity is applied, the box falls apart. So there needs to be some kind of *glue* that holds the edges of the box together.

What Blender or Unity features do I need to apply to the box to make it a single, rigid unit, like all the edges are nailed together?

# Answer
If the object contains a single mesh, it will hold together. It sounds like you have used separate meshes to create each side, so by default, they are separate pieces. However, there is a pretty easy way to hold them all together. Have them parented together.

### Parent the mesh objects

You can do this in either Blender or Unity. I am not overly familiar with the process, in Blender, but I imagine it would be pretty easy for future work. In Unity, it is just a matter of dragging the secondary objects onto the main object, via the Inspector. To keep things consistent, it might be a good idea to parent all sides to an empty game object, placed in the dead centre of your cube.

### Use a single rigidbody

At this point, it is important to ensure that your parent object contains the rigidbody; this body will encompass all containing parts, not just the base object. In contrast, placing a rigidbody on all separate components tells Unity that they *are* separate components, which is not what you want. You can see this demonstrated in the animation, below. Both cubes are the same *"HollowCube"* construct you see in the above image; the yellow cube has a rigidbody attached to its base *"HollowCube"* object, while the multi-coloured cube has a rigidbody attached to each of the children *"Cube\_"* objects. As you can see, the object with multiple rigidbodies immediately breaks up, while the object with the single rigidbody stays connected.
> 2 votes

---
Tags: unity, blender
---


# Question
Title: D3D9CAPS gives unusual maximum shader instructions value
I'm trying to implement a vertex and pixel shader on a piece of hardware we're developing a game for which uses the DirectX 9.0c runtime. The shaders are for boned mesh animation and is a bit more complicated than the only other shader I have gotten working so far which is a simple 2d sprite shader. The boned mesh shader seems to work fine when developing on my PC but doesn't work when I transfer it over to the target hardware. This lead me to checking the hardware capabilities of both machines to check for any differences and I got the following unusual results:

Development machine Dx9 cap results:

```
Maximum primitive count: 16777215
Device supports level 3.0 vertex shaders
Vertex shader maximum number of instructions run when using flow control 65535
Vertex shader maximum number of constant buffers 256
Vertex shader maximum number of 30 instruction slots 4096
Vertex shader instruction predication supported
Vertex shader dynamic flow control depth 24
Vertex shader number of temporary registers 32
Vertex shader static flow control depth 4
Device supports level 3.0 pixel shaders
Pixel shader maximum number of instructions run when using flow control 65535
Pixel shader maximum value of arithmetic component 65504.000000
Pixel shader maximum number of instruction slots 4096
Pixel shader instruction predication supported
Pixel shader dynamic flow control depth 24
Pixel shader number of temporary registers 32
Pixel shader static flow control depth 4
Pixel shader number of instruction slots 512

```

Target machine Dx9 cap results:

```
Maximum primitive count: 5592405
Device supports level 3.0 vertex shaders
Vertex shader maximum number of instructions run when using flow control -1
Vertex shader maximum number of constant buffers 256
Vertex shader maximum number of 30 instruction slots 32768
Vertex shader instruction predication supported
Vertex shader dynamic flow control depth 24
Vertex shader number of temporary registers 32
Vertex shader static flow control depth 4
Device supports level 3.0 pixel shaders
Pixel shader maximum number of instructions run when using flow control -1
Pixel shader maximum value of arithmetic component 340282346638528860000000000000000000000.000000
Pixel shader maximum number of instruction slots 32768
Pixel shader instruction predication supported
Pixel shader dynamic flow control depth 24
Pixel shader number of temporary registers 32
Pixel shader static flow control depth 4
Pixel shader number of instruction slots 512

```

What I found unusual was the maximum number of instructions during flow control was -1 for both the pixel and vertex shaders on the target machine. Is it the case that the target hardware can only support shaders with no flow control? i.e. no for loops, if conditions etc.

The only reason I ask is because the simple shader, with no flow control, works fine but the more complicated boned mesh shader, with for loops and if conditions, isn't working. It just seemed like too much of a coincidence that the only major difference between the two caps seems to be the flow control based one or am I barking up the wrong tree?

In case this helps I've linked the two shaders I've written just in case there's any obvious errors in there:

2D Sprite shader: https://pastebin.com/0G9swKu6

3D Boned Mesh shader: https://pastebin.com/Ayd0bXWU

Any input/ideas would be greatly appreciated.

# Answer
> 1 votes
These two caps - MaxVShaderInstructionsExecuted and MaxPShaderInstructionsExecuted - are both of type DWORD, which is an unsigned int type.

From d3d9caps.h:

```
DWORD   MaxVShaderInstructionsExecuted; // maximum number of vertex shader instructions that can be executed
DWORD   MaxPShaderInstructionsExecuted; // maximum number of pixel shader instructions that can be executed

```

Cross-checking on other PCs we see that they can have values of 4294967295, or hexadecimal 0xffffffff.

If you cast/convert this to a signed int type, you get -1.

**The -1 value is therefore not significant but rather a bug in your own code** \- you're converting an unsigned int to a signed int at some stage between retrieving and displaying the caps.

As for what's wrong with your shaders - you need to be more specific when you say "not working" - you need to describe what's actually happening. From a brief glance at the shader code I would suggest that you're using a lot of constant registers for SM3, but in the absence of clarification (and I suggest you make it a separate question) I can't do more than speculate.

---
Tags: c++, shaders, hlsl, 3d-meshes, directx9
---


# Question
Title: How to work properly with different coordinate-systems
Let's say we got a little set {S} wich has 4 possible coordinate systems (LH=left handed, RH=right handed):

1. LH-y\_up
2. LH-z\_up
3. RH-y\_up
4. RH-z\_up

Now, let's say my Opengl engine is using a RH-y\_up coordinate system and I want to import models from some 3d package which uses a RH-z up coordinate system (like 3ds max). One way to do it would be at the exporting/preprocessing stage flipping the y&z model's components. That solution doesn't seem like a really good idea though... what about if i decided to change eventually on my engine from coordinate system 3) to 1) or 2)?

So, my question would be. Let be A & B 2 coordinate systems from set S. What's the proper way to use models from A onto B?

# Answer
> 2 votes
You can get things pretty generic by writing a conversion layer, likely using matrix transformations. You're already thinking along these lines with the pre-processing stage.

At a high level, this would look like:

```
LoadModel(Model modelData)
   CoordinateSystem modelCoordSystem = DetectModelCoordinatesSystem(modelData);
   if(modelCoordSystem != engineCoordSystem)
       modelData = ConvertModelCoordinates(modelCoordSystem, modelData)
   AddModelToDatabase(modelData)

ConvertModelCoordinates(CoordinateSystem current, Model data)
    Transform transform = GetTransform(current, engineCoordSystem)
    return ApplyTransform(transform , data)

```

Where `GetTransform` would select the correct Matrix Transform to convert from the current orientation to the desired orientation. This implementation does provide for a change in engine system down the road, but it won't be as simple elsewhere in the engine to switch, or it'll mean considerably more work to code every method that assumes a certain coordinate system to be coordinate system agnostic.

As for what happens if you change your mind later. *If* you were to change your mind, you'd just modify your conversion layer at the same time.

However, if your design is so up in the air you're thinking your coordinate system might change in the future, you might want to nail some things down before going too much further. Remember that it's very difficult to finish something like a game engine. Worrying about making it flexible enough to accept foundational changes later down the road is going to stretch your development time to infinity.

---
Tags: opengl, transformation, coordinates, 3dsmax
---


# Question
Title: What should I be considering when designing an Event Manager System?
I have been puttering around with the fundamentals of a Java game engine, and I've reached the point where I'm ready to add in an Event Manager system.

I know, *in theory*, what an Event Manager should do: allow objects to "register" for certain events, and whenever the Event Manager gets notified of an event, broadcast the event to the "registered" listeners. What I'm stumped on is how to start implementing it.

I haven't been able to find anything, online, about implementing an event system from scratch, so I'm looking for input on what the best practices are in this case - what I *should* and *should not* be doing.

For instance, is it really necessary for each of my game objects to have an `EventManager` field? Since all of my game objects inherit from a single, abstract parent class, I think I should be able to use a static reference so that there's only one instance of the Event Manager, shared between all the game objects. I do something similar, with the Applet, that I use to render each object, already.

I suppose I'd have to maintain a collection of some sort for each possible subscribed event - adding and removing game objects from the list, as needed. I think it should be possible to make a queue of events that need to be broadcast, in which case I could simply add "EventManager.Update()" to the main game loop, and have the `Update()` method broadcast the events that occurred at the end of each frame. Finally, each object would have a `HandleEvent(Event e)` method, that they could then parse and respond to, appropriately.

---

Does this sound like the appropriate direction towards implementing such a system, or am I way off track and/or missing something quite obvious?

# Answer
This can be as simple as you want.

```
for each object in the subscriber list:
    object.notify(this event) // (or 'HandleEvent' if you prefer)

```

Don't try and work out what an event manager 'should' do - work out what you need it to do. The rest should follow from there, or at the least, should suggest some more specific questions.
> 7 votes

# Answer
The three essential methods an event system needs is an addListener() method, a removeListener() method, and a method to dispatchEvent(). That is, a method objects use to register for an event, a method objects use to un-register, and a method to actually broadcast an event to all the listeners. Everything else is gravy.

As you note, you will certainly need some sort of data structure to keep track of registered listeners. The simplest approach would be an associative array (Dictionary, or an Object in JavaScript) that associates a vector (or simply an Array depending on the language) with an event. That vector is a list of all the registered listeners; add listeners to the list or remove them in the add/removeListener() methods.

To broadcast an event in dispatchEvent() it can be as simple as looping through the vector. You could add more complexity to dispatching by sorting the priority of events or whatever, but don't worry about that until you need it. In many cases you won't need it.

There is a little nuance to dispatchEvent() when you consider what data to pass along with the event. At the most basic level you might not pass any additional data; all the listener has to know is that an event happened. However most events have additional data that go with them (eg. where the event happened) to you'll want to have dispatchEvent() accepting and passing along some parameters.

> For instance, is it really necessary for each of my GameObjects to have a "EventManagner" field? Since all of my GameObjects inherit from a single, abstract parent class, I think I should be able to use a static reference so that there's only one instance of the EventManager, shared between all the game objects.

There are many ways to give all your game objects a reference to the EventManager class. A static reference is certainly one way; another is with a Singleton. Both of those approaches are pretty inflexible however, so most people around here recommend either a service locator or dependency injection. I've been doing dependency injection; that does mean a separate EventManager field for each object, which is what you seem to want to avoid, but I'm not sure why that is a problem. It's not like there's a lot of overhead from storing a bunch of pointers.
> 3 votes

# Answer
> *DISCLAIMER*
>
> Im not a Java programmer but i wrote an article explaining how to create an event system in C89, one of the easiest languages (IMHO), check it out
>
> https://prdeving.wordpress.com/2017/04/03/event-driven-programming-with-c-89/

The basics of event handling are pretty simple.

* register an event with a callback
* trigger event
* loop through listeners to see if there's a match
* fire handler if found
* repeat

Knowing this (but not knowing how to implement it in Java), is easy to understand that you need some handlers (functions to handle the events) and add them to an array (with pointers, in C) paired with an event name. Once you trigger an event, you store the triggered event name and it's arguments in a stack, this is called the event pool.

Then you have an event digest (a simple loop), who pops the first event in that stack, tries to find a handler for it, and if theres any, runs it with the params.

Of course, this event digest can be triggered whenever you want, for example once per frame after you call your `Update()` function.
> 0 votes

# Answer
For the EventManager-field, use a static variable. A Singleton for the EventManager would be a great idea, too.

Your approach sounds good, but don't forget to make it thread-safe.

It is good to execute IO-Events before or after the "GameEvent"s, so in one frame every "GameEvent" deals with the same data.
> -2 votes

---
Tags: events
---


# Question
Title: How do I create a horizontal tech tree for the web?
I'm currently using bootstrap, jQuery and KnockoutJS to create a simple game. I would like to make a horizontal tech/research tree where the player can do research to get bonuses.

I found a CSS version, but there is no way to implement research having two dependencies, so it would limit the possibilities. I also found two commercial JavaScropt libraries, but I'd prefer not to spend $2000.

How do I create a horizontal tech tree for the web?

# Answer
Techtreejs might be what you are looking for. Here is a demo.
> 1 votes

---
Tags: javascript, tree, jquery
---


# Question
Title: How does delta compression reduce the amount of data sent over the network?
Many games use the technique of delta compression in order to lower the data load sent. I fail to understand how this technique actually lowers the data load?

For example, let's say I want to send a position. Without delta compression I send a `vector3` with the exact position of the entity, for instance `(30, 2, 19)`. With delta compression I send a `vector3` with smaller numbers `(0.2, 0.1, 0.04)`.

I don't understand how it lowers the data load if both of the messages are `vector3` \- 32 bit for each float - 32 * 3 = 96 bits!

I know you can convert each float to a byte and then convert it back from a byte to float but it causes precision errors which are visible.

# Answer
There are times when you cannot avoid sending the full game state - such as on load of a saved multiplayer game, or when a resync is needed. But sending full state is usually avoidable, and that's where delta encoding comes in. Generally, this is *all* that delta compression is about; your example doesn't really describe that situation. The reason delta compression is even mentioned is because naïve implementations will often send *state* rather than *deltas* because state is usually what any naive game implementation stores anyway. Deltas are then an optimisation.

With deltas, *you'd never send the positions of units that did not move*, at all. That's the spirit of it.

Imagine we were penpals for years, and I lost my memory (and had discarded all your letters after reading them). Instead of simply continuing with your series of letters as normal, you'd have to write me the entire history of your life in one massive letter, all over again, for me to catch up.

In your given case, it may (depending on your codebase) be possible use a lower number of bits to encode the deltas, as opposed to the large bit-ranges needed to send full state. Say the world is many kilometres across, you may need a 32-bit float to accurately encode positions down to say, a centimetre in a given axis. However, given the maximum velocity applicable to entities, which may only be a couple of metres per tick, it may be doable in just 8 bits (2^8=256 so sufficient to store max of 200cm). Of course, this assumes fixed rather than floating point usage... or some kind of half/quarter float as in OpenGL, if you don't want fixed point hassles.
> 43 votes

# Answer
You have the wrong delta. You're looking at the delta of the individual elements. You need to think of the delta of the entire scene.

Suppose you have 100 elements in your scene, but only 1 of them moved. If you send 100 element vectors, 99 of them are wasted. You really only need to send 1.

Now, let's say you have a JSON object that stores all your element vectors. This object is syncronized between your server and your client. Instead of deciding "did so and so move?" on your client, you can just generate your next game tick in a JSON object that contains only the elements that moved. On the client side, you apply the diff to your current tick's vector and you're all set.
> 24 votes

# Answer
Very often another compression mechanism will in combination with delta encoding like for example arithmetic compression.

Those compression schemes work much better when the possible values are grouped together predictably. Delta encoding will group the values around 0.
> 9 votes

# Answer
You are right that a naïve delta calculation on its own, with the result stored in the same size data structure as the operands and transmitted without any further processing would not save any traffic.

However, there are two ways a well-designed system based on deltas can save traffic.

Firstly in *many* cases the delta will be zero. You can design your protocol such that if the delta is zero you don’t send it at all. Obviously, there is some overhead to this as you have to indicate what you are or are not sending, but overall it is likely to be a big win.

Secondly, the deltas will usually have a much smaller range of values than the original numbers. and that range will be centered on zero. This can be exploited either by using a smaller data type for most deltas or by passing the complete data stream through a general-purpose compression algorithm.
> 8 votes

# Answer
You are broadly correct, but missing one important point.

**Entities in a game are described by many attributes, of which position is only one**.

What kind of attributes? Without having to think too hard, in a networked game these might include:

* Position.
* Orientation.
* Current frame number.
* Colour/lighting info.
* Transparency.
* Model to use.
* Texture to use.
* Special effects.
* Etc.

If you pick each of these in isolation, you can certainly make the case that if in any given frame it needs to change, then it must be retransmitted in full.

However, **not all of these attributes change at the same rate**.

Model doesn't change? Without delta compression, it must be retransmitted anyway. With delta compresion it needn't be.

Position and orientation are two cases which are more interesting, commonly being composed of 3 floats each. Between any given two frames, there is a possibility that only 1 or 2 of each set of 3 floats may change. Moving in a straight line? Not rotating? No jumping? These are all cases where without delta compression you must retransmit in full, but with delta compression you need only retransmit that which changes.
> 8 votes

# Answer
While most answers talk about how delta encoding is about only sending the changes to state as a whole, there is another thing called "delta encoding" that can be used as a filter for reducing the amount of data you need to compress in the full state update as well, which may be where the confusion comes from in the question as asked.

When encoding a vector of numbers, you can in some cases (e.g. integers, enums, etc.) use a variable-byte encoding for the individual elements, and in some of these cases you can further reduce the amount of data that each element needs if you store it as either running sums, or as the minimum value and the difference between each value and that minimum.

For example, if you want to encode the vector `{68923, 69012, 69013, 69015}` then you could delta-encode that as `{68923, 89, 1, 2}`. Using a trivial variable-byte encoding where you store 7 bits of data per byte and use one bit to indicate that there's another byte coming, each of the individual elements in the array would require 3 bytes to transmit it, but the delta-encoded version would only require 3 bytes for the first element and 1 byte for the remaining elements; depending on the sorts of data you're serializing this can lead to some pretty impressive savings.

However, this is more of a serialization optimization and is not what is generally meant when we talk about "delta encoding" when it comes to streaming arbitrary data as part of game state (or video or the like); other answers already do an adequate job of explaining that.
> 6 votes

# Answer
It's also worth noting that compression algorithms do their job better on the diff. As other answers mention either most of your elements stay the same between 2 states, or the values change by a small fraction. In both these cases applying a compression algorithm to the difference of your vector of numbers gives you significant savings. Even if you *don't* apply any extra logic to your vector like removing the 0 elements.

Here's an example in Python:

```
import numpy as np
import zlib
import json
import array

state1 = np.random.random(int(1e6))

diff12 = np.r_[np.random.random(int(0.1e6)), np.zeros(int(0.9e6))]
np.random.shuffle(diff12) # shuffle so we don't cheat by having all 0s one after another
state2 = state1 + diff12

state3 = state2 + np.random.random(int(1e6)) * 1e-6
diff23 = state3 - state2

def compressed_size(nrs):
    serialized = zlib.compress(array.array("d", nrs).tostring())
    return len(serialized)/(1024**2)

print("Only 10% of elements change for state2")
print("Compressed size of diff12: {:.2f}MB".format(compressed_size(diff12)))
print("Compressed size of state2: {:.2f}MB".format(compressed_size(state2)))

print("All elements change by a small value for state3")
print("Compressed size of diff23: {:.2f}MB".format(compressed_size(diff23)))
print("Compressed size of state3: {:.2f}MB".format(compressed_size(state3)))

```

Which gives me:

```
Only 10% of elements change for state2
Compressed size of diff12: 0.90MB
Compressed size of state2: 7.20MB
All elements change by a small value for state3
Compressed size of diff23: 5.28MB
Compressed size of state3: 7.20MB

```
> 4 votes

# Answer
Delta compression is a compression of delta encoded values. Delta encoding is a transformation that produces different statistical distribution of numbers. If the distribution is favourable to the compression algorithm chosen, it lowers the amount of data. It works very well in a system like a game where entities move only slightly between two updates.

Let's say you have 100 entities in 2D. On a large grid, 512 x 512. Considering only integers for the sake of example. That's two integer numbers per entity or 200 numbers.

Between two updates, all our positions change either by 0, 1, -1, 2 or -2. There have been 100 instances of 0, 33 instances of 1 and -1 and only 17 instances of 2 and -2. This is pretty common. We choose Huffman coding for compression.

The Huffman tree for this will be:

```
 0  0
-1  100
 1  101
 2  110
-2  1110

```

All your 0's will be encoded as a single bit. That's only 100 bits. 66 values will be encoded as 3 bits and only 34 values as 4 bits. That's 434 bits or 55 bytes. Plus some small overhead to save our mapping tree, as the tree is tiny. Note that to encode 5 numbers, you need 3 bits. We have traded here the ability to use 1 bit for '0' for the need to use 4 bits for '-2'.

Now compare this to sending 200 arbitrary numbers. If your entities can't be on the same tile, you are almost guaranteed that you get a bad statistical distribution. The best case would be 100 unique numbers (all on the same X with different Y). That's at least 7 bits per number (175 bytes) and very hard for any compression algorithm.

The delta compression works in the special case when your entities change only a little. If you have a lot of unique changes, delta encoding will not help.

---

Note that delta encoding and compression is used in other situations with other transformations as well.

MPEG splits picture in small squares and if part of the picture moves, only the movement and a change is brightness are saved. In a 25fps movie, a lot of changes between frames are very small. Again, delta encoding + compression. Works best for static scenes.
> 1 votes

# Answer
If your position are stored in vector3 but the actual entity can only move a few integer at a time. Then send it's delta in bytes would be better than sending it in integer.

> Current position: 23009.0, 1.0, 2342.0 (3 float)
> New position: 23010.0, 1.0, 2341.0 (3 float)
> Delta: 1, 0, -1 (3 byte)

Instead of sending the exact position every time, we send the delta.
> 0 votes

---
Tags: networking, compression
---


# Question
Title: What is the difference between a game framework and a game engine?
What is the difference between a game framework (for example, XNA with C#, SDL for c++) and a game engine?

Do game frameworks use engines? Does a game engine encapsulate sub-engines like physics engines, particle engines etc? Should they be used together, or are they mutually exclusively?

I take it there are separate engines for both 2D and 3D?

# Answer
> 22 votes
There really aren't strict definitions for "engine" or "framework."

Generally speaking, an engine is considered to "do more" or have more tools and related support than a framework, which is itself is often just a loose collection of related functionality exposed through some unified API.

To that end, things that claim to be engines may use things that claim to be frameworks to achieve functionality, but that does not always need to be the case. Similarly, a thing claiming to be a game engine can claim that it's constituent parts (the physics and rendering, et cetera) are implemented with a physics engine or a physics framework. The kinds of technology referred by both terms can be used interchangeably, or not.

There can be "engines" or "frameworks" for just about anything -- physics, sound, and yes, even 2D or 3D graphics.

It's really just a terminology issue, and it doesn't generally matter much. From a functionality perspective, a perspective focused on making your game, what should matter is whether or not the technology in question delivers what you need to make your game. Whether it calls itself an engine or a framework won't have any bearing on that.

# Answer
> 11 votes
Simple definition that I use: you can build an engine on a framework but you would never build a framework on an engine. One is the skeleton that determines architecture and program flow, the other is muscle that does the work.

For a concrete example, Artemis is a neat little framework for building component systems but you'd never call it an engine. You could build Artemis Systems and standard components to create an engine from it.

# Answer
> 3 votes
For a realy detailed explanation I recommend reading the one and only bible Game Engine Architecture by Jason Gregory. I guess it is the most complete work about this topic since it was published. It does not only handle the C++ part but also and important for every game engine programmer the theory/architecture behind. It's a good starting point independent of the language. To get an overview what we are talking about is this image from the book

Let me give it a try to answer the question.

Whatever you write it will be code :-) after years of experience, write what you need and how you need it or use what provides you what you need.

The terms **engine** and **framework** come from software architecture along with other terms. So let's start with the basic terms und lets move upwards.

---

**Library**

Typical examples: a math library providing all the basic types and functions for mathematical calculations (Vector, Matrix,...) or image (jpeg or png) library providing the functionality for writing jpeg or png images

In Unity 3D Math is a math libray.

Theory: a libray provides dedicated features around a topic (e.g. math) AND **is called by the programmer on demand**.

Some preview: there can be libraries holding frameworks aka being a framework library.

---

**Framework**

Theory: A framework introduces an **inversion of control**. This means the developer most of the time does not call the framework methods but the framework calls the code of the developer. Exceptions are when you have to integrate the framework library in your code and have to start the framework. A framework library provides all methods and functions and interfaces for a framework with a dedicated usage. So frameworks can be in a library.

Typical example: The Unity 3D MonoBehaviour provides methods like Awake, Start, OnUpdate. The developer implements these methods and then **these methods get called by the (game object management) framework (this is the inversion of control)**. The same with the methods OnCollisionEnter, OnCollisionExit. They are in the same Monobehaviour but I would bet they are called by the physics framework.

---

**An preview: Engine, Runtime, Editor, SDK**

Since the term engine was always kind of vague and still is (and it does not become better with further technological developments) some preview explanation.

The term engine is used for multiple things and it can not be uniquely said which one is right. Back in 2004 when I first had contact with writing game engines it was vague too. You had a game engine in the meaning of some sort of code loading predefined data and let you play the game. Since it loads predefined data they were called data-driven engines. You compile them once and the external data could have been different games without recompiling it. At some point of time this was the same like a runtime.

The editor is clear. It lets you define the predefined data loaded by the engine/runtime.

An engine with an editor was called SDK (e.g. Hammer SDK).

Then there were/are dedicated engines. A phyiscs engine, rendering engine, sound engine, gameobject management engine, network engine,....

In my personal opinion those are not engines (especially a render engine IS NOT a game engine since it does only rendering). When I google game engine the results contain 90% pure render engines which are not game engines. I would call all of them libraries but since they may load predefined data they would match the term data-driven engine.

A last short side note before we get into details: I successfully graduated with a masters degree in computer science. My master thesis handled the topic "how to develop the core of a game engine". Meaning the part of the code which clues together all the other engines, does the game object management, the game loop, etc...

I published my master thesis as a (short) book. The only comment on Amazon from a buyer/reader is (after a few years out): this is not about a game engine. Since I graduated successfully and therefore have defended my thesis against 3 experienced programmers (2 of them dedicated to games and interactive applications) I guess I have written a game engine.

---

**Editor**

Easy: lets you define the data in the format the other parts require them and therefore eliminates the demand to write those files by hand or use external tools to create them.

This is what the Unity 3D editor does.

---

**Runtime**

This term is often **used equally with engine** (which can be correct or incorrect).

The runtime executes the generated data and does what it has to do with the data. E.g show you the game and let you play the game. It does not create any data (except maybe save games) in the meaning you can't modify the game itself withit.

The Unity Web Player is/was a runtime let you play Unity games within a webbrowser.

You can load and execute multiple different games with the same runtime.

In the case of the Unity 3D scripting API there is a cut between functionality that will work in the game and functionality that will only work within the editor.

---

**SDK**

This term is often **also called framework**.

Back then an SDK has been a bundle of tools like an editor, IDE (integrated developer environment) for programmers, exporters for dataformats and the runtime/engine.

So an SDK/framework provides you with a predefined workflow and utilities and shows you a (well designed) way how you can (easily) create a game.

Basically Unity 3D engine would be wrong since it would fit more into the SDK direction. But since Unity is even more a new word/definition is needed to match what it is.

Anyway, to introduce the other term, an SDK/framework provides you a predefined game development pipeline (not only a asset pipeline but maybe, like Unity, a pipeline for assets, logic, builds, deployments,....)

---

**Engine**

**sarcasm on** Used for everything since everybody wants to be cool by writing not only a library, a framework or a game but better writing a complete engine.**sarcasm off**

Let's trigger it down:

An engine

1. is a piece of code/software
2. it is aimed to be reused in multiple projects (you can also write a game engine for only one game)
3. for being reused the game engine seperates the reusable part from the game specific part
4. for being reusable (depending on how it is intended to be reused) there are different flavours like a **data-driven engine** loading external data

A engine can consist of multipe other engines (since everything is called an engine nowadays). A game engine can include

* a render engine doing the rendering (AGAIN: god, damn, hell: code doing only rendering IS NOT a game engine)
* a physics engine doing the physics (it's a physics engine, not a game engine)
* an AI engine handling the AI stuff (it's an AI engine and not a game engine)
* a network engine (e.g. RakNet) doing the network stuff (it's a network engine, not a game engine)
* an audio engine doing the audio stuff (it's an audio engine and not a game engine)

An example for an application based on a core engine providing a plug-in based framework for cluing everything together in a component based game object management model. Each subengine (rendering audio) is a module added to the game engine as plug in. Each component can be part of a subengine/module. And the (component based) game object management is the connecting link between the seperated modules.

---

**The closest definiton for Game Engine**

A **game engine** is the part of the **source code** of your game that **provides all the functionality** which is **intended to be reused** accross multiple games and let you **code and execute** your game. Therefore it **clues together** all the other parts of the code (rendering, audio, physics, game object management, networking) which are either libraries, frameworks or dedicated engines (rendering, physics,...).

The game engine is the mess in the middle.

---

# Answer
> 2 votes
A framework is a collection of (usually) lower level libraries and helper stuff that you can use to do whatever the hell you want (graphics, sounds, etc.). There is nothing game-related about a framework except they're usually optimized or designed to do things that are common in games.

Example: an engine allows you to have a list of entities, each with a position on the map. A framework allows you to render a 3d object at a certain position.

So you connect them by giving each of your entities a 3d object, and render them when needed.

And ta-da, you have a game.

# Answer
> 0 votes
As @Josh already stated, there's no strict definition of framework or engine but, in a conceptual sense, both are very different tools.

A framework contains a basic API abastraction to work with, giving the user higer level tools to interact with the platform or the functionality without (generaly) worrying about performance, compatibility, etc. In the examples you gave, SDL is a framework, it gives you abstarction over the platform, and you can build your software behind that layer without worring about window management, OS specific stuff, etc. If you want to build a whole software, you are going to need diferent frameworks, f.e SDL to manage the media and platform stuff, Box2D to manage physics, etc.

An engine is different, in this case, the tool ships everything needed for the development, a physics engine will provide you with everything needed to manage physics and will ship an easy to use API, so, if you want to build a physics simulation you wont need any other third party library. Engines are no more than a collection of frameworks, other engines, interfaces, snippets and general code who provides everything needed to complete the project without needing other 3rd parties nor worring about lower level stuff.

---
Tags: terminology
---


# Question
Title: How to make a drawing action run in an left released event in Game Maker?
At first I tried to make the progress bar update using only one object that would command everything (`obj_Control`), linking to the `global left released` event a script containing the `draw_rectangle` function, but I got no results.

The Game Maker did not acknowledge any errors, but the progress bar did not update when I clicked on the created rectangles.

**obj\_Control** (already without the `draw_rectangle` event):

Because of this I decided to create 3 new objects (`obj_Vida, obj_Fome, obj_Energia`), each containing a sprite and when each was clicked it would perform the action to update the progress bar:

**obj\_Vida**:

scpt 1 =\> `obj_Control.vida+=10;` (**applies to self**)

scpt 2 =\> `draw_healthbar(120,100,240,120,vida,c_black,c_red,c_green,0,true,true);` (**applies to obj\_Control**)

**obj\_Fome**:

script 1 =\> `obj_Control.fome+=10;` (**applies to self**)

script 2 =\> `draw_healthbar(120,150,240,170,fome,c_black,c_red,c_green,0,true,true);` (**applies to obj\_Control**)

**obj\_Energia**:

script 1 =\> `obj_Control.energia+=10;` (**applies to self**)

script 2 =\> `draw_healthbar(120,200,240,220,energia,c_black,c_red,c_green,0,true,true);` (**applies to obj\_Control**)

**Room**:

Room size =\> 360x640

Translate =\> **vida/life, fome/hungry, energia/energy**

What happens is that even dying of clicking on objects (`obj_Vida, obj_Fome, obj_Energia`) nothing happens to the progress bar. I discovered that it is because of the event, it would have to be a draw event. I added one below the `left released` event, but it did not work.

I apologize for any typing errors. I am not an English speaker and I had to translate everything. If something was not clear, please signal.

Thanks for everything.

# Answer
> 1 votes
`draw_` functions works only in `Draw` event (to be precise, it works anywhere, but all what you drew will be erased before `Draw` event). See Draw Event in the documentation.

So, you need separate it like this:

**obj\_Vida**, Left Mouse Button Pressed event:

```
obj_Control.vida+=10;

```

**obj\_Fome**, Left Mouse Button Pressed event:

```
obj_Control.fome+=10;

```

**obj\_Energia**, Left Mouse Button Pressed event:

```
obj_Control.energia+=10;

```

**obj\_control**, Draw event:

```
draw_healthbar(120,100,240,120,vida,c_black,c_red,c_green,0,true,true);
draw_healthbar(120,150,240,170,fome,c_black,c_red,c_green,0,true,true);
draw_healthbar(120,200,240,220,energia,c_black,c_red,c_green,0,true,true);

```

---
Tags: game-maker, events
---


# Question
Title: Where is the best way to store game stats?
I am building a small Android game with Unity. Everything is going OK, but I have some things bothering me, that I see no real solution.

**The problem**

In my game, you build your character as you like, and you can equip him with loot that you acquire as you play the Story Mode. I am currently storing the attributes for each equipment on a database, and the game makes calls to `WebServices` to get these attributes.

However, this becomes a problem if the user has no internet connection, and wants to play the game. I would like the game to be playable in this case, but I can't think of a good solution.

I could store the data for the current equipment in the device, but what if the user changes the equipment? Any help is widely appreciated.

# Answer
Alright, since you're looking for ways to make a loot system (and to store it) for a game, there are a few major systems that you could use.

## Procedural Loot Generation

In this method, you generate loot in action. You don't keep your loot stats tied down to your loot, but instead, you make an archetype of loot and apply prefixes and suffixes or unique names if you wish.

Let's take a leather helm for example. It could just be a leather helm and it would give a random low range armor amount since it's usually called a light armor. After deciding that, you generate the item and give it to the player, then save the player's current items. This way, you don't need to keep a database of items but instead just generate them on the fly. Each suffix or prefix will need an identifying number so that you can apply updates to existing items, and items will need to draw their stats using these IDs. If you don't do it this way, then you'll need to store the stats of every item separately.

You could for example give it a prefix of "Muffled" which would give a bonus to stealth, or a better prefix of "Silent" which would give a higher stealth bonus. Both of those would be random values, depending on the quality of the prefix. This has the potential of not making any sense (Muffled Leather Helm? Wha?...), but you could restrict the attributes to loot types to make more sense.

## Predefined Loots

So you want more control over your game? You want the iron sword to act exactly as you want it to, because there are reasons for wanting that. Then you could just make each and every item and put them in the game and give each of them an identifying number and when the player gets an item, they only need to have the identifying number of that item.

This way, you only ever need one of said item to exist within the code and then just use that item for everything that needs that item.

These won't need much space on the device unless you plan on having a few million items or a few million suffixes and prefixes.

## Storage

If you're concerned about the size of said game then you could just use the "Split Application Binary" option and separate game's textures etc. from the main application.

If you absolutely want to have them off on a server, then I suggest holding an encrypted copy of the loot table on the server and then downloading that loot table to local storage and then decrypting and using it at runtime. You can then check the loot that the player has gathered during their offline play and compare that to the list you have on the server and just change it as necessary.
> 1 votes

# Answer
Just my thoughts

This depends on the scenario how your game is played/used.

Scenario 1: the web backup

This means your game is always played on android and the character remains to this one device. If the player plays the game on a second (android) device or via unity web player he gets a new character with new stats. In this case you can keep your data local and backup your data to the server in case the phone is lost or reset or game is uninstalled,.... The only case you want to load the data from the server is when the user requests the backup. In this case the player would not need a internet connection when playing (only on restore) and if an internet connection is present the data would be back uped automatically in the background. Of course here may the problem arises that the player never had an internet connection and therefore no backup on the server.

Scenario 2: the sync store

When your game is played on multiple devices with multiple clients (may not simultaneosly). This means the player plays on android while away but switches to web player or standalone game when at home on PC. In this case you have to keep them in sync all the time necessarily. Otherwise dataloss and difficult to solve syncing cases will occure. Here a constant internet connection is required.
> 1 votes

---
Tags: unity, android, databases
---


# Question
Title: How to make a static Material reference?
I have a class `Edge` which may change to multiple colors - materials in this case. I need to switch a `Material` on `MeshRenderer`.

In order to do this, I'd need to make multiple prefabs public variables like

```
class Edge : Mono{

    public Material red, blue, green;

    public void SwitchColor(SomeColorEnum param){
        switch(param)
           // change
           // this.renderer.mat = something;
    }

}

```

This is a bad solution for this, cause I'd need at least 3 material references in each `Edge` object. Is there any way to make a material static, assign it from a prefab and then access it statically?

# Answer
> 2 votes
Quite often I'll use a `ScriptableObject` to hold this kind of shared data.

It's similar to OC\_RaizW's suggestion of a `MonoBehaviour`, but doesn't require a `GameObject` to host this content - a `ScriptableObject` can exist as its own asset:

```
// This attribute makes the asset show up in the editor's Assets -> Create menu
// and when right-clicking in your Project window and choosing Create
[CreateAssetMenu(filename = "New Material Library", menuName = "Custom/Material Library")]
public class MaterialLibrary:ScriptableObject {

    // You could also expose individual named fields, or provide a public method
    // to retrieve a material based on an enum key or other input...
    public Material[] materials;

}

```

Now all your edges can share a reference to this `MaterialLibrary`.

I often use this for collecting up pools of foley sounds that many characters use, or for sharing configuration parameters used by multiple player/enemy instances. This gives me a single place to make changes to tune all instances currently running or that have yet to be spawned. This is a form of the flyweight pattern.

Another trick I like to use for materials in particular is to prepare a general-purpose material variant cache:

```
public static class MaterialCache {

    struct Variant {
        public Material originalMaterial;
        public Color32  color;
    }

    static Dictionary<Variant, Material> _cache;

    public static Material GetMaterialVariant(Material originalMaterial, Color32 color) {
        var key = new Variant{originalMaterial = originalMaterial, color = color};

        Material output;
        if(_cache.TryGetValue(key, out output) == false)
        {
            output = Instantiate<Material>(originalMaterial);
            output.color = color;
            _cache.Add(key, output);
        }
        return output;
    }

    // You may also want to provide a Flush method to destroy cached materials,
    // in case your game ever enters a state where you don't need them anymore.
}

```

Now anything that wants to modify its display colour can do so like so...

```
public class ColorChanger : MonoBehaviour {
    Material _originalMaterial;
    Renderer _renderer;

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

    public void ChangeColor(Color32 color) {
        var mat = MaterialCache.GetMaterialVariant(_originalMaterial, color);
        _renderer.sharedMaterial = mat;
    }
}

```

If I'm using only a handful of easily-standardized colours like `Color.Red`, then every instance with the same base material asking for a red variant will get a reference to the same red material instance, rather than creating copies all over the place. And best of all, I don't have to manually create and assign all those near-duplicate materials - they're just created on demand. :)

# Answer
> 1 votes
Unfortunately Unity can't serialize static members in inspector.

Though, as a workaround, you can use a singleton class that derives from `Monobehaviour`, as an asset reference database. So you can assign references to this singleton instance, instead of class directly.

That being said, having a couple of excess members in all instances won't effect anything in a noticeable manner. Especially when you need to use workarounds.

Before optimizing your program, always, always, always profile beforehand. Optimization without profiling is called "Premature Optimization", and is one of the most discouraged acts in programming.

# Answer
> 0 votes
1. If you only want to change some properties, do it via Runtime in code.

Material mat; mat.GetComponent().color = Color.red;

Then you will get a new fresh instance of one material.

2. If you have different Materials with different Shaders though, you have to change the materials.

For this just make a "BaseClass" Mono Behaviour with public Materials.

```
public class BaseMaterials : MonoBehaviour
{
public Material redMat;
public Material greenMat;
public Material blueMat;
}

```

and in your Edge class:

class Edge : Mono{

```
public BaseMaterials baseMats;

public void SwitchColor(SomeColorEnum param){
    switch(param)
       // change
       this.renderer.mat = baseMats.redMat;
}

```

Now you only need to assign the "baseMats" reference.

There are now multiple solutions to this.

Do it in Start() with GetComponent() or drag and Drop it in the Inspector or do it via Dependency Injection and Interfaces

The biggest advantage here is : There is only 1 reference instead of 3

---
Tags: unity, optimization, materials
---


# Question
Title: What should I consider when evaluating libraries, engines and frameworks for making a game?
I'm going to make a game. I've noticed that there are a lot of game engines, libraries, and frameworks available out there, and I'm having a little trouble deciding which one to use.

I'm already pretty good with some programming languages, but there are others which I don't know at all. I'm not against learning new programming languages, if that'll help, but my real goal is just to make my game.

**What criteria should I use to compare engines, libraries, and frameworks against each other, so that I can decide which one will allow me to be the most productive to finish my game?**

# Answer
It's sort of like picking a car or a computer. Or pretty much anything that has assorted features, some of which you care about very much, others you don't mind and some you might even not want included.

1. Make a list of the features you're interested in. i.e. 2D/3D support, lighting, physics, uses a language you know well, etc.
2. Rank them based on importance to you, based on your current project.
3. Research your options and for each option, attempt to rank their support features based on how well they align with your project goals.
4. Use the one that best matches with your goals. Alternatively you can select the top few and give them a test drive. Implement some simple feature of your game and see which one you like more.

I think a lot of this boils down to actually knowing what you want. Which means you'll need to have a pretty good idea of the game you're making. Which probably means you're going to need a fairly detailed plan of how to implement your game, and what it's going to include. As a bonus, having all that detailed information will actually help you complete your game. It's far easier to follow a plan and check things off a list than to just have an idea for a game and just start writing code.
> 14 votes

# Answer
First you should have at minimum a rough idea of what your game will be and what it will need. There are the usual questions like whether or not your game will need physics. Then there are the interrelated questions, which are mostly about the environment your game will be developed and run on and how commercial your game is or isn't.

* What platforms will you support? What platform are you developing your game on?
* What programming language(s) do you intend to implement your game in?
    + This is influenced by the platforms you intend to support.
* What kind of graphics, audio, and input will your game have?
* Is your game freeware or open source, or is it commercial?
    + If open source, will you want to go commercial later, either with your game or with another game that uses your first game's engine?

If you're going to be Windows-only then DirectX and C#-based libraries are strong candidates. If you want to be multiplatform then you'd want to look at libraries based on OpenGL and C/C++, or Flash if your game is 2D and you can afford Adobe's tools. Like your platform, your programming language will influence your available libraries. A program written in C++ will have a hard time calling a Java library.

If your game is commercial then you can consider buying an engine like Unity. If your game is freeware or open source you will want to focus on libaries that are also open source, or at least free for non-commercial projects. Open source libraries are useful to commercial projects too of course. When looking at open source libraries make sure to check their license. Some licences require you to make parts of your own software open source depending on how you use a library. Restricting yourself to open source libraries will obviously place another limit on what libraries you can use.

When looking at a library, make sure to check how active its development and community is. I'd trust a library that is well-known and actively maintained more than one that is hosted on someone's university web page that hasn't been updated since 1999.

One final question, especially if this isn't your first game project, is whether or not there aspects your game will need that you *know* you'll struggle with if you try to do it yourself. Because these aspects in particular are candidates for finding a library. If your game needs collision detection and you know you can't implement collision detection yourself (like I can't), consider picking up a physics engine and leverage the collision detection features in it.
> 3 votes

# Answer
* Does the library do what you need?
* Is it specialized to do what you need? How much clutter is attached to it?
* How is it designed? Do you want to vomit when you see it? If yes, then it's probably not the best choice for both your health and sanity.
* Is it flexible enough for your needs? It's not good noticing that the library doesn't work after you already have written half of your code with it.
* How future proof is the library? Is the developer adding features over time? Is he fixing things? Is he improving things? This can make quite a difference if it will be likely that your game's development is taking a few years. Not so important for small projects you'll have out in a month.
* Is the size appropriate? For small projects it can make a big difference whether the player has to download 20MB or 200MB. Bigger projects are probably big enough that the size of the middleware makes little difference.
> 1 votes

# Answer
In addition to the game-specific features that people have commented on, you should also consider some general questions.

1. support structure - even if game engine is perfect, perhaps support is too expensive, or non existent.
2. how easy is it to learn - you may not want something too big, as time to learn may be prohibitive.
3. does it cover your future plans - you may not want to invest time learning a perfect-for-now engine, only to relearn a brand new engine from scratch for next project. Or maybe you do want that.
4. license - if you're making a closed source game, make sure engine's license doesn't make it opensource.
> 1 votes

# Answer
Go here.

Despite the *number* of game engines out there, you actually *don't* have that many choices.

1. license restrictions. Some engines will hamper your ability to release your product without first paying large licensing fees, e.g. Unity, used to charge an additional fee to compile to iOS, for example (this changed in 2016)
2. platforms. Do you care about targeting multiple platforms? Which ones?
3. 2D or 3D? Some engines cater to 2D.
4. Requires physics? Some engines provide physics
5. FPS, RTS? It may be wise to use an engine that is specialized for the game type you're creating.
6. Obviously you'd like to work in your favorite language. Don't like C? Then don't use Allegro!
7. Are you a huge design patterns, OOP fan? Well known OGRE "overuses" patterns
8. Active development? You should consider the tradeoff between availability of bleeding edge features (DX11 / OGL 4) vs the stability of an engine's whose development tapered off a couple of years ago
9. User base? A large user base usually means better forums, so easier to answer your questions
> 0 votes

# Answer
**A short cheat sheet for evaluating libraries, frameworks, engines and SDKs and picking the best**

* Libraries, frameworks, engines SDKs and so on are tools which are intended to solve problems for you or assist you to solve problems and meet certain requirements.
* Evaluating means figuring out which one meets the most requirements.

Therefore before you even start evaluating you need to be clear in which scenario you are and which requirements you have/want to have because this are the questions which should be answered by the evaluation.

The scenario defines where the requirements come from (who decides what is an requirement and what isn't).

---

Typical scenarios are:

**The hobbiest project scenario**

You on your own or together with some friends want to create your (maybe first) game. Perfect, you can decide everything on your own and you are only limited to basic technical desicions and technical requirements (should it be a mobile game, a PC game, a console game, a web game,....). You can decide whatever you want.

Implicit requirements will be that you may want to learn something specific (a language, a specific framework/engine)

**The student scenario**

Requirements may come from your teacher. Typical requirements I had in that case: the game needs to have some physics elements and multiplayer network support. Or it has to be written in C++. So evaluating becomes easy. You are looking for a game engine which lets you code in c++ and may already include a network and physics engine.

A more evil (real life) requirement: everything has to be written from scratch (but using libraries is allowed). So no editor is allowed (e.g. Unity3D). So you are not looking for engines/sdks but for libraries.

**The indie game scenario**

You want to make money with the game later on. Therefor you will need to sell it somehow which brings you to check which requiremnts come from the store you want to sell your game on.

Does it allow Java games, HTML5 games,....)

Does it require you to include specific libraries (if yes, in which languages are those libraries available)

The Google Playstore will require you to write your game as Android game, Apple AppStore will require you to write your game as iOS app. Or you have the requirement to pick a multiplatform engine.

**The professional scenario**

You do not only have a store providing requirements but most likely a publisher or customer having own immaginations of requirements. In this scenario you will also have a bigger team of employed developers. Depending on their skill set new requirements arise (our programmers can only write c++ so we can not use a pure Java/Android game engine without them needing (lot of) time to learn something new).

I do not go into detail for this scenario, once you managed to build up a team of employes and find a customer/publisher you already know what you are looking for on evaluating things.

---

**How do I decide what my requiremts are when I am a hobbiest or indi and no one else tells me?**

Ask your self questions about your goals and your game?

* What should my game be? mobile, pc, web (html/Js), which controllers will I use (touch screen, gyroscope, game pad)
* What is new in my game and what does other games also have. Those parts other games also have (rendering, audio, input handling) will be done by the most (game engines) tools you can find or it is easy to bundle up libraries having that functionality in your own game or game engine.
* What is the dimension of my project: angry birds or skyrim? Angry Birds can be done in nearly every tool and skyrim would be limited to high performance tools with (assumed) years of additional customization (high performance terrain engines aren't easy)
* Is my only goal just to get a game done? yes? perfect, you can use some highly advanced thing like Unity, Unreal,... having a handy editor and a large community providing you with tutorials and answering your questions. It takes away the burden of handling low level tasks like mesh loading, implementing your own math functions,....
* Is my goal to learn something specific? yes? what do you want to learn?
* Which language should I choose? If the goal is still just to get your game done pick the one you/your team knows best? If you want to learn a specific language you will pick a tool in that language.
* Will tool X have enough performance for my game? Maybe, you will never know. Even in large productions the optimization and polishing phase takes a long time and is a huge affort to get it done. Start caring about performance when you hit performance issues. You do not know how the tool will perform unless to reached its limits. Everything on the web site of the tools developer is just a rough guess. After years of evaluating tools I stoped beliving anything from the developers website.

---

Answering such questions brings you to the requirements. The evaluation is finding a list of tools and TESTING (not just reading the homepage) what the tool can provide or can't.

---

Requirements are not cut into stone but are dynamic. They will come and go during development. If the game needs physics or not for example depends on the design. If the design changes the requirement can change too.

Take the requirements you have and get started. Changing requirements are the daily bread of the suffering, ahm, happy developers independent of project size and experience level.
> 0 votes

---
Tags: software-engineering
---


# Question
Title: color individual triangles on a mesh in Unity?
I am trying to use Unity to display a model and color some triangles on the model to high light those parts of the model.

I have created a scene, with a camera, a light source and a cube. After the scene loads I have a script on the cube where I am importing a new mesh and replacing the cube mesh with the new mesh. I am also giving each triangle a random color.

```
    void Update () {
    if (Time.time > 10 && newShapeLoaded)
    {
        System.Collections.Generic.List<facet> newModel = readStl(@"C:\testing1\stls\sphere.stl");
        System.Collections.Generic.List<Vector3> vertices = new System.Collections.Generic.List<Vector3>();
        foreach (facet f in newModel)
        {
            vertices.Add(f.vecA);
            vertices.Add(f.vecB);
            vertices.Add(f.vecC);
        }
        Mesh mesh = GetComponent<MeshFilter>().mesh;
        mesh.vertices = vertices.ToArray();
        int[] t = new int[vertices.Count];
        Color32[] colors = new Color32[vertices.Count];
        Color32 currentColor = new Color32();
        for (int i = 0; i < vertices.Count; i++)
        {
            t[i] = i;
            colors[i] = currentColor;
            if (i % 3 == 0)
            {
                currentColor = new Color(
                                    Random.Range(0.0f, 1.0f),
                                    Random.Range(0.0f, 1.0f),
                                    Random.Range(0.0f, 1.0f),
                                    1.0f);
            }
            colors[i] = currentColor;
        }
        mesh.triangles = t;
        mesh.colors32 = colors;
        mesh.RecalculateBounds();
        mesh.RecalculateNormals();
        mesh.UploadMeshData(true);
        newShapeLoaded = false;
    }
}/* Update() */

```

This was not working and searching I found I needed to change the material type to a material that uses vertex color shading. I found the Particles\>VertexLit Blended Shader colors the triangle but then the triangles are drawn in the wrong order so the shape appears inside out.

Is their anyone that knows more about Unity and 3D that could give me some advice or let me know where I have gone wrong with this?

(edit) So I have investigated this further and I believe the comment made about the particle material being the reason for the shape appears inside out is correct.  I also noticed that the original cube has this problems before I change the mesh as well. So I have tried to find a material with a shader that will still let me color the triangles but not break the render order of the triangles. Unfortunatly I haven't been able to get anything to work. I have found a thread here where several people have tried to create a shader to do this and I have downloaded their projects and run them and tried to get them to work with very limited success. This lead me to also find several tutorials on shader programming to try and understand what was happening, but these have not given me any better understanding of how to get vertex coloring working.

I am now wondering if I have gone off track because all I really want to do is to make a simple model and change the color of some triangles on the model. I though this would be like a simple hello world exercise for 3D graphics, but I have put over a week into this now and tried several different approaches and still have not been able to get this working.

I would be very grateful if someone could show me an example of changing colors of triangles on a mesh? Or if someone that understands 3D graphics could just point me in the right direction to a tutorial or guide that will help me learn what I need to know to get this working and let me know if this is the correct way to try and be able to change colors on a mesh?

# Answer
> 1 votes
As mentioned in the comments above, the "inside out" or incorrect ordering effect comes from using a particle shader - these are written for layering transparent content so they don't write to the depth buffer the way we'd want an opaque shader to do.

So,we just need to make our own opaque shader that uses vertex colours. I'd been hoping to keep the answer concise by showing just a lit or unlit version depending on what the asker wanted, but since they never replied back on that point, here's one of each...

**Unlit:**

```
Shader "Unlit/VertexColored"
{
    Properties
    {
    }
    SubShader
    {
        Tags { "RenderType"="Opaque" }
        LOD 100

        Pass
        {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag

            #include "UnityCG.cginc"

            struct appdata
            {
                float4 vertex : POSITION;
                // Read vertex color from mesh.
                fixed4 color : COLOR0;
            };

            struct v2f
            {
                // Pass interpolated vertex color to fragment.
                fixed4 color : COLOR0;
                float4 vertex : SV_POSITION;
            };

            v2f vert (appdata v)
            {
                v2f o;
                o.vertex = UnityObjectToClipPos(v.vertex);
                o.color = v.color; // Pass the color through.
                return o;
            }

            fixed4 frag (v2f i) : SV_Target
            {
                // Output the color straight.
                return i.color;
            }
            ENDCG
        }
    }
}

```

**Using Unity's standard lighting model:**

```
Shader "Custom/VertexColoredStandard" {
    Properties {
        _Glossiness ("Smoothness", Range(0,1)) = 0.5
        _Metallic ("Metallic", Range(0,1)) = 0.0
    }
    SubShader {
        Tags { "RenderType"="Opaque" }
        LOD 200

        CGPROGRAM
        // Physically based Standard lighting model, and enable shadows on all light types
        #pragma surface surf Standard fullforwardshadows

        // Use shader model 3.0 target, to get nicer looking lighting
        #pragma target 3.0

        struct Input {
            // Ask Unity to pass the vertex color through.
            float4 color : COLOR0;
        };

        half _Glossiness;
        half _Metallic;

        void surf (Input IN, inout SurfaceOutputStandard o) {
            // Use the vertex color as albedo.
            fixed4 c = IN.color;
            o.Albedo = c.rgb;
            o.Metallic = _Metallic;
            o.Smoothness = _Glossiness;
            o.Alpha = c.a;
        }
        ENDCG
    }
    FallBack "Diffuse"
}

```

# Answer
> -1 votes
By inside out, do you mean the face normals are reversed? If so, try to manually calculate the normals. The code below should be pretty easy to follow.

```
//mesh.RecalculateNormals();
mesh.normals = RecalculateNormals(vertices, triangles);

    public static Vector3[] RecalculateNormals(Vector3[] vertices, int[] triangles) {

        var normals = new Vector3[vertices.Length];

        for (var i = 0; i < triangles.Length; i += 3) {
            int i1 = triangles[i];
            int i2 = triangles[i + 1];
            int i3 = triangles[i + 2];

            //Calculate the normal of the triangle
            Vector3 p1 = vertices[i2] - vertices[i1];
            Vector3 p2 = vertices[i3] - vertices[i1];
            Vector3 normal = Vector3.Cross(p1, p2).normalized;

            normals[i1] += normal;
            normals[i2] += normal;
            normals[i3] += normal;

        }

        for(int i = 0; i < normals.Length; i++){
            normals[i] = normals[i].normalized;
        }

        return normals;
    }

```

If this still produces backwards normals, then just invert the final assignment to the normals array; `normals[i] = -normals[i].normalized;`

If that isn't the issue, then I can only assume it has something to do with how you are reading from the .stl file, or with the shader. If not, it would go a long way to see a picture of your issue.

---
Tags: unity, depth-buffer, vertex-shader
---


# Question
Title: Root Animation unusual position and non root animation snaps back
Im trying to do a stop animation . when i release the W key then from Run it will do this animation then goto IDLE . But somehow this is not working right. as you see in those videos below. So how do i achieve this ?

Im using animation from mixamo.

After Root Motion http://i.imgur.com/JwY98P2.gifv

Before Root Motion https://fat.gfycat.com/ReflectingMealyCrane.mp4

# Answer
> 2 votes
Mixamo has root bone as hip bones. So i needed to add a Root bone as parent of all bones using blender. This video shows it . https://www.youtube.com/watch?v=a79tRO7M0I .

Some other videos also fixes this issue but they were too complicated, as im not an animator i just tried this one and it worked so far so good.

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