# Question
Title: Rigidbody2D without pushing eachother on collision
TLDR; How to stop movement if two Rigidbodies collides?

Also, here's a potato video of the problem: https://gfycat.com/ComposedArcticBetafish

Say I have three objects in a scene:

1. Player
2. Enemy
3. Rock

The player and enemies is moving freely, but the rock is static. So I attached a Rigidbody2D on player and enemy to move them around with script. All of them has a Box Collider 2D.

Now, if I (Player) move into an Enemy, I will start to push it (changing its position). I don't want this. I can set the Enemy's mass to something large, but then two enemies can still push eachother. I don't want this. If I try kinematic solutions I've found, but then they can move through the rock.

I want:

* Player can not move enemies
* Enemies can not move players
* Enemies can not move each other
* Nothing can move or go through the rock
* Enemies can not move through player
* Player can not move through enemies

I keep reading that if I'm moving colliders, I should also use Rigidbodies for performance. But I can't see how I get this to work with Rigidbodies.

How do I set it up? Or should I move away from rigidbodies and set it up myself?

# Answer
Add Player, Enemies, and Rocks to their own layers. Then in Edit-\>Project Settings-\>Physics 2D has a collision matrix containing layers that collide with other layers. Disable the collisions you don't want, then implement your custom collision handlers for the collisions that should be handled differently (i.e. player to enemy collisions)

Since rocks don't move based on physics interactions, they should probably be kinematic.

**Edit:**

Unity's physics engine is meant to model a 2D version of real physics. In the real world, if a "Player" pushes an "Enemy" hard enough, the enemy will move. You're asking how to make the player move into the enemy's collider space and then react to being hit (possibly by jumping backwards)-- this is not supported by Unity's physics because it is a simulation that will not allow two objects to occupy the same space. Whichever object has sufficient force to move the other's mass will do so. Therefore, your only option is to turn off collision handling between these two object types and implement it yourself.

You don't need to completely throw away the `RigidBodies` though. At least one of the colliding objects needs a `RigidBody` for `OnCollisionEnter()` or `OnTriggerEnter()` events to fire and you could use these events to do your own collision handling.

Lastly, I should note that I tried using some of Unity's physics for a 2D platformer and I couldn't get it to feel right. I ended up turning off the whole collision matrix and using raycasting to detect collisions with immovable objects. Though I did keep rigidbodies on my objects so that I could still use `OnCollisionEnter()` and `OnTriggerEnter()`
> 0 votes

# Answer
Here's a very simple way to prevent characters from pushing or interpenetrating kinematic or static colliders:

(here assuming they use circular colliders - you can do this equivalently with rectangular colliders or combinations of shapes too)

```
[RequireComponent(typeof(Rigidbody2D))]
[RequireComponent(typeof(CircleCollider2D))]
public class NoPushMovement : MonoBehaviour {

    public float moveSpeed = 1f;

    Rigidbody2D _body;
    CircleCollider2D _collider;

    void Start () {
        _body = GetComponent<Rigidbody2D> ();
        _collider = GetComponent<CircleCollider2D> ();
    }

    void FixedUpdate () {
        // Compute desired movement in this physics step
        // (using whatever method is appropriate for your player or AI)
        Vector2 movement = new Vector2 (
            Input.GetAxis ("Horizontal"),
            Input.GetAxis ("Vertical")   );

        movement *= moveSpeed * Time.deltaTime;

        // Check for a collision along our path.
        RaycastHit2D collision = Physics2D.CircleCast (
                        transform.TransformPoint (_collider.center),
                        _collider.radius,
                        movement,
                        movement.magnitude);

        // Move only if the way is clear.
        if(collision.collider == null)
            _body.MovePosition(_body.position + movement);
    }
}

```

More sophisticated versions can retain the portion of the movement that's parallel to the collision plane, so you slide along obstacles instead of stopping dead, or allow a partial-timestep of movement when you're close but not quite touching the obstacle.
> 0 votes

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


# Question
Title: Unity: Editing a DontDestroyOnLoad object in another scene
I figured out how to make certain objects like my Camera and Canvas persist across scenes, but I can't figure out how to access them in the editor from scenes in which they're not instantiated.

I can make these objects prefabs and make my changes to the prefab rather than the instance, but then I can't make references in the prefab to objects in the hierarchy; I would have to use an instance of a prefab to do that.

How can I edit subsequent scenes in the same way that I edited the first scene, where all the DontDestroyOnLoad objects are instantiated for the first time and I can access them through the hierarchy?

# Answer
> 2 votes
> I figured out how to make certain objects like my Camera and Canvas persist across scenes, but I can't figure out how to access them in the editor from scenes in which they're not instantiated.

A scene is basically a **collection of objects** (and **serialized properties**) that the engine bundles and can load together. As such, **it's allowed to cross reference objects that belong to the same scene**.

DontDestroyOnLoad mark an object in such a way that when a non additive scene loading operation(Apllication.LoadLevel|LoadLevelAsync) is performed, that object won't be destroyed. It controls the **runtime lifetime of an object**. In editor mode, isn't possible to reference an object across different scenes.

> I can make these objects prefabs and make my changes to the prefab rather than the instance, but then I can't make references in the prefab to objects in the hierarchy; I would have to use an instance of a prefab to do that.

That's how it works, right. If you want to setup references in one of your persistent object you basically have 2 ways:

1. **Instantiate** (or save it into a scene) **once**, prevent it gets destroyed(DontDestroyOnLoad), and initialize reference at runtime when a different level is loaded (es. OnLevelWasLoaded)
2. **Save a prefab instance** of such objects **in each scene**, and serialize references you need into the relative instances.

> How can I edit subsequent scenes in the same way that I edited the first scene, where all the DontDestroyOnLoad objects are instantiated for the first time and I can access them through the hierarchy?

If you are asking how to reference in a `Scene_B` a prefab is supposed to be instantiated and not destroyed in a `Scene_A`, in `editor mode` then **you can't.** The object instance is only available when a particular scene will be loaded (at runtime or in the editor for editing)

# Answer
> 0 votes
Try using the new SceneManagerAdditiveLoading function. You can view a tutorial at YouTube.

# Answer
> -1 votes
So you have:

* Scene one that contains the camera and canvas (which have been marked don't destroy on load). It also has a script that does a load for scene two.
* Scene two that contains objects that need to reference the canvas in scene one.

There's a few solutions for this:

**Solution one (low effort)**

Use GameObject.Find in Scene two to find the relevant objects in scene one, and assign them to your scripts.

**Solution two**

Create a singleton manager, which will avoid the sometimes expensive GameObject.Find call. A script in scene two can reference variables mediated by the singleton.

# Answer
> -1 votes
Try this:

```
var GameObject object=GameObject.Find("object name that won't be destroyed");

```

You will get an object reference in each scene.

---
Tags: unity
---


# Question
Title: Failed to spawn server object, Unity UNET
I'm familiar with Unity and programming but I'm new to this site.

So I have an issue with clients on Unity. I start servers with no errors, flawless. But when I join a server as a client I get a bunch of the error mentioned in the title. What causes this issue? I am using the UNET networking components.

I think it's lines like these, when executed by a client:

```
    NetworkServer.Spawn (objectNameHere);

```

How can I fix it if that's the case?

Edit

After hours of having this issue I have become so frustrated that I think it's best I take a break. I'll check back on this site from time to time.

# Answer
> 0 votes
I was having the same trouble, and figured it out. In my Player prefab, under the Network Identity component I had not checked "Local Player Authority". Once I checked this all subsequently behaved as expected.

---
Tags: unity, unity-networking
---


title: Track first time leveling up

text:
# Question
Title: Track first time leveling up
Broad question, but I'm looking for some better ideas.

Currently I have a Player class and booleans for hasSeenLevel2, hasSeenLevel3, etc. When I give a player exp I call a checkLevel method that checks to see if they level up.

```
checkLevel(){
    if(totalExp > 100){
         level = 2;
         if(!hasSeenLevel2){
             display("You gained level 2");
             hasSeenLevel2 = true;
         }
    }

}

```

this works, but is incredibly tedious to setup and inefficient.

What better ways are there to organize player levels and exp?

# Answer
Whenever you have multiple variables with names which just differ by a number, you should really consider if an array is more appropriate. So you should first replace your `hasSeenLevel2`, `hasSeenLevel3`, etc. variables with an array `hasSeenLevel` with one entry per level.

You should also use an array for storing the exp values required on each level to reach the next.

```
const int LEVEL_CAP = 5;
bool hasSeenLevel[LEVEL_CAP + 1];
int expForNextLevel[LEVEL_CAP];

expForNextLevel[1] = 100;
expForNextLevel[2] = 300;
expForNextLevel[3] = 500;
expForNextLevel[4] = 1000;

checkLevel(){
    while(totalExp >= expForNextLevel[level]){
         level++;
         if(hasSeenLevel[level]){
             display("You gained level" + level);
             hasSeenLevel[level] = true;
         }
    }
}

```

When your exp table isn't handmade but follows a fixed formula, you can alternatively populate the `expForNextLevel` array procedurally at startup.

Note: In the `expForNextLevel`array, the 0th index is not used and in the `hasSeenLevel` array, the indexes 0 and 1 are unused. You could fix that by subtracting 1 and 2 from the level whenever you access these array, but that's a large cost in code readability for a minuscule decrease of memory consumption, so I would really recommend you to live with that.
> 1 votes

# Answer
Here is a pseudo code way of doing it.

```
expForLevel = [100, 200, 300, 400]

currentLevel = 0
maxLevelReached = 0
currentExp = 0

checkLevel
  if currentExp >= expForLevel[currentLevel]
    currentLevel += 1
    if currentLevel == maxLevelReached + 1
      print "cool for your new level bro: level " . currentLevel
      maxLevelReached += 1
    else
      print "cool, you reached that level again: level " . currentLevel

```
> 0 votes

# Answer
There's a few ways to do this depending on the architecture of your engine and how your players are designed.

# Method 1: Array

As Phillip described, when storing variables whose names differ by incremental values, it's best to use a container of those (implied) variables. With an array, you simply assign the value (flag in this case) by the index. That being said, for this use case (level flags), you'll be setting a hard upper limit on levels; and, you would be breaking encapsulation.

# Method 2: Associative Array (Dictionary)

Depending on the language you're using this may or may not be better than an array. Unlike the array, this can extend as levels are added; however, an error catch must be implemented to catch error types.

# Method 3: Event Management System

I would recommend implementing an EMS system as you'd avoid having to store a variable to check against. With an EMS system, you'd simply fire an event when the Person levels up. That event in turn calls back a function which prints the intended message. Ideally the event would carry a variable containing the level they just hit, which is then in the callback function.
> 0 votes

# Answer
For determining the amounts per level, use an array as others have pointed out.

For the message logic, you need but one extra piece of state: `unlocked_level`. When the player earns enough XP, print your message and bump `unlocked_level`. When the player actually levels up, bump only `level`. The invariant is that `level <= unlocked_level`.

```
levels[] = {0, 100, 250, 700, 2000, ..., sentinel}

gain_xp(int amount):
  self.xp += amount
  while self.xp >= levels[self.unlocked_level]:
    self.unlocked_level += 1
    print 'You are now level ', self.unlocked_level

can_level_up():
  return self.xp >= levels[self.level]

level_up():
  if can_level_up():
    do_level_up_stuff

```
> 0 votes

---
Tags: architecture, rpg
---


title: Process of Game Updates/Patches

text:
# Question
Title: Process of Game Updates/Patches
I am currently in school studying game design and programming and I am wondering, simply: How are games updated?

Whenever I create simple, little programs, if I change anything, essentially the entire program is recreated. Obviously, game with sizes of 5, 10, even 20 Gb are much too large to recreate the whole thing if there are only a few small changes, so what is the process of updating the game's code?

Specifically PC if anything, but knowledge on other systems would be nice too, if they are different.

# Answer
> 1 votes
Here's a general primer, and I'd recommend searching StackOverflow for different specifics. There isn't a lot of game specific information beyond a discussion of game specific asset types or game specific operating systems (consoles, steam, etc.).

## Just Assets:

So your images, sounds, models, animations, etc. are probably loaded as needed.

They may exist as separate files, in which case you can build a mechanism to update these files and possibly even force the assets to be reloaded while the game is running.

They may also exist as part of a package. A single file where the asset data is just part of the file as a whole. If this is the case, you need to be able to rewrite the specific data or accept updating the whole package file.

## Code Updates:

Biggest issues here are permissions. If any application was allowed to download new code and run it there are a host of security issues. Normally in Windows there are some folders that you are allowed to place code updates for this reason.

Shared libraries, .dll files in windows. Break the code apart into smaller parts that are loaded as needed. Then you can replace those smaller .dll files.

Scripting engines allow you to essentially turn code into an asset. Instead of having to be compiled and loaded by the operating system, script just becomes text that can be easily changed.

This is a trade off of performance for ease of updates.

## Conclusion:

It comes down to breaking the game into pieces, having a core set of code that handles updating those pieces and then loads and executes them.

There are way too many specifics to consider here, as well as a lot of existing solutions that could be leveraged, but I hope this gets you started.

---
Tags: software-engineering, assets, pipeline, patching
---


# Question
Title: How to Load and Apply a Cube Map with DDS Texture Loader?
So I have been spending a lot of time recently implementing a working skybox/skysphere, and have almost completed it. The last thing that I need to do is to load my given texture, a skybox texture consisting of 6 equal images, as a cube map and not a normal texture like I have been doing.

**\- IGNORE FOLLOWING AND SKIP DOWN TO UPDATE -**

As you can see from the following image, the skybox texture is being loaded as a normal 2D texture and therefore gets warped by my HLSL effect as it should be. I also noticed that when I enable my vertex buffer, I get no visual output except for the default clear color (light blue). The picture taken below is rendered *without* my vertex buffer activated, and only my index buffer working. Also notable that this texture is being applied to a sphere currently, but I plan to move to a box once I get this working.

*IMAGE REMOVED*

I load the sky texture in with the following function.

```
ID3D11Texture2D* texture;
ID3D11ShaderResourceView* shaderResView;

// ...

CreateDDSTextureFromFileEx(device, pathToTexture, 0, D3D11_USAGE_DEFAULT, D3D11_BIND_SHADER_RESOURCE, 0, D3D11_RESOURCE_MISC_TEXTURECUBE, false, (ID3D11Resource**)&texture, &shaderResView, nullptr);

```

My skybox render function is below. I also added some header code if you are curious.

```
////////////////////
// In header file //

struct Vertex
{
    Vertex() {}
    Vertex(float x, float y, float z,
        float u, float v,
        float nx, float ny, float nz)
        : pos(x, y, z), tex(u, v), nor(nx, ny, nz) {}

    XMFLOAT3 pos;
    XMFLOAT2 tex;
    XMFLOAT3 nor;
};

struct SKY
{
    XMMATRIX WVP;
    XMMATRIX World;
};

// In header file //
////////////////////

XMMATRIX scale, trans;
sky = XMMatrixIdentity();

// 'cpos' is the camera position vector.
scale = XMMatrixScaling(2.0, 2.0, 2.0);
trans = XMMatrixTranslation(XMVectorGetX(cpos), XMVectorGetY(cpos), XMVectorGetZ(cpos));
sky = scale * trans;

XMMATRIX WVP;
UINT s = sizeof(Vertex);
UINT o = 0;

dc->IASetIndexBuffer(sib, DXGI_FORMAT_R32_UINT, 0);
//dc->IASetVertexBuffers(0, 1, &svb, &s, &o);

// NOTICE: The vertex buffer is commented out here, which
// produces the effect as seen in the screenshot of this
// post. When rendering without commenting it out, the only
// display output is of the background color.

WVP = sky * view * proj;
SKYOBJ.WVP = XMMatrixTranspose(WVP);
SKYOBJ.World = XMMatrixTranspose(sky);
dc->UpdateSubresource(SKYOBJBUFFER, 0, NULL, &SKYOBJ, 0, 0);
dc->VSSetConstantBuffers(0, 1, &SKYOBJBUFFER);
dc->PSSetShaderResources(0, 1, &srv);
dc->PSSetSamplers(0, 1, &ss);

dc->VSSetShader(vs, 0, 0);
dc->PSSetShader(ps, 0, 0);
dc->OMSetDepthStencilState(dss, 0);
dc->RSSetState(rs);
dc->DrawIndexed(faces * 3, 0, 0);

return;

```

**UPDATE:** So after quite a bit of playing around, I managed to pull off a working skysphere with almost a working texture. The following pictures are of the current result.

From the above images, you can clearly see that I produced a working sphere/box, and all that is left to do is load the texture in as a texture cube, not a plain texture. The following is my current texture loading function, which I thought would do the job. (Obviously doesn't).

```
ID3D11Texture2D* texture;
ID3D11ShaderResourceView* shaderResView;

// ...

hr = CreateDDSTextureFromFileEx(
    device,
    pathToTexture,
    0,
    D3D11_USAGE_DEFAULT,
    D3D11_BIND_SHADER_RESOURCE,
    0,
    D3D11_RESOURCE_MISC_TEXTURECUBE,  // I'm guessing this is wrong/no effect.
    false,
    (ID3D11Resource**)&texture,
    &shaderResView,
    nullptr);

```

And here is my vertex and pixel shader for the skybox itself. (Put here in case I am missing something crucial.)

```
SamplerState ss;
TextureCube skyMap;

cbuffer SKY
{
    float4x4 WVP;
    float4x4 World;
};

struct vIn
{
    float3 pos : POSITION;
};

struct pIn
{
    float4 pos : SV_POSITION;
    float3 tex : TEXCOORD;
};

pIn vmain(vIn i)
{
    pIn o = (pIn)0;

    o.pos = mul(float4(i.pos, 1.0f), WVP).xyww;  // Disable Z
    o.tex = i.pos;

    return o;
}

float4 pmain(pIn i) : SV_TARGET
{
    return skyMap.Sample(ss, i.tex);
}

```

Thank you in advance.

# Answer
A Cube Map is actually an array of six 2D textures, two for each axis (x, -x, y, -y, z, -z). The first thing we do when loading a cube map is tell D3D we will be loading a texture cube, by creating a `D3DX11_IMAGE_LOAD_INFO` structure and setting its MiscFlags member with `D3D11_RESOURCE_MISC_TEXTURECUBE`.

Then we will create a 2D texture from the file. This 2D texture will actually be an array now since we said we are loading a texture cube.

Next we get the description of our texture so we can create a resource view description that matches the texture we loaded in.

Now we will create the shader resource view description. We will say that this resource view is a texture cube, or an array of 2D textures, so when the pixel shader is texturing a pixel, it will know how to use the 3D coordinates we give it, which are used to find the texel on the texture cube. Remember a 2D texture uses (u, v) coordinates, well a 3D texture uses (u, v, w) coordinates.

And finally we create the resource view using the texture we loaded in from a file, the shader resource views description, and storing the shader resource view in smrv.

```
D3DX11_IMAGE_LOAD_INFO loadSMInfo;
loadSMInfo.MiscFlags = D3D11_RESOURCE_MISC_TEXTURECUBE;

ID3D11Texture2D* SMTexture = 0;
hr = D3DX11CreateTextureFromFile(d3d11Device, L"skymap.dds",
    &loadSMInfo, 0, (ID3D11Resource**)&SMTexture, 0);

D3D11_TEXTURE2D_DESC SMTextureDesc;
SMTexture->GetDesc(&SMTextureDesc);

D3D11_SHADER_RESOURCE_VIEW_DESC SMViewDesc;
SMViewDesc.Format = SMTextureDesc.Format;
SMViewDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURECUBE;
SMViewDesc.TextureCube.MipLevels = SMTextureDesc.MipLevels;
SMViewDesc.TextureCube.MostDetailedMip = 0;

hr = d3d11Device->CreateShaderResourceView(SMTexture, &SMViewDesc, &smrv);

```
> 1 votes

# Answer
You don't render a skybox as a "cubemap". You often render objects using a environment cubemap that matches the skybox, but the skybox itself is just rendered with a set of 2D textures.

On Direct3D Feature Level 10.0 or later hardware, you can use a Texture2D array with 6 faces as both a cubemap and with another shader as six individual faces.

The WIC loader only loads 2D textures. If you want to pre-create complex surfaces like 2D arrays, cubemaps, or volume maps you should use `DDS` files instead. The texassemble and texconv tools can help with that.
> 0 votes

---
Tags: c++, textures, directx, rendering, cubemap
---


# Question
Title: How to create a path-finder for a map like this?
I'm not sure if this is considered grid-based, because as you can see there is also a line. And that line is also a non-walkable point, I have no idea how do I create a path-finder with a non-grid-based. Currently I am using pacman-astar grid-based pathfinder, but it won;t fit to my game because I am using a line to block a characters path.

**In the image below is the map with lines.**

**In the image below is the graph, white is walkable, black is not.**

**In the image below is the actual path-finding, as you can see in the red circle still passing through because I am using gridbased.**

# Answer
> 3 votes
So the problem is that your pathfinding algorithm also just checks if it can move diagonally but it doesn't keep in mind that it's unable to pass diagonal if both the neighbouring blocks are walls.

For example: If you move diagonally right up, it will not check the block above and the block to the right.

Add a check to your algorithm and this should probably fix it. Or you can just disable checking diagonal spaces.

---
Tags: libgdx, path-finding
---


# Question
Title: Unity, positioning with ints instead of floats
I round my transform.position to the nearest integer at the end of every frame so it's never a decimal number. I would like to know if there's a way to make unity store the position in ints instead of floats to prevent floating points precision problems.

# Answer
No, you can't do that because Unity is doing all its internal calculation in `float`.

But if you would like to implement your game mechanics completely with integer arithmetics, you could write your own `Vector3Int` class, use it for all of your game mechanics, and then have each of your game objects write its Vector3Int-position to `transform.position` in `LateUpdate()`.
> 1 votes

# Answer
Assuming that you mean a Vector3 type that uses `int`s, I don't think there is a type that uses ints as internal storage seeing as how the unity transform system all uses floats everywhere.
> 0 votes

---
Tags: unity, floating-point
---


# Question
Title: Can't move rectangle constantly with key down
I can only move the rectangle every time I push a key down. How would I continuously move my shape when the key is down?

Here's my code:

```
for event in pygame.event.get():

    if event.type == pygame.QUIT:
        running=False

    if event.type == pygame.KEYDOWN:
        if event.key == pygame.K_d:
            lead_x_change += -10
        if event.key == pygame.K_a:
            lead_x_change += 10
        if event.key == pygame.K_w:
            lead_y_change += -10
        if event.key ==pygame.K_s:
            lead_y_change += 10

    if event.type == pygame.KEYUP:
        if event.key == pygame.K_a or event.key == pygame.K_d:
            lead_x_change = 0

    rectx += lead_x_change
    screen.fill(color)
    rect=pygame.Rect(rectx,recty,10,10)
    screen = pygame.display.set_mode(screen_dimensions)
    pygame.display.update()

```

# Answer
> 1 votes
You want to move your rectangle updating and screen updating code out from the event loop. Your current code doesn't move the rectangle or update the window if no events are generated. This leads to the incorrect behavior. So, instead your game loop should look something like this:

```
while Run:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            Run = False
        ...

    rect.x += velocityX

    screen.fill(Black)

    pygame.display.flip()

```

Also, you seem the me recreating the window each event. You should call `pygame.display.set_mode` once before the game starts, and simply fill the surface between frames.

# Answer
> 0 votes
If you are only pressing and then releasing one key at a time, that logic should work for you. There must be a problem in the update code that you are not showing. (You *do* have code somewhere to add `lead_x_change` to the x position every timer tick, don't you?)

However, you're not handling "rollover" properly. Rollover is where the new key-down action is detected before the key-up from the previous keypress. Suppose you are alternating between left(A) and right(D) quickly. You'll often get the sequence of events:

1. A key down, sets `lead_x_change` to -10
2. delay while rectangle moves
3. D key down, sets `lead_x_change` to 10
4. A key up, sets `lead_x_change` to 0
5. delay while rectangle is *supposed* to move, but doesn't
6. D key up, sets `lead_x_change` to 0 again

On `KEYDOWN`, record the last key pressed in a state variable at the same time you set the `lead_?_change` state variable. Then, on a `KEYUP` event, only clear the `lead_?_change` state variable if the key code matches the key code that last set that value.

You have do to that for each group of "mutually exclusive" keys. You have two independent motion axes, x and y, and each will need it's own "last key code" state to make this work.

---
Tags: input, python, pygame, keyboard
---


# Question
Title: Code reading difficulties with raycasting engine
I'm trying to teach myself to program some basic engines. I've been following this tutorial: http://www.playfuljs.com/a-first-person-engine-in-265-lines/ to get a decent idea of a basic way to render objects.

I'm confused, though, about certain items. I remember that in JavaScript, one must declare and define variables and objects, to me it doesn't seem like this programmer defines objects and methods like "column" and "step". For example, when he tries to find a ray's angle, he has these three lines of code:

```
var x = column / this.resolution - 0.5;
var angle = Math.atan2(x, this.focalLength);
var ray = map.cast(player, player.direction + angle, this.range);

```

The problem is, I'm trying to connect the dots and see how he defines "column", "angle", and "ray" and how they fit into the code at large, but in his tutorial I don't see those definitions everywhere! So I have no idea how this code seems to fit together. Is there something I'm missing? Some library or built-in stuff with Javascript?

# Answer
> 0 votes
The code snippets provided in this article are not correct programs, but just short extracts. They won't work on their own, they require to be put together with other pieces of code to make sense. The author of the article highlights the interesting parts of the source code, and does not cite the parts that would be uninteresting for the target audience, which - in this case - are programmers with significant experience in javascript and graphical engines.

---
Tags: javascript, raycasting
---


title: Problem with Basic Diffuse Lighting

text:
# Question
Title: Problem with Basic Diffuse Lighting
So recently I have been learning how to implement Diffuse Lighting in DirectX and I have done so with the following code:

```
float4 PS(VS_OUTPUT input) : SV_TARGET
{
    input.normal = normalize(input.normal);

    float4 diffuse = ObjTexture.Sample(ObjSamplerState, input.TexCoord);

    float3 finalColor;

    finalColor = diffuse * light.ambient;
    finalColor += saturate(dot(light.dir, input.normal) * light.diffuse * diffuse);

    return float4(finalColor, diffuse.a);
}

```

which has produced the following results:

Before I progress any further with specular lighting I wanted to clean up my code a little so I re-implemented this with a function and few changes.

```
float3 DirectDiffuseBRDF(float3 diffuseAlbedo, float nDotL)
{
    return (diffuseAlbedo * nDotL);
}

float4 PS(VS_OUTPUT input) : SV_TARGET
{
    input.normal = normalize(input.normal);

    float4 diffuseAlbedo = ObjTexture.Sample(ObjSamplerState, input.TexCoord);

    float nDotL = saturate(dot(input.normal, light.dir));

    float3 diffuseLighting = DirectDiffuseBRDF(diffuseAlbedo, nDotL);

    return float4(diffuseLighting, diffuseAlbedo.a);
}

```

Which produces:

As you can see the modified code has it's diffuse lighting a little different compared to the original. What am I missing from the original code to get it back to normal?

# Answer
> 1 votes
I have combined the before and after code and came up with this:

```
float3 DirectDiffuseBRDF(float3 diffuseAlbedo, float nDotL)
{
    return (diffuseAlbedo * nDotL);
}

float4 PS(VS_OUTPUT input) : SV_TARGET
{
    input.normal = normalize(input.normal);

    float4 diffuseAlbedo = ObjTexture.Sample(ObjSamplerState, input.TexCoord);

    float nDotL = dot(input.normal, light.dir);

    float3 diffuseLighting = diffuseAlbedo * light.ambient;

    diffuseLighting += saturate(DirectDiffuseBRDF(diffuseAlbedo, nDotL) * light.ambient);

    return float4(diffuseLighting, diffuseAlbedo.a);
}

```

I haven't tested it but it should work.

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


title: Web-based interactive fiction engine?

text:
# Question
Title: Web-based interactive fiction engine?
Are there any web-based interactive fiction engine that allow you to script a game and have it run from a website?

# Answer
Inform and TADS are the weapons of choice for most experienced IF authors. Quest seems to be catching up in terms of functionality. ChoiceScript is perfect for simple choice-based games, but hard to extend beyond that. Undum (and its popular extension Vorple) is based on JavaScript and probably offers the easiest way to get your game into a browser. It creates nice-looking stories and can be extended quite easily. (I once implemented a World of Darkness RPG system on top of it.)
> 9 votes

# Answer
One system that I've used, and it comes to my mind recently as someone wrote a game using it for the last Ludum Dare, is Twine. Quite easy to use, and gives a fun view of how your web pages connect! Easy deployment as well, it will make html files and you just put them up on your website!
> 3 votes

# Answer
I made a text adventure engine myself because I wanted something very minimal and that didn't require hosting.

It's called gist-txt.

It's very easy to use: you just need to create a new GitHub Gist with at least an `index.markdown` file in it. Then go to the URL `http://potomak.github.io/gist-txt#<your-gist-id>` to play your text adventure.

You can see an example text adventure at http://potomak.github.io/gist-txt/#acebd8fe14942fab4e8e.
> 0 votes

# Answer
I wrote the advenjure engine as a project to learn Clojure and then ported it to ClojureScript so it can also target the browser.

You can see it working online here.
> 0 votes

---
Tags: browser-based-games, interactive-fiction
---


# Question
Title: Bare-bones OpenGL game engine crashing 1/6 of the time with GLFW/GLEW
I am currently writing an OpenGL game engine, in which I am currently experiencing a crash every 1 out of 6 times. The error message with Visual Studio 2015 is:

> Exception thrown at 0x545579C6 (nvoglv32.dll). Access violation reading location 0x085C2000.

It points to either the end of the main method, or this line of code in the OBJ Loader class:

```
return renderer::Model3D(
    final_vertices, final_uvs, final_normals, final_indices, position, shader);

```

I believe that it is a rendering issue on my behalf, relating to an Nvidia driver problem, or a GLFW/GLEW problem.

Here are the Renderer3D `init`, `flush` and `submit` methods:

```
void Batch::init(std::vector<const Model3D*> models) {
    glGenVertexArrays(1, &pr_VAO);
    glGenBuffers(1, &pr_VBO);

    glBindVertexArray(pr_VAO);
    glBindBuffer(GL_ARRAY_BUFFER, pr_VBO);
    glBufferData(GL_ARRAY_BUFFER, RENDERER_BUFFER_SIZE, NULL, GL_DYNAMIC_DRAW);

    glEnableVertexAttribArray(SHADER_VERTEX_INDEX);
    glEnableVertexAttribArray(SHADER_UV_INDEX);
    glEnableVertexAttribArray(SHADER_NORMAL_INDEX);

    glVertexAttribPointer(SHADER_VERTEX_INDEX, 3, GL_FLOAT, GL_FALSE,
            RENDERER_VERTEX_SIZE, (const GLvoid*)0);
    glVertexAttribPointer(SHADER_UV_INDEX, 2, GL_FLOAT, GL_FALSE,  RENDERER_VERTEX_SIZE,
            (const GLvoid*)(offsetof(renderer::VertexData, renderer::VertexData::uv)));
    glVertexAttribPointer(SHADER_NORMAL_INDEX, 3, GL_FLOAT, GL_FALSE,
            RENDERER_VERTEX_SIZE, (const GLvoid*)(3 * sizeof(GL_FLOAT)));

    for (const Model3D* model : models) {
        std::vector<unsigned short> indices = model->getIndices();

        pr_IBO = new buffers::IndexBuffer(indices, RENDERER_INDICIES_SIZE);
    }
    glBindBuffer(GL_ARRAY_BUFFER, 0);
}

void Batch::flush() {
    glBindVertexArray(pr_VAO);
    pr_IBO->bind();

    glDrawElements(GL_TRIANGLES, 128, GL_UNSIGNED_SHORT, NULL);

    pr_IBO->unbind();
    glBindVertexArray(0);

    indexCount = 0;
}

void Batch::submit(const renderer::Model3D* renderable) {
    std::vector<glm::vec3> vertices = renderable->getVertices();
    std::vector<glm::vec2> texCoords = renderable->getTexCoords();
    std::vector<glm::vec3> normals = renderable->getNormals();

    for (int i = 0; i < vertices.size(); i++) {
        pr_Buffer->vertex = vertices.at(i);
        pr_Buffer->uv = texCoords.at(i);
        pr_Buffer->normal = normals.at(i);
        pr_Buffer++;
    }

    indexCount += 6;
}

```

Here is the `OBJLoader`'s `LoadOBJ` method:

```
renderer::Model3D OBJLoader::LoadOBJ
        (const char* filePath, glm::vec3 position, shaders::Shader& shader) {
    std::vector < glm::vec3 > temp_vertices;
    std::vector < glm::vec2 > temp_uvs;
    std::vector < glm::vec3 > temp_normals;
    std::vector < unsigned short> temp_indices;

    std::vector < glm::vec3 > out_vertices;
    std::vector < glm::vec2 > out_uvs;
    std::vector < glm::vec3 > out_normals;
    std::vector < unsigned short> out_indices;

    std::vector < glm::vec3 > final_vertices;
    std::vector < glm::vec2 > final_uvs;
    std::vector < glm::vec3 > final_normals;
    std::vector < unsigned short> final_indices;

    std::vector< unsigned int > vertexIndices, uvIndices, normalIndices;
    FILE * file = fopen(filePath, "r");

    if (file == NULL) {
        printf("Impossible to open the file!\n");
        getchar();
    }

    while (1) {
        char lineHeader[128];

        int res = fscanf(file, "%s", lineHeader);
        if (res == EOF)
            break;

        if (strcmp(lineHeader, "v") == 0) {
            glm::vec3 vertex;
            fscanf(file, "%f %f %f\n", &vertex.x, &vertex.y, &vertex.z);
            temp_vertices.push_back(vertex);
        }
        else if (strcmp(lineHeader, "vt") == 0) {
            glm::vec2 uv;
            fscanf(file, "%f %f\n", &uv.x, &uv.y);
            uv.y = -uv.y;
            temp_uvs.push_back(uv);
        }
        else if (strcmp(lineHeader, "vn") == 0) {
            glm::vec3 normal;
            fscanf(file, "%f %f %f\n", &normal.x, &normal.y, &normal.z);
            temp_normals.push_back(normal);
        }
        else if (strcmp(lineHeader, "f") == 0) {
            std::string vertex1, vertex2, vertex3;
            unsigned int vertexIndex[3], uvIndex[3], normalIndex[3];
            int matches = fscanf(file, "%d/%d/%d %d/%d/%d %d/%d/%d\n", &vertexIndex[0],
                    &uvIndex[0], &normalIndex[0], &vertexIndex[1], &uvIndex[1],
                    &normalIndex[1], &vertexIndex[2], &uvIndex[2], &normalIndex[2]);

            if (matches != 9) {
                printf("File can't be read\n");
            }

            vertexIndices.push_back(vertexIndex[0]);
            vertexIndices.push_back(vertexIndex[1]);
            vertexIndices.push_back(vertexIndex[2]);
            uvIndices.push_back(uvIndex[0]);
            uvIndices.push_back(uvIndex[1]);
            uvIndices.push_back(uvIndex[2]);
            normalIndices.push_back(normalIndex[0]);
            normalIndices.push_back(normalIndex[1]);
            normalIndices.push_back(normalIndex[2]);
        }
        else {
            char stupidBuffer[1000];
            fgets(stupidBuffer, 1000, file);
        }
    }

    for (unsigned int i = 0; i<vertexIndices.size(); i++) {
        unsigned int vertexIndex = vertexIndices[i];
        unsigned int uvIndex = uvIndices[i];
        unsigned int normalIndex = normalIndices[i];

        glm::vec3 vertex = temp_vertices[vertexIndex - 1];
        glm::vec2 uv = temp_uvs[uvIndex - 1];
        glm::vec3 normal = temp_normals[normalIndex - 1];

        out_vertices.push_back(vertex);
        out_uvs.push_back(uv);
        out_normals.push_back(normal);
    }

    indexVBO(out_vertices, out_uvs, out_normals, final_indices,
            final_vertices, final_uvs, final_normals);

    return renderer::Model3D
            (final_vertices, final_uvs, final_normals, final_indices, position, shader);
    }
}

```

Finally, the `main` method:

```
int main() {
    Window window(800, 600, "Proton");
    Shader shader("src/shaders/vertexShader.txt", "src/shaders/fragmentShader.txt");
    shader.enable();

    shader.setUniform3f("lightPosition", glm::vec3(4, 3, 3));
    shader.setUniform3f("lightColour", glm::vec3(1, 1, 1));

    GLuint texture = Texture::loadImage("res/textures/texture.bmp");
    glActiveTexture(GL_TEXTURE0);
    glBindTexture(GL_TEXTURE_2D, texture);

    shader.setUniform1i("texture1", 0);

    Model3D model =
            OBJLoader::LoadOBJ("res/models/cube.obj", glm::vec3(0, 0, 0), shader);

    std::vector<const Model3D*> models;

    models.push_back(&model);

    Batch renderer(models);

    std::cout << glGetError() << std::endl;

    while (!window.shouldClose()) {
        window.clear();

        glm::mat4 pr_matrix =
                glm::perspective(glm::radians(70.0f), 800.0f / 600.0f, 0.1f, 100.0f);
        glm::mat4 vw_matrix =
                glm::lookAt(glm::vec3(12, 9, 9), glm::vec3(0, 0, 0), glm::vec3(0, 1, 0));
        glm::mat4 matrix = glm::mat4(1.0f);

        shader.setUniformMat4("ml_matrix", matrix);

        shader.setUniformMat4("pr_matrix", pr_matrix);
        shader.setUniformMat4("vw_matrix", vw_matrix);

        renderer.begin();

        renderer.submit(&model);

        renderer.end();

        renderer.flush();

        window.update();
    }

    shader.disable();

    return 0;
}

```

# Answer
Access violations during glDrawArrays or glDrawElements are most often due to incorrectly enabled vertex attribute arrays. Please check your current state of the enabled vertex attributes very carefully. One which is left enabled inadvertently without providing any or enough data will result in these kinds of errors when sourcing data out of bounds during the draw call.

If that's not it, maybe there is some problem with memory consumption. You're running a 32-bit app according to the DLL name. Does the same thing happen in a 64-bit version?
> 1 votes

---
Tags: opengl, c++, glfw
---


# Question
Title: How do I render my DirectX C++ engine to a C# Panel?
The title pretty much sums it up. I'd like to know how I can get the `HWND` of my C# Panel object to my DirectX engine so I can render to it. I know it involves making a C++/CLI wrapper, but I'm not quite sure what to do beyond that.

# Answer
> 8 votes
You actually do *not* need C++/CLI for this, although you could use it if you wanted. I don't really recommend it. C#'s platform invoke facilities should be sufficient for you.

You'll need to make your engine available as a DLL. Doing so is beyond the scope of this question, but there's plenty of information about making DLLs available on the web. Once you have that, you need to expose a C-style function that can initialize your engine with a provided `HWND`:

```
// in C++:
extern "C" {
  void InitializeMyEngine(HWND window);
}

```

You can then then use P/Invoke in C# to access that function:

```
// in C#:
class Engine {
  [DllImport("engine.dll")]
  public static extern void Initialize(IntPtr window);
}

```

You can then call `Engine.Initialize(someWindowHandle)` in your C# code to initialize your engine. You may also want to expose P/Invoke wrappers to manually pump your engine's update or render loop from the C# side of things, for example from a variant of the canonical Windows Forms game loop.

All you need now is the `HWND` of the `Panel`. If you were using the Windows Forms `Panel` class, this would be very straightforward: it's just the panel's `Handle` property, because Windows Forms objects are mostly 1:1 mappings to Win32 counterparts and all have underlying handles.

WPF objects do *not*, however, so it's more difficult to get the WPF HWND from a WPF `Panel`. You can use the `HwndSource` class to do so:

```
HwndSource hwndSource = (HwndSource)HwndSource.FromVisual(yourPanel);
Engine.Initialize(hwndSource.Handle);

```

# Answer
> 5 votes
So like Josh has described above I have written an Engine in a DLL and used p/invoke in C# to use it. If anyone is interested here is the code:

**DLL Header.h**

```
#pragma once

#define DllExport __declspec(dllexport)

#include <windows.h>
#include <windowsx.h>
#include <d3d11.h>
#include <d3dx11.h>
#include <d3dx10.h>
#include <DirectXMath.h>

using namespace DirectX;

// include the Direct3D Library file
#pragma comment (lib, "d3d11.lib")
#pragma comment (lib, "d3dx11.lib")
#pragma comment (lib, "d3dx10.lib")

// global declarations
IDXGISwapChain *swapchain;             // the pointer to the swap chain interface
ID3D11Device *dev;                     // the pointer to our Direct3D device interface
ID3D11DeviceContext *devcon;           // the pointer to our Direct3D device context
ID3D11RenderTargetView *backbuffer;    // the pointer to our back buffer

extern "C"
{
    __declspec(dllexport) void InitD3D(HWND hWnd, int Width, int Height);    // sets up and initializes Direct3D
}

extern "C"
{
    __declspec(dllexport) void RenderFrame(void);     // renders a single frame
}

extern "C"
{
    __declspec(dllexport) void CleanD3D(void);        // closes Direct3D and releases memory
}

```

**DLL Main.cpp**

```
#include "Header.h"

void InitD3D(HWND hWnd, int Width, int Height)
{
    // create a struct to hold information about the swap chain
    DXGI_SWAP_CHAIN_DESC scd;

    // clear out the struct for use
    ZeroMemory(&scd, sizeof(DXGI_SWAP_CHAIN_DESC));

    HRESULT hr = S_OK;

    // fill the swap chain description struct
    scd.BufferCount = 2;                                    // one back buffer
    scd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;     // use 32-bit color
    scd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;      // how swap chain is to be used
    scd.OutputWindow = hWnd;                                // the window to be used
    scd.SampleDesc.Count = 8;                               // how many multisamples
    scd.SampleDesc.Quality = 1;
    scd.Windowed = TRUE;
    scd.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH;     // allow full-screen switching// windowed/full-screen mode
                                                            // create a device, device context and swap chain using the information in the scd struct

    hr = D3D11CreateDeviceAndSwapChain(NULL,
        D3D_DRIVER_TYPE_HARDWARE,
        NULL,
        NULL,
        NULL,
        NULL,
        D3D11_SDK_VERSION,
        &scd,
        &swapchain,
        &dev,
        NULL,
        &devcon);

    // get the address of the back buffer
    ID3D11Texture2D *pBackBuffer;
    swapchain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&pBackBuffer);

    // use the back buffer address to create the render target
    dev->CreateRenderTargetView(pBackBuffer, NULL, &backbuffer);
    pBackBuffer->Release();

    // set the render target as the back buffer
    devcon->OMSetRenderTargets(1, &backbuffer, NULL);

    // Set the viewport
    D3D11_VIEWPORT viewport;
    ZeroMemory(&viewport, sizeof(D3D11_VIEWPORT));

    viewport.TopLeftX = 0;
    viewport.TopLeftY = 0;
    viewport.Width = Width;
    viewport.Height = Width;

    devcon->RSSetViewports(1, &viewport);

}

void RenderFrame(void)
{
    // clear the back buffer to a deep blue
    devcon->ClearRenderTargetView(backbuffer, D3DXCOLOR(0.0f, 1.0f, 1.0f, 1.0f));

    // do 3D rendering on the back buffer here

    // switch the back buffer and the front buffer
    swapchain->Present(0, 0);
}

void CleanD3D(void)
{
    // close and release all existing COM objects
    swapchain->Release();
    backbuffer->Release();
    dev->Release();
    devcon->Release();
}

```

**C# Project**

```
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace DirectXinForms
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Dengine.InitD3D(panel1.Handle, panel1.Width, panel1.Height);
            Dengine.RenderFrame();
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            Dengine.CleanD3D();
        }
    }

    public class Dengine
    {
        [DllImport("DirectXENGINEDLL.dll")]
        public static extern void InitD3D(IntPtr window, int Width, int Height);

        [DllImport("DirectXENGINEDLL.dll")]
        public static extern void RenderFrame();

        [DllImport("DirectXENGINEDLL.dll")]
        public static extern void CleanD3D();
    }

}

```

You must make sure that the C# project is compiled as 64 bit if your DLL is 64 bit (same goes for 32 bit), if you compile with AnyCPU you will get a `SystemBadImage` error.

For some reason I could not add a reference to the DLL in Visual Studio 2015 but I just added it to the project by dragging and dropping the DLL which worked. However each time you make a change to the DLL you need to delete the one that you previously added and add it again in the same manner.

For the added .DLL file, under properties and copy to output directories set it as 'Copy Always'.

Hopefully this has helped some of you :).

---
Tags: c#, c++, directx, dll, c++cli
---


title: Unity WebGL build throws errors

text:
# Question
Title: Unity WebGL build throws errors
I am working on a multiplayer game for WebGL platform and I am using SocketIo & node.js server for handling the game.

I am facing issues, as shown in the attached image. I have no idea about what these errors mean. I don't think that the issue is from my coding side, as my multiplayer game runs perfectly in standalone builds, with more than 4 instances of the standalone build running.

It does not even open in my WebGL build. Does WebGL does not support threading? What are these errors all about? Can these issues be solved, or do I have to change my whole project implementation?

# Answer
> 1 votes
WebGl does not support threading currently. As for your error, I can't say what it is exactly. It's still tough to debug WebGL builds.

# Answer
> 1 votes
***The error is ambiguous, but from your phrasing, I think it is safe to say it is your use of threading.***

The error specifically notes *"uncaught abort(-1)"* error. In my experience, this tells us that something went wrong, but you need to do more digging to find out *exactly what*. It actually tells you this, in the actual error. Twice.

> See your browser's JavaScript console for more info
>
> **...**
>
> If this abort() is unexpected, build with -s ASSERTIONS=1 which can give you more information.

Ultimately, given that you ask "Does WebGL not support threading?", we can assume that you are using threading. WeblGL does not, in fact, support threading. *That is not to say this will cause a crash*; the Unity manual instructs otherwise:

> "Currently, the JavaScript language does neither support multi-threading, nor SIMD. So, any code which benefits from these features will see bigger slowdowns then other code."
> **<sub>\- Unity Manual - WebGL performance considerations</sub>**

That said, you *will* run into unforeseen behavior, if you insist on implementing threading. Apart from the aforementioned performance cost, you will likely have logical errors arising from the resulting mismanagement of the methods you *intended* to multi-thread, which can quite easily lead to an abort.

---
Tags: unity, multiplayer, webgl, socket
---


title: Using an unregistered company name

text:
# Question
Title: Using an unregistered company name
If I want to release an App with a Company Name do I have to have that registered before I can use it?

I have checked and the name is not taken, so is it fine to just use a made up company name?

As a side note, I have made this game just as a hobby project, not looking to make any money from it.

# Answer
> 5 votes
Ultimately, no. You do not need to register your company name. That said, you might what to consider *if you should*. You should consider it from a development point of view, and from a legal point of view.

### A developers point of view

You do not need to have the company name registered to publish an application; at least, not for Android. While you do have to provide a company name, this is mainly to identify your applications, in case another user posts an application with the exact same name.

### A legal point of view

This is where things get tricky, especially so given that I am not a lawyer, and I am only vaguely familiar with business name registry in Australia. At the end of the day, nothing requires you to register the name, but it is not really yours unless you do so. If another individual registers the name, it becomes theirs. If they wish to stop you from operating under the same name that they would then own, they might have a case to do so.

---

Ultimately, it does not sound like you are concerned with the monetary implications, given that you are making the game as a hobby. If you have any concerns regarding legal ramification, I would ask over at Law.SE, or better yet, an actual business lawyer. If you are only concerned with being rejected when attempting to *publish* your application, you need not worry.

---
Tags: legal
---


# Question
Title: C# Minesweeper - When cells with no mines nearby gets clicked
I'm currently making a Minesweeper in C#. I've already done the basics (generating minefield, rules and ui) but I don't know how I should implement when the user clicks a cell and the cell has no mines nearby and clicks nearby cells with also no mines nearby, like this:

And after click

This is my current code on this:

```
if (MineField(x,y) == false) // If the clicked cell isn't a mine
{
    if (GetNeighbours(x,y) == 0) // GetNeighbours returns the amount of mines in the closest 8 cells
    {
        // To be honest, no idea...
    }
}

```

# Answer
> 4 votes
One way to do this, is to use recursive Flood Fill algorithm. Something like:

If cell(x,y) has no bomb: 1. If coordinates (x,y) didn't went beyond game board, and cell (x,y) wasn't marked as visited:

a) give cell (x,y) property visited to true (or mark it in any other way) b) if getNeighbours(x,y) \> 0: print number of cell (x,y) c) if getNeighbours(x,y) == 0: reveal cell (x,y) and call whole function responsible for revealing field for coordinates (x-1,y-1),(x-1, y), (x-1, y+1), (x, y+1), (x+1, y+1), (x+1, y), (x+1, y-1), (x, y-1).

---
Tags: c#, algorithm
---


# Question
Title: How do I change color of one part of sprite in Game Maker?
I want to generate a competitive game like Age of Empires where each player has access to a variety of units, and each player can be distinguished by a color in each unit

And instead of sprites create 8 different colors, would have **only one**, with a mark where that color is changed, for example:

How do I change color of one part of sprite in Game Maker?

# Answer
> 1 votes
There are two common ways.

1. Without a shader. Split a sprite to the two parts. First of them will contain elements which must be drawed "as is", without changes (won't be colorized). And second part will contain elements which must be colorized (the elements must be white/grayscale).

In your example first part will contain green and black elements and second part will contain fuchsia element (but it must be white) Drawing will be like this:

```
var color = c_fuchsia;
draw_sprite_ext(sprite_index, 0, x, y, image_xscale, image_yscale, image_angle, c_white, 1);
draw_sprite_ext(sprite_index, 1, x, y, image_xscale, image_yscale, image_angle, color, 1);

```
2. Using simple shader.

Pass new color to your shader. Shader must check the color of the drawing pixel and change it to new color, if need. If you have no experience with shaders, then see `Demos -> Advanced -> Simple Shader Examples` (Shader Demo 5, Simple Colour Swapping) in GMS. But instead comparsion like this:

```
if ((col.r == 1.0) && (col.g == 0.0) && (col.b == 1.0))

```

use something like this:

```
if ((col.r > 0.99) && (col.g < 0.01) && (col.b > 0.99))

```

Shaders provide many ways and abilities (just one color, skins, palettes, etc).

P.S. Also you may use one of shaders from Marketplace: Retro Palette Swapper, Palette Based Drawing (but both are paid)

---
Tags: graphics, game-maker
---


title: HLSL Function Problem

text:
# Question
Title: HLSL Function Problem
Right now I am trying to implement Specular lighting in my DirectX Engine. Whenever I create the DirectSpecularBRDF function in my .HLSL file, my program crashes. Can anybody help me? The problem is in DirectSpecularBRDF, I haven't called the function yet but when I comment out the function code everything works fine. DirectDiffuseBRDF works fine when I call it though. Here is my code:

**effects.fx**

```
#include "Common.hlsl"

struct Light
{
    float3 dir;
    float4 ambient;
    float4 diffuse;
};

cbuffer cbPerFrame
{
    Light light;
    float4x4 camPos;
    float Roughness;
    float Metalness;
};

cbuffer cbPerObject
{
    float4x4 WVP;
    float4x4 World;
};

Texture2D ObjTexture;
SamplerState ObjSamplerState
{
    Filter = ANISOTROPIC;
    MaxAnisotropy = 16;
    AddressU = Wrap;
    AddressV = Wrap;
};

struct VS_OUTPUT
{
    float4 Pos : SV_POSITION;
    float2 TexCoord : TEXCOORD;
    float3 normal : NORMAL;
};

float3 DirectDiffuseBRDF(float3 diffuseAlbedo, float nDotL)
{
    return (diffuseAlbedo * nDotL);
}

float3 DirectSpecularBRDF(float3 specularAlbedo, float3 positionWS, float3 normalWS, float3 lightDir)
{
    float3 viewDir = normalize(camPos - positionWS);
    float3 halfVec = normalize(viewDir + lightDir);

    float nDotH = saturate(dot(normalWS, halfVec));
    float nDotL = saturate(dot(normalWS, lightDir));
    float nDotV = max(dot(normalWS, viewDir), 0.0001f);

    float alpha2 = Roughness * Roughness;

    // Computes the distribution of the microfacets for the shaded surface.
    // Trowbridge-Reitz/GGX normal distribution function.
    float  D = alpha2 / (Pi * pow(nDotH * nDotH * (alpha2 - 1) + 1, 2.0f));

    // Computes the amount of light that reflects from a mirror surface given its index of refraction.
    // Schlick's approximation.
    float3 F = Schlick_Fresnel(specularAlbedo, halfVec, lightDir);

    // Computes the shadowing from the microfacets.
    // Smith's approximation.
    float  G = G_Smith(Roughness, nDotV, nDotL);

    return D * F * G;
}

VS_OUTPUT VS(float4 inPos : POSITION, float2 inTexCoord : TEXCOORD, float3 normal : NORMAL)
{
    VS_OUTPUT output;

    output.Pos = mul(inPos, WVP);

    output.normal = mul(normal, World);

    output.TexCoord = inTexCoord;

    return output;
}

float4 PS(VS_OUTPUT input) : SV_TARGET
{
    input.normal = normalize(input.normal);

    float4 textureColor = ObjTexture.Sample(ObjSamplerState, input.TexCoord);
    float3 specularColor = float3(Metalness, Metalness, Metalness);

    float nDotL = saturate(dot(input.normal, light.dir));

    float3 diffuseLighting = textureColor * light.ambient * light.diffuse;

    diffuseLighting += saturate(DirectDiffuseBRDF(textureColor, nDotL));

    return float4(diffuseLighting, textureColor.a);
}

```

**common.hlsl**

```
//=================================================================================================
// Constant Variables
//=================================================================================================
static const float Pi       = 3.141592654f;
static const float Pi2      = 6.283185307f;
static const float Pi_2     = 1.570796327f;
static const float Pi_4     = 0.7853981635f;
static const float InvPi    = 0.318309886f;
static const float InvPi2   = 0.159154943f;

//=================================================================================================
// Sampler States
//=================================================================================================
SamplerState SamplerLinear
{
    Filter = MIN_MAG_MIP_LINEAR;
    AddressU = Wrap;
    AddressV = Wrap;
};

SamplerState SamplerAnisotropic
{
    Filter = ANISOTROPIC;
    MaxAnisotropy = 16;
    AddressU = Wrap;
    AddressV = Wrap;
};

// ===============================================================================================
// http://holger.dammertz.org/stuff/notes_HammersleyOnHemisphere.html
// ===============================================================================================
float2 Hammersley(uint i, uint N)
{
    float ri = reversebits(i) * 2.3283064365386963e-10f;
    return float2(float(i) / float(N), ri);
}

// ===============================================================================================
// http://graphicrants.blogspot.com.au/2013/08/specular-brdf-reference.html
// ===============================================================================================
float GGX(float NdotV, float a)
{
    float k = a / 2;
    return NdotV / (NdotV * (1.0f - k) + k);
}

// ===============================================================================================
// Geometry Term
// -----------------------------------------------------------------------------------------------
// Defines the shadowing from the microfacets.
//
// Smith approximation:
// http://blog.selfshadow.com/publications/s2013-shading-course/rad/s2013_pbs_rad_notes.pdf
// http://graphicrants.blogspot.fr/2013/08/specular-brdf-reference.html
//
// ===============================================================================================
float G_Smith(float a, float nDotV, float nDotL)
{
    return GGX(nDotL, a * a) * GGX(nDotV, a * a);
}

// ================================================================================================
// Fresnel
// ------------------------------------------------------------------------------------------------
// The Fresnel function describes the amount of light that reflects from a mirror surface
// given its index of refraction.
//
// Schlick's approximation:
// http://blog.selfshadow.com/publications/s2013-shading-course/rad/s2013_pbs_rad_notes.pdf
// http://graphicrants.blogspot.fr/2013/08/specular-brdf-reference.html
//
// ================================================================================================
float3 Schlick_Fresnel(float3 f0, float3 h, float3 l)
{
    return f0 + (1.0f - f0) * pow((1.0f - dot(l, h)), 5.0f);
}

// ===============================================================================================
// http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
// ===============================================================================================
float3 ImportanceSampleGGX(float2 Xi, float Roughness, float3 N)
{
    float a = Roughness * Roughness; // DISNEY'S ROUGHNESS [see Burley'12 siggraph]

    float Phi = 2 * Pi * Xi.x;
    float CosTheta = sqrt((1 - Xi.y) / (1 + (a * a - 1) * Xi.y));
    float SinTheta = sqrt(1 - CosTheta * CosTheta);

    float3 H;
    H.x = SinTheta * cos(Phi);
    H.y = SinTheta * sin(Phi);
    H.z = CosTheta;

    float3 UpVector = abs(N.z) < 0.999 ? float3(0, 0, 1) : float3(1, 0, 0);
    float3 TangentX = normalize(cross(UpVector, N));
    float3 TangentY = cross(N, TangentX);

    // Tangent to world space
    return TangentX * H.x + TangentY * H.y + N * H.z;
}

```

# Answer
If you use the latest version of Effects 11 using `D3DX11CompileEffectFromFile`, in the Debug configuration it dumps all the HLSL compiler error/warning output to the debug window.

You can also try directly compiling your file using the `FXC` command-line compiler by opening a VS 2015 Command Prompt:

```
fxc /T fx_5_0 effects.fx

```

If you do, you'll see the following output:

```
effects.fx(47,32-50): error X3020: type mismatch
effects.fx(47,22-51): error X3013: 'normalize': no matching 1 parameter intrinsic function
effects.fx(47,22-51): error X3013: Possible intrinsic functions are:
effects.fx(47,22-51): error X3013:     normalize(floatM|halfM|min10floatM|min16floatM)

```

You have `camPos` defined as a `float4x4` which is a matrix, not a `float3` position.
> 3 votes

---
Tags: c++, directx, hlsl, effects
---


# Question
Title: Simulated 3D hit point from surface normal
Here is an illustration describing what I'm trying to do...

# Answer
> 0 votes
Have a look into parallax mapping. This technique takes given geometry and a normal map to redefine the position that a given texel is displayed at. It does that by calculating an offset from the pixel's position using the normal map, just as you are trying to do. I did not yet implement parallax mapping in my engine yet, so I cannot give you a fitting solution, but maybe parallax mapping's math will give you an idea of what to do.

---
Tags: normal-mapping
---


# Question
Title: How to display text for 3 seconds in pygame
I am trying to print "You Crashed" when car hits wall(or blocks) for 3 seconds and then again start game loop.

I tried using `time.sleep(3)` but it's not working.

```
def crash():
    crash_font = pygame.font.Font('freesansbold.ttf',115)
    crash_text = crash_font.render("You Crashed!",True,black)
    game_display.blit(crash_text,((display_width/4 - 100), (display_height/4 + 100)))
    pygame.display.update()

    time.sleep(3)
    game_loop()

if x > display_width - car_width or x < 0:
        crash()

```

When I run this it blinks "You Crashed" for fraction of second and starts game\_loop()

---

If anyone wants to see full code http://pastie.org/10940745

# Answer
You don't want to stop executing the game loop while displaying the text. What you want to do is display the text from within your main loop, and count the passed time within the main loop. So, your code should look something like the following (pseudo-code):

```
# Mainloop:
while True:
    check_events()

    # Put your own condition here
    if not display_crash_text and shouldCrash:
        # Set the flag and get the current time.
        display_crash_text = True
        start_time = get_current_time()

    screen.fill(Black)

    # If the text should be displayed.
    if display_crash_text:
        screen.blit("You Crashed!", ...)

        # Check if three seconds have passed. This assumes that "get_current_time()" operates on seconds.
        if get_current_time() - start_time > 3:
            display_crash_text = False

    pygame.display.flip()

```

It's not very often that you should be using `time.sleep` in your game, as you most likely want to keep the main loop running at all times to keep your game responsive.
> 1 votes

---
Tags: 2d, python, pygame, text
---


# Question
Title: OOP design principles that fit with Unity
So my current concept is top-down arcade style game. Meaning you have a character and you walk around a closed space killing waves of enemies coming at you. My question is how to structure my abstractions. Since I'm using Unity3d at the end of the day there must a MonoBehaviour component that exist in the scene. For example I can have the following structure for the character.

```
public class CharacterController : MonoBehaviour
{
    ICharacter _character;
    IInputController _inputController;
    //and so on
}

```

Is this a good idea at all ? Unity3d doesn't really cater to normal OOP practices imho. I know this question can be flagged as opinion based but please find it in your heart not to. I want to figure out a pattern to write good and easily extensible code in unity.

# Answer
Unity does cater for that sort of abstraction, however you have to do some additional work to leverage it.

In my current project I have series of characters that can be controlled by the player or by AI, so I wanted to abstract their control. So I created a base class derived from `MonoBehaviour` that looks like this:

```
using UnityEngine;
using System.Collections;

[RequireComponent(typeof(Rigidbody))]
public class CharController : MonoBehaviour
{
    [HideInInspector]
    public Vector3 movementVector = Vector3.zero;

    [HideInInspector]
    public Quaternion lookAtRotation = Quaternion.identity;

    public float moveSpeed = 250.0f;
    public float turnSpeed = 1.0f;

    protected Rigidbody _rigidbody = null;

    protected virtual void Awake()
    {
        _rigidbody = GetComponent<Rigidbody>();
    }

    protected virtual void Start()
    {
    }

    protected virtual void Update()
    {
    }

    protected virtual void FixedUpdate()
    {
        _rigidbody.AddForce(movementVector * moveSpeed);
        _rigidbody.rotation = Quaternion.Slerp(_rigidbody.rotation, lookAtRotation, turnSpeed);
    }
}

```

Which is standard Unity except for the use of `protected` and `virtual` on the standard methods.

Here is an example of a specialised version of this class:

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

public class SpecialCharController : CharController
{
    protected override void Awake()
    {
        base.Awake();

        // Special stuff here
    }

    protected override void FixedUpdate()
    {
        base.FixedUpdate();

        // Special stuff here
    }
}

```

Note the use of `protected`, `override` and calls to `base.Method()`.

The `PlayerController` and `AIController` scripts only need to find and communicate with the `CharController` script in order to control all of the characters and the specialised version of the characters will work just fine.
> 3 votes

---
Tags: unity, oop
---


title: LibGDX - problem with AssetLoader

text:
# Question
Title: LibGDX - problem with AssetLoader
can someone tell me where i make a mistake? i want to use AssetLoader to load textures but.... always have the same error. I thought that problem is with my game so I made new project but I still have error.

> Couldn't load dependencies of asset: assets/badlogic.jpg

Here is my code:

```
public class TestApp extends ApplicationAdapter {
   SpriteBatch batch;
   Texture img;

   @Override
   public void create () {
      Assets.load();
      batch = new SpriteBatch();
      img = Assets.manager.get(Assets.image, Texture.class);
   }

   @Override
   public void render () {
      Gdx.gl.glClearColor(1, 0, 0, 1);
      Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
      batch.begin();
      batch.draw(img, 0, 0);
      batch.end();
   }

   @Override
   public void dispose () {
      batch.dispose();
      img.dispose();
   }
}

public class Assets {

    public static final AssetManager manager = new AssetManager();

    public static final String image = "assets/badlogic.jpg";

    public static void load(){
        manager.load(image, Texture.class);
        manager.finishLoading();
    }

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

```

# Answer
Read LibGDX's guide for plugging your assets folder to your IDE: https://github.com/libgdx/libgdx/wiki/Using-libgdx-with-intellij-idea

Especially **Linking the asset directories** part.

Everything in code seems ok.
> 1 votes

# Answer
There must be something wrong with the image's path. Try and find what might be wrong with it.
> 1 votes

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


title: LibGDX - question about game UI

text:
# Question
Title: LibGDX - question about game UI
I have question about game UI. Im using only one Screen class in my game and for different "screens" Im using gamestates. My question is how to set stage with buttons (play button, pause button, restart button) with custom listeners for each state? for example my play button should have 2 different listeners. First of them start the game if gamestate = menu and second unpause game when gamestate = pause.

What should I do ? make one playButton with "if" operator for different game states? or make two different playButton? and what with table? add all the buttons to one table and clear table each time when game state is changing? or make a few tables?

# Answer
Create two separate listeners and plug them when you switch your stage/gamemode. Like this:

```
ClickListener gameMode1Listener = new ClickListener(){
    @Override
    public void clicked(InputEvent event, int x, int y){
        super.clicked(x,y)

        // here goes your behaviour for 1st game mode
    }
}

ClickListener gameMode2Listener = new ClickListener(){
    @Override
    public void clicked(InputEvent event, int x, int y){
        super.clicked(x,y)

        // here goes your behaviour for 2nd game mode
    }
}

```

Now if you have your button you can set a listener you want by calling:

```
someButton.addListener(gameMode1Listener);

```

If your game changes and you need a second behaviour for a button, you can call:

```
someButton.removeListener(gameMode1Listener); // not sure what's the name of the 'remove' method
someButton.addListener(gameMode2Listener);

```
> 1 votes

# Answer
* If you don't have too many buttons/tables and the project is relatively small then using different "if"s is perfectly fine.
* If you have several of them then it would be better to have a function that is called whenever the state is changed and have it switch the listeners and tables.
* An even better approach would be to create different groups, each with their own buttons and tables, and switch the group whenever the state of the games has changed. This approach sacrifices some memory but should make for faster switches.
> 1 votes

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


title: Cbuffer Padding Error

text:
# Question
Title: Cbuffer Padding Error
In my cbuffer in DirectX, I send 2 variables over to my HLSL shader called `Light` & `Roughness`. If I remove the `Roughness` variable my program compiles fine but as soon as I introduce `Roughness` I get the error: `Exception thrown at 0x00007FFDDEFA0030 (d3d11.dll) in Eagle Engine.exe: 0xC0000005: Access violation reading location 0x00000000000000C0.`

On the HLSL side the light variable contains it's defined value that was set in C++ and works fine without `Roughness`. If anyone could help me that would be great, I've included the necessary code below.

**effects.fx**

```
#include "Common.hlsl"

struct Light
{
    float3 dir;
    float4 ambient;
    float4 diffuse;
};

cbuffer cbPerFrame
{
    Light light;
    float Roughness;
};

cbuffer cbPerObject
{
    float4x4 WVP;
    float4x4 World;
};

Texture2D ObjTexture;
SamplerState ObjSamplerState
{
    Filter = ANISOTROPIC;
    MaxAnisotropy = 16;
    AddressU = Wrap;
    AddressV = Wrap;
};

struct VS_OUTPUT
{
    float4 Pos : SV_POSITION;
    float2 TexCoord : TEXCOORD;
    float3 normal : NORMAL;
};

float3 DirectDiffuseBRDF(float3 diffuseAlbedo, float nDotL)
{
    return (diffuseAlbedo * nDotL);
}

VS_OUTPUT VS(float4 inPos : POSITION, float2 inTexCoord : TEXCOORD, float3 normal : NORMAL)
{
    VS_OUTPUT output;

    output.Pos = mul(inPos, WVP);

    output.normal = mul(normal, World);

    output.TexCoord = inTexCoord;

    return output;
}

float4 PS(VS_OUTPUT input) : SV_TARGET
{
    input.normal = normalize(input.normal);

    float4 textureColor = ObjTexture.Sample(ObjSamplerState, input.TexCoord);

    float nDotL = saturate(dot(input.normal, light.dir));

    float3 diffuseLighting = textureColor * light.ambient * light.diffuse * Roughness;
    diffuseLighting += saturate(DirectDiffuseBRDF(textureColor, nDotL));

    return float4(diffuseLighting, textureColor.a);
}

```

**In my Main.cpp**

```
constbuffPerFrame.light = light;
constbuffPerFrame.Roughness = 1.0f;

devcon->UpdateSubresource(cbPerFrameBuffer, 0, NULL, &constbuffPerFrame, 0, 0);
devcon->PSSetConstantBuffers(0, 1, &cbPerFrameBuffer);

```

**Header.h**

```
struct Light
{
    Light()
    {
        ZeroMemory(this, sizeof(Light));
    }
    XMFLOAT3 dir;
    float pad;
    XMFLOAT4 ambient;
    XMFLOAT4 diffuse;
    XMFLOAT4 specular;
};

struct cbPerFrame
{
    Light  light;
    float Roughness;
};

Light light;
cbPerFrame constbuffPerFrame;

```

# Answer
You are not padding after the roughness in the C++ side structure. You need to add 3 more floats of padding after roughness so that the buffer size is a multiple of 16 bytes.

On MSDN you can read a more complete explanation.
> 2 votes

---
Tags: c++, directx, hlsl
---


# Question
Title: Unity: Why do my 2 gameObjects 'share' materials?
no one has answered this on Unity answers yet so I thought I might as well ask this here:

recently, I imported my .blend game character and the character consisted of 2 colors: Red and black. Therefore as unity always does it creates 2 red and black materials for the colors of the character. Then, I imported the grass platform for my game. Because the grass platform is green and brown, Unity should have created 2 new green and brown materials and the platform should have stayed green and brown. But, instead, my grass platform decided to use my character's materials and my platform is now red and black. (If I import the grass platform first, my character becomes brown and green). Please help, this is an extremely annoying problem, thanks!

# Answer
Make sure they are named differently in blender, also make sure that you try importing to different folders in unity. If that fails, just re-apply the materials? (Create the new ones yourself)
> 0 votes

# Answer
I've noticed this myself, but with U/V scaling of a material on 2 different objects. I guess the only way to solve this is to duplicate the material and assign a different one to each object and then adjust the material to suit the object.
> 0 votes

---
Tags: unity, textures
---


# Question
Title: Generating "tile map" by stamping a full map
I'm building a game using Tiled tilemap editor.

I was originally creating tilesets to stamp around and create my map in Tiled.

Id prefer to create the base map in a Adobe Illustrator and stamp in the whole map as the level. Then stamp in trees or whatever on more layers as needed.

What are the implications on performance doing it this way vs creating the tilemaps and stamping them in tiled?

**Example**:

Tile:

Stamped Map:

# Answer
> 1 votes
Having a huge image for your map will take more texture memory than a tileset would. Assuming a 32bit color depth, a 6400 x 6400 px map will take 156 MB of texture memory. Not much for PCs and consoles but might be too much for some low-end mobile devices.

But drawing it will be slightly faster because you don't need to iterate tiles but can just blit from the original image (assuming your graphic engine is actually doing this and isn't stupidly blitting it tile by tile because the TMX file says so).

# Answer
> 0 votes
As the other answer mentioned it will take more memory to use but will be faster to render... that being said why not use a combination of both?

What I mean by that i sthat you could draw out the level using a very specific colour palette then when the level loads (or using a tool then saving the result) you could generate a map using the pixel colour of the full map as a guide for what tiles place in the actual game. So a green pixel could be grass, a grey one a road etc..

With a bit more logic you could place small variations of tiles so that the map looks better without having to do much more work or even create rules so that when a pixel is surrounded by X tiles of the same type it uses a different tile which is more related than the basic one. E.g. a basic tile could be short grass while a tile that is surrounded by 6 tile of the same type is long grass. It could also help make transitions between terrain types smoother (depending on what is required).

---
Tags: tilemap, rpg
---


# Question
Title: How can I rotate the camera for a player walking around the surface of a sphere?
I'm making a 3D game where the player can walk across the surface of a planet.

I am having a problem correctly rotating the camera's frame of reference, so that the camera is oriented correctly anywhere on the planet.

My strategy so far has been to create a quaternion that represents the rotation from an "up" vector (i.e. north pole) to the current position vector of the camera:

`var up = new THREE.Vector3(0, 1, 0);
camera.quaternion.setFromUnitVectors(up, camera.position.clone().normalize());`

To get the final rotation of the camera, I apply the rotation of where the player is looking:

`camera.quaternion.multiply(sensor.getState().orientation);`

This means that wherever the player is, if they look down they will look towards the center of the planet.

I then apply that rotation to the `up` vector to get the direction the player is looking:

`var direction = up.clone().applyQuaternion(camera.quaternion);`

Assuming the player is looking directly forward, if the player travels in that direction, I would expect them to walk around the planet in a straight line.

This works correctly near the north pole, however as I approach the south pole, the camera seems to rotate laterally (from the perspective of the player), finally as I reach the south pole the camera rapidly rotates 360 degrees around the pole.

What is causing this and how can I avoid it?

# Answer
> 0 votes
I finally solved the problem. Big thanks to @DMGregory and his answer to a similar problem.

His answer is very comprehensive in explaining the problem, but I couldn't get the solution to work with three.js, and it was too prescriptive in the way the player moved.

He points out that this is caused by Hairy Ball Theorem which I understand to mean that you can't have a smooth continuous mapping around a sphere; something I was attempting to do with a quaternion representing the rotation of the player from the north pole.

The solution I used was to incrementally update a quaternion (`playerRotation`) as the player moves. Each incremental step happens as if the player was at the north pole, avoiding all hairy ball issues:

```
var playerRotation = new THREE.Quaternion();

function renderLoop() {
  camera.oldPosition = camera.position.clone();

  // Update the camera's position however you want here

  var currentRotation = new THREE.Quaternion();
  currentRotation.setFromUnitVectors(
    camera.oldPosition.clone().normalize(),
    camera.position.clone().normalize()
  );

  playerRotation.premultiply(currentRotation);

  camera.rotation.copy(playerRotation);
  camera.rotation.multiply(sensor.getState().orientation);
}

```

One gotcha that stumped me for a while was the fact that quaternion multiplication is not commutative - order matters.

The `premultiply` step is equivalent to`playerRotation.copy(currentRotation.multiply(playerRotation))` i.e. multiplying the quaternions in reverse order. This is important because `playerRotation` is a rotation in the world's frame of reference. It needs to be applied before the other rotations.

In contrast `sensor.getState().orientation` represents the camera rotating around in the player's frame of reference, so that should be applied after `playerRotation`.

# Answer
> 1 votes
Your problem seems to be that you're telling your camera that its up direction is a fixed world up, and then turning it upside down, which causes all sorts of fun mathematical chaos that's not at all what you want.

As a fix, try using the direction from the center of the planet to the player as the up on your camera instead of an arbitrary world vector. This should be updated as the player walks around the planet, but if your code was working around the north pole before it should otherwise require no additional changes.

# Answer
> 0 votes
I haven't worked in Three.js; however, since the problem may be reduced to geometric rotations in mathematics, I'll approach it from that avenue.

## Mathematical Approach

From your description, as your azimuthal/inclination/elevation angle approaches the south pole (180°, π rads), the rotation being applied to the camera's polar angle (θ) increases without bound. Is this correct?

If so, then I suspect that the rotation you're applying is multiplying the polar angle by the azimuthal angle, θ → θ x φ.

---
Tags: vector, quaternion, three.js
---


title: Cbuffer Packing

text:
# Question
Title: Cbuffer Packing
So I recently had this error: Cbuffer Padding Error

Which has led me to ask this question. Can somebody explain packing/padding in a Buffer for DirectX? I cannot get my head around it, rather than doing this manually there has to be some easier way right?

# Answer
> 1 votes
Basically, computers typically like (and sometimes require) data to be aligned on certain byte 'boundaries'. DirectX 11 requires 16 byte alignment and DirectX 12 is 256 byte. You can read about why alignment is good/required on the internet elsewhere. But the short of it is that computers will read multiple values at the same time, in sizes that are powers of 2 (Usually a minimum of 4 bytes at a time).

When things are unaligned, to read a single value, the computer may be required to read multiple regions to fetch the data (or worst case, read single bytes at a time) `[..==|==..]` (both the first and second slots would have to be read to read the value in the middle, whereas, if correctly aligned, `[====|....]` could read just the first. (This also has storage implications).

This also means, that when reading a single value that is multiple bytes (say a float4, you may want to align it on its own 16 byte boundary)

You can find sizes of the data types here: https://msdn.microsoft.com/en-us/library/windows/desktop/bb509646(v=vs.85).aspx

Remember that one byte is 8 bits. So, a float is 32 bits, which is 32 / 8 == 4 bytes.

Vectors are just multiples of the scalar (so if float is 4 bytes, float4 is 4 * 4 == 16 bytes).

So, in a constant buffer, you want your values to align to those 16/256 byte boundaries (and will be required to fill up to the next 16/256 bytes).

```
cbuffer {
    float2 position; //offset = 0, size = 8
    float2 texcoord; //offset = 8, size = 8
    //16 byte boundary
    float3 normal;   //offset = 16, size = 12
    float  padding;  //offset = 28, size = 4
    //16 byte boundary
    float4 tangent;  //offset = 32, size = 16
    //16 byte boundary
};

```

---
Tags: c++, directx, hlsl
---


# Question
Title: How are the same items generated with slightly different attributes?
Consider games like Destiny. How do they generate weapons that have the same skins and names, but different attributes? Two people can have the same weapon or armor piece, but have different attributes on these pieces based on luck or drop rate etc. How is this accomplished programmatically?

# Answer
it's pretty easy if you view every single weapon got by player as an instance of pre-defined weapon model. each instance can have their own data like attack power or weight. They will share material for efficiency, but logically they're single instance since created, you can even use single material for single weapon.

As a side note, game like Destiny often use adjectives to generate variety. It use the **prototype pattern**. Imagine you have defined a common sword, and how the game can generate a fire sword with no definition? You can treat **fire** adjective as a **decorator**. When you access the weapon attack, it will come from fire decorator, which will first get normal sword power and then add the fire power.
> 0 votes

# Answer
* Create some sort of data structure to hold different attribute types.
* Create some sort of luck formula that fits your game and chooses attributes from above mentioned data structure
* Assign values to said attributes based on the same luck formula or another formula or just plain randomness.
* profit ?
> 1 votes

# Answer
To add another example, especially after ZenWu's anwer, I would like to refer to World of Warcraft. Since the last expansion they have a similiar approch to crafted gear where you have basic prototypes as you may call them like these Demonsteel Gauntlets. In the item tooltip you will notice that there are only the mainstat and some stamina but no secondary stats. These gauntlest do exist in various versions like these Demonsteel Gauntlets of the Peerless. The developers have specific affixes to their item names which are different versions of the same item. These different item versions can be explored using the link to the right of "Item Version" where you can change both the item level, the affix, tertiary stats or sockets. While doing so you might notice the url change as well since the bonus variable holds a bunch of id representing specific additions.

In this small example one could possibly think about a `DemonsteelGauntlet` class which just holds a variable based on an enumeration of all the particular types to deduce what version you have at hand (no pun intended). Of course this is only feasible if you have a limited amout of possible variants of the same item. If you are going to randomize more than just a dozen affixes you might want to attach some further meta-information to those particular items. Some kind of reasonable datastructure which holds those stats or some other special information where you can add those.
> 0 votes

---
Tags: software-engineering
---


# Question
Title: Vertex Displacement Distortion Correction
I am developing for Mobile VR using GoogleVRSDK and Unity. My target platform is Android. I have a shader which displaces vertices to create a reverse lens distortion.

Following is my shader,

```
Shader "Unlit/Cube"
{

Properties {
    _Color("Main Color", Color) = (1,1,1,1)
}

Category {

    Tags { "Queue"="Geometry" "IgnoreProjector"="True" "RenderType"="Opaque" }

    Blend Off
    AlphaTest off
    Cull off
    Lighting Off
    ZWrite On
    ZTest LEqual
    Fog { Mode Off }

    SubShader {
        Pass {
            CGPROGRAM

           // #pragma target 3.5
           // #pragma target 2.0
           // #pragma only_renderers gles2
           // #pragma only_renderers gles

            #pragma vertex VertexProgram
            #pragma fragment FragmentProgram
            #pragma multi_compile __ GVR_DISTORTION
            #include "GvrDistortion.cginc"

            struct VertexInput {
                half4 vertex : POSITION;
                half4 texcoord : TEXCOORD0;
            };

            struct v2f {
                half4 vertex : SV_POSITION;
                half4 uv : TEXCOORD0;
            };

            v2f VertexProgram (VertexInput v)
            {
                v2f o;
                o.uv = v.texcoord;
                o.vertex = undistortVertex(v.vertex);
                return o;
            };

            fixed4 _Color;

            fixed4 FragmentProgram (v2f fragment) : COLOR
            {
                return _Color;
            }
            ENDCG
        }
    }
}

```

Following is my GvrDistortion.cginc

```
#if defined(GVR_DISTORTION)

float4x4  _Undistortion;
float     _MaxRadSq;
float     _NearClip;
float4x4  _RealProjection;
float4x4  _FixProjection;

float distortionFactor(float rSquared) {
  float ret = 0.0;
  ret = rSquared * (ret + _Undistortion[1][1]);
  ret = rSquared * (ret + _Undistortion[0][1]);
  ret = rSquared * (ret + _Undistortion[3][0]);
  ret = rSquared * (ret + _Undistortion[2][0]);
  ret = rSquared * (ret + _Undistortion[1][0]);
  ret = rSquared * (ret + _Undistortion[0][0]);
  return ret + 1.0;
}

// Convert point from world space to undistorted camera space.
float4 undistort(float4 pos) {
  // Go to camera space.
  pos = mul(UNITY_MATRIX_MV, pos);
  if (pos.z <= -_NearClip) {  // Reminder: Forward is -Z.
    // Undistort the point's coordinates in XY.
    float r2 = clamp(dot(pos.xy, pos.xy) / (pos.z*pos.z), 0,     _MaxRadSq);
    pos.xy *= distortionFactor(r2);
  }
  return pos;
}

// Multiply by no-lens projection matrix after undistortion.
float4 undistortVertex(float4 pos) {
  return mul(_RealProjection, undistort(pos));
}

// Surface shader hides away the MVP multiplication, so we have
// to multiply by _FixProjection = inverse(VP)*_RealProjection
// and then by inverse(M), in order to cancel it out and leave our
// own transform in place.
float4 undistortSurface(float4 pos) {
  float4 proj = mul(_FixProjection, undistort(pos));
  return mul(unity_WorldToObject, proj);
}

#else
// Distortion disabled.

// Just do the standard MVP transform.
float4 undistortVertex(float4 pos) {

 return mul(UNITY_MATRIX_MVP, pos);
}

// Surface shader hides away the MVP multiplication, so just return   pos.
float4 undistortSurface(float4 pos) {

  return pos;
}

#endif

```

This shader works completely as excepted in Samsung S6 and LG G3 and the Unity Editor.

But we are working for a phone named Venus. In that phone shader renders but the displacement of vertices doesn't happen.

I tried disabling conditional compiling. I tried changing render targets and forcing different OpenGL versions in render.

Nothing worked. I would love to hear a solution. Thank you.

The specs of the Venus,

GPU Adreno(TM) 405 Runs OpenGL ES 3.0 GPU SM:4.0 and VRAM 512MB RM 2gigs Screen 1080x1920 60hz dpi 480 Android 5.1 API-22 CPU is ARMv7 VFPv3 NEON (8 cores)

The shader in LG G3 :  The shader in Venus :

# Answer
I know that it is not preferred to answer my own question but i think it will be maybe useful to some people.

I forgot to update this post.

After long hours. The problem resolved.

It is the case of bad GLES drivers i guess.

Even if the phone says that it uses **GLES 3.0**,

forcing to use **GLES 2.0** in player settings worked.

If you ever stumble any non-standart phone try that first.
> 0 votes

---
Tags: shaders, vertex, virtual-reality, displacement-mapping
---


# Question
Title: Performance of separate Animators vs single multilayer Animator
I am making a 2D game with Unity 5.4 and I want to animate my 2D human character.

He has different sprites for its body parts - leg(s), hand(s), head, eye(s), nose, mouth. Its eyes, hands, legs move independently from each other - meaning their animations and transitions are not related in any way.

My question is, which alternative is the better choice performance-wise when animating?

1. For legs, hands, eyes, etc. create separate Animator and animate them separately.
2. For all animations use single Animator (attached on body's "container" GameObject) and create for legs | hands | eyes different Layers in the Animator.

# Answer
I'm not 100% sure with Unity, but in my experience with C++ and lower level stuff, combining them into a single animator should be more efficient than having four of them doing their own thing. The higher level you get, the more "bookkeeping" stuff there tends to be, so having more animators will just waste more processing cycles on stuff the other animators have already done, or will do again.

That being said, I doubt there'd be much difference either way. Unity's pretty decent on performance, especially for 2D games. I wouldn't worry too much about framerate until it's done, and if it runs acceptably and it's easy to maintain, then score! If not, it's easier to profile and find what's slowing you down.
> 1 votes

---
Tags: unity, animation
---


# Question
Title: Debugging .FX files in Visual Studio not working
So I have been learning how to use DirectX 11 for a while now and I have chosen to use the .FX framework rather than seperate .vs & .ps files. (I know it's deprecated but I found it a little easier to use for learning, I will use in seperate .vs and .ps files in the near future).

In order to get my engine to compile I have to keep the `effects.fx` file in the same file directory as the engine project but I cannot include it in the VS2015 project directly (This works fine). At the moment whenever I am writing some code in my .FX file and it creates an error I get an error from the C++ side of things and nothing from my shader. Which leaves me clueless on what is causing the issue.

How can I get the HLSL compiler error/warning output to the debug window?

# Answer
First you will have to set up a custom build step like so: right click on project -\> build customization-\> then add the fx(targets, props).

Looks like this:

Have all the shaders under a filter in VS then right click the shader(.fx) file-\> propertys-\> set item type on the left to HLSL compiler-\> hit apply-\> change HLSL compiler settings to effect.

I also use an extension so I have real time compellation of shaders as I type and it hooks into the MSDN docs so u get some info on what u are doing its called HLSL tools for Visual Studio, once I change some shader code I hit compile on the shader file in VS and see what I get in the output window\error window.
> 2 votes

# Answer
You have to enable debugging in the initialize of the shader.

```
DWORD dwShaderFlags = D3DCOMPILE_ENABLE_STRICTNESS |
        D3DCOMPILE_IEEE_STRICTNESS | D3DCOMPILE_DEBUG; //Debug yay =D
hr = D3DCompile(shader_code.data(),
        shader_code.size(),
        NULL,
        pDefines,
        D3D_COMPILE_STANDARD_FILE_INCLUDE,
        pEntrypoint,
        pTarget,
        dwShaderFlags,
        NULL,
        pCompiledShader,
        &pErrorBlob);

```
> 2 votes

---
Tags: c++, directx, hlsl, visual-studio
---


title: Infinite platform 3d

text:
# Question
Title: Infinite platform 3d
How do we make a infinite platform generator using prefabs. So ,for example, you have 3 prefabs and it generates a infinite platform by randomly generating the 3 prefabs.

This might come as a shock, but I did search it up and found nothing good or as explanatory.

# Answer
> 4 votes
I'm not quite sure about your questions, so i will assume something below first according to common situation.

1. Your prefabs are a group of multiple objects which big enough to contain player character and take the whole screen.
2. Your character are actually moving forward, and the camera following it. (In some case, it could be character and camera remain still and scene moving backward)

## Path Generating

1. At game begin, arrange all prefab instances as one line randomly, like 3,1,2
2. With character moving, get past instance 3 and instance 1 the camera view come to the end of instance 2. At this time, randomly pick a prefab from prefabs except current prefab, which is {3,1} in this case. (you can also include instance 2, and that means you need to allow cloning instance 2, and releasing).
3. Move it (or clone it) to the end of instance 2.

## Randomisation

As a side note since your didn't mention it.

**easy way**: random pick equally each time

**hard way**: design a **Director AI** to make decision, which pretty like someone well prepared a level first and adjust it according to your behavior during playing. It will consider player interest, player emotion, level variety, drama plot.

you may choose some way between these two, depending on your situation.

## Implementation

Here's sample pseudo code for Path Generating

### OnGameBegin

```
Instances = instance(obj) for obj in Prefabs // {1, 2, 3}
Instances.random_sort() // 3, 1, 2
// Here for simplicity, We start from the last one, which is 2
Instances.foreach((instance&, i)=>{instance.setPos(Vec3.X * -i)})

```

### OnUpdate

```
if (currFocusInstance.End - MainCamera.Pos <= 0.5f * ViewScreen.Width):
    //Camera came to the end of current focus instance
    nextInstance = Pick(Instances - {currFocusInstance});
    nextInstance.setBegin(currFoucsInstance.End)

```

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