# Question
Title: Voronoi graph - traversing from vertex to vertex
I'm working on a Unity Project in C#

I've built a 3D Voronoi Diagram using the csDelaunay library from PouletFrit and using the X and Y values from a 2D diagram to instead setup some Vector3's with something like (x,0,y)

Example:

My current task is to build a river, as a List of Vector3's

I've so far been able to figure out most of the library code, and build/retrieve lists of:

* The north-most Vertices, South-most, East and West
* All Edges, and for each their left vertex (green) and right end vertex (red)
* All Sites / Seeds

To start the river I've picked one vertex at random from the North-most list and then pick a suitable opposing vertex on the south list.

I've been at this for many hours now, getting nowhere really, but I think my main problem is I can't focus. So I'm going to avoid splines, meshes, etc. for now and keep this simple, I just want to get a list of points the river will go through.

as advised by 'Arcane Engineer' on a previous question (too broad), I'll just use the Voronoi cell boundaries for this, but I need to find the shortest or best path between my north river point and my south point.

I've been assuming that either Dijkstra's Algorithm or A\* are the best way to do this but I'm really struggling now, and A\* seems to be more built for open space and determining the route around obstacles, rather than shortest path through fixed nodes ?

as Dijkstra's would need a graph data structure (among other things), would I be correct in saying that The Voronoi class in the library I'm using is already a type of graph data structure ? or would I need to augment it a bit to perform Dijksta's algorithm

My background is mainly in Java, and I hope I have a decent understanding of all the OOP principles I need here, and I have some data structure knowledge, at least at a high level. but if possible i'd like to use pre-written stuff. I found a Priority Queue class from Microsoft that may help me in implementing Dijkstra's ?

I tried working on a "simpler" recursive algorithm that checks from the first point (north-most), what edges are connected, and then what direction vector they are going in and compares the angles for each edge vs the target direction, and the smallest angle wins. I haven't got it working yet. But I also get the feeling this is NOT the best way to do this.

Any advice you could give is much appreciated!

# Answer
> 0 votes
In the end, my particular requirements meant that moving towards a custom algorithm based on angles gave me more control over river directions and potential meanders in the end. As wondra explained above, I don't actually need the absolute optimal path, just something that looks like a river. So I went with the recursive approach as the amount of stack space required will be reasonably low, and I will profile this later for performance if required.

# Answer
> 2 votes
A\* also requires a graph. It can be applied to discretized open spaces, but that just means imposing some sort of graph over the open space.

For example, imagine a grid over your open space. You are allowed to move along the lines of the grid. The intersections are the nodes. each line has a default cost of 1. Now, wherever there's an impassable obstacle on the map, remove those nodes & their associated lines. Next, if you some areas that can be moved through with greater difficulty (slow terrain, etc), increase the cost of the lines that cross those accordingly.

That's the basics of how A\* (or most any other path finding algorithm) deals with open space. there's still a lot of details for real world use. Huge graphs need hierarchies in order to be performant. Graph based robot path planning may need a different discretization method.

There's an example of applying A\* to a graph on wikipedia.

As a general rule, I try avoid heavily recursive code. Recursive problem solving is fine & anything that can be done with recursion can be done with a stack instead. I find iterative easier to debug & reason about. It's also tends to have fewer performance penalties.

Unless you're actual intended data set is order of magnitude bigger, or you need to repeatedly resolve the problem in near-real time, either A\* or Dijkstra's will work for this problem. If you're feeling overwhelmed, I suggest Dijkstra's - while it tends to be slower, it's simpler. Also, once you have it working, it's easier to leverage what you know to write up an A\* replacement.

A priority queue helps the performance of Dijkstra's. Since most languages have one built in somewhere, start with that. They're likely to be more robust, have fewer bugs & perform better than anything you cook up. Presumably, you want to develop a game first & foremost, not abstract high performance data structures. If you game needs performance improvements, find the problems when the arise by profiling.

That being said, you might want to brush up on your data structures, especially graphs. I've yet to find a premade graph class that isn't overly complex in an attempt to be super generic or overly adapted to someone else's problem.

---
Tags: algorithm, procedural-generation, data-structure, dijkstra
---


# Question
Title: If someone is using JNI then are they are true user of NDK (c++)?
As someone involved in the hiring of engineers that must have experience using NDK (I work for Unity and support the VR/graphics groups), I see quite a few resumes of people who claim to be using NDK and c++ but at the same time reference the use of JNI. I thought JNI basically made it possible to use NDK using java without using c++. Any thoughts? ( I know I am a recruiter but I am not using stack overflow to recruit, rather, better understand the very technologies I am working around every day. I appreciate your help in advance )

# Answer
Hiring is difficult. I commend that you are taking the extra step to familiarize yourself with these sorts of software engineering details.

As you observed, the two languages aren't interchangeable. However, knowing JNI doesn't preclude experience with NDK, or vice-versa. In fact, it might be preferable to note applicants that are familiar with both. For instance, most high level language programmers don't strictly need knowledge of assembly level programming, but those who do may be more versatile. Having some awareness of what happens outside your required knowledge domain can give you insight toward performing better inside your knowledge domain.

Ultimately, if NDK experience is 'must have' requirement, advertise accordingly. Some of job seekers fear aggressive keyword filters & tend toward over inclusion in an attempt to avoid being screened out. On the other hand, some applicants get real loose with the truth in an attempt to get in the door. Clearly signalling the job requirements (I.E. *'must have NDK experience'*) is probably the best way to avoid losing qualified candidates. After that, advertising time/space/$ permits, stating that *'JNI by itself is not sufficient'* may help focus your candidate pool.

.
> 1 votes

---
Tags: c++, ndk
---


# Question
Title: UI and line renderer layer order when using screen space - camera
I'm using a canvas with screen space - camera because I needed a line renderer that could work for my UI.

However, I need that line to render behind Image elements on my canvas and I'm not seeing any way to accomplish that.

Every UI element on my canvas behaves like its z:90 and `"order in layer": 0` but those aren't really configurable values for a UI object. My line renderer, if z:90, must have a layer order \> 0, or a `z` value \< 90. In both cases, it shows *on top of* my UI.

I essentially have a canvas with a background image, which must be behind everything else, a line renderer (used to connect "dots"), and circle-shaped Images which must be on top.

Here's my hierarchy:

```
Canvas
  |- Background (Panel, no image, color)
  |- GameBoard
       |- LineRenderer (Layer: default, order: 0)
       |- Circle Clone(1)
       |- Circle Clone(2)
       |- etc...

```

What's bizarre is that if I turned off (active=false) the Background object, and my LineRenderer is z:90, order: 0, it works fine. It appears *behind* my UI elements correctly. Yet if this object is active, my LineRenderer appears *on top of* of the elements, despite no z/order changes.

# Answer
> 2 votes
Instead of changing Z-position you can solve this problem by Using Rendering Order

> You can determine in which order your objects are drawn using the Queue tag. A Shader decides which render queue its objects belong to, this way any Transparent shaders make sure they are drawn after all opaque objects and so on.

assign Sprites shader to your line renderer's material because It have Important tag as ZWrite.

> Controls whether pixels from this object are written to the depth buffer (default is On). If you’re drawng solid objects, leave this on. If you’re drawing semitransparent effects, switch to ZWrite Off. For more details read below.

so if you have custom shader use `Zwrite Off` then set your own Rendering Order like this:

# Answer
> 0 votes
To render a line behind a camera space canvas, the line will need to be behind the elements. By default, LineRenderer is set to 'use world space', so setting it's Z position will not affect the position of the line. You can check this by disabling '2D' on the top left of the scene view.

So either you can set the Z position of each vertex on the line to be behind the canvas, or you disable 'use world space' on your LineRenderer and move that. You can also set the plane distance of the canvas to be closer to your camera.

---
Tags: unity
---


# Question
Title: Mobile screen resolution and canvas size
I'm making a HTML5 game using the canvas. I was building it for my iPhone 6 which state a resolution of 1334x750 pixels but also a resolution of 667x375 points. I notice that my canvas need to match the size in points or else it would go beyond the screen.

```
<canvas width="667" height="375" />

```

Is it possible for my canvas to actually be 1334x750? Or am I stuck at 667x375?

# Answer
> 0 votes
You are not "stuck" at a lower resolution, since the device will use it's actual resolution.

As far as I understand, at a logical level you will be using points (not pixels). If you were to work on pixels, your game would look bigger on older devices with less pixel density.

More info here: https://stackoverflow.com/questions/12019170/what-is-pixel-and-points-in-iphone

---
Tags: javascript, html5, html-canvas, resolution
---


# Question
Title: DX11: Alpha blending not working with textured quads
A bit novice on directx11. I am rendering some textured quads out of PNG files (with alpha transparency) and get some inconsistency with my alpha blending. I have a background changing color constantly and you can see transparency is there , since in the transparent bits of the texture you can see the background colour below.

However , when it comes to having one texture on top of another it seems to skip the one below and use the background colour instead!

I can provide some code but I don't exactly know where to problem might sprawl from yet.

Any ideas? Thanks!

# Answer
You need to set your alpha blending state according to the effect you want to achieve. In the Output Merge Stage (when you combine the objects you're drawing with the backbuffer) the blending occours for each pixel according to the following equation:

```
finalColor = backbufferColor * DestBlend + pixelColor * SrcBlend
(same for alpha)

```

In your case I think you wonna set

```
SrcBlend = D3D11_BLEND_SRC_ALPHA;
DestBlend = D3D11_BLEND_INV_SRC_ALPHA;

```

For example if your current alpha is 0.1 (the pixel is almost trasparent) you'll get:

```
finalColor = backBufferColor * 0.9 + pixelColor * 0.1

```

which is the effect you need, I think.

Sources:

https://msdn.microsoft.com/en-us/library/windows/desktop/ff476087(v=vs.85).aspx https://msdn.microsoft.com/en-us/library/windows/desktop/ff476200(v=vs.85).aspx https://msdn.microsoft.com/en-us/library/windows/desktop/ff476086(v=vs.85).aspx

Then you need to render first the opaque objects to fill the backbuffer with the colors you're going to blend with the transparent pixels. You also need to sort the transparent objects you're going to render based on their depth (you render first the deepest), since the blending operation is not commutative (using INV\_SRC\_ALPHA and SRC\_ALPHA). A normal rendering pipeline is (using z testing):

```
-turn on z writing (in depth stencil state)
-render all opaque objects
-turn off z writing
-render all transparent objects from the farthest to the nearest

```

In you're case I think you're first rendering the cross and then the rectangle so you're blending the transparent pixels of the cross quad with what there's on the depth buffer: the background colour. Since the depth writing is on, you block the rendering of other pixels with the same depth (the blue rectangle's ones).

If you only mind to use completely transparent or opaque objects (not alpha = 0.5 for example) you can use the discard() function in you're pixel shader based on an alpha threshold:

```
If(pixel.aplha < 0.01f) discard()

```

This function blocks the pixel before it reaches the Output Merging stage, as if I hasn't ever existed and so you don't write is depth, allowing other pixels to be rendered in that position. If this is your case you can render everything in one pass discarding those pixels.

On a side note: order indipendent transparency (OIT) is a difficult topic which is still being researched I think. You'll still probably get pretty consistent results if you don't order the transparent objects (I think it depends on the variance of the alpha channel of the different quads/pixels).

I hope I've been clear enough. Ask for everything :)
> 1 votes

---
Tags: 2d, textures, directx11, transparency, alpha-blending
---


title: What’s an "IHV"?

text:
# Question
Title: What’s an "IHV"?
I have seen several questions here referencing the “IHVs,” e.g. this one, without defining the abbreviation.

A Google search offers “Inter-Human Virology,” and, a few links down, a Wikipedia disambiguation page that includes “independent hardware vendor,” which certainly *seems* more pertinent to the contexts in which I’ve seen “IHV” here, but I’m not certain about it.

# Answer
> 18 votes
Your assumption is correct, IHV in this context means **Independent Hardware Vendor**. In the linked answer it refers mainly to AMD and NVidia.

---
Tags: terminology
---


# Question
Title: How can I create scenes programmatically from a deployed build in Unity?
This is somewhat of an extension to this question.

I have a client who would like to create an entire game only using XML files. This is how the process should go like:

* Build and run a "GameCreator" project.
* Read an XML file that has the attributes of all the scenes.
* Create new scenes, fill it with new GameObjects, and load some prefabs.
* Deploy this new project as a standalone build.

All of the above should *not* use the Unity Editor. Is that possible?

I used Unity to create a framework, and now the client wants to use this framework to generate more games without using the Unity Editor, only through XML files.

I know that one can read XML files with Unity, but how can one create a scene, fill it with `GameObject`s, and load prefabs all using a standalone build, not the editor? Is there any other way to do what I've described?

# Answer
> 5 votes
Unity 2017.3 supports the concept of creating scenes directly at either runtime or edittime.

see SceneManager.CreateScene()

https://docs.unity3d.com/ScriptReference/SceneManagement.SceneManager.CreateScene.html

> Create an empty new Scene at runtime with the given name.
>
> The new Scene will be opened additively into the hierarchy alongside any existing Scenes that are currently open. The path of the new Scene will be empty. This function is for creating Scenes at runtime. To create a Scene at edit-time (for example, when making an editor script or tool which needs to create Scenes), use EditorSceneManager.NewScene.

You could also use something like this scriptable objects and json example to create both built in and user generated levels:

https://youtu.be/VBA1QCoEAX4?t=1261

# Answer
> 4 votes
You can do something like this. It looks monumentally stupid (Unity has an awesome editor, why not use it?), but just in case you do have a good reason:

1. You can't create *scenes* programmatically, but you can have an empty scene and add whatever you need programmatically.
2. Using prefabs is probably not the best idea: prefabs are usually loaded only when referenced in the scene. You can build a big list of all required prefabs in your game, and reference it, but then they all will be in memory - even the ones you don't need.
3. Better use Asset Bundles - pack all your assets into bundles. Your bundle-building script can also save whatever metadata you need - so you'd have a list of all bundles, with IDs or names or whatever. Then when creating a scene from XML, you can load required bundles and instantiate the objects. Note that you'd probably have to "patch" the references by hand - e.g. if a model bundle needs a texture from another bundle, Unity may not find the texture automatically.
4. The Asset Bundles would still have to be built using Unity Editor. If what you want is loading raw assets (e.g. .fbx or .png files) you'd have to write your own parser to load them, or look at Asset Store - there are loaders for some more popular formats there. However, at this point, you should actually stop using Unity as it's causing more trouble than it's saving.

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


# Question
Title: Need help with simple octree implementation
Hello I'm trying to implement an octree, but when I query the centre positions they all return zero, but these should be offset from zero. Here is my code:

```
class Octree:

def __init__( self, _centre, _size ):
    '''
    Class to create an Octree

    @param: _centre: [float,float,float], position in world space for centre of octree
    @param: _size: float, length of one edge of the first cube, should be big enough to fit all data
    '''

    self.centre = _centre
    self.size = _size
    self.octreeNodes = []

def subdivideOctree( self, _subdivisions ):
    '''
    subdivides octree

    @param: _subdivisions: int, number of times to subdivide octree
    '''

    for i in range(8):
        newCentre = self.centre

        if ((i&2) == 2):
                newCentre[0] += self.size * 0.25
        else:
                newCentre[0] -= self.size * 0.25

        if ((i&4) == 4):
                newCentre[1] += self.size * 0.25
        else:
                newCentre[1] -= self.size * 0.25

        if ((i&1) == 1):
                newCentre[2] += self.size * 0.25
        else:
                newCentre[2] -= self.size * 0.25

        print newCentre

        self.octreeNodes.append(Octree( newCentre, self.size * 0.5 ))

        if( _subdivisions > 0 ):
                self.octreeNodes[i].subdivideOctree( _subdivisions - 1 )

def isLeaf( self ):
    return self.octreeNodes == None

def getCentre( self ):
    return self.centre

def getSize( self ):
    return self.size

a = Octree([0,0,0], 2.0)
a.subdivideOctree(2)

print a.getCentre()
print a.octreeNodes[0].getCentre()
print a.octreeNodes[0]

for n in a.octreeNodes:
    for b in n.octreeNodes:
        print b.getCentre()

```

# Answer
When you do

```
newCentre = self.centre

```

then that doesn't create a new array, but it uses the same object instead. If you modify `newCentre`, `self.centre` gets modified as well. It probably stays 0, because it's symmetric.
> 3 votes

# Answer
You have to do newCentre = self.centre\[:\]
> -1 votes

---
Tags: python, octree
---


title: How to Implement Screen Freeze in Godot

text:
# Question
Title: How to Implement Screen Freeze in Godot
Many 2D games have an intentional screen freeze (say, 75 milliseconds) when the player takes or deals damage. During this freeze, all physics and animation processing stops.

**How can one implement a screen freeze in Godot?**

If you want to suggest how to do this in Unity or another engine, that's fine too. It might help me to figure out how to do it in Godot.

---

My only idea is to have a boolean called `is_screen_freeze` along with some variables `freeze_start_time` and `freeze_duration`. In all my nodes' `_process()` and `_physics_process()`methods, I can just pass if `is_screen_freeze` is true. This seems like a rather inelegant way of going about a screen freeze, and I'm not even sure it would work since animations would probably keep playing. Is there a better way?

# Answer
As flesk already stated, Godot has a very good pause function. You can just call

```
get_tree().paused = true

```

However, this will basically stop all physics, process and input functions making your game completely non-responsible.

Since your game obviously should recover after a short time, I would just create a new node that doesn't inherit the pause property from its parent (this can be set in the editor) but is set to process mode. You could then create a signal that is emitted by this node after a given amount of time. For example with the timer node:

```
freeze_timer = Timer.new()
freeze_timer.connect("timeout", self, "on_freeze_timeout")
freeze_timer.set_wait_time(0.075) # time in seconds
add_child(freeze_timer)
timer.start()

```

Finally you create an `on_freeze_timeout` function to catch the signal.

```
func on_freeze_timeout():
    get_tree().paused = false

```

Alternatively, you could also create a dedicated Timer node and just call it or use the process() function to count up to the time you want. However, with the latter your timing might be a bit off, depending on the time that passed between two function calls.
> 2 votes

# Answer
I have no experience with Godot but I have done this in Unity.

Taking a quick look at the documentation, I'd say you can pause the game using `OS.set_time_scale(0.0)` and get the current ms ticks (milliseconds since start of the engine) with `OS.get_ticks_msec()`

This would freeze the simulation, as `delta` would be 0 each frame. You then can wait the amount of time you want by comparing your stored ms ticks with the current `OS.get_ticks_msec()`, and once the 75 milliseconds has passed, you can set `OS.set_time_scale(1.0)` to keep the execution.
> 2 votes

---
Tags: 2d, godot
---


# Question
Title: Why do I keep getting two exceptions: Slope Limit must be smaller than 90 degrees and offset must be less?
The two exceptions/errors in the editor:

Slope Limit must be smaller than 90 degrees Step Offset must be less or equal to + * 2

In the Hierarchy I have a a First Person Character named Player under it as child a Player Camera and as child of the Player Camera a NAVI object.

I changed in the Inspector the NAVI scale to 0.01 on XYZ:

And I have another empty gameobject in the hierarchy with a script attached to it:

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

public class ObjectsManipulation : MonoBehaviour
{
    //Camera
    public Camera playerCamera;

    //Scaling
    private Scaling scaling;

    //Lights
    public DimLights dimlights;
    private Coroutine lightCoroutine;

    //Colors
    private Colors colors;

    //Rotating
    public bool stopRotation = false;
    private Rotating rotating;

    private void Start()
    {
        scaling = GetComponent<Scaling>();
        scaling.Inits();

        colors = GetComponent<Colors>();
        colors.Start();

        rotating = GetComponent<Rotating>();
    }

    // Use this for initialization
    void Update()
    {
        //Scaling
        if (Input.GetKeyDown(KeyCode.F))
        {
            //Flip the scale direction when F key is pressed
            scaling.scaleUp = !scaling.scaleUp;

            //Stop old coroutine
            if (scaling.scaleCoroutine != null)
                StopCoroutine(scaling.scaleCoroutine);

            if (lightCoroutine != null)
                StopCoroutine(lightCoroutine);

            //Scale  up
            if (scaling.scaleUp)
            {
                //Start new coroutine and scale up within 5 seconds and return the coroutine reference
                rotating.rotateBack = false;
                scaling.scaleCoroutine = StartCoroutine(scaling.scaleOverTime(scaling.objectToScale, scaling.maxSize, scaling.duration));
                if (dimlights.lightsOnOff == false)
                    lightCoroutine = StartCoroutine(dimlights.dimLightOverTime(1, scaling.duration));
            }

            //Scale Down
            else
            {
                //Start new coroutine and scale up within 5 seconds and return the coroutine reference
                rotating.rotateBack = true;
                scaling.scaleCoroutine = StartCoroutine(scaling.scaleOverTime(scaling.objectToScale, scaling.minSize, scaling.duration));
                if (dimlights.lightsOnOff == false)
                    lightCoroutine = StartCoroutine(dimlights.dimLightOverTime(0, scaling.duration)); ;
            }
        }

        //Rotate
        if (Input.GetKey(KeyCode.R) && !scaling.scaleUp)
        {
            rotating.x += Time.deltaTime * rotating.rotationSpeed;
            scaling.objectToScale.transform.localRotation = Quaternion.Euler(0, 0, rotating.x);
            rotating.keyPressed = true;
        }
        if (Input.GetKeyUp(KeyCode.R))
        {
            rotating.keyPressed = false;
        }

        if (!rotating.keyPressed && !scaling.scaleUp && rotating.rotateBack == false
            && DetectInteractable.detected == false)
        {
            scaling.objectToScale.transform.rotation = Quaternion.LookRotation(playerCamera.transform.forward);
        }

        if (DetectInteractable.detected == true && !scaling.scaleUp && stopRotation == false)
        {
            rotating.x += Time.deltaTime * rotating.rotationSpeed;
            scaling.objectToScale.transform.localRotation = Quaternion.Euler(0, 0, rotating.x);
        }
    }
}

```

In this script in the Inspector in the Scaling part I changed the Min Size on xyz also to 0.01

Since then Im getting this exceptions.

Tried to google for a solution , But not sure how to fix it yet.

# Answer
Try this:

Take your player avatar object that you want to scale down and break it into two parts:

1. A top-level container object you can think of as your "logical avatar." This object should have its scale set to (1, 1, 1). It will be used for any gameplay behaviours the avatar needs to interact with, including:

* hosting the character controller component
    * being the target of any scripts that need to reference the player avatar
2. A child "visual" object that contains your character's mesh and any animation components it needs. You can scale this object however you want without interfering with the physics & gameplay logic handled higher up at its parent.

Separating the gameplay & visual parts of your objects can give you a lot more flexibility to iterate with appearances, feedback, and scales without mucking up your physics & play logic.
> 1 votes

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


# Question
Title: Invalid character '' in input string at LitJson.Lexer.NextToken ()
Here's my script:

```
 IEnumerator Refresh_()
{
    Debug.LogWarning("TODO: Loading Popup on.");

    rh.eLanguage language = tzGlobal.Instance.OPTION.language;

    string json = StreetUtility.LoadJsonFromStreamingAssets("notice.json");
    if (json != null)
    {
        // Separate only the necessary parts.
        LitJson.JsonData data = LitJson.JsonMapper.ToObject(json);
        json = data[language.ToString()].ToJson();

        notice = LitJson.JsonMapper.ToObject<string[]>(json);
    }

    string path = string.Format("{0}/{1}/language", rh.Const.LOCALIZATION_PATH, language);
    json = StreetUtility.LoadJsonFromResources(path);
    if (json != null)
    {
        // json load.
        Dictionary<string, string> dic = LitJson.JsonMapper.ToObject<Dictionary<string, string>>(json);

        // dictionary copy.
        dic_localization_text = new Dictionary<eTextKey, string>();
        eTextKey e;
        for (int i = 0; i < dic.Count; i++)
        {
            e = (eTextKey)i;
            dic_localization_text[e] = dic[e.ToString()];
        }

        // Run registered localize function.
        for (int i = 0; i < list_localize_method.Count; i++)
        {
            complete = false;
            list_localize_method[i].Invoke();
            yield return new WaitUntil(() => complete);
        }
    }

    Debug.LogWarning("TODO: Loading Popup off.");
}

```

Now what is happening here is that it loads the `notice.json` file but then as the execution goes this error will pop out

> Failed to Load. LitJson.JsonException: Invalid character '' in input string at LitJson.Lexer.NextToken () \[0x00000\] in :0 at LitJson.JsonReader.ReadToken () \[0x00000\] in :0 at LitJson.JsonReader.Read () \[0x00000\] in :0 at LitJson.JsonMapper.ReadValue (LitJson.WrapperFactory factory, LitJson.JsonReader reader) \[0x00000\] in :0 at LitJson.JsonMapper.ToWrapper (LitJson.WrapperFactory factory, System.String json) \[0x00000\] in :0 at LitJson.JsonMapper.ToObject (System.String json) \[0x00000\] in :0 at StreetUtility.LoadJsonFromStreamingAssets (System.String path\_with\_extention\_under\_streaming\_assets\_folder) \[0x00000\] in :0 notice.json

Here's my code of my `LoadJsonFromStreamingAssets()` that i uses of calling my `notice.json` :

```
public static string LoadJsonFromStreamingAssets(string path_with_extention_under_streaming_assets_folder)
{
    string json = null;
    try
    {
        //Android Platform
#if UNITY_ANDROID
        string full_path = Path.Combine(Application.persistentDataPath, path_with_extention_under_streaming_assets_folder);
        if (full_path.Contains("://") || full_path.Contains(":///"))
        {
            WWW www = new WWW(full_path);
            while (!www.isDone) { }
            json = www.text;
        }
        else
        {
            json = File.ReadAllText(full_path);
        }
        Debug.Log("Loaded File : " + json);
        JsonData itemData = JsonMapper.ToObject(json);

#elif UNITY_IOS //IOS Platform

#elif UNITY_STANDALONE //PC Platform
        string full_path = string.Format("{0}/{1}", Application.streamingAssetsPath, path_with_extention_under_streaming_assets_folder);
        StreamReader reader = new StreamReader(full_path);
        json = reader.ReadToEnd().Trim();
        reader.Close();

        Debug.Log(json);
#endif
    }
    catch (Exception e)
    {
        Debug.LogWarningFormat("Failed to Load.\n{0}\n{1}", e, path_with_extention_under_streaming_assets_folder);
    }
    return json;
}

```

And here is my json file

```
{

"EN": [
"Cancel is available with Cancel button.",
"If you succeed in a lottery, you can receive additional rewards.",
"Round 2 and 3 are shorter than you think.",
"Please check the homepage in Confirm Game Method and Change Member Information."
],
"KR": [
"Cancel 버튼으로 배팅 취소가 가능합니다.",
"로또에 성공하면 추가적인 보상을 받을 수 있습니다.",
"라운드 2와 3은 생각보다 시간이 짧습니다.",
"게임 방법 확인 및 회원정보 변경은 홈페이지에서 확인해주세요."
],
"CN": [
"[中文] Cancel is available with Cancel button.",
"[中文] If you succeed in a lottery, you can receive additional rewards.",
"[中文] Round 2 and 3 are shorter than you think.",
"[中文] Please check the homepage in Confirm Game Method and Change Member Information."
],
"HK": [
"[广东话] Cancel is available with Cancel button.",
"[广东话] If you succeed in a lottery, you can receive additional rewards.",
"[广东话] Round 2 and 3 are shorter than you think.",
"[广东话] Please check the homepage in Confirm Game Method and Change Member Information."
]
}

```

And i uses JsonLint for verifying my json file and yes it is valid. I don't know why it is happening . Could someone point out what's going on ?

# Answer
> 1 votes
What you need to do here is that in your

```
if (full_path.Contains("://") || full_path.Contains(":///"))
    {
        WWW www = new WWW(full_path);
        while (!www.isDone) { }
        json = www.text;
    }
    else
    {
        json = File.ReadAllText(full_path);
    }
    Debug.Log("Loaded File : " + json);
    JsonData itemData = JsonMapper.ToObject(json);

```

You must comment out this `JsonData itemData = JsonMapper.ToObject(json);` This will lead you to another error i'm very sure of it . Just trim out your json file

```
json = www.text.Trim();

```

That's it. That is why you have this error

> Invalid character '' in input string at LitJson.Lexer.NextToken ()

Though you have the correct JSON format still it won't work unless you trim it.

Any by the way. Hello Copy Cat. :)

---
Tags: unity, c#, android, json
---


# Question
Title: Could not find a part of the path "/jar:file:/data/app
I need a hand on this . On Unity Editor this pretty works fine but when i'm building the apk and try to run my `Language Changer` function it can't find the path . Could some point me out where i am lost.

```
Debug.LogWarning("TODO: Loading Popup on.");

    rh.eLanguage language = tzGlobal.Instance.OPTION.language;

    string json = StreetUtility.LoadJsonFromStreamingAssets("notice.json");
    if (json != null)
    {
        // Separate only the necessary parts.
        LitJson.JsonData data = LitJson.JsonMapper.ToObject(json);
        json = data[language.ToString()].ToJson();

        notice = LitJson.JsonMapper.ToObject<string[]>(json);
    }

    string path = string.Format("{0}/{1}/language", rh.Const.LOCALIZATION_PATH, language);
    json = StreetUtility.LoadJsonFromResources(path);
    if (json != null)
    {
        // json load.
        Dictionary<string, string> dic = LitJson.JsonMapper.ToObject<Dictionary<string, string>>(json);

        // dictionary copy.
        dic_localization_text = new Dictionary<eTextKey, string>();
        eTextKey e;
        for (int i = 0; i < dic.Count; i++)
        {
            e = (eTextKey)i;
            dic_localization_text[e] = dic[e.ToString()];
        }

        // Run registered localize function.
        for (int i = 0; i < list_localize_method.Count; i++)
        {
            complete = false;
            list_localize_method[i].Invoke();
            yield return new WaitUntil(() => complete);
        }
    }

    Debug.LogWarning("TODO: Loading popup off.");

```

EDITTED:

my `rh` is a namespace obviously where in i put my file paths for example this `rh.Const.LOCALIZATION_PATH` here's what it looks like

```
// FILE PATH.
public static readonly string LOCALIZATION_PATH = "RH/Data/Localization";

```

And my `StreetUtility` class is here

```
using UnityEngine;
using System;
using System.IO;
using LitJson;

public class StreetUtility
{

// Parsing 1 (Unity default parser).
public static string ToJson<T>(T requestObject)
{
    return JsonUtility.ToJson(requestObject);
}

public static T FromJson<T>(string responseJson)
{
    return JsonUtility.FromJson<T>(responseJson);
}

// Parsing 2 (LitJson).
public static string ToJson_mk2<T>(T requestObject)
{
    return LitJson.JsonMapper.ToJson(requestObject);
}

public static T FromJson_mk2<T>(string responseJson)
{
    return LitJson.JsonMapper.ToObject<T>(responseJson);
}

// SAVE 1.
public static void SaveJson(string json, string path)
{
    using (FileStream fs = new FileStream(path, FileMode.Create))
    {
        using (StreamWriter sw = new StreamWriter(fs))
        {
            sw.Write(json);
        }
    }
 #if UNITY_EDITOR
    UnityEditor.AssetDatabase.Refresh();
 #endif
}

// SAVE 2.
public static bool SaveJson_mk2(string json, string path)
{
    try
    {
        StreamWriter writer = new StreamWriter(path, false);
        writer.WriteLine(json);
        writer.Close();
    }
    catch (Exception e)
    {
        Debug.LogWarningFormat("(Failed to save) 저장 실패.\n{0}\n{1}\n{2}", e, path, json);
        return false;
    }

#if UNITY_EDITOR
    UnityEditor.AssetDatabase.Refresh();
#endif
    return true;
}

// Resources 1.
public static string LoadJsonFromResources(string path_without_extention_under_resources_folder)
{
    TextAsset textAsset = Resources.Load<TextAsset>(path_without_extention_under_resources_folder);
    return textAsset.text;
}

// Load 2 (StreamingAssets).
public static string LoadJsonFromStreamingAssets(string path_with_extention_under_streaming_assets_folder)
{
    string json = null;
    try
    {
        //Android Platform
 #if UNITY_ANDROID
        string full_path = string.Format("{0}/{1}", Application.streamingAssetsPath, path_with_extention_under_streaming_assets_folder);
        StreamReader reader = new StreamReader(full_path);
        json = reader.ReadToEnd().Trim();
        reader.Close();

#elif UNITY_IOS //IOS Platform

#elif UNITY_STANDALONE //PC Platform
        string full_path = string.Format("{0}/{1}", Application.streamingAssetsPath, path_with_extention_under_streaming_assets_folder);
        StreamReader reader = new StreamReader(full_path);
        json = reader.ReadToEnd().Trim();
        reader.Close();

        Debug.Log(json);
 #endif
    }
    catch (Exception e)
    {
        Debug.LogWarningFormat("Failed to Load.\n{0}\n{1}", e, path_with_extention_under_streaming_assets_folder);
    }
    return json;
  }
}

```

# Answer
It won't find the path because Android has a different path when it comes to streaming assets.

Your code won't work, whereas the below will:

```
if (full_path.Contains("://") || full_path.Contains(":///"))
{
    UnityWebRequest file = new UnityWebRequest(full_path);
    while (!file.isDone) { }
    json = Convert.ToString(file.downloadHandler.data).Trim();
}
else
{
    json = File.ReadAllText(full_path);
}

```

You must use the UnityWebRequest class when streaming assets on Android.
> 3 votes

---
Tags: unity, c#, android, json
---


# Question
Title: Love2D game and editor in two separate programs
I'm building an engine in Love2D and I need to build an editor who will create scenes with game objects I wrote in lua.

The thing is that there's this guy in my team who said : "Don't include the editor within the game, make it separate from it so you won't load the whole editor with the game itself"

So I'm asking how could I achieve this type of structure, because I want my libraries to be shared between the game and the editor.

```
- MAIN FOLDER
    | - core
    |   | core features of the engine
    | - editor
    |   | main.lua
    | main.lua

```

I can't see how I'll be able to require files with this structure, is there a specific way to do this kind of thing in lua ?

What I'm trying to do now is this :

*main.lua (game)*

```
require "core/engine"

function love.load()  -- This works
    print("Loaded")
end

```

*main.lua (editor)*

```
require "../core/engine"

function love.load() -- Won't work
    print("Loaded")
end

```

# Answer
> 5 votes
Alright, found it !

I had to add this to the *main.lua* file in the editor folder and it worked :

```
package.path = package.path .. ";../?.lua"
require "core.engine"

```

---
Tags: architecture, lua, love2d
---


# Question
Title: What's the best low cost ways to host your own "play in browser" games
I've been developing games as a hobbiest/part-time indie for a few years now and have half a dozen games that I'm reasonably proud of. I was wondering if anyone could suggest good, relatively low cost options for setting up a web-site to host my games, playable natively in the browser, to more easily share them with friends, online communities, and potential employers.

# Answer
> 1 votes
If it's just simple offline browser games that don't require any kind of interaction with a server, you can use github pages. You can easily set up a "demo" branch containing all your dependencies (if you didn't commit them into the project in the first place).

This has the added benefit of making it easy for your potential employers to check your source code :)

More info: https://pages.github.com/
Example (built on the master branch): https://github.com/bdaenen/dungemoji

Another option would be hosting them on https://itch.io. This is slightly less straightforward as you need to upload a zip file containing all the required files and your game is loaded in an iframe. The advantage here is that your games can be discovered by a relatively large audience.

More info: https://itch.io/developers Example: https://vassildador.itch.io/

(disclaimer: the linked games/pages are mine, I only intend for them to be used as an example, not as self-promotion.)

---
Tags: hosting
---


# Question
Title: How does the following code generate a full screen quad?
How does this

```
struct Output
{
    float4 position_cs : SV_POSITION;
    float2 texcoord : TEXCOORD;
};

Output main(uint id: SV_VertexID)
{
    Output output;
    output.texcoord = float2((id << 1) & 2, id & 2);
    output.position_cs = float4(output.texcoord * float2(2, -2) + float2(-1, 1), 0, 1);
    return output;
}

```

and this

```
pImmediateContext->VSSetShader(fxaaVS, ..., ...);
pImmediateContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
pImmediateContext->Draw(3, 0);

```

generate a Full Screen Quad?

1. It has only three vertices b(provided quad has 4 vertices)
2. the positions produced are also not like a (half of a) quad.

Looking at this, i might be confused between a quad and a full screen triangle.

# Answer
> 7 votes
it doesn't generate a quad, instead it generates a fullscreen triangle.

The outputs end up as:

```
output[0].texcoord = float2(0,0);
output[0].position_cs = float4(-1, 1, 0, 1);

output[1].texcoord = float2(2,0);
output[1].position_cs = float4(3, 1, 0, 1);

output[2].texcoord = float2(0,2);
output[2].position_cs = float4(-1, -3, 0, 1);

```

It goes beyond the edges of the screen but any part outside will get clipped by the rasterizer stage. Doing this avoid double coverage of evaluated pixel on the diagonal you get with 2 triangles.

---
Tags: opengl, textures, directx, hlsl, vertex
---


# Question
Title: How can I make item interactable for action?
In this script when there is a detection I'm setting the flag detect to true and using in with other scripts. And using the `clickForDescription` flag and OnGui to display text description for each interactable item if there is a text for it.

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

public class DetectInteractable : MonoBehaviour
{
    public Camera cam;
    public float distanceToSee;
    public string objectHit;
    public bool interactableObject = false;
    public Transform parentToSearch;
    public static bool detected = false;

    private RaycastHit whatObjectHit;
    private bool clickForDescription = false;
    private bool clickForAction = false;
    private int layerMask = 1 << 8;

    private void Start()
    {

    }

    private void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            clickForDescription = true;
            clickForAction = true;
        }

        Debug.DrawRay(cam.transform.position, cam.transform.forward * distanceToSee, Color.magenta);
        if (Physics.Raycast(cam.transform.position, cam.transform.forward, out whatObjectHit, distanceToSee, layerMask))
        {
            detected = true;
            objectHit = whatObjectHit.collider.gameObject.name;
            interactableObject = true;
            print("Hit ! " + whatObjectHit.collider.gameObject.name);
        }
        else
        {
            detected = false;
            clickForDescription = false;
            print("Not Hit !");
        }
    }

    private void OnGUI()
    {
        if (clickForDescription == true)
        {
            ProcessOnGUI(parentToSearch);
        }
    }

    void ProcessOnGUI(Transform parent, int level = 0)
    {
        foreach (Transform child in parent)
        {
            if (child.GetComponent<ItemInformation>() != null)
            {
                ItemInformation iteminformation = child.GetComponent<ItemInformation>();
                if (child.name == objectHit)
                {
                    var centeredStyle = GUI.skin.GetStyle("Label");
                    centeredStyle.alignment = TextAnchor.UpperCenter;
                    GUI.Box(new Rect(
                          Screen.width / 2 - 50 + 20 * level, // <== INDENTATION
                          Screen.height / 2 - 25, 100, 50),
                        iteminformation.description, centeredStyle);
                }
            }

            // Process next deeper level
            ProcessOnGUI(child, level + 1);
        }
    }

    public class ViewableObject : MonoBehaviour
    {
        public string displayText;
        public bool isInteractable;
    }
}

```

This is the ItemInformation:

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

public class ItemInformation : MonoBehaviour
{
    [TextArea]
    public string description;
}

```

Once object is tagged for Interactable and the ItemInformation is attached to it it will display some description for the item.

Now I want to do something for action. For example if the item is Interactable and a script name ItemAction is attached to it do some action, For example move the object from side to side or rotate the object. The logic should be like the Information. It's just with the Action there might be many options then just displaying text.

I'm not sure how to make some logic and how to work with the ItemAction.

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

public class ItemAction : MonoBehaviour
{

}

```

# Answer
> 1 votes
I'd create an component with a single empty virtual function which should be called when the item is interacted with. Something like this:

```
public class ItemAction : MonoBehaviour {
     virtual void ItemUsed() {

     }
}

```

Then you can create a new behavior that inherits from this class in order to implement the specific action. For example, if you want an item to make a *knock* sound when used displaying a bubble with the text "Knock", you could implement:

```
public class KnockAction : ItemAction {
     public string text;
     override void ItemUsed() {
          DisplayBubbleModule.Show(text);
     }
}

```

Just set `text` to "Knock", and you are ready to go.

---

## Both heritage and composition

This might seem like an overkill, creating two classes to just specify such a simple behavior. But it has its advantages:

* You can create new actions without the need to touch old actions' code.
* It's easy to mix different actions

Imagine you create another action that changes the sprite of the item. You could use this to make, for example, a drawer being opened. You could create this class:

```
    public class KnockAction : ItemAction {
        public Sprite NewSprite;
        override void ItemUsed() {
            GetComponent<SpriteRenderer>().sprite = NewSprite;
        }
    }

```

You just add the component to the item, and put the desired sprite on the NewSprite field.

Now you want to make a shelf with another behavour, that when used, the sprite changes and shows the shelf knocked down, and a text bubble displaying the text "CRASH". **You don't need to create a third action, you can just add both actions we previously created, and setting their fields accordingly.**

Note that for this to work, you should get ALL the ItemAction components in an item, not just one.

---

## Extending interactivity

You could also extend you base class, and make the item interactable in more than one way:

```
public class ItemAction : MonoBehaviour {
     virtual void ItemUsed() {

     }

     virtual void ItemHit(){

     }

     virtual void ItemBurned(){

     }
}

```

You could use these new functions, to be called when the item is set on fire, or when it's hit by an attack. Or you could even create a specific class for each of the type of actions to be done on a item, that really depends on how versatile you want your behaviors, and how to keep them all tidy.

---

## Triggering actions

How to trigger these actions really depends on how your system works, but the idea is basically the same in almost all cases:

* Detect the item you want to be activated
* Retrieve the ItemAction Components of the item and call the desired

Once know what item to activate, it's as simple as:

```
foreach( ItemAction ia in gameObjectToActivate.GetComponentsInChildren<ItemAction>() ){
    ia.ItemUsed();
}

```

If you plan to call these actions very quickly and expect to have a lot of actions triggering at the same time, you should probable cache all the item's actions and stored them, in order to call them without the need of relying on the GetComponentsInChildren\<\> which has some overhead.

Detecting which item to trigger, and how is a whole new issue. You could decide which item to activate and when by:

* Clicking on them
* Making you character stand in front of it and pressing a key
* Adding a new component to you character so specific actions are activated when walking near them
* Create a new class that creates messages in order to trigger ItemActions in a generic and extensible way, the same way we just did for ItemActions
* Create listeners that will trigger actions when certain event happen

But pretty much what you are doing in your `DetectInteractable` class is enough: Get the item and look for the components to call the required function.

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


# Question
Title: Mipmaps for Automatically Generated Texture Objects
I want to generate mipmaps for textures generated by BitmapFont(FileHandle fontFile) constructor. Since it doesn't have that option, what can i do? Can I somehow deep copy the Texture object with mipmaps on or is there any other setting for using mipmaps after Texture object has already been initialized?

I want to use MipMapLinearLinear filter.

# Answer
You can manually load the font texture and give it to the `BitmapFont` contructor. Manually loading the texture will allow you to create mipmaps.

```
// true means generate mipmaps, important!
Texture fontImage = new Texture(Gdx.files.internal("path/to/texture.png", true);
fontImage.setMinFilter(TextureFilter.MipMapLinearLinear); // choose
fontImage.setMagFilter(TextureFilter.Nearest); // choose

// Bitmap font constructor takes a TextureRegion
TextureRegion region = new TextureRegion(fontImage);
// false means dont flip. If your font looks strange try changing it to true.
BitmapFont font = new BitmapFont(Gdx.files.internal("path/to/font.fnt"), region, false);

```
> 0 votes

---
Tags: libgdx
---


title: How to design AI Manager

text:
# Question
Title: How to design AI Manager
I am currently building a AI system for a game. I am familiar with State design pattern and implemented different states for each agent in my game.

Different states are like Running, Attack, Idle, Cover, Support etc.

In this game, I have around 10 agents which have mainly two behaviours - Defender and Attacker.

I made a class AIManager which have reference of all agents in the game. This class decides which agent will do what but I am facing issues in managing this class. There are many rules in the game like -

1. There will be two teams.
2. Each team will have 2 defender and 3 attackers.
3. Attacker will attack attackers and defenders.
4. Defender only attack to defenders.
5. At a time only two agents can attack a single agent.
6. If defender is in cover, it will not go to support state.
7. If defender is attacking, it will not go to run state.
8. If attacker is attacking, it can run away on specific condition. ... etc

To make these rules applicable, my AIManager class is totally mess, contains lots of if/else, need to check every possibilities, for loops. I am sure I am not doing right in implementing these game logic because when I need to change some rules or need to add another state, I need to go through all my game logic. This manager code is totally unstable.

I want to know how to tackle this situation, Is there any design pattern which I should follow or any suggestion would be of great help.

# Answer
> 0 votes
"Managers" are widely considered anti-patterns. Why don't agents themselves implement these rules? For starters, all the attacker-specific logic belongs in Attacker. All the Defender-specific code goes to its class. Common code goes to their common base class (Agent). The Team class is pretty trivial as it chiefly needs to create 3 attackers and 2 defenders.

You now see that the "Manager" class is rather pointless as it would only have to deal with creating 2 teams. That's approximately one line of code.

---
Tags: game-design, design-patterns
---


title: When should you check collisions?

text:
# Question
Title: When should you check collisions?
Suppose a basic game with several circles drawn to screen. The user can select and drag any ball and move it around the screen. Should the selected ball overlap with any other ball on screen, the other ball should displace so they are no longer touching.

The example I've seen use the following structure:

```
for (every ball pair):
   if (collision = true){
   - resolve collision
  }

```

However, with this method, isn't there a risk that a displacement could cause an overlap in a pair already checked, and therefore the overlap printed to the screen?

Would it not be better to re-check every ball pair's collision, every time a ball is displaced, rather than every time-step?

Maybe something like:

```
for (every ball pair):
    if (collision = true){
      -resolve collision
         for (every ball pair):
            if (collision = true){
              - resolve collision
              }
       }

```

EDIT:

Even the method I've listed above shouldn't always provide 100% accurate results. The only way I can think this could work is with some sort of recursive function which only stops when there are no more collisions. Does that seem right?

# Answer
What if resolving the second-order collision itself produces a new collision? For full generality, you'd need to keep resolving collisions through a potentially unbounded number of layers of collisions until you finally reach a state where no further collisions remain.

And if the game were ever presented with an unresolvable state (eg. two objects wedged inside a static container too small for them both), then you'd have an infinite loop.

This is not an easy thing to sidestep. The chains of dependency that make the situation unresolvable can be arbitrarily deep and convoluted - we'd never know for sure if we've found a genuinely impossible situation or if "maybe just a few more iterations will crack it" in the general case. So a system that wants to guarantee it finds a solution if one exists is going to accept the possibility of searching for one forever.

So in practice we have to put a cut-off somewhere and say "we tried our best, maybe we'll find a better solution next frame"

Many physics engines will run some finite number of iterations where they try to resolve all collisions/constraint violations detected in the previous pass, then try to resolve all collisions/constraint violations remaining after that pass, etc, to a developer-controlled maximum number of steps.

Past here, they say "well, showing a slight penetration/constraint violation for a single frame isn't the *worst* sin, let's go with what we have for now and iterate again next frame"

Usually the errors that result are small and short-lived, working themselves out after a few frames. Or they're truly unresolvable situations like the over-confined objects example or a linked chain stretched beyond its maximum length, and trying to find a feasible solution is a fool's errand anyway.

To minimize errors seen this way, you'll want to avoid situations where you have a large number of bodies interacting together - particularly in stacks/chains where the propagation of collision/constraint resolution effects from one end to the other is limited by the number of iterations.
> 1 votes

# Answer
A physics approach is to treat balls as elastic objects. That means they have a position X, a speed V, and are subject to forces F that cause acceleration A.

When two balls would overlap, there is a force that compresses them. The direction of this force is normal to the surface, so for circles and spheres that points to the center. The magnitude of this force increases with the overlap, but you can smuggle how much it increases. This likely won't be noticeable.
> 0 votes

---
Tags: collision-detection, physics, collision-resolution
---


# Question
Title: In pygame, is there no graphicsContext.translate() method?
I am new to pygame. I was searching on the internet and the pygame documentation for the functions which can translate, rotate, scale the entire graphics Context, but I couldn't find them. I know that I can apply transformations on individual surfaces using functions that are present in pygame.transform module, but I couldn't find the functions that will apply transformations to the graphics context itself. Are these functions in a different module or they don't exist?

# Answer
> 1 votes
The short answer is: they don't exist.

Some graphics APIs (Java's Graphics2D for instance) are context oriented, but as you've discovered, Pygame orients its drawing functionality on Surfaces. All the functions for drawing & transforms target a `Surface` passed as an arguement.

---
Tags: pygame
---


# Question
Title: How to structure a game that continue even when closed?
I'm developing a Unity based game purely for fun but I'm stuck with a problem. How can I implement a system that keep my game running even when is closed? I don't want to HAVE IT running when it's closed, but I was thinking to add some kind of timer and compute the logic of the game with the time difference between (LAST\_SESSION)-(ACTUAL\_SESSION).

But how can I implement this? The thing is, how can I "accelerate" the game when I open it so that it's current state is equal to what would have been if I would not have closed it?

EDIT: The game is a sort of RTS. You control a base that has some number of entities that can move independently. Each entity has some kind of job like mine minerals, defend the base from enemy AI, build a structure. The mechanics are the interactions between each entity and the world.

I have a main loop where I update every entity, one at a time. I was thinking that I could do some kind of Load function that calls that main loop with a time\_elapsed variable and with every iteration lower this variable by Time.deltaTime or something like that, and when it reaches zero I can start the game.

Sorry for my bad english.

# Answer
The proper way to do this is, when you exit the game, save the current time somewhere in your project. My .Net skills are awful, but a quick google search suggests `System.DateTime.Now`.

When the game opens again, check again the time with `System.DateTime.Now` and compare it with the saved one to calculate how much time has passed. Based on the result, apply your logic for what every object in the scene has been doing all this time.

Pseudo-code:

```
void OnExit() {
    now = SecondsSinceEpoch();
    write("file.save", now);
}

void OnOpen() {
    last_time = read("file.save");
    now = SecondsSinceEpoch();

    time_elapsed = now -last_time;

    // time_elapsed now holds how many seconds has passed since last time
}

```

Note that people can change their system time to mess with this.
> 3 votes

---
Tags: unity, timer, logic
---


# Question
Title: How can I rotate models in their local space using OpenGL?
I have a base application where a model is loaded in, however I need to manipulate the models positions and rotations independently so that each model in the scene can have its own rotation and position.

At the moment, I have only one object and I am trying to combine the rotation, scale and translation matrices to form the model's matrix but for some reason the model is not rendered.

```
glm::mat4 rotMatrix = eulerAngleXYZ(orientation.x, orientation.y, orientation.z);
glm::mat4 scaleMatrix = scale(mat4(), vec3(1.0f, 1.0f, 1.0f));
glm::mat4 transMatrix = translate(mat4(), vec3(1.0f, 1.0f, 1.0f));

glm::mat4 modelMatrix = transMatrix * rotMatrix * scaleMatrix;

glm::mat4 mvp = camera->getCameraMatrix() * modelMatrix;

glUniformMatrix4fv(matrixId, 1, GL_FALSE, &mvp[0][0]);
glUniformMatrix4fv(modelMatrixId, 1, GL_FALSE, &modelMatrix[0][0]);

```

When using the above code, I don't see anything on the screen, when I'd expect to see the object at position `(1.0f, 1.0f, 1.0f)` as that is the translation.

When I set the model matrix to `glm::mat4(1.0f)`, I can then see the model correctly but it is placed at the origin and I cannot move it.

What am I doing wrong?

# Answer
The problem is that you are multiplyng 3 different matrices, and putting the result into a fourth matrix, and then setting that into the shader.

What you need to do instead is create a single 4x4 matrix, modify it, and then pass that into the shader. Here is a simple example, where we create a model matrix, and set it to default values:

```
glm::mat4 model = glm::mat4(1.0f);

model = glm::translate(model,glm::vec3(0,0,0)); //position = 0,0,0
model = glm::rotate(model,glm::radians(0.0f),glm::vec3(1,0,0));//rotation x = 0.0 degrees
model = glm::rotate(model,glm::radians(0.0f),glm::vec3(0,1,0));//rotation y = 0.0 degrees
model = glm::rotate(model,glm::radians(0.0f),glm::vec3(0,0,1));//rotation z = 0.0 degrees
model = glm::scale(model,glm::vec3(1,1,1);//scale = 1,1,1

```
> 4 votes

---
Tags: opengl, c++, rotation
---


title: Tetris - Smooth piece drop (c++)

text:
# Question
Title: Tetris - Smooth piece drop (c++)
So I have coded simple tetris games on the past but I have never done one where the pieces drop smoothly, like for instance Super Tetris 3 on the SNES.I am planning to learn SDL and for such I want to code a Tetris on it.

My questions are two, as follow :

* Can you give me some hints as to how to code this?
* How hard is to code this compared to make the pieces fall in the easy way?

# Answer
Here is one of many ways to do it.

First I will explain an algorithm for dropping the pieces, then I will explain how to drop them at intervals that don't line up with the grid...

--

0 background

1 piece 1

2 piece 2

```
0 0 1 1 1 0 0
0 0 0 1 2 0 0
0 0 0 0 2 0 0
0 0 0 0 2 0 0

```

Form a matrix that defines each piece by the grid of square locations taken up by that piece.

Start by assuming all pieces are falling.

In each iteration, loop through every piece to determine which pieces are definitively anchored, and stop iterating when the previous iteration finds no new anchored pieces.

To determine whether a piece is anchored, loop through every component of the piece. If any of the following conditions are true, then the piece can be considered anchored.

1. A component is in the bottom row.
2. The space below a component is from another component that is determined to be anchored.

Once you have determined which pieces are falling you can update the matrix and the scene by dropping all the components of those pieces by 1 and restart the algorithm until you have a situation where all pieces are anchored.

--

Now all you need to do is change the step size from 1 to 1/x. Pieces that are inbetween the grid of squares above do not need to be tested in the algorithm. If a piece is inbetween gridlines, then it is guaranteed to be falling, and you can continue dropping it until it lines up with the grid.

Make sure that it lines up with the grid every x steps (if using floating point numbers, some rounding/grid snapping will be required.)
> 1 votes

# Answer
The way I solved this issue in my grid based puzzler:

When a piece goes down you already have them fixed to the next designated position in the array, but you offset your Y coordinates by one grid cell high and simply update that offset by fall speed. When that offset reaches zero you move the pieces to the next grid position below and offset the Y again to make it animate again.

Or slightly different:

When a piece goes down you already have them fixed to a designated position at the *bottom* on the board and simply animate the offset downwards. You'd have to recalculate the offset once you move or rotate your pieces.

It might be handy to give your pieces some state to know if it's still falling or if it's already static.

Keep in mind that this could be very rigid to your liking but personally it worked out pretty well for me.
> 1 votes

---
Tags: c++, tetris
---


# Question
Title: How to Hold on Final Frame of Animation in Godot
I am learning Godot 3.0 and I have a question concerning animation.

I have a player object whose node structure is KinematicBody2D \> Sprite \> AnimationPlayer. In the AnimationPlayer, I have ascend and descend animations that I want to play until their final frames, at which point I want to hold on those frames.

For now, I initiate my animations using the following function, which looks at my player's `state` attribute:

```
func animate():
    var animation_player = $Sprite.get_node("AnimationPlayer")

    # image matches orientation
    if orientation == "LEFT":
        $Sprite.flip_h = true
    else:
        $Sprite.flip_h = false

    # animation depends on state
    if state == "idle":
        if not ["idle"].has(animation_player.current_animation):
            animation_player.play("idle")

    if state == "run":
        if not ["run"].has(animation_player.current_animation):
            animation_player.play("run")

    if state == "ascend":
        if not ["ascend"].has(animation_player.current_animation):
            animation_player.play("ascend")

    if state == "descend":
        if not ["descend"].has(animation_player.current_animation):
            animation_player.play("descend")

```

I have disabled looping for my ascend and descend animations and yet they still loop. Probably because when their animation finishes, the idle animation starts and is then immediately changed back to ascend or descend since the player is still in this state.

So my question is: **How do I go about holding on the final frame of certain animations?**

---

I have looked into the `animation_finished()` signal of the AnimationPlayer, but I can't figure out how to use it properly.

All I can think to do is use a Call Func track on the ascend and descend animations, calling a custom function at the end of these animations which switches to a different, single-frame but looped animation (ascend\_static or descend\_static). But surely there is a better way?

# Answer
> 3 votes
I think the problem is that you call your animate function in every loop. This leads to a constant restart of the finished loop. If you wouldn't check whether or not the animation is running your animation would restart over and over again.

I think it is better to put the animate function into the setter function of `state`, which is called whenever your variable is changed. To do this, just add the following line to your script:

```
var state = "idle" setget state_change

```

And the function:

```
func state_change(new_state):
    state = new_state
    animate(state)

```

The `state_change` function is only called when the state changes and therefore the animate function is only called once (you also don't have to check for a running animation anymore). Since you probably want to loop your idle animation, you have to make sure that this animation is set to loop.

---
Tags: animation, godot
---


# Question
Title: unity & c# - File.ReadAllLines() vs TextAsset Split('\n')
I switched from one approach to the other in my code and I noticed that File.ReadAllLines() has a string length of equal to the alpha-numeric chars in the string, with exception of the last line of the file. I assume that is eol. String.Split('\n') however will result in that extra char for every string in the array, and so only matches ReadAllLines() on the final string. Am I write in assuming its an end of line character that's introduced on every string in the split version? How can I trim these? I don't know of any eol in the special chars. I tried to trim \n and \r but it didn't change the line lengths

--- further clarification as to why I put it here instead of stackoverflow

I am not familiar enough with the workings to be sure. I thought perhaps the results might be due to unity. The File.ReadAllLines() version works on the path to the txt file, the string.Split() version works on the TextAsset.text and the TextAsset is passed through the inspector as reference.

Sorry if I made the wrong decision in posting here!

# Answer
You can test this for yourself by walking through the characters of each string and comparing their values, or printing them as integers to find out what the character is.

eg. `Debug.Log((int)myString[characterIndex]);`

Whipping up a quick sample, the `String.Split()` version includes an extra character `13` at the end - a Carriage Return character.

This is because I composed the text file on a Windows machine that uses `CR` `LF` at the end of each line, characters `13` and `10` respectively. Splitting on `'\n'` = `LF` strips out the latter character, but leaves the former, while `ReadAllLines` consumes both characters of the linebreak.

You can use `"\r\n"` as your delimiter to consume both characters together in the Windows order, or an array including multiple different newline possibilities if you're unsure whether the file might use a different/mixed convention.
> 0 votes

---
Tags: c#, file-format
---


# Question
Title: Java: refresh KeyInput to avoid sticky fingers during gameover state
In short, I am trying to avoid my keys from sticking when its in the gameover state. The problem is if the player is holding down the right button for instance and dies, then he restarts the game moving right indefinitely until the player presses down the right button again. How can I prevent this from occuring? I tried setting up a boolean variable that detects if it's pressed or not but that isn't working.

```
else if(state == STATE.GAMEOVER)
    {
        gameover.tick();
        MouseInput.pressed = true;
        KeyInput.pressed = false;
    }

public void keyPressed(KeyEvent e)
{
    int key = e.getKeyCode();

    for (int i = 0; i < handler.object.size(); i++)
    {
        GameObject tempObject = handler.object.get(i);

        if(tempObject.getId() == ID.Player && pressed == true)
        {
            if (key == KeyEvent.VK_W) handler.setUp(true);
            if (key == KeyEvent.VK_S) handler.setDown(true);
            if (key == KeyEvent.VK_A) handler.setLeft(true);
            if (key == KeyEvent.VK_D) handler.setRight(true);
        }
        if (key == KeyEvent.VK_ESCAPE && pressed == true)
        {
            Game.setState(Game.STATE.PAUSE);
        }
    }
}
public void keyReleased(KeyEvent e)
{
    int key = e.getKeyCode();

    for (int i = 0; i < handler.object.size(); i++)
    {
        GameObject tempObject = handler.object.get(i);

        if(tempObject.getId() == ID.Player && pressed == true)
        {
            if (key == KeyEvent.VK_W) handler.setUp(false);
            if (key == KeyEvent.VK_S) handler.setDown(false);
            if (key == KeyEvent.VK_A) handler.setLeft(false);
            if (key == KeyEvent.VK_D) handler.setRight(false);
        }
    }
}
public static boolean isPressed()
{
    return pressed;
}
public static void setPressed(boolean pressed)
{
    KeyInput.pressed = pressed;
}

    if(handler.isUp() && KeyInput.pressed == true) velY = -5;
    else if(!handler.isDown() && KeyInput.pressed == true) velY = 0;

    if(handler.isDown() && KeyInput.pressed == true) velY = 5;
    else if(!handler.isUp() && KeyInput.pressed == true) velY = 0;

    if(handler.isRight() && KeyInput.pressed == true) velX = 5;
    else if(!handler.isLeft() && KeyInput.pressed == true) velX = 0;

    if(handler.isLeft() && KeyInput.pressed == true) velX = -5;
    else if(!handler.isRight() && KeyInput.pressed == true) velX = 0;
}

```

# Answer
Did you try clearing the player's directions when entering the game over state? Something like this:

```
else if(state == STATE.GAMEOVER)
{
    gameover.tick();
    MouseInput.pressed = true;
    KeyInput.pressed = false;
    player.setUp(false);
    player.setDown(false);
    player.setLeft(false);
    player.setRight(false);
}

```
> 0 votes

---
Tags: java, keyboard
---


# Question
Title: GameObject transform with respect to local camera?
I'd like to recycle objects as they pass behind the camera frustum -- i.e, the plane of the local Z axis, orthogonal to the camera vector: `Camera.main.transform.forward.`

Is there a nice method to test for the above case? That is, "if a GameObject's location \< local Z = 0 plane", we can know that it is behind the camera.

# Answer
> 1 votes
You could use the methods in `MonoBehaviour`, `OnBecameVisible ()` and `OnBecameInvisible ()`, they are called whenever a gameObject becomes invisible or visible to the game camera.

For example:

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

public class ExampleScript : MonoBehaviour {
    void OnBecameInvisible () {
        GetComponent <Renderer> ().enabled = false;
    }

    void OnBecameVisible () {
        GetComponent <Renderer> ().enabled = true;
    }
}

```

I also think the cameras in Unity already cull objects by default automatically, you might not even need to do this at all.

# Answer
> 0 votes
You can also do it like this:

```
bool IsBehind(Vector3 worldPosition, Transform observer) {
    return Vector3.Dot(worldPosition - observer.position, observer.forward) < 0f;
}

```

This dot product computes the signed distance of the provided world position along the observer's forward axis. If it's negative, the position is behind the observer.

---
Tags: unity, camera, transformation
---


# Question
Title: Creating/Displaying Image at Specific Size in Unity with C#
I'm trying to draw an image background for Dialogue in a RPG I'm working on and having issues with preventing the image from taking up the whole screen. The goal is to create an object (if it needs to be created), and otherwise show it, via code.

At the moment, it draws the image successfully, but it takes up the full screen every time.

Here's the code:

```
        GameObject canvasObject = GameObject.Find(DialogueObject);  //DialogueObject is a const string ID

        if (canvasObject == null)
        {
            canvasObject = new GameObject()
            {
                name = DialogueObject
            };

            var canvas = canvasObject.AddComponent<Canvas>();
            var background = canvas.gameObject.AddComponent<Image>();

            canvas.renderMode = RenderMode.ScreenSpaceOverlay;

            canvas.transform.parent = canvasObject.transform;
            background.transform.parent = canvas.transform;

            background.rectTransform.anchorMin = new Vector2(0f, 0f);
            background.rectTransform.anchorMax = new Vector2(1f, .5f);

            if (background.sprite == null)
            {
                background.type = Image.Type.Sliced;
                background.fillCenter = true;
                background.sprite = Resources.Load<Sprite>(DialogueBackgroundResource); //DialogueBackgroundResource is a const string
                background.color = new Color(1, 1, 1, 0.5f);
                background.rectTransform.sizeDelta = new Vector2(40, 40);
            }
        }

        canvasObject.gameObject.SetActive(true);

```

The above is literally all of my code. I've tried setting the sizeDelta, per a number of queries on the web, and even though it changes, the image is always full screen. Is there something else I am missing? My understanding is that the anchors are telling it to basically only take up the spot in the bottom half of the screen.

Any help is appreciated!

# Answer
> 1 votes
1. You attached your background image component to the same object as the canvas.

The anchor properties only affect layout relative to an object's parent, and an object cannot be its own parent, so that robs you of all control over its layout.

Try creating your background this way instead, so your image has its own layout object:

`var background = new GameObject("Background").AddComponent<Image>();`
2. This line is meaningless:

`canvas.transform.parent = canvasObject.transform;`

`canvas` is a component you attached to `canvasObject` so it has the same `Transform` as the object it's attached to. So you're trying to make the `canvas` its own parent, to which Unity will say "ha ha, no. It's null"
3. You set the background's parent with `.parent =` which generates a warning when you do it with UI objects since it's probably not what you want. Instead:

`background.transform.SetParent(canvas.transform, false);`

keeps the background's default `localPosition` where it was created, rather than repositioning it to try to keep the same worldspace position (which would lead to an offset background in this situation)

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


# Question
Title: 2D Collision at corners using C# - without xna or unity
I'm trying to make collision for a 2D game, the player (car) has to collide with the walls of the track when it hits them. I looked into pixel color detection, and X,Y -based collision (But since its a race track, which isn't square, I don't think this will be the best solution. Correct me if I'm wrong).

I understand the concept of collision for straight lines or squares, but i have no idea how to make a perfect collision in the corners of the track. example race track.

I've been searching the web a lot for tutorials and documents on this subject, but failed to find any real examples that don't use XNA or Unity. I need to find a solution that doesn't include using any kind of game engine.

Any links / documents / code snippets, or even pseudo code snippets would really help me a lot.

An example would be: Per Pixel Collision , the thing about this link is that it uses xna, which i can not use.

# Answer
> 1 votes
Since you don't want XNA code snippets, some pseudo code then. I assume you have you're able to read the bitmap or sections from the bitmap since you're referring to the collision part only. Also this varies from the engine/technique used.

For per pixel collision, you would do this:

Get the source rectangle you want to check (the car) and the target rectangle (the track section underneath your car). Collect the pixels from the bitmaps corresponding these rectangles.

Let's say this is the car bitmap where X is a colored pixel:

```
...xx...
x..xx..x
xxxxxxxx
x..xx..x
...xx...
x..xx..x
xxxxxxxx
x.xxxx.x

```

The tracksection would be of equal size, since we only check against the part of the bitmap that is underneath the sprite (let's say it is part of a curve):

```
........
........
........
......xx
...xxxxx
.xxxxxxx
xxxxxxxx
xxxxxxxx

```

Now you check each pixel in the car rectangle against the pixel at the same location in the track rectangle. There are a few options here: 1. If all car `x` pixels are on a track `x` pixel, the car is entirely on the track. 2. If at least 1 car `x` pixel is matched against a track `.` pixel a part of the car is not on the track, and a collision against the scenary occurs. 3. If no car `x` pixel matches against a track `x` pixel, the car is completely off the track.

Usually as soon as a car `x` is matched against a track `.`, the algorithm stops and returns a collision (condition 2 is met), but you can vary this to suit your game mechanics.

Another option is to describe the track using polygons, this would enable you to do simpeler collision checks however it may be a bit harder to create elaborate irregular tracks.

# Answer
> 1 votes
Here is how I would do it:

When creating the map, I'd make lines going from start to finish (probably looping). The lines on the outside (towards the edges of the map) would be clockwise, and the lines on the inside (pointing towards the center of the map) would be counter clockwise.

While the car is racing, check the collision of the closest lines. It's up to you how to do this, you can for example divine the stage in cells, and check only lines inside the car's cell. Then use this formula:

```
d=(x−x1)(y2−y1)−(y−y1)(x2−x1)

```

This detects if a point is on the left or right of a line. `x, y` are the point's position, `x1, y1` and `x2, y2` are the line's edges. if `d` is positive, the point lies on one side of the line, while if it is negative it lies on the other side.

To check if a car is colliding with the edges, check the outer line with this formula, if `d` is positive, the point is inside the track (on the right side of the line, assuming it's facing from `x1, y1` to `x2, y2`. Check the same with the inner line. if `d` is positive again, point is inside the track.

If a line shows `d` as negative, then the car has just collided with that line.

Obviously a car is not just a point, but a full mesh/sprite, in this case you can apply the formula multiple times on the car's corners, this way you can not only tell if the car has collided or not, but also which side collided, so you can handle it differently.

Here's an example of what I mean:

# Answer
> 0 votes
Even if you don't use XNA or Unity, you could still use a C# physics engine, for instance VelcroPhysics (formerly Farseer Physics, a port of Box2D with additional features)

You could also code your own physics from scratch, but I wouldn't recommend it unless you have a really good reason to do so. I did it on a project as I wanted some specific behaviour on some collisions, but it's a lot of work and it means you have to debug and maintain it as your game evolves...

If you still want to follow this path, you should consider your car and the track as shapes (a rectangle for the car and segment list for both sides of the road). Then, knowing the position of your car at the previous frame and its new position after update, you can check whether the rectangle has crossed any segments. In my case, instead on segments, I decomposed my word in angles (acute or obtuse) which where easier to test against my character's rectangle.

---
Tags: c#, 2d, collision-detection, cornering
---


title: Game time and pausing

text:
# Question
Title: Game time and pausing
I am writing a simple game where some things happen after some amount of time. I used simple time analog of the framework I use to schedule these events, however, I have found that I will not be able to pause the game because the time is continuously increasing and nothing can stop it. So I decided to have my own time which is updated each `update()` function call to a delta time (example in Lua):

```
current_time = 0.0

function update(dt)
    current_time = current_time + dt
end

```

So I am able to pause the game now by simply not incrementing the game time and not doing anything at all (simply `return` from the `update` function). The question is do I do this correctly? Does every game engine do this this way? I just could not think of any other method for implementing game time with pausability.

P.S. `update` function is called in the game loop on each iteration. The fps is locked to a constant.

# Answer
> 2 votes
My favorite way to pause a game is this:

```
void Update() {

    if (paused) {
        // handle paused state
        // maybe an animation is showing while game is paused
        // maybe something is moving around
        // actual game time is paused, but the app is still running
        return;
    }

    // Handle update
}

```

This way, if the game is paused, inside update, it will handle the paused interface and then return from `Update()` so it doesn't update the game itself. This depends on what engine/programming language you are using. I've used this when I made a custom game engine, and it was working amazingly well.

---
Tags: timer, pausing
---


# Question
Title: Godot 3 - Trying to make a character dash (wavedash)
So, I'm trying to make a character do a wavedash in Godot 3 and I don't know what I'm missing here. When I press 'Z', the character should burst speed and then a few miliseconds later it should decelerate back to the normal speed. Tried to use a while loop, adding the var to the motion, but it didn't work.

Here's the code (testing only in the right direction).

```
extends KinematicBody2D
const UP = Vector2(0, -1)
const GRAVITY = 20
const ACCELERATION = 50
var MAX_SPEED = 150
var JUMP_HEIGHT = -400
var MAX_DSPEED = 300
var motion = Vector2()
var CAN_DASH = true
var ADD_SPEED = 0

func _physics_process(delta):

motion.y += GRAVITY
var friction = false

if Input.is_action_pressed("ui_right"):
    motion.x = min(motion.x+ACCELERATION, MAX_SPEED)
    $Sprite.flip_h = false
    $Sprite.play("Run")
    if Input.is_action_pressed("dash"):
        ADD_SPEED = 300
        while ADD_SPEED > 0:
            ADD_SPEED -= 3
            motion.x = min(motion.x+ADD_SPEED, MAX_DSPEED)

elif Input.is_action_pressed("ui_left"):
    motion.x = max(motion.x-ACCELERATION, -MAX_SPEED)
    $Sprite.flip_h = true
    $Sprite.play("Run")
else:
    $Sprite.play("Idle")
    friction = true
    motion.x = lerp(motion.x, 0, 0.2)
    JUMP_HEIGHT = -400

if is_on_floor():
    if Input.is_action_just_pressed("ui_up"):
        motion.y = JUMP_HEIGHT
    if friction == true:
        motion.x = lerp(motion.x, 0, 0.2)
else:
    if motion.y < 0:
        $Sprite.play("Jump")
    else:
        $Sprite.play("Fall")
    if friction == true:
        motion.x = lerp(motion.x, 0, 0.05)
motion = move_and_slide(motion, UP)
pass

```

# Answer
You can't use a while loop in this case. When you execute your script and press the dash button you while loop is processed before the next rendering or physics step. That means you just change you motion.x value 100 times until the `add_speed` variable has a value of 0.

Since you use the `add_speed` only for the dash, I think the easiest way to perform the dash with your code is to reduce the add\_speed in each call of the `physics_process` function. For example by adding the following line before(!) the `if Input.is_action_pressed("ui_right"):` part:

```
if add_speed > 0:
    add_speed -= 3

```

However, this would reduce the speed in a linear way. Thats fine if you want it. But if just want a really short "jump" I would consider to define a "dash state" of you character. In my opinion that would help to fine-tune the character behaviour during the dash.
> 1 votes

---
Tags: platformer, godot
---


# Question
Title: How to create custom methods for sprite groups in pygame?
I want to use sprite groups in my game using pygame and the default draw isn't enough. I have tried some tutorials but I failed.

So, being more specific: I want to create custom methods for sprite groups in pygame such as `.handle_event` (this method can exist at all sprites or not).

# Answer
> 2 votes
You can create a `pygame.sprite.Group` subclass and add the methods you need. If you want to customize and override the `draw` method (which you can see here), you have to copy the original method and then add your modifications to it.

```
class ExtendedGroup(pygame.sprite.Group):

    def handle_event(self, event):
        for spr in self.sprites():
            # Check if the sprite has a `handle_event` method.
            if hasattr(spr, 'handle_event'):
               spr.handle_event(event)

    def draw(self, surface):
        sprites = self.sprites()
        surface_blit = surface.blit
        for spr in sprites:
            self.spritedict[spr] = surface_blit(spr.image, spr.rect)
            # I've added this line which draws a rect.
            pygame.draw.rect(surface, SIENNA, (spr.rect.topleft, (15, 15)))
        self.lostsprites = []

```

# Answer
> 1 votes
I keep track of sprite groups using attributes of my `Game` class, which contains my game loop.

For example, in the `new_game()` method of this class, I create groups in the following way:

```
    # create groups
    self.mobs = pg.sprite.Group()
    self.projectiles = pg.sprite.Group()
    self.portals = pg.sprite.Group()

```

Each of these groups corresponds a class I created which inherits from Pygame's `Sprite` class. For example, here is a sketch of my `Mob` class.

```
class Mob(pg.sprite.Sprite):
    def __init__(self, game, x, y):
        self.groups = game.mobs
        pg.sprite.Sprite.__init__(self, self.groups)     # this will add any instance of this class to the game's mobs group
        self.game = game
        self.image = pg.Surface((64,64))
        self.image.fill(RED)
        self.pos = vec(x,y)
        self.bounding_rect = pg.Rect((0,0),(64,64))
        self.bounding_rect.center = self.pos

    def update():
        pass

    def draw():
        pass

```

Notice that in my initialization code, I add any instance of this class to my `mobs` group. Notice further that I allow myself to define `update()` and `draw()` methods for this class.

I do something similar with classes for projectiles, portals, etc. They all have their own group and can have their own `update()` and `draw()` methods.

If you structure things this way, you can then update and draw all your objects in your main game loop's `update()` and `draw()` methods like this:

```
def update(self):
   for mob in self.mobs:
       mob.update()
   for projectile in self.projectiles:
       projectile.update()
   ...

def draw(self):
   for mob in self.mobs:
       mob.draw()
   for projectile in self.projectiles:
       projectile.draw()
   ...

```

In this way, you can create custom `update()` and `draw()` methods for whatever objects your game requires.

---
Tags: sprites, pygame, oop
---


# Question
Title: How does UNO determine how often do +4,+2 & other special cards occur in a deck/game?
For UNO-like card games, what factors would one consider when they wanted to set a reasonable proc rate of receiving a special card (for example in UNO's case: +4,+2, color-wheel, reverse, skip)? What factors should I consider when designing a similar game?

I understand probabilities etc. are involved in this. I would appreciate if someone can demonstrate the mathematics/concepts behind it.

# Answer
**tl;dr:** Math is useful, but it can not replace playtesting.

1. Card economy. You don't want the game to take forever, so you need to make sure that over time players will have a net loss of cards. So you need to make sure that the cards picked up by "take X" cards do not outweight the natural rate of losing cards. This is one aspect where trying to find a solution based on math makes sense. We could now analyze the exact math for UNO here, but that might be enough material for a university homework assignment and of little use for you unless you want to make an UNO clone.
2. Balance luck vs. skill. The more powerful the special cards and the easier they are to play, the more luck-based does the game become. For example, many people who play UNO ignore an important rule regarding the +4 card. You can only play it when you can not play any other card. Following that rule correctly makes that card a lot less powerful during the early- and mid-game and thus makes the game less luck-based.

Children usually prefer more luck-based games while adults often prefer more skill-based games. So the ideal balance in this regard is a question of target demographic.
3. But most importantly, playtests, playtests and more playtests. Even the best game designer can not design a fun game without actually playing it. Play it over and over again with different decks and different rule variations to figure out what works best in achieving your game design goals.

* Don't just play a certain combination once. Play it multiple times to make sure that your results are not just due to chance or bad play.
    * Don't always play to win. Have testplayers vary their playstyle from match to match. Try strategies you don't expect to work and see where it leads to. Even if that strategy eventually loses, the results might still surprise and inspire you.
    * Don't always playtest it with the same people. Try to bring in new players from time to time to bring in a fresh perspective and make sure that your rules are still accessible to newcomers.

Then analyze your test games and pinpoint phases which weren't fun. Think of how you can modify the game to fix or avoid these phases. Implement your changes and do yet more playtests.
> 27 votes

# Answer
In the case of UNO, I find it highly unlikely that there was *any* deep consideration of the underlying mathematics. Consider this image of the UNO deck of cards (taken from the Wikipedia page on UNO):

It contains 108 cards. That's an interesting number. Why? Because it's twice the number of cards in a standard deck of playing cards - 54 (13 of each suit, plus 2 jokers) - moreover, the cards appear in 4 "suits" (colours in the final game). I strongly suspect therefore that UNO was developed playing with two sets of playing cards and, in fact, the ratios of the different cards reflect the distributions that could be easily created from these decks rather than any deep consideration of design principles.
> 16 votes

---
Tags: game-design, card-game
---


# Question
Title: Make a game object move inside circle and bounce from walls without gravity
I have a circle with a `RigidBody2D` and `CircleCollider2D` components on it.

I'm trying to make it move constantly inside a bigger circle without gravity involved, make it bounce off the circle walls like it has constant velocity but without any delays, same speed all the time.

Here is an example of the same behaviour but inside a rectangle:

I would like to do the same but inside a circle and detect the collision with the circle walls

Thanks in advance :)

# Answer
Some suggestions to get you started:

1. Change your rigidbody gravity scale to 0 and mass to 0.
2. Rigidbody2D.AddForce();
3. Use the EdgeCollider component for your shape you want to bounce off.

Good luck
> 1 votes

---
Tags: unity, movement, rigidbody
---


# Question
Title: Unity: Hiding Game Objects vs Creating them
My game project involves collecting items that will be displayed in trophy cases of sorts.

There could be several hundred objects as the scale of the project increases, each with their own position, rotation and scripts.

I would find it easier to place the assembled items in their correct location using the editor and set their canvas group alpha to 0 (and set booleans in the script to inactive etc) and 'activate' them when they are 'collected' rather than instantiate them from prefabs as GameObjects.

My main question is about performance, is it costly to have my Gameobjects set in scene & created but set to 0 alpha? I don't need these objects to move or be destroyed etc.

My second question is about best practices for architecture design, is this a horrible way to do things? is a workaround for instantiating prefabs just lazy and counterproductive?

# Answer
Hiding inactive game objects off-screen and out of bounds (where collision won't be a factor) and then teleporting them in place on certain triggers is actually a very common technique.

It vastly simplifies lifetime management of those object. It keeps pointers/references alive so you are less likely to crash by using a pointer to a freed object.

It front-loads the time spent allocating the object to the loading time of the level itself. With a specialized allocator you can even allocate all the memory a level needs in one go and then partition it out to the object in the level. "Allocate" here can also mean reuse the chunk of memory the previous level used. How the memory gets partitioned can be precalculated so the level load itself focus just on getting all the assets in place.

And because you are not allocating/freeing in the middle of a level, crashes due to out of memory are less likely in the middle of play and instead only happen as you load the next level (after your autosave makes sure that the player can resume at that point after you patch the mem leak that caused it).

If you have a level that gets revisited but needs different (heavy) prefabs then you could make 2 variants of the level. One for each set of prefabs you need for it.
> 3 votes

# Answer
In general, frequently instantiating and destroying game objects should be avoided. Expensive build-up and tear-down operations happen behind the scenes whenever you do that. Unity will also constantly allocate and deallocate memory. This fragements the RAM used by your game which in turn harms locality of reference which harms execution performance.

However, in your particular situation, this is unlikely to matter.

It matters, for example, in a bullet hell shooter where you would have to create and destroy several bullets each frame. In that case you would reuse objects in an object pool. The downside of object pooling, besides the added complexity, is that it prevents your game from returning memory it doesn't need anymore.

But in your case you are only going to create and destroy an object every few minutes on average. When something happens so rarely, it is not performance critical. The memory aspect does not apply either, because at one point the player will have collected all items anyway. So the best practice will be to do whatever leads to sourcecode which is easier to understand, debug and maintain.
> 2 votes

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


title: How to use uv mapping in Unity 2017

text:
# Question
Title: How to use uv mapping in Unity 2017
I want to create a game with a Minecraft style world. Now I need uv mapping for some cubes in my game. But I could not find any good tutorial in the internet. I want to use the following texture with an uv map:

Each side of the cube has a texture with 64x64 pixels. The dirt texture on the right side has to be the top of the cube. Can anyone tell me how to use uv mapping in my case?

# Answer
You *can* specify UV coordinates in Unity: https://docs.unity3d.com/ScriptReference/Mesh-uv.html

The UV coordinates go from 0 to 1, and the index in the `uv` array corresponds the the vertex with the matching index in the `vertices` array. This Unity Answers post may prove useful. It lists the vertices in Unity's cube primitive. The top face is first in the vertices, so you would map the uvs of the top face in the first four indices of the uv array like this:

```
uv[0] = (1, .333)
uv[1] = (.75, .333)
uv[2] = (1, .667)
uv[3] = (.75, .667)

```

I'll leave it to you to figure out the rest of the faces. Of course, assigning the uvs in a script would be more ideal only if you are generating content at runtime, so making your own mesh in a program like blender would be more ideal ... or you could make a script that runs in the Editor to create a new mesh for you based on the cube primitive. You can do this using the AssetDatabase interface.
> 1 votes

---
Tags: unity, uv-mapping
---