title: Why does this code not display ads?

text:
# Question
Title: Why does this code not display ads?
Can someone tell me what I am doing wrong?

Here's my `AndroidLauncher`:

```
public class AndroidLauncher extends AndroidApplication {

    public static final String BANNER_AD_USER_ID = "ca-app-pub-xxxxxxxxxxxxxxxxxxxxxxxxxxx";
    private AdView adView;

    @Override
    protected void onCreate (Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();

        //  RELATIVE LAYOUT
        RelativeLayout layout = new RelativeLayout(this);

        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);

        //  GAME VIEW
        View gameView = initializeForView(new MyGame(), config);
        layout.addView(gameView);

        //  ADS
        AdRequest.Builder builder = new AdRequest.Builder();
        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
        adView = new AdView(this);
        adView.setAdUnitId(BANNER_AD_USER_ID);
        adView.setAdSize(AdSize.BANNER);
        adView.setVisibility(View.VISIBLE);
        adView.setLayoutParams(layoutParams);

        adView.loadAd(builder.build());
        layout.addView(adView);

        setContentView(layout);
    }
}

```

and my game's `Gradle`

```
project(":android") {
    apply plugin: "android"

    configurations { natives }

    dependencies {
        compile project(":core")
        compile "com.badlogicgames.gdx:gdx-backend-android:$gdxVersion"
        natives "com.badlogicgames.gdx:gdx-platform:$gdxVersion:natives-armeabi"
        natives "com.badlogicgames.gdx:gdx-platform:$gdxVersion:natives-armeabi-v7a"
        natives "com.badlogicgames.gdx:gdx-platform:$gdxVersion:natives-arm64-v8a"
        natives "com.badlogicgames.gdx:gdx-platform:$gdxVersion:natives-x86"
        natives "com.badlogicgames.gdx:gdx-platform:$gdxVersion:natives-x86_64"
        compile "com.badlogicgames.gdx:gdx-box2d:$gdxVersion"
        natives "com.badlogicgames.gdx:gdx-box2d-platform:$gdxVersion:natives-armeabi"
        natives "com.badlogicgames.gdx:gdx-box2d-platform:$gdxVersion:natives-armeabi-v7a"
        natives "com.badlogicgames.gdx:gdx-box2d-platform:$gdxVersion:natives-arm64-v8a"
        natives "com.badlogicgames.gdx:gdx-box2d-platform:$gdxVersion:natives-x86"
        natives "com.badlogicgames.gdx:gdx-box2d-platform:$gdxVersion:natives-x86_64"
        compile "com.badlogicgames.gdx:gdx-freetype:$gdxVersion"
        natives "com.badlogicgames.gdx:gdx-freetype-platform:$gdxVersion:natives-armeabi"
        natives "com.badlogicgames.gdx:gdx-freetype-platform:$gdxVersion:natives-armeabi-v7a"
        natives "com.badlogicgames.gdx:gdx-freetype-platform:$gdxVersion:natives-arm64-v8a"
        natives "com.badlogicgames.gdx:gdx-freetype-platform:$gdxVersion:natives-x86"
        natives "com.badlogicgames.gdx:gdx-freetype-platform:$gdxVersion:natives-x86_64"
        compile 'com.google.firebase:firebase-ads:10.0.1'
    }
}

```

The game works well but does not show ads.

# Answer
Make sure that you have enabled network connectivity in your android manifest.
> -2 votes

---
Tags: java, android, libgdx
---


# Question
Title: How to smooth the movement of my player in Unity?
I would like to move my player from one position to another position using key detection. I would like to know how I can make the player movement smooth.

Code:

```
if (Input.GetKeyDown(KeyCode.A))
    {
        xSpeed = -1f;
        ySpeed = 0f;
        X = X + xSpeed;
        Y = Y + ySpeed;
        Vector3 NewPos = new Vector3(X, Y, 0);
        gameObject.transform.position = NewPos;
    }
    else if (Input.GetKeyDown(KeyCode.D))
    {
        xSpeed = 1f;
        ySpeed = 0f;
        X = X + xSpeed;
        Y = Y + ySpeed;
        Vector3 NewPos = new Vector3(X, Y, 0);
        gameObject.transform.position = NewPos;
    }
    else if (Input.GetKeyDown(KeyCode.W))
    {
        xSpeed = 0f;
        ySpeed = 1f;
        X = X + xSpeed;
        Y = Y + ySpeed;
        Vector3 NewPos = new Vector3(X, Y, 0);
        gameObject.transform.position = NewPos;
    }

    else if (Input.GetKeyDown(KeyCode.S))
    {
        xSpeed = 0f;
        ySpeed = -1f;
        X = X + xSpeed;
        Y = Y + ySpeed;
        Vector3 NewPos = new Vector3(X, Y, 0);
        gameObject.transform.position = NewPos;
    }

```

# Answer
The most basic approach is, as stated in the link in the comments, to multiply your movement with `Time.deltaTime` in the Update-method of your gameobject.

`Time.deltaTime` is the time passed between the last frame (update) and the current.

In your case:

```
if (Input.GetKeyDown(KeyCode.A))
{
    xSpeed = -1f;
    ySpeed = 0f;
    //Consider to increase your speed or add a new factor to multiply with, otherwise your movement will slow down significantly
    X = X + xSpeed * Time.deltaTime;
    Y = Y + ySpeed * Time.deltaTime;
    Vector3 NewPos = new Vector3(X, Y, 0);
    gameObject.transform.position = NewPos;
}

```
> -1 votes

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


title: Identifying assets in a game engine?

text:
# Question
Title: Identifying assets in a game engine?
I want to identify my loaded assets, but I don't know which one should I choose. There are 2 options:

* **Name (string)**

+ This is the easiest and also fast with unordered\_map ( O(1) ), but way slower then using integers.
    + Easily understandable in the code.
* **Integers**

+ Fastest.
    + Aren't understandable in code.

I know that strings are not so safe or fast, but is it that bad, or does it only count as bad in a AAA title? I could make enums, to use integers, but if I load the scene, assets, etc from a file at runtime, I can't use enums. Is there a way to make these integers readable if they are generated at runtime?

I know that this issue has a few threads all around the internet, but I couldn't find out how important in which cases is this.

# Answer
You can support both.

While it is often more efficient at runtime to reference assets by an integer or some similar fast-to-compare key, it's often more efficient at design time to reference them by name, because humans are a lot better at working with names like `enemy_bullet_casing_sound` than `72910613`.

Use an integer key to look up the resources directly, and use this integer in code wherever possible (where you can put the actual value of the integer in a variable and thus work with it easier). Provide a mapping from name *to* that integer key (rather than to the resource directly), and use that mapping whenever you encounter named references to assets to resolve the actual integer key and find the asset.

Using the name-based lookup will make your data files much easier to work with, and mapping the name to a faster key will preserve all the important benefits of a faster, integer-type key anywhere its needed.
> 19 votes

# Answer
In my project I use hashed strings, which are transformed, at compile time in unique (I wish!) numbers. So, when I need a resource, for example a texture I simply call

```
MngTexture->get(hash("my_texture"))

```

And since I'm creating a simple entity system framework and I need to load components data from files I created a simple language like json to store data, but is compilable (transforming words and chars from digits to number and from strings to hashed values). So, for example, if I want to link the texture with ID hash("my\_texture") to "ball.PNG" in my data file I'll have

```
|my_texture| = "ball.PNG"

```

Where || is an operator which tells the compiler to hash the word inside.

So basically I use strings which are mapped to ints at compile time (so they haven't any overhead), both in the actual code and in the files which are the streams for loading components. For computing the hash a compile time simply google it, it a simple function of 5-10 lines of code.

Of course you can load the string from you're files and hashes it at run time, in this case you don't have to write the dictionary on your own because the algorithm will do it for you (creating integers from strings) and I think hasing is at least as fast as searching in a map, because of memory locality (you are just looping through a string which is few bytes long).

Hope this can help.
> 1 votes

# Answer
Identifying object by strings is not optimal, ints are much more efficient. For convenience you can maintain a string table (or dictionary) of strings to ints to help at design time and during debugging.

I would, however, advocate that within your core game code you only refer to objects by their integer ID (or an enum for readability). Doing this makes it simpler to break out the string table as a separate asset. If your core game code doesn't rely on this string table then you can drop it from the released game potentially saving a significant amount of memory - an important consideration if you are working on a mobile game and want to keep download sizes as small as possible.
> 0 votes

---
Tags: c++, architecture, assets, asset-management
---


# Question
Title: Detect which Entity caused the collision
I have a 2D plane with two or more moving entities (polygons with an AABB). On collision both of them will go through a "collidesWith" Method, where I have access to both entities but only want to modify the other one to avoid that something is applied twice. For collision detection I am using a custom implementation of the SAT Algorithm.

The entities will only move in x or y direction not diagonal. (Though I would like to add diagonal, if there is a solution that works for diagonal as well)

What I want to achieve is:

1. a moves vertically and b moves into it, b should invert its movement
2. d moves horizontally and c moves into it, c should invert its movement

How do I approach this without a huge amount of if statements?

# Answer
> 2 votes
All you need to do is check the x and y velocity of each entity when they collide, if the velocities are in the direction of the other block (say for instance if you're an entity where Vx is -1 and Vy is 0, and the entity you have collided with has a location that is to the left of you) you can determine that you caused the collision as you moved towards the other block. Once you have determined this you can simply multiple the appropriate velocity(x or y) by -1.

# Answer
> 0 votes
If both objects are moving, neither one of them "caused" the collision any more than the other, so we should seek a better definition of how we would define which object should bounce.

In real-life physics, the bouncing would have a lot to do with momentum (mass * velocity), but in the two examples you have given, if we distill it down, you view the object that got "in the way" of the other as NOT being the "cause". More specifically, if you think of an object's "front" face as being the side facing the direction the object is moving, when a collision occurs you have stated a desired that the object whose front-face collides should be the one that bounces.

From a pseudo-code perspective, you could then think of it like this:

* Object A and Object B have been found to collide.
* Find the "front" face of Object A
* If the front face of Object A has done the collision, Object A bounces. (In this case, if you want a "head-on" collision to bounce both objects, you would also have to check the front-face of Object B.)
* If the front face of Object A did not collide, you can assume Object B bounces.

edit: was typing this at the same time as benh. His answer is more concise & doesn't wax philosophical about defining your collision, so I think it's better. As a side-note: his recommendation will cover everything I've mentioned, including head-on collisions.

---
Tags: java, collision-resolution
---


# Question
Title: How do I show a camera's field of view area through another camera?
I have a side camera that can be set on run-time with changeable field of view with GUI. I am searching for a way to show the field of view of the side camera using my main camera. I am thinking about custom mesh creation through code so that it can be generated alongside the camera rectangle, but it seems too complex. Should I proceed with this method or are there any other solutions?\[!

# Answer
I was interested in this and thought I'd try and make a "field of view pyramid object" on a camera. This isn't a good method to include inside `Update` but you can make it into an `onCall` method and call it when it's needed. Here's the code (pyramid making code was taken from here and here and modified to make a "fov indicator"):

```
void Start ()
{
    cam = gameObject.GetComponent<Camera>(); //finds camera on this object
    GameObject g = GameObject.CreatePrimitive(PrimitiveType.Cube); //makes a cube
    Destroy(g.GetComponent<BoxCollider>()); //destroy the box collider on the cube because it's not needed
    MeshFilter meshFilter = g.GetComponent<MeshFilter>(); //get the meshfilter on cube
    //make a new mesh
    Mesh mesh = new Mesh();
    Vector3[] points = new Vector3[5];
    points[0] = cam.transform.position;
    points[1] = cam.ViewportToWorldPoint(new Vector3(0, 0, cam.farClipPlane));
    points[2] = cam.ViewportToWorldPoint(new Vector3(0, 1, cam.farClipPlane));
    points[3] = cam.ViewportToWorldPoint(new Vector3(1, 0, cam.farClipPlane));
    points[4] = cam.ViewportToWorldPoint(new Vector3(1, 1, cam.farClipPlane));
    mesh.vertices = new Vector3[] {
        points[0], points[1], points[2],
        points[0], points[3], points[1],
        points[0], points[4], points[2],
        points[0], points[3], points[4],
        points[1], points[2], points[4],
        points[1], points[4], points[3]
    };

    mesh.triangles = new int[] {
        0, 1, 2,
        3, 4, 5,
        8, 7, 6,
        11, 10, 9,
        14, 13, 12,
        17, 16, 15
    };

    mesh.RecalculateNormals();
    mesh.RecalculateBounds();
    mesh.MarkDynamic();
    //set the new mesh to cube's mesh
    meshFilter.mesh = mesh;
    //set the camera as the cube's parent
    g.transform.SetParent(cam.transform);
}

```

Demo:
> 1 votes

# Answer
You're probably looking for frustum calculations. There's a Unity built-in method on the Camera class if I recall correctly. Ah nope, GeometryUtility.

It's generally used as the input to GeometryUtility.TestPlanesAABB to see if a given collier is inside the view frustum (for render culling; i.e. hiding stuff behind the camera). However, you could write your own code to calculate a percentage value from the default camera, depending on your actual goal. That is the ratio `FOV1 / FOV2` might be sufficient for your needs. Or perhaps not.

I'm including the following method for generating a view frustum from an arbitrary point (no Camera component needed) as it will be helpful in understanding what, exactly, the GeometryUtility method does in the event you need to compare two Plane arrays. This code returns an identical set of Planes as the GeometryUtility method.

```
    public static Plane[] CalculateFrustum(Vector3 origin, Vector3 direction, float fovRadians, float viewRatio, float distance) {
        Vector3 nearCenter = origin + direction * 0.3f;
        Vector3 farCenter  = origin + direction * distance;
        Vector3 camRight   = Vector3.Cross(direction,Vector3.up) * -1;
        Vector3 camUp      = Vector3.Cross(direction,camRight);

        float nearHeight = 2 * Mathf.Tan(fovRadians / 2) * 0.3f;
        float farHeight  = 2 * Mathf.Tan(fovRadians / 2) * distance;
        float nearWidth  = nearHeight * viewRatio;
        float farWidth   = farHeight * viewRatio;

        Vector3 farTopLeft  = farCenter + camUp*(farHeight*0.5f) - camRight*(farWidth*0.5f);//new Vector3(-camRight.x * (farWidth*0.5f), (farHeight*0.5f), -camRight.z * (farWidth*0.5f));
        //Vector3 farTopRight = farCenter + camUp*(farHeight*0.5f) + camRight*(farWidth*0.5f);//new Vector3( camRight.x * (farWidth*0.5f), (farHeight*0.5f),  camRight.z * (farWidth*0.5f));
        Vector3 farBottomLeft  = farCenter - camUp*(farHeight*0.5f) - camRight*(farWidth*0.5f);//new Vector3(-camRight.x * (farWidth*0.5f), -(farHeight*0.5f), -camRight.z * (farWidth*0.5f));
        Vector3 farBottomRight = farCenter - camUp*(farHeight*0.5f) + camRight*(farWidth*0.5f);//new Vector3( camRight.x * (farWidth*0.5f), -(farHeight*0.5f),  camRight.z * (farWidth*0.5f));

        Vector3 nearTopLeft  = nearCenter + camUp*(nearHeight*0.5f) - camRight*(nearWidth*0.5f);//new Vector3(-camRight.x * (nearWidth*0.5f), farCenter.y + (nearHeight*0.5f), -camRight.z * (nearWidth*0.5f));
        Vector3 nearTopRight = nearCenter + camUp*(nearHeight*0.5f) + camRight*(nearWidth*0.5f);//new Vector3( camRight.x * (nearWidth*0.5f), farCenter.y + (nearHeight*0.5f),  camRight.z * (nearWidth*0.5f));
        //Vector3 nearBottomLeft  = nearCenter - camUp*(nearHeight*0.5f) - camRight*(nearWidth*0.5f);//new Vector3(-camRight.x * (nearWidth*0.5f), farCenter.y - (nearHeight*0.5f), -camRight.z * (nearWidth*0.5f));
        Vector3 nearBottomRight = nearCenter - camUp*(nearHeight*0.5f) + camRight*(nearWidth*0.5f);//new Vector3( camRight.x * (nearWidth*0.5f), farCenter.y - (nearHeight*0.5f),  camRight.z * (nearWidth*0.5f));
        Plane[] planes = {
            new Plane(nearTopLeft,farTopLeft,farBottomLeft),
            new Plane(nearTopRight,nearBottomRight,farBottomRight),

            new Plane(farBottomLeft,farBottomRight,nearBottomRight),
            new Plane(farTopLeft,nearTopLeft,nearTopRight),

            new Plane(nearBottomRight,nearTopRight,nearTopLeft),
            new Plane(farBottomRight,farBottomLeft,farTopLeft)};

        return planes;
    }

```
> 0 votes

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


# Question
Title: Quantity of dropped/spawned items in container
I'm having trouble figuring out how to spawn more than one item in to a container with a weight limit. What I'm having trouble with is the *understanding*, rather than what statements to write;

My items are composed of `weight`, `type` and `foundIn`, among other things. My containers are items, with some minor changes. `foundIn` is an array of strings which match "container" items, and should be either "world", "container-name", or empty (`[]`). "container" items follow a similar structure, with slight deviance.

---

Whenever I want to drop an item, I get a pool of items in a `foundIn` location, make a `Math.random` check against the `commonRate`, and *if that item is a `type = "container"`*, I try to fill the container.

Here is where I have my problem; I can not figure out how to decide if multiple items of the same `type` should be dropped inside the container, and if so, how many. If I can figure this out, I can have monsters carry their own drops, instead of having to write a whole monster drop-table with levels and oddities.

---

The following is my code. The last method, `dropItem`, glues the displayed methods together.

```
placeExists(place) {
    return this._itemPlaces.indexOf(place) > -1;
}

getItemsOfType(arrayOfTypes, inList) {
    if (!Array.isArray(arrayOfTypes)) throw new Error('Index must be string');
    let pool = this.list;
    if (inList) pool = inList;

    return pool.map((item => {
        if (arrayOfTypes.indexOf(item.type) > -1) {
            return item;
        }
    }));

}

populateContainer(container, pool) {
    let chance = Math.random();
    pool = pool.map(item => {
        let canBeFound = item.foundIn.indexOf(container.name) > -1
                || item.foundIn.indexOf('world') > -1;
        if (item.commonRate >= chance && canBeFound) return item;
    });

    this.getItemsOfType(container.availableTypePool, pool).some(item => {
        if (container.capacity.freeSpace <= 0) return true;
        if (item.commonRate >= Math.random()
                && item.weight <= container.capacity.freeSpace) {
            container.addItem(item);
        }
    });

    return container;
}

getItemsOfPlace(place) {
    return this._LIST.map(item => {
        if (item.isFoundIn(place)) {
            return item;
        }
    })
}

dropItem(fromPlace) {
    if (this.placeExists(fromPlace)) return [];
    let foundItem = [];

    let pool = this.getItemsOfPlace(fromPlace);
    pool.some(item => {
        let chance = Math.random();
        if (chance > item.commonRate) {
            if (item.type == 'container')
                foundItem.push(this.populateContainer(item, pool));
            else
                foundItem.push(item);
            return true;
        }
    });

    return foundItem;
}

// container abstracted method of adding an item

container.addItem = (item = new Item()) {
    if (item instanceof Item === false) throw Error('item needs to be of type Item');
    if (item.type == 'container') throw Error('Yo dawg, I heard you like containers...');

    this._contained.push(item.code);
    this.carryingWeight = +item.weight;
}

```

---

How do I decide if I should drop multiple items, and how do I randomly select that amount?

Note that `this.list` and `this._LIST` are the same list. For some reason, WebStorm seems to lose track of one or the other when inside certain callbacks, so I switch to avoid losing autocomplete. For reference, `this.list` is `get list() { return this._LIST }`, and is obtained from extending a custom `List` class.

# Answer
I wasn't thinking correctly: The action of the user should control how much items can fall (so we can later apply modifiers to this value without having to change how the Item class works) not *the place* where the user picks the item from. as such, now an Item has `dropInfo = { chance: 0~1, maxQty: 0, dropsFrom: [''] }`;

Whenever I want to drop an item I all `dropEvent` with "item", "variety" and "modifier" as its arguments, for the "how much" the `maxQty` is used (with a modifier) - this also controls how much of this item can be bundled together.

```
dropEvent(fromPlace, variety, modifier) {
    let dropped = [];
    this.byDropPlace(fromPlace).some((item = new Item()) => {
        if (variety === 0) return true;
        if (variety > 0) variety--;
        if (item.drop.tryDrop) {
            let quantity = Math.floor(Math.random() * (item.drop.maxQty + modifier) + 1);
            dropped.push(this.makeBundleReference(item, quantity))
        }
    });
    return dropped;
}

```

A `bunldeReference` is a reference to the item, containing the item name, code, description and weight for basic informational proposes.

I still have to figure out a way of not following a ordered list, so I can avoid the first items getting to drop more often than the last items of the list - but `dropEvent` solves the original question.
> 0 votes

---
Tags: software-engineering, game-mechanics, node.js, roguelikes
---


# Question
Title: How to export unreal assets in a package like in unity?
Unity has an asset exporter that export it into a .unitypackage format. This ensure that the prefab has all the links to its child assets.

In Unreal 4, its migrate tool allow for moving of assets. However, it require that both project be on the same machine to migrate from one content folder to another content folder.

How can I export unreal assets for easy sharing in a similar way to unity?

# Answer
You can start with making sure that all the child dependencies lies in the same folder lets say "MyAsset".

In Unreal we have something called Blueprints which is equivalent to prefabs in Unity I will say.

So lets say you want to create an asset as a collectible in the game. You start with New Blueprint -\> Actor and name your blueprint. Afterwards double click to launch the editor. The editor will have 3 tabs viewport, event and constructor.

In the view port tab you can preview your actor and add additional objects/praticles/effects as per your need.
> 2 votes

---
Tags: unreal-4
---


# Question
Title: How do I efficiently implement Fog of War in a Real-time Strategy game?
How is fog of war implemented in RTS games such as *StarCraft II* or *Age of Empires*? I'm making an RTS, and plan for every unit on the field to have circular vision up to a certain radius.

My first thought was having a mask that is black for every point except for points close to units, where it is transparent. The masking operation itself is fast in most graphics APIs (e.g. just call `mix` in a shader). The hard part is figuring out what mask to use and how to update it: updating it when any unit moves is very processor-heavy.

Is there any simpler way to manage this type of fog of war?

# Answer
> 5 votes
If your game has cell based occupancy, you can reduce the fog of war calculations by restricting up dates to the moments when a unit crosses the threshold from one cell to the next.

# Answer
> 9 votes
*Following answer is based on own RTS experience, which visually aligns with Age Of Empires and other RTS games*

**Nowadays there is not one, but 2 Fog Of Wars (FOW)**

Static FOW is simpler (once revealed, remains open):

**First FOW** is calculated on CPU and is used for **games logic** to test what units "see" in the game and can/cannot do. For an RTS it must be 100% identical between all players machines and graphics settings and be 100% repeatable, assuming that RTS traditionally use lock-step multiplayer. Given that, to avoid extra CPU load, it has to be more granular - e.g. 1 sample per tile per 5 game logic's ticks (or you can optimize by updating units sight only when they arrive at new tile).

**Second FOW** is rendered on GPU and is more dynamic / detailed. This FOW is **what player sees**. GPU can render/update it every frame at much higher resolution that CPU could handle (e.g. 4096\*4096 pixels), to produce smooth sight circles. The FOW being much more accurate, can mismatch game logics FOW slightly, which is okay, since typical mismatches happen on FOW edge where exact judgement is vague.

Why not use GPU FOW for both logic and visuals? It takes a lot of time to stream texture data from GPU back to CPU. GPU rendering can not be trusted, it can greatly differ between players configurations / drivers / settings.

For static FOW you can get away with a sort of "additive" updates - each time for each FOW sample - pick the brightest and keep it.

---

Making **FOW dynamic** is another complex problem. In simplest, dynamic FOW can take 5 states: fully covered, semi-explored, explored, semi-revealed, fully revealed. You can map these states to be 0, 1-49, 50, 51-99, 100-255. Now when unit reveals fog, it reveals it to 255. Each tick you dim "semi-revealed" and "fully revealed" FOW by e.g. 10. This means that when unit leaves, FOW remains "fully revealed" for 15 ticks before starting to fade to semi-revealed and then another 5 ticks before stopping at "explored".

# Answer
> -2 votes
Unity allows you to add a "cookie" to a light source, which will mask the light based on an image texture - which you can update by using a RenderTexture for that texture and then updating that with your fog of war.

I would suggest keeping and updating the raw fog of war data in main memory, and then, once per frame, flushing whatever you need for your fog of war mask over to the RenderTexture.

---
Tags: rts, fog-of-war
---


# Question
Title: How can I increase framerate, when drawing tiles to a HTML canvas?
I am using the HTML 5 canvas to make a simple platformer game. I am currently drawing the tiles using a `for` loop that runs through a list of tiles and checks if they will be drawn to the screen.

```
for (var i = 0; i < tiles.length; i++) {
    if (tiles[i].x + scale > pos.x - (canvas.width / 2)
            && tiles[i].x < (pos.x + scale) + (canvas.width)) {
        canvas.drawImage(tiles[i].x - pos.x, tiles[i].y - pos.y, scale, scale,
                "img/Tiles/" + tiles[i].Tile + ".png")
    }
}

```

I am also using this custom library to draw the image to the screen:

```
this.drawImage = function(x, y, width, height, src, alpha) {
    if (alpha) {
        ctx.globalAlpha = alpha
    }

    if (document.getElementById(src) == undefined) {
        document.head.innerHTML
                += '<img width="16px" height="16px" src=' + src + ' id=' + src + '></img>'
    }

    var img = document.getElementById(src)
    ctx.drawImage(img, x, y, width, height);
    ctx.globalAlpha = 1.0
    document.getElementById(src).outerHTML = ""
}

```

---

When I run the `for` loop, the frame rate of the game seems to drop. Is there an alternate option to going through every element of the array that I'm not aware of?

# Answer
> 1 votes
Determine the frustrum (range) of your viewport, then use that to only iterate over visible tiles.

For instance, if your viewport can only see rows 14 - 27 and columns 33 - 89, then your rendering loop should only even *consider* drawing those tiles. Assuming you have calculated this visible range:

```
for (let y = bottom; y <= top; ++y)
  for (let x = left; x <= right; ++x)
    draw_tile(x, y);

```

Calculating that range depends on how you've setup the rest of your drawing code. It might in your case be as easy as taking the eye/camera position, adding/subtracting half the canvas dimensions, and then converting into tile positions (remember to round up/down for tiles partially visible):

```
const left = floor(camera.x - canvas.width*0.5)
const right = ceil(camera.x + canvas.width*0.5)
const top = ceil(camera.y + canvas.height*0.5)
const bottom = floor(camera.y - canvas.height*0.5)

```

Tweak as necessary for your vector library and whether your coordinates are +Y up or +Y down (I'm not immediately familiar with what canvas uses).

# Answer
> 0 votes
Fixed by using a seperate loop to evaluate which blocks are on screen before drawing them. This loop runs at 1/4th the speed of the main loop to help reduce lag. Here is the code:

```
//Variable to hold which tiles are on scree
var currTiles = []

//Calculate which tiles to draw to screen. Runs at 15 fps
function draw2() {
  currTiles = []
  for (var i = 0; i < tiles.length; i++) {
    if (tiles[i].x + scale > pos.x - (canvas.width / 2) && tiles[i].x < (pos.x + scale) + (canvas.width)) {
      currTiles.push(tiles[i])
    }
  }
}

//Loop to draw tiles in the "currTiles" array. Running at 60 fps
function draw() {
  for (var i = 0; i < currTiles.length; i++) {
    canvas.drawImage(currTiles[i].x - pos.x, currTiles[i].y - pos.y, scale, scale, "img/Tiles/" + currTiles[i].Tile + ".png")
  }
}
```

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


title: Snake user input

text:
# Question
Title: Snake user input
So I'm basically doing a snake game in Console Application. I'm kind of new to programming and I'm not sure how to do the game loop. My code looks like this:

```
while (true)
{
    System.Threading.Tasks.Sleep(250);
    Refresh();
}

```

I want it to read user input while sleeping. Could you tell me how to do it? Thanks in advance

# Answer
> 2 votes
I think it goes without saying that this is not something that a console application is well suited for, but at the same time, I've also written a Tetris clone for same. So....

While it's not quite an answer to the question you've asked (you can't do anything while sleeping. It's the point of sleeping), you can handle input to a console while managing drawing at the same time.

```
DateTime lastMeasuredTime = DateTime.Now;
double desiredFrameTime = 1000.0 / 24.0; //24FPS

//Main game looop
while (true)
{
    while (Console.KeyAvailable)
    {
        ConsoleKeyInfo key = Console.ReadKey(true);
        //Process input for each key
    }
    if ((DateTime.Now - lastMeasuredTime).TotalMilliseconds >= desiredFrameTime)
    {
        //Do a game tick here
        // ...
        // ...
        lastMeasuredTime = DateTime.Now;
    }
}

```

This approach is neither foolproof nor well-advised, but it is functional. Instead of relying on fixed sleep calls to create your time delay, you create your own timer to handle the waits for you. You then capture input inside the main loop, but outside the timer logic so that input can be received as close to immediate as possible. Also note that using DateTime is not going to create the world's most accurate timer, but it works for this application.

Also note than when using console as a renderer, you need to be smart about how you "draw" to it. Only drawing when and where necessary.

---
Tags: c#, game-loop
---


title: Unity3D: iTween ValueTo() not working

text:
# Question
Title: Unity3D: iTween ValueTo() not working
I have the following code to animate the Camera's FOV change:

```
public float fieldOfView;
public Camera theCamera;
public float animTime;

private float origFOV;

void OnTriggerEnter(Collider other) {
    origFOV = theCamera.fieldOfView;

    Hashtable h = new Hashtable ();
    h.Add ("from", (float)origFOV);
    h.Add ("to", (float)fieldOfView);
    h.Add ("time", animTime);
    h.Add ("onupdate", "OnFOVUpdate");

    iTween.ValueTo(theCamera.gameObject, h);
}

void OnTriggerExit(Collider other) {
    Hashtable h = new Hashtable ();
    h.Add ("from", (float)fieldOfView);
    h.Add ("to", (float)origFOV);
    h.Add ("time", animTime);
    h.Add ("onupdate", "OnFOVUpdate");

    iTween.ValueTo(theCamera.gameObject, h);
}

void OnFOVUpdate(float val) {
    theCamera.fieldOfView = val;
}

```

but I always get the following error when the script compiles:

`iTween Error: ValueTo() requires an 'onupdate' callback function and a 'from' and 'to' property. The supplied 'onupdate' callback must accept a single argument that is the same type as the supplied 'from' and 'to' properties!`

What am I doing wrong?

# Answer
I think you, basically, have to do what is asking for. Implement `onupdate` function with parameters of the same row which your are planning to change.

Please find similar issue and solution here https://forum.unity3d.com/threads/itween-valueto.62448/
> -2 votes

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


# Question
Title: How do I programatically lay tiles with the Godot engine?
I am completely new to Godot Engine, and quite an amateur in game development, in general. I have a small project where I want to implement a procedurally generated level, and for that I'd like to be able to programmatically place tiles. I'm thinking about something like in this video for GameMaker, however, I haven't found a documented way to do that for Godot.

Does Godot support programmatically laying tiles, and if so, how?

# Answer
You can programmatically set a cell in the `TileMap` class by using the `set_cell` function.

Note: if you're new to an engine & game dev in general, I highly recommend working through any of the tutorial information provided; I happened to come across the the link to the `TileMap` class in:

2d Tutorials -\> Graphics -\> Using TileMaps

Note: the above was for the 3.x version of Godot.
Information for the current/stable version can be found here or by changing the version in the lower left hand corner:
> 14 votes

---
Tags: procedural-generation, godot
---


# Question
Title: Gravity vector and forward vector to local heading (yaw), pitch and roll
I've looked around for hours and I simply don't get it. I am the first to admit I am severely lacking in mathematics. So please, keep it simple.

I am trying to get a vectors rotation (angle) around another vector so i can get useful Yaw, Pitch and Roll from said vectors. This on a "vehicle" that has a forward vector (and of course accompanying right and up vectors) which is "flying" over a planet (sphere) with gravity going towards it's center. This gravity vector is also known.

Here's an example of what i am looking at:

I am using Unity to EXPERIMENT with. The goal is to implement this in another project. Thus, all the powers of Unity doesn't help me find a solution for my other project. I am constricted to Vector3.Cross(), Vector3.Dot, Math.Cos/Sin/ACos/ASin/Tan/ATan/ATan2 etc.

Here's the code i have. I did remove all the calculations i tried beforehand as they all failed and i'd rather have a clean answer.

```
    // Time that debug lines and rays will be displayed for.
    var duration = Time.deltaTime;
    // Draws a line through the south/north poles of the sphwere.
    Debug.DrawLine(Vector3.down * 100, Vector3.up * 100, Color.cyan, duration, false);

    // Gravity that affects the vehicle
    var gravity = Vector3.Normalize(planet.transform.position - transform.position) * 9.81F;
    Debug.DrawRay(transform.position, gravity, new Color(0.4F, 0.0F, 0.0F), duration, false);

    var gravityEast = Vector3.Cross(gravity.normalized, Vector3.down).normalized;
    var gravityNorth = Vector3.Cross(gravityEast.normalized, -gravity.normalized).normalized;

    Debug.DrawRay(transform.position, gravityEast, Color.yellow, duration, false);
    Debug.DrawRay(transform.position, gravityNorth, Color.white, duration, false);
    Debug.DrawRay(transform.position, transform.forward * 0.5F, Color.blue, duration, false);

    text.text = "gravity: " + gravity + "\n";
    text.text += "gravityEast: " + gravityEast + "\n";
    text.text += "gravityNorth: " + gravityNorth + "\n\n";

    text.text += "forward: " + transform.forward + "\n\n";

```

I am looking to get Yaw in 360 degrees (-180 to 180 works too and even radians, that's not a problem), roll in -180 to 180 degrees and pitch in -90 to 90 degrees. This all in respect to the gravity vector and where zero Yaw is pointing to the north along the sphere. 90 Yaw is east, 180 is south and 270 is west.

As i said, i've been looking at hundreds of different examples (both on SE and elsewhere) and i still don't understand how to do this. All the things i have tried have either not worked at all or they have worked only in certain circumstances such as the "vehicle" being on one side of the sphere but not the others. As far as i can understand, i need to transform the calculations to local vector space so that the formulas stay relative to my ever changing gravity vector.

And because i am mathematically illiterate at best, a bunch of mathematical formulas won't really help me. I've looked at them all and it just doesn't click. Instead, if this can be shown in pseudocode or even straight up C# that would be optimal.

And just to be perfectly clear here. I know i can use "transform.eulerAngles" on my cube to get global and local angles right away. Again, i need to port the solution to another project that doesn't come with those simple properties/fields.

Thank you!

# Answer
> 0 votes
I found the solution myself after a (bad) night's sleep on it.

## Working Code

```
void Update () {
    // NOTE: I am really bad at this (vectors, cross products, dot products etc), hence my comments will be to the best of my understanding.

    // Time that debug lines and rays will be displayed for.
    var duration = Time.deltaTime;
    // Draws a line through the south/north poles of the sphwere.
    Debug.DrawLine(Vector3.down * 100, Vector3.up * 100, Color.gray, duration, false);

    // Gravity that affects the vehicle
    var gravity = Vector3.Normalize(planet.transform.position - transform.position) * 9.81F;
    // Cross products of gravity to describe planes.
    var gravityEast = Vector3.Cross(gravity.normalized, Vector3.down).normalized;
    var gravityNorth = Vector3.Cross(gravityEast.normalized, -gravity.normalized).normalized;

    // Draw vehicle forward, right and up vectors. Makes it easier to see how it's currently rotated.
    Debug.DrawRay(transform.position, transform.forward * 0.5F, Color.cyan, duration, false);
    Debug.DrawRay(transform.position, transform.right * 0.5F, Color.cyan, duration, false);
    Debug.DrawRay(transform.position, transform.up * 0.5F, Color.cyan, duration, false);

    // Draw gravity vector and it's plane vectors.
    Debug.DrawRay(transform.position, gravity.normalized, new Color(0.0F, 0.0F, 0.5F), duration, false);
    Debug.DrawRay(transform.position, gravityEast, new Color(0.5F, 0.5F, 0.0F), duration, false);
    Debug.DrawRay(transform.position, gravityNorth, new Color(0.5F, 0.0F, 0.0F), duration, false);

    // Debug text to verify the absolute values of the gravity and it's plane vectors.
    text.text = "gravity: " + gravity + "\n";
    text.text += "gravityEast: " + gravityEast + "\n";
    text.text += "gravityNorth: " + gravityNorth + "\n\n";

    // Define "aligned" (plane) vectors that rotate with the vehicle.
    //  For example, gravityAlignedRight will stay pointing along the height plane over the
    //  surface of the sphere and rotate with the vehicle always pointing to the right.
    //  This is used to determine angular difference between vehicles right vector and gravity's aligned right vector.
    //  The reason we need that is because Vector3.Angle() would measure the whole angle between a fixed vector such as
    //  gravityEast and the vehicle right vector otherwise.
    // gravityAlignedForward is used for yaw and pitch.
    // gravityAlignedDown is used for pitch and is needed to get the correct dot product for pitch.
    var gravityAlignedRight = Vector3.Cross(gravity.normalized, -transform.forward).normalized;
    var gravityAlignedForward = Vector3.Cross(gravity.normalized, gravityAlignedRight).normalized;
    var gravityAlignedDown = Vector3.Cross(gravityAlignedRight, transform.forward).normalized;

    // Draw aligned gravity vectors for ease of debugging.
    Debug.DrawRay(transform.position, gravityAlignedForward * 0.25F, Color.green, duration, false);
    Debug.DrawRay(transform.position, gravityAlignedRight * 0.25F, Color.magenta, duration, false);
    Debug.DrawRay(transform.position, gravityAlignedDown * 0.25F, Color.red, duration, false);

    // And draw the absolute values which helped me set them up.
    // That is, i had to experiment my way forward to each of these...
    text.text += "gravityAlignedRight: " + gravityAlignedRight + "\n";
    text.text += "gravityAlignedForward: " + gravityAlignedForward + "\n";
    text.text += "gravityAlignedDown: " + gravityAlignedDown + "\n\n";

    // Get dot products for yaw, pitch and roll so we can set the appropriate sign on the final YPR readings.
    var yawDot = Vector3.Dot(gravityAlignedForward, gravityEast);
    var pitchDot = -Vector3.Dot(gravityAlignedDown, gravityAlignedForward);
    var rollDot = -Vector3.Dot(transform.up, gravityAlignedRight);

    // Measure angle between the aligned gravity vectors and the vehicles forward and right vectors.
    // yaw is special in that it uses the aligned forward gravity vector. Don't ask me why, i wouldn't know... ;)
    var yaw = Vector3.Angle(gravityAlignedForward, gravityNorth) * Mathf.Sign(yawDot);
    var pitch = Vector3.Angle(transform.forward, gravityAlignedForward) * Mathf.Sign(pitchDot);
    var roll = Vector3.Angle(transform.right, gravityAlignedRight) * Mathf.Sign(rollDot);

    // Debug text showing the results of all this... It works, finally.
    text.text += "yawDot: " + yawDot + "\n";
    text.text += "pitchDot: " + pitchDot + "\n";
    text.text += "rollDot: " + rollDot + "\n\n";

    text.text += "yaw: " + yaw + "\n";
    text.text += "pitch: " + pitch + "\n";
    text.text += "roll: " + roll + "\n";
}

```

---

## Debug shots

Some shots where everything just works... I am happy now because i can actually port this to the other project! (I hope)

**Ok, so i made a mistake when taking the screenshot, pitch from 22.5 to 135 in unity**

And with all that said, thanks to everyone that read and tried to help me out. I never want to have to figure this out again...

**That being said**, i still would very much appreciate input on what i have done and if it can be simplified in any way as well as perhaps some *eureka* hints you could send my way to actually make me understand what i have done here.

Cheers!

## EDIT:

IT WORKS! ;)
Thanks again!

# Answer
> 2 votes
I will try to break down the step-by-step questions I'd take to solve this problem, with the hope it helps you to understand how to go about solving vector-related problems in the future.

Note: I'll be using radians, and even if your final on-screen output is in degrees I recommend you do calculations in radians as opposed to degrees, since they behave more nicely in a number of ways (for example, you don't have to use additional scaling factors when recalculating angular velocity or acceleration). There's a reason why just about any math library uses radians. Also, sin and cos are defined assuming angles increase going counterclockwise, so you may have to adjust for that. If you prefer clockwise angles and degrees, that's just a matter of multiplying by -1 and 180/pi respectively where appropriate.

**Q) What is `pitch`?**
A) `pitch` is the angle between a `direction` and the horizontal component of that direction (which we'll call `heading`). of course, "horizontal" depends on your definition of "up", so we use the gravity vector.

```
float pitch(Vector3 direction, Vector3 gravity) {
    Vector3 heading = projectOnPlane(direction, gravity);
    return angleBetween(direction, heading);
}

```

**Q) What is Yaw?**
A) Yaw is the angle between the `heading` and `north`. So, it looks very similar to the pitch equation:

```
float pitch(Vector3 direction, Vector3 gravity, Vector3 north) {
    Vector3 heading = projectOnPlane(direction, gravity);
    return angleBetween(direction, north);
}

```

**Q) Okay, but how do I get the `heading` -- the "horizontal" component (i.e. perpendicular to `gravity`) of a `direction`?**
A) formula:  See this formula from Wikipedia:Vector Projection, although you may find easier places to read on vector projection. To project on to a plane, you subtract the vector projection on the normal vector of the plane from the original vector. Or, phrased in english, to get the horizontal component of a vector, you subtract the vertical component from the original vector. Translated verbatim into code:

```
float projectOnPlane(Vector3 a, Vector3 b) {
    Vector3 bProjection = (Vector3.Dot(a, b) / b.Length) * (b / b.Length);
    return a - bProjection;
}

```

**Q) How do I get the angle between two vectors?**
A) Most places tell give you some Equation that looks like . However, this will return the same value for either a clockwise or counterclockwise rotation, and we want the *signed* angle. So, we want the Atan2-based formula:

```
 float angleBetween(Vector3 a, Vector3 b) {
    return Math.Atan2(Vector3.Cross(a, b).Length, Vector3.Dot(a, b));
 }

```

Tada! we're done!

---
Tags: unity, c#, vector, angles, euler-angles
---


# Question
Title: How do I create a view matrix that does not contain the camera translation?
I'm looking at this tutorial https://capnramses.github.io/opengl/cubemaps.html about half way down the webpage, there is a description of a vertex shader

```
#version 400

in vec3 vp;
uniform mat4 P, V;
out vec3 texcoords;

void main() {
  texcoords = vp;
  gl_Position = P * V * vec4(vp, 1.0);
}

```

> The P and V matrices are my camera's projection, and view matrices, respectively. The view matrix here is a special version of the camera's view matrix that **does not contain the camera translation**. Inside my main loop I check if the camera has moved. If so I build a very simple view matrix and update its uniform for the cube map shader. This camera only can only rotate on the Y-Axis, but you might use a quaternion to generate a matrix for a free-look camera. Remember that view matrices use negated orientations so that the scene is rotated around the camera. Of course if you are using a different maths library then you will have different matrix functions here.

I'm having difficulty figuring out how to construct this matrix in my program. How would I construct it from a projection matrix, view matrix, or camera matrix? (These are the matrices already within my program)

# Answer
Okay so I cannot open that link from where I am, but from what I can draw from your text, this is a shader for a cube map, right?

The point of a cube map is that you (the camera) are always at the center of it. You only change the part of the map you can see by rotating your camera. You still are able to move the camera, the skybox just does not change then.

So what you need for your program is two states of the view matrix - one with a possible translations (movement) and one without.
You use the one with translation for every asset in your scene that you want to change position relative to the camera when it moves.
You use the one without translation for the cube map, that is always centred on the camera. The latter one is the one your text talks about.

I can think of two approaches at getting those matrices:
1) Have 2 view matrices "a" and "b" at the start of the game loop. Apply rotations and translations on "a", use that for the first case. Apply only rotations on "b", use that for the skybox.
2) Have 1 view matrix. Apply rotations on it, update your cube map view matrix uniform, then apply translations and update the view matrix uniforms in your other shaders where needed.
> 1 votes

# Answer
In fact you don't need to create a second matrix separately. To remove any translation you just need to cast the matrix to `mat3` and back to `mat4`.

It will change following numbers in the matrix

```
- - - 0
- - - 0
- - - 0
0 0 0 1

```

effectively removing any translation.
> 4 votes

---
Tags: opengl, camera, glsl, matrix, skybox
---


# Question
Title: What do you do with "Player Start" and "Pawn" objects when setting up the default VR game in Unreal?
I followed the setup tutorial provided by Unreal from here but after setting up the pawn and the VR\_GameMode you don't do anything with them. They are never added to the scene or anything and the default game comes with a "Player Start."

Is the "Player Start" object supposed to be removed? If you remove that then running the VR Preview shows the game from wherever your camera is in the viewport and there is no game location. Adding the pawn to the scene doesn't seem to do anything. The final image they show doesn't have the "Player Start" object in the scene at all and they never mention it so I'm unclear about how to complete this process.

Adding the pawn to the scene seems to have no noticeable affect on how the game is run in VR Preview. What's the proper last step?

After following the instructions exactly as-is the floor is way below the current start point and modifying the Z values as instructed has no affect on the floor. Moving the "Player Start" does, but this could have been done from the very beginning without doing any of the setup with the pawn or the GameMode.

# Answer
> 1 votes
You have to change the project settings to tell the level to pick your pawn as PlayableActor. This can be changes from eithert edit-\> project settings -\> maps\**

or from the world settings.

# Answer
> 0 votes
My setup was:

1. Remove PlayerStart
2. Add a YourPawn on the map and adjust camera transform as you needed, also select Auto Posses Player 0 for the pawn.
3. Override YourGameMode::FindPlayerStart() (in C++ or BP) to return the YourPawn on the map.

---
Tags: unreal-4, virtual-reality, htc-vive
---


title: Exporting unity features to your game

text:
# Question
Title: Exporting unity features to your game
I wonder if it is possible to export Unity features to my game.

For example if I want user to be able to modify scale or rotation of object, do I have to scritp it myself or can i somehow export it ? Same question about some simple texturing, adding lights, etc.

# Answer
No, you will have to implement this yourself.

While you can access some of the classes from the `UnityEditor` namespace while testing in the editor, they are unavailable when you actually build the game. The result will be that the game will fail to compile.

So if you want any editing functionality within your game, you need to build that yourself using the Unity UI system with the widgets it provides.
> 2 votes

---
Tags: unity, export
---


title: Smooth 1D terrain generation

text:
# Question
Title: Smooth 1D terrain generation
So I'm pretty happy with my terrain, and the progress on my game. I just want to figure out why the terrain is so steep sometimes. Right now to generate my random seed I use this:

```
seed = (long)(Math.random() * 10000000 + 12345670);

```

It works, but some of the seeds just make a really steep point hill, while I'm looking for more bumpy-flat maps (similar to Terraria's).

Here's my create terrain loop:

```
for (int i = minX; i < maxX; i++) {
    int columnHeight = p.getNoise(i, maxY);
    for (int j = 0; j < columnHeight; j++) {
        System.out.println(columnHeight);
        map[i][j] = new Tile(i * 8, j * 8, 8, 8, TileType.Grass);
    }
}

```

Here's the class I'm using to try to generate terrain. I tried tweaking parameters but nothing works, and I just keep getting crazy random hills.

```
public class Perlin {
    private long seed;

    // Constructor to create a seed
    public Perlin(long seed){
        this.seed = seed;
    }

    // Fetches a random value
    private int random(int x, int range){
        return (int) ((x + seed) * (x + seed) * 8) % range;
        // o = (int) (((x + seed)*(x + seed))*5) % range
        //return o;
    }

    // Calculates the noise
    public int getNoise(int x, int range){
        int chunkSize = 64;

        int chunkIndex = x  / chunkSize;

        float prog = (x % chunkSize) / (chunkSize * 1f);

        float left_random = random(chunkIndex, range);
        float right_random = random(chunkIndex + 1, range);

        float noise = (1 - prog) * left_random + prog * right_random;

        return Math.round(noise);
    }
}

```

Here's a picture of the terrain compared to what I want (what I want is in red):

**EDIT** So I understand what you guys mean about the previous Perlin class not actually being perlin noise. I fixed it with some tweaking and using actual perlin noise, the only thing I'm partially confused about is the seeds, and how do they work..

for example in Java this is how they do it

```
x = (x<<13) ^ x;
return (float)( 1.0 - (( (x * (x * x * 1376312589 + 789221) + 1376312589) + 3517) & Integer.MAX_VALUE) / 2543768824f);

```

if someone could explain what all that really means it'd be great, and why does it use prime numbers?

# Answer
> 2 votes
I didn't get the entire gist of all the functions you provided, but it seems to me that you are looking for something like a random walk or martingale algorithm, where you have an equal probability of the terrain height step to go up or down in comparison to the terrain one step ago. Doing this, your terrain remains random but essentially smooth and without crazy drops and most likely mean level in the long run.To illustrate, try something like this :

```
int posneg = rand() % 17 + (-8);
height[i+1]=height[i] + posneg;

```

You should obtain a height terrain similar to the requested red line.

You can tweak the line with a deterministic trend within a longer range, ensuring that there is a mountain building up or a dale for some while.

```
height[i+1]=height[i] + posneg + trend;

```

Where trend is a random number between - 4 and 4 that remains constant for, let's say, 50 iterations of i. You may wish also to have int(50/aPower) iterations and pow(trend, aPower), where aPower is a random number 1, 2 or 3 to have the mountains a bit less boring and occasionally very steep. And finally, you may play with going an iteration back for a few steps by a small random chance to have an overhang.

# Answer
> 1 votes
Just for the record, here you can check the original Perlin docs, where everything is greatly explained. Basically perlin points are generated and interpolation is done between them. The spacing between points will state the terrain's *rugosity*.

# Answer
> 0 votes
the steps to do this are:

* generate a list of N random heights int h\[\];
* generate a list of N-1 distances where distance is the difference between the 2 heights dist=abs(h\[i\] - h\[1\])
* use this information do draw your line segments with the desired amount of noise where the number of segments between points is \<= distance.

this will ensure that the average change in height is constant. experiment with adding a small amount of randomness to the list created in step 2.

# Answer
> 0 votes
The seed determines the specific output of your noise algorithm for each particular number, but does not determine the "phenotype" of your terrain, which is the general way it looks accross all possible seeds.

That look depends on the noise generation algorithm itself - frequency, octaves, amplitude and the smoothing. The seed doesn't have anything to do with it. Look into the various tutorial on Perlin and Simplex noise (complicated), value noise (simple) or other techniques. They will all have a section about the different variables in the noise generation formula and how they affect the outcome.

---
Tags: java, libgdx, perlin-noise, noise
---


title: pixi.js - PIXI undefined

text:
# Question
Title: pixi.js - PIXI undefined
I am using pixi.js to learn about HTML5 game development. When using this line of code

`var bunny = new PIXI`

I get an undefined error saying that PIXI isn't defined.

Here is my HTML

```
<!doctype html>
<head>
    <title>PixiJS</title>
    <meta charset="UTF-8">
</head>

<body>

<script src="https://cdnjs.cloudflare.com/ajax/libs/pixi.js/4.2.2/pixi.min.js"></script>
<script src="index.js"></script>
</body>

```

# Answer
> 1 votes
First, check that Pixi is working with:

```
console.log(PIXI);

```

If this does not spit out the Pixi object, you will have to google your specific error, or come back here. Since you mention trying to learn, I have to ask, you are running this code on a webserver (local or otherwise), right? The Pixi "Getting Started" tutorial mentions this as a requirement. If you don't have a local server stack (WAMP, XAMPP, MAMP, etc) running, Pixi will not work.

---
Tags: html5
---


# Question
Title: Get different result on different devices (same resolution) after setVelocity
I'm dying with physics , i've tried to use `setVelocity` however i got slightly different value from different devices.

I've tested on iPhone 5 (on simulator) and iPhone 6 (real device) The `Director::getInstance()->getOpenGLView()->getFrameSize()` returns both devices is 640x1136 pixels

But i see they have different result after the animation , its about 2-5 pixels. I really don't know why.

I'm making a multiple player game so i need exactly same coordinates of objects on every devices. Does cocos physics return randomly result?

---

After deep digging, i realize that even i set specific velocity for one object in same device will return different result.

So i don't think this is about the devices, Chipmunk returns different result with the same input parameter!

# Answer
> 1 votes
You are talking about obtaining a deterministic physics simulation. Are you running a fixed timestep?

https://chipmunk-physics.net/tutorials/ChipmunkColorMatch/Tutorials/ColorMatch-ChipmunkPro-Cocos2D.html

> Now let's skip ahead to the update: method. This is the method that Cocos2D calls each time before it draws a frame. The dt variable that it passes is usually going to be about 1/60th of a second, but it's never quite consistent. This is somewhat undesirable for the physics. It's not a good practice to update the physics with these variable sized timesteps because sometimes the CPU might be busy for a few frames. Then the next time you update the physics enough time may have passed so that objects can pass through each other. It also makes the gameplay very non-deterministic and it will act a little differently depending on the framerate.
>
> Instead, you'll want to implement a fixed timestep with Chipmunk. This is really easy to do. I usually do this in all of my games, not just physics ones for the same reasons. Keep the code that updates graphics in update: and create a separate tick: method that handles all the game logic and runs with a fixed timestep. If you want to know more about fixed timesteps, the article in the comment below is a good resource.

# Answer
> -1 votes
So your physics simulation relies on the visualization of your games' objects on screen? Or is that just the symptom you were able to identify that point to your problem: getting different results for the same algorithms on different machines.

Is it just the positioning on screen that is different, or did you look under the hood as well: Are the calculated results REALLY different?

---
Tags: physics, coordinates, cocos2d-x, synchronization, chipmunk
---


# Question
Title: Texture with D3DUSAGE_RENDERTARGET failing to release before IDirect3DDevice9::Reset
Creating the texture:

```
IDirect3DSurface9 *bbsurf;

if (SUCCEEDED (Device->GetRenderTarget (0, &bbsurf)))
{
    D3DSURFACE_DESC desc;

    if (SUCCEEDED (bbsurf->GetDesc (&desc)))
    {
        Device->CreateTexture (
            desc.Width,
            desc.Height,
            1,
            D3DUSAGE_RENDERTARGET,
            desc.Format,
            D3DPOOL_DEFAULT,
            &GAndCRT,
            NULL);
    }

    // don't leak
    SAFE_RELEASE (bbsurf);
}

```

Before Resetting the device:

```
GAndCRT->Release ();
GAndCRT = NULL;

```

I've commented out all other code that refers to this texture but the texture still fails to Release and the device Reset fails. To be clear: the above *is* the minimum complete example to reproduce the problem.

Commenting out the CreateTexture call and obviously the device will succeeed to Reset.

There are about 4 other textures also created with D3DUSAGE\_RENDERTARGET which Release OK.

I know there's no magical incantation that will say "please *really* Release this texture, so what I'm looking for is information and/or advice on how to best go about troubleshooting this further, rather than an actual answer.

# Answer
> 0 votes
Resolved.

The code for creating the texture was being called twice during system startup owing to an unitialized BOOL flagging whether the D3D device was lost.

---
Tags: directx9
---


# Question
Title: 2D - Need help understanding how to resolve multiple collisions in a simple physics engine
I am trying to create a small game engine in Java using only basic openGL functions and implementing everything else from scratch.

I am trying to get a basic physics engine working (similar to box2D only much simpler), I managed to detect collisions between my different bodies using SAT and I followed this tutorial to try and implement collision resolution.

It seems to be somewhat working but there are still some issues left. The biggest one is that when I have multiple objects colliding they seem to be sinking into each other (however everything works fine with only two objects). Here's an example demonstrating what I'm talking about:

Here is my code used to resolve collisions:

```
    /**
 * Resolves the collision
 */
public void         resolve()
{
    TekRigidBody    bodyA;
    TekRigidBody    bodyB;
    TekVector2f     rv;
    TekVector2f     impulse;
    TekVector2f     correction;
    float           normalVelocity;
    float           massSum;
    float           ratio;
    float           e;
    float           j;

    bodyA = collider1.gameObject.getBehavior(TekRigidBody.class);
    bodyB = collider2.gameObject.getBehavior(TekRigidBody.class);
    if (bodyA == null || bodyB == null || (bodyA.getInvMass() == 0f && bodyB.getInvMass() == 0f))
        return ;
    rv = TekVector2f.sub(bodyB.velocity, bodyA.velocity);
    normalVelocity = rv.dot(normal);
    if (normalVelocity > 0)
        return ;
    e = Float.min(bodyA.material.restitution, bodyB.material.restitution);
    j = -(1 + e) * normalVelocity;
    j /= bodyA.getInvMass() + bodyB.getInvMass();
    impulse = TekVector2f.scale(normal, j);
    bodyA.velocity.sub(TekVector2f.scale(impulse, bodyA.getInvMass()));
    bodyB.velocity.add(TekVector2f.scale(impulse, bodyB.getInvMass()));
    correction = TekVector2f.scale(normal, Float.max(penetrationDepth - 0.001f, 0.0f)/ (bodyA.getInvMass() + bodyB.getInvMass()) * 0.8f);
    bodyA.transform.position.sub(TekVector2f.scale(correction, bodyA.getInvMass()));
    bodyB.transform.position.sub(TekVector2f.scale(correction, bodyB.getInvMass()));
}

```

Edit: Updated code to make it easier to read

# Answer
> 1 votes
What you have stumbled onto is an extremely common problem in physics: The three body problem (though it's slightly different in real world physics).

There are a couple of solutions to this I'm aware of:

1. Post-impulse correction. This requires you re-iterating over the bodies after applying impulses, and correcting any remaining intersections.

Pro: relatively simple to code (repeat narrow phase)

Con: It's expensive and doesn't guarantee the problem will be fixed.

2. Normal force computation: compute an additional "normal" force, designed to push objects apart, regardless of their velocities. The strength of the force is dependant on penetration depth.

Pro: cheap (computationally speaking. It's only an extra couple of lines of code.

Con: It might make your objects behave a little weird in extreme cases, for example, make them fly up so fast they never come back down.

# Answer
> 0 votes
I can suggest Baumgarte Stabilization

try adding a bit of energy in your impulse calculation

```
b = beta*penetrationDepth;
j = -(1 + e) * normalVelocity + b;

```

And beta is a "small" constant : "Erin Catto proposed that you start increasing the value from 0 until your physics system starts to become unstable, and then use half that value."

---
Tags: java, 2d, physics, collision-resolution, rigid-body-dynamics
---


# Question
Title: Javascript game engine that can work 'seamlessly' with react-native
I have experience with Unity, but I don't like the fact that Unity compiles your game directly into APK (or IOS equivalent). I want to modify the game to provide chat interface for multiplayer mode etc. So, I thought of doing it the other way - create an app and embed a multiplayer game within it. This approach meant that I had to develop for Android and iOS, separately. I then came across the React-Native library, a mobile extension of the popular React framework.

I have decided to create an app using React-Native, but now I am confused as to which game engine I should use. I think, since React-Native is JavaScript, the game engine needs to be in JavaScript for seamless integration. I am planning to use WebView to embed the game in my react-native app.

Can anyone suggest a good JavaScript game engine that can be used along with react-native? I have done some research on Phaser and Pixi, but they use WebGL for rendering and, I read somewhere that WebView doesn't have great support for WébGL or Canvas.

# Answer
> -2 votes
I would recommend using phaser, it should work

---
Tags: javascript, html-canvas, mobile, webgl
---


# Question
Title: How to tilt an object(2D) after collision and the rotate continuously
I am having trouble rotating and object after collision. The object only transforms to the given angle of rotation once and stops. I would like to achieve in a way that after it has collided with the player object it rotates continuously till its killed after exiting the screen. The `OnCollisionEnter2D(Collision2D collision)` can't achieve this.

How can I achieve it using the `FixedUpdate` function?

Here is the code:

```
namespace Assets.scripts
{
    public class Barmovementscript : MonoBehaviour
    {
        public float Tilt;

        private void FixedUpdate()
        {
        }

        // upon collision the object rotates in a clockwise direction.
        void OnCollisionEnter2D(Collision2D collision)
        {
            if (collision.collider.tag == "Player")
            {
                Tilt += Time.deltaTime * -10;
                gameObject.transform.rotation = Quaternion.Euler(0, 0, Tilt);
            }
        }
    }
}

```

# Answer
> 1 votes
Simply make the collision event change a Boolean. And rotate your object if the Boolean is true in the fixed update

# Answer
> 1 votes
Keep a `float` called, say, "spin," indicating angular velocity. In your `Update` method, update your `Tilt` with `Spin`, and recalculate your quaternion.

(I haven't tried to compile this.)

```
namespace Assets.scripts
{
    public class BarMovementScript : MonoBehaviour
    {
        // angular velocity
        public float Tilt;
        public float Spin;

        private void FixedUpdate()
        {
            if (0.f != Spin)
            {
                Tilt += Spin * Time.deltaTime;
                gameObject.transform.rotation = Quaternion.Euler(0, 0, Tilt);
            }
        }

        // upon collision the object rotates in a clockwise direction.
        void OnCollisionEnter2D(Collision2D collision)
        {
            if ("Player" == collision.collider.tag)
            {
                Spin = -10.f;
            }
        }
    }
}

```

For a slightly cleaner (IMHO) approach, just use Verlet integration. In `FixedUpdate()`, get the difference between current tilt and that in the previous frame, add it to Tilt, and update your transform:

(Again, I haven't compiled this.)

```
namespace Assets.scripts
{
    public class BarMovementScript : MonoBehaviour
    {
        // angular velocity
        public float Tilt;
        private float m_prevTilt;
        private float m_prevDT = 1.f / 60.f; // lame hack, assume 60FPS initially.

        private void FixedUpdate()
        {
            var dTheta = Tilt - m_prevTilt;
            var dt = Time.deltaTime;

            if (0.f != dTheta && 0.f != m_prevDT)
            {

                Tilt += dTheta * dt / m_prevDT;

                gameObject.transform.rotation = Quaternion.Euler(0, 0, Tilt);

                m_prevTilt = Tilt;
            }

            m_prevDT = Time.deltaTime;

        }

        // upon collision the object rotates in a clockwise direction.
        void OnCollisionEnter2D(Collision2D collision)
        {
            if ("Player" == collision.collider.tag)
            {
                Tilt = Time.deltaTime * -10;
                m_prevDT = Time.deltaTime;
            }
        }
    }
}

```

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


# Question
Title: Creating a "world" for evolution of programs
I am trying to create a "world" where "copies of programs" are allowed to evolve, proliferate and fight for resources. Organisms copy information with errors and memorize the results. It seems like one can create a "world" with resources, place various copies of a program and let them fight for resources, grow and evolve.

What would it be for Java programs. World has cells each producing certain amount of letters per tic. An organism is a `String` of text that `extends Life`, compiles correctly, has methods `eat`, `move` and `breed`. Every tic `move`, `eat`, `breed` are executed. On `move` organism can decide to move to nearby cell. On `eat` it can move all free letters from cell to it's body (store those behind `/* here */` to make sure program compiles). During `breed` stage it it can build it's own copy using letters from the commented area of the program body. Copying is error prone. If the resulting copy compiles it joins the race for resources.

Here are the problems I am having: A single character change in a program tends to cause compile time error. How to increase survival chances of an offspring with a point mutation? IRL organisms eat each other. How to model predator attacking prey? Some simple `injectPoison(prey);` that injects `*/` between 50th and 51st characters in the body of prey string would kill pretty much any program. Something like "to fight: run Robocode - winner gets all loser's letters" would turn the world into a Robocode engine competition. IRL organisms do exchange information. One can allow programs to exchange their methods, but then it is very tempting for a program to just inject a suicide method and eat the body of dead partner.

My questions are: Is there any research on building such world? What is the best way to model resources? What limits the extent of evolution in such models.

# Answer
As mentioned in the comments, for most practical purposes, you need to select a level of granularity / abstraction that can be easily modified without invalidating the code. When I studied artificial life in graduate school, the option were to either:

* directly use a language that was well suited to symbolic programming (we used LISP at the time)
    + this is less work up front since you're not building your own custom language, although this is not true if you have to learn a new language that's signifgantly different from what you're used to using
    + gives more flexibility since technically anything that could be coded could be generated by the simulation
    + often takes longer to converge on a solution since there are typically way more wrong / inapplicable programs than correct / relevant ones
* create your own op codes & and interpreter for them in what ever language you want (I used C++ to reimplement the Santa Fe Trail Problem)
    + this is more work up front since you have to build at least some of your language before you can start evolving/ simulating stuff
    + gives less flexibility since you're opcodes are typically tailored to a specific problem
    + often takes less to converge on a solution since you typically have fewer opcodes than a general purpose programming language & they're typically all relevant to your problem of interest

Having tried both, I favor the roll your own approach, but both have there place. From a game dev perspective, it's probably better to roll your own since you can constrain things for safety - not cool if you allow the user to evolve a program that nukes their hard drive.
> 3 votes

# Answer
Speculative question indeed, and thus a bit unwelcome here, but a favourite topic of mine. A-life is a fascinating field, as is Evolutionary Computing and related / sub-fields like Genetic Programming.

> A single character change in a program tends to cause compile time error.

Then don't model the program code in that way. Rather ensure that any given string (perhaps within some enforced set of parameters such as a max length, or only unique characters in the string) can always be interpreted as a compilable program. For example `A` might denote a certain ability/functionality on its own. This has been done I believe, though I forget the name(s) of the language(s) in question.

It could even be as simple as that every character in the ASCII range has some fixed meaning within the context of your "organism", e.g. `Z` means it is motile. That's a very simplistic scheme, though.

> RL organisms eat each other. How to model predator attacking prey?

Perhaps you have some standard approach, like in Chess where moving onto the enemy's cell is in itself an attack. This obviously implies that organisms are "territorial".

```
Is there any research on building such world?

```

You're certainly not the first to foray into this area, though not sure anyone has written a game that has executed these ideas really well (as in hit title). Also, see the aforementioned fields for *much* more.

> What is the best way to model resources?

That's a very open-ended question. I would say the choice is initially between abstractly and spatially. Spatially probably makes for a more visually engaging gameplay experience. Set it up on a grid. Let them fight for resources and find their tactics through spatial engagement... as e.g. cells in tissue.

> What limits the extent of evolution in such models.

Combinatorial complexity. Just how many permutations does your code support, and just how many are you planning to test, and just how many thousands of CPU hours will that take? The simpler you keep it, the more testable it is. Then again, games like Go show that even an incredibly simple ruleset can lead to extremely deep gameplay.

**A word of advice.** There really are a million directions in which you could take this. Anything heavily procedural and close to pure logic / mathematics is prone to quickly getting bogged down in exceeding complexity, when looked at from a creative standpoint. In a way, you're playing with the fundamentals of existence, so try to limit your *depth* in terms of design, at every step. Fast prototyping / iteration and rapid elimination of potential design paths will be your best friends in this endeavour.
> 3 votes

# Answer
There is quite a lot of research in that area. But usually the agents are not controlled by programs written in programming languages humans would code in. A popular choice to control evolving AI agents are neural networks. They are rarely completely crippled by small mutations but can still form surprisingly complex behaviors.

A project very similar to what you seem to want to do based on neural networks is Critterding.

If you want to create something similar with a real-world human programming language like Java, you might not want to work on the level of single characters, because these are practically guaranteed to break the program. Rather go up a step in abstraction and deal with permutations on basis of the syntax tree. That way you will have a much easier time creating permutations which might actually be valid programs.
> 1 votes

---
Tags: algorithm, ai, evolution
---


# Question
Title: How do I use SharpDX with the .NET Core framework?
I started a project to build a game engine. As a result of circumstance, I won't have the luxury of building the engine in C++, so I'm going to have to settle for C# with the .NET Core.

Given that background, I thought I would use SharpDX to supply me with some basic functionality to build my engine on top of, except it seems like SharpDX doesn't support .NET Core, and only supports .NET Native. After testing it, and trying to include SharpDX in my dependencies file, Visual Studio Code explicitly tells me that SharpDX conflicts with .Net Core and it couldn't be installed. However, an issue posted to their GitHub page seems to imply that they might support .NET Core.

Unfortunately, this is the only piece of information I found regarding SharpDX supporting .NET Core, so I'm not entirely sure if support was ever implemented or not. Perhaps I'm just not including it correctly in my project file.

Does SharpDX support .NET Core, and if so how do I link against those libraries properly in VS Code?

# Answer
> 1 votes
So, for anybody looking to find an answer to this in the future, the answer is "No." You can not use SharpDX with .NET Core (note that VS Code supports only .NET Core if you develop in C#).

Your options are not using SharpDX or porting to VS Community. I personally chose to port to VS Community because it is a trivial move and allowed me to continue to use SharpDX. Not using SharpDX is not particularly practical for people looking to have the experience of creating your own game engine from the ground up (without using C++), because the alternatives are somewhat non-existent now. OpenTK is dead, SlimDX is dead, and Monogame (and other frameworks of that ilk) are a little too "engine-y" as it is in my opinion to get the whole experience.

Anyway, that's what I found after multiple hours of searching, but if you have any insight to add, don't hesitate to leave a comment.

---
Tags: c#, sharpdx, .net
---


title: LibGDX - Show a minimap

text:
# Question
Title: LibGDX - Show a minimap
I've started to develop a small roguelike game in LibGDX. I've also made a minimap class, which creates and updates the minimap as the player explores the dungeon, by using a `Pixmap`. The minimap class has an `OrthographicCamera` (currently unused), which will be used for centering the minimap on the player. The minimap is currently rendered with it's own `SpriteBatch`. Now I'd like to put the minimap on the upper right corner, and clip it, because it is so big, that it'd obscure the half of the screen. I'm not really sure how to do this clipping part. I assume I should use the `ScissorStack` class, but the LibGDX wiki is a bit uninformative for me.

# Answer
first, you are using more than one SpriteBatch? Don't do that. Share one instance.

Clipping works really simple that you push a Rectangle to the stack, render what you need (only stuff in your rectangle will be drawn) and afterwards pop the rectangle.

However, the best way to achieve a minimap is with the viewport class.

your render queue should look something like this:

1. viewport of your game (might be more than 1 camera for parallax)
2. viewport of the minimap
3. scene2d or whatever you are using for ui

The default implementations of the viewport are setting the lower left corner to 0, 0 by default, so you need your own implementation:

```
public class InteractiveViewport extends ScreenViewport{

        public InteractiveViewport(OrthographicCamera camera){
            super(camera);
        }

        public void update (boolean centreCamera) {
            setScreenBounds(getScreenX(), getScreenY(), getScreenWidth(), getScreenHeight());
            setWorldSize(getScreenWidth() * getUnitsPerPixel(), getScreenHeight() * getUnitsPerPixel());
            apply(centreCamera);
        }

    }

```

set world **width**, **height** and **x,y** position of the lower left corner to whatever position in screen cords you want. With some more work you can make minimap interactive as in able to pan and zoom; and even resizing. And if needed clear the background of the viewport with 0.5f alpha for a cool effect.

The advantage of the viewport is that it sets the gl\_viewport to the size of the viewport and you dont have to bother with complicated coordinate transformation to make your map work.

You might want to take a look at something similar I wrote. I hope it helps. https://github.com/Heerbann/Box2dCamera
> 4 votes

# Answer
As you are using a pixmap you can clip it easily. I am not on desktop so I am giving a pseudo code for now.

```
for( int x = player.x - desiredMapWidth / 2, i = 0; x < player.x + desiredMapWidth / 2; ++x, ++i) {
    for( int y = player.y - desiredMapHeight / 2, j = 0; y < player.y + desiredMapHeight / 2; ++y, ++j){
    Color c = fullMinimap.getPixel( x, y );
    clippedMinimap.setPixel( i, j);
    }
}

```

Note: code may be different from exact code. I just tried to show the way.
> 0 votes

---
Tags: libgdx, clipping
---


# Question
Title: per-pixel collisions using Libgdx Java (is there existing class for this??)?
I am making a simple side scrolling space shooter game using Libgdx and everything is going nicely. However until now I haven't been testing collisions for my players ship with other ships. I have lasers colliding with baddie ships using simple rectangle overlap method that exists already in libgdx.

But the "white/transparent" space around the edge of many of my sprites is quite a lot and when i am now applying the code to check collision with my player it is happening from a long way off from actual collision. In the past I used XNA Framework C# and there was quite a simple way to do a box collision and then within that test if both pixels in question where transparent and ONLY WHEN both pixels were NOT transparent would it return true as a collision.

I'm really struggling to find this method or how to implement this using LibGDX , can anyone help me out here??

Here is the code snippet in question, if you need the full games code please let me know:

```
        if (ship.getBoundingRectangle().overlaps(baddiePurple.getBoundingRectangle())){
        purpleDyingSound.play();
        KillPurpleSoloEnemy();
        game.setScreen(new MenuScreen(game));
    }

```

Of course I'm aware that I could just trim down all the images to have almost zero transparent edges but the problem with doing that is they are animated sprites in sprite-sheets and i can't get them into the right position if I try that. (Also, I plan on having LOTS of different enemies etc and trimming would be a major ballache)

THANKS IN ADVANCE FOR ANY HELP! peace out!

# Answer
Most games that need the type of accuracy that you want use polygonal collision. My favorite is the Hyperplane Separation Theorem. You wouldn't get pixel-perfect collision, but it will definitely reduce the problem you're experiencing. The collision doesn't need to be absolutely perfect; the player won't notice when they're in the heat of the action. Collision just needs to be good enough.

For LibGDX, you can use the Intersector class to detect polygonal collisions:

```
Polygon polygonA = new Polygon(new float[] {
        0, 0  // Vertices (x,y)
        5, 0,
        5, 5
    });
Polygon polygonB = new Polygon(new float[] {
        -10, 0
        10, 0,
        5, 10
    });

if(Intersector.overlapConvex(polygonA, polygonB)) {
    // Polygons overlap = collision
}

```

The vertices should be declared in counter-clockwise order (I'm not sure if this is a requirement for LibGDX's particular intersection algorithm, but most do so it wouldn't hurt to get into the habit of doing so). The only limitation is that the polygons must be convex. However, this can be easily worked around by splitting the polygons into smaller polygons that are convex while the general shape of all the polygons is concave.
> 1 votes

# Answer
Does xna support gpu based collision detection out of the box? Libgdx does not have such a thing.

In general I would not advice to write your own collision implementation and rather use box2d. Of course you can use intersector for a more simple approach but you will quickly run into performance issues and you will need to solve problems like spatial partitioning and checking broad/ narrow phase which box2d already has.
> 1 votes

---
Tags: java, libgdx, collision-detection, game-design, per-pixel
---


# Question
Title: Memory leak while loading libgdx game screen
So, I have a lot of texture atlases in my code for a talking tom type libgdx, and I use around 6 of them per screen. The app crashes abruptly without any errors on devices with 1gb ram or less. I started profiling my code and found that I have 3500+ texture bindings, how should i minimize these?

# Answer
> 1 votes
Are you using the AssetManager? You can load/unload only when a texture is needed and in the end discard all at once. Furthermore, there should never exist more than 1 instance for every unique texture (atlas). Share a pointer with all your entities.

https://libgdx.badlogicgames.com/nightlies/docs/api/

# Answer
> 1 votes
Maybe you have local variable and you create those objects with those variables. Textures in libgdx doesn't have garbage collector. You must free the memory yourself with the method dispose().

---
Tags: android, libgdx, android-studio
---


# Question
Title: NavMeshAgent is not calculating a new path
I have the following code that gets run when a game object collides with a trigger. When the object is created, it is created within an initial trigger which fires the `SetNextWaypoint` code below and it works fine.

```
protected NavMeshPath path;
protected NavMeshAgent agent = null;

void Start () {
    path = new NavMeshPath();
    agent = GetComponent<NavMeshAgent>();
}

public void SetNextWaypoint(Vector3 location){
    agent.ResetPath();
    path.ClearCorners();
    agent.CalculatePath(nextWayPoint, path);
    agent.SetPath(path);
}

```

Once the agent enters a new waypoint (it may not have reached its destination yet) `SetNextWaypoint` is called again and when it does the agent just stops where it is, and doesn't move anywhere.

# Answer
> 0 votes
I figured it out! The issues was that my next waypoint was positioned too far above the NavMesh. But for some reason `path.status` was still returning `PathComplete`.

Moving the Waypoint closer to the navmesh allowed the object to go to the next Waypoint instead of just stopping.

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


title: Random copies of an object?

text:
# Question
Title: Random copies of an object?
If I press C\<\kbd\>, several copies of a prefab show up in the scene. However, my script only creates one. I need to make a random copies, like between 1 to 5.

How do I do this?

```
if (Input.GetKey(KeyCode.C))
{
    Instantiate(Diamonds,transform.position,transform.rotation);
}

```

# Answer
> 1 votes
You actually have a couple of problems, here. I am going to try and tackle them, in order, to best explain your situation and solution.

## Input with `Input.GetKey`

First and foremost, for the type of reaction you want your input to have, you are most certainly using the wrong `GetKey` method. Let's take a look at `GetKey`, in the Unity API:

> ### Input.GetKey
>
> public static bool **GetKey**(KeyCode**key**);
> **Description**
> Returns true while the user holds down the `key` KeyCode enum parameter. ***Think auto fire***. \- Input.GetKey @ docs.unity3d.com/ScriptReference

Your checking if the key *is* pressed; however, your game updates 50-60 times, per second. If you check if the key *is* pressed, you are going to have multiple method calls; nobody can explicitly press a key for 1/60th of a second. You *want* to be checking if the key *was* pressed. This way, we only call the method *once*.

> ### Input.GetKeyDown
>
> public static bool **GetKeyDown**(KeyCode**key**);
> **Description**
> Returns true during the frame the user **starts** pressing down the `key` KeyCode enum parameter.
> **You need to call this function from the Update function**, since the state gets reset each frame. It will not return true until the user has released the key and pressed it again.
> \- Input.GetKeyDown @ docs.unity3d.com/ScriptReference

### Making Multiple Copies

Next, we need to actually make the multiple copies. In your case, you have a line that makes a single copy. Forget the multiple copies that spawn, as with correct input implementation, this will give you a single object:

```
Instantiate(Diamonds,transform.position,transform.rotation);

```

How do we make multiple objects? We call the line to make *one* object, *multiple* times.

```
Instantiate(Diamonds,transform.position,transform.rotation);
Instantiate(Diamonds,transform.position,transform.rotation);
Instantiate(Diamonds,transform.position,transform.rotation);
Instantiate(Diamonds,transform.position,transform.rotation);
Instantiate(Diamonds,transform.position,transform.rotation);

```

This works, but it looks messy. We only had to copy and paste the line, so it was not much work, but we could make this look much better with a loop.

```
for(int i = 1; i <= 5; i++)
{
    Instantiate(Diamonds,transform.position,transform.rotation);
}

```

This will loop through the line, five times. In turn, this will create 5 copies of your game object.

### Using `Random`

Using random can be complicated. Luckily, it is done for you. The `UnityEngine` namespace has a method that takes in a minimum and maximum number, and spits out a random number, between them.

Note that `System` also has a method defined as `Random`. If you are using the `System` namespace, you will also have to define `Random = UnityEngine.Random`, so you ensure you call the correct method.

Also note that there are *two* variations of `UnityEngine.Random`. They are defined by the *types* you use. *Do not get them mixed up*, or you may have unexpected behaviour.

* `Random(int min, int max)` handles the values as *integer* numbers. As such, this method will randomly return a number from `min` to `max`, but will *not* return `max`.
* `Random(float min, float max)` handles the values as *floating point* numbers. As such, this method will randomly return a number from `min` to `max`, but unlike the `int` variation, *may* return `max`.

---

There you have it. When you put all of these concepts into practice, instantiating a random amount of game objects on key press is really quite simple.

```
void Update()
{
    if(Input.GetKeyDown(KeyCode.C))
    {
        InstantiateRandom(5);
    }
}

void InstantiateRandom(int max)
{
    // Increase max by 1, to include original value in random.
    // Remember, integer random will not return the max value.
    max++;

   // Convert max to a random integer within its range.
    max = Random(1, max);

    // Use the random integer to loop through our Instantiate line.
    for(int i = 0; i <= max; I++)
    {
        Instantiate(Diamonds,transform.position,transform.rotation);
    }
}

```

---
Tags: unity
---


# Question
Title: How do I handle loads of (prefab?) objects in Unity2D/3D?
I have been looking around for information regarding this process but I was unable to come across anything that would help me out. Basically, in a game where you may have many items or enemies or player objects, how would one go about creating these objects?

Am I supposed to be creating every single one of these objects as a prefab and then load them into the game when needed? Or is it possible to create one object that has references to the different variables needed to create the above objects and then load in from an external source all the necessary information? And then during run time, depending on what object I am looking at, the script will 'create' the object with the information from the external source.

Meaning, if I decide to have 50 different enemies in my game, do I need to make 50 prefabs, one for each enemy? Or just one prefab that loads in data pertaining to the 50 different enemies and then build upon that information?

Thank you!

# Answer
I would say if you know Entity Component System, and instead of inheritance would use aggregation, then you can go with one prefab. I will try to explain what I mean. You can have one prefab with components, like behaviour, movement, visual(graphic) and so on. Then you can build some sort of factory, which will produce you a different type of enemy, by instantiating an enemy prefab, loading correct asset(3d model, texture, material, etc.) and passing it to visual component; add appropriate behaviour and movement scripts and so on. It will give you a lot of flexibility. But the solution with multiple prefab configured correctly will work well. It's more about preferences.
> 2 votes

# Answer
If all the enemies are the same (model, material, script etc) then create one prefab and reuse it. If you have 50 different enemy types with unique components you will need 50 prefabs. It all depends on your needs.
> 1 votes

---
Tags: unity, data-structure
---


# Question
Title: Creating proper jump mechanics in LibGDX with Box2D?
I'm trying to create a proper jumping system for a 2D platformer with box2D, however, I'm not exactly sure how to make a good jumping system. Right now, I'm just doing

```
public void jump(float delta) {
    body.applyLinearImpulse(new Vector2(0, 7), body.getWorldCenter(), true);
}

```

What I want to do, is have a system like Mario's or Sonic's, where the height jumped is determined by how long the player held the jump button. How do I do something like that? Also, what's better, a rectangular box2D fixture, or an oval one? I'm sorry for such a newb question, and thank you for the help!

# Answer
SMB "weakens" gravity to extend jump height when these three conditions are met:

1. You are still moving upwards.
2. You didn't release the jump button since you left the ground.
3. You didn't collect a power up.

I included a link to the documentation regarding SMB jumping physics in a comment above. The idea is that you have an initial upwards speed `s` when you hit the jump button. For instance 10m/s and as long as the previous conditions are being met, gravity is much weaker or in Box2D terms, there is a continuous force pushing you upwards and that force is weaker than gravity, being about 70% as strong so gravity is reduced to 30% of it's usual strength.

This allows the player to fine tune the jump height.
> 2 votes

# Answer
iforce2d to the rescue. if you can do some vector math nothing is impossible.

https://www.iforce2d.net/b2dtut/jumping
> 1 votes

---
Tags: java, physics, box2d, jumping
---