# Question
Title: In Unity - displaying long lists of information to screen? Tables?
Hello folks I'm making a little game for fun in unity, Its a boxing management sim. I've got the code done to create boxers and give them many properties such as names, weights, stats, etc. I've made another screen , lets call it 'office screen' for now. In that I want to open a panel which will show all the boxers in the game (ideally I'd like to be able to make the player be able to filter these results by which company he's signed to etc - but I think that might be out of my skill range so maybe i will just make a separate screen for Owned Boxers)

But I cannot seem to find a way to display all these infos in a table with columns such as Name ; Age ; Company ; etc;

I have had a go just using the UI Text components and panels. But thing is, there will be approx 100 boxers or more and this number will always change also.

Any ideas for this in Unity specifically?

EDIT: I am storing all the data just as variables (i think fields) in a class called Boxer which is assigned as a component of a new GameObject i instantiate at the time each boxer is created. So each boxer has its own gameobject.

EDIT 2 :D i've found this: https://docs.microsoft.com/en-us/aspnet/mvc/overview/older-versions-1/models-data/displaying-a-table-of-database-data-cs
would this be the sort of thing I can add to Unity (assuming I can follow along with the guide)?

Thanks for any help

# Answer
Somehow I have managed to cobble something together that works. I've purely done the layout here and not pulled any data into it yet, but in case any one else has the same confusion as me, I will post the method here I used. It is actually very short method and seems to work for me after I made the Row a prefab, and make it a parent of the panel which i want the table to stretch within.

```
   public void BuildTable()
{
    // TODO: Deal with more than 10 boxers by making it sort them into pages somehow.

    // discover which boxers user owns:
    List<Boxer> ownedBoxers = new List<Boxer>();
    foreach (Boxer b in Game.instance.boxers)
    {
        if (b.companySignedTo == Game.instance.playerCompanyName)
            ownedBoxers.Add(b);
    }

    for (float i = 0; i < ownedBoxers.Count; i += rowHeight)
    {
        tableRowPrefab = Resources.Load("BoxerTableRowPrefab") as GameObject;
        tableRow = Instantiate(tableRowPrefab);
        tableRow.GetComponent<RectTransform>().SetParent(panelRectTransform);
        tableRow.GetComponent<RectTransform>().offsetMin = Vector2.zero;
        tableRow.GetComponent<RectTransform>().offsetMax = Vector2.zero;
                    tableRow.GetComponent<RectTransform>().anchorMin = new Vector2(0f, 1 - (i * 0.9f) - rowHeight);
        tableRow.GetComponent<RectTransform>().anchorMax = new Vector2(1f, 1 - (i * 0.9f));
    }
}

```
> 1 votes

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


# Question
Title: How to parent object to empty when looked at
I am making a fps in unity. I have an empty parented to the camera for the gun, and I want to be able to pick up and drop guns found in the scene. Does anyone have a simple c # script that would allow the player to look at the gun on the ground, press a key and have it be parented to the empty? I would also like for the player's old gun to drop on the floor where the one being picked up was and un-parent from the empty when the new gun is picked up. If you want an example I guess you could say it is like halo where you can go around and pick up new guns. I am not looking to make an inventory, just a simple script where you can swap your weapon.

# Answer
> 1 votes
Since the condition for picking up a gun is that it is in range (the player is nearby and looking at it) and the players presses a key, you need to maintain a list of all the guns close enough to pick up, and decide how you will choose. The simplest way, as shown here, is to pick whatever was added to the list first, but you could also choose among them based on which is closest to the player.

When the player presses a certain key ("Fire2" as set by the input manager in this case), the currently held gun's parent is unassigned, and the nearby gun takes its place. It's parent becomes whatever this script is attached to. You then move the gun to the hand's position to take it off the ground.

In your player script:

```
GameObject heldGun;

List<GameObject> nearbyGuns;

void Start() {
    //initialize guns. Assume you start not holding a gun.
    heldGun = null;
    nearbyGuns = new List<GameObject>();
}

//Another gun is close enough to be picked up
void OnTriggerEnter(Collider other) {
    if (other.tag == "Gun"  && !nearbyGuns.Contains(other.gameObject)) {
        nearbyGuns.Add(other.gameObject);
    }
}

//The player walked away; can no longer pick up the gun
void OnTriggerExit(Collider other) {
    if (nearbyGuns.Contains(other.gameObject)) {
        nearbyGuns.Remove(other.gameObject);
    }
}

void Update() {
    //Check if key is pressed and a gun is nearby
    if (Input.GetButtonDown("Fire2") && nearbyGuns.Count > 0) {
        //drop any held gun
        if (heldGun != null)
            heldGun.transform.parent = null;
        //new gun is held
        heldGun = nearbyGuns[0];
        //held gun no longer on ground
        nearbyGuns.Remove(heldGun);
        heldGun.transform.parent = transform;
        //put held gun in hand
        heldGun.transform.position = handPosition;
    }
}

```

To make this work, you'll need to set `handPosition` to the local position of the hand. You'll also need to put a trigger collider on the player/camera. Position it so that anything in the trigger can be picked up.

---
Tags: unity, scripting, first-person-shooter
---


title: Circular Particle Effect in Monogame

text:
# Question
Title: Circular Particle Effect in Monogame
I'm new to C# and Monogame, and I'm trying to create an effect of a 'psychic' ability, the user will press a key and a circular aura blast will emit from their position. I'm just trying to get the actual blast working before setting up the positions and all that, but my problem is when trying to get all the particles to move out from the origin of a circle to the outside.

I've never worked with circles yet and only with Rectangles so my knowledge of this is very basic. You'll probably recognise the code from a youtube channel and that's because I've been trying to learn from wherever I can, most of the time that leads me to youtube since a video demonstration works best but I digress.

This is my code for the particle generator so far.

```
class ParticleGenerator
{
Texture2D texture;
float spawnWidth;
float density;

List<Particles> particles = new List<Particles>();

float timer;

public ParticleGenerator(Texture2D newTexture, float newSpawnWidth, float newDensity)
{
    texture = newTexture;
    spawnWidth = newSpawnWidth;
    density = newDensity;

}

public void createParticle(GraphicsDevice graphics)
{

    particles.Add(new Particles(texture, new Vector2(graphics.Viewport.Width / 2 , graphics.Viewport.Height /2), new Vector2(5, 1)));

}

public void Update(GameTime gameTime, GraphicsDevice graphics)
{
    timer += (float)gameTime.ElapsedGameTime.TotalSeconds;
    while (timer > 0)
    {
        timer -= 1f / density;
        createParticle(graphics);
    }

    for (int i = 0; i < particles.Count; i++)
    {
        particles[i].Update();
        if (particles[i].Position.Y > graphics.Viewport.Height)
        {
            particles.RemoveAt(i);
            i--;
        }
    }
}

public void Draw(SpriteBatch spriteBatch)
{
    foreach (Particles particle in particles)
    {
        particle.Draw(spriteBatch);
    }
}

```

Many thanks for any help :)

# Answer
> 1 votes
I tend to talk to all of my objects in "Polar Coordinates" which is a vector to represent where it is in 3d space and then a "direction" in which it is facing.

I can then "point" my object in that direction, build a movement vector for it, and simply move in that direction on each update. Code that determines an angle between two points looks something like this:

```
    public static float AngleTo(float x1, float y1, float x2, float y2)
    {
        return (float)Math.Atan2(y1 - y2, x1 - x2);
    }

```

though in your case it's probably more simple than this, as you could simply create your particles an evenly divided amount of space around your object.

Unfortunately your definition for the Particle class is not here; but you should add a Movement Vector or a Rotation to it, and utilize that when you "Create" a particle to set it in motion in the correct direction.

*Note: You will want to check all four bounds of the area instead of just the upper-Y now.*

To build a movement vector in a direction, first determine what the movement vector is by default. Let's say that it's defaultMvec=(1,1,0). Now the code to change that movement vector is something like

```
mvec.X = defaultMvec.X * cos(rotation)
mvec.Y = defaultMvec.Y * sin(rotation)

```

Without understanding trigonometry on a reasonable level I'm not sure I can tell you why this is the case. Try to look up how Cos and Sin work in terms of "Radians" and get used to it a bit. Cos(Pi) for instance is -1, and Cos(0) is 1; and the gradiant of multipliers in between will make sense of the math I posted above.

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


# Question
Title: Clipping Effect in Toon Boom Harmony 15.0
I want to do similar effect like this tutorial Masking Effect. The tutorial using Toon Boom Studio 8, I'm using Toon Boom Harmony 15 and can't seem to find the Cliiping Effect they use in tutorial. Not even from Node View. Any advice to do the same effect ??

# Answer
> 0 votes
They use the same effect using Cutter. Connect the cutter to the drawing, and fill the matte field with new layer for masking. Works like a charm!

Documentation : Cutter

---
Tags: 2d, clipping
---


# Question
Title: Collision Detection - point hitting a rotating rectangle
Im developing a game which has a flying chopper and an enemy firing bullets at it. Whats the best way to detect when the bullet hits the bounds of the chopper. The chopper is placed to the left of screen, continously rotating around its center. Bullet is fired from the right, always in a straight line. Im using Marix post rotate and translate for the choppers rotation.To make it simpler, I just want to consider the chopper to be a rectangle. Lets say im not bothered about any more precision in terms of specific hit points.

# Answer
> 3 votes
Checking if a point is inside a rectangle is easier when the rectangle is not rotated. You just have to check if the position of the point on the x axis is between the mininum and the maximum of the rectangle, then you do the same on the y axis.

This image shows how it works for the x axis. The blue point is between the min and the max of the rectangle. The red isn't.

Example code:

```
if(point.x > bottom_left.x && point.x < top_right.x
&& point.y > bottom_left.y && point.y < top_right.y)
{
    // the point is inside
}

```

To check if a point is inside a rotated rectangle you first rotate everything so that the rectangle is aligned with the axes. Then you do the same thing as before.

Note that you don't have to rotate the rectangle. You can use the coordinates before it was rotated. You just have to rotate the point by minus the angle of the rectangle, around the center of rotation of the rectangle.

To rotate a point around another point you do the following:

```
Vec2 Rotate(Vec2 point, float angle, Vec2 center_of_rotation)
{
    float sinus   = sin(angle)
    float cosinus = cos(angle);
    Vec2 temp;

    point  = point - center_of_rotation;
    temp.x = point.x * cosinus - point.y * sinus;
    temp.y = point.x * sinus   + point.y * cosinus;
    point  =  temp + center_of_rotation;

    return point;
}

```

If you're using matrices for your transformations you can use the inverse to find the position of the point.

# Answer
> 0 votes
Calculate the inverse transform matrix of the chopper.

Transform the bullet's world position by that matrix (world-space -\> object-space)

Check if the resulting coordinate is within the untransformed (axis aligned) bounding rectangle in object-space (aka local-space).

# Answer
> 0 votes
A very very easy way to check for polygon-point collision is to use area calculations.

The point and the edges of the rectangle define 4 triangles. You can calculate the area of these triangles by calculating the distance from the point to the endpoints of the edges and using the sinus law:

```
triangle_area = 1/2 * a * b * sin P

```

Where a and b are the distances and P is the angle at the point.

You then add these areas together. If the sum is bigger than the area of the rectangle, then the point is outside, if it equals the area, then it's inside.

This isn't a cheap way to calculate this though, so if you use this, do a broad phase before.

# Answer
> 0 votes
The way this is usually done, because it avoids the any trig, is to take dot products of the line from the bullet to center of the box with each of the boxes axes. If the absolute value of any of the dot products is greater than half the dimensions of the box along the corresponding axis, then the point is outside the box.

# Answer
> -2 votes
I'm assuming you are using Unity 5 for this, but it's possible that other game engines might have collision detection work in a similar or same way as this.

You should use OnTriggerEnter, because what you can do with it is not only deduct the helicopter's health, but also destroy the bullet object that still exists even after the collision.

You could also use OnCollisionEnter, but I think it's more for when you want to deform the helicopter as the collision occurs. Since you are only using a single image for your chopper, I think it's a little impractical to use this approach.

---
Tags: collision-detection
---


# Question
Title: Does it make sense to use voxel editors only for meshing?
I am a hobbyist game developer. If there is something that I really don't like is 3D modeling, in particular all the work that needs to be put in the "pipeline" for the creation of models, in particular UV mapping.

Remembering games like Minecraft or "Little big planet", I was wondering if voxel editors could be used for **just** modeling; let me explain: using a voxel editor to make each object I need for my games and then export them singularly as FBX with either marching cubes or even better dual contouring for meshing.

Does an approach like this make sense in terms of performance? From what I can tell, I would need a voxel software which allows all of the following criteria.

* Dual contouring meshing
* FBX or OBJ export of meshed area
* Multiple materials

Now, it looks like such software doesn't exist, which makes me think that this approach for 3D modeling may be totally wrong. Any heads-up on this?

# Answer
> 1 votes
There are voxel art editors which can export to polygon-based formats which can then be imported in stock game engines. MagicaVoxel is one example. But if you need a software recommendation, please ask on https://softwarerecs.stackexchange.com because we generally don't recommend specific products.

One thing you need to be aware of is that your models will require far more rendering resources than one would think. Stonehearth, for example, is often criticized for having bad framerates although its graphics look so retro. Those people don't realize that building shapes from voxels requires far more polygons than building shapes from polygons.

# Answer
> 0 votes
I'm not familiar of any software focused on 3D voxel editing. However that doesn't stop you from making voxel models on a regular 3D software, like Blender. After all, voxel graphics aren't some "special" models, they are just organized in a specific way.

Performance-wise, it really depends. A game like Minecraft does not have detailed models, so it uses way less vertices than a regular game, and it's textures are lower resolution too, this means that performance is definitely boosted. In theory I could say that voxel graphics are friendlier (performance-wise) but it is possible to make something with an unnecessary amount of vertices.

In my opinion, either using voxel art or not, it's a matter of taste. It doesn't make much difference work-wise. If its easier for you to make voxel art because you are a programmer, then that would be a reasonable choice. I've been there, and I've made terrible 3D models for games I've made in the past, so I understand your struggle.

---
Tags: 3d-meshes, voxels
---


# Question
Title: Why am I getting the error "SDL_Event has not been declared"?
I don't understand what I'm doing wrong. In my game.cpp, I have this:

```
void Game::input() {
    SDL_Event e;
    while(SDL_PollEvent(&e)) {
        if(e.type == SDL_QUIT) {running=false; cout << "Quitting" << endl;}
        if(e.type == SDL_KEYDOWN) {
            if(e.key.keysym.sym == SDLK_ESCAPE) {
            running=false;
            }
            moveSprite(e);
        }
        if(e.type == SDL_KEYUP) {
        }
        SDL_GetMouseState(&mousex, &mousey);
    }
}

```

In my player header file, I have:

```
class player {
public:
    player();
    int getPlayerX();  //get player's x position
    int getPlayerY();  //get player's y position
    void moveSprite( SDL_Event& e );
private:
    int xPos, yPos;
};

```

I'm getting the following error:

> SDL\_Event has not been declared"

on the line: `void moveSprite( SDL_Event& e );`

It seems like something simple but I've been staring at it for hours and I can't figure it out. Be gentle, I'm a third semester programming student.

# Answer
> 0 votes
If you aren't including `"SDL.h"`, you need to forward-declare the union. Do note that forward declaring is only possible when you're using the type as a reference or a pointer.

So here's what you need to add to the player header file before the player class:

`union SDL_Event;`

You could also just `#include "SDL.h"` in the header file, but it's generally a good idea to reduce the amount of includes in headers.

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


# Question
Title: Unable to list target platforms. Please make sure the android sdk path is correct
For some reason, I am unable to test my android program because of this error. Here are some pictures of the errors. This error is not allowing me to test my app on my test Android device, I have tried uninstalling and reinstalling, checking if it is acatually the root folder, everything, PLEASE HELP!

**1st error**

```
CommandInvokationFailure: Unable to list target platforms. Please make sure the android sdk path is correct.
C:/Users/jayso/AppData/Local/Android/sdk\tools\bin\avdmanager.bat list target -c

stderr[

]
stdout[

ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.

Please set the JAVA_HOME variable in your environment to match the
location of your Java installation.
]
exit code: 1
UnityEditor.Android.Command.WaitForProgramToRun (UnityEditor.Utils.Program p, UnityEditor.Android.WaitingForProcessToExit waitingForProcessToExit, System.String errorMsg)
UnityEditor.Android.Command.Run (System.Diagnostics.ProcessStartInfo psi, UnityEditor.Android.WaitingForProcessToExit waitingForProcessToExit, System.String errorMsg)
UnityEditor.Android.AndroidSDKTools.RunAndroidSdkTool (System.String toolName, System.String arguments, Boolean updateCommand, UnityEditor.Android.WaitingForProcessToExit waitingForProcessToExit, System.String errorMsg)
UnityEditor.Android.AndroidSDKTools.ListTargetPlatforms (UnityEditor.Android.WaitingForProcessToExit waitingForProcessToExit)
UnityEditor.Android.AndroidSDKTools.GetTopAndroidPlatformAvailable (UnityEditor.Android.WaitingForProcessToExit waitingForProcessToExit)
UnityEditor.Android.PostProcessor.Tasks.CheckAndroidSDK+SDKPlatformDetector.GetVersion (UnityEditor.Android.AndroidSDKTools sdkTools)
UnityEditor.Android.PostProcessor.Tasks.CheckAndroidSDK+SDKComponentDetector.Detect (UnityEditor.Android.AndroidSDKTools sdkTools, System.Version minVersion, UnityEditor.Android.PostProcessor.ProgressHandler onProgress)
UnityEditor.Android.PostProcessor.Tasks.CheckAndroidSDK.EnsureSDKComponentVersion (System.Version minVersion, UnityEditor.Android.PostProcessor.Tasks.SDKComponentDetector detector)
UnityEditor.Android.PostProcessor.Tasks.CheckAndroidSDK.EnsureSDKComponentVersion (Int32 minVersion, UnityEditor.Android.PostProcessor.Tasks.SDKComponentDetector detector)
UnityEditor.Android.PostProcessor.Tasks.CheckAndroidSDK.Execute (UnityEditor.Android.PostProcessor.PostProcessorContext context)
UnityEditor.Android.PostProcessor.PostProcessRunner.RunAllTasks (UnityEditor.Android.PostProcessor.PostProcessorContext context)
UnityEditor.BuildPlayerWindow:BuildPlayerAndRun()

```

**2nd Error**

```
Error building Player: CommandInvokationFailure: Unable to list target platforms. Please make sure the android sdk path is correct.
C:/Users/jayso/AppData/Local/Android/sdk\tools\bin\avdmanager.bat list target -c

stderr[

]
stdout[

ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.

Please set the JAVA_HOME variable in your environment to match the
location of your Java installation.
]
exit code: 1

```

# Answer
> 1 votes
(*EDIT: Updating to Unity 2018.1 fixed the issue for the asker. The below answer is not correct for this case, but it may be relevant for other people with the same error message*)

You need to downgrade your JDK version to JDK 8 for now.

There is an active issue on the Unity Issue Tracker for JDK 9.

If this does not solve your issue, you should debug to see if your JAVA\_HOME path is set correctly in your PATH variable as your error message suggests. For more details, see this relevant SO post.

# Answer
> 1 votes
Updating to unity 2018.1 solved the issue

---
Tags: unity, android
---


title: LibGdx Camera Movement

text:
# Question
Title: LibGdx Camera Movement
I just started learning a few things about libGdx and i don't really understand how the camera works because i've created a camera, then set the camera position to viewport.getWorldWidth()/2 and viewport.getWorldHeight()/2 and then i would like to draw a image at 0,0 or where the camera starts drawing but i don't really understand why it's not working.Here's the code:

```
public class PlayScreen implements Screen {

    private OrthographicCamera cam;
    private Viewport viewport;
    private MainClass mainClass;
    Texture img;

    public PlayScreen(MainClass mainClass){
        this.mainClass = mainClass;
        img = new Texture(Gdx.files.internal("badlogic.jpg"));
        cam = new OrthographicCamera();
        viewport = new StretchViewport(400, 200, cam) ;
        cam.position.set(viewport.getWorldWidth()/2, viewport.getWorldHeight()/2, 0);

    }

    @Override
    public void show() {

    }

    @Override
    public void render(float delta) {
        Gdx.gl.glClearColor(1, 1, 1, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

        if(Gdx.input.isKeyPressed(Input.Keys.RIGHT)) {
            cam.position.x += 100 * delta;
            System.out.println(cam.position.x);
        }

        if(Gdx.input.isKeyPressed(Input.Keys.LEFT)) {
            cam.position.x -= 100 * delta;
            System.out.println(cam.position.x);
        }

        cam.update();
        mainClass.batch.setProjectionMatrix(cam.combined);

        mainClass.batch.begin();
        mainClass.batch.draw(img, 0  , 0); //here i'm not sure what position should it be
        mainClass.batch.end();
    }

```

The output it's just a blank window, i don't understand where it starts drawing

# Answer
> 0 votes
This is because you are not updating and applying your `Viewport` before drawing. The best place to do this would be in the `resize(width, height)` method like so:

```
@Override
public void resize(int width, int height) {
    // Update the viewport so it properly converts coordinates
    viewport.update(width, height);
    // Actually apply the viewport. True means center camera.
    viewport.apply(true);
}

```

Since we're calling `apply` with `true` we also don't have to center the camera manually in the constructor.

---
Tags: libgdx, camera
---


title: physics engine without time steps

text:
# Question
Title: physics engine without time steps
I'm looking for physics engines that doesn't use time steps. I don't think time steps are reliable, and I don't like how without tweaking the engine a bullet going too fast can pass through a wall without colliding it. Moreover I suspect they do a lot of unnecessary computations.

I thought of a physics engine concept where all the movements are represented by forces and movement beginning time. In such an environment as long as no event occur the engine would not do any computation.

I imagine the following:

* I shoot a bullet in space, an object is created representing its physics properties.
* The engine compare the bullet trajectory with other's to find if it's gonna collide with an other object.
* It finds a collision, in 3 seconds.
* An callback is programmed to trigger in 3s to process the collision.
* In the meantime if no other event occur (like shooting an other bullet, changing an object trajectory, etc...) no other computation is done.

Does such an engine exists? Is there a name to this technique? Have you ever tried using this approach?

# Answer
> 7 votes
The problem is this only works if movement is linear and there is no possibility of other moving objects hitting one another.

As soon as you have multiple forces changing the direction in non-linear ways (eg: friction, gravity, wind) you're forced to do integration which involves slicing everything down into infinitely small time slices.

This is why and for reasons of numerical stability fixed time steps are usually used.

# Answer
> 2 votes
I have created a 2D collision detection engine which I used in one of my games. All the objects moved in linear segments, and their bodies were defined as circles with a given radius. The distances at a time t could be defined as quadratic equations, which are easy to solve. (I had to do a bit of algebra on paper to get my equations to be number-crunchable) I solved the equations for the time of collision and in my case i scheduled a collision event at that time in the future.

In 2d, this is entirely doable. It gets more complicated with non-circular objects, but that's just complexity. The quadratic equation gives two solutions, but it's easy to find out which is the one you are looking for.

Obviously all collisions need to be recalculated every time something changes. This could be a problem for a game with many actors in the same space. The same is true for a step-based solution, however. You could argue that the problem in both cases comes down to computational speed.

It's worth noting that objects will usually move linearly in computer games. Some will move in parabolas, such as things falling under gravity. This should also be perfectly solvable in 2D, but I have never tried. You could also have hyperbolic and elliptic motions in games focusing on space travel. The physics in these games could also be solved without being step-based, but it would require the whole engine to do so.

In a 3D space the maths become much more difficult, but you could still get good results with approximate or numerical methods. They would be less accurate, but you could still avoid the problems of "idle computing" of a step-based approach. You could also use the numbers from low iterations as early warning, so to speak.

# Answer
> 1 votes
Physics systems require time steps to work. They are integration engines, which perform calculus in order to model physical interactions.

What makes a physics engine work best is a **fixed** time step. This means that even if the engine slows down, the engine still moves things in acceptably small increments to be stable. This makes the engine reliable.

Variable time step physics engines are far less stable, because if the update time since the last is too large, you can end up with velocities or impulses being too large, destabilising the simulation, or objects tunnelling through each other, reducing the accuracy of the system.

# Answer
> 1 votes
Does a name for such a technique exist? Well, it's effectively solving the equations of motion exactly, which typically is not impossible. This basically gets into the arguments of a deterministic universe; if you know all the data, you can predict the future with 100% accuracy.

Problem: The universe isn't deterministic. No, this isn't a quantum mechanics argument, but rather that there's one aspect that's very uncertain: the Player. Games are a notoriously interactive medium, no matter what people like David Cage are trying to do.

Now, you did address this: As long nothing occurs, we don't have to do anything. Fair enough, but at that point you'll be checking whether or not you need to recalculate every frame as opposed to doing a calculation every frame and updating it, which is, in practice, not different, and definitely not as flexible. Additionally, depending on the circumstances, the computations can be far harder to do, and they require a lot more data, which is bad for many reasons.

Are there any alternatives? Yes. You could use pre-scripted physics or use a stochastic system which I have used in the past for a variety of applications. However, these cannot replace traditional physics engines in all situations.

---
Tags: physics-engine, simulations
---


title: What event before new Scene is loaded ?

text:
# Question
Title: What event before new Scene is loaded ?
Unity3d: I know exist OnApplicationQuit called before the application is ended.

But, does exists an event that is called before a new scene is loaded ?

Thanks

# Answer
Yes, there is, it's `SceneManager.activeSceneChanged`, it's defined as follows:

```
public static event UnityAction<Scene, Scene> activeSceneChanged;

```

The first argument is the current scene, the second argument is the new scene.

There's a page in the documentation with an actual usage example:

https://docs.unity3d.com/ScriptReference/SceneManagement.SceneManager-activeSceneChanged.html
> 4 votes

# Answer
You are likely looking for `SceneManager.sceneUnloaded` to get a notification when a scene has unloaded (or `SceneManager.sceneLoaded` to get a notification when a scene has loaded). See Unity's documentation on SceneManager.

Note that `OnLevelWasLoaded` is deprecated (marked as Obsolete) as of Unity 5.4. @Chris' answer is still supported, but it's preferable to use `SceneManager`. As that answer points out, keep in mind the Execution Order of Event Functions.

See the example code in SceneManager.sceneUnloaded documentation:

```
using UnityEngine;
using UnityEngine.SceneManagement;

public class SceneLoaded1 : MonoBehaviour
{
    public void Start()
    {
        SceneManager.sceneUnloaded += OnSceneUnloaded;
        Debug.Log("Start: SceneLoaded1");
    }

    private void OnSceneUnloaded(Scene current)
    {
        Debug.Log("OnSceneUnloaded: " + current);
    }

    void Update()
    {
        if (Input.GetKey("space"))
        {
            Debug.Log("Quitting Scene1");
            ChangeScene();
        }
    }

    void ChangeScene()
    {
        Debug.Log("Changing to Scene2");

        SceneManager.LoadScene("Scene2");
    }

    void OnDestroy()
    {
        Debug.Log("OnDestroy");
    }
}

```
> 1 votes

---
Tags: unity
---


title: Find Coordinates of Exit Point

text:
# Question
Title: Find Coordinates of Exit Point
I'm trying to make a bullet penetration system. Taking a look at the picture below could help explain what I want better.

If we know the coordinates of a square shape as well as AB vector with direction coefficient, how do we find X,Y for C point?

Basically I'm trying to find the X,Y coordinates of the point of the opposite side of an object of another point. As you can see I'm not exactly going for realism as it's linear. Below are a couple more examples to clarify my objective.

===========================================================================

Any help is greatly appreciated :D

# Answer
You can intersect the ray against each of the edges (segments).

If you get zero intersections, the ray misses the shape.

If you get two intersections, the one furthest away from A is the exit point.

Note that the ray-vs-segment problem can be further decomposed: Simply calculate the intersection of two lines, and see if the point of intersection is at the right side of the ray, and in the right range of the segment.

I'm pretty sure this approach even works if the shape is concave: you just get multiple entry and multiple exit points.
> 1 votes

---
Tags: collision-detection, mathematics, vector
---


# Question
Title: Help generating clues in a treasure finding game
I am a high school student creating a small game in unity for fun and would greatly appreciate your opinions on this game mechanic. I have a treasure finding game that takes place in a randomly generated forest with randomly placed treasure. There are also randomly placed landmarks such as large rocks, lamp posts, picnic tables, etc. The treasure spawns within a certain radius of a landmark as to provide a reference point for clues to the position of said treasure. I am having some difficulty however, deciding what sort of clues i could generate. I thought of a few ideas such as generating clues referencing a landmark the treasure is near, clues referencing cardinal directions, and clues which are an image of the treasure's surrounding environment. I would love some feedback on the clues i have thought of so far, and new suggestions for clues. Thanks in advance!

# Answer
> 1 votes
I'd point out the game BounceFloor on Newgrounds (fairly new.)

Game:

* You must find someone who is in a crowd of people who does not belong at the club

Mechanics:

* After some amount of time, a clue is generated (something visual that helps the player; such as an item that the person is wearing)
* If the player is close to the person to-be-bounced-out; that person will attempt to wander further from the player

I found this to be successful (if extremely short.) Relating this to your game, you want a component that helps the player as time passes (strangers mention a little thought bubble about where they think it is?) and then another component that clues the player in based on their own actions (maybe a thief who attempts to act on the information?)

I'd also mention that if you used Triangulation instead of putting it near a land mark, you can make it so landmarks are spread out and the clues can just be land marks. A single clue gives you a large area around a center location, a second gives you a strip of land you'd check, and a third would encircle the location (and after that, the thief runs towards it like crazy?)

If you want the game to be longer you may want clues of where it's *not* instead; pointing out that some Stranger has checked the area around Mt Peak and didn't find it.

# Answer
> 2 votes
You could use an audio feedback. Calculate distance to treasure, and use that as a frequency for a repeating beep.

After spawning, player hears:

**beep.......beep........beep.....**

Player starts to walk away from treasure (goes in wrong direction:)

**beep.............beep...............beep..............**

Player is standing right next to the treasure:

**BeepBeepBeepBeepBeepBeepBeep...**

It would basically be a simulated Geiger counter, but with a less noisy signal. For kicks, you could add noise to the signal and go full Geiger counter.

# Answer
> 1 votes
It is not really possible to estimate how well your clues would work or what else could work just from reading a theoretical concept. It just depends on too many implementation details, down to your particular graphic design and interface choices.

The only way to find out is to build a very basic prototype of your game and find some playertesters. Observe them while they play and see:

* How correctly do they interpret the clues and how much instruction and practice do they need?
* Which clues are helpful for them and which are not?
* Which clues are actually *too* helpful?
* Which environmental circumstances make clues more or less helpful?

When the test session is over, you might want to interview them and ask them where exactly they felt they needed more information or where they found clues to be unclear. Then and only then think about how you can give them that missing information.

---

Game design is an iterative process. You can not design a perfect game on paper. Fail faster! Design, prototype, fail, redesign, improve, fail less, repeat, repeat and repeat until you have a game that works.

---
Tags: game-mechanics, random, content-generation
---


title: How to make my SpriteSheet be POT?

text:
# Question
Title: How to make my SpriteSheet be POT?
So let's say my sprite sheet has 3 sprites in one row. One sprite is 64 pixels wide and high. When that is combined my sheet would be 192 pixels wide and 64 high. So from that, how am I supposed to make it's dimensions POT without stretching sprites inside?

# Answer
Just add extra, blank space.

A 256x64 texture is a "power of two" texture and can fit your three sprites packed into the left (or right, if you really prefer) side of the image. You'll have an extra 64x64 block of empty space in the texture you can fill with additional data as you need to. Or just leave blank.
> 3 votes

---
Tags: spritesheet, texture-atlas
---


title: Custom Model Format & Loading

text:
# Question
Title: Custom Model Format & Loading
I've been working on a small engine for educational purposes. I understand that going production with "raw" model files like .obj is wrong mostly because of parsing and loading time. Thus, I want to create a program which parses these raw files and formats it in a new way, let's say using protobuf.

My questions:

1. Are there any best practices, or any example lib I can take a look at?
2. What should I do with attached texture files? Seperate files?
3. How can I support multiple types of models and/or attributes in the models like materials, uv mapping, etc...

# Answer
> 1 votes
> Are there any best practices, or any example lib I can take a look at?

Generally the point of creating a custom model format is so that model format is the *most efficient* thing for your engine to consume at runtime. Beyond that, there aren't really that many "best practices."

That also means it's going to be hard to tell you exactly what to do, because you've provided no information about what your graphics engine looks like, how it operates, how you load or manage resources and runtime, et cetera.

> For instance, what am I doing with attached texture files? Seperate files?

That's up to you. Separate files are easier to share and often easier to deal with. Bundling the texture data into the model data makes for less code involved in ensuring models actually end up with textures at the end of the load.

As above, it will depend on what your project needs.

> How can I support multiple types of models and/or attributes in the models like materials, uv mapping, etc...

You can't support any of these unless you rendering engine *also* supports them. So, based on what your engine supports, build up a little structure of data that indicates which features a model uses and serialize that structure somewhere in your model data.

For example, if your engine supports up to four textures per model and also supports optional glow colors embedded in the vertex color data, you might have a structure like:

```
struct ModelOptions {
   int textureCount; // 0 to 3, indicates how many texture coordinates exist per each vertex.
   bool hasGlowColors; // If true, each vertex has a color attribute. Otherwise it does not.
};

```

If you store that information in the model file's header or before the actual vertex data, that will tell you how to interpret the actual data that follows.

---
Tags: opengl, c++, 3d-modeling
---


# Question
Title: Impulse resolution for purely rotational collisions (relative linear velocity = 0)
I've been writing a basic physics engine, (loosely) following Randy Gaul's online tutorial. I have been using this equation that he derives:

$$j=\frac{-(1+e)((V^A-V^B)\*t)}{\frac{1}{{mass}^A}+\frac{1}{{mass}^B}+\frac{(r^A\times t)^2}{I^A}+\frac{(r^B\times t)^2}{I^B}}$$

(https://gamedevelopment.tutsplus.com/tutorials/how-to-create-a-custom-2d-physics-engine-oriented-rigid-bodies--gamedev-8032)

This equation works well for the majority of all collisions. However, if two objects collide through rotation and rotation alone (that is, their relative linear velocity is 0), an impulse of 0 will be applied since VA \- VB is 0. This results in one object clipping into another, passing through as if it were never there. While less noticeable, this can also be a problem for collisions where relative linear velocity is non-zero, but angular velocity is much greater than relative velocity.

This is clearly not how objects would interact with real-world physics. That being said, how would I determine the "effective" relative velocity used in the equation for rotating bodies? I have already tried adding the linear velocity of the collision contact point to the center of mass velocity for both objects, but have gotten unsatisfactory results.

# Answer
Those velocities should be velocity at points of contact. To compute these quantities, you would do something like:

$$\vec v ^\prime = \vec v + \vec w \times \vec r$$

Where w (omega) is angular velocity and r is the radius vector from center of mass to the point of contact. You can see here in the sample code how the relative velocity is computed: https://github.com/tutsplus/ImpulseEngine/blob/master/Manifold.cpp#L70-L71
> 1 votes

---
Tags: 2d, rotation, collision-resolution, physics-engine
---


title: Help Improving Map Generation

text:
# Question
Title: Help Improving Map Generation
I've recently attempt for the first time to implement a map generation system and while it does work, it doesn't work exactly the same I want but I'm not really sure on what changes I can make it to make it generate the type of map I want.

This is my map generation code

```
///<summary>Generates a Room at a Start Position</summary>
    void GenerateMap(Vector2 roomStartPos)
    {
        Vector2 startPos = roomStartPos;

        int roomTileNum = random.Next(minRoomTiles, maxRoomTiles);
        for (int i = 0; i < roomTileNum; i++)
        {
            if (CheckTilePosValid(startPos)) //Checks if a position is taken by a tile already
            {
                Tile newTile = CreateTile(startPos); //Creates a Tile at a passed in Position
                startPos = GetRandomEdgeDirection(newTile.SpritePosition); //Gets a Random position next to the passed in Position

            }
            else
            {
                startPos = GetRandomEdgeDirection(startPos);
                i--;
            }
        }
    }

```

It's likely a really bad way of generating a map. It basically gets a random number of tiles to generate, it will then place a Tile at the start position and select a new position in a random direction (Up, Down, Left, Right). It'll then place a new tile at that new position specified, it will then simply loop through that till it's placed every tile. The "CheckTilePosValid()" function is used to determine if the random position that is gathered has already been taken by a tile. If the position isn't taken then it will create the tile and continue through the loop, while if the position is taken then it will get a new position and basically keeping doing that till it gets a position that hasn't been taken already.

This generates maps like this:

The issue is mainly with the first image since as you can see, the map is very stretched out which isn't what I want. I'd more want a map similar to the second image, tiles much closer together and not so stretched out but is still random enough.

I'm just not sure how exactly I can achieve this so I was wondering if anyone would be able to help me? Would I need to completely rework my generation system or can I just make simple changes to fix this? I'd very much appreciate the help :)

# Answer
> 1 votes
You could consider a different approach where you place some number of nodes on your map and then attach them together via hallways. This would allow you to generate your rooms at appropriate sizes because you'd be focusing on the rooms instead of the generation.

If you're looking for "Dead ends" I would simply use one of the following two options:

* Generate some 0x0 rooms.
* Generate Dead-End Nodes (basically the same as the above, but one is a special case and the other is a hack.)

You may start with your nodes, create your rooms, then have A\* find a path between your rooms for you. Either way, I think that's enough to get your brain moving.

EDIT: I just realized I answered your related question before: Basic Random Tile Map Generation

Apologies that this advice is somewhat contradictory to my previous advice, as my previous was under the assumption you didn't want "hallways."

Either way, both pieces of advice hinge on building a room *then* dealing with additional randomization. I would literally have a room class that is something like:

```
class Room
{
    int width, height;
    Point TopLeftCorner;
    public static Room Generate()
    {
        Room room = new Room();
        Random rnd = new Random(/*timestamp or seed*/);

        // get our dimensions
        room.height = rnd.Next(2,6);
        room.width = rnd.Next(2,6);

        // create a point where the room can exist without hitting the edge
        TopLeftCorner = new Point(
                            rnd.Next(0,screenWidth-room.width),
                            rnd.Next(0,screenHeight-room.height));

        room.BuildRoom(); // where you place your tiles
    }

    void Buildroom()
    {
        //pseudo code cause I'm lazy
        for i in width
            for j in height
                placeTile(i,j)
    }

    // approximates center of room
    public Point RoomNode()
    {
        Point returnpt = new Point(width >> 1, height >> 1);
    }
}

```

After this, the remaining code would be about picking which sides you'd want to connect with a hallway and then using another generate function to walk tiles out between the rooms.

---
Tags: procedural-generation, tilemap
---


# Question
Title: WWW(Unity) with HTTPS on Android not working
I'm using a native android plugin my team made for communication with a server, and as it uses HTTPS I use a certificate with it. Everything's fine with that, the problem is that, in Unity, when I try to use WWW with anything HTTPS, I get this error

> V/com.facebook.unity.FB: sending to Unity OnLoginComplete({"error":"Caught exception: javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.","callback\_id":"5","key\_hash":"XXXXXXXX"})

I get this error in particular when trying to use the Facebook SDK to post a picture to the user's timeline. Looking at the source code, it uses Unity's WWW for the POST. If in Unity I never call my native plugin's methods, then everything works nicely. Is there any way to get around that? Somehow install another certificate? Use some different header? Any help would be great, thanks.

# Answer
Error which You are getting is standard error generated by Android when given certyficate can't be full checked. Try to validate Your certyficate with tools like: https://www.digicert.com/help/. Yours admin should fix it if its not valid.

If You can't fix certificate then its needed to modify your company plugin to use custom ssl factory/trust manager for request from Android level. This thread on SO seems helpful with understanding the case: https://stackoverflow.com/questions/6825226/trust-anchor-not-found-for-android-ssl-connection
> 1 votes

# Answer
I had a signed certificate which stopped working when I upgraded IOS. I fixed it by adding the intermediate (chain) cert file on the web server. This fixed the problems with IOS but for some reason I still have Android problems, those may or may not be something totally different.
> 0 votes

---
Tags: unity, android, security, plugin, http
---


# Question
Title: Run a method once per iteration without adding a component to a game object in Unity
I want to run a function once per main loop iterator but I don't want to add this as a script to a game object in my scene. This is something that should always run no matter what scene and making people include it into every scene on a game object would cause issues because I'll/people will forget. Is there any hooks into the main loop where I can tell unity to run this function once per loop for the entire game not just per scene?

# Answer
> 2 votes
You can create directly from the script a gameobject as a singleton marked as `DontDestroyOnLoad`: this way, the gameobject will be persistent during the entire duration of the runtime.

Note that you have to create a game object in the first scene loaded, or you won't be able to execute the `Update` method. With this script, however, you don't need to physically create the game object in the editor, it's created automatically by the script itself only at runtime.

This is the code:

```
using UnityEngine;

public class AutoSingletonScript : MonoBehaviour {
    [RuntimeInitializeOnLoadMethod]
    private static void Initialization() {
        if (FindObjectOfType<AutoSingletonScript>() != null)
            return;
        var instance = new GameObject { name = "AutoSingleton" };
        instance.AddComponent<AutoSingletonScript>();
        DontDestroyOnLoad(instance);
    }

    private void Update() {
        // Do Stuff
    }
}

```

---
Tags: unity
---


# Question
Title: Independent Column sizes in Scene2D Table in LibGDX
For my game's (mostly GUI based) UI i am using table from Scene2D in libGDX. I want independent column sizes in my table but first cell width is the width for all other rows in column. Is it possible to have a table in Scene2D with independent cell width in each row? For example, first cell in first row should have 10% width and first cell in second row should have 15% width. I tried using Horizontal Groups, Containers but they make my code too shabby and cluttered.

# Answer
There is an option to do this:

First of all you need to find out what your smallest size of a column is, therefore you have to merge all rows into one and pick the smallest width of all columns.

the numbers in the picture are displaying the width of the columns.

Knowing your smallest width (in my example it's displayed as 1) allows you to create a table with as many columns as you need. (for my example its 17 columns -\> width / 17).

Now use:

```
table.add(Actor).colspan(#); //replace # with the amount of columns you want to span

```

In my example this would be:

```
Table t = new Table(skin);
t.add(Actor0).colspan(1).expandX();
t.add(Actor1).colspan(5).expandX();
t.add(Actor2).colspan(3).expandX();
t.add(Actor3).colspan(3).expandX();
t.add(Actor4).colspan(2).expandX();
t.add(Actor5).colspan(3).expandX().row();
t.add(Actor6).colspan(2).expandX();
t.add(Actor7).colspan(2).expandX();
t.add(Actor8).colspan(5).expandX();
t.add(Actor9).colspan(4).expandX();
t.add(Actor10).colspan(3).expandX();
t.add(Actor11).colspan(1).expandX();

```

output looks as follows: (note that I added a row with equally sized columns for reference above)
> 4 votes

---
Tags: libgdx, scene2d
---


# Question
Title: Checkers movement and capture logic in java
I am making a checkers game.

I implemented a 2D array to store the board position, and made a grid layout with all my squares as panels. I also have my pieces drawn.

I wanted some info on how I would make the movement methods or the capture method. My main issue is finding a mathematical way to code the jump and what I need to do in order to move the pieces properly.

I was thinking of having a method to check if the move is legal and a method to actually move.

# Answer
> 1 votes
Going by this.

Working with a grid is fairly easy because you can directly check adjacent tiles.

You can check for valid moves during the attempt to move a piece or pre-check when you select a piece. So let's get one thing out of the way:

You can not move head on, you're only interested in tiles that are diagonal to the current tile. Checking adjacent tiles is as simple as

```
 boardgrid[currentY-1][currentX-1] // top left
 boardgrid[currentY-1][currentX+1] // top Right
 etc

```

Your tiles probably have some sort of state. Whether it's occupied and by whom. Based on this information it's really easy to check for validity.

pseudo code:

```
if adjacent tile is not occupied:
     move current piece to adjacent tile

else:
do:
  if current adjacent tile is occupied by the enemy AND
     check if a tile is free in the same direction:
       mark enemy piece for removal // queue it up to process after
       additional logic goes here, like keeping track of where the piece moves to
       valid move has been found
  if not:
     move is invalid

while( valid move has been found )

```

Once your piece jumps, the rules state that you must continue jumping if any adjacent tile is occupied by the enemy. So when you jump, at the new position you check the diagonal tiles again and repeat the process.

If you want to animate your pieces you can queue up the valid moves and perform them in a sequence. Hope this helps.

# Answer
> 0 votes
i create a game like this before and other method you need is a game over. I used this one and it work good.

public boolean gameOver() {
return gameOverInternal(0, 0, 0, 0); }

```
public boolean gameOverInternal(int c, int r, int white, int black){
    if(data[c][r] == white|| data[c][r] == white king)
        white+= 1;
    if(data[c][r] == black|| data[c][r] == black king)
        black+= 1;
    if(c== tiles-1 && row == tiles-1){
        if(white== 0 || black== 0)
            return true;
        else return false;
    }
    if(c== tiles-1){
        r+= 1;
        c= -1;
    }
    return gameOverInternal(c+1, r, white, black);
}

```

Sorry if this answer wasnt your main question, iam new to this website. sorry for bad english

---
Tags: java, movement, board-game
---


title: Create a 2d circular maze

text:
# Question
Title: Create a 2d circular maze
How can I create a 2d procedurally generated circular maze like the following picture:

# Answer
> 5 votes
Any maze generation algorithm, that only relies on a set of nodes (pretty much all) will work. Instead of creating a grid, where each grid point is a node and they connect to their neighbours, you need to generate them in the circular shape.

So, first of all, the center is a node. Let's say the next layer has 6 nodes and the middle connects to all of them. To make sure the maze stays consistent, each layer (apart from the second) should have twice as much nodes, as the one before, because you need one neighbour for every node in the last layer and you need to put one extra node between them, so that the maze becomes more detailed the farther you go from the center.

Pseudo code for this:

```
nodes is an empty set of nodes
put central node in nodes
put the second layer's nodes in nodes
connect the first and second layer

let currentLayerCount be 12
for every layer
    for i from 0 to currentLayerCount
        create a node with a position
            x: cos(2*pi / currentLayerCount) * layerId
            y: sin(2*pi / currentLayerCount) * layerId
        put node in nodes
        if i is divisible by 2
            connect the node to the neigbouring nodes in the same and last layer
        else
            only connect the node to the neighbouring nodes in the same layer
        end if
    end for
    multiply currentLayerCount by 2
end for

```

---
Tags: unity, procedural-generation, maze
---


# Question
Title: Measure the length of the platform in Unity
I created a platform in Unity. It consists of an empty parent object and child objects. Child object have attached components: `Sprite renderer` and `Edge collider 2D`.

How could I get the length and height of such a platform? By the length and height in the case I mean the respective measures in x and y axis.

# Answer
> 1 votes
Just get the `width` scale value of the platform. This should return the 'length value' of it.

So, if you had a platform at around `position 0, 0, 0` and a scale at around `scale 32, 8, 0`, then you have the length of it sideways. You can do the same thing, only with the `height` value to get the length in that dimension.

**EDIT**

In case anyone, or the user that asked this question, finds this answer, and does not want to look in the comments, I thought I should edit and add this in.

When I said 'scale values,' i meant the scale of the Transform. So, use the transform scale values when reading my answer.

---
Tags: unity, 2d, platformer
---


title: Cross-platform GLFW build with CMake

text:
# Question
Title: Cross-platform GLFW build with CMake
I know this is probably a popular question and can be very vague, so I'm going to be as specific as possible. I don't really know how to even form this question to be able to search Google, so I came here.

I've been following the tutorials from learnopengl.com and they have been by far the best explanations I've found on modern OpenGL anywhere. After I'm done with the tutorials, I'll be making a game. I have already started working on the game engine and it works just fine on Ubuntu and Mac OS X. Building the project is done with CMake (I've found this to be the easiest). The project uses GLFW and Glad as used in the tutorial. I can post the GitHub repo if you want.

Today I started trying to figure out how to get the project to run on Windows, but don't even know where to start. Hence coming here. I plan on using Visual Studio but haven't used it since college. How do I even start making the project? I've tried building GLFW on the machine and the building the project using CMake, but I get build tool errors that I don't know how to troubleshoot. Where do I begin?

# Answer
> 1 votes
After a few hours of research and testing, I found a solution that works for me.

1. In order to run my project on windows, the first thing you have to do is download glfw straight from the glfw homepage. Move the resulting directory into the libraries directory in the project and rename it to `win_glfw`. You also need the glfw binaries in a later step.
2. Next, you need to build glfw with cmake (either the gui or the command line). The only thing you have to make sure is set correctly is the `CMAKE_INSTALL_PREFIX`. I set that to a folder in my directory. Others who have tried before failed if they didn't update this because it usually automatically defaults to somewhere in `C:\Program Files` which causes an access denied type of error.
3. With the newly generated glfw folder in the project file, you have to build it from visual studio. I won't go into the details unless somebody really wants to know, but that's where it got really hairy.
4. Next, all you have to do is generate the CMake files for the project, open the generated `.sln` file, build it, and be on your way.

There are alot of details I left out because, like I said, it just got really hairy. Thankfully, after building GLFW once, you don't have to do all this nonsense again. I'm sure I'll streamline everything moving forward, but at least now it's working.

---
Tags: opengl, visual-studio, cross-platform, glfw
---


# Question
Title: How to find the largest bounding boxes in 3D array to cover all cells?
I'm trying to generate colliders automatically from a 3D array where each cell represents a constant-sized piece in a world (like a voxel). I'm trying to optimize the number of colliders, so I want to traverse the 3D array and create as few colliders as possible to cover all cells.

I know that for a single axis (1D array), I could do something like this:

```
// Let's say 0 = empty and 1 = wall
int[] array = {0, 1, 1, 0, 1, 0, 1, 1, 1, 0, 1};
boolean creating = false; // Was start index found?
int startIndex = 0; // Where the box started?
int endIndex = 0; // Where the box ended?

for (int i = 0; i < array.length; ++i) {
    if (!creating) {
        if (array[i] == 1) {
            creating = true;
            startIndex = i;
            endIndex = i;
        }
    }else{
        if (array[i] == 1) {
            // The line of blocks continues, increment the end index
            endIndex = i;
        }else{
            // Empty cell found, create a collider
            createBox(startIndex, endIndex);
            creating = false;
        }
    }
}

// Result would be four colliders sized 2, 1, 3 and 1

```

However, I can't figure out how to expand this to two and three dimensions. For instance, take this 2D array:

```
{{ 1, 1, 1, 0, 0, 0, 0 },
 { 1, 1, 1, 0, 1, 0, 0 },
 { 1, 1, 1, 0, 1, 0, 0 },
 { 0, 0, 0, 0, 1, 0, 0 },
 { 1, 1, 1, 1, 0, 0, 0 }}

```

This should result in three colliders: the first from (0, 0) to (2, 2), the second from (3, 1) to (3, 5) and the third from (0, 4) to (3, 4). However, simply looping the two dimensions wouldn't work.

Any ideas how to tackle this?

# Answer
I'm not really sure whether or not the process you describe guarantees the least amount of bounding boxes, but it surely is a good way to approach the problem, as it definitely reduces the amount of bounding boxes that you need to check collisions against. I use this approach myself.

Basically, I just do this one dimension at a time. First, I process the level horizontally, so row by row, and place in temporary bounding boxes. You seem to already know how to do this, so I won't bother with pseudo code here.

After you have the boxes connected in one dimension, you just need to do a pass on all the boxes in the other dimension. Either do a full coordinate loop, or simply iterate over the boxes you created previously. You just need to look for a box directly underneath the box you're trying to connect, and make sure its width matches. So something like:

```
void processVertical()
{
    for (Box box : HorizontalBoxes)
    {
        // Ignores invalid (already processed) boxes, see the comment below.
        if (box.width == 0) continue;

        // Check if we can merge with the box below us.
        Box below = findBoxDirectlyBelow(box.x, box.y)
        if (below && below.width == box.width)
        {
            box.height += below.height;  // Expands.

            // Makes the box below unusable, so that we don't end up processing it.
            below.width = 0
        }
    }
}

Box findBoxDirectlyBelow(int x, int y)
{
    for (Box box : HorizontalBoxes)
    {
        if (box.x == x && box.y == y + 1) return box;
    }
    return null;
}

```

For a third dimension, you would just repeat the process but compare the width and height of the created boxes with the boxes close to each other in the Z-direction.
> 1 votes

---
Tags: java, 3d, voxels
---


# Question
Title: Why is server frame rate slower than client's?
I have read in my lecture notes in a game dev class that in a server-client-architecture multiplayer game, it is common practice to have the server running at a lower frame rate than the client (20 fps compared to 60 fps for example)

No reason was given in the notes so I want to ask if anyone has a solid explanation for this?

My guess is that the server "waits" a little for all clients to send some packets before making its calculation. But this seems to be a different technique (bucket synchronization) altogether

# Answer
> 6 votes
1. It's not necessary. The reason why you need 60 FPS on the client is because you want the animations and movements to look fluent. But when it comes to just the game mechanics, 20 FPS is more than enough.
2. It saves money. A third of the framerate means you can run three times as many game instances on the same amount of server hardware.
3. It lowers the chance that the server fails to fulfill it's target framerate and skips frames. This can cause all kinds of gameplay and synchronization problems (which exactly depends on implementation details of you mechanics and netcode)

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


# Question
Title: Unity: UI following scene object lags or jumps
I have a 3D plane with "enemies", each one has it's canvas with a health bar, that follows the enemy position. When the enemy rotates, the health bar position gets laggy and jittery (you see no fluently, like a jump)

The code that I'm using is:

```
 private Camera _camera;
 private RectTransform _healthBarReact;

 void Start {
     _camera = GameObject.Find("Camera").GetComponent<Camera>();
     _healthBarReact = transform.FindChild("HealthBarImage").GetComponent<RectTransform>();
 }

 void Update {
       Vector3 screenPoint = _camera.WorldToScreenPoint(transform.parent.position); // the parent is the enemy, I attached the script to the child canvas "HealthBar"
     _healthBarReact.position = screenPoint;
 }

```

How can I fix that "lag" issue? apparently, the issue only occurs when the enemy is rotating... when it follows you in a straight line, the healthbar looks well.

# Answer
All UI follow functionality should be implemented in `LateUpdate()` method. See manual.

Example using your code:

```
void LateUpdate {
    Vector3 screenPoint = _camera.WorldToScreenPoint(transform.parent.position); // the parent is the enemy, I attached the script to the child canvas "HealthBar"
    _healthBarReact.position = screenPoint;
}

```
> 2 votes

# Answer
Camera matrix update is delayed until very late in frame (probably updates just before rendering). WorldToScreenPoint relies on matrix to calculate screen position.

To make it work correctly you have to do two things:

1. Ensure HealthBar update is called AFTER input handling (which moves camera)
2. Force Camera matrix to be updated

The code:

```
using UnityEngine;

public class HealthBarPositionUpdate : MonoBehaviour
{
    public GameObject Enemy;
    public RectTransform HealthBarElement;

    // LateUpdate ensures that camera position was already updated
    private void LateUpdate()
    {
        Camera.main.ResetWorldToCameraMatrix(); // Force camera matrix to be updated
        var targetPos = Camera.main.WorldToScreenPoint(Enemy.transform.position);
        if (targetPos.z > 0)
        {
            var pos = targetPos.Round(); // Pixel snapping
            pos.z = 0;

            HealthBarElement.SetPositionAndRotation(pos, Quaternion.identity);
        }
    }
}

```
> 0 votes

---
Tags: unity, gui
---


# Question
Title: Finding SpriteRenderer of specific Child Gameobject
So i'm trying to work on my Equipment System to also change the appearance of the sprites on my Character once i change the equipped item. My animations are setup in limbs so all i would have to do (i think?) is change the actual sprite of the specific limb skin i want to change (e.g. The Shoes), since the animation should still work independent of what the sprite is. However the problem i'm having is that my equipment manager is on a seperate gameobject than the character is and i don't seem to be able to find the SpriteRenderer components (Null pointer reference). My current function looks like this: Obviously the commented parts are irrelevant for my question, and i will eventually make the gameobject search more specific to which item piece i'm equipping. For clarification, the Equipment Manager is on my GameManager object and the sprites are on the Player Screenshot Object and its' children.

```
public void EquipItem(Equipment newItem)
{
    //int slotIndex = (int)newItem.equipSlot;
    //Equipment oldItem = null;

    SpriteRenderer targetSR;

    //if(currentEquipment[slotIndex] != null)
    //{
    //    oldItem = currentEquipment[slotIndex];
    //    inventory.AddItem(oldItem);
    //}

    //if (onEquipmentChanged != null)
    //{
    //    onEquipmentChanged.Invoke(newItem, oldItem);
    //}
    //currentEquipment[slotIndex] = newItem;

    targetSR = GameObject.Find("Mage5/Hip/Body/Hand_L").GetComponent<SpriteRenderer>();
    targetSR.sprite = newItem.icon;
}

```

# Answer
> 0 votes
That is a very slow method and unreliable in case you misspell some naming. Or just rename something. Use references to your `SpriteRenderer`s and simply use them when you need. For example place this in your character code.

```
[SerializeField] private BodyPartsSpriteRenderers _bodyPartsSpriteRenderers;

// Use example
private void Start()
{
    this._bodyPartsSpriteRenderers._Head.sprite = // Some head sprite
}

[System.Serializable]
public class BodyPartsSpriteRenderers
{
    [SerializeField] private SpriteRenderer _head;
    public SpriteRenderer _Head     { get { return this._head; } }

    [SerializeField] private SpriteRenderer _leftArm;
    public SpriteRenderer _LeftArm  { get { return this._leftArm; } }

    [SerializeField] private SpriteRenderer _rightArm;
    public SpriteRenderer _RightArm { get { return this._rightArm; } }

    [SerializeField] private SpriteRenderer _legs;
    public SpriteRenderer _Legs     { get { return this._legs; } }
}

```

Specific for your case:

```
public void EquipItem(Equipment newItem)
{
    switch (newItem._BodyPart) {.........
        case BodyPart.Legs:

            this._bodyPartsSpriteRenderers._Legs.sprite = newItem.icon;

        break;
    ..... }
}

```

Don't forget to assign them in the inspector or you will get `NullReferenceException`.

# Answer
> 0 votes
If your character have only on SpriteRenderer Component you can try something like

```
//Player is the root of your player gameobject
TargetSR = Player.GetcomponentInChildren<SpriteRenderer>();
TargetSR.sprite = newIcon;

```

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


# Question
Title: Using polymorphism in an Entity-Component System without sacrificing data-oriented design
I've been planning out an Entity-Component System in C++. My idea of it is most in line with the one described on this page of the entity systems wiki. To summarize, components are just structs of data, all code is in systems, and entities are just IDs shared by components.

The issue I'm having is mostly to do with how components are stored and accessed. My intent was to have a vector for each component type (which inherit a base `Component` class). These vectors are then stored in an unordered map, with a `ComponentType` (an enum) as the key. An `EntityManager` handles interactions with the vector, with functions like `removeComponent`, which takes a ComponentType and ID as arguments (which would search the unordered map and then iterate over the matching vector until finding the correct component to remove).

I specifically liked this implementation because it meant **I could add new component types without having to change the way the manager accesses the vectors.**

I realized that this implementation only works when utilizing polymorphism (i.e., a bunch of `vector<Component*>`s), since this allows them to all be stored in a **single container**, and operated on the same way. Unfortunately, this design results in the actual object data being scattered all over memory (even though the pointers are contiguous).

An advantage of the original structure that I chose, in my mind, was the improved cache performance offered by accessing large contiguous structures of data. But storing components in vectors is a problem, because then each vector is of a **different type** (ex: `vector<Position>`vs `vector<Velocity>`). This means I can't store them in one container, or use the same interface for operations on all of them. I believe I'd have to add new code to handle each new type of vector every time one was added.

I've been wracking my mind for the last few hours trying to devise a compromise. I can't seem to think of a design that would both **store each type of component contiguously in data** as well as **allow for generic operations on those collections** (ex: functions like the aforementioned `removeComponent` that don't require edits with each new compent type). I'm also unsure if my desire to maintain contiguity is reasonable, or if the impact on performance would actually be quite minor.

# Answer
The way I approached this was to use a constexpr string-hash which I apply to my components at compile-time to assign each of them a unique id. I essentially do this with the use of a macro where I provide a generated UUID string that gets hashed and a name to my macro.

Under the hood, this macro adds some static methods allowing me to fetch the the class name and its associated string-hash value of the UUID so that I have some basic RTTI data about this class.

```
struct PositionComponent
{
  COMPONENT_RTTI( PositionComponent, "004cdde9-bf20-4da2-a013-c6150fe87492" )
}

```

The most important thing the above macro exposes is:

```
static ComponentType TYPE = StringHash::hash( uuid );

```

Next I design my component pools using a base class and a templated derived class where I actually manage the storage for each specific component-type:

```
struct ComponentPoolBase
{
  virtual Component* CreateComponent(EntityId entityId) = 0;
  virtual Component* GetComponent(EntityId entityId) = 0;
  virtual void DestroyComponent(EntityId entityId) = 0;
};

template<typename T>
class ComponentIterator
{
public:
  // ...
};

template<typename T>
class ComponentPool : public ComponentPoolBase, public ComponentIterator<T>
{
public:
  ComponentType GetType() const { return T::TYPE; }

  template<typename T> T* Create(EntityId entityId);
  template<typename T> T* Get(EntityId entityId);
  virtual void Destroy(EntityId entityId);

private:
  std::vector<T> components_;
}

```

There are several benefits with this approach. The first is that how you store the components it abstracted away from the EntityManager. Should you decide to change the implementation, the EntityManager is none the wiser as it is based on whatever exposed API the pool provides, as it should be from a SRP perspective.

Secondly the component pool does store the components in contiguous memory; however you do need to take care here because of the vector implementation and the fact memory addresses could become invalidated after a new component is inserted.

Should you need some type of reliable pointer mechanism, you can add another layer of indirection to this solution where you have something like a uint32 or uint64 value that maintains several key pieces of information encoded into the value

1. Component handle valid or not (based on some version)
2. Index into a sparse array inside the component pool

The sparse array inside the component pool is meant to be a lookup-table that the pool maintains when components get shifted around so that you effectively can translate a Handle -\> index in the vector.

But for a simple approach, something like this will always work:

```
Position *position = entityManager->AddComponent<Position>( playerId );
position->SetPosition( x, y, z );

```

Now inside the EntityManager, you can maintain an unordered\_map of your component pools based on their component types quite simply.

```
template<typename T, typename... Args>
T* EntityManager::AddComponent(EntityId entityId, Args&&... args)
{
  ComponentPool<T> *pool = GetOrCreatePool<T>();
  return pool->Create( entityId, std::forward<Args>( args )... );
}

template<typename T>
ComponentIterator<T> EntityManager::GetComponents()
{
  return GetOrCreatePool<T>();
}

template<typename T>
ComponentPool<T>* EntityManager::GetOrCreatePool()
{
  ComponentPool<T> *pool = nullptr;

  auto itor = pools_.find( T::TYPE );
  if ( itor == pools_.end() )
  {
    pool = new ComponentPool<T>( this );
    pools_.insert( std::make_pair<>( T::TYPE, pool ) );
  }
  else
    pool = itor->second;

  return pool;
}

```

As you can see I've exposed a `ComponentIterator<T>` class type allowing me to expose the `ComponentPool<T>` as a specialized iterator class where I can easily iterate all components in the underlying pool without concern of the storage itself.
> 1 votes

# Answer
I had almost the same problem you have right now, except i tried to use pointer for the to my Buffers createComponent-method and call those.

The solution they gave me was to have arrays (or vectors) of base classes like this: `class ComponentBase {
 public:
 ComponentBase() {};
 virtual void* createComponent(unsigned int ID) = 0;
 virtual void deleteComponent(unsigned int ID) = 0;
 virtual ComponentID getComponentID() = 0;
 virtual int getSize() = 0;
 };`

Additionally i made a buffer class, saving components in an contiguous memory block until full, then opening another contiguous memory block and delete them when empty and so on.

These can be inherited by your ComponentBuffer:

`template <typename TComponent = Component>
 class ComponentContainer : public Buffer<TComponent>, public ComponentBase`

In your Entity manager, you can now have Array/Map/whatever\[ComponentBase\] oder \[ComponentBase\*\], which hold your ComponentContainers.

Only 'Problem' with this is, that your EntityManager itself doesn't know, what Component type is inside each ComponentContainer. In my system that is not a problem, since every other manager registers the components it needs in the EntityManager and when needed asks the EntityManager for a ComponentBase and casts it to the ComponentContainer with the needed TComponent.
> 0 votes

---
Tags: c++, entity-system, polymorphism, data-oriented
---


# Question
Title: How to automatically rank items in an array by the sum of certain of their properties?
I am making a little boxing management sim in my spare time. What I'm stuck on is trying to give the pool of boxers their initial rankings.

I have a List\<\> of Boxers all with random stats. Each individual boxer class then adds all these stats together and has a public variable called 'totalStats'

I want to make the boxer with highest value of totalStats ranked number 1.

How can i do this in a for loop? or is there some other way I should do it?

So for now what I have is this:

```
    void CreateAllBoxers()
{
    for (int i = 0; i < startingBoxerCount_HeavyWeights; i++)
    {
        GameObject boxer = new GameObject();
        boxer.AddComponent<Boxer>();
        boxer.GetComponent<Boxer>().BuildBoxerStats(
            GetRandomFirstName(),
            GetRandomSurname(),
            GetRandomHomeGym(),
            GetRandomCompany(),
            Random.Range(8, 20),
            Random.Range(8, 20),
            Random.Range(8, 20),
            Random.Range(8, 20),
            Random.Range(8, 20),
            Random.Range(8, 20),
            Random.Range(Constants.minWeight, Constants.maxWeight),
            Random.Range(Constants.minHeight, Constants.maxHeight),
            Random.Range(18,40),
            Random.Range(Constants.minCommission, Constants.maxCommission));
        boxer.GetComponent<Boxer>().SetId(boxers.Count);
        boxer.name = "Boxer_" + boxer.GetComponent<Boxer>().GetId(); //this just sets the instance hierarchy name in editor, not the actual boxers name string
        boxers.Add(boxer);
        Debug.Log("Boxer created: name " + boxer.GetComponent<Boxer>().GetNameA() + " " + boxer.GetComponent<Boxer>().GetNameB() + ", signed to" + boxer.GetComponent<Boxer>().GetCompanySignedTo());

    }
}

void GiveBoxersInitialRank()
{

}

```

# Answer
> 2 votes
I can't tell if you're in C# or not; so **this advice is for c#.**

You can do a simple Linq query to sort arrays:

```
// Order a new list to be sorted by boxers, then transform into an array
ArrayOfBoxers = ArrayOfBoxers.OrderBy(boxer => boxer.totalStats).ToArray();

```

The reason I mention linq is that while there are sorting functions you can use, Linq allows you to use Lamda functions for annoying tasks like this. Ordering dictionaries, lists, arrays, etc.

You could, instead, implement IComparable then make a list from your array, call List.Sort on that and then ToArray that; but the above Linq will do all of that for you in a single line.

Please note that you shouldn't use things like this in code that gets called a lot as this is going to create a list, then create a new array, and finally (in my example) drop your old array; making it likely to cause high memory fragmentation and be slow due to a lot of allocating/deallocating.

Your final option (off the top of my head anyway), which is the most work, is implement a Quicksort (or another sort..) somewhere and do it yourself. This will be efficient on both memory and time if done right, but comes at the cost of having to write custom code for it.

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


# Question
Title: How to pass vector<struct> to GLSL shader?
I am using core OpenGL to draw fonts. This works when I do just one font set at a time. Now I am trying to use three different sets in an array.

I have this structure:

```
struct _sdf_Vertex
{
    glm::vec2       position;
    glm::vec2       textureCoord;
    glm::vec4       color;
};

```

and I use three fonts - so this:

```
vector<_sdf_Vertex>     sdf_vertex[3];
vector<unsigned int>        sdf_indexes[3];

```

I then populate each font type like this ( this works fine - I can see all the data in each element):

```
void sdf_addVertexInfo(uint whichFont, glm::vec2 position, glm::vec2 textureCoord, glm::vec4 color)
{
_sdf_Vertex     sdf_vertexTemp;             // Temp to hold vertex info before adding to vector

sdf_vertexTemp.position = position;
sdf_vertexTemp.textureCoord = textureCoord;
sdf_vertexTemp.color = color;
sdf_vertex[whichFont].push_back(sdf_vertexTemp);
}

```

and then I want to pass one set of font data to the shader:

```
    glBufferData ( GL_ARRAY_BUFFER, sizeof(_sdf_Vertex) * sdf_vertex[whichFont].size(), &sdf_vertex[whichFont], GL_DYNAMIC_DRAW );

    glVertexAttribPointer ( shaderProgram[SHADER_TTF_FONT].inVertsID, 2, GL_FLOAT, GL_FALSE, sizeof(_sdf_Vertex), (GLvoid*)offsetof(_sdf_Vertex, position) );
    glEnableVertexAttribArray ( shaderProgram[SHADER_TTF_FONT].inVertsID );
    //
    // Specify the texture info
    glVertexAttribPointer ( shaderProgram[SHADER_TTF_FONT].inTextureCoordsID, 2, GL_FLOAT, GL_FALSE, sizeof(_sdf_Vertex), (GLvoid*)offsetof(_sdf_Vertex, textureCoord) );
    glEnableVertexAttribArray ( shaderProgram[SHADER_TTF_FONT].inTextureCoordsID );
    //
    // Specify the color array
    glVertexAttribPointer ( shaderProgram[SHADER_TTF_FONT].inColorID, 4, GL_FLOAT, GL_FALSE, sizeof(_sdf_Vertex), (GLvoid*)offsetof(_sdf_Vertex, color) );
    glEnableVertexAttribArray ( shaderProgram[SHADER_TTF_FONT].inColorID );

glBufferData ( GL_ELEMENT_ARRAY_BUFFER, sdf_indexes[whichFont].size() * sizeof(unsigned int), &sdf_indexes[whichFont], GL_DYNAMIC_DRAW ) );
glDrawElements ( GL_TRIANGLES, sdf_indexes[whichFont].size(), GL_UNSIGNED_INT, 0 ) );

```

Checking the vertex shader with renderDoc - I'm not seeing any of the sdf\_vertex data coming through, or sometimes it's all scrambled. I think it's got to do with the how I'm trying to point glBufferData to the vector of structs inside an array.

How do I pass the location of the vector inside an array?

Thanks.

# Answer
So you've got to arrays of vectors, sdf\_vertex and sdf\_indexes.

The problem I can see, these two statements:

```
&sdf_vertex[whichFont]

```

and

```
&sdf_indexes[whichFont]

```

are accessing the address of each of the vecotors, rather than the data in those vectors.

You should be able to update those in place to

```
sdf_vertex[whichFont].data()

```

and

```
sdf_indexes[whichFont].data()

```

Note .data() is C++11, if you're unable to use that there's the older .front().

\** I'm assuming C++ here, though that's not tagged or explictly mentioned.
> 1 votes

---
Tags: opengl, glsl
---


title: How to compress Unity apk output?

text:
# Question
Title: How to compress Unity apk output?
I made a game with Unity but the size of .apk file got so large, it is about 70mb... Is there some way that I can compress my apk file?

# Answer
> 6 votes
You can compress certain assets individually.

After building the project, go into the log file and there will be a summary of what assets were packaged with the apk, and their sizes. (On windows, located in C:/Users/username/AppData/Local/Unity/Editor/Editor.log)

Find large textures/music/sound, and select them in the project view to bring them in the inspector.

For each texture, there are multiple options: Reduce the 'max size'/'max resolution' (default max resolution is 1024^2, reducing this will force unity to resize the texture upon building the project) Change the compression (Avoid setting textures to TrueColor except where needed)

For music/sound, make sure the format is "Compressed", and then you can adjust the compression value. Compression of ~80kbps is normally good enough to cut the size down, and still mantain decent quality. You can go lower if you really want to. If the 'force to mono' checkbox is enabled, check it. It will reduce the footprint of the file by combining the sounds from the left and right channels.

Be sure to test the game with the assets compressed, and make sure things still look 'good'. You will lose quality by using lossy compression such as reducing resolution or using highly compressed texture formats.

# Answer
> 2 votes
1. You can use Tinypng to decrease you graphics size without visible graphics quality damage, Decreasing graphics size ultimatly leads to decrease in apk size.
2. Make spritessheets either using Texture Packer or using Unity3d own Sprites Packer.
3. (Optional ) if you are targeting only ARMv7 or x86 Devices then change it from player Settings it will reduce approximately 8 to 10 MB.

> Edit \> Project Settings \> Player
>
> In Other Settings Section You will find Device Filter

# Answer
> 1 votes
Set your image size square and Set unity suggested pixels.(32, 64, 128, 256, 512, 1024, 2048, 4096, 8192) If your image size is 567x890 pixels then set this image in a 1024x1024 pixels background transparent blank image and save it as a png file.

Then in unity inspector set this image as a sprite and slice it by sprite editor. This process will make your image size reduce minimum 20%.

Example image and changes given below.

Before: resolution 567x890 pixel, size 1.9MB

After: resolution 1024x1024 pixel, size 1.3MB

Result: size 0.6MB reduced, almost 32%.

Image file Link: https://drive.google.com/file/d/0B9zkzr6JdNYlaHhqcDVUSk9KNjA/view

# Answer
> 0 votes
You can also choose to set the Device filter to Arm7. This will exclude certain devices, but I believe the number is quite small and it does minimize the apk size a bit. (This is located in Player Setting -\> Other Settings -\> Device Filter). You could try a build and see how much it would reduce it by and decide whether it was worth it.

Some Info on device filter: http://answers.unity3d.com/questions/971648/device-filter-to-arm-7-only.html

# Answer
> 0 votes
It is also good to set texture / sprite compression format.

Check this website: https://docs.unity3d.com/Manual/class-TextureImporterOverride.html

Most texture compression format needs image in power of 2 resolution (128, 256, 512, 1024, 2048). Resolutions 4096 and 8192 may not work on some android devices.

For example texture with no alpha in 1024x1024 resolution using RGB ETC2 compressions takes about 0,5MB in memory. Image 1280x800 with compression format RGB 16bit takes 2MB

---
Tags: c#, 2d, unity, unityscript
---


title: Poker AI's designed for casual play

text:
# Question
Title: Poker AI's designed for casual play
> DISCLAIMER: So I asked this on StackOverflow and was told it was not a good question for the community but was suggested to check here. If this question sucks or just doesn't belong here either, feel free to let me know. It seems a fair question to me, but I know it's important to maintain high standards on these sites.

So I just put the finishing touches on a poker game in JavaFX. Part of the functionality in this program is a single player mode, where you can play hands against the computer. To be transparent, this is a university project, so I'm not aiming for perfection. More, just an ai that behaves semi-intelligently for game variation and minor challenge for casuals.

So to be clear, I am aware of general poker strategy, and have found numerous articles/research papers/links on more in-depth poker AI's designed to compete against competitive players. I guess as an analogy, there's the Easy mode bots in League of Legends, then there's the deep learning AI that beat a DOTA pro in laning.

I'm definitely aiming for the former here. While I currently have a basic algorithm that works as:

```
if(gamestate = flush, straight, 3-pair, full-house, face card pairs)
{
     raise 1/4 pot;
}
else if(gamestate = pair, potential flush or straight, etc)
{
     check/call;
}
else
{
    fold;
}

```

So I already have functionality that can detect current board/hand states, but I do not have any functionality that can estimate chances at winning the hand, compare with opponent's possible hands, etc. Since the game only needs to be for casual play, the more advance algorithm's seem like massively overkill.

I guess my wishful thinking hope is that something exists similar to min-max in tic tac toe, although poker is obviously more complex. But something that can make some kind of rough approximation of hand value, that wouldn't require thousand's of if statements to cover every possible situation.

So if anyone knows of any algorithms that would be used in, for example, a poker phone game or such, I'd really appreciate some help. To reiterate, if this question is too vague, I'm happy to provide any other information about my existing research, program design, or anything in this vein.

# Answer
Strategically, poker is a very complex game, but there's also a very limited set of actions a player can take. Count 'em: fold, call, check, raise X. So really there's countless ways you can implement even a simple AI. I would suggest you approach the problem iteratively, and adjust until you've got an acceptable AI.

As a start, you could make an AI that **calls everything**. It will be unbluffable, but also easy to beat because as long as you have a good hand you can raise and win everything. But it's a dead-simple algorithm with at least some chance for the player to lose.

Next you could add a **call limit**. The AI will be willing to bet more if their hand is good or if their chance of winning is good. This AI has the opposite weakness: it's too easy to bluff. But for fixed-limit poker, it might be fine.

As for estimating the chance to win, this can be very simple. It is simply looking at the chance that an opponent could have a higher hand than the player, out of all the cards that are not shown. For example, let's say that the only opponent has one card in their hand that the player can't see, and the only chance they can beat the player's hand is if it is an ace, and there are currently no aces in view. There are 4 aces, and suppose there are 40 cards not in view, so their chance of winning is 4/40 or 1-in-10 chance, and the player has a 9-in-10 chance.
> 1 votes

---
Tags: ai, card-game, poker
---


# Question
Title: Using a remote highScore storage/retrieval system. I have no idea on how to implement
The system is something like this:

> highScoreDB || Validator || PlayerSession
> ---Database---||--Script---||----Game------

`PlayerSession` is an active game session, on finalizing a match, the game checks if `highScoreDB` is full, if full; compare the session's score with the lowest DB score and replace if its greater; if not full then just add the session score normally. Upon score submission, the game also sends some other data for the `Validator`.

The `Validator` checks if the score is legit by processing the extra data(match duration, key entities interacted with, etc); if the score is valid, then score is applied successfully; otherwise, it's rejected and the sent data is logged elsewhere(not relevant ATM).

The `highScoreDB` simply stores the data for retrieval by players.

---

Now I do not know how to make and where to stick the scripts as well as how to appropriately store the data. I'd appreciate any assistance on this matter.

# Answer
> 1 votes
The components `Validator` and `Database` will have to be on a remote server. Trying to implement either in Unity would be a bad idea.

I would recommend to use the HTTP protocol for the communication between database and validator. The reason is that HTTP is very unlikely to be blocked by firewalls, that you can implement the endpoint using a webservice and that the Unity script can use the class `WWWForm` to send POST requests to it. The example uploads an image to a webserver. You would want to upload playername, score and the data you need to validate the score. Use `WWWForm.AddField(string key, string value)` to add the necessary data to your HTTP POST request.

There is a vast variety of technologies you can use to implement the validator. You can use anything which can be used to create webservices and communicate with a database backend. The options are so numerous, that it is difficult to give any recommendation. There is something for everyone available here. ASP (.NET or classic), JSP, PHP, Node.js, Django, Ruby on Rails, etc. etc. Just pick the tech you know or would like to learn.

The database should be a common SQL (or NoSQL, if you feel adventurous) database. The scoreboard would be one table (`name`, `score`, `timestamp`). But you also might want to persist the validator-data so you can retroactively catch cheaters when you add additional validations later.

# Answer
> -1 votes
In your game level scene you should have the actual score. In the same scene you could have the script(s) that check your highscore and update it if the actual score is higher.

You could do this at the end of the game. For example:

```
public void GameEnd()
{
    if(PlayerSession.GetInt() < actualScore) //I don't remember if this is the correct syntax of player session.
    {
        //Do stuff here to update score
    }
}

```

Now you only call this method when the player has lost.

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


# Question
Title: Why is my texture array getting only the last link index?
Here's my code:

```
[SerializeField] GameObject[] uitex = new GameObject[3];

void GetTextureFromServer()
{
    string dealer_img = "";

    for (int i = 0; i < PlayInfo.Instance.gametablelist.Count; i++)
    {
        dealer_img += PlayInfo.Instance.gametablelist[i].dlrimage;
        dealer_img += ",";
    }
    Debug.Log("HERE ARE THE LINKS : " + dealer_img);

    string[] links = dealer_img.Split(',');

    for (int j = 0; j < links.Length - 1; j++)
    {
        Debug.Log("HERE ARE THE NEW LINKS : " + links[j]);

        new BestHTTP.HTTPRequest(new System.Uri("*************************amazonaws.com/resources/" + "dealer/pic/" + links[j]),
        (BestHTTP.HTTPRequest req, BestHTTP.HTTPResponse res)
        =>
        {
            for (int k = 0; k < uitex.Length; k++) {
                var tex = new Texture2D(20, 20);
                tex.LoadImage(res.Data);
                uitex[k].GetComponent<UITexture>().mainTexture = tex;
            }
        }).Send();
    }
}

```

The problem with this code is that it's only getting the last index of my `links`. What could be the problem on my iteration?

Here's an approach that works that shows what the expected behavior is:

```
 for (int i = 0; i < tzPlayInfo.Instance.bc_gametablelist.Count; i++)
{
    dealer_img += tzPlayInfo.Instance.bc_gametablelist[i].dlrimage;
    dealer_img += ",";
}
string[] newLinks = dealer_img.Split(',');

new BestHTTP.HTTPRequest(new System.Uri("**************************.amazonaws.com/resources/"
    + "dealer/pic/" + newLinks[0]),
    (BestHTTP.HTTPRequest req, BestHTTP.HTTPResponse res)
    =>
    {
        var tex = new Texture2D(20, 20);
        tex.LoadImage(res.Data);
        uitex[0].GetComponent<UITexture>().mainTexture = tex;
    }).Send();

new BestHTTP.HTTPRequest(new System.Uri("**************************.amazonaws.com/resources/"
    + "dealer/pic/" + newLinks[1]),
    (BestHTTP.HTTPRequest req, BestHTTP.HTTPResponse res)
    =>
    {
        var tex = new Texture2D(20, 20);
        tex.LoadImage(res.Data);
        uitex[1].GetComponent<UITexture>().mainTexture = tex;
    }).Send();

new BestHTTP.HTTPRequest(new System.Uri("**************************.amazonaws.com/resources/"
    + "dealer/pic/" + newLinks[2]),
    (BestHTTP.HTTPRequest req, BestHTTP.HTTPResponse res)
    =>
    {
        var tex = new Texture2D(20, 20);
        tex.LoadImage(res.Data);
        uitex[2].GetComponent<UITexture>().mainTexture = tex;
    }).Send();

new BestHTTP.HTTPRequest(new System.Uri("**************************.amazonaws.com/resources/"
    + "dealer/pic/" + newLinks[3]),
    (BestHTTP.HTTPRequest req, BestHTTP.HTTPResponse res)
    =>
    {
        var tex = new Texture2D(20, 20);
        tex.LoadImage(res.Data);
        uitex[3].GetComponent<UITexture>().mainTexture = tex;
    }).Send();

```

It's working perfectly, but now the problem is that it is not very clean code.

# Answer
Since you want to assign a single link to a single texture, just capture the index into a lambda, kinda like you were doing.

```
for (int i = 0; i < newLinks.Length; i++)
{
    var index = i;  // We need to make a local copy because C# captures variables by reference to lambdas.
    new BestHTTP.HTTPRequest(new System.Uri("**************************.amazonaws.com/resources/"
        + "dealer/pic/" + newLinks[index]),
        (BestHTTP.HTTPRequest req, BestHTTP.HTTPResponse res)
        =>
        {
            var tex = new Texture2D(20, 20);
            tex.LoadImage(res.Data);
            uitex[index].GetComponent<UITexture>().mainTexture = tex;
        }).Send();}
}

```

So we take the link at the index, and assign the downloaded image into the texture at the same index. The additional `index` variable is required, because C# captures by reference. See here.
> 1 votes

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