# Question
Title: Unity: object with strange transparent color?
In my game the players left arm is this weird transparent color, but the right is normal. When i drag the right arm's material over to the left it doesn't fix the problem, so there's something wrong with the object itself not the material. How do i fix this?

# Answer
> 2 votes
3D models are usually rendered only on the outside or inside of the model, the reason the right arm is partially transparent is probably because during the 3d modelling process the right arm had its faces flipped so that when rendered in unity the arms inside faces are the only faces that render hence the reason you can see the back and not the front. I know in particular blender renders both sides which can confuse people when they import their models into unity and see only one side of the face rendered.

I don't know what 3d modelling software you use but if you look online you should find a tutorial on how to invert the drawn faces, this may solve your problem.

# Answer
> 0 votes
I don't know what is the problem behind this, but one possible solution is to import your right hand in Google SketchUp and make its mirror image model. Then export its .fbx file and include this .fbx file to your unity project. It should work.

---
Tags: unity
---


# Question
Title: How to add & copy ParticleSystem attached to an existing GameObject using C# script in Unity?
I have a GameObject "FireBall" with a ParticleSystem attached to it. I want to add the same ParticleSystem to other GameObject "Avatar". Initially there is no ParticleSystem attached to "Avatar".

When I do this -

```
ParticleSystem fireparticlesyst = gameObject.AddComponent<ParticleSystem>();

```

It adds a ParticleSystem to "Avatar" but I want to set all the properties of this ParticleSystem to the ParticleSystem attached to "FireBall".

If I add all the properties by individually I can't set some of the properties as they are read only.

How to do this ?

# Answer
A simple workaround to do so is:

1- Make an empty `GameObject` with `ParticleSystem` attached.

2- Make prefab of that. Borrow that prefab as `public GameObject` in your script.

3- Instatiate as GameObject in your script.

4- Make child of `FireBall` and other `GameObjects` as well.

```
public GameObject _particleSystem;

void CreatePS()
{
    //Instantiate _particleSystem as new GameObject.
    GameObject ps = Instantiate(_particleSystem);

    // Set new Particle System GameObject as a child of desired GO.
    // Right now parent would be the same GO in which this script is attached
    // You can also make it others child by ps.transform.parent = otherGO.transform.parent;
    ps.transform.parent = transform;

    // After setting this, replace the position of that GameObject as where the parent is located.
    ps.transform.localPosition = Vector3.zero;
}

```
> 3 votes

---
Tags: unity, c#, particles, shuriken
---


# Question
Title: What's the reasoning behind using "redistributable" packages?
On Windows, many if not all games require some DirectX package and some VC++ runtime. Others also need OpenAL, wmfaredist, nvidia physx, windows live and probably others.

I'm trying to figure out why do game developers use them. Like what problems are they trying to fix by using them, and how are those problems bigger than the problems they are creating by using them, like the compatibility issues of the VC++ packs, or inconveniencing players.

I'm thinking that it's because these are libraries developed by others, thefor they can save game developers some coding time. That's fine I guess, but then why aren't they including the .dll files directly into the game?

# Answer
There are different answers here depending on which REDIST packages we are actually talking about.

In most cases, the reason that REDIST packages are used is because the components involved require administrator rights to install because they install drivers, update system components, install files into `%WINDIR%\System32`, and/or install Windows Services. For User Account Control support, you can really only require administrator rights at install time, not every time the application is run.

# Visual C++ REDIST packages

The rules here have changed over the various releases of Visual C++, so some of the usage here is based on simply looking for the easiest and quickest solution. In most cases, games already have an installer that requires administrator rights so it's just easiest to launch the VC REDIST EXE (either x86 or x64 depending on their game EXEs) to deploy the CRT DLLs system-wide.

Application local deployment (i.e. just copying the DLLs with your game EXEs) is an option, but for security servicing it's actually nicer to have a system-wide version that gets patched automatically as needed. For VS 2005 / 2008 the Fusion Side-by-side manifests tried to make it possible to service even local deployment, but it was a bit flakey. As of VS 2010, the use of these old manifests were removed so if you use local deployment you have to update your application to apply any CRT security fixes.

The only really good reason to do application local deployment for the Visual C++ CRT is if you are trying to avoid the need for admin rights for deployment, but you have to take responsibility for security updates and don't get anything 'for free' in this regard.

> Windows Store apps do not deploy the CRT. It's taken care of by the system.

# DirectX REDIST (aka DirectSetup)

The answer here is that most developers are using the REDIST because they don't understand what it actually does. Or more importantly, what it doesn't do. Ideally, most games would never use the legacy DirectX SDK anymore (see Living Without D3DX), but there are still a few specific scenarios where you need to rely on it. And the main reason they use the REDIST is that the License Agreement doesn't allow you to do application local deployment of any of those DLLs.

Back in the day, DXSETUP installed DirectX components like DirectDraw, Direct3D, DirectSound, etc. The modern REDIST, however, *never* installs DirectX components. As of Windows XP Service Pack 2, these are all part of the OS and are only updated through Service Packs, Windows Updates, or new versions of the OS.

The legacy DirectX SDK REDIST is still required to deploy D3DX9, D3DX10, D3DX11, XAudio 2.7, XInput 1.3, XACT, or D3DCompile #43.

XAudio 2.8, XAudio 2.9, and XInput 1.4 are part of the Windows 8.x and Windows 10 operating systems, and again are never deployed by the legacy DirectX SDK REDIST.

D3DCompile #46 and #47 are available to be deployed application local in the Windows 8.x SDKs and Windows 10 SDKs. D3DCompile #47 is part of the Windows 8.1 and Windows 10 OS, so you don't have to deploy it application local for these platforms. Ideally you'd never do any HLSL compilation at runtime and ship all your shaders prebuilt, but you need the D3DCompile DLL to use any shader metadata reflection APIs. D3DCompile #46 and #47 are never deployed by the legacy DirectX REDIST.

> Windows Store apps can't use the legacy DirectX SDK REDIST at all. They use the built-in OS components, and all DLLs that they ship in their AppX package must meet the API restrictions of the WACK validation tool.

Note that if your game is actually using something that the legacy DirectX REDIST installs, you should take a look at using the April 2011 update of those files--the `.CAB` files were not changed, just the DXSETUP files.

See Not So Direct Setup,
XAudio2 and Windows 8,
XINPUT and Windows 8,
HLSL, FXC, and D3DCompile
> 2 votes

# Answer
* Save drive space,
* Save RAM usage by sharing read-only memory pages (code & ro-data),
* Fix critical bugs and security issues by updating the libs.

The first two are pretty moot points nowadays but the last one is still useful.
> 1 votes

---
Tags: directx, windows, dll, microsoft
---


# Question
Title: Is it legal to clone a character from other game?
Is it legal to make a character very similar/exact from other game? E.g. take characters from Team Fortress 2 game, remake them in pixel art and use it in my game, but just change their names(with an intent to make money).

Would I get in trouble?

# Answer
When the IP holder whose characters you rip off feels like it, their lawyers can cause you all kinds of legal trouble. Copyright and IP lawsuits are civil lawsuits, and in civil lawsuits it's not about who is right, it's about who is right and has enough money to prove it.

Even if we assume the best case and a court ends up deciding that all their claims are ridiculous, this will be after you paid a fortune in legal fees and after various injunctions, subpoenas and DMCA takedown notices have already ruined your business.

Instead of ripping off someone else's IP, better develop your own. It's far safer and it's more fun anyway.
> 1 votes

---
Tags: copyright, trademark
---


title: Designing loots for chests

text:
# Question
Title: Designing loots for chests
Let's say we have a game, with enemies you fight, items to get and also chests to find and loot. Imagine a RPG game if you will. We also have a table with x items that the player can loot from these mentioned chests. Some of these items are "one drop only", while others can drop more than one time. We might set that as a variable in the table. Now to the question: **When would you scatter the items in the table to the chests?**

* Would you do this as soon as the level loads?
* Would you do a lookup when the player opened a chest?

As far as I see it, if you scatter the items when the level starts, the player could miss a unique item, if the player skipped that specific chest containing that unique one-time-only item. But, if you do a lookup when the player opens a chest, the player does not need to worry (if the player knew exactly how it was coded) about actually missing unique items. How would you handle this design wise? Is it ok for players to miss unique items for being lazy/bad/unlucky? Or, do we always want the player to be able to get just about all the items in this table at one point? Which way would you prefer as a dev? Which way would you prefer as a player? Have I missed an important factor, a third way to handle it, or something else?

# Answer
My view: if you generate on chest open this will induce save scrimming (spelling?) and people re-loading saves for better loot unless it's MMO. If you do it on a per-level basis, on the other hand, you risk people missing cool loot due to (P)RNG screw ups and missed drop chances. Neither is terribly optimal IMO. As a single player, story based and not random-generated loot developer, I personally prefer pre-set loot in most cases with minor variance cast on 'chapter' initialization (removed from level loads but still playthrough specific) states which are flipped, i.e. Item1 always appears somewhere, the question becomes is it in Part I, Part II, or Part III. I can also include minor variance in scenes based on the same RNG cast, making the game world seem less fixed, even if you reload prior to starting a new 'part' - whatever that mean in context, and parts for different 'types' of items may be cast at various points which are not advertised to the player but are internally consistent. Seen from a practical perspective, my motivation is to ensure the player will (probably) run across all the items of type X if they do the appropriate quests/missions and access the thematically relevant content. At the same time, every playthrough is a bit different, because where items drop - both in a thematic 'set' progression and in general timeline progression - will influence how the character plays, but only within a certain spectrum. This isn't a perfect system, to be honest, but when playing my own games (assuming someone like me, who knows where all the loot can be), it's incredibly annoying to NOT get an item just because a stupid RNG roll screwed me over. I prefer to walk over a trigger point for a specific encounter 10 times hoping for the respective outcome than to bungle around, looting randomly, and not getting what I want despite hours spent trying to perfect my character. My philosophy is to allow a player who wants X and knows how to get X to get X reliably within the scope of a sub-progression, but not on a per level (or per-encounter) basis. This generally only works in SP games however. If you're going for something MP or group-centric, this will turn out badly.
> 0 votes

---
Tags: single-player
---


# Question
Title: Advice on how to approach building background glow for 3d galaxy?
I've got a proceduraly generated 3d galaxy galaxy, very large. Milky Way scale. It is broken up into sectors, where I can relatively quickly get the star density and average star color of any given sector with a simple call:

```
Color GetColorAt(x,y,z); //where hue represents star color and intensity is density

```

I am already pulling in the sectors around the player's location, so that the player can fly through the stars. Works great, performance is fine. Now what I want to do is add in the collective glow from stars in the galaxy that are very far away. Just like when you look at the night sky (in a rural area) you can see the glow of the milky way. So one approach is to build a skybox. For each pixel of the skybox, cast a ray through the volume of the galaxy, and check at some # of points along the ray for the star density/color there, and add it all up, then use that to set the pixel of the skybox. However this is computationally extremely expensive. ~6x1024x1024x10 operations or thereabouts at a minimum. Another idea was do to a much sparser sampling of the galaxy density around the player, and use that data to create a particle system. Where each particle will take up way more than just 1 pixel. The effect might even look pretty good. Any other ideas? Is there a data structure that would let me do this quickly?

# Answer
> 0 votes
Well... very large is an pretty elastic term. I would suggest these 2 ways.

*Generation&Preparation stage*

* Arrange your sectors into a tree like spatial data structure (e.g. an octree-like structure) with lod support, so that you can get the spatially neighbourhood of sectors fast. You will need the lod technique to filter to filter 'invisible stars' in the distance.

Rendering stage

* Get the minimum amount of this tree's nodes within the player's view frustum. This results in O( log( |Nodes within tree| ) ).
* For each star in your node selection, cast a ray from the star to the camera (!) resulting in O( |Stars in Selection| ).

If this is not enough, performance-wise, you could try this:

*Generation&Preparation stage*

* Arrange your sectors into spatial data structure (e.g. an octree), so that you can get the spatially neighbourhood of sectors fast.
* For each sector generate a skysphere.

*Rendering stage*

* Take the current sector's skysphere and the skyspheres from the adjacent sectors.
* Combine these displaced and weighted to use the resulting skysphere for the actual rendering of the 'sky' in the next step.

---
Tags: skybox
---


# Question
Title: Cannot load png images to textures with SDL2 in Visual Studio 2015
I'm learning SDL2 with Visual Studio 2015 and I'm trying to draw a 16x16 level with a .map file and 32x32 .png images for tiles (that's 256 tiles) on a 512x512 window. I have both SDL2 and SDL2 Image set up.

I'm attempting to turn the .png image into a texture using IMG\_LoadTexture, but it never succeeds.

Here's the code for the structure for a single tile:

```
struct Tile
{
    int tileType; //a range from 1-12 that determines what kind of tile it is.
    SDL_Texture *texture = NULL; //The texture for the tile that comes from a .png file
    SDL_Rect texture_rect; //Rectangle for rendering the texture with SDL_RenderCopy
};

```

I successfully read the tileType from a .map file and use it in a function to give a tile in an array of tiles the right texture. Here is the code for the function :

```
void get_textures(Tile a[16][16])
{
    for (int i = 0; i < 16; i++)
    {
        for (int k = 0; k < 16; k++)
        {
            cout << a[i][k].tileType << ", ";
            switch (a[i][k].tileType)
            {
            case 1:
            a[i][k].texture = IMG_LoadTexture(renderer, "Sprites\Tiles_png\1.png");
            break;
        case 2:
            a[i][k].texture = IMG_LoadTexture(renderer, "Sprites\Tiles_png\2.png");
            break;
        case 3:
            a[i][k].texture = IMG_LoadTexture(renderer, "Sprites\Tiles_png\3.png");
            break;
        case 4:
            a[i][k].texture = IMG_LoadTexture(renderer, "Sprites\Tiles_png\4.png");
            break;
        case 5:
            a[i][k].texture = IMG_LoadTexture(renderer, "Sprites\Tiles_png\5.png");
            break;
        case 6:
            a[i][k].texture = IMG_LoadTexture(renderer, "Sprites\Tiles_png\6.png");
            break;
        case 7:
            a[i][k].texture = IMG_LoadTexture(renderer, "Sprites\Tiles_png\7.png");
            break;
        case 8:
            a[i][k].texture = IMG_LoadTexture(renderer, "Sprites\Tiles_png\8.png");
            break;
        case 9:
            a[i][k].texture = IMG_LoadTexture(renderer, "Sprites\Tiles_png\9.png");
            break;
        case 10:
            a[i][k].texture = IMG_LoadTexture(renderer, "Sprites\Tiles_png\10.png");
            break;
        case 11:
            a[i][k].texture = IMG_LoadTexture(renderer, "Sprites\Tiles_png\11.png");
            break;
        case 12:
            a[i][k].texture = IMG_LoadTexture(renderer, "Sprites\Tiles_png\12.png");
            break;
        }
        if (a[i][k].texture == NULL)
        {
            cout << "Failed to load texture from file." << endl;
        }
        a[i][k].texture_rect.x = k*TILE_WIDTH; //defined as 32
        a[i][k].texture_rect.y = i*TILE_HEIGHT; //defines as 32
        a[i][k].texture_rect.h = 32;
        a[i][k].texture_rect.w = 32;
    }
}
}

```

Every time this runs I get a tileType and a "Failed to load texture from file." for every one of the 256 tiles. I have re-checked the file paths multiple times, made sure the "Sprites" folder is in the same folder as the project's .vcxproj file and that the folders and images are included in the project in Visual Studio and it still doesn't work (I only get a black SDL window).

Any help would be appreciated.

# Answer
> 2 votes
You could use one of this two ways to place a backslash in a string:

```
@"Sprites\Tiles_png\11.png"
"Sprites\\Tiles_png\\11.png"

```

This must be done because C# implements backslashes. So, next character literals `\n`, `\r`, `\t`, `\"` and `\\` are respectively *a new line*, *character return line feed*, *vertical tab*, *qoutation mark* and *one backslash*.

It's also possible to escape them by using a string literals like the `@`-char before opening the first quotation mark, like I'd for the first string.

Here you have the definition of literals:

> A literal is a source code representation of a value.

---

A third option is to use forward slashes and then you haven't that problem anymore with the implementation of the backslashes. But because Microsoft use by default backslashes for file paths, I prefer to use one of the first two options.

```
"Sprites/Tiles_png/11.png"

```

# Answer
> 0 votes
I've found out my stupid mistake. The file path recognizes "/" and not "\\".

# Answer
> -1 votes
From the answers on these links it says not to use IMG\_LoadTexture, and IMG\_Load instead.

Here is a great tutorial on how to load a .png with SDL2: http://lazyfoo.net/tutorials/SDL/06\_extension\_libraries\_and\_loading\_other\_image\_formats/index2.php

Also this post suggests to use \*IMG\_Load instead of IMG\_LoadTexture for loading images:SDL Function for Loading PNGs

---
Tags: c#, sdl, sdl2
---


# Question
Title: What is a good way to procedurally generate large tilemaps?
I'm sorry if this question was already asked before. The game I'm aiming to make is a 2D-top down game in similar fashion to Zelda. I'm generating tilemaps, simple grids with 16x16 pixels per tile, and I'm using cellular automata combined with some other methods to generate these tilemaps. I can generate fairly large tilemaps, but It's problematic to go too big and it seems very ineffiecent. To be able to have a big world I decided it was probably smart to divide everything up in smaller seamlessly connected tilemaps, but I'm really unsure how to actually deal with such a large map. Since I'm planning on having maybe 40x40 tiles per area, and 100x100 areas for the whole world that will add up to a ridiculous amount of tiles in total. What is the best way to generate such a huge area and still letting it all flow together nicely and naturally? I'm currently generating a mini map of a world to get the general layout of the world. (100x100 pixels) And I could generate all of the areas seperately based on this layout, but i'm not sure it would allow me to create larger open and natural environments. I see 3 different options:

1) Generating the whole map at once as the game is started, everything in one go, this including all the different regions like forests, lakes, mountains etc.

2) Breaking the areas down by the type of region, for example, getting the bounds of a forest area (which spans over several tilemaps) and then generating it with more detail, and moving on to other regions after that

3) Generating the areas one by one as you enter them, meaning the world will only be fully generated once you explored it all.

I appreciate all replies a lot! It's more of a general question and I imagine there are a lot of ways to do these, so any suggestions are welcome! Maybe I have the wrong approach altogether? I'm very new to procedural map generation so I apologise if I come off as very inexperienced Thank you!

# Answer
I develop games as a hobby by myself and never actually talked or advised anyone about the details of game development before so my comment might be a bit off.

You say you use cellular automata to generate your map; I'm not sure but it sounds like every tile is reliant on one of the tiles before it to be generated, right? If that is the case you should definitely switch to a noise function such as simplex or Perlin, with these you can compute any coordinate irrespective of any other tiles on your map. The way I do it is I only calculate the tiles around visible and a bit outside the players view and I save the results in a cache so that the program doesn't have to keep recalculating the same tiles. Of course you should also limit the size of your cache also, so that the game doesn't keep data from areas the user visited way back for too long.

I think this guide could be helpful for you: http://www.redblobgames.com/maps/terrain-from-noise/
> 3 votes

---
Tags: user-generated-content
---


title: Achievements system like in Starcraft2

text:
# Question
Title: Achievements system like in Starcraft2
I am playing Starcraft2 and I am fascinated of how it is engineered. So lets say you played a 1v1 ranked game and you pumped 10 marines in the first 320 seconds. You'll get an achievement for that. I was wondering how is the achievements system designed underneath? Yes it analyzes the replay file which is frame based, but how? There are 1000 achievements now.

# Answer
Achievement systems are actually pretty simple.

They can be built in any number of ways, but they revolve around two things:

1. Statistics tracking
    * Every time a thing happens, a notification (event, a method call, or other notification type) is sent off to the statistics tracking object saying "this thing happened." e.g. When you build a marine, the statistics tracker adds 1 to the `numMarinesBuilt` value
    * Singleton or a static class is sufficient for a single player game, for multiplayer you'd need an instance per player
2. Statistics comparison
    * Then the altered statistic is compared against a threshold value of some kind, and if all checks pass, the achievement is awarded. e.g. `if(Achievements.marines320.isNotAwarded() && numMarinesBuilt > 10 && curGameTime < 320) { //award achievement }`

Both happen in the same method, usually. Some achievements like "win a game never having destroyed an outpost" have the logic split up: *destroying* an outpost sets a flag to true ("we did this thing at least once"), then when the game *ends* and the win logic is checked, the statistics comparison is made to check to see that that flag is still false ("if we did *not* do the thing: achievement").

Receiving the achievement would then fire off its own notificaiton to a central handler that would result in the popup saying "Yay you did Thing!" with a picture icon and some text on a GUI object background. If using SteamworksAPI (or similar) you'd also inform the API of the achievement as well.
> 3 votes

---
Tags: frame-buffer, achievements, starcraft-2, replays
---


# Question
Title: How to predict future position of an object(bullet sync)?
There is a multiplayer game and server sends to all clients a message when a shot happens, containing bullet position, bullet velocity and timestamp. By having timestamp, we can calculate the lag, let's say it's 100ms.

My game uses Box2D. How can I predict the real and current bullet position by having such data? I guess velocity might also change a little bit too.

# Answer
> 1 votes
`current_position = starting_position + ((lag_delay + time_elapsed ) * velocity)`

Where "time elapsed" is how long we've known about the bullet existence. Ostensibly this doesn't need to be stored, as when the bullet is created client-side, it is 0, and afterwards we update its position every frame update.

The lag delay is merely just an extra bit of deltaTime applied when the bullet is first spawned.

---
Tags: physics, box2d, projectile-physics, movement-prediction, extrapolation
---


title: 2d raycast collision problem

text:
# Question
Title: 2d raycast collision problem
I am currently making a 2d top down game in unity and have stumbled upon a problem with my raycast collision. I want my green player to stop moving when colliding with a wall, therefore i made my player object cast a ray in the direction it is moving. Its velocity is nullified when the distance to the collision point is equal to zero, or below. What seems to be the case is that the player object stops moving way to late and ends up overlapping the wall object. I tried to make an offset such that the player stopped a bit earlier, but it seems that the offset needs to differ depending on the side of the wall block. It even feels like the point at where the player stops is arbitrary and differs from time to time.

I would really like to know why this happens and what i can do to fix it. BTW, I would also really like to be able to change the players speed and still have it work.

Here are some pictures of my problem:

The code i use for the player:

```
using UnityEngine;
using System.Collections;

public class Player : MonoBehaviour {

    [SerializeField]
    private float speed;

    Rigidbody2D body;
    bool justChangedDir;
    Vector2 moveDir;

    void Start()
    {
        body = GetComponent<Rigidbody2D>();
    }

    void MoveDirection()
    {
        Vector2 input = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));

        if ((input.x != 0 && input.y == 0) || (input.x == 0 && input.y != 0))
            justChangedDir = false;

        if (moveDir.x != 0)
        {
            moveDir = new Vector2(input.x, 0);

            if (input.y != 0 && !justChangedDir)
            {
                moveDir = new Vector2(0, input.y);
                justChangedDir = true;
            }
        }

        else if (moveDir.y != 0)
        {
            moveDir = new Vector2(0, input.y);

            if (input.x != 0 && !justChangedDir)
            {
                moveDir = new Vector2(input.x, 0);
                justChangedDir = true;
            }
        }

        else
            moveDir = input;
    }

    void CheckCollision()
    {
        RaycastHit2D hit = new RaycastHit2D();

        if (moveDir.x != 0)
        {
            hit = Physics2D.Raycast(body.position, Vector2.right * moveDir.x, 1);

            Debug.DrawRay(body.position, Vector2.right * moveDir.x, Color.yellow);

        }

        else if (moveDir.y != 0)
        {
            hit = Physics2D.Raycast(body.position, Vector2.up * moveDir.y, 1);

            Debug.DrawRay(body.position, Vector2.up * moveDir.y, Color.yellow);
        }

        if (hit.collider != null && hit.distance <= 0.5 )
        {
            body.velocity = Vector2.zero;
        }
        else
        {
            body.velocity = moveDir * speed;
        }

    }

    // Update is called once per frame
    void Update()
    {
        MoveDirection();

        if (moveDir != Vector2.zero)
        {
            CheckCollision();
        }
        else
            body.velocity = Vector2.zero;
    }

}

```

Any help will be really appreciated :) Many thanks in advance!

Gusgus

# Answer
This is because your raycast is from the center of the player to a length equal to speed. You're discounting the *size* of the player in this calculation.

```
hit = Physics2D.Raycast(body.position, Vector2.right * moveDir.x + player_radius, 1);

```

Where `player_radius` is the size of your player. It would be best to make this either a reference to the game object's transform's scale, the game object's collider's size, or a constant property (collider size is best, if you're using one).
> 4 votes

---
Tags: unity, 2d, collision-detection, raycasting
---


# Question
Title: My point light shadows only really work if my point light is at the world origin (0,0,0)
When I move the light, the shadows will fall apart as if their occluders aren't occluding them in certain areas.

For example, in the following scene, I move a pointlight 400 units down the Z axis, I get a scene like this, where somehow occluded fragments are passing the shadow test:

The shadowmap texture appears fine to me. Since I'm working with a pointlight, I need a cubemap, so here are the relevant portions of its texture:

---

I'm fairly certain my issue has to be somewhere in one of my shaders.

My point light's shadowing logic subtracts the lights' position from the fragment's world position, takes the length of that vec3 and outputs that as the FragColor.

```
#version 330

in vec3 WorldPos; // aka ViewMatrix*ModelMatrix*Vertex

layout (location = 0) out float FragColor;

uniform vec3 LightPos;

void main()
{
    vec3 LightToVertex = WorldPos - LightPos;
    float LightToPixelDistance = length(LightToVertex);

    FragColor = LightToPixelDistance;
}

```

And then within the actual lighting logic, I do this to calculate a shadow factor (where 1.0 == full illumination, and 0.0 == full darkness)

```
uniform samplerCubeShadow ShadowMap;
in vec3 WorldPos;

float CalcShadowFactor()
{
    vec3 LightDirection = WorldPos - pointLight.position;
    float Distance = length(LightDirection);
    vec3 Direction = normalize(LightDirection);

    float Factor = 0.2;
    vec4 UVC = vec4(Direction, (Distance + EPSILON));
    Factor += texture(ShadowMap, UVC) +0.05;

    return Factor;
}

```

# Answer
> 1 votes
Byron's comment was right. I thought I needed to use the camera's view matrix (from the light's position), but alas it wasn't needed. Removing it solved the problem

---
Tags: opengl, shaders, shadows, shadow-mapping
---


# Question
Title: How to check if an GameObject exists in Unity2D? (Javascript)
Im making an AI that checks if the player exists or not. How do I check if a certain object exists and put it in a boolean variable?

# Answer
> 1 votes
try using GameObject.FindGameObjectsWithTag or GameObject.FindWithTag or by name (or namepath) GameObject.Find

```
bool playerexists = (GameObject.Find("player") != null)

```

# Answer
> 1 votes
Unity tutorials explicitly says that "Gameobject.Find()" is a bad way to do this. It is very resource intensive and is not necessary! Take a Look at Adam Buckner's tutorial on this subject, "communication between scripts and game objects". You can find the article here:

https://unity3d.com/learn/tutorials/modules/beginner/live-training-archive/communicating-between-components-gameobjects?playlist=17117

I know you may not be too concerned about effiency at this point, BUT! as you polish this, you will become more and more concerned about it, and this will be a good habit to learn now, instead of attempting to fix a bad habit later!

Hope this helps!!!

---
Tags: unity, java, 2d, unityscript, gameobject
---


# Question
Title: Unable to move mouse cursor while pressing keyboard button
I've a player to which I've attached character controller and two scripts - `Controller` and `MouseLooker` to control the player movements but when I try to move my mouse cursor while pressing keyboard key(s), my mouse cursor gets locked. When I release the keyboard keys(s) it starts working.

How should I fix this to get both keyboard and mouse to work at the same time?

# Answer
This looks like it is related to something in the UPDATE() method on your MouseLooker script.

The LockCursor() calls need some tweaking.

Is this happening with only 1 keyboard key, or several keyboard keys?

Also, you may get more insight into what is happening if you added some "print()" calls in your "UPDATE()" methods, which output the cursor lock state, and some other code based values to help you troubleshoot.
> 0 votes

---
Tags: unity, input
---


# Question
Title: Can this script be edited to create a "shotgun" type spread when firing? [Top down shooter]
I have this code and I'd like to add a shotgun to the game by slightly modifying the code. I've looked online for any example but everything I find is for FPS not a TDS.

```
void Shoot ()
{
    timer = 0f;

    gunAudio.Play ();

    gunLight.enabled = true;

    gunParticles.Stop ();
    gunParticles.Play ();

    gunLine.enabled = true;
    gunLine.SetPosition (0, transform.position);

    shootRay.origin = transform.position;
    shootRay.direction = transform.forward;

    if (Physics.Raycast (shootRay, out shootHit, range, shootableMask))
    {
        EnemyHealth enemyHealth = shootHit.collider.GetComponent <EnemyHealth> ();
        if(enemyHealth != null)
        {
            enemyHealth.TakeDamage (damagePerShot, shootHit.point);
        }
        gunLine.SetPosition (1, shootHit.point);
    }
    else
    {
        gunLine.SetPosition (1, shootRay.origin + shootRay.direction * range);
    }
}

```

I have a basic understanding of most of this code. I don't quite understand how shootRay.direction understands transform.forward means always the front of player. As DMGregory stated adding a variable of some sort that runs through a for loop firing multiple different angles (or simply different coordinates if making angle rays is over my head) is the route I first thought of but I cannot find a way to implement it. I'm having issues with understanding how to manipulate ray coordinates because they cannot be changed by floats which is the extent of my current knowledge of problem solving.

# Answer
> 1 votes
The "realistic" way to handle this is to just change the `shootRay.direction` vector.

```
for (var i = 0; i< pellets; i++){
    var offset = Random.insideUnitSphere * accuracy;
    shootRay.direction = transform.forward + offset;
    //then your raycast
}

```

`Random.insideUnitSphere` will give you a random point inside a unit sphere.

`accuracy` should be a small float value to lessen the effect of insideUnitSphere

When `transform.forward` is added to the offset it will change they x, y and z coordinate for the direction

The easiest way is simply to reduce the damage based on the distance away the target is.

edit: Didn't notice what you said about examples for FPS. Why do feel like handling it different than a FPS?

Edit 2: You can set `offset.y=0` to make sure there is no spread.

---
Tags: physics, shooter
---


# Question
Title: Should I store local forward/right/up vector or calculate when necessary?
I'm working on an object picking and translation/rotation/scale gizmos system in my engine where you select objects and perform transformations on them in a 3d editor-like fashion (e.g. Blender)

In my transform struct, I'm storing the position, rotation angle, rotation axis and a uniform scale value. When transforming my objects, I build the TRS matrix which forms my ModelToWorld matrix. All good.

Now I want to add the notion of local vs world translation. i.e. you select an object, and you can either move it along its local x axis, or the global x axis.

The global movement is easy I just add directly to my position vector. But for the local one, I have to build a local forward/right/up vector. e.g.

```
v3 GlobalUp = V3(0, 1, 0);
v3 LocalUp = m4_Rotate(Rotation->Angle, Rotation->Axis) * GlobalUp;

```

And then I translate my position by that amount:

```
Selection->Transform.Position += LocalUp;

```

I'm kind of torn whether I should store these local up/forward/right vectors in my transform (which means I have to calculate them once every frame in my update function, but every use of them after that point needs no calculation) or only when needed (no need to calculate every frame, but I have to call a function to do the calculation every time I need one, I could still keep the value in a local variable in my usage area if I'm using it more than once)

I'm not sure what approach to go with but I'm leaning towards calculating them as needed.

Are there any other pros/cons to each approach? or is this one of those things where there's no 'absolute right' way to do it?

Any advice is appreciated!

# Answer
> 2 votes
I'm incline to suggest there is no 'right way' to do this but I think there are 'better ways' and some considerations to make when implementing your own system.

**Should an object's transform be authoritatively a world-space matrix, or a local-space matrix?**

If you are going to have deep, complex hierarchies, storing a local-to-parent transform (or separate components) as the authority is preferable. The alternative requires transforming a child's world matrix by the inverse of the parent, which is a costly operation and can introduce additional, unnecessary floating point errors. Instead you can calculate the world matrix on demand, concatenating with the parent's world matrix as needed. Local space transformations are then simple enough, and world-space transformations are performed relative to the parent's matrix.

**Should an object's transform be a matrix, or the components of a matrix?**

It certainly is *cheaper* to have a matrix, but I would argue that keeping the components separate make more sense here because, again, once a matrix is built the components become effected by floating point errors, as well as interference with one another. Furthermore, when manipulating just a transform, you have to continually renormalize the matrix because the accumulated floating point error will denormalize your matrix, and it will stop being orthogonal. While you *can* extract scale from the matrices, it is easier to just keep it distinct. I didn't do that in my editor, and sometimes it frustrates me to no end. I extract the Translation, Rotation and Scale (TRS) components when the object is selected, and then manipulate those to build the matrix. Instead I think I would keep the data separate if I did it again.

**How to keep it all in sync?**

So I think the format of your matrix should look something like this:

```
class Transform
{
    // Private members behind accessors
    Matrix worldCache;
    Matrix localToParentCache;
    Vector3 Translation; // Position in local X,Y,Z axis
    Vector3 Scale; // Scale in local X,Y,Z axis
    Quaternion Rotation; // rotation axis & magnitude
    enum DirtyFlags
    {
        WorldDirty = ( 1 << 0 ),
        LocalDirty = ( 1 << 1 ),
    }
    DirtyFlags dirtyFlags = WorldDirty | LocalDirty;
}

```

Encapsulate the data into a class, and hide the worldCache & localToParentCache behind accessors. Use setters on the scale, position & rotation to set the dirty flags, Whenever the position, rotation or scale change, to invalidate the caches. When a parent moves, invalidate the worldCache (but not the localToParentCache). On access rebuild the matrices as required.

Here are some sample methods:

```
class Transform
{
    // setters on the values:
    public Vector3 Translation
    {
        get { return Translation; }
        set { dirtyFlags |= ( WorldDirty | LocalDirty ); MarkChildrenAsDirty(); Translation = value };
    }

    void MarkChildrenAsDirty()
    {
        // when a node moves, all of it's children's world matrices are invalidated
        // so they need to be marked.
        for ( all children )
        {
            child.dirtyFlags |= WorldDirty;
            child.MarkChildrenAsDirty(); // recurse into children's children
        }
    }

    // now the matrices
    public Matrix World
    {
        get { if ( dirtyFlags & WorldDirty ) RecalculateWorldMatrix(); return worldCache; }
    }

    public Matrix LocalToParent
    {
        get { if ( dirtyFlags & LocalDirty ) RecalculateLocalMatrix(); return localToParentCacheDirty; }
    }

    // And the recalculation:
    private void RecalculateWorldMatrix()
    {
        worldCache = Parent.World * LocalToParent; // depends on your order
        ClearDirty( WorldMatrixDirty );
    }

    private void RecalculateLocalMatrix()
    {
        // build matrix using whatever code you would use
        localToParentCache.MakeMatrix( Translation, Scale, Rotation );

        ClearDirty( LocalMatrixDirty );

        // make world matrix dirty now
        MarkDirty( WorldMatrixDirty );

        // And the children
        MarkChildrenAsDirty();
    }
}

```

An important consideration here is that when an object has it's world matrix affected, we need to broadcast that dirty state on to the children, since their cached world matrix is invalid - the parent has moved. When any child has it's world matrix requested, it will rebuild the hierarchy from that point up to the first non-dirty world matrix.

This requires the manipulators/gizmos to understand this kind of transform complexity, instead of just performing transforms agains the matrix, but I think it is more concise in and editor. Obviously in a game, at runtime you wouldn't have all of these things if you were not editing the object.

---
Tags: rotation, vector, transformation, spaces
---


# Question
Title: What does EventSystem.currentSelectedGameObject consider the current object to be?
I've been working with UI in my project as of late and I can't figure out what Unity's event system is supposed to return for `currentSelectedGameObject`.

```
if (EventSystem.current.currentSelectedGameObject != null)
{
    Debug.Log(EventSystem.current.currentSelectedGameObject.name);
}

```

With the code above I figured that it should return something when I'm moving the mouse across the various UI elements. Unity's documentation appears to be poor on this function stating:

> The GameObject currently considered active by the `EventSystem`.

maybe I'm just being stupid but does anyone know what triggers `currentSelectedGameObject`?

# Answer
The `currentSelectedGameObject` is not updated by simple mouse-over, as far as I'm aware.

Instead, it's more analogous to moving through an interface with tab. In the Unity UI system, you can move around between buttons with the keyboard. I think you'll find that behaves as expected.

If you want to know what UI object the mouse is over, I believe you'll need to implement that manually.

Quoting from: (4.6 UI) How to detect mouse over on button on answers.unity3d.com.

> * Add an event trigger component to your button game object.
> * Click on `Add New` button and select `PointerEnter`.
> * Now click on `+` button to add a new item to the list of event of type `PointerEnter(BaseEventData)`.
> * Select the object containing your script.
> * Now select the function to be called from the list of functions.
> 5 votes

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


# Question
Title: What state is stored in an OpenGL Vertex Array Object (VAO) and how do I use the VAO correctly?
I was wondering what state is stored in an OpenGL VAO. I've understood that a VAO contains state related to the vertex specifications of buffered vertices (what attributes are in the buffers, and what buffers are bound, ... ). To better understand the correct usage of VAO's, I'd like to know exactly what state they hold.

---

# How I assume VAO's should be used

From simple examples, I've understood that correct usage of VAO's is as follows:

**Setup**

```
Generate VAO
BindVAO
---- Specify vertex attributes
---- Generate VBO's
---- BindVBO's
-------- Buffer vertex data in VBO's
---- Unbind VBO's
Unbind VAO

```

**Rendering**

```
Bind VAO
---- Draw
Unbind VAO

```

From this, I assume that at least the **vertex buffer bindings** and the **vertex attribute specifications** are stored in the VAO. I'm unsure however how this usage pattern extends to situations where (multiple) textures and (multiple) shader programs come into play. Is the **active shader program** stored in the VAO? And are the **texture bindings** (with their **sampling/ wrapping settings**) stored in the VAO as well? Ditto for **uniforms**?

---

Therefore, my questions are:

* What exact **state** is stored in an **OpenGL VAO**? (VBO bindings, attribute specifications, active shader program, texture bindings, texture sampling/wrapping settings, uniforms ... ?)
* How do I **correctly use VAO's** in a more **complex rendering setup** where (multiple) textures with associated sampling/wrapping settings, (multiple) shader programs and uniforms are involved?

# Answer
VAO stores data about vertex attribute locations. (And some other data related to them.)
`"VBO bindings, active shader program, texture bindings, texture sampling/wrapping settings, uniforms"` are completely unrelated to it.

You may ask why it doesn't remember VBO binding. Because you don't need to bind VBO to draw something, you only need to bind it when creating VAO: When you call `glVertexAttribPointer(...)`, VAO remembers what VBO is currently bound. And VAO will take attributes from these VBOs when you draw it, even if these VBOs are not bound currently.

---

Also, VAOs and VBOs must be used slighty differently:

This will not work

```
Generate VAO
BindVAO
---- Specify vertex attributes
---- Generate VBO's
---- BindVBO's
-------- Buffer vertex data in VBO's
---- Unbind VBO's
Unbind VAO

```

because you need to bind VBO to specify attribute locations.

So, you should do it like this:

```
Generate VAO
BindVAO
Generate VBO's
BindVBO's
Specify vertex attributes

```

You can change VBO's data whenever you want, but you must bind it before.

And drawing should look like this:

```
Bind VAO
Draw

```

As you may noticed, I removed `unbind` calls from your lists. They are almost completely useless and they will slightly slow down your program, so I see no reason to call them.
> 25 votes

# Answer
Here is a simple but effective explanation , basically a buffer object has information which can be interpreted as just simply bits of raw data, which on its own mean nothing, so it is PURELY the data which can be looked at any way really

```
i.e float vbo[]={1.0,2.0,34.0...}

```

and the way OpenGL was designed to work is that you must DEFINE what the data that your passing to the various shaders is going to look like to the shaders

in that you also have to define how it will read that data, what format it is in, and what to do with it and how it will be used and for what,all of this information is stored in the VAO

for example you can declare data that is stored in an array like this `float vbo = {11.0,2.0,3.0,4.0}`

what is required next at this point is how to interpret that data from the VBO in the VAO, and what that means is as follows

the VAO can be set to read 2 floats per vertex (which would make it 2 vectors with two dimensions x,y) or you can tell the vao to interpret it as 1 vector with 4 dimensions i.e x,y,z,w etc

but also other attributes of that data is defined and stored in the VAO such as data format(despite that you declared an array of float you can tell the shader to read it in as an integer, with of course the system converting the raw data in the process from float to integer and has its own set of rules what to do in such circumstances)

So basically the VBO is the data, and the VAO stores how to interpret that data, because the shaders and OpenGL server is designed to be very nosey and needs to know everything before it decides how to process it and what to do with it and where to put it

of course its not actually nosey, its actually looking to be most efficient because it needs to store that data on the graphics server memory so that it gets the most efficient and quickest processing(unless it decides that it doesn't need to do this if the data is not to be processed in such a way and used for some other information that isnt accessed often) , and hence why the details of what to do with the data and how to process it is required to be stored in the VAO , so the VAO is like a header and the VBO is like the pure raw data that the header uses and defines(in this case passes to the shader vertex attributes) with the exception that the VBO is not limited only to be used by one VAO, it can be used and reused and bound to many VAO's for example:

what you can do is you can bind one buffer object to VAO1 and also(separately) bind the same buffer object to VAO2 with each interpreting it differently so that if your shader where to process the data, depending on which VAO is the one that is bound it would process the same raw data differently to the frambuffer(drawing pixels to window) resulting in different display of the same data which would be based upon how you defined its use in the VAO
> 5 votes

# Answer
It only stores the vertex binding and the index buffer binding

That is all the parameters of `glVertexAttribPointer` plus the buffer bound to Vertex\_Array\_buffer at the time of the call to `glVertexAttribPointer` and the bound Element\_Array\_buffer.

Uniforms are part of the current program.

Everything else is global state.

In doubt you can check the state tables in the spec of the version you are using.
> 4 votes

---
Tags: opengl, vao
---


# Question
Title: Cross-platform C++/OpenGL ES development (iOS/Android)
I already have reasonable experience with C++ and OpenGL, and I have recently decided to try out mobile game development. After successfully creating a simple OpenGL ES Android app using Java, I researched ways to target both Android and iOS with as little rewriting code as possible. I tried using Visual Studio 2015's proudly-boasted cross-platform app development tools, but found them to be too new and therefore extremely under-documented. I could build the template projects the program gave to me, but I couldn't figure out how, given these templates, I might add assets into the game or handle touch screen input.

I have an unfortunately specific desire, too specific to find with Google. I want to make an OpenGL ES game using C++, with thin platform-specific wrappers for Android and iOS. People have asked similar questions to me (though not exactly the same), and more than one person responding has stated that what I want to do is not only possible, but relatively easy, since I don't have to worry about UI.

I tried this tutorial, but it's almost three years old and therefore probably designed for older technology, and as a result I ran into various unaccounted-for bugs. As of right now, though, that tutorial is the closest thing to what I want that I've found. Everything else is either Android-only, or recommending that I pay hundreds of dollars a year to use the Marmalade SDK. At times I feel like just writing the code twice, once in Java and once in Objective-C, but I am kept motivated by the knowledge that this solution is possible, but for some reason, not covered anywhere in any modern detail.

To summarise, I want to make an OpenGL ES game for iOS and Android, with a single C++ codebase wrapped in small amounts of platform-specific code. However, despite the fact that several people have recommended this approach, no one can tell me how to do it. Can somebody tell me if it's actually possible, and if so, what I can do or where I can go to learn how?

# Answer
> 6 votes
You may find my answer to a similar question here to be helpful.

You may also find it helpful to look into the source code of other solutions. The Godot Engine for example is a cross platform open source game engine so you never need to pay anything.

As I mention in my other answer you don't need to (and likely can't) rely on one IDE to do the work for you. CMake, Scons, and many other build tools can help with the cross compilation/build process across platforms and IDEs.

Godot Engine, for example, uses Scons and the LLVM project (aka the compiler framework used by clang the C/C++/Objective-C compiler) uses CMake.

A popular approach for games is to build an engine in C/C++ and, as you mention, abstract away platform specifics. When it comes to iOS and Android this is the life cycle management logic that interfaces with the OS. If you wanted to go the extra mile and utilize Emscripten to also compile to asm.js and realize near native speed in the browser, you are doing something similar with abstracting away the main loop behind what amounts to requestAnimationFrame calls.

Emscripten recommends the use of SDL to make the porting process easier as it can help handle abstracting the platform specifics, but there is nothing stopping you from doing this yourself (other then loads of research, debugging, etc.).

If you are really, really crazy you can do what I am doing and write your own language utilizing the power of LLVM to compile to native C ABI or even JIT on supported platforms.

The point is that yes it is indeed possible, but some roads are more complicated/time consuming then others.

***Note:*** You will likely need to use Mac OSX via a Mac, VM, or Hackintosh with XCode to compile to iOS. This is one of many reasons I find a Macbook Pro to be a great candidate for a development system.

***Note2:*** It is worth mentioning that many cross platform engines today utilize scripting languages for game specific logic. Unity doesn't even let you near their source code for example (although you can write native plugins). This can help speed up development cycles as well as keeping porting to a minimum as the scripting languages are fairly platform agnostic (especially interpreted languages running in a VM). The goal for my language is to allow both JIT (mostly for development time savings) and static compilation.

***Note3:*** If you haven't found this out already. If you do not utilize SDL or some other solution that abstracts platform specifics, you will need to utilize each platform's specific C/C++ interfacing features. With iOS this is pretty simple in XCode as the compiler (clang as mentioned above) supports C/C++ already. With Android you need to utilize the NDK and marshall calls between Java and C/C++.

---
Tags: c++, android, ios, mobile, cross-platform
---


# Question
Title: Network Communication For Multi-Player Turn-Based Game
I'm attempting to develop a multi-platform turn-based game that \[I suspect\] follows the general client-server pattern. For this question, let's assume I only care about communications inside of a "battle" right now.

Here are the relevant mechanics of a battle: there are some number of "soldiers" in each battle. Each soldier is under the control of a player and a player may be in control of multiple soldiers in a given battle. Each turn only 1 soldier makes an action, the server will contain logic to determine which soldier that is. There are no time limits on turns. The player in control of that soldier select an action for that soldier which is sent to the server. The server will then determine the result of that action and send that information to every client.

This diagram can hopefully show my intended flow of information:

With each communication to client I was expecting to send a json of a ClientBattle object that holds all the data a client needs. On communications to the server, I was expecting to send a json of an Action object that contains all the info the server needs to calculate the outcome and advance the battle.

Unfortunately, I'm not quite sure how I would go about implementing this.

An approach that I would know how to implement that mimics this behavior would be to have each client HTTP GET a turn number from the server at a regular interval of ~3 seconds. If the turn number matches the client's data it does nothing until asking the server again in 3 seconds. If the number doesn't match, then the client HTTP GETs new battle data from the server and uses that to update its display. On client to server communication I'd send a HTTP POST request.

How would I clean this up - or - how could I implement it as in the diagram?

# Answer
Using simple AJAX polling I think you've come up with the best solution, with the exception that a client doesn't need to be in a polling state while it is their turn. This reduces some of the polling. I also think you can reduce the frequency of polling to 5 or even 10 seconds since someone waiting for their turn won't know when exactly the other player finished their turn. You could also perform an incremental system where you poll ever 3 seconds until 15 seconds have passed, and then slow down, under the assumption that you are not in a rapid pace state of the game, so neither player will care for or require really responsive turn-taking.

Otherwise you want to investigate some kind of push notification. Here are some links to other questions:

https://stackoverflow.com/questions/16122911/efficient-reloading-data-pushing-data-from-server-to-client

https://stackoverflow.com/questions/5753674/php-best-way-to-push-data-from-server-to-clients

And some other information:

http://www.abrandao.com/2013/06/websockets-html5-php/
> 0 votes

---
Tags: networking, client-server, turn-based, http
---


# Question
Title: Bullet Physics Collision is Not Detected
I have created two `btConvexTriangleMeshShape` objects. One is a cube of size
`(0.1 x 0.1 x 0.1)`, and the other is is a plane of size `(1.0, 0.1, 1.0)`. The plane is static, and the cube is dynamic, and should fall onto the plane under gravity.

Now, if I set the world position of the plane to be at `(0, 0, 0)`, and the cube to be at `(0, 0.3, 0)`, then the cube falls onto the plane and rests there, as would be expected. However, I am getting some strange behaviour when I change the position of the plane, even slightly.

For example, if I set the world position of the plane to be at `(-0.1, 0, -0.1)`, with the cube still at `(0, 0.3, 0)`, then the cube falls right through the plane, and there is no collision. But the plane is still directly beneath the cube as it falls, and so a collision should be detected. In fact, if I set the plane to be positioned at anything other than `(0, 0, 0)`, then there is no collision.

The plane's position is set in the code:

```
btDefaultMotionState* plane_start_motion_state = new btDefaultMotionState(
    btTransform(
        btQuaternion(0, 0, 0, 1),
        btVector3(0, 0, 0)
    )
);

```

And no collision is detected when I use:

```
btDefaultMotionState* plane_start_motion_state = new btDefaultMotionState(
    btTransform(
        btQuaternion(0, 0, 0, 1),
        btVector3(dx, 0, dz)
    )
);

```

for even small values of `dx` and `dz`, other than zero. Any ideas on what is causing this? The minimum code to repeat this is below:

```
#include <iostream>

#include <Eigen/Eigen>

#include "btBulletDynamicsCommon.h"
#include "BulletCollision/Gimpact/btGImpactShape.h"
#include "BulletCollision/Gimpact/btGImpactCollisionAlgorithm.h"

int main(int argc, char** argv)
{
    // Set up Bullet

    btDefaultCollisionConfiguration* collision_configuration = new btDefaultCollisionConfiguration();
    btCollisionDispatcher* dispatcher = new btCollisionDispatcher(collision_configuration);
    btBroadphaseInterface* broadphase = new btDbvtBroadphase();
    btSequentialImpulseConstraintSolver* solver = new btSequentialImpulseConstraintSolver;
    btDiscreteDynamicsWorld* dynamics_world = new btDiscreteDynamicsWorld(dispatcher, broadphase, solver, collision_configuration);
    dynamics_world->setGravity(btVector3(0, -9.81, 0));

    // Make the plane

    float plane_dx = 1.0;
    float plane_dy = 0.1;
    float plane_dz = 1.0;

    int plane_num_vertices = 8;
    int plane_num_triangles = 12;
    int plane_num_indices = plane_num_triangles * 3;

    std::vector<Eigen::Vector3f> plane_vertex_positions;
    std::vector<int> plane_vertex_indices;

    plane_vertex_positions.resize(plane_num_vertices);

    plane_vertex_positions[0] << 0, 0, 0;
    plane_vertex_positions[1] << 0, -plane_dy, 0;
    plane_vertex_positions[2] << 0, -plane_dy, plane_dz;
    plane_vertex_positions[3] << 0, 0, plane_dz;
    plane_vertex_positions[4] << plane_dx, 0, 0;
    plane_vertex_positions[5] << plane_dx, -plane_dy, 0;
    plane_vertex_positions[6] << plane_dx, -plane_dy, plane_dz;
    plane_vertex_positions[7] << plane_dx, 0, plane_dz;

    plane_vertex_indices.resize(plane_num_indices);

    plane_vertex_indices[0] = 0;
    plane_vertex_indices[1] = 3;
    plane_vertex_indices[2] = 2;
    plane_vertex_indices[3] = 2;
    plane_vertex_indices[4] = 1;
    plane_vertex_indices[5] = 0;
    plane_vertex_indices[6] = 4;
    plane_vertex_indices[7] = 0;
    plane_vertex_indices[8] = 1;
    plane_vertex_indices[9] = 1;
    plane_vertex_indices[10] = 5;
    plane_vertex_indices[11] = 4;
    plane_vertex_indices[12] = 7;
    plane_vertex_indices[13] = 4;
    plane_vertex_indices[14] = 5;
    plane_vertex_indices[15] = 5;
    plane_vertex_indices[16] = 6;
    plane_vertex_indices[17] = 7;
    plane_vertex_indices[18] = 3;
    plane_vertex_indices[19] = 7;
    plane_vertex_indices[20] = 6;
    plane_vertex_indices[21] = 6;
    plane_vertex_indices[22] = 2;
    plane_vertex_indices[23] = 3;
    plane_vertex_indices[24] = 2;
    plane_vertex_indices[25] = 6;
    plane_vertex_indices[26] = 5;
    plane_vertex_indices[27] = 5;
    plane_vertex_indices[28] = 1;
    plane_vertex_indices[29] = 2;
    plane_vertex_indices[30] = 0;
    plane_vertex_indices[31] = 4;
    plane_vertex_indices[32] = 7;
    plane_vertex_indices[33] = 7;
    plane_vertex_indices[34] = 3;
    plane_vertex_indices[35] = 0;

    btTriangleIndexVertexArray* plane_mesh = new btTriangleIndexVertexArray(plane_num_triangles, plane_vertex_indices.data(), 0, plane_num_vertices, (btScalar*)plane_vertex_positions.data(), 0);
    btConvexTriangleMeshShape* plane_shape = new btConvexTriangleMeshShape(plane_mesh);
    plane_shape->setLocalScaling(btVector3(1., 1., 1.));
    plane_shape->setMargin(0.04f);
    btVector3 plane_inertia(0, 0, 0);
    btScalar plane_mass(0.0f);
    plane_shape->calculateLocalInertia(plane_mass, plane_inertia);
    btDefaultMotionState* plane_start_motion_state = new btDefaultMotionState(btTransform(btQuaternion(0, 0, 0, 1), btVector3(0, 0, 0)));
    btRigidBody* plane = new btRigidBody(plane_mass, plane_start_motion_state, plane_shape, plane_inertia);
    plane->setFriction(0.5);
    plane->setRestitution(0.5);
    dynamics_world->addRigidBody(plane);

    // Make the Cube

    float cube_dx = 0.1;
    float cube_dy = 0.1;
    float cube_dz = 0.1;

    int cube_num_vertices = 8;
    int cube_num_triangles = 12;
    int cube_num_indices = cube_num_triangles * 3;

    std::vector<Eigen::Vector3f> cube_vertex_positions;
    std::vector<int> cube_vertex_indices;

    cube_vertex_positions.resize(cube_num_vertices);

    cube_vertex_positions[0] << 0, 0, 0;
    cube_vertex_positions[1] << 0, cube_dy, 0;
    cube_vertex_positions[2] << 0, cube_dy, cube_dz;
    cube_vertex_positions[3] << 0, 0, cube_dz;
    cube_vertex_positions[4] << cube_dx, 0, 0;
    cube_vertex_positions[5] << cube_dx, cube_dy, 0;
    cube_vertex_positions[6] << cube_dx, cube_dy, cube_dz;
    cube_vertex_positions[7] << cube_dx, 0, cube_dz;

    cube_vertex_indices.resize(cube_num_indices);

    cube_vertex_indices[0] = 0;
    cube_vertex_indices[1] = 3;
    cube_vertex_indices[2] = 2;
    cube_vertex_indices[3] = 2;
    cube_vertex_indices[4] = 1;
    cube_vertex_indices[5] = 0;
    cube_vertex_indices[6] = 4;
    cube_vertex_indices[7] = 0;
    cube_vertex_indices[8] = 1;
    cube_vertex_indices[9] = 1;
    cube_vertex_indices[10] = 5;
    cube_vertex_indices[11] = 4;
    cube_vertex_indices[12] = 7;
    cube_vertex_indices[13] = 4;
    cube_vertex_indices[14] = 5;
    cube_vertex_indices[15] = 5;
    cube_vertex_indices[16] = 6;
    cube_vertex_indices[17] = 7;
    cube_vertex_indices[18] = 3;
    cube_vertex_indices[19] = 7;
    cube_vertex_indices[20] = 6;
    cube_vertex_indices[21] = 6;
    cube_vertex_indices[22] = 2;
    cube_vertex_indices[23] = 3;
    cube_vertex_indices[24] = 2;
    cube_vertex_indices[25] = 6;
    cube_vertex_indices[26] = 5;
    cube_vertex_indices[27] = 5;
    cube_vertex_indices[28] = 1;
    cube_vertex_indices[29] = 2;
    cube_vertex_indices[30] = 0;
    cube_vertex_indices[31] = 4;
    cube_vertex_indices[32] = 7;
    cube_vertex_indices[33] = 7;
    cube_vertex_indices[34] = 3;
    cube_vertex_indices[35] = 0;

    btTriangleIndexVertexArray* cube_mesh = new btTriangleIndexVertexArray(cube_num_triangles, cube_vertex_indices.data(), 0, cube_num_vertices, (btScalar*)cube_vertex_positions.data(), 0);
    btConvexTriangleMeshShape* cube_shape = new btConvexTriangleMeshShape(cube_mesh);
    cube_shape->setLocalScaling(btVector3(1., 1., 1.));
    cube_shape->setMargin(0.04f);
    btVector3 cube_inertia(0, 0, 0);
    btScalar cube_mass(1.0f);
    cube_shape->calculateLocalInertia(cube_mass, cube_inertia);
    btDefaultMotionState* cube_start_motion_state = new btDefaultMotionState(btTransform(btQuaternion(0, 0, 0, 1), btVector3(0, 3, 0)));
    btRigidBody* cube = new btRigidBody(cube_mass, cube_start_motion_state, cube_shape, cube_inertia);
    cube->setFriction(0.5);
    cube->setRestitution(0.5);
    dynamics_world->addRigidBody(cube);

    float t = 0.00001f;

    for (int i = 0; i < 10000000; i++)
    {
        dynamics_world->stepSimulation(t, 10, t / 10.0f);
        btTransform cube_transform;
        cube->getMotionState()->getWorldTransform(cube_transform);
        std::cout << "Cube position = " << cube_transform.getOrigin().getY() << std::endl;
    }
}

```

# Answer
Using btConvexTriangleMeshShape as a dynamic collision shape isn't recommended. I would use a cube and a plane using the classes btBoxShape and btStaticPlaneShape respectively. They have distinct properties (boxes are solids, planes are one sided) that give better collision response. Colliding two triangle meshes together is unlikely to be supported well by Bullet.

Furthermore, btConvexTriangleMeshShape is for convex triangle hulls. A plane is not a convex shape.

You can read the author's response here: http://www.bulletphysics.org/Bullet/phpBB3/viewtopic.php?f=9&t=2927

> Mesh versus mesh is not implemented for btBvhTriangleMeshShape, because btBvhTriangleMeshShape is supposed to be used only for 'static' world geometry without collision detection between static versus static.

While it's a btBvhTriangleMeshShape I expect the same (unsupported) results with btConvexTriangleMeshShape because the underlying colliders are very similar.
> 3 votes

---
Tags: c++, physics, bullet-physics
---


title: Event Handling in an ECS

text:
# Question
Title: Event Handling in an ECS
I apologize if this has been answered already. I've looked around here, and read a few blog posts, but none seem to fully answer my question.

I am writing an Entity Component System.

* `Entity` is a store for Components, and is the central GameObject.
* `Component` is just a POD struct that describes some attribute (Health, Mana, etc.)
* `System` dictates the laws of the game world. Systems describe how an `Entity` will behave based on the `Components` that entity has, and the data stored within the `Component`. Additionally, a `System` can interact with other `Systems` using Events.

A pretty straight-forward and common approach. Now, the issue I am having is when an Event should interact with an `Entity`. For example, a `DieOnCollision` event for some Entities, or a `HealOnUse` event for others.

At first, I thought about just making a bunch of `Systems` for every type of event. An `Entity` would subscribe to these Systems, just like other Systems, except their `Update` function would do nothing. Instead, they only operated once per frame when passed an `Event` from the `EventQueue`.

I don't like this approach, because it is putting the `System` in charge of specific Entities, rather than operating on a collection of Entities.

Another approach I thought of was just creating a Component for each event, each of which holds a function pointer. When an event happens, such as `ExplosionEvent`, a list of entities in the area is given to the `EventHandler`, which then checks for the `OnExplosionEvent` component and calls the corresponding function (or maybe queues it up so all the functions can be processed in order).

I'm not too fond of this approach either, because it puts behavior into a component and it puts the EventHandler in charge of telling the Entities. Of course, I could probably just have the EventHandler pass the Event to GameWorld which then passes it to the Entities who have the needed components, but it still puts behavior into a component, which I want to avoid.

One last idea that just came to me would be to give the Entity a map of events it can listen for, something like `std::map<EventID, FunctionPointer>`. The entities could then be notified of Events during event handling, and their functions could be queued up. I do like this approach, but I am curious if there are any other suggested ways to handle Events pertaining to an `Entity` rather than a `System`.

# Answer
The `DieOnCollision` event couples behavior to an event. This causes tight coupling and could be why you're having trouble deciding how to handle these use cases. Instead I would concentrate on the fact you want to perform some behavior when a collision occurs, therefore it makes logical sense to expose some way to know when a collision has happened.

Since collision data is often useful to numerous logic systems, your `CollisionSystem` detects collisions, resolves them, and stores the resolved data in some queriable list.

Then there is any number of logic systems that store a list of entities that contain a specific marker component and use the `CollisionSystem`'s resolved data to determine whether entities with the special marker component has a collision and perform specific behavior.
> 3 votes

---
Tags: c++, entity-system, events
---


title: Configurable Joint, linear limit range

text:
# Question
Title: Configurable Joint, linear limit range
I am working on a physics driven pressable button, but I cannot seem to tackle the minimum and maximum limits.

This is the *rig* I have set up for the button (as it looks when pressed down).
2D view:

3D view:

The idea is that the box collider is a trigger and the button (cylinder, mesh collider) is a rigidbody with configurable joint, locked and limited on a single axis. I am using configurable joint, as that's the only one that supports basic, linear restrictions.

I have set up the configurable joint to restrict motion on a single axis, but the joint only allows single dimensional limit, that is applied to both directions. Screen capture of relevant configuration:

Basically, the opened `Linear Limit` section is the last property that has been changed for the joint - anything else are defaults and irrelevant (at least I haven't found my solution in the properties below, mostly angular stuff).

The limit of `0.2` units work, and the button can be pressed - it only gets *pressed* until those `0.2` units and thats the expected behaviour.
The unexpected is that sometimes the angle at which I hit the button, adds force to the button outwards from the box, and it moves `0.2` away from it, ending up like this:

Obviously, the specified limit of `0.2` units constrain the movement in both directions from the anchor, actually resulting in the range of `-0.2` to `0.2` (relative to anchor).

How, and is it even possible, to restrict the movement only in a single direction relative to anchor?

# Answer
You are correct about the fact that the limit isn't a min-max limit, but rather constraints in both directions. So if your goal is to limit your movement range to `0.2` units, your limit has to be set to `0.1` (`-0.1 - 0.1`).

For this to work correctly, your initial "button" position has to be centered between the desired min- and max-position.

You can then add an initial force to move the button to its max position or add a `Constant Force` Component to the button which will push the button outwards. The latter will have the nice effect that the button will move back out once pressed.
> 2 votes

---
Tags: unity, physics, 3d, joints
---


# Question
Title: AS3 .hitTestObject() not working with Tween function
(This was originally in an other senction but many told me to ask here, hopefully someone can answer this) I am having a major problem in my new browser app.

Okay so I made game where different cubes (squares) spawn at the top of the screen and I use the Tween class to make them go down the screen and then disappear.

However I want to detect a collision when a cube hits the player (that is also a flying cube).

I tried everything, truly everything but it does not seem to work. The problematic thing is that when I remove the "Tween" function it does detect collision with the hitTestObject method but when I add the "Tween" line collision won't be detected anymore.

The code looks like this:

```
    function enemiesTimer (e:TimerEvent):void {

newEnemy = new Enemy1();
  layer2.addChild(newEnemy);
  newEnemy.x = Math.random() * 700;
  newEnemy.y = 10;
  if (enemiesThere == 0)
  {
      enemiesThere = true;
      player.addEventListener(Event.ENTER_FRAME, collisionDetection)
  }

  var Tween1:Tween = new Tween(newEnemy, "y", null, newEnemy.y, newEnemy.y+distance, movingTime, true); }

```

The collision detection part:

```
private function collisionDetection (e:Event):void
  {

      if (player.hitTestObject(newEnemy))
      {
          trace("aaa");
      }

  }

```

\*Another weird thing is that the collision detection works only in the starting point, where the squares spawn but they aren't really there anymore so I don't quite get it.

I hope someone can answer this and maybe tell me how I can code this. Thanks in advance :)

\*I've tried out Tweener & TweenMax as well, the problem is always the same

# Answer
> 2 votes
I'm sure this has nothing to do with the Tweening library you're using (as indicated in the comments) but rather with how you reference your enemy in the `collisionDetection`. Depending on how your code is structured, `newEnemy` might not be set in that scope or be set to something you're not expecting.

I suggest you try this:

```
var newEnemy:MovieClip = new Enemy1();
layer2.addChild(newEnemy);
newEnemy.x = Math.random() * 700;
newEnemy.y = 10;
newEnemy.addEventListener(Event.ENTER_FRAME, collisionDetection);
var Tween1:Tween = new Tween(newEnemy, "y",
    null, newEnemy.y, newEnemy.y+distance, movingTime, true);

```

And in your `collisionDetection` method:

```
private function collisionDetection (e:Event):void
{
    // e.currentTarget is the enemey that emits the event
    if (e.currentTarget.hitTestObject(player)){
        trace("aaa");
    }
}

```

---
Tags: collision-detection, actionscript-3, debugging, actionscript
---


# Question
Title: Efficiency - Cubemap or Raytraced reflection?
I'm an amateur in 3D game development. The thing I want to know is shading related. For reflection purpose, which will be the efficient way? Either "Realtime render to Cubemap" or "Ray trace based" reflection? In which way I will get better frames per second and my gpu gets less tired? No matter which API I use (e.g. DirectX, GL, GL ES, Metal). And please note my question is out of any game engine.

# Answer
For games, there are two main reflection techniques.

You mentionned cube maps that is one of them. Cubemaps are good for reflections on arbitrary complex objects (sphere, teapots, ...). One other advantage is that they can also easely handle reflections on normal mapped objects.

In terms of computing poxer needs, you have to be aware that for each reflecting objects, you have to render 6 times you scenes to the cube map. There are several optimisation possible (not render cube map at each frame, use low def render surface, ...) but it remains costly.

The other way is to use "portal" related techniques that are very well described in this question.

The main advantage of this technique is that you will only require one more rendering pass. Another good point is that you can handle mirrors reflecting mirrors in a more complete and easy way than with cube maps (still it is not esay to handle such cases).

The main drawback is that you have to cull objects that are behind the reflective surface. Another drawback is that reflective surface must be a plane.

Raytracing in real time games is, afaik not used because it is too much resource hungry.
> 2 votes

# Answer
Cubemaps are much *much* faster than realtime (raytraced is realtime) although it does have its disadvantages.

https://en.wikipedia.org/wiki/Cube\_mapping#Advantages

> Cube mapping is preferred over other methods of environment mapping because of its relative simplicity. Also, cube mapping produces results that are similar to those obtained by ray tracing, but is much more computationally efficient – the moderate reduction in quality is compensated for by large gains in efficiency.
> 0 votes

---
Tags: cubemap, raytracing, reflection-rendering
---


# Question
Title: Mouse input position is being printed as Unity coordinates, but the actual coordinates used seem incorrect
This will be hard to explain, but I'll try to keep it short and simple:

I'm trying to set the position of a UI rectangle to the position of the mouse when clicked. When initialized, the position of the rectangle works fine (if, during Awake(), I initially set it so that x = 100 and y = 100 and then check the Rect Transform component during run time, Pos X and Pos Y are both set to 100 as intended). However, if I use the X and Y coordinates of Input.mousePosition, Pos X and Pos Y are given strange numbers that I have no clue where they're coming from.

I don't think they're pixel coordinates because the value for Pos X of the rectangle when my mouse clicks at the farthest left possible during run time is a value over 300 when it should be 0, and that value goes up as I progressively click rightwards.

Now here's the strange bit. When I try to use print() to print the mouse position x and y values that I use to set the rectangle's position, they're printed as intended (clicking the bottom left of the game area yields x = 0 and y = 0) yet the rectangle's position is far from close the values printed (rectangle's position is x = 337.5 and y = 192.5).

Can someone please explain why this happens, and how I can fix it? I suppose I can manually fix it by subtracting the new position values by 337.5 for x and 162.5, but it feels too brute-force-ish and there's bound to be consequences down the line.

Here is a screenshot to help clarify my issue: https://i.stack.imgur.com/6xebh.png

# Answer
> 2 votes
`localPosition` and `position` has no difference if your `GameObject` is not a child of any other `Gameobject`. But if your `GameObject` is a child of any other `GameObject` then `localPosition` represents the `position` with respect to its `parent`. For example, if your `parent` has position `10,10,10` and its child `localPosition` is `0,0,0` then your child object is actually at `10,10,10`(Globally). If you change your `GameObject's localPosition` to `10,0,0` then it will replace its position and add 10 units in X-axis of `parent`. Now the `localPosition` of child is `10,0,0` and `position` (aka Global Position) will become `20,10,10`.

In your case `rectangle` is a child and you are setting `localPosition` and giving it coordinates according to Global Position. That's the point.

I hope you got my point.

# Answer
> 2 votes
If you're using `localPosition`, the position will be relative to the GameObjects parent. You should use `position` instead, if you want to work with absolute coordinates.

---
Tags: unity
---


# Question
Title: good and free 3D modeling programs for implement into Unity
I'll make some objects that are not easy to make in Unity, but on my previous question Making holes in 3D objects (Unity) was there an answer that said that I can make it whit an other 3D modeling program.

So my question is now in witch 3D modeling program can I use for make 3D figures on a **simple** way, can be **implement into Unity**, **has CSG** modeling options and can I download and use **for free**? Here is a list:

* SketchUp
* ArchiCAD
* Blender
* FreeCAD
* IntelliCAD
* Maya
* Tinkercad
* ZBrush
* MoI3D
* Autodesk 123D
* Hexagon 2.5
* GtkRadiant
* Leadwerks Engine
* Roblox Studio - Since 2014
* UnrealEd
* Valve Hammer Editor
* ... for everything I've forgot.

Or is it better to use free and simple Unity plug-ins?

# Answer
One of the best Unity-specific level-editing tools is ProBuilder. Tools like Maya and Blender are generally my recommendation for 3D art, but you did ask for CSG.
> 3 votes

---
Tags: unity, game-design, 3d-modeling, csg
---


# Question
Title: How do you get the best rendering performance in a 2D Java Game?
I have seen a lot of tutorials, and they develop games with 2 different ways:

The first one is using a virtual image (BufferedImage) and filling it's pixels. And displaying virtual picture.

```
private BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
private int[] pixels = ((DataBufferInt) image.getRaster().getDataBuffer()).getData();
private int[] colors = new int[6 * 6 * 6];

```

Second one is using lots of real images. And displaying they.

```
SpriteSheet sheet = new SpriteSheet(ImageLoader.loadImage("/textures/sheet.png"));

    //PLAYER SPRITES PROVIDED BY: AddFact
    player = sheet.crop(width * 4, 0, width, height);

    dirt = sheet.crop(width, 0, width, height);
    grass = sheet.crop(width * 2, 0, width, height);
    stone = sheet.crop(width * 3, 0, width, height);
    tree = sheet.crop(0, 0, width, height);

```

**First Question:** Which one has the best performance ?

**Second Question:** How should we load maps? With images or with text files ? Which one is good to chose ?

Sorry for my english. I hope I can explain to you :) Thanks for helping, have a nice day ^^

# Answer
Both of these methods are utilizing software rendering, not using the GPU. If you were to use LWJGL or LibGDX or something else that uses the GPU for graphics rendering, it would be faster than both of these algorithms (or at least more efficient, most of the time). Anyways, let me discuss the two methods you asked about though:

In method 1 you are manually filling in the pixels of 1 image, then rendering it to the screen. In method 2 you are using a spritesheet, however in Java this way you are really just getting a bunch of individual BufferedImages by using the crop() method (I assume the crop() method really returns a subimage), so loading the image will be faster however you will be rendering multiple images to the screen. That being said, I can't entirely tell you which one is faster, because both utilize a form of software rendering, however I imagine method 2 would be faster, simply because of it's native implementation in Java, but it wouldn't be too much faster (I could be wrong). I can say, for sure, that using a library/framework that supports using the GPU (such as LWJGL, allowing you to use OpenGL) will be faster than these methods.

As for your second question, maps can be stored/loaded in many different ways. You can use an image to store tile data, maybe, or create (or use) a map editor and write it to a text file, then load it in. You may also want to consider another file to store entity data if you are using the image loading of a level.

I hope this helped a little bit, best of luck!
> 1 votes

# Answer
For images, you should almost always use a sprite sheet - switching between images is extra work for the GPU. You should load your sprite sheet and load VBOs (Vertex Buffer Objects) using that sprite sheet. LibGDX handles all of this for you and has amazing performance, so I suggest that you check it out.

Storage depends on a lot of things. If your map is an extremely simple one, you could use an image. E.g. The red and blue channels could serve as a tile type for the top layer and the green and alpha channels could serve as a tile type for the bottom layer. Where would you store your entities? If you want the image to look remotely related to the map, it's difficult to arrange things properly.

For my game, which consists of regions, entities, inventories and quests, I chucked everything into a binary file in byte form. However, I had to be really organised, as it's difficult to find errors with this method if you're not. E.g. For a single map with under 256 different types of tiles, that is 4 by 4 tiles, the file would look something like: 4 4 23 45 0 91 255 3 1 8 43 90 12 11 33 43 87 12, the first 2 numbers being the width and height and the next 16 numbers representing tiles.
> 0 votes

# Answer
Weird connection, but consider how Minecraft does it. The block textures are all in one image. Back in classic each texture was in a separate file. This worked fine because the rendering was very elementary. But as the game became more complete, it started to use much more resources, so a sprite sheet was a great optimization. Lesson... Use sprite sheets please. But if you'd rather not, you could always load each image during initialization, then reference back to them when needed.

Glad I can help.
> 0 votes

---
Tags: java, 2d, rendering
---


# Question
Title: Quite conflicted on advice given to "learn programming" for game development
I have been reading a few sources online that talk about learning programming with the end goal of game development in mind. I have heard many people saying that starting with Unity is the best way to go but others stating that C++ is what you need to get started with in order to be a game developer.

But as far as I'm concerned, this leaves me in quite a dilemma. Am I right in thinking that if I'm not overly fussed about making little indie games at the moment and just want to get stuck in with learning how to program, is C++ the right choice?

I have begun my journey with C++ and I am really enjoying it. I think it is the time further down the line that I am confused about. I am quite unsure on where to turn and what direction to go down to try and do this game development thing.

My end goal isn't necessarily working on an indie game project, I'd much rather aim to work at a gaming company which in my mind is a bit more realistic.

Thank you in advance.

# Answer
I'll say this: pick a language that you wish to learn. Learn it. Learning (almost) any language, whether it be C++, Java, C#, etc. will allow you to learn other languages very, very fast. Often times a programmer or game developer should know more than one language, so if you learn one language well, then you will easily be able to understand and quickly learn other languages. So, if you decide to learn with C++, go ahead. After you learn C++, get into C++ game development, and experiment with making a few games. You can then get on to learning other languages, which will make you more open with knowledge (and jobs, potentially!). At this point in time, games made by companies use many languages - C++ is good to learn, but remember that other languages for gamedev are also becoming quite relevant and more used! So, long story short, if you don't have much programming knowledge, I personally would recommend just choosing and learning a language.

I hope this helped a little, best of luck!
> 1 votes

---
Tags: education
---


# Question
Title: Sprite cut in half after placed on Scene
I have noticed a very odd behaviour in Unity 5.2.1. When I drag and drop a Sprite into the Scene, it's cut in half like this:

I tried with PNG and PSD formats but it didn't help. Although when I flipped an image horizontaly in PS and then imported it, it worked. Is this a Unity bug?

**Edit:** It happens only when I set Max Size to 512 or more, but still - why?

# Answer
This looks like a clipping plane problem in the scene view when you have large sprites that should not cause problems in your game view. Select the sprite and press F to focus on that object in the scene view. This will adjust clipping planes to suit the object's size. Any difference?

As far as I know you can not adjust the Scene View clipping but your game view clipping is adjusted on your active camera.

http://docs.unity3d.com/Manual/class-Camera.html
> 0 votes

---
Tags: sprites, unity
---


title: How to Create levels in game in libgdx

text:
# Question
Title: How to Create levels in game in libgdx
I am create trying to create a Android game using Libgdx. I want to Create levels in game . So what i do. Which classes i need to use and how to create them explained. Plz help.Also i want to add buttons to game to move a car from left to right. plz tell me

# Answer
LibGDX is not like some simplistic game engines so there is no set way to create levels. It completely depends on your game. If you would create a 2D game with tiles then you can use a simple CSV file where you put in numbers that correspond to your textures or perhaps a image where the pixels correspond to textures. There are some libraries and programs that integrate well with LibGDX but I personally never used them much.

* Tiled, LibGDX has functionality to load in the maps you create in there.
* overlay2D You can drag and drop stuff on a canvas and export that to your project. I have no experience with this but it looks great.

I'm not aware of a 3D level builder but imho LibGDX should be used for 2D althought it can deal with 3D pretty good. For 3D there are other engines out there like unity and UE4. But you can always role your own 3D map editor in LibGDX.
> 0 votes

---
Tags: android, physics, libgdx, game-design
---


# Question
Title: How to call a method after a yield instruction in the same frame?
When I run this script...

```
int frameCount;

void Start()
{
    frameCount = 0;
    StartCoroutine(first());
}

void Update()
{
    frameCount++;
    Debug.Log("Frame " + frameCount);
}

public IEnumerator first()
{
    Method1();
    yield return StartCoroutine(second());
    Method2();
}

public IEnumerator second()
{
    Method3();
    yield return null;
}

void Method1() { Debug.Log("Method1"); }
void Method2() { Debug.Log("Method2"); }
void Method3() { Debug.Log("Method3"); }

```

I get the following output:

```
Method1
Method3
Frame 1
Frame 2
Method2

```

How can I call all three methods in same frame without changing the code structure? The output i want:

```
Method1
Method3
Method2
Frame1
Frame2

```

---

**Note:** If this is not possible, please show me whether i can get this output (without changing the code structure):

```
Method1
Method3
Frame1
Method2
Frame2

```

# Answer
> 1 votes
You issue seems to be the over-use of yields. You don't need to yield on `second()` the way it's being used here so your `first()` function should look like this:

```
public IEnumerator first()
{
    Method1();
    StartCoroutine(second());
    Method2();
    yield break;
}

```

## Important note:

The code in `second()` will only complete execution before `Method2()` is called if it doesn't `yield` on anything extra. Your `yield return StartCoroutine(second())` will wait for all of `second()` to finish before `Method2()` but the way I have it written (without the `yield return`) will only perform operations *before the first `yield` in `second()`*. Since the first `yield` is *after* `Method3()` I assume this is fine but since this is a simplification of your actual code, I want to make that clear.

As another note, if you're adding a `yield` just to get an `IEnumerator` to compile, `yield break;` is sufficient.

---

I've run this myself and get:

```
Method1
Method3
Method2
Frame 1
Frame 2

```

# Answer
> 1 votes
Change your Start method from `void` to `IEnumerator` and use one of the examples below.

> Method1 Method3 Method2 Frame1 Frame2

```
IEnumerator Start()
{
    Method1();
    Method3();
    Method2();
    yield return null; // frame
    yield return null; // frame
}

```

> Method1 Method3 Frame1 Method2 Frame2

```
IEnumerator Start()
{
    Method1();
    Method3();
    yield return null; // frame
    Method2();
    yield return null; // frame
}

```

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