# Question
Title: Why does Unity use reflection to get the update method?
Why does Unity use reflection in order to access `MonoBehaviour` message methods like `Awake`, `Update`, `Start`,...?

Wouldn't it be slow to use reflection? Why doesn't it leverage other approaches like `Template Method`? It could simply define the methods as abstract in `MonoBehaviour` base class and force the subclasses to implement it.

# Answer
# It doesn't

> ### How Update is called
>
> **No, Unity doesn’t use System.Reflection to find a magic method every time it needs to call one.**
>
> Instead, the first time a MonoBehaviour of a given type is accessed the underlying script is inspected through scripting runtime (either Mono or IL2CPP) whether it has any magic methods defined and this information is cached. If a MonoBehaviour has a specific method it is added to a proper list, for example if a script has Update method defined it is added to a list of scripts which need to be updated every frame.
>
> During the game Unity just iterates through these lists and executes methods from it — that simple. Also, this is why it doesn’t matter if your Update method is public or private.

As for the *reasons* it is done this way, I'll largely refer you (the reader) to DMGregory's answer, which boils down to a balance of two competing things:

1. Performance optimization
2. Ease of new developer utilization

A new developer just wants it to Work and doesn't want to have to figure out "how do I connect this in to the event system?" but it should still run fast with minimal overhead.

The solution is probably the *best that can be achieved* within these two constraints. Or at least, the best the Unity dev team was able to come up with at the time. We may never know.
> 24 votes

# Answer
> It could simply define the methods as abstract in MonoBehaviour base class and force the subclasses to implement it.

One of the advantages of the system Unity uses is that you *don't* have to implement every MonoBehaviour message, of which there are over 60.

Usually we just need one or a small handful of these methods. Since some are specific to 2D/3D physics, some unique to cameras or particle systems, it's highly unlikely that any one script would ever need all of them.

By leaving the messages we don't need as unimplemented, we can clearly signal to the runtime "don't even bother calling OnCollisionStay2D on this object — I don't need it"

This can be a substantial efficiency win. Now the engine can filter down a short-list to call Update on only the ~20 objects in my scene that need custom update logic every frame, and not all ~200 objects that make up all the scenery or only respond to physics events.
> 11 votes

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


# Question
Title: maya script editor: how to keep python code after execute
see my gif, in script editor, I hope keep python code after code is executed and run it again next time, how should i do?

# Answer
I find the best way is script editor \> file \> save script, i save script to test.py, script editor will create "test.py" tab, run code in this tab will not clear code after code is executed
> 2 votes

# Answer
Myself I always select the code, then run it.

Selected text in the Script Editor will not be removed on execution. https://i.stack.imgur.com/kjc6j.jpg
> 0 votes

---
Tags: python, maya
---


# Question
Title: Bump and push entities without a physics engine
I have seen on many games the ability to push entities around and bump into enemies/characters. What is this called?

I have implemented Matterjs to accomplish this with Pixijs but it seems overkill when I just need the ability to bump and push. I'm not really interested in an accurate physics model, just collision enough to allow the character to interact with the environment.

I can't seem to find out what this is called. My idea is to have all entities defined by a circle collision boundary, and move away from the character based on primitive collision detection and a tangent force calculation to displace.

# Answer
I ended up finding a solution to my somewhat nebulous question and it ended up being quite simple: I set the air friction to an arbitrarily high value (to dampen movement) and the gravity to 0 (to simulate a top-down perspective). The entities can now bump each other around properly. This was easily and accurately done with the MatterJS library by setting the airFriction and gravity.y properties.
> 0 votes

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


title: What to use if you want a looping list?

text:
# Question
Title: What to use if you want a looping list?
No, I'm not talking about foreach. I have the following list:

```
public List<float> angles = new List<float>(new float[] { 0, 90, 180, 270 });

```

This list can vary depending on the object I use, having only 0 and 90 or all except 270 for example.

What I want to do is have a rotClockwise and rotCounterClockwise function that grabs the value before or after a given value. Here's some pseudo code:

```
function float rotClockwise(angle) {
    return angles.grabNextAngle(angle);
}

function float rotCounterClockwise(angle) {
    return angles.grabPrevAngle(angle);
}

```

So calling rotClockwise(90) would return 180, rotCounterClockwise(90) would return 0, rotClockwise(270) would return 0, etc.

How can I accomplish this? Is there a list type that allows me to loop back to the beginning when I reached the end?

# Answer
AFAIK there is no class in the C# standard which works like a circular list. However, it is quite easy to build such a class yourself:

```
public class RotatingFloatList {

    private int current = 0;
    private float[] values = new float[] { 0, 90, 180, 270 };

    public float GetCurrent() {
        return values[current];
    }

    public float GetNext() {
        current++;
        if (current >= values.Length) current = 0;
        return GetCurrent();
    }

    public float GetPrevious() {
        current--;
        if (current < 0) current = values.Length - 1;
        return GetCurrent();
    }
}

```

Try it online!

Exercises for the reader to make this class more reusable:

* Have it take the values from a constructor.
* Turn this into a generic class so it can be used for other things than `float`s.
> 1 votes

# Answer
Add extra values so it seems to wrap and use IndexOf in the correct range to avoid overflow.

```
public List<float> angles =new List<float>(new float[] { 0, 90, 180, 270, 0 });

float nextAngle(angle){
    return angles[angles.indexOf(angles, 0) + 1]; //looks from the start and
    //will never pick the last element because it's a duplicate of an earlier one
}

float previousAngle(angle){
    return angles[angles.indexOf(angles, 1) - 1]; // looks from index 1 and will never pick 0
}

```

However using floats like that isn't ideal because if you ever get a rounding error then indexOf will return -1.

Using an enum `NORTH`, `EAST`, `SOUTH`, `WEST` for this is a better idea with a conversion to the actual angle or orientation when needed.
> 1 votes

# Answer
A circular buffer is simple to implement, you can do it as Philipp suggest or you may - for example - use `index % array.Length` to query (unless the index is negative).

*Remember that accesing a negative index of the array is an `IndexOutOfRangeException`.*

However, what you want is something slighly different, since you want to find the previous and next items given a value.

Assuming we start with a sorted array, we can do this with `Array.BinarySearch`. We will not use `IndexOf` for reasons that will become clear later.

First, our array:

```
var array = new float[] { 0, 90, 180, 270 };

```

And what we are going to be looking for:

```
var query = 10;

```

I will add `rotClockwise` and `rotCounterClockwise` to store the adjacent values...

```
float rotClockwise;
float rotCounterClockwise;

```

Then, we execute the `Array.BinarySearch`...

```
float rotClockwise;
float rotCounterClockwise;
var searchResult = Array.BinarySearch(array, query);

```

Ah, but it would return negative if it is not found, we need to check that...

```
float rotClockwise;
float rotCounterClockwise;
var searchResult = Array.BinarySearch(array, query);
if (searchResult < 0)
{
    // ...
}
else
{
    // ...
}

```

If the result is positive, it is easy, just add or substract 1 to searchResult:

```
float rotClockwise;
float rotCounterClockwise;
var searchResult = Array.BinarySearch(array, query);
if (searchResult < 0)
{
    // ...
}
else
{
    rotClockwise = array[(searchResult + 1) % array.Length];
    rotCounterClockwise = array[searchResult == 0 ? array.Length - 1 : searchResult - 1];
}

```

Now, when it is negative...

*Remember that accesing a negative index of the array is an `IndexOutOfRangeException`.*

`Array.BinarySearch` is actually telling us where we would, in theory, insert the new value... (This is why we do not use `IndexOf`) we have to start by getting the bitwise complement of the result:

```
float rotClockwise;
float rotCounterClockwise;
var searchResult = Array.BinarySearch(array, query);
if (searchResult < 0)
{
    searchResult = ~searchResult;
    // ...
}
else
{
    rotClockwise = array[(searchResult + 1) % array.Length];
    rotCounterClockwise = array[searchResult == 0 ? array.Length - 1 : searchResult - 1];
}

```

Now, since that is the index where it would be inserted, it is also the index of the first item that is larger than the query... unless the query is larger than all, in which case we want to get the first item. In either case `index % array.Length` will do.

Ah, and for the last item larger than the query, we just substract 1.

```
float rotClockwise;
float rotCounterClockwise;
var searchResult = Array.BinarySearch(array, query);
if (searchResult < 0)
{
    searchResult = ~searchResult;
    rotClockwise = array[searchResult % array.Length];
    rotCounterClockwise = array[searchResult == 0 ? array.Length - 1 : searchResult - 1];
}
else
{
    rotClockwise = array[(searchResult + 1) % array.Length];
    rotCounterClockwise = array[searchResult == 0 ? array.Length - 1 : searchResult - 1];
}

```

And there you go. Well, almost, the code is not aware that these are angles...

You can transform the input like this (not optimized):

```
if (query < 0)
{
    query += (1 -(int)(query / 360)) * 360;
}
if (query >= 360)
{
    query -= (int)(query / 360) * 360;
}

```

... and optimize, error check, encapsulate as needed.

---

I have adapted the code like this:

```
public static void Main()
{
    var array = new float[] { 0, 90, 180, 270 };
    var queries = new float[] {-1000, -15, 0, 1, 10, 90, 95, 300, 270, 780};
    foreach (var item in queries)
    {
        var query = item;
        if (query < 0)
        {
            query += (1 -(int)(query / 360)) * 360;
        }
        if (query >= 360)
        {
            query -= (int)(query / 360) * 360;
        }
        var tuple = Rot(array, query);
        Console.WriteLine(item + " = " + query + " Clockwise: " + tuple.Item1 + " CounterClockwise: " + tuple.Item2);
    }
}

public static Tuple<float, float> Rot(float[] array, float query)
{
    float rotClockwise;
    float rotCounterClockwise;
    int searchResult = Array.BinarySearch<float>(array, query);;
    if (searchResult < 0)
    {
        searchResult = ~searchResult;
        rotClockwise = array[searchResult % array.Length];
        rotCounterClockwise = array[searchResult == 0 ? array.Length - 1 : searchResult - 1];
    }
    else
    {
        rotClockwise = array[(searchResult + 1) % array.Length];
        rotCounterClockwise = array[searchResult == 0 ? array.Length - 1 : searchResult - 1];
    }
    return new Tuple<float, float>(rotClockwise, rotCounterClockwise);
}

```

Output:

```
-1000 = 80 Clockwise: 90 CounterClockwise: 0
-15 = 345 Clockwise: 0 CounterClockwise: 270
0 = 0 Clockwise: 90 CounterClockwise: 270
1 = 1 Clockwise: 90 CounterClockwise: 0
10 = 10 Clockwise: 90 CounterClockwise: 0
90 = 90 Clockwise: 180 CounterClockwise: 0
95 = 95 Clockwise: 180 CounterClockwise: 90
270 = 270 Clockwise: 0 CounterClockwise: 180
300 = 300 Clockwise: 0 CounterClockwise: 270
360 = 0 Clockwise: 90 CounterClockwise: 270
365 = 5 Clockwise: 90 CounterClockwise: 0
780 = 60 Clockwise: 90 CounterClockwise: 0

```

Try it online!

Addendum:

Of course, this code can be made generic. You may not want to deal with float. You may also be interested in supporting an `IComparer<T>` interface, there you can check with your prefered method of comparing floating point numbers.
> 0 votes

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


# Question
Title: Instantly snap into specific directions?
In my 2d setup, I want the player to constantly move in a specific direction at a set speed. It's similar to "Snake" in that you can only move in four directions and you can't stop your movement.

Right now, the way I do this is by having a char variable "direction", which can either be u, d, l, r (take a guess what those stand for). Based on those letters, I use GetComponent().MovePosition and increase/decrease the position on the x or y axis.

Is there a better way to do this? I would prefer if I could just enter the degree (0, 90, 180, 270) to make the player move in the right direction. I tried AddForce but I couldn't get it to work.

Side note: it's important for me that I can set the direction without player input, as there are some objects that force the player into a different direction.

Edit: As the tag would suggest, I'm looking for a Unity specific answer, as I'm not sure which function would best suit my needs.

# Answer
> 0 votes
Here's a solution I found thanks to help from @cmprogram.

Rotating the object:

```
rb.eulerAngles = new Vector3(0, 0, angle);

```

Making the object move in the new direction inside FixedUpdate:

```
rb.velocity = rb.right * speed * Time.fixedDeltaTime;

```

Very simple.

---
Tags: unity
---


# Question
Title: Unity - How to get UI text to follow an object?
I'm a relative beginner trying to learn Unity, and I'm trying to do something that I thought would be relatively simple: Have a piece of text hover over an object, following it if it moves around the screen. I understand that a UI element can't be directly attached to an object because it has to exist on a canvas, so I tried writing a simple script that would move the UI text depending on where the object is on the screen.

Here's the code:

```
using UnityEngine;
using System.Collections;

public class NameFollow : MonoBehaviour {

    public GameObject robot;
    public Camera camera;
    private Transform thisTransform;
    private Vector3 roboPos;

    // Use this for initialization
    void Start () {
        roboPos = robot.transform.position;
        thisTransform = this.transform;
    }

    // Update is called once per frame
    void Update () {
        Vector3 roboScreenPos = camera.WorldToScreenPoint(roboPos);
        Vector2 local = new Vector2();
        RectTransformUtility.ScreenPointToLocalPointInRectangle(this.GetComponent<RectTransform>(), roboScreenPos, camera, out local);
        this.GetComponent<RectTransform>().anchoredPosition = local;
        //thisTransform.position.Set(roboScreenPos.x, roboScreenPos.y + 1f, roboScreenPos.z);
    }
}

```

However, the text just seems to jump from its original location to what seems to be the anchor point on the canvas and back every frame, so it just flickers between the two locations. It doesn't seem to respond to the target's movement at all.

Can someone point out what mistake I'm making in my code? I'm not familiar enough with Unity UI scripting to figure it out, but conceptually that makes sense to me.

**UPDATE**

I managed to kind of get there

```
void Update () {
    Vector3 roboScreenPos = camera.WorldToScreenPoint(robot.transform.TransformPoint(roboPos));
    Vector2 local = new Vector2();
    RectTransformUtility.ScreenPointToLocalPointInRectangle(this.GetComponent<RectTransform>(), roboScreenPos, camera, out local);
Debug.Log("Robopos " + roboScreenPos);
//Debug.Log(this.GetComponent<RectTransform>().anchoredPosition);
    this.GetComponent<RectTransform>().anchoredPosition = local;
    //thisTransform.position.Set(roboScreenPos.x, roboScreenPos.y + 1f, roboScreenPos.z);
}

```

It seems the jumping between two positions thing is being caused by `RectTransformUtility.ScreenPointToLocalPointInRectangle`, since `roboScreenPos` shows a consistent value as long as nothing moves, and changes reasonably when it does move.

Am I using that function the right way?

**UPDATE 2**

I was pointed to a not very intuitive solution, but it mostly works:

```
rt = GetComponent<RectTransform>();
canvasRT = GetComponentInParent<Canvas>().GetComponent<RectTransform>();
roboScreenPos = camera.WorldToViewportPoint(robot.transform.TransformPoint(roboPos));
rt.anchorMax = roboScreenPos;
rt.anchorMin = roboScreenPos;

```

I guess the idea is that if you only give the UI element one place to put itself, it has to put itself in that place. Maybe. Apparently I don't quite understand the way anchoredposition, anchorMax, and anchorMin work.

However it works, the UI text does now follow the character around as intended. The one issue I have now is that if the target object starts at any position that isn't the origin, then the UI text permanently offsets its position by that distance from the target, essentially placing it twice the distance away from the origin in the same direction. I does still move along with the target, but always with that offset.

Here's the current code:

```
public class NameFollow : MonoBehaviour
{

    public Vector3 pos;

    public GameObject robot;
    public Camera camera;
    private Vector3 roboPos;
    private RectTransform rt;
    private RectTransform canvasRT;
    private Vector3 roboScreenPos;

    // Use this for initialization
    void Start()
    {
        roboPos = robot.transform.position;

        rt = GetComponent<RectTransform>();
        canvasRT = GetComponentInParent<Canvas>().GetComponent<RectTransform>();
        roboScreenPos = camera.WorldToViewportPoint(robot.transform.TransformPoint(roboPos));
        rt.anchoredPosition = roboScreenPos + new Vector3(0,45,0);
        //rt.anchorMax = roboScreenPos;
        //rt.anchorMin = roboScreenPos;
    }

    // Update is called once per frame
    void Update()
    {
        roboScreenPos = camera.WorldToViewportPoint(robot.transform.TransformPoint(roboPos));
        rt.anchorMax = roboScreenPos;
        rt.anchorMin = roboScreenPos;
    }
}

```

As you can see, I tried setting the position of the element in Start, but that doesn't help. It's not a major issue since it can be easily worked around, but I want to understand what's going on.

# Answer
Based on your description, you might have better luck using a Text Mesh, which will be treated more in line with the other Components that the rest of Unity uses (rather than delving into the `Canvas` system).

You could create GameObjects with Text Mesh components, and make them children of the enemies, with the y-component of the transform offest so they'd be above them.

You could then attach a simple script to your child GameObject that has something along the lines of:

```
void Update() {
    this.transform.LookAt(player.transform);
}

```

... in order to make sure your Text Mesh is always oriented towards your player. While this is different than what your above code, it may be cleaner & easier to understand going forward.

My $0.02 would be that the canvas is more geared towards more static applications & is great at rescaling for aspect ratios, but is less apt for what you're trying to do.
> 3 votes

# Answer
Upgrading my comment to an answer.

You need to add the canvas to the object and set its render mode to "WorldSpace".

Read more here:

https://docs.unity3d.com/560/Documentation/Manual/HOWTO-UIWorldSpace.html
> 1 votes

# Answer
I agree with lase. Text Mesh is probably what you would want for your solution. If you do need to use a canvas specific item then I have a simple function that will get you where you need to be. You simply pass your target object, canvas, and camera to the function and it will return a position you can use on your text object in the canvas.

Here is that function (C#)

```
        //Get the screen position of a physical object in world space (i.e. The Robot)
public static Vector3 GetScreenPosition(Transform transform,Canvas canvas,Camera cam)
{
    Vector3 pos;
    float width = canvas.GetComponent<RectTransform> ().sizeDelta.x;
    float height = canvas.GetComponent<RectTransform > ().sizeDelta.y;
    float x = Camera.main.WorldToScreenPoint (transform.position).x / Screen.width;
    float y = Camera.main.WorldToScreenPoint (transform.position).y / Screen.height;
    pos = new Vector3 (width * x - width / 2, y * height - height / 2);
    return pos;
}

```

Here is how to use it...

```
   text.transform.position = GetScreenPosition(object.transform, canvas, mainCamera);

```

or if you use RectTransform just modify the left side of the statement to match to position.
> 0 votes

# Answer
I use a Text mesh and this script for player names in my game.

```
 public class BlendFollower : MonoBehaviour
        {
            public Transform leader;
            public float followSharpness = 1f;
            private Vector3 OffSetVector;

            void LateUpdate()
            {
                OffSetVector = new Vector3(leader.position.x, leader.position.y, leader.position.z);
                transform.position += (OffSetVector - transform.position) * followSharpness;
            }
        }

```
> 0 votes

# Answer
Use a TextMesh, as said in the answers above.

And a Parent Constraint Component on the TextMesh, that's 'connected' to the object you desire to mimic the movement of. Offsets are available, and can be animated, within the Parent Constraint Component, too.

It's also got individualised control over which axis and rotations are parented. Making it a quite powerful and useful component.
> 0 votes

---
Tags: unity, ui-design
---


# Question
Title: How to make my model's top section rotate without rotating the entire model?
I'm trying to learn a bit of Maya modeling so that I can be self sufficient when it comes to creating super basic assets for my game development. I'm trying to understand skeletal rigging and how it modifies the model geometry itself.

I've got the most basic model - a cube with proportions that make it into a 3D rectangle. I've rigged it with a very simplistic skeleton. My goal is to learn how all of this works, and create a character that has motion similar to maybe the magic carpet from Aladdin - it's a rectangle but the edges somewhat move like it has arms and legs.

When I rotate some joints, it distorts the entire model. I added a bit more geometry thinking that it'd allow the top section of my model to rotate a bit more without having to deform the entire model, but it still just seems to do the same thing.

How can I make the top section of my model be capable of moving forward and backward in such a way that it does not cause the entire model to move forward?

Here are some screenshots to help explain and show my situation ...

This is my model and skeleton (I told you it was super basic, lol) ...

And here is what happens when I rotate around the neck joint ...

And here is sort of what I was hoping to achieve ...

# Answer
> 1 votes
Remove the weights from "J\_Neck" from all components but the ones you want effected by it.

You can either open the "Windows \> General Editors \> Component Editor" and remove unwanted weights or use the "Skin \> Paint Skin Weights" to paint the desired weights.

Your very simple model might however be too simple. For deformation you really need geometry to support it.

---
Tags: animation, 3d-meshes, maya
---


# Question
Title: How can I reduce the amount of GLSL code written?
I am writing a game engine for Linux. It has a sufficiently large number of effects that can be turned on / off. Effects are defined before compiling with `#ifdef`. But the problem is that I literally have to “wrap” each variable in `#ifdef`. Another problem is that when adding new effects, I have to rewrite the conditions, since one variable can refer to several effects at once. For example:

```
#if defined ALGINE_LIGHTING_MODE_ENABLED || defined ALGINE_SHADOW_MAPPING_MODE_ENABLED
uniform vec3 viewPos;                       // Camera position
#endif

#ifdef ALGINE_DOF_MODE_ENABLED
uniform float focalDepth;
uniform float focalRange;
#endif

```

How could I reduce the amount of re-write needed when adding new effects?

# Answer
If you are using macros for defining the variables, then there is really no way around it. You could, however, do something like this:

```
// constants.h
#if defined ALGINE_LIGHTING_MODE_ENABLED || defined
ALGINE_SHADOW_MAPPING_MODE_ENABLED
uniform vec3 viewPos;                       // Camera position
#endif

#ifdef ALGINE_DOF_MODE_ENABLED
uniform float focalDepth;
uniform float focalRange;
#endif

```

And then include this file in your shader code:

```
// vertex-shader.glsl
#include "constants.h"
// [...]

```
> 2 votes

---
Tags: opengl, glsl
---


# Question
Title: How to implement ECS architecture in C#?
As C# is a strongly-typed language, I'm having great difficulties associating all my data types together so that I can have a clean, if not performant, game loop.

**Example #1: Keeping Components Together**

Keeping components together means I need an interface or base class to store them in an array, which would require keeping track of each type separately so that it can be converted back to the derived type before being consumed. The constant type conversion seems like a bad idea in an ECS?

To compound the problem, I would prefer to use structs instead of classes for my components, which when cast to an interface will cause boxing. In some simple stop watch tests I've run it seems the casting/boxing is 16x slower than just looping over the raw type. (Pseudo code below)

```
IComponent sprite = new SpriteComponentStruct() // boxing

for(int i=0; i<iComponents.Length; i++)
{
    var type = GetComponentTypeByIndex(i);
    var system = GetSystemWithType(type);
    SpriteComponent sprite = Convert.ChangeType(...);
    system.Execute(sprite);
}

```

**Example #2: Keeping Components Separate**

To keep components separately in their own classes/managers/systems I would likely need a generic class to cut down on the code duplication. The problem I run into here is that looping over each class will require a base class or interface, which at the very least would force me to cast the component types again. (Pseudo code below)

```
ComponentManager<T>() where T : struct
{
    T[] components;

    // can't use with non-generic interface to put manager into a list
    public void AddComponent(T component) {...}

    // won't compile; type "T" will not cast to type "T"
    public void AddComponent<T>(T Component) {...}

    // requires casting and/or boxing, which defeats
    // the purpose of keeping components separate
    public void AddComponent(object component) {...}

}

```

It seems every which way I try to implement a ECS in C# ends with hacky/non-performant code, that's assuming I can get it to compile in the first place. From studying other ECS systems around the net, it seems some side-step these issues by using void/int pointers or storing component bytes directly in memory (like I believe the new ECS in Unity 2018 does). Either way those are unsafe operations in what's supposed to be a managed memory language.

So is C# the wrong tool for the job? Am I approaching this incorrectly? I'd love to hear some opinions as this just seem impossible...

# Answer
So a solution to this, as I've just successfully implemented, is to keep and "consume" all data types separately, thus avoiding casting/boxing operations. Every component type has it's own unique array and type-specific methods (a generic helps here, but the generic really needs to be accessed separately and not part of a bigger collection). The key to keeping everything separate seems to be using indexes to link it all back together. I've included example code below.

\*Note that using "structs" as I mentioned in my question has an additional requirement of using the REF keyword (a lot), or finding a way to re-assign any updated components.

```
class Game
{
    // entities store indexes of type and component together
    Entity[] entities;

    // type index for identifying components
    Dictionary<Type,int> componentTypes;

    PositionComponent[] positionComponents;
    SpriteComponent[] spriteComponents;
    HealthComponent[] healthComponents;

    PlayerSystem playerSystem;

    void UpdateLoop()
    {

        // for each entity...

        this.playerSystem.Execute(
            GetPositionComponent(entity),
            GetSpriteComponent(entity),
            GetHealthComponent(entity));

    }

    PositionComponent GetPositionComponent(Entity entity)
    {
        int typeIndex = this.componentTypes(typeof(PositionComponent);
        int componentIndex = entity.GetComponentIndex(typeIndex);
        return this.positionComponents[componentIndex]
    }

    ...
}
class entity
{
   int[] componentTypes;
   int[] componentData;
}

```
> 3 votes

# Answer
If you haven’t already checked it out, Artemis is an excellent ECS framework. Originally written in Java, there is a C# port available here:

https://thelinuxlich.github.io/artemis\_CSharp/

I’ve successfully implemented it in a couple of SharpDX projects, most recently with a threaded message bus infrastructure. The GitHub repo is here:

https://github.com/thelinuxlich/artemis\_CSharp
> 0 votes

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


# Question
Title: Do old games still generate revenue for their developer companies?
For the purpose of this question, let's say an "old" game is one released over 20 years ago, or for which the platform it runs on has become unavailable.

Do the developers still earn revenue off of titles this old?

If the answer is no, why aren't more of these titles made available for free (officially)?

# Answer
Yes, they do. You never know if an IP you considered worthless might become valuable again.

For example, 10 years ago nobody thought Sega and Nintendo would ever make another cent from their 8 bit and 16 bit games. But then came the pixel art retro boom. Sega released a bunch of their Mega Drive catalog on Steam and Nintendo created the Virtual Console to re-release their old classics on their new systems. I don't think any of these old games really sell that many copies, but it's nevertheless revenue on investments which were already written off ages ago.

There are also specialized stores like Good Old Games which try to re-monetize older PC titles (although they recently re-specialized and also sell new releases).

But often releasing an old classic can be more trouble than it's worth. Possible barriers are:

* Unresolved copyright questions. Game companies get formed, sold, merged, split, renamed, closed, liquidated, bought etc. all the time. Often multiple companies work together and share the copyright to a game. Sometimes you have things like music tracks, brands or technology which are licensed from 3rd parties and the contracts do not explicitly allow a re-release. Trademarks might have expired and other game companies might have registered similar trademarks in the meantime. The resulting chaos can often lead to a situation where nobody is really sure who has the necessary rights to re-release an old game. If the game would have a large economic value, it might be worth it to pay some lawyers for a few dozen hours to find out, but often just that alone might be more than the economic value of the game. A good example was the drama surrounding No One Lives Forever. tl;dr: multiple game companies said "*Maybe* we have the rights to the game according to some contract buried in some file cabinet, but we don't care enough to find out. But if you try to release it, we *will* find out and if we do we will sue you!"
* Waiting for the right moment. They want to see if the IP might become more valuable. Maybe the company got some plans in the shelf to revive an old review in form of an HD re-release? Maybe they are waiting for the retro gaming boom of that particular era of gaming history? If they release it now, they might lose out on larger profits in the future.
* It might cannibalize your actual market. People don't need to buy any of your *new* games while they are busy playing all your *old* games. While you might not really lose a large number of sales that way, you might lose at least *a few* sales if the timing is bad.
* The PR effect for your company might actually be negative. One could argue that releasing your old games for free could be a great advertisement for your new games. But keep in mind that the perception of old games through nostalgia goggles is often far better than it is when you actually play those games. So the halo-effect* your old game has on the perception of your new game might in fact be negative. This is a risk which is hard to estimate, but it is there and might cause management to hesitate.
* There is no reason to do it. Even if you release an old game for free in an "as is" state, you need to write a press release, add a download page to your website, pay for server capacity for the download, might have legal liabilities, might have to offer support, etc.. All of these are peanuts compared to the costs associated with a "real" release, but the benefit minus cost calculation of $0 minus peanuts is still negative.

*has nothing to do with the game Halo
> 7 votes

# Answer
At least some do although perhaps not in the way you are thinking. Old, but still new enough to be digitally distributed games could still bring in the occasional revenue. But games with physical aspects (cartridges) are eventually no longer manufactured and eventually their first-party sales revenue will dry up.

However, it may still be possible to make money on the licensing of the IP or sale of related property, and a company may account that as revenue from from products.

As for why “old” games aren’t always released for free, well, it tends tends to come down to the fact that the owner wants to maybe make money re-releasing the game in the future or that making it available for free would actually cost them (in manufacturing, hosting or support for example) and thus not be an attractive business proposition.
> 2 votes

---
Tags: business, revenue
---


# Question
Title: Goal oriented Action Planning with multiple Agents
I'm a little bit stuck:

I implemented an AI with GOAP (Goal oriented Action Planning, http://alumni.media.mit.edu/~jorkin/gdc2006\_orkin\_jeff\_fear.pdf) for a simulation game. That works fine.

*Now I want that the agents can cooperate (e.g. doing actions together). What is in this case the best AI-Design that the GoapActions keep loose couplet?*

Should they plan together? (what is in this case the "worldstate"?)Or Should they share their plans? some kind of message-system?

**Example**
Agent1: Worldstate Agent 1: isLonely= true
Goal Agent1: isLonely = false

Plan Agent1: AskAgent2ToTalk -\> TalkToAgent2

Agent2 Worldstate Agent 2: hasWood = false
Goal hasWood = true

Plan Agent2: GetAxe -\> ChopWood -\> BringWoodToSupply

*How I get this constellation?*

Agent1 Plan: TalkToAgent2
Agent2 Plan: TalkToAgent1 -\> GetAxe -\> ChopWood -\> BringWoodToSupply

Or if they are talking and one of the agents is interrupted (e.g. by an attacking enemy) the other agent must know that his TalktoAgent2 Action has ended.

# Answer
I highly recommend you do not use aciton planning. It's very difficult to extend, design, and bugfix. We abandoned task planning very early on in DwarfCorp because it's too complex to quickly design new behaviors around. But if you must, you have to interpret this as a multi-agent planning problem.

One way to achieve this is through **Heirarchical Planning**. You need to create a *meta-agent* for assigning subproblems to your lower level agents. The meta agent, or "Task Planner" tries to achieve an overall goal, and uses the sub-agents under its control as meta-actions.

For example, your meta-agent might have a goal "Build a house". It has the action "gather wood" which takes as input an agent and a location to gather the wood at. It can then assign different agents to different subtasks. Maybe one agent goes and gathers the wood while the other uses the gathered wood to build the house.

It may have other goals, like "reduce loneliness". Those goals need to be ordered by priority so that they can subsume each other. The central task planner decides at any given time what the most important goals are, and assigns agents to them using different subgoals. It looks for idle agents, figures out what the best subtask is to assign to the agent, and then puts them on the case.
> 1 votes

# Answer
I think goap is new version of state machines that tries to setup states to achieve a goal. you just have to define which scenarios are happening in every state.

for example you have some AI enemies that have patrol, chase, search and attack states.you can simply write a code that when one of enemies found player, all off change state to attack or chase state. other example you have scenario that in attack state, one or 2 of enemies have to flank player and other have to support them. so every enemy checks if there is an enemy flanking or some other condition(you can just define a bool variable for that). if there isn't, go flank else go support. all depends on scenarios and rules you define.
> 0 votes

# Answer
I don't know if you try to achieve a coupling loose between agents, since that was what I interpreted, anyhow, that would be the best approach, you should check for the Observer Pattern, which is an event subscription system that avoids dependencies. You could use it like this way (I'll try to be language agnostic):

```
public interface ILonelyObserver
{
    void ItsLonely();
}

public class Agent implements ILonelyObserver
{
    private static List<ILonelyObserver> observers;
    private bool busy;

    public static void IAmLonely()
    {
        for(int i = 0; i < observers.Count; i++)
        {
            observers.ItsLonely();
        }
    }

    public static void Subscribe()
    {
        if(observers == null) observers = new List<IObserver>();
        observers.Add(this);
    }

    public static void Unsubscribe()
    {
        if(observers != null) observers.Remove(this);
    }

    public void ItsLonely()
    {
        /// Do what it takes to make company...
    }

    public Agent()
    {
        Subscribe();
    }

    ~Agent()
    {
        Unsubscribe();
    }
}

```

So it would be up to you to make the logic to subscribe/unsubscribe when the agent is busy and cannot make company.

If you were to use C#, you should check Event Delegates, which already implements the aforementioned pattern.

Hope it gives you an idea at least.
> 0 votes

# Answer
You would have to A: use step and assess and B: you have to have **multiple** goals with priorities.

If Agent1 wants X and Agent2 never wants X, **they can't work together**. That can't happen *in any system*. To fix this, you will need to have multiple goals tracked. You can even *prioritize goals based on how far one has progressed towards them and how easily other goals can be accomplished*. In your scenario with out priorities, this becomes:

> Agent1: Worldstate Agent 1: isLonely= true Goal: isLonely = false
>
> Plan Agent1: AskAgent2ToTalk -\> TalkToAgent2
>
> Agent2 Worldstate Agent 2: hasWood = false, isLonely= true
>
> Goal: hasWood = true
>
> Goal: isLonely = false
>
> Plan Agent2: GetAxe -\> ChopWood -\> BringWoodToSupply, AskAgent1ToTalk -\> TalkToAgent1

Agent1 then would continually ask Agent2 to talk until it got an affirmative, which would happen after it completed its first task.

Taking steps towards each goal will have to be evaluated, and while with only one goal this isn't a big deal, more goals could potentially slow down your game.

To solve this issue you need *trees generated from accomplishing tasks* which may hide checking multiple goals at a time, speeding up processing of decisions.
> 0 votes

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


# Question
Title: Is it possible to make desktop visible behind drawn object using SDL2?
I would like to draw an avatar over the desktop, something similar to those word 97 assistants, my idea so far is to make only the background transparent but I haven't had any luck, any suggestion? is it possible to make with SDL2?

# Answer
* You could try `SDL_SetWindowShape` which is implemented but is not officially documented, probably because it does not work well on all supported platforms. It may work for major platforms though (Windows, macOS, X11/Mir/DirectFB)
* Try this Windows-only approach: https://stackoverflow.com/q/4052940/2038264 The caveat is that graphics performance will be very slow since it involves coping GPU data to RAM every frame
> 1 votes

# Answer
Not with SDL directly. These sorts of things are generally accomplished by getting the DC of the desktop window and drawing to it using GDI. I'm not sure how well that technique works with the window composition manager of modern Windows.

You could also look at using `SetWindowRgn` to define a non-rectangular window. This imposes some pretty strict limits on the overall outline of your little avatar though.
> 0 votes

---
Tags: c++, sdl, sdl2, c
---


# Question
Title: How to use Moving Average to avoid lucky streaks in RNG
I spent the last week reading about Luck Mitigation and what a dev can do to avoid extreme cases where the player's psychology will be messed up.

I came up to this question How do I avoid “too” lucky / unlucky streaks in random number generation?, plus some others outside GameDev site. To illustrate my question, let's have this simple game example.

We have a turned base fighting game, like BiteFight. Two characters have their attributes and the match outcome is based entirely to those attributes.

In specific:

**Player 1:** Str: 10 Def: 15 Agl: 20

**Player 2:** Str: 12 Def: 20 Agl: 15

The process is simple:

```
If rnd() * P1_Agl >= rnd() * P2_Agl:
    P1 will attack
else:
    P1 will attack

```

Then with the same way in case of Player 1 is attacking

```
If rnd() * P1_Str >= rnd()* P2_Def:
    reduce life points from P2

```

Repeat the same unlimited times until one of players' life reach zero.

**Solutions I found:**

1. Instead of 1 `rnd()` call, use x-times `rnd()` and get the average. Something like `( rnd() + rnd() + rnd() ) / 3`. This will move the results closer to 0.5 and make the whole process less "random". However, it is still possible enough to have streaks of lucky or unlucky events.
2. Keep track of the results and if you have x-times the same result then hard-code the other. For example, if on the above, P1 won the Agility test 3 times in the row, then the 4th time will always go to P2. What I didn't like on this are the predictability. Users might understand that behavior through time. But the most important is what would happen if P1 uses an item that changes his attributes on the 4th step? When you hard-code the outcome, the result would be based on different attributes.
3. I read many times the suggestion to use a Moving Average or a Cumulative Moving Average on the `rnd()` to guess if their is a streak of lucky results. For example, if Player 1 keeps getting `rnd()` above 0.9, it is a lucky streak. I wrote a script to calculate those two and here is an example for CMA and MA

**Cumulative Moving Average**

```
0 : Random number:  0.348  CMA:  0.348
1 : Random number:  0.74  CMA:  0.544
2 : Random number:  0.967  CMA:  0.685
3 : Random number:  0.578  CMA:  0.659
4 : Random number:  0.932  CMA:  0.713
5 : Random number:  0.134  CMA:  0.617
6 : Random number:  0.397  CMA:  0.585
7 : Random number:  0.537  CMA:  0.579
8 : Random number:  0.861  CMA:  0.611
9 : Random number:  0.893  CMA:  0.639

```

**Moving Average**

```
0 : Random number:  0.295 Moving Average:  0.098
1 : Random number:  0.866 Moving Average:  0.354
2 : Random number:  0.768 Moving Average:  0.492
3 : Random number:  0.888 Moving Average:  0.624
4 : Random number:  0.94 Moving Average:  0.729
5 : Random number:  0.325 Moving Average:  0.595
6 : Random number:  0.823 Moving Average:  0.671
7 : Random number:  0.208 Moving Average:  0.517
8 : Random number:  0.743 Moving Average:  0.592
9 : Random number:  0.038 Moving Average:  0.407

```

So, I end up to my 2 questions

1) Even if I read many times the suggestion of Moving Average, no-one mentioned how exactly you use it. So, my guess is that each time, you compare the `rnd()` with the moving average and based on that you take some actions. But what exactly you can do?

2) In the above example, you can see that we have two comparisons. One for Agility and one for Strength. Should one use two different Moving Averages to "identify" lucky streaks for each case, or it should be one for every case that RNG comes to the game?

# Answer
> 1 votes
Can't you just do something like: lets say Crit chance is 25% \[round 1\]. If there's a crit then he/she can't crit again for at least 4 rounds \[till round 5 no crit\] (because of 25%) & will crit 100% after 4 rounds \[so in round 9 there will be a crit if there was no crit between round 5 to 8\].

Or you can do it even simpler. I've thought for some projects if I have crit chance of 25% I will crit every 4 rounds/hits. I like that idea because I'm able to add nice combos. So the player will think: I will use my best damage skill in round 4 so that it will crit, also the enemy could know after some rounds what is the % crit and react to that with a evade skill or just a block skill, something like that.

I like your idea. I like Bite Fight but there is something missing (lost much potential). I would like to be one of your testers when your ready/finished.

# Answer
> 1 votes
Moving average just means you take an average of the last N rolls. To use it for breaking lucky streaks, you compare the moving average against the ideal random chance, and adjust your next roll to move the average towards the ideal.

For example, let's look at adjusting **coin flips over a period of 4**. Suppose we've had the following coin flips:

```
0 1 2 3 4 5 6
H T H T T T T

```

In the last 4 flips we had 4 Tails. This can happen 1-in-16 times but let's suppose we want to avoid this kind of streak. We force the next flip to be a Head.

```
0 1 2 3 4 5 6 7
H T H T T T T H

```

Now the last 4 flips has 1 Head and 3 Tails.

Avoiding streaks is especially useful for rare events like critical hits and rare loot drops. Consider if you have a rare item that drops only 1% of the time. What's the chance that someone misses that item after 300 tries? `0.99^300` or 5%, which is quite likely, similar to the chance of getting 4-tails in a row. But for the poor player grinding 300 times, that would seem very unfair.

Moving average also works for non-binary outcomes. Suppose you have a weapon that deals **"12-17 damage per hit"**, but you want the **moving average to be 14-15 over a period of 4 hits**. Maybe in this game, enemies usually take 5 or more hits to kill and you want the number of hits to be predictable. Start with the following hits:

```
 0  1  2
12 14 13

```

What would the next roll need to be so that the moving average is 14-15? `4*14-(12+14+13)` to `4*15-(12+14+13)`, or `17` to `21`. Since we can't roll any higher than 17 without breaking our own game rules, we force the next roll to be 17.

```
 0  1  2  3
12 14 13 17

```

Now the average is 14. But what about the next roll? It would need to fall between `4*14-(14+13+17)` to `4*15-(14+13+17)`, or `12` to `16`.

```
 0  1  2  3  4
12 14 13 17 16

```

Similarly, the next roll needs to be between `12` (raised from 10) and `14`, since we rolled a few high numbers last time.

```
 0  1  2  3  4  5
12 14 13 17 16 14

```

And so on and on.

# Answer
> 0 votes
Got curious so I ran some numbers by hand. If you restrain your randomness to \[0, 1\] as you had done then you could do soemthign along the lines of calculating your moving average and multiply your next roll by 1.5 - MovingAverage and it will move it back towards the center.

---
Tags: mathematics, game-design, random
---


# Question
Title: Should I call SDL_ConvertSurface right before SDL_CreateTextureFromSurface?
Is there a significant benefit (or any benefit at all), when I convert SDL surface and create a texture from optimized surface?

Here is example of what I mean:

```
loadedSurface = IMG_Load(path);
optimSurface = SDL_ConvertSurface(loadedSurface, SURFACE_FORMAT, 0);
loadedTexture = SDL_CreateTextureFromSurface(renderer, optimSurface);
//return loadedTexture and destroy the rest

/*  VS  */

loadedSurface = IMG_Load(path);
loadedTexture = SDL_CreateTextureFromSurface(renderer, loadedSurface);
//return loadedTexture and destroy the rest

```

According to SDL2 documentation

> This function is used to optimize images for faster repeat blitting. This is accomplished by converting the original and storing the result as a new surface. The new, optimized surface can then be used as the source for future blits, making them faster.

Its tied with surface blitting, but I can't say its effect "within" texture.

Thank you

# Answer
> 4 votes
Check the source for SDL\_CreateTextureFromSurface. It calls SDL\_ConvertSurface already. So using SDL\_ConvertSurface is entirely redundant.

I took a quick peek at what `SDL_ConvertSurface` does in the SDL source code (GitHub mirror here), and it seems to just change surface internals, if even that.

The only way I could imagine that had an effect would be to save on the conversion/data transmit that is performed when the texture data is sent onto the GPU, but I highly doubt that actually makes a difference here. So I would not call `SDL_ConvertSurface`.

In general, with SDL2, you can discard most of the surface manipulation, since the focus is in the hardware accelerated renderer.

---
Tags: c++, sdl, sdl2
---


# Question
Title: Game mechanics for a persistent real-time strategic/tactical game
I am designing a game based around a fairly realistic simulation of 'Age of sail'-like trading and combat, and I am currently trying to decide whether to make the game a limited on-line application, in which the game world exists only while all the players - 2 to 8 of them - are *all* online, or a persistent real-time mmo application, in which game events occur on a set schedule. As a game for a small number of players, uninteresting events could be time-accelerated away.

The trouble with a real-time MMO is that the world objects would be persistent, yet the players would be transient. Since in-game encounters and combat would take place on a schedule determined by the actions of all the players, not just those that happen to be online, players could easily miss an encounter or battle in which their vessel happened to be involved - or at least *could* be involved.

An idea I had for the MMO version was that otherwise idle time could be spent in training - which would be simulated, not merely administrative, and that active crew positions such as gunners, helmsmen, marines and officers could be filled by players, so one ship might have many players online in engagements, each contributing to the success - or otherwise - of the battle. These positions would be filled by players whose vessels were all engaged in uninteresting travel or laid up for repairs, using a matchmaking system to match the players' observed skill to that of the NPC into whose shoes they would be stepping. NPC skill progression would be based upon the actual skill improvement of the players who step into the role.

What other game mechanics could allow a game such as this to be playable as a persistent real-time mmo, especially when vessels could spend a long time in transit, doing nothing much of interest?

# Answer
> 1 votes
The experience players would be looking for when they hear "Age of sail simulator" would be lots of naval battles, plundering and trading.

But a "fairly realistic simulation of the age of sails" in real-time with real-world scale and with every player playing a sailor would likely not be a very enjoyable game. The reality was that sailors usually spent weeks on open sea during eventless voyages, wondering if scurvy or boredom will kill them first. So if you don't want to create a "sitting on deck and staring at waves simulator" with a pathetically low awesome per second frequency, then it is important that you avoid players being stuck in long travel times. This will require some breaks with realism. Possible options would be:

* Fast-travel. Just skip the long voyages and teleport the ships right to their destination. The result will be plenty of non-stop action, but also a very chaotic strategy meta-game. The players go to bed and when they wake up the world control map looks completely different. Whether you want a slowly changing strategic world map (like in Eve Online, for example) or a quickly changing strategic world map (like in Planetside 2, for example) is a matter of preference.
* Realistic travel speed, but make the game world unrealistically compact, so that voyages which would take weeks in reality now only take minutes. This also makes encounters between player ships during travel a lot more frequent. This might have the same effect as the previous solution: Lots of action and very quickly changing strategic situations which allow little long-term planning.
* As you suggested, *ships* move in real-time, but *players* don't. Players are allowed to "teleport" to where the action is. Managing ship movement on a separate world map could then be a meta-game which plays out in real-time. Action events happen when a ship arrives at its destination. This also neatly solves the problem that most players will want to be captains of their own customized ship \[please tell me you have plenty of customization options. It's Halloween. How much do I need to pay to get a spiderweb pattern on my skysail and a pumpkin as a crow's nest?\] and nobody will want to be "just" a sailor on the ship of someone else. Players are captain in the events which involve their own ship, but those only happen rarely. While they wait for those to happen, they can play crew in events involving ships of other players. This travel mechanic should also allow players to schedules events in a way that they happen when they and their friends have time to play.

The biggest game design challenge I see here is to balance travel times, encounter durations and crew sizes in a way that players will always be able to find events to join but are still able to attract enough crew members during their own events. The easy solution would be to simply auto-generate events involving only NPC ships when nothing is going on, but this would also be the least interesting solution.

Me and my crew are looking forward to sending some scurvy dogs to the bottom of the ocean in your game.

---
Tags: game-design, game-mechanics, mmo, realtime
---


# Question
Title: How to change a background from a list of images on button click?
I'm trying to create a button within the settings menu that allows you to change the image of a GameObject per click. So, let's say there are only 2 different images available to choose from and it starts with Image1, if you press the button it changes to Image2 and if you press again it goes back to Image1, like a loop. My issue is on how to write the script for this.

# Answer
> 1 votes
In order to do this, you will need a script which has:

* A reference to the game object which is controlled by the button
* A list of possible sprites to cycle through
* A counter which keeps track of which sprite in the cycle you are currently displaying
* A method `NextSprite()` which is supposed to handle button click events. This method should increases the counter by one, set it back to 0 when it reached the end of the image list and then switche out the image according to the current value of the counter.

Such a script could look like this:

```
using UnityEngine;

public class SpritePicker : MonoBehaviour {

    public GameObject controlledObject;
    public Sprite[] sprites;
    private int counter;

    public void NextSprite() {
        counter++;
        if (counter >= sprites.Length) counter = 0;
        SpriteRendere spriteRenderer = controlledObject.GetComponent<SpriteRenderer>();
        spriteRenderer.sprite = sprites[counter];
    }

}

```

Now you just need to put that script on an appropriate game object and assign a few things in the inspector:

* Assign the game object you want to control to the "Controlled Object" slot of the Texture Picker
* Assign the sprite assets you want to cycle through to the Sprites array of the Texture Picker
* Create a new entry in the "On Click ()" event list of your button, assign the object with the texture picker to the entry and pick the "TexturePicker.NextImage" method for that entry.

---
Tags: unity, 2d, ui-design
---


title: How to inflate geometry?

text:
# Question
Title: How to inflate geometry?
I have a shape containing vertices and triangles

I want to inflate that geometry using some `radius` to get something like that

I should move each point along vector `center-vertex`. I suppose each point should be moved using quadratic function (closer to center, further it will be moved)

How should I calculate the offset of each point?

# Answer
> 2 votes
To inflate the shape:

1. For all edges, find how well aligned it is with the neighbour edge, using the dot product between their normalized directions.
2. Determine the lowest and highest values.
3. For the edge with highest dot value (smallest angle between edges), push out the vertex between them, away from center, with a certain percentage.
4. For the edge with the lowest (negative in your example) dotproduct value, push in the vertex between them, towards the center, with the same percentage.

To visualize it in your example shape:

The left most vertex has most acute angle, and will be pushed in.

The second most left vertex has the shallowest angle, and will be pushed out.

Then rinse and repeat, to slowly converge. Note that this has some basis in real world physics too: the surface tension in a fold is very low, and will be the part of the inflatable to move.

---
Tags: geometry, vertex
---


title: Cannot open include file: 'linmath.h'

text:
# Question
Title: Cannot open include file: 'linmath.h'
I have set up GLFW and GLAD in Visual Studio 2017 as follows:
I created in C: directory folder GLFW-GLAD, and put in there, "glfw" (Windows pre-compiled binaries, 32-bit Windows binaries) as well "glad". Also in V.S. I created Empty Project "Project-0" and Source file "Main.cpp".
1. In project GLFW-GLAD's "Properties", Configuration: \[All Configurations\], Platform: \[Active(Win32)\], Configuration Properties:
1.1. C/C++ \> General \> "Additional Include Directories" window \> "C:\GLFW-GLAD\glfw\include" and "C:\GLFW-GLAD\glad\include".
1.2. Linker \> General \> "Additional Library Directories" window \> "C:\GLFW-GLAD\glfw\lib-vc2015"
1.3. Linker \> Input \> "Additional Dependencies" window \> "opengl32.lib; glfw3.lib; glfw3dll.lib".
1.4. Linker \> System \> Subsystem \> Console (/SUBSYSTEM:CONSOLE)
2. In project folder "Project-0" I have pasted files: "glad.c" and "glfw3.dll".
I copied program from https://www.glfw.org/docs/latest/quick.html and pasted in Main.cpp code area. I attempted run it but failed. Output is
"fatal error C1083: Cannot open include file: 'linmath.h': No such file or directory"
Please help.

# Answer
> "fatal error C1083: Cannot open include file: 'linmath.h': No such file or directory"

This error means what it says: the specified file (`linmath.h`) was not found. Step number one is diagnosing this error is to *find the file* yourself on your filesystem and prove it actually exists. I suspect it doesn't, in your case, due to something I note below.

But if you *can* find the file, the next step is to compare the include search paths for the source file being compiled and make sure that one of them would result in the compiler being able to find the file by the name you specified in the `#include` directive.

`linmath.h` is inside the `deps` directory in the source tree for GLFW. If you examine the directory structure of a package Windows distribution of GLFW, you won't find `linmath.h` at all.

If you want to use that source code example unmodified, you have to download a copy of the `linmath.h` header and put it either next to your `Main.cpp` source file or inside one of the include paths you configured.
> 3 votes

---
Tags: glfw
---


title: Should I use Panels or Frames?

text:
# Question
Title: Should I use Panels or Frames?
Hi I am creating my first game in NetBeans using Java, the game is going to be an RPG that will look a bit look Undertale on the surface in that there will be a menu, then a load game section and then will go onto a world where you can walk around.

I've used a JFrame and then a JPanel on top of that to contain the initial menu screen. Should I use another JPanel over the menu screen when I press load game or new game to go to those screens, or should I make a new JFrame altogether?

If you think like how Minecraft has a load game button which sends you to a screen that shows you all the games you can load up, would that be a new JPanel or a new JFrame?

# Answer
In order to answer this question, let's first examine what's the difference between JFrame and JPanel.

When you switch between different UI contexts, which one do you want to replace?

You likely want to keep the window but just change its content. So you should switch out the JPanel, not the JFrame of your application.
> 4 votes

---
Tags: java, swing, jframe
---


# Question
Title: "The Object you want to Instantiate is null" But it works, can I ignore the error?
This has never happened to me so I'm a bit confused.

```
GameObject someObject = Instantiate (Resources.Load ("Prefabs/Items/" + someName)) as GameObject;

```

This throws an error but the object is actually instantiated and everything works as intended. The error doesn't stop the program no matter how many times I reproduce this.

Can I ignore this error or is there some problem that I'm not seeing?

# Answer
If the object is instantiated correctly despite the `Intantiate()` line throwing an exception, then the error is coming from another instance of the script — you might accidentally have a second copy in your scene.

One instance is configured correctly, and performing the `Instantiate()` as expected with no errors, so the object is created as desired.

Another instance is configured incorrectly, and throws an error. But if you're just looking at the correctly-configured instance, this error will seem to come from nowhere and have no visible consequence.

You can print out the path to the object on Start - or in a null check just before the offending line - to help track down unwanted scene duplicates.

You absolutely should not ignore this error.

At best, it's burning compute cycles unnecessarily. At worst, it's a sign that your game is doing something you don't fully understand, and that can be the root of much bigger problems down the line.
> 45 votes

# Answer
# Answer

Let me start off by answering your question directly:

> it works, can I ignore the error?

You *could*. You *should* not, because it means something is going wrong. You would get used to this error, but it could "hide" or cause another error.

Currently you have an error message and it still works correctly. The other way around, it *not* working and not having (or rather: not recognising) feedback why, is far worse!

# Advice

To find out where this comes from, split this whole thing up into several lines.

```
string resourceLocation = "Prefabs/Items/" + someName;
Object prefab = Resources.Load(resourceLocation);
Object instance = Instantiate(prefab);
GameObject someObject = instance as GameObject;

```

An error only tells you at which line it happened. If the error happens in this code, the line number will tell you more about which part went wrong here. Also, I'd advise using the generic version of `Resources.Load`, that would actually give us one step less to worry about:

```
string resourceLocation = "Prefabs/Items/" + someName;
GameObject prefab = Resources.Load<GameObject>(resourceLocation);
GameObject someObject = Instantiate(prefab);

```

# Finding out why

* Now, a bit of Unity experience tells us that “The Object you want to Instantiate is null” is caused by `Instantiate()`.
* So, that means `prefab` is `null`.
* So that means `Resources.Load` returns `null`.
* The documentation for `Resources.Load` says "*Returns the asset at `path` if it can be found otherwise returns null.*"
* So that means it doesn't find the given path (the string I called `resourceLocation`)

Something is wrong with this path, so the obvious first step would be to see what it actually ends up being, with Debug.Log. As "everything works as intended", its probable that there is some duplication going on where one version works and the other gives you this error.

In that case, it's a good idea to use the 2 parameter version of Debug.Log `Debug.Log(resourceLocation, gameObject);`. Now if you click on the log message in the Unity editor, it will select the `GameObject` where it came from.
> 21 votes

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


# Question
Title: How can I create a 2D sprite shadow like in "Alto's Odyssey"?
I've seen that the game "Alto's Odyssey" has a very nice way of projecting shadows on the ground the player is sliding on:

How could i replicate that? Would I use some shader magic, or by projecting a 3D mesh/image on the ground plane?

# Answer
> 1 votes
My approach would be similar as mentioned in the comments. I would take a grey copy of the sprite and would have it mirrored. I would set an offset for the shadow which depends on how far the player is away from the floor. You can use Rays to check that. I also would apply the rotation of the player object to shadow object inversed (just the negative value). The shadow depends on how you set your imaginary light source. so you can use other values. But I would say.

```
float shadowOffset = playerheight / 2; //so shadow is always halfway-> for realistic light effects
position = currentFloorPosition - new Vector2(0, shadowOffset);
rotation = -playerRotation; //not sure about this line that it works
shadowScale *= (shadowOffset * adjustValue) //maybe you need a adjust value which makes sure that the shadows size is good
//code to find the actual postion of the floor

```

so in this code example, you get a rough idea. You need to find the current position of the floor because it´s not constant as it´s curvy. You could also use the player position as a reference point for your shadow offset but I would be scared that the shadow jumps off the floor. To find the current position of the floor you could use a ray or a line cast and use the hit point as the current position. If you have any questions feel free to comment or message me. I hope I could help you. BTW these lines are more pseudo code than the real working code you might tweak some values etc.

---
Tags: 2d, shadows
---


# Question
Title: Add tiles to both sides of TileMap List in MonoGame
This is what my tile map looks like (red highlighting added for clarity):

My code:

```
private List<List<int>> _layoutLayer = new List<List<int>>(50); // Layout Layer
private List<List<int>> _trLayer = new List<List<int>>(50); // Transitional Layer
private List<List<int>> _entityLayer = new List<List<int>>(50); // Object Layer
private List<List<int>> _logicLayer = new List<List<int>>(50); // Logic Layer

// To add a tile
if (inputManager.IsMouseHeld(true))
{
    try
    {
        switch (_currentLayer)
        {
            case LayerRepresentation.LayoutLayer:
                _layoutLayer[_gridMouseY][_gridMouseX] = _currentTile;
                break;
            case LayerRepresentation.TransitionalLayer:
                _trLayer[_gridMouseY][_gridMouseX] = _currentTile;
                break;
            case LayerRepresentation.EntityLayer:
                _entityLayer[_gridMouseY][_gridMouseX] = _currentTile;
                break;
            case LayerRepresentation.LogicLayer:
                _logicLayer[_gridMouseY][_gridMouseX] = _currentTile;
                break;
        }
    }
    catch
    {
         // Player clicked outside of map bounds, add specified amount of tiles to map
    }
}

```

What I need:

When the player clicks outside of map bounds for example on the point A, add the amount of tiles between point A and the map to the map's height. Do the same with point B, but add to the map width instead.

What I've tried:

```
    // Inside the above catch block
    if (_mapHeight - _gridMouseY == 0 && _gridMouseX < _mapWidth && _gridMouseX > -1)
    {
        List<int> tempDefaultLayout = new List<int>();
        List<int> tempDefaultOther = new List<int>();

        for (int i = 0; i < _layoutLayer[0].Count; i++)
        {
            tempDefaultLayout.Add(0);
            tempDefaultOther.Add(-1);
        }
        _layoutLayer.Insert(_gridMouseY, tempDefaultLayout);
        _trLayer.Insert(_gridMouseY, tempDefaultOther);
        _entityLayer.Insert(_gridMouseY, tempDefaultOther);
        _logicLayer.Insert(_gridMouseY, tempDefaultOther);
        _mapHeight++;
    }
    else if (_mapWidth - _gridMouseX == 0 && _gridMouseY < _mapHeight && _gridMouseY > -1)
    {
        for (int y = 0; y < _layoutLayer.Count; y++)
        {
            for (int x = 0; x < _layoutLayer[y].Count; x++)
            {
                if (_layoutLayer[y].Count <= _mapWidth)
                {
                    _layoutLayer[y].Add(0);
                    _trLayer[y].Add(-1);
                    _entityLayer[y].Add(-1);
                    _logicLayer[y].Add(-1);
                }
            }
        }
        _mapWidth++;
    }
    return;

```

The problems:

> The first part is about adding tiles to the height (only one row at a time) Adding the temp `List`s to the layer `List`s with `List.Add()` doesn't work, I don't know why. I used `List.Insert` instead.
>
> The second part is used to add a single column to the map one at a time.

Any help would be appreciated.

# Answer
> 0 votes
I actually figured this out:

Using `Add()` actually works and the problem was in the loop where I was adding the `List<int>`s to my `List<List<int>>`s. I was adding the wrong amount (about 430, instead of the 16 I wanted). I couldn't spot this bug earlier because the four hundred-something lists were all empty and didn't render. So `Add()` was adding the `tempList` to position 431 or something, and trying to index the layer by `[x]` at `[y] = 16` so it threw an `IndexOutOfRangeException`. When I fixed the loop there `Add()` was working as expected.

I also removed the try/catch as it was bad for the exception trace and instead made actual logic that detects clicks outside of the map and `Add()`s elements to my lists before indexing to place/delete a tile.

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


# Question
Title: Why do I get an access violation exception when enumerating joysticks using DirectInput?
Good morning,

I'd like to write an application that uses game controllers and I decided to use DirectInput. The problem is that I get an "access violation execution" (when I run the program inside the debugger of Visual Studio 2017). I'd like to add that I am on Windows 10 and I had a lot of trouble following the documentation on MSDN (the syntax of the calls do not work everytime for me, I have to use macros that I found the SDL2 source code uses; I also need to cast my callback function otherwise the compiler is angry)

Here is a sample program that enumerate the game controllers that are plugged, counts them and then display a simple window.

```
#include <stdio.h>
#include <windows.h>

#define DIRECTINPUT_VERSION 0x0800
#include <dinput.h>
#pragma comment (lib, "dinput8.lib")
#pragma comment (lib, "dxguid.lib")

HINSTANCE g_instance;

// My callback function that is called each time a new joystick is detected.
// I simply count them for now.
// The 'LPVOID pvRef' is a pointer to some user data; I pass the adress of the integer counting the joysticks.
BOOL DIEnumDevicesCallback(LPCDIDEVICEINSTANCE lpddi, LPVOID pvRef) {
  LPDIRECTINPUTDEVICE8 gameController;
  int *p_numJoysticks = (int*)pvRef;

  ++(*p_numJoysticks);
  return DIENUM_CONTINUE;
}

LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam);

int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PWSTR pCmdLine, int nCmdShow)
{
  // Register the window class.
  const wchar_t CLASS_NAME[] = L"Sample Window Class";

  WNDCLASS wc = { 0 };

  wc.lpfnWndProc = WindowProc;
  wc.hInstance = hInstance;
  wc.lpszClassName = CLASS_NAME;

  RegisterClass(&wc);

  g_instance = hInstance; // Save the HINSTANCE in a global in case I need it elsewhere

  // Create the window.

  HWND hwnd = CreateWindowEx(0,                              // Optional window styles.
                 CLASS_NAME,                     // Window class
                 L"Learn to Program Windows",    // Window text
                 WS_OVERLAPPEDWINDOW,            // Window style

                 // Size and position
                 CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,

                 NULL,       // Parent window
                 NULL,       // Menu
                 hInstance,  // Instance handle
                 NULL        // Additional application data
                 );

  if (hwnd == NULL) {
    return 0;
  }

  ShowWindow(hwnd, nCmdShow);

  LPDIRECTINPUT8 directInputInterface = NULL; // the main DirectInput device
  HRESULT result = DirectInput8Create(g_instance,
                      DIRECTINPUT_VERSION,
                      IID_IDirectInput8A,
                      (void **)&directInputInterface,
                      NULL);
  switch (result) {

  case DI_OK: { // No error
    // Enumerate the joysticks
    int g_numJoysticks = 0; // We'll pass the address of this integer to EnumDevices which will then pass it to my callback function each time a joystick is detected

    // This function call raises an execption: access violation
    result = directInputInterface->EnumDevices(DI8DEVCLASS_GAMECTRL,
                           (LPDIENUMDEVICESCALLBACKW)DIEnumDevicesCallback, // The callback I defined at the top of this file
                           &g_numJoysticks, // Pointer to some data I'd like the callback to receive
                           DIEDFL_ATTACHEDONLY); // flags

    // Inspect the variable :numJoysticks: in the debugger
    if (DI_OK != result) {
      OutputDebugStringA("Error in IDirectInput8_EnumDevices\n");
    }

    else {
      int dummyStatement = 0; // break here and inspect :numJoysticks:
    }
    break;
  }

  default: { // handle error
    break;
  }

  // Run the message loop.

  MSG msg = { 0 };
  while (GetMessage(&msg, NULL, 0, 0))
    {
      TranslateMessage(&msg);
      DispatchMessage(&msg);
    }

  return 0;
}

LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
  switch (uMsg)
    {
    case WM_DESTROY:
      PostQuitMessage(0);
      return 0;

    case WM_PAINT:
      {
    PAINTSTRUCT ps;
    HDC hdc = BeginPaint(hwnd, &ps);
    FillRect(hdc, &ps.rcPaint, (HBRUSH)(COLOR_WINDOW + 1));
    EndPaint(hwnd, &ps);
      }
      return 0;
    }
  return DefWindowProc(hwnd, uMsg, wParam, lParam);
}

```

**Remark 1:** why not Xinput? Because I have a SNES controller and a PS4 controller that do not work with XInput.

**Remark 2:** why not a higher level API like SDL2? SDL2 can detect my controller but does not detect any button press. (see this post)

# Answer
> 3 votes
Callbacks in WinAPI need to be defined with the `CALLBACK` specifier (which expands to `__stdcall`), so you need to change the callback signature to

```
BOOL CALLBACK DIEnumDevicesCallback(LPCDIDEVICEINSTANCE lpddi, LPVOID pvRef)

```

---
Tags: directinput
---


# Question
Title: How can I implement an infinite parallax background like in Slither.io?
I am trying to replicate the endless scrolling of slither.io but, I can't figure out how to implement it. Since the players can move to any direction and the background needs to be available during player's displacement.

All the parallax background scrolling tutorials show only moving on one axis, either x or y, but my case it could be to any possible direction like an arrow compass.

Can some one point me in the right direction about how I can implement this effect?

EDIT: User can move to any possible direction like an arrow in a compass.

Custom Camera Controller that follows the player

```
public class CameraController : MonoBehaviour {

    public GameObject Player;

    private Vector3 offset;

    // Use this for initialization
    void Start () {

        offset = transform.position - Player.transform.position;
    }

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

        transform.position = Player.transform.position + offset;
    }
}

```

# Answer
> 1 votes
Myself, I'd solve this in a shader.

We can make a shader that offsets our wrapping background texture based on where the object is positioned in the scene.

Then we can apply this to a material on a quad that's parented to our camera.

As our camera moves around the world, it will never move past the edge of the background quad, since the quad is a child that moves with the camera.

Instead, as the camera moves, it shifts the position where we're rendering the background quad, which offsets its texture lookups accordingly in the shader.

Here's a shader that can do this:

```
Shader "Unlit/ParallaxTexture"
{
    Properties
    {
        _MainTex ("Texture", 2D) = "white" {}
        // Add a variable to control how quickly the parallax scrolls as we move in x & y.
        _ScrollRatio ("Scroll Ratio", Vector) = (1, 1, 0, 0)
    }
    SubShader
    {
        Tags { "RenderType"="Opaque" }
        LOD 100

        Pass
        {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag
            // I removed the lines relating to fog.
            #include "UnityCG.cginc"

            struct appdata
            {
                float4 vertex : POSITION;
                float2 uv : TEXCOORD0;
            };

            struct v2f
            {
                float2 uv : TEXCOORD0;
                float4 vertex : SV_POSITION;
            };

            sampler2D _MainTex;
            float4 _MainTex_ST;
            float4 _ScrollRatio;

            v2f vert (appdata v)
            {
                v2f o;
                o.vertex = UnityObjectToClipPos(v.vertex);
                o.uv = TRANSFORM_TEX(v.uv, _MainTex);

                // Shift the texture according to our position in the world.
                o.uv.x += unity_ObjectToWorld[0].w * _ScrollRatio.x;
                o.uv.y += unity_ObjectToWorld[1].w * _ScrollRatio.y;
                return o;
            }

            fixed4 frag (v2f i) : SV_Target
            {
                fixed4 col = tex2D(_MainTex, i.uv);
                return col;
            }
            ENDCG
        }
    }
}

```

---
Tags: unity, parallax-scrolling, scrolling
---


# Question
Title: Difference between "buffer" and "array" in OpenGL?
When I read doc on webGL or OpenGL there can be seen some patterns in how names of functions and objects are used. But I can't understand the difference between buffer object and an array.

There are "vertex buffer objects", "vertex array objects" and even some kind of "buffer array" or "arraybuffer".

In OpenGL context, When something is "array" and when it should be called a "buffer" instead?

# Answer
The naming of Vertex Array Object is somewhat unfortunate. There's three different things that appear (used to appear) in/with/around your application, and which are (have been, historically) named differently, with "array" or "buffer" in the name (well, there's framebuffer objects too, but I'll ignore that).

1. Data that lives in your application, formally and factually, but which is pulled by OpenGL in one go (as opposed to vertex-by-vertex). This was once upon a time what you would call **vertex array**.
The intent of this was to make accessing more efficient since OpenGL could just copy the whole thing in one go at a well-defined time when you gave the promise that data was consistent, and push it over AGP or whatever in one block. This no longer exists.
2. Data obscured and accessible by a handle that can be "bound", i.e. made active. Data *may* factually live in main memory, or on the graphics card, or be moved to a PCIe-mappable region, whatever, but either way you *formally* do not own (even if it is physically in RAM and if the data came from your application) it -- unless you have currently "mapped" it via the corresponding API, getting back a writeable (and sometimes readable) pointer. You are also limited in your ability of controlling what happens to the data at all (you can give some hints, but that's pretty much it).
OpenGL may move this data around more or less freely, and you are only ever allowed/able to copy to/from the buffer via the corresponding API or access the data while it is being mapped. That is what you call a **buffer object** (vertex buffer object if it contains vertices, but it really doesn't have to, could as well be image data or uniforms, only vertices were the first to be supported, once upon a time).
The intent of this is to guarantee that OpenGL can (in principle) do what it wants, it can even push the buffer over PCIe speculatively before you even draw. That works because you do not own the data (OpenGL does!) and you can only access it via the given API, so it is known at all times that data is valid. The driver can even opt to throw away buffer memory on the graphics card when it needs memory for something different and later restore it from its secret copy when needed.
3. A really stupid misnomer for which a much better name would be something like buffer-set or descriptor-set, this is the infamous **vertex array object**. It is, from your point of view, nothing but a set of buffer handles bunched together under another obscure handle (which you can bind). As it happens, reality is a bit more complicated. In fact, VAO is much closer to how the actual hardware works. Graphic cards have a small number (often something like 2, 4, or 8) of descriptor sets (not just for buffers, but also for samplers) with so-and-so-many entries in each, between which they can switch very efficiently.
Now, the intent of the vertex array object is to reduce the number of API calls and to reduce the number of consistency checks that OpenGL must make internally, and of course, to use the hardware as-it-works. If you bind 5 buffers, then each must go through some possibly expensive checks, and each one is a candidate for cache misses in the driver, plus each single one requires communicating with the graphics card to change a descriptor, etc etc. If you instead bind one VAO, the driver can (often) simply switch the descriptor set on the graphics card, and be done.
> 7 votes

# Answer
> A Vertex Array Object (VAO) is an object which contains one or more Vertex Buffer Objects and is designed to store the information for a complete rendered object.

(pulled from khronos)

Each buffer tends to constitute one attribute of a vertex array (object). A VAO can contain many vertex attributes (e.g. position, color, UV). Each might be held in its own buffer, where *buffer* indicates an unformatted series of contiguous bytes, and where you need to explicitly specify the size (type) per buffer element for both CPU side OpenGL calls and GPU-side shader work.

That's one way. The other ways this can work are:

* All of the attributes are stored *interleaved* in a single buffer, OR
* Some of the attributes exist in their own dedicated buffers, while others share buffers.

The below diagram illustrates these latter two cases.

Bottom line: If the phrase "vertex array" is used unqualified in OpenGL, you can assume it means VAO, which, in an OpenGL context (specifically) is a very different thing indeed from a buffer.

EDIT re your comment: `GL_ARRAY_BUFFER` indicates an intention to use that buffer object for vertex attribute data, as described above. This is because buffers are not used *only* for vertex attributes. However, as it is the most common use-case and you are asking about VAOs, I won't go into the others; here however is a list of the other types of buffers that can be set up.
> 10 votes

# Answer
This terminology is rooted in the history of OpenGL. What's important to remember is that, for most of the GL versions which are relevant here, OpenGL was evolved incrementally and by adding new functionality to an already existing API rather than changing the API.

The first version of OpenGL had none of these object types. Drawing was achieved by issuing multiple glBegin/glEnd calls, and one problem with this model was that it was very inefficient, in terms of function call overhead.

OpenGL 1.1 took the first steps to address this by introducing vertex arrays. Instead of directly specifying vertex data you could now source it from C/C++ arrays - hence the name. So a vertex array is just that - an array of vertices and the GL state required to specify them.

The next major evolution came with GL 1.5 and allowed storing vertex array data in GPU memory rather than in system ("client-side") memory. A weakness of the GL 1.1 vertex array specification was that the full set of vertex data had to be transferred to the GPU each time you wanted to use it; if it was already on the GPU then this transfer could be avoided and potential performance gains achieved.

So a new type of GL object was created to allow storing of this data on the GPU. Just like a texture object is used for storing texture data, a vertex buffer object stores vertex data. This is actually just a special case of a more general buffer object type which may store non-specific data.

The API for using vertex buffer objects was piggy-backed on the already existing vertex arrays API, which is why you see weird things like converting byte offsets to pointers in it. So now we have a vertex arrays API that just stores state, with the data being sourced from buffer objects rather than from in-memory arrays.

This brings us almost to the end of our story. The resulting API was quite verbose when it came to specifying vertex array state, so another avenue of optimization was to create a new object type that collected all of this state together, allowed multiple vertex array state changes in a single API call, and allowed GPUs to potentially perform optimizations due to being able to know what state was going to be used ahead of time.

Enter the vertex array object, which collects all of this together.

So, to summarise, a **vertex array** started life as a collection of state and data (stored in an array) for drawing with. A **vertex buffer** replaces the in-memory array storage with a GL object type, leaving the **vertex array** just being state. A **vertex array object** is just a container object for this state, allowing it to be changed more easily and with fewer API calls.
> 4 votes

# Answer
I havent worked with OpenGL in a while, so I might only be half-right. Generally speaking: Buffers store an array of unformatted memory. An array is a general term of contiguous memory.

A buffer needs to be bound to the context, whereas an array is just an array of data. If i recall correctly, the data in the buffer is meant to be copied onto the graphics card (hence the binding).

Hope this helps a bit
> 0 votes

---
Tags: opengl, webgl
---


# Question
Title: Avoiding GC Allocation in Unity UNet API
I'm trying to profile the game using `Unity Profiler`, I can see in the Hierarchy tab that there's an `18.3 KB` correlated to `NetworkIdentiry.UNetStaticUpdate()`.

I guess this has happened inside the `Unity UNet API`, is there a workaround to avoid that to happen? and why an internal Unity calls can cause `GC`?

# Answer
C# is a language with a garbage collector. `GC.Alloc()` just tells you that something is allocating memory. It is not surprising that internal Unity calls allocate memory.

https://docs.unity3d.com/Manual/BestPracticeUnderstandingPerformanceInUnity4-1.html

> In Unity’s CPU Profiler, the Overview has a “GC Alloc” column. This column displays the number of bytes allocated on the managed heap in a specific frame (4) (Note: Note that this is not identical to the number of bytes temporarily allocated during a given frame. The profile displays the number of bytes allocated in a specific frame, even if some/all of the allocated memory is reused in subsequent frames). With the “Deep Profiling” option enabled, it’s possible to track down the method in which these allocations occur.
> 0 votes

---
Tags: unity, c#, memory-efficiency, profiling
---


# Question
Title: Can I change previously unlocked game levels into locked locked by updating game?
I have 14 unlocked levels in my android game so that the player can play whichever he want. Can I make those 14 levels locked in next update? Players who previously reached 8th level would have to play from level 1 after the updating game.

# Answer
When you make an update on the Play Store, you have to upload a new `.apk`. This new file can be anything you want, even an entirely different game, so if you know how to make two versions of the game, one with unlocked levels and one with locked, this shouldn't be a problem.

> Player who reached 8th level will have to play from level 1 after the updating game

If by "unlock" you mean that you want to erase the save file of the player, so they start all over again, this could be tricky. I don't know of any way to remove save files on update, but when saving data you can add a version prefix to the key, something like "v1.0-level", so when you update, the app will search for "v1.5-level" and fail, forcing the player to start over.
> 1 votes

---
Tags: unity, android
---


# Question
Title: MonoGame SetRenderTarget is wiping the backbuffer
In my Monogame (XNA) Windowed App, compiled for Windows PC, running on Windows 7, I have

```
public RenderTarget2D renderTarget = null;

```

In the Inititate() function I have

```
renderTarget = new RenderTarget2D(graphicsDevice, 200, 200, false,
                           graphicsDevice.PresentationParameters.BackBufferFormat,
                           graphicsDevice.PresentationParameters.DepthStencilFormat);

```

My drawing is as follows

```
public override void Draw(GameTime gameTime)
{
    base.Draw(gameTime);

    // POSITION A

    // draw some stuff to the back buffer
    graphicsDevice.Clear(ClearOptions.Target | ClearOptions.DepthBuffer,
                         backgroundColor, 1, 0);

    SceneRoot.Draw(gameTime);    // draw some 3d primitives

    spriteBatch.Begin();
    spriteBatch.Draw(...some things...);
    spriteBatch.End();

    // POSITION B

    spriteBatch.Begin();
    spriteBatch.Draw((Texture2D)renderTarget, new Vector2(5f, 200f),
                     new Rectangle(0, 0, renderTarget.Width, renderTarget.Height),
                     Color.White);
    spriteBatch.End();
}

```

If I put the following code to draw to the renderTarget in POSITION A then I can see the stuff drawn between POSITION A and POSITION B, with the stuff drawn to the renderTarget on top, as expected.

If I put the following code in POSITION B then I can't see anything drawn between POSITION A and POSITION B, just the stuff drawn to the renderTarget.

```
graphicsDevice.SetRenderTarget(renderTarget);
graphicsDevice.Clear(Color.Red);
spriteBatch.Begin();
spriteBatch.Draw(...some things...);
spriteBatch.End();
graphicsDevice.SetRenderTarget(null);

```

With the above code for insertion, I can even reduce it to

```
graphicsDevice.SetRenderTarget(renderTarget);
graphicsDevice.SetRenderTarget(null);

```

and still get the same result (only see what is drawn to the renderTarget, which is now nothing, ie a blank screen). I've tested, and it's the `SetRenderTarget(renderTarget)` that's causing the problem, seemingly by wiping the backbuffer.

Oh, and none of the sprites drawn cover the whole display, so it's not the sprites displaying wrong, I don't think, as I should still see the 3d stuff.

I've looked and I don't see anything in SetRenderTarget about wiping the backbuffer. Can anyone help? Is it something else, like something to do with the RenderState or the Effects? I can provide more of my code if need be.

# Answer
> 4 votes
I am not 100% sure about the Monogame implementation. But, in XNA, **what you are seeing is the correct behaviour**. One would expect Monogame to be faithful to the XNA implementation.

The reason this behaviour exists is that on some devices (Xbox 360, WinPhone) the operations for saving and restoring a backbuffer are *slow*. So the default is to clear a render target (including the backbuffer via `null`) whenever it is set with `SetRenderTarget`. Even on hardware that does not require a clear, it is cleared anyway so that your code works cross-platform.

The behaviour is controlled by passing `RenderTargetUsage` (MSDN) to the `RenderTarget2D` constructor (MSDN) or setting it in your `PreparingDeviceSettings` handler (MSDN; the thing to set is `args.GraphicsDeviceInformation.PresentationParameters.RenderTargetUsage`).

But, rather than modifying the `RenderTargetUsage`, **it is generally better to simply draw to your render targets in an order that respects dependencies**.

*(And, yes, the XNA documentation is terrible for not mentioning this anywhere.)*

# Answer
> 2 votes
I'm going to post this answer as an adaptation from @James Carlyle-Clarke's comment. Because the code formatting in an answer makes it easier to understand. It has also been modified to make it shorter.

You should place this in your Game Object's constructor, after setting a new GraphicsDeviceManager.

```
graphics.PreparingDeviceSettings += (object s, PreparingDeviceSettingsEventArgs args) =>
{
    args.GraphicsDeviceInformation.PresentationParameters.RenderTargetUsage = RenderTargetUsage.PreserveContents;
};

```

---
Tags: xna, c#, monogame, rendertargets
---


title: How to implement swooping movement?

text:
# Question
Title: How to implement swooping movement?
I am trying to code some swooping behavior for a flying enemy in my 2D platformer.

The ideal behavior has the enemy starting from an arbitrary height above the ground, then accelerating downward and horizontally until flush with the ground, after which he slows and comes to a rest.

I would like to code this in such a way that I can adjust a parameter controlling the steepness of the curve.

In other words, I want a kind of asymptotic movement, similar to this:

https://www.mathsisfun.com/algebra/asymptote.html

**How can I code this kind of movement in such a way that my enemy can start from any height and smoothly and elegantly accelerates down this kind of curve before gracefully stopping?**

I have recourse to all the usual stuff (for example, acceleration, velocity, friction, raycasts, etc.). I would prefer to code the movement using this stuff, rather than hardcoding movement along a curve or path.

I was thinking it might be possible to achieve what I want by raycasting downward and getting the enemy's distance from the ground, and using this distance to adjust accelerations and velocities, but I'm not exactly sure how to go about it.

I work in Godot, but would like an engine-neutral explanation of how to achieve this kind of behavior.

# Answer
The easiest way is probably using an exponential filter:

```
float target_height = 0.0f;
float current_height = 100.0f;
float smoothness = 0.95f;

void update() {
   current_height = smoothness * current_height +
                    (1.0f - smoothness) * target_height;
}

```

Notice that this is non-physical. If you must make use of physics, you can do this using a PD controller.

```
// Controls how fast the plant responds to the error.
float proportional_gain = -0.1f;
// Damps the response so that it doesn't overshoot the target.
float derivative_gain = -2.0f;
float current_height = 100.0f;
float target_height = 0.0f;
float prev_error = 0.0f;
float current_velocity = 0.0f;
float mass = 1.0f;

void update(float dt) {
    float error = current_height - target_height;
    float dError = (error - prev_error) / dt;
    float output = proportional_gain * error +
                   derivative_gain * dError;
    prev_error = error;
    velocity += (output / mass) * dt;
    current_height += velocity * dt;
}

```

Output of the PD controller:
> 2 votes

---
Tags: 2d, physics, movement, steering-behaviors
---