# Question
Title: In GameMaker, is it possible for users to code something into a game while playing, and verify that it is correct?
I was wondering if in GameMaker it would be possible to allow people to code a small bit of the game in so that they then unlock that move/code?

Think of the game DLC Quest, in the way that you had to find a few coins and then you were able to buy the ability to jump, would it be possible to do this but instead of getting people to buy the ability to jump, get them to code it? (Only a little bit of code, of course, not an entire script?)

# Answer
> 5 votes
What you're describing is effectively **running gameplay mechanics in a virtual machine,** which can simplify the process of authoring them and insulate against bad behaviour.

As it happens, a lot of games already do their gameplay like this under the hood! If you've ever heard developers talk about incorporating scripting languages like Lua, or node graph systems like Unreal's Blueprints, this is how they work.

These scripting methods let game/level/quest designers, who might have less hardcore coding experience than the programmers/developers on the team, quickly prototype and iterate on ideas, without recompiling after every change (sometimes editing live while the game is running), and (usually) without crashing the system when a gameplay script isn't quite right for the situation.

To go from this to what you describe, you'd just be adding a friendly user interface inside the game so the player can script this behaviour themselves. This could take the form of typing commands into a text editor, or snapping together blocks/modules, or wiring up a web of nodes, for example.

Once a gameplay script has been created, it's just raw data to feed through the game's scripting system, which doesn't need to care whether it came from a designer or from the player (apart from maybe giving designer scripts a higher level of trust/permissions to muck with aspects of the game state which you might decide to treat as off-limits to the player to maintain challenge and/or stability...)

There's a thriving genre of games exploring programming-by-the-player as a core mechanic in different ways, including...

For some insights into how you might implement such a virtual machine yourself, check out the Game Programming Patterns article on what they call the "Bytecode" pattern (although the same concepts apply even if you don't boil down to literal bytecode as your internal representation)

**One thing to watch out for:**

> "...and have the programme check to see if its right"

This can be a bit more complicated than it may sound at first. You could literally check whether `player's script == solution` but this is pretty narrow & brittle. As any programmer or problem-solver knows, there's usually many ways to approach a task, and it's less fun if the player has to guess & regurgitate the one (or one of several) solutions the game considers "right," versus inventing their own.

Mechanically analyzing a program's code to determine whether it *would* have the desired behaviour is also often not feasible.

So usually the best way to check the player's script is to actually run it and see what happens - evaluating the player on the *result* of the program rather than the code itself (although you can still use code-based challenge stats to get players to try aiming for "fewest instructions used" or "solve without using \[forbidden command\]" etc)

# Answer
> -1 votes
There is the function execute\_string(string,arg1,arg2,...). The arguments are optional and are the same format as script arguments. Other than that, I do not know of any means to do it without coding your own custom language and parser. However, checking for correctness it not feasible. You can check for syntax errors in that the player will receive them, but that is it. Perhaps make a one-time checkpoint that will delete upon loading and be removed once the code is finished and that section completed? Then, if the game crashed they can just reload.

---
Tags: game-maker, scripting
---


# Question
Title: How do I maintain the world pitch, roll or yaw of child objects?
I've got an application where I'm trying to display an object in 3D, with information provided by real-world accelerometers and inclinometers - sensors that pick up the angle of the equipment, relative to ground. The trouble comes when I want to show this 'world pitch' or 'world roll' on an object that is a child of another. I'd think that there is a trivial solution to the problem, but for the life of me, I can't figure out what it is.

Let's say I've got a robot arm with several pieces - "LowerArm", "Elbow", "UpperArm" and "Hand". "Hand" is the child of the "UpperArm", and "UpperArm" is the child of "Elbow". I'd like to place "Hand" at 0 degree pitch, relative to world-space, no matter how I move the parent objects. If I grab my "LowerArm", and rotate it 90 degrees, the hand should still lay 'flat', relative to the ground; in local coordinate space, it should moved 90 degrees, to compensate.

I want it to remain attached; so it should continue to follow the other parts, in terms of roll and yaw. If I twist the arm, the hand twists with everything else - it just maintains that 0 degree world pitch. Observe the yellow object, in the below example:

How can I do this? I would have thought that there was some kind of trick, with matrices or quaternions, that could resolve it; but I've had no luck, so far. It's hard to figure out what the new 'forward' vector should be.

# Answer
> 1 votes
A user over at UnityAnswers gave me the solution to the problem.

Assuming you've got a variable named 'worldPitch', you can do the following (Unity C# code), although ...

```
Vector3 forward = Vector3.Cross(transform.parent.right, Vector3.up);
Vector3 up = Vector3.Cross(forward, transform.parent.right);
transform.rotation = Quaternion.LookRotation(forward, up) * Quaternion.Euler(new Vector3(worldPitch, 0, 0));

```

You can extend this to other orientations (ie. roll, pitch or yaw) by adjusting the axes.

http://answers.unity3d.com/questions/1360796/child-object-world-rotation-on-a-single-axis.html?sort=newest

---
Tags: mathematics, rotation, transformation, quaternion
---


title: Importing levels at runtime

text:
# Question
Title: Importing levels at runtime
I know that the Unity editor can import/export packages which could contains Scenes (levels), but is it possible to import a Scene into a game at runtime without the Unity Editor?

What I am trying to achieve is:

1. The client should only need to download/install the game once.
2. The original game would NOT include any Scenes/levels except the start-up Scene.
3. The original game would also not be aware of any levels so that developers can create more levels AFTER the game was released.
4. The client should be able to place separate pre-created level-files (whether in some Unity scene format or any other format) into some directory where the game can at RUNTIME import these files without the Unity Editor.
5. After the game imported these levels, the game should be able to play those new added levels without re-compiling/restarting.

Before I go and create my own special level-format and Unity Scene exporter/importer I was wondering if this problem has not already been solved.

# Answer
As mentioned in the comments, Unity has AssetBundles ( https://docs.unity3d.com/Manual/AssetBundlesIntro.html ).

These can be loaded at runtime with the 'www' class (if they are stored locally, you can use a file:/ URL, or if they are remote you can use http://).

However, there's one major word of warning. For security reasons, these bundles may NOT include scripts. So if the scenes in these downloadable packages need specific code, you'll need to embed that code in the main executable.

You'll also want to be comfortable that everything is right with your scripts - if you change the parameters a script needs, you'll need to re-build and re-deploy any asset bundles that use it.

Asset Bundles may also be platform-specific (ie. if you are deploying to PC, IOS and Android, you may need to create three different bundles - one for each).

However, they do allow you to load in large chunks of objects, models, animations etc. fairly seamlessly.
> 1 votes

---
Tags: unity, assets, file-format, levels, scene
---


# Question
Title: How can I build a data structure that will persist across saves/loads in GameMaker version 8.1 and earlier?
I wish to build data structures such as trees, linked lists, graphs, stacks, queues, etc. in Game Maker. However, the concept of object in Game Maker Version 8.1 and older does not have a reliable concept of what a pointer is. They shift whenever something is deleted or instantiated, which is obviously bad if everything relies upon a construct of pointers. I think the motivation behind this is to avoid a dangling pointer error, but it makes objects practically useless.

The built in data structures found in the "ds\_..." functions do not persist when saving and loading. They are simply unsaved altogether. This is also not very good in the long run as it could complex constructs to fall apart at random.

Therefore, this begs the question of how one can implement data structures *in general* that don't have this issue?

**Due to recent updates in the engine's implementation of pointers in Game Maker Studio, the problem itself no longer exists as pointers do not need to shuffle to prevent dangling pointer exceptions (as was apparently the motivation behind that *cough* idiotic *cough* design choice). However, as objects in the language are somewhat bloated this question still serves as a way of asking for a *memory-cheap* solution to this problem.**

Users of the original Game Maker software or people attempting to mod older games which feature code-based modding will still benefit from this post.

# Answer
> 1 votes
The solution is to use C-style dynamic memory allocation which is essentially the idea of a struct based programming language. In this sense memory within an array is allocated (for instance 5 indices) and those indices act as your individual node, list, graph or what-have-you. Pointers in this context will just be array indices.

Below are the scripts used to implement this (with titles in bold). The mm\_init function sets up the allocator and should be ran once per object as this is a locally scoped allocator. A global one can also exist either by having one master object everything accesses or by changing the array variables to global. I personally feel that local scope will be better as a global variable might become subject to memory leaks when changing rooms.

Malloc is a function that allocates n indices.

Free is a function that deallocates a block returned by malloc. Pass it what was originally received (which is also the first indice in the memory block).

All of this will require one to write low-level structs to begin with and build their way up to a list or tree. However, I will point out that once nodes are implemented, lists and other things can just be simple manipulations of the node structs. I would recommend writing get and set scripts for all structs you choose to make. It will obscure the nature of the pointers and make it more like manipulation of ordinary structs like in C.

---

**mm\_init**

```
HEAD_NODE = 0;
/*no need to align 0*/
HEAP_SPACE[HEAD_NODE] = 0;
LINKED_LIST_LENGTH = 0;
TAIL_NODE = HEAD_NODE;
return 0;

```

---

**mm\_malloc**

```
newsize = argument[0] + (argument[0] mod 2);
freeP = HEAD_NODE;

if (mm_getLength(freeP) - newsize > 0 && !mm_getFree(freeP))
{
    mm_setFree(freeP,true);
    mm_insert(freeP, newsize);
    return freeP + 1;
}
while (mm_getNext(freeP) < TAIL_NODE)
{
    freeP=mm_getNext(freeP);
    if (mm_getLength(freeP) - newsize > 0 && !mm_getFree(freeP))
    {
        mm_setFree(freeP,true);
        mm_insert(freeP, newsize);
        return freeP + 1;
    }
}

p = TAIL_NODE; /*add to the heap and return the starting position*/
//p = mem_sbrk(newsize + 8); /*add to the heap and return the starting position*/
if (p == -1)
{
    return NULL;
} else
{
    HEAP_SPACE[p] = (newsize) + (1 << 31);
    HEAP_SPACE[mm_getNext(p) - 1] = newsize;
    if (LINKED_LIST_LENGTH == 0)
    {
        HEAD_NODE = p;
    }
    TAIL_NODE = mm_getNext(p);
    LINKED_LIST_LENGTH += 1;
    return (p + 1);
}

```

---

**mm\_free**

```
/* adjust so that ptr points
 * to the node for this block
 */
p = argument[0] - 1;
HEAP_SPACE[p] = mm_getLength(p);

/*did the pointer originate from the heap*/
if (p > HEAD_NODE && p < TAIL_NODE)
{
    if (!mm_getFree(mm_getPrevious(p)))
    {
        /* the previous node
         * can be coalesced
         */
        mm_removeNode(p);
        p = mm_getPrevious(p);
    }

    if (!mm_getFree(mm_getNext(p)) && mm_getNext(p) <= TAIL_NODE)
    {
        /* the next node
         * can be coalesced
         */
        if (mm_getNext(p) == TAIL_NODE)
        {
            TAIL_NODE = p;
        }
        mm_removeNode(mm_getNext(p));
    }
}

```

---

**mm\_getNext**

```
return (argument[0] + mm_getLength(argument[0]) + 2);

```

---

**mm\_getPrevious**

```
return (argument[0] - mm_getLength(argument[0]-1) - 2);

```

---

**mm\_getLength**

```
/*zero out the leftmost bit, reserved for the free value*/
return HEAP_SPACE[argument[0]] & (~(1 << 31));

```

---

**mm\_getFree**

```
return ((HEAP_SPACE[argument[0]] & (1 << 31)) > 0);

```

---

**mm\_setLength**

```
HEAP_SPACE[argument[0]] = argument[1] + (mm_getFree(argument[0]) << 31);
HEAP_SPACE[mm_getNext(argument[0]) - 1] = argument[1];

```

---

**mm\_setFree**

```
HEAP_SPACE[argument[0]] = mm_getLength(argument[0]) + (argument[1] << 31);

```

---

**mm\_removeNode**

```
mm_setLength(mm_getPrevious(argument[0]),mm_getLength(mm_getPrevious(argument[0]))+mm_getLength(argument[0])+2);
LINKED_LIST_LENGTH -= 1;
/*length is in terms of integer words*/

```

---

**mm\_insert**

```
/* the node has to fit to avoid distorting
 * the linked list's heap property
 */
if (argument[1] + 2 < mm_getLength(argument[0]))
{
    node = argument[0] + argument[1] + 2;
    /*ensure the free field is 0*/
    HEAP_SPACE[node] = 0;
    mm_setLength(node,mm_getLength(argument[0])-argument[1]-2);
    mm_setLength(argument[0],argument[1]);
} else
{
    /* all blocks and nodes are 2 byte aligned, so a difference of one
     * would only exist in the case of a system flaw
     */
    HEAP_SPACE[argument[0]] = mm_getLength(argument[0]) + (1 << 31);
}

```

---
Tags: game-maker, data-structure, memory-efficiency, memory, efficiency
---


# Question
Title: Detecting single circle within multiple circles area
There are multiple circles with same radius, given another circle in different radius, how to detect the another circle is fully in multiple circles area.

Image below shows left samples is in the area, right is not.

# Answer
> 1 votes
The first case is as simple as checking whether the offset between the centres added to the radius of the contained circle, is less than the radius of the container circle.

Your second example on the left is a good case to work from. Here we have tried the approach of the first case and it has failed, so we fall back to another approach. Call the left container circle in grey A, the right one B, and the red contained circle C. Examining C against A, you would need to exclude that arc of C which falls outside of A, call the arc D and the remaining arc (A-D). Examining D against B now tells you whether that arc is wholly contained in B; if both arcs (A-D) and D are contained by the set of containers, then D is contained. This analytical approach is probably cleanest and most performant, but there are many corner cases to be aware of.

You can easily extend this to accommodate the third case on the left.

You could also try turning the entire set into arrays of different coloured pixels, and then do examinations pixelwise. This will avoid any corner cases, but is not as elegant and a computationally more expensive.

# Answer
> 1 votes
Another trick you can try is exploiting the Minkowski Difference.

First, combine all your background circles into a compound shape where they overlap, so you have a single sequence of arcs representing the perimeter of each connected blob.

Then, inset this perimeter by the radius of your test circle. (If your background circles have radius `R` and your test circle has radius `r`, then this changes convex arcs in this perimeter to arcs of radius `R - r`, and changes corners where two circles intersect into concave arcs of radius `r`)

This same operation reduces your test circle to a single point. So now you can simply check whether this point is inside the perimeter of any of the islands left by the shrinking.

While computing these inset compound shapes is not trivial, this technique can be advantageous if you can re-use these shapes after computing them once. For example, if you needed to test dozens or hundreds of candidate positions for the small circle, you can front-load all the hard work into this Minkowski difference, then you only need to do the simpler point-inside-perimeter test for each candidate.

# Answer
> 0 votes
My solution, to traverse the intersection point of all black circles and red circle, and if these points are in the red circle, and then check whether these points are in the black circle, if all so, the red circle must be in the black circle.

# Answer
> 0 votes
Whilst these are good ideas, there's the Corner Case of

> What if the Red Circle is completely within a Single Circle?

You would need a check for this as well, which from the sounds of things should likely resemble the "Minkowski Difference" mentioned in DMGregory's Post, but you are simply checking for a Smaller Radius. Basically the Flow Order is thus:

```
if (GreyRad[1]Shell contains RedRad)
{
  if (GreyRad[1]Core contains RedRad)
    Return True
  Else if (GreyRad[1]Inner contains RedRad)
  {
    if (GreyRad[2]Inner contains RedRad)
    {
      if (GreyRad[3]Inner contains RedRad)
        Return True
      Else
        Return False
    }
    Else
      Return False
  }
  Else
    Return False
}
Else
  Return False

```

Which should return True if everything is matched up, False otherwise, now clearly this isn't factoring in for a 2 Radian Pairing, this would only work on a 3 Radian Pairing, as a 2 Radian Pairing would have a smaller Diameter, which would mean you'd want it before the Core but after the 3 in the logical order, but if someone is trying to break the game, chances are you'll want the Core Radian to be called right after the Shell, then you simply work your way in from the Shell, that lowers the Overload chances as the first thing it checks once it recognizes collision is "are they fully within me? If not, how much are they within me?"

Also, don't forget to clamp your variables to prevent Memory Leaks, you don't want to have 5,000,000 variables for GreyRad\[\]Inner if you only have 30,000 to check against, also useful for breaking accidental infinite loops as you can include an Error Tracker Counter (eg. if Errors \> 120 in last 60 sec, kill all threads)

---
Tags: mathematics, geometry, computational-geometry
---


# Question
Title: How to instantiate a gameobject multiple times in unity during runtime?
After destroying a gameobject in unity, how to instantiate it and make it do the exact same thing what the gameobject before getting destroyed was doing? My gameobject is a car which follows a path made out of nodes. After it is destroyed at a particular node, I want to instantiate it at a particular point which is the spawnSpot in my code, then I want it to follow the same path again and then get destroyed again and get instantiated again and follow the same path again and so on. Right now, I am able to make my car follow a certain path and then destroy it at a certain node and and instantiate it and make it follow the same path again. Then my car is destroyed again and instantiated again but this time it does not follow the path and stays right at the spawnPoint. I am using the destroy and instantiate functions in fixed update. Here's the relevant part of my code:

```
private void Destroy()
{
    if(currentNode == nodes.Count - 1)
    {
        Destroy(this.gameObject);
    }
}

private void Instantiate()
{
    if(currentNode == nodes.Count - 1)
    {
        Instantiate(prefab, spawnspot, Quaternion.identity);
    }
}

```

P.S. prefab is the gameObject.

# Answer
Instead of destroying the object, just deactivate it. And inactive game object is no longer doing anything, but can be reactivated at any time. It will retain all of its state.
> 2 votes

# Answer
You can do this simply by copying your gameobject in another gameobject and then use that gameobject instead of prefab.

```
GameObject copiedGameObject;

private void Destroy()
{
    if(currentNode == nodes.Count - 1)
    {
        copiedGameObject = this.gameObject;
        Destroy(this.gameObject);
    }
}

private void Instantiate()
{
    if(currentNode == nodes.Count - 1)
    {
        // No need to give position and rotation becasue it automatically take last stored rotation and position.
        Instantiate(copiedGameObject);
    }
}

```
> 0 votes

---
Tags: unity
---


# Question
Title: How to Convert DirectX Texture2D to a DXGI Surface for WPF Rendering?
I have an image in my WPF application that uses a `D3DImage` to render DirectX content. On the DirectX side I render everything to a `Texture2D` using SharpDX (a C# DirectX wrapper), but I'm not sure how to convert the rendered texture to a `D3DImage`.

I found the `D3DImage.SetBackBuffer(D3DResourceType backBufferType, IntPtr backBuffer)` method, but that requires the texture to be a DXGI Surface. Here's the code I'm working with:

```
// renderTexture is a Texture2D that serves as the renderTarget for the DirectX content
// d3dimg is the D3DImage that WPF uses

d3dimg.Lock()
d3dimg.SetBackBuffer(D3DResourceType.IDirect3DSurface9,
                     renderTexture.QueryInterface<Surface>().NativePointer);
d3dimg.Unlock();

```

But for some reason, the `SetBackBuffer` function call throws an exception saying that the "specified cast is not valid," even though I'm not doing any casts here (as far as I can see). What am I doing wrong?

# Answer
Did you solve this? D3DImage only works with Direct3D 9Ex surface so it won't work with DXGI/Texture2D which are Direct3D 11... unless you arrange some very tricky DXGI surface sharing between 11 -\> 9Ex in advance. I have all the numerous code fragments that prove this should be possible (i.e. accelerated Direct3D 11 video pipeline targeting WPF) but have struggled to fully stitch them together after months of work (albeit starting from zero Direct3D knowledge). Note that this form of surface sharing requires coordinating synchronization manually. In comparison, If you can switch to Direct3D 9 source everything works very easily.

The casting error you are getting is from inside the D3DImage, when it fails to cast your 11 surface to the Surface9Ex it expects and requires.

---

\[edit: see my comment below for more information on a full solution\]
> 1 votes

---
Tags: c#, directx, sharpdx, wpf
---


# Question
Title: Unity: Disable push on dynamic Rigidbody2D objects
I have a player, and several NPCs. I also have several static colliders in the world (trees, water, fence, etc), I want my NPCs to collide with this, so the `Rigidbody2D` needs to be `dynamic`, since `kinematic` does not collide with static colliders (colliders without a rigidbody).

My problem is that since both player and NPC have `dynamic` `rigidbodies`, they push each other when they collide. I could disable this by setting the following in the NPC script:

```
void OnCollisionEnter2D(Collision2D other){
    if (other.gameObject.name == "Player") {
        isMoving = false;
        myRigidBody.isKinematic = true;
    }
}

```

However, the NPC still gets pushed a few pixels before it stops, its barely noticable, but it is noticable, and if you keep colliding with the NPC you could move it as far as you wanted (tedious, but possible).

I've spent a few hours looking and cannot find a good solution to this. I want my NPC to collide with static colliders, but I don't want them to get pushed by the player. How can I solve this?

# Answer
> 0 votes
This one is actually pretty easy to do (although it may not be apparent at first look). All you need is a **massive** NPC. Not in terms of *size* but in terms of *mass*.

Just set the Mass parameter under the Rigidbody to something like 1000 times the player's mass. That way, your player will never be able to apply enough force to the NPC, but you can still make the NPC move, collide, be affected by physics etc.

Demo gif:

---
Tags: unity, physics
---


# Question
Title: How can I bake several variations of a substance?
I have a substance (sbsar) that I'm using to generate a procedural material . I have applied this texture to reversi pieces. It works well, but all the pieces look identical. I addressed this by using a script to change the `$randomseed` property and then call the `RebuildTextures` method for each piece. The effect is exactly what I want: each piece has a slightly distinct marble pattern.

The problem is that the process of rebuilding the textures for 64 pieces takes about 20 seconds. For a simple Android game, this is not acceptable performance.

The designer has the option to "bake" the material under Load Behavior, but this only works for one variation. Is there a way I can bake many different random seeds? I'd be OK with pre-generating a batch of non-procedural materials from the substance and picking randomly from that batch at runtime, but I'm not sure how that can be done.

# Answer
I wrote the following script to generate a batch of pre-rendered textures from a `ProceduralMaterial`. Just add it to an empty object in the scene, set the parameters, and run.

Note that you must set the format of the material to RAW first.

```
using System.IO;
using System.Linq;

using UnityEngine;

public class ExportTexture: MonoBehaviour {

    public ProceduralMaterial Material;

    public string[] TextureNames = {};

    public int Iterations = 1;

    public int RandomSeed = -1;

    public string Folder = "Export";

    public void Start() {
        if( RandomSeed >= 0 ) Random.InitState( RandomSeed );
        for( var i = 0; i < Iterations; ++i ) {
            var mat = Material;
            mat.SetProceduralFloat( "$randomseed", Random.Range( 0f, 1000f ) );
            mat.isReadable = true;
            mat.RebuildTexturesImmediately();

            var textures = ( TextureNames.Any() ? TextureNames.Select( mat.GetGeneratedTexture ).ToArray() : mat.GetGeneratedTextures() ).Cast<ProceduralTexture>();
            foreach( var tex in textures ) {
                var tex2d = new Texture2D( tex.width, tex.height );
                tex2d.SetPixels32( tex.GetPixels32( 0, 0, tex.width, tex.height ) );
                tex2d.Apply();
                var bytes = tex2d.EncodeToPNG();
                var outFile = new FileInfo( Path.Combine( Folder, string.Format( "{0}_{1}.png", tex.name, i ) ) );
                outFile.Directory.Create();
                File.WriteAllBytes( outFile.FullName, bytes );
            }
        }
    }
}

```

I release this code under the WTFPL.
> 1 votes

---
Tags: unity, textures, procedural-generation
---


# Question
Title: Architecture for extremely modular game?
I'm developing a modular game in Unity 5.6. Each module has very little overlap in assets with the others. I'm concerned about having a bloated repository after a few months of development, and since I'm using Bitbucket (a free account) I'm limited in my repo size, but not in my number of repos. So instead of having one huge folder for my game I'm considering having a launcher project and scene that loads builds from a folder in /Assets. Each module would be its own project, and I would just drop its build into the launcher's folder.

My question is, is this a reasonable approach to building a highly modular game? Hopefully I'll be continuing development for quite a while, and I want to make sure the project is as lightweight and extendable as possible. Or am I overthinking this, and should I just use one big repo?

# Answer
> 1 votes
This is not an uncommon pattern when it comes to procedural games, who load assets as they are needed (which in their cases might be never). Under this system you'd load your assets in chunks via Unity's Resource Loader, which allows unity assets to be loaded via a runtime command. This can hurt performance, but can help you manage packages of assets separately .

Other Techniques to consider:

1) Consider leaving all **unmodified** third party assets outside of source control and simply maintain a text file listing what they are. This means not having to spend repo space on assets already being maintained by the asset store and avoids issues if you accidentally provide a third party asset publicly.

2) Consider using the more advanced AssetBundle system which allows you to load assets as packages. Then each project could just maintain it's own package.

3) There are several books on Unity Game Optimization that cover, amongst other things, file size and identifying unneeded assets. I hesitate to make a direct recommendation, but I have a book from PacktPub that helped me address several asset size issues.

# Answer
> 0 votes
I haven't experimented with this yet, but you can write plugins for Unity.

Doc/Manual link: https://docs.unity3d.com/Manual/PluginsForDesktop.html

Video tutorial: https://unity3d.com/learn/tutorials/topics/scripting/writing-plugins

In regards to an architecture, look into Dependency injection and Events/Event Managers. Aside from that I can't say I've seen any specific implementation of this.

---
Tags: unity, architecture
---


# Question
Title: How can I make something happen for a set number of frames?
I want to add a nitro boost feature to my racing game. I want the car to go faster for 45 frames when the nitro is used, but for whatever reason I can't make it work. I originally tried using a `while` loop but obviously that doesn't work for JavaScript physics. Here's what I have now:

```
this.nitro = function() {
    if (this.hasNitro) {
        this.nitroSpeed = this.carSpeed * 2;
        this.speedCopy = this.carSpeed;
        var refreshIntervalId = setInterval(function() {
            this.carSpeed = this.nitroSpeed;
            this.nitroCount--;
            if(this.nitroCount==0){
                this.endNitro();
            }
        }, 1000 / FRAMES_PER_SECOND);
    }
}
this.endNitro = function(){
    clearInterval(refreshIntervalId);
    this.carSpeed = this.speedCopy;
    this.hasNitro = false;
}

```

There are two cars in the game, each an instance of the car class. One of them is controlled with the arrow keys and the other is controlled with WASD. When the car's nitro button is pressed, `nitro()` is called on that car. The goal of the nitro is to double the car's speed for `NITRO_TIME` frames. When the car is initialized, `nitroCount` is set to `NITRO_TIME`.

# Answer
Assuming that you have these parameters in you `Car` class:

```
this.StandardSpeed = 33; // Your own units here; set this to your liking
this.NitroFactor = 2.0;  // set this to your liking
this.NitroDuration = 45; // In frames; set this to your liking

```

I would suggest that once the 'nitro' button is pressed, enable a 'time left' counter to your `Car` object:

```
this.nitroFramesLeft = this.NitroDuration;

```

then in the 'update' method of your car (the 'move' method), apply the nitro if the counter is not zero:

```
var carSpeed = this.StandardSpeed;

if ( this.nitroFramesLeft > 0)
{
  this.nitroFramesLeft = this.nitroFramesLeft - 1;
  carSpeed = carSpeed * this.NitroFactor;
}

// Move the car with the modified (or not) carSpeed.

```

It's as simple as that :)

---

I've not done a lot of JavaScript in my life, so this might not be the exact syntax, but it will give you a good idea.

Also, typically, you'll want a single `setInterval` in your code as much as possible, and that's what is going to run your main loop.

Adding other calls to `setInterval` will eventually lead to headaches for debugging.
> 1 votes

---
Tags: javascript, frame-rate
---


# Question
Title: How can I make units in my board game equal in stats yet unique?
I am making a board game, but can't figure out how to make the units overall equal in their stats, with each one being individual?

# Answer
> 1 votes
I think you are talking about game balancing? It's tricky. It takes finesse and lots of tweaking.

Besides play testing, calculating specific scenarios and common sense, there is not a lot you can really do.

One thing you can do is make some assumptions about the 'value' or 'weight' of each different stat so that you can abstract them and then they can be compared directly. Then you can allocate X number of abstract points to each unit and adjust the stats until its allocation is used up.

For instance, for the sake of a simple example say each unit has movement speed and armor rating. Speed is worth 1pt, armor is worth 2 and each unit can have 10 points. One unit could have a speed of 2 and armor of 4 while another could have an armor of 1 and a speed of 8.

Setup a spreadsheet with calculated fields to help out.

After play testing, when you find the balance is not right, tweak the weighting or the stats themselves. You will probably need to do a LOT of iterations, tweaking and testing... Have fun :)

---
Tags: 2d
---


# Question
Title: Is it possible to create custom functions in Twine 2's Harlowe format?
I'm starting to learn Twine and I'm putting together a little framework for making a game.

I'd like to be able to store functions or procedures somehow so that I can use them over and over again without having to write the whole thing each time.

Example\[Something like this\]: (set: $incrementItemsAmount to (set: \_item's amount to it + 1))

I've looked at lambda macros, but they look like they're more for looped procedures.

# Answer
> 2 votes
Not in the traditional sense. What you can do is create a passage with the code you want in it, then (display:) the passage. You'll need to create a variable to pass information to the passage if it needs to evaluate something.

A couple examples:

A passage named "func:hero health" which displays a variable (with a text effect):

```
{(text-style: "emboss")[(print: $heroHealth's (round: $heroHP))]}

```

Called with

```
(display: "func:hero health")

```

For something more complex, a menu item which takes the player to the version history document (used as a menu item):

```
{(text-colour: "$gameColorCodes's w3-pink")[(link: $menuPassageNameForGoTo)[
(if: (passage:)'s name is 0)[
    (set: $gamePreviousPassage to "main")]
(else:)[
    (set: $gamePreviousPassage to (passage: )'s name)]
(goto: $menuPassageNameToGoTo)
    ]
]}

```

Which I call and pass variables to with:

```
{(set: $menuPassageNameToGoTo to "doc:version history")
(set: $menuPassageNameForGoTo to "Version History")
(display: "func:left menu goto passage")}

```

---
Tags: harlowe, twine
---


# Question
Title: How do I successfully implement Google Mobile Ads and Google Play Services into my Unity arcade game?
I have been trying for like a month now to properly implement Google Play Services and Google Mobile Ads into my Unity Android Game. I have had success in getting Google Play Services to work but when I added Google Mobile Ads at first it didn't work. I just didn't see any ads pop up. Now when I build my app it won't open it just crashes. Not exactly sure what I did. I have configured all the services correctly according to my knowledge and I'm am just using code from the documentation for the ads. Heres that code:

```
public static AdManager Instance { set; get; }

public string bannerId;
public string videoId;
public string deviceId;
BannerView bannerView;
InterstitialAd interstitial;

private void Start ()
{
    Instance = this;
    DontDestroyOnLoad(gameObject);
    interstitial = new InterstitialAd(videoId);
    AdRequest request = new AdRequest.Builder().AddTestDevice(deviceId).Build();
    // Load the banner with the request.
    interstitial.LoadAd(request);
}

public void ShowInterstitial()
{
    if (interstitial.IsLoaded())
        interstitial.Show();
}

```

I am using the correct ad Ids, I double checked that. I don't know what else to do. I can provide any other information you may need upon request.

Anyone with experience with this would be super helpful! Thanks!

# Answer
> 1 votes
Here's the official guide on implementing `AdMob` to your game: https://developers.google.com/admob/unity/start

You basically download the scene on top of this website and import it through `Assets -> Import -> Custom Package`.

Then you restart Unity and your code editor to apply library changes and make the namespace visible.

Then, you create a script called `AdmobManager` and put inside:

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

public class AdmobManager : MonoBehaviour {

    private InterstitialAd staticAd;

    void Awake () {
        LoadStaticAd(); // load it first time
    }

    private void LoadStaticAd(){
        if(staticAd != null) staticAd.Destroy();
        staticAd = new InterstitialAd("ca-app-pub-###/###"); // put here the ID of the static ad from the admob website
        AdRequest request = new AdRequest.Builder()
        // you can add a test device id to test the ads on your phone before releasing the game
        // download this app: https://play.google.com/store/apps/details?id=pe.go_com.admobdeviceidfinder&hl=pl
        // to find the correct id of your device
        //  .AddTestDevice("################################").Build();
            .Build();

        staticAd.LoadAd(request);
        staticAd.OnAdClosed += OnAdClosed; // ad a listener to reload the ad when user finishes watching it
    }

    private void OnAdClosed(object ob, EventArgs args){
        LoadStaticAd(); // when the ad is closed, reload the ad in background
    }

    public void ShowStaticAd(){
        if(staticAd != null && staticAd.IsLoaded()){ // safety checks
            staticAd.Show();
        }
    }

    private static AdmobManager instance; // singleton pattern to access the AdmobManager anywhere
    public static AdmobManager Instance() {
        if(!instance){
            instance = FindObjectOfType(typeof (AdmobManager)) as AdmobManager;
            if(!instance)
                Debug.Log("There need to be at least one active AdmobManager on the scene");
        }

        return instance;
    }
}

```

Remember to replace the ad ID with your own from the `AdMob` website. You can also put your `DeviceID` to test the ads when you're in the Beta phase and the game isn't published yet.

To show an ad in the game, you do:

```
void LevelFinished(){
    AdmobManager.Instance().ShowStaticAd();
}

```

And that's it.

There are two ways on implementing this. One from the tutorial above and one from the `Unity Admob Plugin`. I've tried 6 times implementing `Admob Plugin` from github, always crashes the device, ALWAYS. This guide above worked for 4 games so far on `Unity 5.5` and Unity `5.6`.

# Answer
> 0 votes
I've used admob in my earlier work. Check the code here;

```
using UnityEngine;
using System.Collections;

[RequireComponent(typeof(AdMobPlugin))]
public class ReklamAdmob : MonoBehaviour
{

public GUISkin skin;
private const string AD_UNIT_ID = "YourAdUnitId";
private const string INTERSTITIAL_ID = "YourInterstirialId";
private AdMobPlugin admob;
public Score other2;

public bool hidden = true;

public void Awake()
{
    DontDestroyOnLoad(this);
}

public void Start()
{
    admob = GetComponent<AdMobPlugin>();
    admob.CreateBanner(AD_UNIT_ID, AdMobPlugin.AdSize.SMART_BANNER, true, INTERSTITIAL_ID);
    admob.RequestAd();
    admob.HideBanner();
}

// Update is called once per frame

public void Update()
{
    if(other2.CurrentScore<=0 && hidden==true)
    {
        admob.RequestInterstitial();
        hidden=false;
    }

}

void OnEnable()
{
    AdMobPlugin.InterstitialLoaded += HandleInterstitialLoaded;
}

void OnDisable()
{
    AdMobPlugin.InterstitialLoaded -= HandleInterstitialLoaded;
}

void HandleInterstitialLoaded()
{
    admob.ShowInterstitial();
}
}

```

But i've used Unity Ads, which seems better for me.

If you did not check it yet look here. Implementation is much easier.

---
Tags: unity, google-play-services, google-play, monetization, advertisements
---


# Question
Title: Game Maker Language's random function always giving the same result
I'd like to create a Snake game, and for that, I'd like to position the sweet which makes the snake bigger in a random position.

For that, I use this code in the create event of the object bonbon :

```
position_x = round(random(10));
position_y = round(random(10));

x = position_x*16;
y = position_y*16;

```

But the sprite of this object is always in the same position of the room.

I tried changing the argument to the function `random()`, and then it changed the position of the sweet once, but after a rerun, the position doesn't change from that new location.

I think the position of the sweet is set using the argument to the `random()` function.

How can the position of the sweet be randomized? Why does the random function return the same values every time I run the game?

Thanks to DMGregory, I changed the code and this code works :

```
randomize();
position_x = irandom(10);
position_y = irandom(10);

x = position_x*16;
y = position_y*16;

```

# Answer
I've changed the 'random()' function by the 'irandom()', and add the 'randomize()' function, in order to reset the value which are going to be randomized.

```
randomize();
position_x = irandom(10);
position_y = irandom(10);

x = position_x*16;
y = position_y*16;

```

Sorry for the spelling's mistakes, I'm French.
> 1 votes

---
Tags: game-maker, random
---


# Question
Title: Am I experiencing a gimbal lock problem when rotating my cube?
So I'm trying to build a simple mechanic where the player see's 3 sides of a cube at a time: top, left and front(I called the front-side "Right" in my code, due to the orthographic view). The player can click on the front side or left side of the cube to rotate the cube so that the side that was pressed moves and becomes the top face. I want to smooth/animate the rotation.

*The red faces are the faces that the user can click on.*

My Logic seems to work quite well when I click on the left face (Rotating along the x axis), but doesn't seem to work well for the front/right face(It usually works once and then does weird stuff on the next click, this is on the z-axis)

```
public class CubeRotator : MonoBehaviour
{
    private const float STOP_THRESHHOLD = 0.1f;
    private const float ROTATE_AMOUNT = 90f;

    [SerializeField, Header("Touch Quads Colliders")]
    private Collider touchQuadLeft;
    [SerializeField]
    private Collider touchQuadRight;

    [SerializeField, Space(10)]
    private float timeToRotate;

    private bool mustRotateLeft = false;
    private bool mustRotateRight = false;

    private float targetX = 0.0f;
    private float targetZ = 0.0f;

    private float xVelocity = 0.0F;
    private float zVelocity = 0.0F;

    int layerMask;

    private void Start()
    {
        layerMask = LayerMask.GetMask("Touch Quad");
    }

    void Update()
    {
        ListenForTouch();
        RotateCube();
    }

    private void ListenForTouch()
    {
        if (Input.GetMouseButtonDown(0))
        {
            Vector2 touchPoint = Input.mousePosition;
            RaycastHit rayCastHit;
            Ray ray = Camera.main.ScreenPointToRay(touchPoint);

            if (Physics.Raycast(ray, out rayCastHit, 150f, layerMask))
            {
                if (rayCastHit.collider == touchQuadLeft)
                {
                    mustRotateLeft = true;
                    targetZ = targetZ - ROTATE_AMOUNT;
                    zVelocity = 0f;
                }

                else if (rayCastHit.collider == touchQuadRight)
                {
                    mustRotateRight = true;
                    targetX = targetX + 90f;
                    xVelocity = 0f;
                }
            }
        }
    }

    private void RotateCube()
    {
        float zAngle = transform.rotation.eulerAngles.z;
        float xAngle = transform.rotation.eulerAngles.x;

        if (mustRotateLeft)
        {
            zAngle = Mathf.SmoothDampAngle(zAngle, targetZ, ref zVelocity, timeToRotate);

            if (Mathf.Abs(zVelocity) <= STOP_THRESHHOLD)
            {
                mustRotateLeft = false;
            }
        }

        if (mustRotateRight)
        {
            xAngle = Mathf.SmoothDampAngle(xAngle, targetX, ref xVelocity, timeToRotate);

            if (Mathf.Abs(xVelocity) <= STOP_THRESHHOLD)
            {
                mustRotateRight = false;
            }
        }

        transform.rotation = Quaternion.Euler(xAngle, 0f, zAngle);
    }
}

```

Inspector Values:

I've tried several things, the only problem I can think of is, gimbal lock. Thanks in advance.

# Answer
You can change your script with this code:

```
using UnityEngine;
using System.Collections;

public class CubeRotation : MonoBehaviour {

    private const float ROTATE_AMOUNT = 90f;

    [SerializeField, Header("Touch Quads Colliders")]
    private Collider touchQuadLeft;
    [SerializeField]
    private Collider touchQuadRight;

    [SerializeField, Space(10)]
    private float timeToRotate = 20;

    int layerMask;

    private void Start() {
        layerMask = LayerMask.GetMask("Touch Quad");
    }

    void Update() {
        ListenForTouch();
    }

    private void ListenForTouch() {
        if (Input.GetMouseButtonDown(0)) {
            Vector2 touchPoint = Input.mousePosition;
            RaycastHit rayCastHit;
            Ray ray = Camera.main.ScreenPointToRay(touchPoint);
            if (Physics.Raycast(ray, out rayCastHit, 150f, layerMask)) {
                if (rayCastHit.collider == touchQuadLeft) {
                    StartCoroutine(RotateCube(Vector3.forward));
                }
                else if (rayCastHit.collider == touchQuadRight) {
                    StartCoroutine(RotateCube(Vector3.right));
                }
            }
        }
    }

    IEnumerator RotateCube(Vector3 direction) {
        float step = ROTATE_AMOUNT / timeToRotate;
        for (float t = 0; t < ROTATE_AMOUNT; t += step) {
            transform.Rotate(direction, step, Space.World);
            yield return null;
        }
    }
}

```

This will always rotate the cube "upwards", and without bothering about Quaternions and such.

If you need further explanations about parts of the code, feel free to ask ofc.
> 0 votes

---
Tags: unity, rotation, gimbal-lock
---


title: How do I import a custom map into UE4?

text:
# Question
Title: How do I import a custom map into UE4?
I have seen videos on creating the map/level in UE4, but not how to import the map from something like maya. Would I have to import it as an object? I have been playing around in the editor but haven't been able to find any setting that seems to do the trick.

# Answer
> 1 votes
Export your map from Maya (or any other tool) as an FBX file. Ensure your scale is centimeters, or the map will be incorrectly scaled in Unreal. Now open Unreal, right-click in the Content Browser, and select Import.

Be aware that you cannot change map layout using this method; if you find errors or changes needed in layout or flow, you will need to make those changes in the external tool then reimport the FBX.

---
Tags: unreal-4, maya
---


title: undeclared identifier UBoxComponent

text:
# Question
Title: undeclared identifier UBoxComponent
I have created an Actor C++ component "PickUp". But there are few lines that are throwing errors. I have declared UShapeComponent, UStaticMeshComponent, USceneComponent, OnPlayerEnterPickUpBox() functions

```
#pragma once

#include "CoreMinimal.h"
#include "GameFramework/Actor.h"
#include "PickUp.generated.h"

UCLASS()
class YT_API APickUp : public AActor
{
    GENERATED_BODY()

public:
    // Sets default values for this actor's properties
    APickUp();

protected:
    // Called when the game starts or when spawned
    virtual void BeginPlay() override;

public:
    // Called every frame
    virtual void Tick(float DeltaTime) override;

    UPROPERTY(EditAnywhere)
    USceneComponent* PickUpRoot;

    UPROPERTY(EditAnywhere)
    UStaticMeshComponent* PickUpMesh;

    UPROPERTY(EditAnywhere)
    UShapeComponent* PickUpBox;

    UFUNCTION()
    void OnPlayerEnterPickUpBox(UPrimitiveComponent* OverlappedComp, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult& SweepResult );
};

```

This is the cpp files. Where all the code is written in constructor

```
#include "PickUp.h"

// Sets default values
APickUp::APickUp()
{
    // Set this actor to call Tick() every frame.  You can turn this off to improve performance if you don't need it.
    PrimaryActorTick.bCanEverTick = true;

    PickUpRoot = CreateDefaultSubobject<USceneComponent>(TEXT("PickupRoot"));
    RootComponent = PickUpRoot;

    PickUpMesh = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("PickupMesh"));

    PickUpMesh->AttachToComponent(PickUpRoot, FAttachmentTransformRules::SnapToTargetNotIncludingScale);

    PickUpBox = CreateDefaultSubobject<UBoxComponent>(TEXT("PickupBox"));
    PickUpBox->SetWorldScale3D(FVector(1.0f, 1.0f, 1.0f));
    PickUpBox->bGenerateOverlapEvents = true;
    PickupBox->OnComponentBeginOverlap.AddDynamic(this, &APickUp::OnPlayerEnterPickupBox);
    PickUpBox->AttachToComponent(PickUpRoot, FAttachmentTransformRules::SnapToTargetNotIncludingScale);
}

// Called when the game starts or when spawned
void APickUp::BeginPlay()
{
    Super::BeginPlay();

}

// Called every frame
void APickUp::Tick(float DeltaTime)
{
    Super::Tick(DeltaTime);

}

void APickUp::OnPlayerEnterPickUpBox(UPrimitiveComponent* OverlappedComp, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult& SweepResult )
{
    Destroy();
}

```

When I try to run this I get following errors:

```
Info Setting up Mono
Info /Users/Shared/Epic Games/UE_4.16/Engine /Users/Shared/Epic Games/UE_4.16/Engine/Binaries/Mac
Info Compiling game modules for hot reload
Info Parsing headers for YTEditor
Info   Running UnrealHeaderTool "/Users/abhimanyuaryan/Documents/Unreal Projects/YT/YT.uproject" "/Users/abhimanyuaryan/Documents/Unreal Projects/YT/Intermediate/Build/Mac/YTEditor/Development/YTEditor.uhtmanifest" -LogCmds="loginit warning, logexit warning, logdatabase error" -Unattended -WarningsAsErrors -installed
Info Reflection code generated for YTEditor in 7.82594 seconds
Info Performing 2 actions (8 in parallel)
Info [1/2] Compile PickUp.cpp
Info /Users/abhimanyuaryan/Documents/Unreal Projects/YT/Source/YT/PickUp.cpp:20:40: error: use of undeclared identifier 'UBoxComponent'; did you mean 'RootComponent'?
Info     PickUpBox = CreateDefaultSubobject<UBoxComponent>(TEXT("PickupBox"));
Info                                        ^~~~~~~~~~~~~
Info                                        RootComponent
Info Runtime/Engine/Classes/GameFramework/Actor.h:463:19: note: 'RootComponent' declared here
Info         USceneComponent* RootComponent;
Info                          ^
Info /Users/abhimanyuaryan/Documents/Unreal Projects/YT/Source/YT/PickUp.cpp:20:17: error: no matching member function for call to 'CreateDefaultSubobject'
Info     PickUpBox = CreateDefaultSubobject<UBoxComponent>(TEXT("PickupBox"));
Info                 ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Info /Users/Shared/Epic Games/UE_4.16/Engine/Source/Runtime/CoreUObject/Public/UObject/Object.h:81:15: note: candidate template ignored: invalid explicitly-specified argument for template parameter 'TReturnType'
Info         TReturnType* CreateDefaultSubobject(FName SubobjectName, bool bTransient = false)
Info                      ^
Info /Users/Shared/Epic Games/UE_4.16/Engine/Source/Runtime/CoreUObject/Public/UObject/Object.h:95:15: note: candidate template ignored: invalid explicitly-specified argument for template parameter 'TReturnType'
Info         TReturnType* CreateDefaultSubobject(FName SubobjectName, bool bTransient = false)
Info                      ^
Info 2 errors generated.

```

# Answer
> 1 votes
You have defined PickupBox as a UShapeComponent\* in the header, yet you are casting it to a UBoxComponent in the CPP.

Change the header to match the variable type you ultimately want (in other words, change the header to UBoxComponent\* PickupBox).

Addendum: UShapeComponent is a parent of UBoxComponent. It does not define shapes itself, that is why you must use (and cast to) the child class to detect collisions. See https://docs.unrealengine.com/latest/INT/API/Runtime/Engine/Components/UShapeComponent/index.html

---
Tags: c++, unreal-4, unreal
---


title: In Game Window Frame Size Consistency

text:
# Question
Title: In Game Window Frame Size Consistency
I'm currently building a game that utilizes many of its own 'windows' to display various information and dialogue to the user. Since there are multiple sizes and proportions these windows must be displayed at, we need a consistent way to draw the frame around the window itself so that it does not become stretched as we change the default size/proportion of the art asset during runtime.

The solution we have currently come up with is drawing the frame in pieces, and the background of the windows separately. We would have the background, a 'corner piece', and a 'connector piece'. The background would be drawn and resized to whatever size and proportion not caring about if this particular piece was stretched . The corner would be drawn and rotated to fit at each corner of the window. Finally the connectors would be 1 pixel wide pieces that would be drawn and rotated/stretched to fill the gap between the 4 corner pieces.

While I feel this is an adequate solution to the problem I am not sure if this is the solution most games use when they have windows they would like to keep consistently framed. Is there a more commonplace solution for this issue, or does what we've come up with pretty much nail it on the head?

# Answer
> 1 votes
This is a common pattern; in Flash it is called 9-slice scaling, and in Unity it is called 9-slicing. If you ever implement it in 3D as opposed to 2D, 27-slice scaling is the appropriate term. It is undoubtedly implemented in countless other UI APIs across all known languages / platforms.

So yes, you are on exactly the right track, although you may wish to check if there is a UI library that already does this for you, rather than you having to do it yourself, given what a common pattern it is.

---
Tags: c++, rendering, windows
---


# Question
Title: Why is the sprite flickering in full screen mode in SFML?
I have been trying to make a simple platformer game with SFML. Here is my main method where draw and update functions call the draw and update functions of all my entities which in turn update the variables and draw updates the position of the sprite which is to be rendered.

```
int main() {
sf::RenderWindow window(sf::VideoMode(0, 0), "My First SFML Game", sf::Style::Fullscreen);
int frames = 0;

if(!init()) {
    std::cout << "Could not initialize\n";
    return 1;
}

sf::Clock clock, frameClock;

while(window.isOpen()) {
    sf::Event event;
    while(window.pollEvent(event)) {
        switch(event.type) {
        case sf::Event::Closed:
            window.close();
            break;
        case sf::Event::KeyPressed:
            if(event.key.code == sf::Keyboard::Escape)
                window.close();
            break;
        }
    }

    //keyboard handler
    if(sf::Keyboard::isKeyPressed(sf::Keyboard::Left)) {
        if(player->velX > -7) player->velX--;
    }
    else if(sf::Keyboard::isKeyPressed(sf::Keyboard::Right)) {
        if(player->velX < 7) player->velX++;
    }

    if(frameClock.getElapsedTime().asSeconds() >= 1/FPS) {
        update();
        draw(window);
        window.display();
        window.clear();

        frames++;
        frameClock.restart();
    }

    if(clock.getElapsedTime().asSeconds() >= 1) {
        std::cout << frames << " frames per second\n";
        clock.restart();
        frames = 0;
    }
}
}

```

There is a strange flicker when I press left or right arrow keys (actually, almost every second). However, it did not happen when I repeatedly pressed prt sc. It also does not happen when with that much intensity (but it still happens a little bit) when I switch out of the full screen mode.

# Answer
I enabled vertical sync by `window.setVerticalSyncEnabled`. It gives a low frame rate when you are not in full screen mode. The frame rate returns to normal in the full screen mode and it does not flicker so yay!
> 1 votes

---
Tags: c++, sfml
---


title: How to create a button in SFML?

text:
# Question
Title: How to create a button in SFML?
How can I get clickable buttons working in SFML? I've failed figuring it out on my own. At first I tried just putting in text and then I tried an image for the Exit button. Neither of them work in the `sf::Event::MouseMoved` event. I want the exit button to highlight a different color when I mouse over it but it just flickers every time the mouse moves whether its in the coordinates or not. Also, doing a `sf::FloatRect = exitButtonImage.getRect();` seems to not work either.

```
#include <SFML\Graphics.hpp>
#include <SFML\Audio.hpp>
#include <string>
#include <iostream>

int main()
{
    sf::RenderWindow window(sf::VideoMode(1024, 622), "Survival Game", sf::Style::Default);

    sf::Texture background;
    sf::Sprite backgroundImage;

    if (!background.loadFromFile("Alaskan Wilderness.png"))
        std::cout << "Error: Could not display Alaskan Wilderness image" << std::endl;

    backgroundImage.setTexture(background);

    while (window.isOpen())
    {
        sf::Font font;
        if (!font.loadFromFile("MATURASC.TTF"))
            std::cout << "Can't find the font file" << std::endl;

        sf::Texture exitButton;
        sf::Sprite exitButtonImage;
        if (!exitButton.loadFromFile("Exit Button.png"))
            std::cout << "Can't find the image" << std::endl;
        exitButtonImage.setPosition(50.0f, 500.0f);

        float exitButtonWidth = exitButtonImage.getLocalBounds().width;
        float exitButtonHeight = exitButtonImage.getLocalBounds().height;

        exitButtonImage.setTexture(exitButton);

        sf::Text startText;
            startText.setFont(font);
            startText.setStyle(sf::Text::Bold);
            startText.setString("Create New Game");
            startText.setFillColor(sf::Color::Black);
            startText.setCharacterSize(48);
            startText.setPosition(50.0f, 320.0f);
        sf::Text loadText;
            loadText.setFont(font);
            loadText.setStyle(sf::Text::Bold);
            loadText.setString("Load Game");
            loadText.setFillColor(sf::Color::Black);
            loadText.setCharacterSize(48);
            loadText.setPosition(50.0f, 380.0f);
        sf::Text settingsText;
            settingsText.setFont(font);
            settingsText.setStyle(sf::Text::Bold);
            settingsText.setString("Settings");
            settingsText.setFillColor(sf::Color::Black);
            settingsText.setCharacterSize(48);
            settingsText.setPosition(50.0f, 440.0f);

        sf::Event Event;
        while (window.pollEvent(Event))
        {
            switch (Event.type)
            {
            case sf::Event::Closed:
                window.close();
                break;
            case sf::Event::MouseMoved:
                sf::Vector2i mousePos = sf::Mouse::getPosition(window);
                bool mousePositionExit = mousePos.x == exitButtonWidth && mousePos.y == exitButtonHeight;
                if (sf::Mouse::getPosition(window).x > exitButtonImage.getGlobalBounds().left &&
                    sf::Mouse::getPosition(window).x < exitButtonImage.getGlobalBounds().left +
                    exitButtonImage.getGlobalBounds().width && sf::Mouse::getPosition().y >
                    exitButtonImage.getGlobalBounds().top && sf::Mouse::getPosition(window).y
                    < (exitButtonImage.getGlobalBounds().top + exitButtonImage.getGlobalBounds().height));
                {
                    exitButtonImage.setColor(sf::Color(250, 20, 20));
                    window.draw(exitButtonImage);
                }
                break;
            }
        }

        window.clear();
        window.draw(backgroundImage);
        window.draw(exitButtonImage);
        window.draw(startText);
        window.draw(loadText);
        window.draw(settingsText);
        window.display();
    }
    return 0;
}

```

# Answer
The *first* thing to note, is that you have a `;` after an if statement, *before* the code for the `true` condition. This means that the `if` line is useless, and that code for the `true` condition will *always* be executed.

Removing that semi-column will be our first step.

The second thing to note is that you don't need all that code for the *if* condition. SFML offers a `contains` method on the rectangle which returns `true` if the vector passed is in the rectangle. This really reduces the code and improves readability and reliability.

The third thing to note is that the `window.draw( exitButtonImage );` is useless in that `if( isOver )` condition because you'll draw it anyway at the end of the while.

The fourth thing to note is that, with the previous changes, the button will become 'red' only when you *actually* move the mouse over it. We need a way to preserve the state. This is nice because...

The fifth thing to note is that the code is doing a very bad usage of memory allocation and disk access. The creation of your buttons could be done only once, with the objects *reused* every frame, instead of being *recreated* every frame.

We'll take the text and image creation outside of the `while ( window.isOpen() )`. This will allow us to keep the state of the `exitButtonImage` from frame to frame. If the mouse moves over the exit button, it will set it to 'red', and if we stop moving the mouse, no more mouse event are received, so the last state stays in place. Nice, our button stays put!

But that causes another bug: the button does not get back to its 'pristine' state when we mouse-out.

To fix that, we simply add an `else` to the 'mouse move and mouse is over the button' `if`: `exitButtonImage.setColor( sf::Color( 255, 255, 255 ) );`. This will put the button in it's original state.

With that, you only need to detect the 'click' event, and you'll have something usable.

*Note that this is a bit of a hackish way of doing things as you'll change the colour of the button every frame the mouse moves, whether you actually need to change it or not, which may take up more resources than needed. I think in your situation it's fine to go that way, though; you can ignore this small issue for now.*

That's basically what I had to say about your code :)

---

For your convenience, here is the code I think you wanted to write:

```
#include <SFML/Graphics.hpp>
#include <SFML/Audio.hpp>
#include <string>
#include <iostream>

int main()
{
  sf::RenderWindow window( sf::VideoMode( 1024, 622 ), "Survival Game", sf::Style::Default );

  sf::Texture background;
  sf::Sprite backgroundImage;

  if ( !background.loadFromFile( "Alaskan Wilderness.png" ) )
    std::cout << "Error: Could not display Alaskan Wilderness image" << std::endl;

  backgroundImage.setTexture( background );

  sf::Font font;
  if ( !font.loadFromFile( "MATURASC.TTF" ) )
    std::cout << "Can't find the font file" << std::endl;

  sf::Texture exitButton;
  sf::Sprite exitButtonImage;
  if ( !exitButton.loadFromFile( "Exit Button.png" ) )
    std::cout << "Can't find the image" << std::endl;
  exitButtonImage.setPosition( 50.0f, 500.0f );

  float exitButtonWidth = exitButtonImage.getLocalBounds().width;
  float exitButtonHeight = exitButtonImage.getLocalBounds().height;

  exitButtonImage.setTexture( exitButton );

  sf::Text startText;
  startText.setFont( font );
  startText.setStyle( sf::Text::Bold );
  startText.setString( "Create New Game" );
  startText.setFillColor( sf::Color::Black );
  startText.setCharacterSize( 48 );
  startText.setPosition( 50.0f, 320.0f );
  sf::Text loadText;
  loadText.setFont( font );
  loadText.setStyle( sf::Text::Bold );
  loadText.setString( "Load Game" );
  loadText.setFillColor( sf::Color::Black );
  loadText.setCharacterSize( 48 );
  loadText.setPosition( 50.0f, 380.0f );
  sf::Text settingsText;
  settingsText.setFont( font );
  settingsText.setStyle( sf::Text::Bold );
  settingsText.setString( "Settings" );
  settingsText.setFillColor( sf::Color::Black );
  settingsText.setCharacterSize( 48 );
  settingsText.setPosition( 50.0f, 440.0f );

  while ( window.isOpen() )
  {
    sf::Event Event;
    while ( window.pollEvent( Event ) )
    {
      switch ( Event.type )
      {
      case sf::Event::Closed:
        window.close();
        break;
      case sf::Event::MouseMoved:
        {
          sf::Vector2i mousePos = sf::Mouse::getPosition( window );
          sf::Vector2f mousePosF( static_cast<float>( mousePos.x ), static_cast<float>( mousePos.y ) );
          if ( exitButtonImage.getGlobalBounds().contains( mousePosF ) )
          {
            exitButtonImage.setColor( sf::Color( 250, 20, 20 ) );
          }
          else
          {
            exitButtonImage.setColor( sf::Color( 255, 255, 255 ) );
          }
        }
        break;
      case sf::Event::MouseButtonPressed:
        {
          sf::Vector2i mousePos = sf::Mouse::getPosition( window );
          sf::Vector2f mousePosF( static_cast<float>( mousePos.x ), static_cast<float>( mousePos.y ) );
          if ( exitButtonImage.getGlobalBounds().contains( mousePosF ) )
          {
            std::cout << "Clicked, yay!" << std::endl;
          }
        }
        break;
      }
    }

    window.clear();
    window.draw( backgroundImage );
    window.draw( exitButtonImage );
    window.draw( startText );
    window.draw( loadText );
    window.draw( settingsText );
    window.display();
  }
  return 0;
}

```

This only manages the exit button that you wanted to create, but a lot of programming is generally done by monkey-see-monkey-do, so I assume you'll be able to adapt the code.

---

I'll end this answer by noting that it might not be the most optimal way of doing what you want, architecturally speaking, but since you're just starting, you'll find ways to improve your software as you see fit.
> 4 votes

# Answer
First off, i don't recommend to call `loadFromFile()` function in the window loop, it'll read the file every frame.

Next, your problem lies if you set the color on the `pollEvent()` loop. The `pollEvent()` loop may not execute when there's no event, which in your case cause flickering when you move the mouse. Try it with a `bool` variable, set it to true when it's over the button and false otherwise. And `draw()` function should be outside the `pollEvent()` loop (Your draw function that's inside the `pollEvent()` loop doesn't matter anyway, because you cleared it again afterwards).

```
bool mouseOverButton = false;
// load files
while (window.isOpen()) {
    // Setting up buttons
    sf::Event e;
    while (window.pollEvent(e)) {
        switch (Event.type)
        {
        case sf::Event::Closed:
            window.close();
            break;
        case sf::Event::MouseMoved:
            // If mouse is over
                mouseOverButton = true;
            // If not
                mouseOverButton = false;
            break;
        }
    }
    // Check mouseOverButton and setFillColor or setTexture accordingly
    window.draw(button);
    window.display();
}

```

Edit: Changing the color inside the `pollEvent()` loop is actually fine **if** you declare your button outside the window loop to avoid being created each time with default color.
> 0 votes

---
Tags: c++, sfml
---


# Question
Title: Using multiple indexes with buffer objects in OpenTK
I've got multiple buffers in OpenGL holding data on position, normals and texcoords.

I also have an equal number of buffers holding distinct index data for each of those buffers.

I quite like this format (indvidual indexes for each buffer) utilised by COLLADA since it strikes me as optimally efficient at accessing each buffer.

I've set up pointers to the relevant data arrays using VertexPointer, NormalPointer, etc however I have no way to assign pointers to the index buffers since DrawElements appear to only look at one ElementArrayBuffer.

Can I utilise multiple indices some way or will I be better off using a different technique which can support this? I'd prefer to keep the distinct indices if at all possible.

# Answer
> 1 votes
You can have bound only one index array at a time. So you cann't use separate index array for each vertex attribute. So only choice is to rearrange all arrays according to one index array.

# Answer
> 1 votes
I know this is really old, but for those googling.

I'm fairly sure you can just bind multiple EBO's to a single VAO.

(in OpenTK, but it would be something like this):

```
        GL.BindVertexArray(vao);

        // Vertices
        GL.BindBuffer(BufferTarget.ArrayBuffer, vbo);
        GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)(vertices.Length * Vertex.SizeInBytes), vertices, BufferUsageHint.StaticDraw);
        GL.BindBuffer(BufferTarget.ArrayBuffer, 0);

        // Indices
        GL.BindBuffer(BufferTarget.ElementArrayBuffer, ibo);
        GL.BufferData(BufferTarget.ElementArrayBuffer, (IntPtr)(indices.Length * sizeof(uint)), indices, BufferUsageHint.StaticDraw);

        // Second lot of indices
        GL.BindBuffer(BufferTarget.ElementArrayBuffer, ibo2);
        GL.BufferData(BufferTarget.ElementArrayBuffer, (IntPtr)(indices2.Length * sizeof(float)), indices2, BufferUsageHint.StaticDraw);

        GL.BindVertexArray(0);

        // Remember to unbind ebo AFTER vao, not before
        GL.BindBuffer(BufferTarget.ElementArrayBuffer, 0);

```

Now all you have to do is use the DrawElements function for each set of indices, or like The Fiddler said above use MultiDrawElements.

# Answer
> 0 votes
GL.MultiDrawElements should be able to do this. Check out the documentation for this function.

---
Tags: opengl, opentk, vbo
---


# Question
Title: Is state change command less reliable than sending the entire state?
I'm asking for a game that I develop right now. The game is using TCP communication, there's server and multiple clients. While players in a room are playing the game, I send state update commands in a custom binary protocol every 33 ms. (30 FPS) Problem is those states are huge - there are players moving, objects spawning and also destructible blocks.

If I were to send all this data a single state update to every player will be huge, resulting in huge bandwidth.

So I'm thinking different approach:

1. Initially send the huge state with all moving and stationary objects, when the room starts
2. Do the state update commands every 33 ms, but include just the moving objects, and **not** include the state and location of the stationary objects.
3. For stationary objects, issue separate commands to tell they are destroyed or spawned and expect clients to update their copy of the state.

My concern is that it may somehow happen that due to not including the stationary objects in every state update, clients may somehow miss the separate commands that update on those and not reflect that change in their copy of the state.

Here is a visual representation of what I imagine:

Less bandwidth (is it less reliable?):

```
game started -> obj1 {id,location}, obj2{id,location}, obj3{id,location}
state update 1 -> obj1 {id,location}, obj2{id,location} #assumes obj3 is there
state update 2 -> obj1 {id,location}, obj2{id,location} #assumes obj3 is there
state update 3 -> obj1 {id,location}, obj2{id,location} #assumes obj3 is there
object removed -> obj3 #removing the object locally
state update 4 -> obj1 {id,location}, obj2{id,location} #obj3 not present at this point

```

More bandwidth - include all objects in every state update and assume if something is not present, it has been removed (is it more reliable?):

```
game started -> obj1 {id,location}, obj2{id,location}, obj3{id,location}
state update 1 -> obj1 {id,location}, obj2{id,location}, obj3{id,location}
state update 2 -> obj1 {id,location}, obj2{id,location}, obj3{id,location}
state update 3 -> obj1 {id,location}, obj2{id,location} #obj3 is not here, so removing it locally
state update 4 -> obj1 {id,location}, obj2{id,location} #obj3 not present at this point

```

# Answer
I guess most will agree that one should (basically) never re-send information that was already sent. Distributing only the changes produces a correct end result, provided the changes went through successfully. Obviously :-). It's a matter of the greed every game coder must have. Never ever do anything unnecessary.

As you know, TCP is problematic in the sense that it struggles for an eternity to perform well (and btw adds latency for the sake of being a good network citizen). But things change rapidly inside a game. Nobody cares about old, outdated data, it is a much worth as no data. Maybe consider UDP, or a hybrid of TCP and UDP?

I understand your concern, everyone does and everyone knows it. What to do with the lag, network errors, high ping bastards? 95% got the Go signal, how to deal with that 5 %?

Depends on your game, goals, business, whatnot. Apparently, one wants to give them an as good experience as possible?

Hence, you must make the system tolerant. Ofc, one could just kick out the erratic cases, but that would be a bit brutal. So one wants to keep it all alive, even if something's wrong.

An object should be allowed to become "unstable", "unreliable". But how that affects the game logic, is a thing only you know.

Imho there is no simple answer to your question. Basically:

* consider (and read on) the TCP. It delivers, no matter what. But are you willing to wait, if there are problems? Are you willing to make a deal with TCP, as your only delivery service?
* send changes only (at least mostly; naturally, a full set occasionally is not at all forbidden). Pre-calc, cache, sparsify, persist. Maybe let the actual change event raise and time a transmission?
* can always transmit tiny checksums to pack/inform a snapshot of multiple states. Endpoints (server, peer) can calc them individually, locally; compare with the checksum they got in and react on a mismatch =\> something has changed (after which a peer can ask for an update, etc., to fix the problem).
* have the game objects be "impatient", "self-aware". Meaning they count their time and timeout, to ask for new data, if they didn't get any attention for some time.
* "grey out" untrustworthy objects/states, both visually and logically (meaning in the maths). This is where the tolerance comes in...

Never forget rule #1: Add fog

(Ie: Hide the problems. Not literally by using fog, but by using whatever smart actions available)

---

Edit, in reply to the comment.

Logically, TCP guarantees delivery, untill a timeout that would best be called "long hang". Additionally, TCP delivers in the correct order. Hence, the logical chain of events will not be broken (but the timing between peers may cause issues, see below). Nevertheless, TCP allows you to distribute changes only, in a safe manner. The communication in itself maintains the validity checking, and the assumption is that the computer receiving the data cannot calculate erratically if received correct data -\> no further errors will occur.

Timing issues: I guess people who consider you case think further, as i did too. There are "what if"-questions related to the overall functionality. But if leaving them on the discussion side only, the answer to your sole question is that sending changes only is as safe as "it can be". In addition, the fact that less data was sent, in fact increases the overall performance, reducing chances for problems.
> 2 votes

# Answer
> But are there cases where the client and server states become different? (for instance lost command or something else).

**If you are using floating point without controlling every detail tightly / correctly, then yes, you may well need regular re-syncing.** Floating point primarily creates problems in respect to rounding and order of arithmetic operations. (Related to incorrect ordering of operations and thus also potentially causing unwanted effects in systems built on floating point arithmetic, are non-deterministic threading solutions like OpenMP; c.f. libDOMP thesis). IEEE-754 floating point can be (according to most sources, note the varied answers here) deterministic, but it's generally how you work with it that can cause serious issues; see various game dev articles around the web on float determinism. See libfixmath which may help you avoid the usual implications of IEEE-754 floating point.

**About TCP**

Really your question perhaps should be, "Can TCP ever fail to deliver packets?" I can only repeat what another here has already said: TCP is *reliable*, that is, it will *not* allow any messages to go undelivered (UDP, OTOH, will allow that). So if there's a failure, it's not on TCP's part, but on the part of your code. TCP waits (indefinitely, potentially) till it receives the appropriate packet in a sequence. No matter how many packets are lost on the wire, TCP (unless managed otherwise) will keep on waiting till the user-specified timeout is reached (usually on the order of several minutes).

**Further to your question**

It's perfectly normal to do state catch up every so often, even with deltas, if there is any chance that your application doesn't catch all cases you would hope. You can even have players set the frequency (every n minutes) in the lobby, but ultimately the more frequently you do it, the less likely you are to experience a checksum mismatch / sync fault, so you may want to fix the frequency accordingly.

You should pay more attention to building systems through which all traffic is routed, and which thus act as a basis for comparison so that you are able to catch, in retrospect, exactly what went wrong, and when. Determinism, logging and diffing, are essential aspects of distributed development. So in your particular use case, you can own the problem and the solution by *knowing what is happening at all times* and being able to track a problem down in the very frame it goes wrong.

You may also want to look into the benefits that peer-to-peer lockstep brings in this regard. And no, if your simulation is built correctly, you should never need to update immovable objects *unless* they spawn or despawn. (The same actually applies to moving objects, as spawn / despawn is a separate class of thing from motion / firing.)

**Re your proposed message approach**

**For Peer-to-Peer,** if you simply leave certain entities out, what if the receiver has reason to believe those entities still exist, but the sender does not? This immediately becomes a point of contention. I suppose it could be made to work, but I think it is more important to treat all your networked communications as a concept of *state changes* or *deltas* rather than sending full state while assuming that if certain things are missing from that state, they should naturally be destroyed by other clients then and there. When we talk about spawn/despawn for example, that there is a *delta*.

**For authoritative client-server**, your approach makes sense. However, for the "fire-and-forget" style of comms you are suggesting, a connectionless protocol like UDP may make more sense than TCP.
> 1 votes

---
Tags: networking, client-server
---


# Question
Title: Child GameObject doesn't follow parent's transform
Look at this picture first:

I have model that has sword in his hand. I added a cube named "Attack Collision" and located to blade position. And then set the hand to parent.

But when the game starts, sword moves but it's children "Attack Collision" doesn't move at all.

The funny thing is in the scene, I tried to move the "sword", but only it's children "Attack Collision" was moved.

Seems like the sword is somekind of locked, because it's transform can be change but not applied at all, it's just stand still there and only it's children that made from Unity was moved like this:

I made this model and animation by Blender and imported to Unity as .FBX file.

What am I missing?

# Answer
Finally I solved! It's quite surprising how easy to make it. The simplest way to solve this problem is attach Attack Collistion GameObject into the bone(armature), not a actual weapon.

I accidently saw the animations were made from Blender into Unity by Animation tab and saw every rotation were only applied to bones.

So I added a Attack Collistion object and child to that bone(weapon), it's perfectly working.
> 1 votes

---
Tags: unity, animation, rotation, transformation
---


# Question
Title: How to increase vertical Nav Mesh detection for AI Actors? Using Default Query Extent?
For my swimming AI, I wish to use a Nav Mesh, so they may avoid obstacles and swim up and down - preferably.

I figured I should try to solve this with a nav mesh, since UE4 has kindly implemented it for us.

To avoid having the Enemy Fish stick to the "ground" of the map, I would have to increase the `Query Extent`, which is testable with a `Navigation Testing Actor` *(see images below)*.

So what I did:

* Add `Nav Mesh Bounds` volume;
* Add AI Actor with Character Movement Component;
* Increase `Default Query Extent` in Project Settings (Engine \> Navigation System).
* No Profit?

Increasing the `Default Query Extent`, under `Agents`, increases it along the positive and negative *Z-Axis*, which is unfortunate, since I would like the AI to prioritize the bottom Nav Mesh surface.

---

I have attached two screenshots showcasing the "bad" behaviour, which I would like to circumvent.

The blue Bounding Box, showcases the *Extent*, which is scaled in both directions, vertically. Preferably, I would like to move it down, relative to the `Nav Agent`.

To hit the point home, here is what happens when the enemy swims underneath some platform *(For simplicity, being the cube)*:

So my question to you good people is: how would I lower the Nav Mesh detection, without increasing the actor size, or something rather silly. Is there a clean way of having the "Enemy Fish" ignore the top platform as much as possible, without using a `Nav Modifier Volume` ?

# Answer
> 0 votes
Unreal allows for several Nav meshes to exist in the same space. Look into the Project Settings, to try defining a different "swimming" AI nav for each fish.

Let's say you have a mackerel and a whale - both aquatic animals, both in the same space. However the mackerel can get into smaller spaces than the whale. If you use a single navmesh for both, either the mackerel will stick to open waters or the whale will clip into places it should never reach. The solution is to define a separate nav mesh for each animal.

This is where I would begin. Additionally, ask the question "Does the nav need to be walkable or can it be a 3D space for flying?" Walkable space is effectively a planar structure (visually), whereas a flying space is a volume.

---
Tags: unreal-4, unreal, navmesh
---


title: Unity Marching Cubes triangulation bug

text:
# Question
Title: Unity Marching Cubes triangulation bug
So, well I've been trying to find out the reason of the following bug in my marching cubes implementation, but I can't figure it out.

Now this is a two state implementation of MC (just two exact isovalues 0 or 1) and the isovalue of the cells at the blue triangles are 0 means that they don't have to be triangulated. But they are for some reason. Therefore they got a fallback texture. But it's been a long time since I'm trying to figure this out, so if you have any idea please share it with me. Here is the code of my MC implementation.

```
    public class MarchingCubes
    {
private Region region;
private Chunk chunk;

private Mesh mesh = new Mesh ();

private List<Vector3> vertices = new List<Vector3> ();
private List<int> triangles = new List<int> ();
private List<Vector2> uvs = new List<Vector2> ();
private ValPair[] pairs = new ValPair[8];
private Debugger debugger;

private int chunkSize = 16;
private float isolevel = 1f;

public MarchingCubes (Debugger debugger)
{
    this.debugger = debugger;
}

private float CornerValue (Vector3i pos)
{
    int x = pos.x;
    int y = pos.y;
    int z = pos.z;

    if (y < 0 || y >= 128)
        return 0f;

    if (x >= 0 && x < chunkSize && z >= 0 && z < chunkSize) {
        return chunk.GetValue (x, y, z);
    } else {
        Chunk neighbor = null;
        int ix = chunk.X (), iz = chunk.Z ();
        if (x < 0) {
            ix--;
            if (ix == -1)
                return 0f;
            x = 16;
        }
        if (z < 0) {
            iz--;
            if (iz == -1)
                return 0f;
            z = 16;
        }
        if (x >= chunkSize) {
            ix++;
            if (ix == region.regionSize)
                return 0f;
            x = 0;
        }
        if (z >= chunkSize) {
            iz++;
            if (iz == region.regionSize)
                return 0f;
            z = 0;
        }
        neighbor = region.GetChunk (ix, iz);
        return neighbor.GetValue (x, y, z);
    }
}

struct ValPair
{
    public Vector3 position;
    public float intsect;
}

public Mesh Render (Region region, Chunk chunk)
{
    this.region = region;
    this.chunk = chunk;

    vertices.Clear ();
    triangles.Clear ();
    uvs.Clear ();
    Cell cell;
    Block block;

    for (int x = 0; x < chunkSize; x++) {
        for (int z = 0; z < chunkSize; z++) {
            for (int y = 0; y <= chunk.GetRow(x, z).GetHeight(); y++) {
                cell = chunk.GetRow (x, z).GetCell (y);
                block = cell.GetBlock ();

                int cubeIndex = 0;

                for (int i = 0; i < 8; i++) {
                    pairs [i].intsect = CornerValue (new Vector3i (x, y, z) + offset [i]);
                    if (pairs [i].intsect < isolevel)
                        cubeIndex += 1 << i;
                }

                if (cubeIndex == 0 || cubeIndex == 255)
                    continue;

                for (int i = 0; i < 8; i++) {
                    pairs [i].position = (new Vector3i (x, y, z) + offset [i]).ToVector3 ();
                }

                Vector3[] vertlist = new Vector3[12];
                if ((edgeTable [cubeIndex] & 1) == 1)
                    vertlist [0] = VertexInterp (pairs [0], pairs [1]);
                if ((edgeTable [cubeIndex] & 2) == 2)
                    vertlist [1] = VertexInterp (pairs [1], pairs [2]);
                if ((edgeTable [cubeIndex] & 4) == 4)
                    vertlist [2] = VertexInterp (pairs [2], pairs [3]);
                if ((edgeTable [cubeIndex] & 8) == 8)
                    vertlist [3] = VertexInterp (pairs [3], pairs [0]);
                if ((edgeTable [cubeIndex] & 16) == 16)
                    vertlist [4] = VertexInterp (pairs [4], pairs [5]);
                if ((edgeTable [cubeIndex] & 32) == 32)
                    vertlist [5] = VertexInterp (pairs [5], pairs [6]);
                if ((edgeTable [cubeIndex] & 64) == 64)
                    vertlist [6] = VertexInterp (pairs [6], pairs [7]);
                if ((edgeTable [cubeIndex] & 128) == 128)
                    vertlist [7] = VertexInterp (pairs [7], pairs [4]);
                if ((edgeTable [cubeIndex] & 256) == 256)
                    vertlist [8] = VertexInterp (pairs [0], pairs [4]);
                if ((edgeTable [cubeIndex] & 512) == 512)
                    vertlist [9] = VertexInterp (pairs [1], pairs [5]);
                if ((edgeTable [cubeIndex] & 1024) == 1024)
                    vertlist [10] = VertexInterp (pairs [2], pairs [6]);
                if ((edgeTable [cubeIndex] & 2048) == 2048)
                    vertlist [11] = VertexInterp (pairs [3], pairs [7]);

                for (int i = 0; triTable [cubeIndex, i] != -1; i += 3) {
                    int index = vertices.Count;

                    vertices.Add (vertlist [triTable [cubeIndex, i]]);
                    vertices.Add (vertlist [triTable [cubeIndex, i + 1]]);
                    vertices.Add (vertlist [triTable [cubeIndex, i + 2]]);

                    float tec = (0.25f);
                    Vector2 uvBase;
                    if (debugger.useDebugUVs) {
                        uvBase = debugger.debugUV;
                    } else {
                        if (block != null) {
                            uvBase = block.UV;
                        } else {
                            uvBase = debugger.debugUV;
                        }

                        uvs.Add (uvBase);
                        uvs.Add (uvBase + new Vector2 (0, tec));
                        uvs.Add (uvBase + new Vector2 (tec, tec));

                        triangles.Add (index + 0);
                        triangles.Add (index + 1);
                        triangles.Add (index + 2);
                    }
                }
            }
        }
    }
    mesh.Clear ();
    mesh.vertices = vertices.ToArray ();
    mesh.triangles = triangles.ToArray ();
    mesh.uv = uvs.ToArray ();
    mesh.RecalculateNormals ();
    mesh.RecalculateBounds ();
    return mesh;
}

bool IsBitSet (int b, int pos)
{
    return ((b & pos) == pos);
}

Vector3 VertexInterp (ValPair pair1, ValPair pair2)
{
    float mu;
    Vector3 p = new Vector3 ();
    if (Mathf.Abs (isolevel - pair1.intsect) < 0.00001)
        return pair1.position;
    if (Mathf.Abs (isolevel - pair2.intsect) < 0.00001)
        return pair2.position;
    if (Mathf.Abs (pair1.intsect - pair2.intsect) < 0.00001)
        return pair1.position;

    mu = (isolevel - pair1.intsect) / (pair2.intsect - pair1.intsect);
    p.x = (float)(pair1.position.x + mu * (pair2.position.x - pair1.position.x));
    p.y = (float)(pair1.position.y + mu * (pair2.position.y - pair1.position.y));
    p.z = (float)(pair1.position.z + mu * (pair2.position.z - pair1.position.z));
    return p;
}

public Mesh ToMesh (Mesh mesh)
{
    if (mesh == null)
        mesh = new Mesh ();
    mesh.Clear ();
    mesh.vertices = vertices.ToArray ();
    mesh.triangles = triangles.ToArray ();
    mesh.uv = uvs.ToArray ();
    mesh.RecalculateNormals ();
    mesh.RecalculateBounds ();
    return mesh;
}

```

Any other rotated versions of the specific case are seeable.

# Answer
> 1 votes
I came across the same problem when developing my own system - the bug came from the order of the triangles index. I know it can sounds odd, but try tweaking them and you will see that the rendering will change as well.

"Which side a triangle is visible from is determined by the orientation of its vertex indices. By default, if they are arranged in a clockwise direction the triangle is considered to be forward-facing and visible. Counter-clockwise triangles are discarded so we don't need to spend time rendering the insides of objects, which are typically not meant to be seen anyway."

For further reading, you can refer to http://catlikecoding.com/unity/tutorials/procedural-grid/

---
Tags: unity, bug, marching-cubes
---


# Question
Title: Move an object towards a point relative to its position
I am attempting to move an object a set distance in a direction relative to the objects current position. In other words I want the object to move to whatever point is 144 pixels below the object, and then stop moving. How can I do this?

# Answer
> 1 votes
144 pixels is a very relative thing. Firstl the closer the viewer is to an object the more pixels the obj takes, therefore the less its gonna move. Secondly the resolutions changes from one pc to another (or phone to another). Third, if the object is not on the screen, it isn't gonna move.

I suggest you just take the object's current position and decrease it how much you want. Every engine will let you do it, on Unity you can use transform.position. Google it so you can be sure of what you're doing

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


# Question
Title: Am I using libGDX Asset Manager correctly?
My understanding is that you initialize the AssetManager as a non-static object in your main class and load the sprites you need...

```
    manager = new AssetManager();
    manager.load("sprite_sheet.txt", TextureAtlas.class);
    manager.finishLoading();

```

I then modified my abstract State class by adding AssetManager to the constructor...

```
 State(GameStateManager gsm, AssetManager manager) {
    this.gsm = gsm;
    this.manager = manager;

```

Now say I have 5 blocks in my sprite sheet called block0, block1... block5 would it be appropriate to create a BlockTextures class like this?

```
private static TextureAtlas textureAtlas;

public BlockTextures(AssetManager manager) {
    textureAtlas = manager.get("sprite_sheet.txt", TextureAtlas.class);
}

public static AtlasRegion get(int id) {
    return textureAtlas.findRegion("block" + id);
}

public static void dispose() {
    textureAtlas.dispose();
}

```

Where I call BlockTextures.dispose() in my Game.dispose() method?

```
public void dispose() {
    BlockTextures.dispose();
}

```

While this code seems to work fine I feel like I am not using AssetManager correctly.

# Answer
> 1 votes
While you certainly can do what you're doing I would suggest that you pass your `AssetManager` around yo the classes that need to load resources instead. So instead of doing `BlockTextures.get(id);` where you need to use the texture you should instead pass the `AssetManager` and do

```
// Store this variable
TextureAtlas atlas = manager.get(name, TextureAtlas.class);

//Use the Atlas later as you would normally
atlas.whatever();

```

It is also **crucial** that you don't dispose individual assets using their `dispose` method. Instead dispose of the `AssetManager` or use the `unload` method of the `AssetManager` to unload a specific resource.

You can read more on AssetManager on the wiki.

---
Tags: libgdx, asset-management
---


# Question
Title: RectTransform Button Start shaking with Vector3.MoveTowards()
I have a RectTransform Button that i want to make it move to a de-terminated vector3.

To move the button i use this code (it is inside Update())

```
        int i = -1;
        foreach (RectTransform Button in Buttons)
        {
            i++;
            Vector3 NewPosBtns = new Vector3(StartButtonsVect[i].x, (StartButtonsVect[i].y + 192.5f), StartButtonsVect[i].z);
            Vector3 CurPosBtns = StartButtonsVect[i];
            Button.localPosition = Vector3.MoveTowards(CurPosBtns, NewPosBtns, AnimationSpeed);
        }

```

`Buttons` is a array and i add the button to the list using unity editor

`StartButtonsVect` is of vector3 that i add the using this code

```
void Start()
{
    foreach (RectTransform Button in Buttons)
    {
        StartButtonsVect.Add(Button.localPosition);
    }
}

```

For some reason the button start shaking instead of going to the target position (NewPosBtns)

# Answer
The first argument of `MoveTowards` is the *current* position of the object.

You've passed a variable called `CurPosBtns`, which might *imply* it's "current", but you initialized that variable to `StartButtonsVect[i]`. Which means despite its name, it's still representing the *start* position of the button, not the current position.

This means that every frame, `MoveTowards` thinks it's starting from scratch - it never has a chance to accumulate any progress because you always pass it the start position. So you only see one frame's worth of movement progress - which will wiggle back and forth based on frame timings (fast frames make very little movement progress, assuming you've scaled `AnimationSpeed` by `Time.deltaTime`).

The fix is to replace `CurPosButns` with the actual position, ie.

```
Button.localPosition = Vector3.MoveTowards(Button.localPosition, NewPosBtns, AnimationSpeed);

```

Also, for positioning elements on a canvas, consider using anchoredPosition rather than localPosition. This tends to play nicer with UI layout and scaling behaviours.
> 1 votes

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