# Question
Title: Why is my render engine only rendering one frame?
Just for background, I'm designing a soft engine in C# using the SharpDX DirectX wrapper library. I've gotten around to implementing the render engine, and I can render a texture to a face, except it only renders exactly one frame. It renders a triangle once, but on the next draw call, the screen is cleared. Even though I've made sure the render call is still firing every frame, the rendered item goes away, and does not get re-drawn in the next or any subsequent frame.

I think it has something to do with the way I initialize my resources; to minimize shader switching and boost performance, I have my render engine hold a set of pre-defined shader classes. Then, only when it is necessary will the shader access the device context and set the vertex, constant, index, etc. buffers one time when the method `Shader.SetActive()` is called. When the shader needs to render something, it can write directly to the buffers that have been created and set in the `Shader.SetActive()` method, using a method called `UpdateShader()`.

---

Here's the source for `SetActive()`:

```
public override void SetActive(D3D11.Device device, D3D11.DeviceContext context)
{
    /*========================== Set Pointers to GPU Buffers ==========================*/
    // write Matrix data first to constant buffer
    matrixBuffer = new D3D11.Buffer(device, matrixBufferDesc);
    vertexBuffer = new D3D11.Buffer(device, vertexBufferDesc);
    indexBuffer = new D3D11.Buffer(device, indexBufferDesc);

    context.InputAssembler.SetVertexBuffers(0, new D3D11.VertexBufferBinding(vertexBuffer,
    Utilities.SizeOf<VertexPositionTexture>(), 0));
    context.InputAssembler.SetIndexBuffer(indexBuffer, Format.R32_UInt, 0);
    context.VertexShader.SetConstantBuffer(matrixBufferPos, matrixBuffer);
    context.PixelShader.SetShaderResource(0, shaderTexture);

    context.InputAssembler.InputLayout = inputLayout;

    /*========================== set context shaders ==========================*/
    context.VertexShader.Set(vertexShader);
    context.PixelShader.Set(pixelShader);
    context.PixelShader.SetSampler(0, samplerState);

    context.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList;
}

```

Here's the code for UpdateShader():

```
public void UpdateShader(D3D11.Device device, D3D11.DeviceContext context,
    Matrix worldViewProj, VertexPositionTexture[] vpts, int[] indices)
{
    DataStream mappedResource;

    //write to buffers
    context.MapSubresource(matrixBuffer, D3D11.MapMode.WriteDiscard, D3D11.MapFlags.None,
        out mappedResource);
    mappedResource.Write(worldViewProj);
    context.UnmapSubresource(matrixBuffer, 0);

    context.MapSubresource(vertexBuffer, D3D11.MapMode.WriteDiscard, D3D11.MapFlags.None,
        out mappedResource);
    mappedResource.WriteRange(vpts);
    context.UnmapSubresource(vertexBuffer, 0);

    context.MapSubresource(indexBuffer, D3D11.MapMode.WriteDiscard, D3D11.MapFlags.None,
        out mappedResource);
    mappedResource.WriteRange(indices);
    context.UnmapSubresource(indexBuffer, 0);

    context.DrawIndexed(indices.Length, 0, 0);
}

```

---

I think something that happens once in the `SetActive()` method should need to actually happen multiple times, and should be moved to the `UpdateShader()` method, but for the life of me I can't figure out what it is, or even if my reasoning is the correct.

Why is my render engine only rendering one frame?

# Answer
> 1 votes
A few things that I found.

First up don't use the datastream object for writing to buffers because in the long run it will end up killing GC performance(have tested), the best bet for writing to DX buffers is to use the one of the Utilities.Write methods to write to the native memory without having to use\dispose of the datastream.

I think your main issue was that you were only setting all the renderstate once and then drawing but the next frame had no shaders or buffers set to draw with.

I moved all the state changing stuff into your updateshader method as shown below.

I would also pre build all index and vertex buffers rather then doing it each draw call so that you can use the immutable flag on them, I have a mesh class for this that contains all the draw methods and update methods. If you have time you should have a look how XNA has its mesh class setup as I based mine off of that.

```
public override void SetActive(D3D11.Device device, D3D11.DeviceContext context)
{

    // write Matrix data first to constant buffer
    matrixBuffer = new D3D11.Buffer(device, matrixBufferDesc);
    vertexBuffer = new D3D11.Buffer(device, vertexBufferDesc);
    indexBuffer = new D3D11.Buffer(device, indexBufferDesc);
}

public void UpdateShader(D3D11.Device device, D3D11.DeviceContext context, Matrix worldViewProj, VertexPositionTexture[] vpts, int[] indices)
{
   //write to buffers
   // MapSubresource returns a databox that contains the native pointer to the buffers memory and you can write to this like shown below.
   DataBox dbox = _Context.MapSubresource(matrixBuffer, 0,   MapMode.WriteDiscard, MapFlags.None);
   Utilities.Write(dbox.DataPointer, worldViewProj);
   _Context.UnmapSubresource(matrixBuffer, 0);

    dbox = _Context.MapSubresource(vertexBuffer, 0,   MapMode.WriteDiscard, MapFlags.None);
   Utilities.Write(dbox.DataPointer, vpts,0,vpts.count);
   _Context.UnmapSubresource(vertexBuffer, 0);

    dbox = _Context.MapSubresource(indexBuffer, 0,   MapMode.WriteDiscard, MapFlags.None);
   Utilities.Write(dbox.DataPointer, indices,0,indices.count);
   _Context.UnmapSubresource(indexBuffer, 0);

    //Setup Context For Drawing

    // Only Change when you really need to
        context.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList;

    // Per mesh
    context.InputAssembler.SetVertexBuffers(0, new D3D11.VertexBufferBinding(vertexBuffer, Utilities.SizeOf<VertexPositionTexture>(), 0));
    context.InputAssembler.SetIndexBuffer(indexBuffer, Format.R32_UInt, 0);

    // Per Batch
    context.VertexShader.SetConstantBuffer(matrixBufferPos, matrixBuffer);
    context.PixelShader.SetShaderResource(0, shaderTexture);

    context.VertexShader.Set(vertexShader);
    context.PixelShader.Set(pixelShader);

    context.PixelShader.SetSampler(0, samplerState);

    //Draw Per Mesh
    context.DrawIndexed(indices.Length, 0, 0);
}

```

I wanted to try keep your code as close to what you had as I could, happy to edit if you want more info.

Before you go and over engineer you code just have a play with the api I don't think you would have a need for fancy shader classes just yet, you can always just rewrite your code later and refactor along the way.

---
Tags: c#, shaders, rendering, sharpdx
---


title: input arrays in OpenGL vertex Shader

text:
# Question
Title: input arrays in OpenGL vertex Shader
would something like this be valid as an input to a vertex shader?

```
layout (location = 0) in float[6] faceTextureOffsets;

```

I know you can use things like vec3s but for this situation I need an array of 6 floats. I am using a texture atlas and I would like for different sides of the cubes i'm rendering to have different textures and I need a way to be able to change the position in the texture atlas.

# Answer
Use a vec4 and a vec2. You can make two calls to glVertexAttribPointer to feed a float\[6\] from the CPU-side as a vec4 and vec2 in the shader.

```
void glVertexAttribPointer(vec4_index,
    4,
    GL_FLOAT,
    false,
    vertex_size,
    &(my_vertex.faceTextureOffsets[0]));

void glVertexAttribPointer(vec2_index,
    2,
    GL_FLOAT,
    false,
    vertex_size,
    &(my_vertex.faceTextureOffsets[4]));

```

Short for-loops in shaders are usually unrolled and functions inlined by the shader compiler so you can replace an iteration of `for(int i=0; i < 6; ++i){ my_code... }` with a function called 6 times as for example:

```
ProcessSide(0, faceTextureOffsets4.x);
ProcessSide(1, faceTextureOffsets4.y);
ProcessSide(2, faceTextureOffsets4.z);
ProcessSide(3, faceTextureOffsets4.w);
ProcessSide(4, faceTextureOffsets2.x);
ProcessSide(5, faceTextureOffsets2.y);

```

And there *should* be no performance penalty. (Depend on the GPU drivers but most do inline functions and unroll loops.)
> 1 votes

---
Tags: opengl, vertex-shader
---


title: How do I count with input, in Unity?

text:
# Question
Title: How do I count with input, in Unity?
How do I count from 1 to 10? I want to count upwards to 10 when I press C, and count down to 0, when I'm not.

```
void Upload()
{
    int ten;

    if (Input.GetKey(KeyCode.C))
    {
        // count from 0 to 10. 1 2 3 4....
        Debug.Log (" + " + ten);
    }
    else
    {
        // count from 10 to 0. 10 9 8 7....
        Debug.Log (" - " + ten);
    }
}

```

# Answer
There are only some minor basic problems with your code. I would advise following the base scripting tutorials, on the Unity website. They will provide you with a suitable base understanding of both general programming and programming with Unity, so you can comfortably do the little things.

---

### Any variable creates inside of a method will be lost as soon as the method completes.

You've declared `ten` during the `Upload` method. As a result, it is disposed of when `Upload` completes.

Simply declare `ten` as a variable of the actual *class*, and any value you set will persist past the `Upload` method.

### `Input.GetKey` works like "rapid fire", and input should generally come from an `Update` method.

You're using `Input.GetKey` to check for input. This *works*, but it only checks that the key is *being pressed*. Your input updates during the `Update` method, which runs many, many times *every* second; as a result, `GetKey` will return `true` for many frames in a row, even if the user attempts to input the key *once*.

For situations where you require a distinct action every time the user *presses* the button, instead of while the user *holds* the button, use `Input.GetKeyUp` and `Input.GetKeyDown`. Of course, both of these flags return `false` outside of the `Update` method, as they are reset during the same frame as they are first raised. *Ideally, you should get input during your `Update` method*.

### Counting

Counting, itself, is easy. Add to `ten` when you want the number to go up, subtract from `ten` when you want it to go down. At an introductory level, you would probably write `ten = ten + 1` and `ten = ten - 1`, but there is an easier way.

An easy shorthand version is to use the operators `++` and `--`, which automatically add and subtract by 1. `ten ++` will increase the value of `ten` by 1, and vice versa. Want to count by more than 1? The `+=` and `-=` operators take care of greater numbers. `ten -= 5`, for example, will automatically subtract the value of `ten` by 5.

### `Update` will count so quickly that you *won't notice*

You probably want the user to be able to *see* the number counting up and down, as I have mentioned in addressing the use of `Input.GetKey`. Given that counting down is the default action, `Update` will count back to 0 so quickly that you probably will not notice. It will appear as if `ten` drops to 0 almost *immediately*.

We can use the `Time` class to account for time, and apply a *timed* countdown, instead of an immediate countdown. This will probably be the most complicated part of the script, but it is all still fairly standard.

There are many ways you might set up a timer. For this purpose, we are counting between `Update` methods, so I will provide an example of how you might use `Time.deltaTime`.

`Time.deltaTime` gives us the time between the two most recent `Update` methods, in seconds. *From* the `Update` method, it is very reliable.

---

Note that you probably may want to include *holding* the key as an event that *prevents* counting down. As such, I ensure that the additional `GetKey` events are not firing, before moving to the count down. *If this is not* what you want, you can simply replace `else if(!(Input.GetKey(KeyCode.C) || Input.GetKeyUp(KeyCode)))` with `else`.

```
<summary>Our counter</summary>
int ten = 0;
<summary>Time between each count down, in seconds</summary>
public float countDownTimer;
<summary>Current count down timer</summary>
float countDown = countDownTimer;

void Update()
{
    if(Input.GetKeyDown(KeyCode.C))
    {
        // If the user just pressed C, count up.
        ten++;

        if(ten > 10)
        {
            ten = 10;
        }

        // Reset the countdown.
        countDown = countDownTimer;

        Debug.Log("+ : " + ten);
    }
    else if(!(Input.GetKey(KeyCode.C) || Input.GetKeyUp(KeyCode)))
    {
        // If the user is not pressing C,
        // Apply countdown to our timer.
        countDown -= Time.deltaTime;

        // If our timer reaches 0, we have been counting down
        // for long enough to apply subtraction.
        if(countDown <= 0f)
        {
            // Count down and reset countdown timer
            countDown = countDownTimer;
            ten --;

            if(ten < 0)
            {
                ten = 0;
            }

            Debug.Log("- : " + ten);
        }
    }
}

```
> 0 votes

---
Tags: unity
---


title: Unity not opening in Ubuntu

text:
# Question
Title: Unity not opening in Ubuntu
I installed the latest version version of Unity for Linux from the official website, but when I try to launch Unity, it displays a blank dialog box. I waited for a long time, but nothing happens.

---

These are my system specifications. I was running Unity on the same computer, several months ago, using Windows.

* **Model:** Thinkpad R500
* **Processor:** Intel® Core™2 Duo CPU P8600 @ 2.40GHz × 2
* **RAM:** 2Gb DDR3 RAM
* **Storage:** 155Gb HDD
* **Graphics Card:** ATI Mobility Radeon HD 3400 Series 128mb dedicated GFX

---

Why is it doing this? Is there a problem with the latest build? What should I do to fix it?

# Answer
> 3 votes
You report a 128Mb ATI Radeon 3400 HD. While I find that model *did* have the DirectX capabilities required as per the official system requirements page, the Linux version appears to be listed with additional requirements.

> Machines also need a modern graphics card with vendor-supported graphics drivers "Unity on Linux: Release Notes and Known Issues"

Unfortunately, there is no clear definition of "modern graphics card". That said, it is fair to say a 128Mb graphic cars may *not* meet these requirements, in today's standard. The best reference I could find to your reported card lists it as almost 10 years old.

---

***If my computer doesn't support the Linux version, why did it successfully run the Windows version?***

This might be a question for those more versed in operating systems and the core differences, but I have certainly seen this happen, before.

Usually, the issue is just put down to a difference at the driver level. In several cases, I have seen speculation that although Windows *should* be more hardware intensive, it is still far more efficient in managing problems that come up (especially in graphics). As a result, Windows may actually run the "officially not compatible" software at a slower pace, where Linux may just give up and give you a black screen.

***Is there any chance this will change?*** If it is the graphic card, unlikely. That said, it is always worth double checking you have the latest drivers. Sometimes, a driver update can make the difference, albeit only in the few cases where the difference required is minimal.

***Surely we have something more concrete in regards to system requirements?*** Unfortunetly not. I found a single forum entry, which I lost as quickly as I found it, where a Unity developer actually stated that the 3000 series *should* run Unity; but he still mentioned that it probably was not a good idea, as you would be severely limited. To their credit, most system requirement queries are easily answered by simply downloading the free client, and giving it a try.

***Is there anything else I can do?*** I would ultimately suggest *replacing the entire computer*; even without the graphics issues, the rest of your specifications speak of an instance of Unity that is *severely* limited, due to low RAM and a Core DUO CPU. Seriously, I use to test run Unity on faster machines, and I am surprised to hear it ran on Windows.

Failing that, you could submit it as a bug report. I can not say how reliable any feedback will be. The post you link asks users to post their bug report case numbers, if feedback is requires. However, a moderator appears to have locked the thread out, preventing any further posts.

# Answer
> 1 votes
The Linux version of Unity is still far from fully stable, as the Windows & Mac OS X versions are. It's still not recommended to use the Linux build for production purposes, though you may use it for testing, bug reporting and bug fixing.

---
Tags: unity, linux
---


# Question
Title: Direct3D11 Reading from (Static) Index Buffer
Good morning,

I have an Indexbuffer created with usage D3D11\_USAGE\_DEFAULT and CPUAccessFlags 0. Now I want to read data from this buffer regularly (it is a terrain index buffer). But the problem is that I am not allowed to read data from the buffer, because the buffer is not created with the flag D3D11\_CPU\_ACCESS\_READ.

Even if I make the buffer dynamic, I still am not allowed to read from the buffer. This is because the CPUAccessFlag D3D11\_CPU\_ACCESS\_READ is not allowed to be used together with usage D3D11\_USAGE\_DYNAMIC.

Could anyone please give me advice on how to properly read data from a vertex or index buffer in Direct3D11. In my case I want to read data from it frequently.

# Answer
You really don't want to read from buffers because you never know where it is in the pipeline and you will normally end up with +20ms of GPU-CPU synchronization.

Even with a copy to a staging resource marked for reading you will still have a large stall if the buffer is still in use on the GPU before you copy it to the staging resource.

If you need access to the vertex\index buffer then just use the CPU side data you had before you built your buffer and then just reupload with a map\unmap or updatesubresource call if the data has changed.

To read from a buffer that is non readable you first need to setup a staging resource that can not be bound to the pipeline in anyway then you copy your vertex\index buffer to the staging resource and then read from that buffer.

Setting up the staging resource:

```
bufferDescription.BindFlags = BindFlags.None;
bufferDescription.SizeInBytes = TerrainVertex.Stride;   //your terrain vertex size * count
bufferDescription.StructureByteStride = TerrainVertex.Stride;   // your terrain vertex size
bufferDescription.OptionFlags = ResourceOptionFlags.BufferStructured;
bufferDescription.CpuAccessFlags = CpuAccessFlags.Read;
bufferDescription.Usage = ResourceUsage.Staging;

DebugBuffer = _device.CreateBuffer(bufferDescription);

```

Copy the buffer:

```
// You should wait a few frames before you try to use the Debugbuffer as the copy is async and will stall the pipeline if you try to use it before the copy is done by the GPU

_Context.CopyResource(CurrentTerrainVertexBuffer, DebugBuffer);

```

Reading the Staging resource:

```
TerrainVertex[] CPUTerrainData = new TerrainVertex[vertcoun - 1] {};

DataBox dbox = _context.MapSubresource(DebugBuffer, 0, MapMode.Read, Direct3D11.MapFlags.None);
readout(dbox.DataPointer, CPUTerrainData);
_context.UnmapSubresource(DebugBuffer, 0);
dbox = null;

```

I'm using sharpDX but its only a wrapper around nativeDX so you should be able to work out what I'm doing as the naming is very close between sharpDX and nativeDX.

Once again this will be slow so as long as you don't want to do it every frame you should be ok and remember that GPU-CPU sync time is +20ms so do not read from the staging resource until a few frames have passed so you can avoid a stall if the GPU hasn't copied the data yet.
> 3 votes

---
Tags: directx11, index-buffer
---


# Question
Title: Unity - "SetDestination" can only be called on an active agent that has been placed on a NavMesh. UnityEngine.NavMeshAgent:SetDestination(Vector3)
I'm using Unity5 right now. I got this error when try to setDestination.

```
"SetDestination" can only be called on an active agent that has been placed on a NavMesh.
UnityEngine.NavMeshAgent:SetDestination(Vector3)
CompleteProject.EnemyMovement:Update() (at Assets/_CompletedAssets/Scripts/Enemy/EnemyMovement.cs:30)

```

My code.

```
using UnityEngine;
using System.Collections;

namespace CompleteProject
{
    public class EnemyMovement : MonoBehaviour
    {
        Transform player;               // Reference to the player's position.
        PlayerHealth playerHealth;      // Reference to the player's health.
        EnemyHealth enemyHealth;        // Reference to this enemy's health.
        NavMeshAgent nav;               // Reference to the nav mesh agent.

        void Awake ()
        å{
            // Set up the references.
            player = GameObject.FindGameObjectWithTag ("Player").transform;
            playerHealth = player.GetComponent <PlayerHealth> ();
            enemyHealth = GetComponent <EnemyHealth> ();
            nav = GetComponent <NavMeshAgent> ();
        }

        void Update ()
        {
            // If the enemy and the player have health left...
            if(enemyHealth.currentHealth > 0 && playerHealth.currentHealth > 0)
            {
                // ... set the destination of the nav mesh agent to the player.
                nav.SetDestination (player.position);
            }
            // Otherwise...
            else
            {
                // ... disable the nav mesh agent.
                nav.enabled = false;
            }
        }
    }
}

```

Please advice. Thank you.

# Answer
Have you baked a navmesh yet?

It looks like you're in the shooter tutorial. The step right after creating the enemy and adding the NavMeshAgent to it includes creating a Nav Mesh to control it's movement. You'll want to...

* go to Window-\>Navigation on the top menu (I have this window docked next to my inspector)
* Choose the Bake tab
* set up some params (The tutorial has Radius=0.75, Height=1.2 and Step Height=.0.1, and the rest of the settings from the tutorial are gone in Unity 5, as far as I can tell.
* Hit Bake at the bottom to bake the nav mesh.

This should run for a short time, and when it's done, try playing again and see if you get the same error.
> 2 votes

# Answer
I think the following line is causing the issue:

```
nav.enabled = false;

```

Comment it out and try your code again!
> -1 votes

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


title: Comparing Prefabs in a Memory Card Game

text:
# Question
Title: Comparing Prefabs in a Memory Card Game
I need to compare two cards together to check if the two cards is identical. Currently I have a prefabs folder with 18 images which are duplicated in the same folder, so the total cards is 36. How can I make unity identify that 2 cards are the same. Till now I can only click on the Back Prefab and see the card behind it.

Thanks

# Answer
> 0 votes
Just add a script to all of the cards called `Card`, make an ID variable in the script, give a unique ID to each card and compare them to each other.

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


# Question
Title: Pong in assembly waiting for input instead of moving the ball
I am writing pong in assembly x86 with TASM and I have a problem.

The program is waiting to get input from the user to move the paddle (int 16h ah=0h) and while it is waiting the ball and the other paddle doesn't move.

What should I do?

# Answer
Most of the keyboard interrupts that return data from the keyboard buffer (that is, most of the interrupt 16h family) block if there is not actually *in* the keyboard buffer.

What you need to do instead is first check if there's anything in the keyboard buffer. If there is, you can issue `int 16h / AH = 0`. Otherwise just continue with your regular game loop.

`int 16h / AH = 1` can be used to check if there's anything in the buffer. It will set `ZF` to 0 if there's a key available for you to read.
> 5 votes

---
Tags: assembly
---


title: How do I Invert a Guard in GDX-AI?

text:
# Question
Title: How do I Invert a Guard in GDX-AI?
I am trying to define an AI behavior where if a conditional (`MyCondition`) is false, execute the task. I know I can do this as follows:

```
import myCondition?:"tech.otter.something.MyCondition"
import otherTask:"tech.otter.something.OtherTask"

root
  selector
    myCondition? # i.e. if !myCondition then otherTask
    otherTask

```

Now I'd like to use the snazzy guard syntax like so:

```
root
  (myCondition?) otherTask

```

The problem is that I really need otherTask to fire when the guard (myCondition?) is *false*. Is there a way to do this shy of defining a "MyInvertedCondition" task?

# Answer
This can be achieved using decorators which can be read about here. I believe the syntax would be like this: `(invert MyCondition)`.

If that doesn't work you can always use a subtree as your guard. The syntax would then be like this:

```
subtree name:"Invertedguard"
    invert MyCondition?

($Invertedguard)

```
> 3 votes

---
Tags: libgdx, ai, behavior-tree
---


# Question
Title: Fragment processing depends on polygon size?
I just set up some simple vertex/fragment shaders for handling lighting instead of using the openGL calls. I have a few terrain VBOs setup that are drawing a million or so triangles for testing (bunch of random spikey ground). I noticed that if make the spikey ground spikes higher by multiplying all of their heights by 5, I see the FPS drop from about 98hz to about 44hz.

Searching the web, I found https://www.khronos.org/opengl/wiki/Performance which says "Fragment processing takes longer for large polygons than for small ones", which would explain why I see the decrease.

However, I can't find anything that says why. So my question is, why does fragment processing time vary based on the size of the polygons?

# Answer
*"The fragment shader is the OpenGL pipeline stage after a primitive is rasterized. For each sample of the pixels covered by a primitive, a "fragment" is generated."* opengl wiki

Therefore the larger the polygon (actually the larger the rasterized primitive corresponding to that polygon) the more pixels you need to process...
> 1 votes

---
Tags: opengl, shaders, glsl, fragment-shader
---


# Question
Title: Tilling with SDL2 via Clipping - Some bug which is hiding quite well
right at the moment i am writting some code for demonstration purposes. unfortunatly i have an stubborn bug in my code which is invisible to me. The Problem is I am trying to draw a Map. The Map contains information of the tiles which should be visible to the user. So far so good. The Map I use is just an 2D array of Ints, hardcoded into the application. I Translate then this 2D array of ints into an 1D-array which then just stores any visible tile on the screen.

It does somehow work.

The way i am drawing recognize the different tiles. But around the red block of tiles there should orange tiles around it but as you see you see nothing. And this is what freaks me out. the clipping should just work fine but apparently it does not. I cannot figure out why. debugger does not help here unfortunalty.

I would appreciate any help which points out the bug i have here. probably something very stupid.

Here is my code ( https://github.com/Johanneslueke/C---Projekt-AEIT6/blob/master/C%20-%20Projekt%20AEIT6/Tiles.c )

```
#include "Introduction.h"

#define TILE_WIDTH 50
#define TILE_HEIGHT 50
#define TILE_TYPE_RED 0
#define TILE_TYPE_BLUE 1
#define TILE_TYPE_GREEN 2
#define TILE_TYPE_ORANGE 3
#define TILE_TYPE_NONE 4

#define TILE_MAP_WIDTH 10
#define TILE_MAP_HEIGHT 10

typedef struct {
SDL_Rect Outlines;
int      Type;
}Tile;

Tile TileClips[4];
SDL_Texture* TileTex = NULL;

Tile initTile(int x, int y, int Type);
SDL_Rect getTileOutlines(Tile* tile);
int getTypeOfTile(Tile* tile);

void render(int x, int y, SDL_Texture* tex, SDL_Rect* clip, SDL_Renderer* renderer)
{

   //Set rendering space and render to screen
   SDL_Rect renderQuad = { x, y, 0, 0 };

   //Set clip rendering dimensions
   if (clip != NULL)
   {
        renderQuad.w = clip->w;
        renderQuad.h = clip->h;
   }
    else abort();;

    //Render to screen       /--------/ /TargetAreaOnScreen/
    SDL_RenderCopy(renderer, tex, clip, &renderQuad);
 }

void RenderTileMap(Tile* Tiles, SDL_Texture* TileSheet, SDL_Rect* TileClips, SDL_Renderer* renderer) {

    for (int i = 0; i < TILE_MAP_WIDTH*TILE_MAP_HEIGHT; i++)
    {
        int x = getTileOutlines(&Tiles[i]).x; //Position on the Screen
        int y = getTileOutlines(&Tiles[i]).y;
        int type = getTypeOfTile(&Tiles[i]);
        SDL_Rect clip = TileClips[type]; // Position of the tile on the TileSheet

        render( x, //Position of the tile
            y, //
            TileSheet,                    //Source of the Tile
            &clip,
        renderer);
    }

    }

int main(int argc, char* argv[]) {

    TileClips[TILE_TYPE_BLUE].Outlines.h = TILE_HEIGHT;
    TileClips[TILE_TYPE_BLUE].Outlines.w = TILE_WIDTH;
    TileClips[TILE_TYPE_BLUE].Outlines.x = 0;
    TileClips[TILE_TYPE_BLUE].Outlines.y = 0;

    TileClips[TILE_TYPE_RED].Outlines.h = TILE_HEIGHT;
    TileClips[TILE_TYPE_RED].Outlines.w = TILE_WIDTH;
    TileClips[TILE_TYPE_RED].Outlines.x = 50;
    TileClips[TILE_TYPE_RED].Outlines.y = 0;

    TileClips[TILE_TYPE_GREEN].Outlines.h = TILE_HEIGHT;
    TileClips[TILE_TYPE_GREEN].Outlines.w = TILE_WIDTH;
    TileClips[TILE_TYPE_GREEN].Outlines.x = 0;
    TileClips[TILE_TYPE_GREEN].Outlines.y = 50;

    TileClips[TILE_TYPE_ORANGE].Outlines.h = TILE_HEIGHT;
    TileClips[TILE_TYPE_ORANGE].Outlines.w = TILE_WIDTH;
    TileClips[TILE_TYPE_ORANGE].Outlines.x = 50;
    TileClips[TILE_TYPE_ORANGE].Outlines.y = 50;

    int TileMap[TILE_MAP_WIDTH][TILE_MAP_HEIGHT] = {
    { TILE_TYPE_ORANGE ,TILE_TYPE_ORANGE ,TILE_TYPE_ORANGE ,TILE_TYPE_ORANGE ,TILE_TYPE_ORANGE ,TILE_TYPE_ORANGE ,TILE_TYPE_ORANGE ,TILE_TYPE_ORANGE ,TILE_TYPE_ORANGE ,TILE_TYPE_ORANGE },//0
    { TILE_TYPE_ORANGE ,TILE_TYPE_RED, TILE_TYPE_RED, TILE_TYPE_RED, TILE_TYPE_RED, TILE_TYPE_RED, TILE_TYPE_RED, TILE_TYPE_RED, TILE_TYPE_RED, TILE_TYPE_ORANGE },//1
    { TILE_TYPE_ORANGE ,TILE_TYPE_RED, TILE_TYPE_RED, TILE_TYPE_RED, TILE_TYPE_RED, TILE_TYPE_RED, TILE_TYPE_RED, TILE_TYPE_RED, TILE_TYPE_RED, TILE_TYPE_ORANGE },//3
    { TILE_TYPE_ORANGE ,TILE_TYPE_RED, TILE_TYPE_RED, TILE_TYPE_RED, TILE_TYPE_BLUE, TILE_TYPE_RED, TILE_TYPE_RED, TILE_TYPE_RED, TILE_TYPE_RED, TILE_TYPE_ORANGE },//4
    { TILE_TYPE_ORANGE ,TILE_TYPE_RED, TILE_TYPE_RED, TILE_TYPE_RED, TILE_TYPE_BLUE, TILE_TYPE_RED, TILE_TYPE_RED, TILE_TYPE_RED, TILE_TYPE_RED, TILE_TYPE_ORANGE },//5
    { TILE_TYPE_ORANGE ,TILE_TYPE_RED, TILE_TYPE_RED, TILE_TYPE_RED, TILE_TYPE_BLUE, TILE_TYPE_RED, TILE_TYPE_RED, TILE_TYPE_RED, TILE_TYPE_RED, TILE_TYPE_ORANGE },//6
    { TILE_TYPE_ORANGE ,TILE_TYPE_RED, TILE_TYPE_RED, TILE_TYPE_GREEN, TILE_TYPE_RED, TILE_TYPE_RED, TILE_TYPE_RED, TILE_TYPE_RED, TILE_TYPE_RED, TILE_TYPE_ORANGE },//7
    { TILE_TYPE_ORANGE ,TILE_TYPE_RED, TILE_TYPE_RED, TILE_TYPE_RED, TILE_TYPE_RED, TILE_TYPE_RED, TILE_TYPE_RED, TILE_TYPE_RED, TILE_TYPE_RED, TILE_TYPE_ORANGE },//8
    { TILE_TYPE_ORANGE ,TILE_TYPE_ORANGE ,TILE_TYPE_ORANGE ,TILE_TYPE_ORANGE ,TILE_TYPE_ORANGE ,TILE_TYPE_ORANGE ,TILE_TYPE_ORANGE ,TILE_TYPE_ORANGE ,TILE_TYPE_ORANGE ,TILE_TYPE_ORANGE },//9
};

Tile TileArray[TILE_MAP_WIDTH*TILE_MAP_HEIGHT];
for (int i = 0,k=0; i < TILE_MAP_WIDTH; i++)
    for (int j = 0; j < TILE_MAP_HEIGHT; j++)
    {
        switch (TileMap[i][j]) {
        case TILE_TYPE_BLUE:
            TileArray[k++] = initTile(j*TILE_WIDTH, i*TILE_HEIGHT, TILE_TYPE_BLUE);
            break;
        case TILE_TYPE_RED:
            TileArray[k++] = initTile(j*TILE_WIDTH, i*TILE_HEIGHT, TILE_TYPE_RED);
            break;
        case TILE_TYPE_GREEN:
            TileArray[k++] = initTile(j*TILE_WIDTH, i*TILE_HEIGHT, TILE_TYPE_GREEN);
            break;
        case TILE_TYPE_ORANGE:
            TileArray[k++] = initTile(j*TILE_WIDTH, i*TILE_HEIGHT, TILE_TYPE_ORANGE);
            break;
        case TILE_TYPE_NONE:
            TileArray[k++] = initTile(j*TILE_WIDTH, i*TILE_HEIGHT, TILE_TYPE_NONE);
            break;
        }

    }

if (!init()) {

}

TileTex = loadImage("tiles.bmp", gRenderer);
while (!quit)
{
    SDL_Event e;
    //Handle events on queue
    while (SDL_PollEvent(&e) != 0)
    {
        //User requests quit
        if (e.type == SDL_QUIT)
        {
            quit = TRUE;
        }
    }

    //Clear screen
    SDL_RenderClear(gRenderer);

    //Render texture to screen
    //SDL_RenderCopy(gRenderer, Tex, NULL, NULL);
    RenderTileMap(TileArray, TileTex, TileClips, gRenderer);

    //Update screen
    SDL_RenderPresent(gRenderer);
}

return 0;

}

Tile initTile(int x, int y, int Type) {
Tile t;
t.Outlines.x = x;
t.Outlines.y = y;
t.Outlines.w = TILE_WIDTH;
t.Outlines.h = TILE_HEIGHT;
t.Type = Type;
return t;
}

SDL_Rect getTileOutlines(Tile* tile) {
return tile->Outlines;
}
int getTypeOfTile(Tile* tile) {
return tile->Type;
}

```

# Answer
So, I have found my bug....

I accidently used my own defined struct "Tiles" to store the data for the clipping. because how C layout structs in memory i could use the struct Tiles as argument for my renderfunction which expectet an pointer of type SDL\_Rect. Nasty little bug...

on my respository on github you can find the corrected version of the code!!!
> 0 votes

---
Tags: tiles, tilemap, sdl2
---


# Question
Title: Can I use Havok Physics for free in my game?
I found out that Microsoft purchased the Havok physics engine. Where can I get it for Windows Visual Studio 2015 Community?

I tried to look around, but I could not find anything for the latest version. There are no download links at both the official website, nor on the Microsoft site.

What do I need to do to use Havok in my own game?

# Answer
> 5 votes
A number of years ago, when Havok was owned by Intel, they offered a binary distribution for Windows. Intel sponsored this as a marketing tool to help promote the sale of Intel processors, and to fight the idea of GPU-accelerated physics such as PhysX (which leverages NVidia's CUDA).

When Microsoft purchased Havok, they discontinued the program as they surely felt it was not in their best interest to give the product away for free.

As a result, the only way to use Havok is to purchase it. This is done by contacting Havok, and entering into negations with them.

In contrast, a product like Bullet is free for use. It might be a better option for you now that Havok is unavailable.

# Answer
> 2 votes
Havok is a product you need to purchase. You can't just go to a website and download it until you've become a registered, licensed Havok developer.

You can contact Havok's sales team to begin this process via their Contact Us page.

---
Tags: physics, havok
---


title: Non-existent instance in Game Maker

text:
# Question
Title: Non-existent instance in Game Maker
I'm currently trying to make the fire object (created by the fireball) stick to the enemy, by specifying the enemy type and its id. I'm getting the following error:

"Unable to find any instance for object index '-4' name undefined". Here's my fireball \[collision with enemy\] code:

```
var sp=other.speed
var dir=other.direction
var oi=other.id
var on=object_get_name(other)
with (instance_create(other.x-lengthdir_x(new_push_amount, pd),other.y-lengthdir_y(new_push_amount, pd),fire))
{
speed = sp
direction = dir
enemyid = oi
enemyname=on
}

```

And here is the Create,

```
enemyname = ""
enemyid = 0

```

and the Step events of fireball:

```
speed = instance_find(enemyname,enemyid).speed
direction = instance_find(enemyname,enemyid).direction

```

Maybe I'm using the wrong functional to get the instance... In any case, help would be really appreciated!

# Answer
First thing. `object_get_name` needs object index, not instance index, like this:

```
var on = object_get_name(other.object_index); // or maybe (other.id).object_index, I don't have ability for check it now

```

Second. You must check what `instance_find` returned. Because instance may not exists.

```
var obj = instance_find(enemyname, enemyid);
if instance_exists(obj)
{
    speed = obj.speed;
    direction = obj.direction;
}

```

Third. `instance_find` needs `object_index`, not an object's name (which is a string) and index (which is not equal `id`).

I don't understand why you don't use just `id` of the instance.

```
var spd = other.speed;
var dir = other.direction;
var inst_id = other.id;

with instance_create(other.x-lengthdir_x(new_push_amount, pd), other.y-lengthdir_y(new_push_amount, pd), fire)
{
    speed = spd;
    direction = dir;
    enemyid = inst_id;
}

```

Or same, but less lines:

```
var obj = instance_create(other.x-lengthdir_x(new_push_amount, pd), other.y-lengthdir_y(new_push_amount, pd), fire);
obj.speed = other.speed;
obj.direction = other.direction;
obj.enemyid = other.id;

```

And `Step End` event (not `Step`, otherwise there will be a lag):

```
if instance_exists(enemyid)
{
    speed = enemyid.speed;
    direction = enemyid.direction;
}
else
{
    instance_destroy(); // ? I don't know, is need you it or not
    // but anyway don't forget to destroy object
}

```
> 0 votes

---
Tags: 2d, software-engineering, game-maker
---


# Question
Title: How to control a 2d charter in an top-down android game with the standard joystick?
So I'm building a 2d top-down game and I need to control my character using unity cross-platform standard asset single joystick.
The problem is with the rotation, I don't want to use the dual-stick for some idea related reasons and the designs and the game mechanics that was considered for this game.
So I want the character to have the same rotation as the joystick and since the joystick only has the horizontal and the vertical axies it's hard to get a descent rotation.
So any ideas how to do this? if you need further clarification let me know.

# Answer
In the mathf class there is a function called Atan2, which is exactly what is needed here.
so all that is needed to be done is to use the mobile single stick control in the cross-platform standard assets and get the Horizontal and Vertical axis from that and use the Atan2 to get the radiant and then turn it to degrees and use it to set the z angle of the player.

```
Player.transform.eulerAngles = new Vector3(0, 0, -(Mathf.Atan2(CrossPlatformInputManager.GetAxis("Horizontal"), CrossPlatformInputManager.GetAxis("Vertical")) * Mathf.Rad2Deg));

```

or for simplicity :

```
float Haxis = CrossPlatformInputManager.GetAxis("Horizontal");
float Vaxis = CrossPlatformInputManager.GetAxis("Vertical");
float Zangle = Mathf.Atan2(Haxis, Vaxis) * Mathf.Rad2Deg;
Player.transform.eulerAngles = new Vector3(0, 0, -Zangle);

```
> 0 votes

---
Tags: unity, 2d, android, rotation, joystick
---


# Question
Title: Does decreasing rendering resolution also decrease the amount of polygons in my 3d models?
When lowering my game resolution I reduce the pixel count of the final rendered output image, does the 3d model I use to render the final image also lose polygons?

# Answer
No your meshes do not lose polygons. Only the amount of fragments generated by the polygons will be reduced. If you think about it, where would the polygons go? You still need all of them to make sure you have correct result when rendering your scene. Even the sub-pixel sized polygons are usually included in final image.

In some cases though, the rendering can be optimized a bit to find and discard polygons that are way too small to be affecting the rendering result. But in these cases the mesh data should be pre-processed before rendering.
> 3 votes

---
Tags: 3d, resolution, 3d-modeling
---


# Question
Title: There any way to insert images inside the code (just for comprehesion) in any IDE compatible with Game Engine Unity3D (Monodevelop for example)?
**M**y code has a lot of geometry codes, thinks that shouldn't be represented just by comments I don't know if it exists, but should be fine to insert images like png in the middle of codes explaning that math behind, just in case I forget what any classes/method/lines do in future. Thanks.

# Answer
Other than ASCII art? No, not that I'm aware of. The closest you could get would be documentation generators like **doxygen** that will create documentation files from comments, which might also include markup for images.

Besides that you could link to images using URLs, which are clickable in most editors and/or use markdown for basic formatting.
> 3 votes

---
Tags: unity, geometry, image, ide, monodevelop
---


# Question
Title: Difficulty understanding integration of Lua with C++ Game Engine
I'm starting work with the Allegro C++ library to get some lower level game development experience after working mostly with Unity. I've read about how Lua is a popular scripting language choice for game developers, but I have never used it before. I've been trying to work through how Lua might be integrated with a game engine in my head, and I've ran into some conceptual problems.

I imagine the simple scenario where I have a block that I want to move to the left at a certain speed for 2 seconds. I imagine that something like the Draw() method would sit nicely in the game engine in C++, where the actual command to move the block, being a fairly specific one, would originate in Lua.

I have trouble imagining where the transition between the languages is. I've read that calling to Lua every frame of the Game Loop isn't very performant, so that means that unless Lua can keep track of the movement timer asynchronously and interrupt C++ execution when the timer runs out, I would have to track the timer in the C++ engine. I would need a method like MoveForSeconds(direction, time) implemented in C++. At that point, Lua calling my MoveForSeconds() method is little more than a passthrough, and seems to defeat the purpose of using a scripting language.

What am I misunderstanding here? Or is my example too myopic, and the uses of Lua become more evident on a larger scale?

Thanks

# Answer
A scriptable engine has 3 parts, the code, an interface and the script.

Let's say you want to be able to write scripts for entities. In code you create an entity component system to easily add scripts as components.

The interface is a *simple* lua interpreter with custom functions/objects to modify the entity (things like a way to get other components and to modify them).
> 1 votes

---
Tags: c++, lua
---


# Question
Title: How can I scale/zoom to a point in canvas in the game?
I am using html5 canvas to build a MMO game. When I scale my background by default it scales to `(0, 0)` which is the top left corner of the background. If I have other sprites on the screen they all will look like they are shifting to the bottom right a little bit. Suppose my sprite(player) is at `(x,y)` of the map and it is placed center on the canvas.How can I make the background scale or zoom to `(x,y)` instead of `(0,0)`? Its world position is `(x,y)` but its screen position is always `(canvas.width / 2, canvas.height / 2)`. I think in this way the sprites around my player wouldn't shift their position to unexpected places. But I don't know how to do this.

# Answer
> 0 votes
You first need to save the context (to be able to set it back later) then translate (x; y) to be in (0; 0)

```
ctx.translate(x, y);

```

Then you zoom in:

```
ctx.scale(2; 2);

```

The canvas' width and height then becomes half as much, so to put (x; y) in the center, we need to translate back by (width / zoom; height / zoom)

```
ctx.translate(-c.width / 4, -c.height / 4);

```

You should store the zoom levek in a variable and increase it when you want to zoom in

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


# Question
Title: Can't figure out how to create texture from a font-surface
I can't seem to be able to render my font, it crashes and I can't figure out why. It seems to load the font correctly, but the parts relating to surface crashes.

Why does my texture crash?

---

Here is the code bits relating to it. SDL2 and TTF has been initialized properly.

```
        TTF_Font *arial;
        SDL_Color mm_txt_color = {255, 255, 255, 0};
        SDL_Texture *myTexture;
        SDL_Rect myRect;
        load_font(MM_FONT_ARIAL, 18,  &arial);

        get_text_and_rect(0, 0, "Exit", arial, &myTexture, &myRect);

int load_font(char *filepath, int size, TTF_Font **font)
{
    (*font) == TTF_OpenFont(filepath, size);
    if((*font) == NULL ) {
        printf("ERROR: Failed to load font: %s.\n", filepath);
        return FAILURE;
    }
    return SUCCESS;
}

    void get_text_and_rect(int x, int y, char *text, TTF_Font *font,
        SDL_Texture **texture, SDL_Rect *rect)
    {
        int text_width;
        int text_height;
        SDL_Surface *surface;
        SDL_Color textColor = {255, 255, 255, 0};

        surface = TTF_RenderText_Solid(font, text, textColor);
        *texture = SDL_CreateTextureFromSurface(renderer, surface);
        text_width = surface->w;
        text_height = surface->h;
        SDL_FreeSurface(surface);
        rect->x = x;
        rect->y = y;
        rect->w = text_width;
        rect->h = text_height;
    }

```

# Answer
Using printf("%s\n", TTF\_GetError()); i got the answer that the font hadn't been loaded correctly, so you provided the correct answer, nothing with the code but just the entered filepath on my part.
> 0 votes

---
Tags: c, sdl2, ttf
---


# Question
Title: How can a BabylonJS FreeCamera be rotated from code?
Say I have a FreeCamera in a BabylonJS 3D world. How could I rotate that camera from program code? Or, more specifically, how might I bind camera rotation (not movement, which I know how to bind to WASD) to the arrow keys so that gamers without a mouse would not find it too troublesome to use? Is this even possible?

Thanks in advance!

# Answer
> 1 votes
FreeCamera extends TargetCamera, so it has a rotation variable. You can change this to rotate the camera around.

---
Tags: 3d, browser-based-games
---


# Question
Title: How can I change Box2D bodyDef type of an object after adding it to the world in Libgdx?
I have a basic 2d square class that has it's body type set to a Static Body. After the player presses a button on the UI I want to change the body type to a Dynamic Body.

When I change the object to a Dynamic Body within the render method nothing happens.

How can I change the Body Type so that it updates on the screen?

```
public void show() {
    ...
    s0 = new Square(-10, -20, 5, 5, 3);
    ground = world.createBody(s0.bodyDef);
    ground.createFixture(s0.fixtureDef);
    ground.setUserData(s0.sprite);
    s0.shape.dispose();
    ...
}

public void render(float delta) {
    ...
    if (ready) {
        s0.bodyDef.type = BodyType.DynamicBody;
    }
    ...
}

```

# Answer
The way you do your update of type is wrong, here you will re-set the type at each frame once *ready* is true.

Have you try this ?

```
s0.setBodyType(BodyType.DynamicBody)

```

EDIT : See comments below, you should update the body created from your world instead of the shape which is just a kind of prefab to create your body to your world
> 1 votes

---
Tags: java, libgdx, box2d
---


# Question
Title: OnCollisionEnter only triggering if colliding object starts inside collider
Despite the absurdly high number of "OnCollisionEnter not working" threads around the internet, no one else seems to have had this specific problem.

To start off with, I have a spherical "shield" object around my ship, which has a shader designed to give off impact effects when hit by an object. To trigger the shader impact effect, you need to give it the position from which do the effect. So, the easiest way to do this is to give the shield a Collider and, whenever OnCollisionEnter is called, it sends the contact.point details to the shader. That's not the difficult part. The part that isn't working is that **OnCollisionEnter is not being called when the laser bolt fired at the shield actually collides with the shield**.

Both the shield and the laser bolt have Sphere colliders, both are **not** triggers. Only the shield has a rigidbody, which is **not** kinematic.

```
void OnCollisionEnter (Collision collision) {
    Debug.Log (Time.time);
    if (collision.transform.tag == "Impact") {
        Debug.Log ("go");
        //Does the shader stuff
        }
    }
}

```

That script is attached to the shield object. Not only is "go" never being logged, but neither is the Time, so OnCollisionEnter is not being called.

The odd thing about this scenario is that, OnCollisionEnter ***will*** be called by objects that ***begin*** inside the shield's collider - so if I start the laser bolt inside the shield, then the function gets called as usual. But when I start the laser outside the shield and Translate it into the shield, nothing happens. For the life of me, I can not work out what's going wrong with it.

# Answer
> 1 votes
You would need to add a Rigidbody, you constrain the simulation in all the axis for the rigidbody and use MovePosition from it instead of using translate.

https://docs.unity3d.com/ScriptReference/Rigidbody.MovePosition.html

---
Tags: unity, collision-detection
---


# Question
Title: Are TestFlight apps the same as the finished product?
This may be an obvious question, but to me it is a little unclear. I built an app using PhoneGap. While testing with PhoneGap Desktop and the associated app it was pretty obvious that this was just a testing environment. For example, any check to see if it was an iOS device would return false even though the app was up and running on my iPhone. Also there were some strange positioning issues between what I saw in the browser vs. what I saw on the app.

So, I finished building the app and packed it and uploaded it as a beta app sent via TestFlight to my phone. I was pleased to see I was now passing the iOS checks and some positioning errors were gone. I am curious if I can conclude for sure if I fix any issues to where it looks good in the testflight app it will look good with the real published app or if testflight too uses some sort of test-web-wrapper?

tl:dr; I'm going to guess and check my positioning via the TestFlight App, if it looks good there will it look good in the wild?

# Answer
Yes, you can use TestFlight to make sure your app is as it should be if you are using the same build/codebase for the release application. If you ask me, it shouldn't matter though if you used PhoneGap or some other platform to send out the iOS builds. I have been using HockeyApp and TestFlight together to test iOS builds from Unity and have never noticed any differences. The main reason to use both is to have different audiences on each testing/distribution platform.
> 1 votes

---
Tags: ios, testing, beta
---


title: Matching game difficulty

text:
# Question
Title: Matching game difficulty
I'm currently making a matching game where the player is given a color or image type and the player has to click on all of the matching colors of images as fast as possible. My problem is how would I go about making a difficulty curve instead of just randomly generating what the next situation will be.

There's a link down below to show the first version of the game I made a while ago. As you can see the new scenario is chosen randomly and one scenario can be harder than the other with no thought of progression. What I want this time is for the game to progress over-time. So, the more of these "scenarios" a player does the more difficult it will get.

https://www.youtube.com/watch?v=sa2mtpv7RzA

# Answer
> 2 votes
Some ideas you can use to change the difficulty:

1. Change the **available time** to solve the puzzle
2. Add a **number of mistakes allowed** before losing, or every mistake can reduce the available time
3. Play with the **colors** of the images. If all different images have different color, it is pretty easy, but if they all have the same color it becomes difficult
4. Have very different **shapes** in easy mode, and really similar shapes in hard mode
5. Work on some hard **transitions** between levels

Then all you have to do is keep some `difficulty` variable that you can increment at each level and use this variable to generate your level.

---
Tags: game-design, difficulty
---


title: Rotating a Row of Textures

text:
# Question
Title: Rotating a Row of Textures
**Preface**: In Linux, using C++11, SDL2, GLEW, and OpenGL.

Hello Ladies/Gents,

I am reaching out as I'm stuck on a fairly simple problem that a decade out of school has further hindered. Specifically, I am able to draw a single texture, rotate, grow, extend as I see fit without any real issue. The issue comes when I choose to repeat the texture (at original size or modified size). I am having the hardest time rotating the boxes as well. My debug box rotates without issue, but it is a set of indices.

Could any of you magnificent people offer any pointers or suggestions on how to go about this? I've included the related code bits below.

This is *drawRepeat*, which handles taking a single texture and it's size (destRect.z = width, destRect.w = height), then repeating through the sizeBounds

```
void SpriteBatch::drawRepeat(const glm::vec4& destRect, const glm::vec4& uvRect, const glm::vec4& sizeBounds, GLuint texture, float depth, const ColorRGBA8& color, float angle) // angle in radians
{
    // fail without info provided
    if(!m_screenHeight || !m_screenWidth || !m_scale) { GameEngine101::fatalError("No screen width/height or scale specified for drawRepeat!"); }

    int x_iterations = static_cast<int>(sizeBounds.z / destRect.z);
    int y_iterations = static_cast<int>(sizeBounds.w / destRect.w);

    // tmp variables
    glm::vec4 tmpDestRect = glm::vec4(0.0f);

    // create glyphs
    for(uint ix = 0; ix < x_iterations; ix++)
    {
        tmpDestRect = destRect;
        tmpDestRect.x = destRect.x + ( destRect.z * ix ); // something else needs to happen here?

        for(uint iy = 0; iy < y_iterations; iy++)
        {
            tmpDestRect.y = destRect.y + ( destRect.w * iy ); // something else needs to happen here?
            if(angle != 0.0f) { m_glyphs.emplace_back(tmpDestRect, uvRect, texture, depth, color, angle); }
            else { m_glyphs.emplace_back(tmpDestRect, uvRect, texture, depth, color); }
        }
    }
}

```

This is the constructor for **Glyph** for rotating textures. Below it is the struct for **Vertex** and the function for *rotatePoint*.

```
Glyph::Glyph(const glm::vec4& destRect,const glm::vec4& uvRect, GLuint Texture, float Depth, const ColorRGBA8& color, float angle) : texture(Texture), depth(Depth)
{
    glm::vec2 halfDimensions(destRect.z / 2.0f, destRect.w / 2.0f);

    // get points centered at origin
    glm::vec2 tl(-halfDimensions[0], halfDimensions[1]); // top left
    glm::vec2 bl(-halfDimensions[0], -halfDimensions[1]); // bottom left
    glm::vec2 tr(halfDimensions[0], halfDimensions[1]); // top right
    glm::vec2 br(halfDimensions[0], -halfDimensions[1]); // bottom right

    // rotate the points
    tl = rotatePoint(tl, angle) + halfDimensions;
    bl = rotatePoint(bl, angle) + halfDimensions;
    tr = rotatePoint(tr, angle) + halfDimensions;
    br = rotatePoint(br, angle) + halfDimensions;

    // top left
    topLeft.setPosition(destRect.x + tl.x, destRect.y + tl.y);
    topLeft.setUV(uvRect.x, uvRect.y + uvRect.w);
    topLeft.color = color;
    // bottom left
    bottomLeft.setPosition(destRect.x + bl.x, destRect.y + bl.y);
    bottomLeft.setUV(uvRect.x, uvRect.y);
    bottomLeft.color = color;
    // top right
    topRight.setPosition(destRect.x + tr.x, destRect.y + tr.y);
    topRight.setUV(uvRect.x + uvRect.z, uvRect.y + uvRect.w);
    topRight.color = color;
    // bottom right
    bottomRight.setPosition(destRect.x + br.x, destRect.y + br.y);
    bottomRight.setUV(uvRect.x + uvRect.z, uvRect.y);
    bottomRight.color = color;
}

struct Vertex
{
    Vertex() {}
    ColorRGBA8 color = COLOR_WHITE; // 4 bytes for R G B A
    glm::vec2 pos = glm::vec2(0.0f);
    glm::vec2 uv = glm::vec2(0.0f); // UV texture coordinates

    void setPosition(float x, float y)
    {
        pos.x = x;
        pos.y = y;
    }

    void setColor(GLubyte R, GLubyte G, GLubyte B, GLubyte A)
    {
        color.r = R;
        color.g = G;
        color.b = B;
        color.a = A;
    }

    void setUV(float u, float v)
    {
        uv[0] = u;
        uv[1] = v;
    }

static glm::vec2 rotatePoint(glm::vec2 pos, float angle)
{
    glm::vec2 newVec;
    newVec.x = pos.x * cos(angle) - pos.y * sin(angle);
    newVec.y = pos.x * sin(angle) + pos.y * cos(angle);
    return newVec;
}

```

Below is an example of a single texture (white box is my debug box):

Next a single texture with rotation:

I have made a comment in the first code block for drawRepeat where I believe the change needs to occur. Next post will contain the repeated textures and rotation. Lack of "reputation" prevents me from posting....

---

EDIT:

**Glyph** constructor without rotation:

```
Glyph::Glyph(const glm::vec4& destRect, const glm::vec4& uvRect, GLuint Texture, float Depth, const ColorRGBA8& color) : texture(Texture), depth(Depth)
{
    // top left
    topLeft.setPosition(destRect.x, destRect.y + destRect.w);
    topLeft.setUV(uvRect.x, uvRect.y + uvRect.w);
    topLeft.color = color;
    // bottom left
    bottomLeft.setPosition(destRect.x, destRect.y);
    bottomLeft.setUV(uvRect.x, uvRect.y);
    bottomLeft.color = color;
    // top right
    topRight.setPosition(destRect.x + destRect.z, destRect.y + destRect.w);
    topRight.setUV(uvRect.x + uvRect.z, uvRect.y + uvRect.w);
    topRight.color = color;
    // bottom right
    bottomRight.setPosition(destRect.x + destRect.z, destRect.y);
    bottomRight.setUV(uvRect.x + uvRect.z, uvRect.y);
    bottomRight.color = color;
}

```

More-recent *drawRepeat*:

```
void SpriteBatch::drawRepeat(const glm::vec4& destRect, const glm::vec4& uvRect, const glm::vec4& sizeBounds, GLuint texture, float depth, const ColorRGBA8& color, float angle) // angle in radians
{
    // fail without info provided
    if(!m_screenHeight || !m_screenWidth || !m_scale) { GameEngine101::fatalError("No screen width/height or scale specified for drawRepeat!"); }

    int x_iterations = static_cast<int>(sizeBounds.z / destRect.z);
    int y_iterations = static_cast<int>(sizeBounds.w / destRect.w);

    // tmp variable
    glm::vec4 tmpDestRect = destRect;

    // rotate by angle, converted from radians to degrees, on the z-axis
    glm::mat4 groupRotation;
    groupRotation = glm::rotate(groupRotation, glm::degrees(angle), glm::vec3(0.0f, 0.0f, 1.0f));

    GLint pUniformM = m_glsl->getUniformLocation("model");
    glUniformMatrix4fv(pUniformM, 1, GL_FALSE, &groupRotation[0][0]);

    // create glyphs
    for(uint ix = 0; ix < x_iterations; ix++)
    {
        tmpDestRect.x = destRect.x + ( destRect.z * ix ); // set X position

        for(uint iy = 0; iy < y_iterations; iy++)
        {
            tmpDestRect.y = destRect.y + ( destRect.w * iy ); // set Y position

            // rotate on angle, if exists
            //if(angle != 0.0f) { m_glyphs.emplace_back(tmpDestRect, uvRect, texture, depth, color, angle); }
            //else { m_glyphs.emplace_back(tmpDestRect, uvRect, texture, depth, color); }
            m_glyphs.emplace_back(tmpDestRect, uvRect, texture, depth, color);
        }
    }
}

```

# Answer
You need to rotate the images as a unit instead of separately. This means, you need to apply the rotation after local transformation. Like this:

```
vPosition = singleImageRotation * cornerPosition; // Probably unnecessary step
vPosition = singleImagePosition + vPosition;
vPosition = groupRotation * vPosition;
vPosition = groupPosition + vPosition;

```

In this example the `singleImageRotation` and `groupRotation` are matrices that rotates your vertices. Also `singleImagePosition` is the image position in relation to the group's pivot point.
> 1 votes

---
Tags: opengl, c++, sdl2, linux, glew
---


# Question
Title: How do I decrease the scale of an instanced node or scene?
I'm trying to decrease size of instanced `RigidBody2D` scene, through code. With `scale()`, I'm trying to decrease the size of the image/sprite that's attached to the `RigidBody2D`. The problem is, it's not working.

No matter how much I try to scale down, the size of the blood drop circle remains the same.

---

```
const blood_druple_scn = preload("res://Scenes/blood.tscn")

func spawnBlood():
    var newBlood = Blood_druple_scn.instance()

    rotationAdd = rotationAdd + 30

    if(switchBloodSize == 0):
        set_scale(Vector2(2,1)) //This part is my problem
        print("blood size: ", newBlood.get_scale())
        add_child(newBlood)
        switchBloodSize = 1

    elif(switchBloodSize == 1):
        newBlood.scale(Vector2(0.5,0.5)) //This part is my problem
        print("Blood size: ", newBlood.get_scale())
        add_child(newBlood)
        switchBloodSize = 0

    newBlood.set_pos(Vector2(100,100))
    rotate(rotationAdd)

```

As you can see, I have two different `if` conditions, each with a different `scale()` and size. Sadly, both remain the same size. The strange part is that it does display the scale values as been altered, yet the `newBlood` instance is not visually changing. Why is this?

# Answer
> 4 votes
According to this issue https://github.com/godotengine/godot/issues/179 you cannot change rigid bodies scale. What is suggested is to scale your nodes instead, for example:

```
var sprite = newBlood.get_node("./Sprite")
sprite.scale(Vector2(0.5,0.5))

```

This "limitation" only occurs in Rigid and Character modes, by the way.

---
Tags: godot
---


# Question
Title: Why do so many game websites end in game.com?
This is my first question here, so please tell me if I'm doing something wrong :)

I've recently noticed that many game websites end in 'game.com' (www.helloneighborgame.com, www.gunpointgame.com, etc). Is there a specific reason for this, or is it just a coincidence?

I've also noticed that many of these titles are usually indie games. Is it a common thing to do?

# Answer
You can perform a whois search to see if and when a domain got registred.

helloneighbor.com is taken since 2002 and gunpoint.com since 1996. The names were not available for the games which came much later, so they had to be creative in their domain choices.

When it comes to domain names, short and generic is usually better than long and specific. But if the name of your game is already taken, attaching "game" is the next best pick for search engine optimization. When someone wants information about the game from Tiny Build and Dynamic Pixels, searches for "hello neighbor" and the first hit is an air freshener, they will try "hello neighbor game" next. If your search query is already almost a domain name, then most search engines will usually rank that domain first, even if other websites rank higher on the search terms when it comes to content and inbound links.

By the way: The `.game` TLD is available since May 2016. We will see if it will catch on. (Registration prices are far higher than for `.com` domains, but for professional game development studios they are not prohibitively high).
> 5 votes

# Answer
Likely because the domain *without* the "game.com" suffix was unavailable.

Alternatively, perhaps it was available but potentially close enough to infringing on another industry's trademark that it was deemed pertinent to specify that the site in question is for a game.

Maybe somebody thought it would be more searchable or more discoverable.

Or perhaps somebody just thought it *sounded cooler*.
> 3 votes

# Answer
The reason why so many game developer publish their game using their own domain that end with game.com is to make their customer find the official website of their game in easy way , like if you have game called " iamsowhat " , and you need the official website for it , you may like " iamsowhat.com is good because customer only need to add .com to go here . "

The point is , it's marketing strategy .
> 0 votes

---
Tags: publishing, distribution
---


# Question
Title: Communication between the SubSystems and the GameObject components?
Currently I have an architecture (not 100% accurate):  The RenderData contains primitives, which will be processed by the GraphicsEngine.

* Upon creation I have to send the pointer of the renderData from the Renderer to the GraphicsEngine.
* This is done by passing it to the GameObject, which passes it to the Scene, which passes it the Core, which will call the corresponding method at GraphicsEngine.

The problem with this is that the Scene has access to the Core. How can I register these RenderData's at the GraphicsEngine correctly?

And this is the same with Behaviour components signaling the AudioEngine to play a sound.

And this is also the same with the Rigidbody component's RigidbodyData and the PhysicsEngine.

* **But there is another problem:** How do I signal the objects which have collided from the PhysicsEngine?

+ I have thought of registering the object ID at the RigidbodyData's of teh collided objects, which Renderer will sense this, and will handle the custom behaviours. (like what happens when a bullet is collided with a player)
    + And if this is good then how do I signal the custom scripts that there is a collosion with another game object? Upon creation of Behaviour's I add their OnCollide method to an array at Rigidbody? Or just instead of storing the Behaviours in the general Component container, have a separated container for them and just iterate through them and call OnCollosion?

**Another problem:** The Window handles the input, and have to signal these Behaviour components in the Scene.

* So it has access the Scene, and on receiving input, it calls the Scene corresponding method which will spread the event somehow?

# Answer
Your `RenderSystem` could hold a reference to the GraphicsEngine. The active components could then be registered with the render system which would then simply use the primitives upon rendering.

To init a render system your core could initialise one when you open a window:

* The window provides a new viewport to `Core`
* `Core` then creates a new `RenderSystem`
* The `RenderSystem` is setup
* The render system awaits for new `RenderComponent` to process
* On each `GameObject` creation Core receives the object and dispatches all the components to the right systems (`Intent`, `Camera`, `Render`, `AI`, `Script`...)
* all the `RenderComponent` objects are registered in the `RenderSystem`
* On each render your `RenderSystem` does its thing with the Render components that are registered and active.

Note that nothing should stop the Render Component from accessing the dependencies like TransformComponent to properly do its job.

The fact that your `GameObject` actively passes render data looks like you have created an overcomplicated architecture.

Try to avoid having specialized functions (based on component specialization) in your GameObject. The game Object should be able to only manage `Component` objects without ever knowing what they contain.

If you have more than one render system you will have to add a way to filter the components that get registered in the different systems.

---

Concerning the input, same thing. The InputSystem is created by your `Core` when the window registers itself:

* Window tells core it will provide input.
* Core creates or uses the existing `InputSystem`
* `InputSystem` will then listen to the inputs.
* `InputSystem` awaits for new `InputComponent` objects notify them about the inputs that have changed.

I don't know what you mean by behavior but if you mean they are custom scripts then these scripts can retrieve the `InputComponent` your game object holds and they can then read the inputs.

This way when a scene starts it will pass all its `GameObject` to `Core`. `Core` will simply register each component of each game object with the corresponding System.

Upon scene deletion the scene will pass all `GameObject` to `Core` and all `Core` has to do is to unregister all the `Component` objects from the systems.
> 1 votes

---
Tags: c++, architecture, entity-system, component-based
---


title: Disc Golf Physics in Unity

text:
# Question
Title: Disc Golf Physics in Unity
I am trying to make a frisbee golf game, and I am stuck on the physics of the frisbee.

I can get the disc to fly, but I have not been able to add spin or make it act the way a frisbee would in real life.

If you can provide some code that would be great, or at least tell me what properties the disc object would need in order for this to work.

The disc has a rigid body with the following set:

* Mass = 0.175
* Drag = 0
* Angular Drag = 200 (I am sure this needs to be changed, just wanted to prevent forward rolling)
* User gravity is checked
* Is kinematic is unchecked, but changed in a script
* Interpolate = None
* Collision Detection = Discrete
* Constraints are all unchecked

Anyway, any guidance would be much appreciated.

# Answer
For spinning make sure to look into RigidBody.AddTorque (https://docs.unity3d.com/ScriptReference/Rigidbody.AddTorque.html)

If things get wobbly, you might want to play around with adding a GameObject container "around" the frisbee, so the trajectory is applied on the container and the spinning on the actual frisbee object.
> -1 votes

---
Tags: unity, physics
---


# Question
Title: What is the formula or algorithm used in libgdx delta time?
I'm studying time stepping algorithm and I need to know how delta time works in libgdx, because I think delta time uses some kind of time stepping algorithm.

# Answer
> 1 votes
libgdx seems, based on the source, to compute delta time with some variant of

```
long time = System.nanoTime();
deltaTime = (time - lastFrameTime) / 1000000000.0f;
lastFrameTime = time;

```

for every back-end renderer implementation. This is usually done when the renderer is ticked (the view is drawn, effectively). There doesn't appear to be any time-stepping going on.

---
Tags: libgdx, timestep
---


# Question
Title: How can I scale a color component by Time.deltaTime and still fit it into a byte?
I am confused about this issue, and I can't find why I get this and how to fix it properly from the Google searches I've tried.

This is a short version of my code:

```
     byte redtarget = 70;
     byte greentarget = 222;
     byte bluetarget = 255;
     byte opacitytarget = 1;
     byte redcurrent = 0;
     byte greencurrent = 0;
     byte bluecurrent = 0;
     void OnMouseOver() {
        redcurrent = redcurrent + redtarget * Time.deltaTime;
        greencurrent = greencurrent + greentarget * Time.deltaTime;
        bluecurrent = bluecurrent + bluetarget * Time.deltaTime;
    if(redcurrent >= redtarget) {
        redcurrent = redtarget;
    }
    if(greencurrent >= greentarget) {
        greencurrent = greentarget;
    }
    if(bluecurrent >= bluetarget) {
        bluecurrent = bluetarget;
    }
    theobject.GetComponent<Renderer>().material.SetColor("_EmissionColor",new Color32(redcurrent,greencurrent,bluecurrent,opacitytarget)) ;
     }

```

Please ignore the other errors that could have been introduced when I copy + pasted it to here.

And this is the error I get:

As you see the error, "cannot implicit convert type float to byte", the problem is caused by `Time.deltaTime` that returns a `float` value, and I need a `byte` due to `Color32`.

Is there any way to turn `Time.deltaTime` to `byte`? Or should I use another type of color that use floating point numbers?

**I'm a beginner with Unity so I'm sorry if this has already been asked somewhere; as I said, I can't find it on the Internet.**

# Answer
The error

> Cannot implicitly convert type 'float' to 'byte'. An explicit conversion exists (are you missing a cast?)

means that you try to assign a value for a type to another where information could be lost (generally).

A `byte` can hold integer values from 0 to 255. `Time.deltaTime` is a `float`, and it can hold *much more* different values. The compiler cannot implicitly convert from `float` to `byte` because you would lose a lot of data, so it asks you to explicitly do the casting (i.e. "tell me you're sure you want to do this").

So to simply make the issue go away, you'd have to explicitly convert the `Time.deltaTime` to `byte` like this:

```
redcurrent = redcurrent + redtarget * (byte)Time.deltaTime;

```

However, in this case, **that's not what you want**. You want to change the type of `redtarget` and others to `float`, because you'll have to take the floating point values in consideration in this current situation, whereas you could not with `byte`.

Only doing this, you'll get more type conversion errors when trying to create a Color32 object.

To do that, you cast the values when/where you need them:

```
theobject.GetComponent<Renderer>().material.SetColor(
    "_EmissionColor",
    new Color32(
        (float)redcurrent,
        (float)greencurrent,
        (float)bluecurrent,
        opacitytarget)) ;

```
> 2 votes

# Answer
For something like this, I'd recommend using either the `Color` or `Color32` types throughout.

eg.

```
Color32 currentColor;
Color32 originalColor;
Color32 targetColor;
float blendProgress;

Material myMaterial;

void OnMouseOver() {
   // Advance your blend progress.
   blendProgress = Mathf.Clamp01(blendProgress + Time.deltaTime);

   // Blend smoothly between the original and destination colors.
   currentColor = Color32.Lerp(originalColor, targetColor, blendProgress);

   // Cache your material in Start so you don't need to look it up every frame.
   myMaterial.SetColor("_EmissionColor", currentColor);
}

```

This keeps your code cleaner, and more explicit about what it's trying to do. You can still access bytes for the red, green, blue, and alpha components via `currentColor.r` etc.
> 2 votes

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


# Question
Title: How to update everything but 1 thing in pygame and python
**What I'm doing**

So I'm developing a game for my Computer Science final with python & pygame. It's done other then I have to make a main menu. I've been developing it over the last 2 weeks because it's been Winter break for me (I'm in high school if that matters) and I've been developing it on my home computer.

My home computer was running my game 60 FPS and never dropped lower than 55. Though I've just recently transferred it to my school laptop, the laptop I have to present it in and I'm getting 25-35FPS.

**What I've done**

I've converted everything that doesn't use transparency (.convert()), I enabled Fullscreen and I'm currently downloading Pypy to hopefully improve performance.

**What I'm trying to do**

Apparently in the Pygame performance thread there is a way to only update things that you need to update.

Though the thing is, for me in terms of graphics, everything needs to be updated but 2 things. Though these 2 things are what's dropping my FPS. The background image, and the block images.

**What I'm asking for**

Is there a way, certain line of code or command where I can exclude these things from being updated. Instead of having to have update only update everything but it.

Like a simpler or faster way. Can i write something like pygame.display.update(!background), something like that maybe?

# Answer
> 0 votes
I would try to utilize the sprite groups in pygame to hold only the objects you want to update. Then calling `update()` and `draw()` on that group will only update the sprites that you've added to it.

Also when looking at the groups it may be worth investigating the `RenderUpdates` group which is supposed to optimize its `draw()` method, but I haven't played around with it enough to see exactly how it works or how much it helps. Here is the documentation for this group: Render Update Doc

I would also recommend looking through the examples provided with the pygame library as I've found them very useful for understanding different parts of the functionality pygame supplies.

You mentioned that the background is one of the objects that is currently limiting your performance. If that is the case try looking at the aliens.py example (the example was inclueded in pygame-1.9.1-release/examples/aliens.py) to see an example of how the background can be separated out from the rest of the objects to help with performance.

First initialize the background

```
 # create the background, tile the bgd image
bgdtile = load_image('background.gif')
background = pygame.Surface(SCREENRECT.size)
for x in range(0, SCREENRECT.width, bgdtile.get_width()):
    background.blit(bgdtile, (x, 0))
screen.blit(background, (0, 0))
pygame.display.flip()

```

Utilize the background when clearing other sprites

```
 # clear/erase the last drawn sprites
 all.clear(screen, background) # all is a sprite group

```

---
Tags: performance, python, optimization, pygame
---


title: Line renderer in 3D sorting order

text:
# Question
Title: Line renderer in 3D sorting order
I'm using a line renderer as a laser aim for my character. If the aim hits an object it ends at that object. If the aim doesn't hit an object it continues a predefined distance.

If I aim at an object it works fine, if I stand behind the object it also works, but if I stand in front of it, the line is rendered behind the object creating the illussion that the character stands behind the object.

If I change the sorting order for the line I can make it to be in front of the object, but this is a bit tedious because then it will be in front of this object when it is in fact behind it.

In the screenshot below a line is drawn from the picked up C4 which is in front of the pillar, but the line is drawn behind the pillar.

Is there any way to solve this issue with a line renderer? I've been thinking of just using a cube and stretch it instead.

Thanks in advance!

**Update 1:** I made a cube-solution instead, but soon realized that the issue is with a shader that is set to fade/transparent and that this is due to sorting order. How can I dynamically change the sorting order in code so that my moving transparent object always appear in the correct place?

**Update 2:** I noticed that my own answer below isn't working 100%. It works for most scenarios but if I'm standing at origo and aiming behind a pillar the sight is rendered in front of the pillar. In the image below it is clearly visible from the top view that I'm aiming behind the pillar. (This is done with a deformed cube, the line renderer had even more issues).

# Answer
**UPDATE: doesn't work entierly!**

I solved this by setting the camera's transparency sort mode to orthgraphic:

```
Camera.main.transparencySortMode = TransparencySortMode.Orthographic;

```

Works for both LineRenderer or using a deformed cube.

https://docs.unity3d.com/ScriptReference/TransparencySortMode.html
> 1 votes

---
Tags: unity, 3d, draw-order
---


title: Placing units on isometric map (2D)

text:
# Question
Title: Placing units on isometric map (2D)
I'm making a map editor for further RTS game (2D), something like the first StarCraft Editor. Terrain tiles will be a rhombuses. So I'll probably just make an 2D array with intigers, that corresponds proper tiles. Then, after creating the terrain, you'd probably like to add some units and structures to map (especially if you're making a scenario). I'm not sure how do I check if the unit can be placed somewhere. I decided to make units almost independent from terrain tiles like in StarCraft (1), so the units are not placed in any grid. I'll give a simple image:

As you can see, those green tiles represent a passable area (grass, let's say), and a blue one impassable (for example water). That stickman in a box is our unit. You can place it only in green area. That means the box can't go outside the green rhombuses.

I have some ideas how to achieve this, but I'm not sure which one would be the most optimal.

1) Since I work in Unity, I could add a collider to every tile. That will be very simple to do and will probably have terrible optimalisation in maps 256x256.

2) Math. I can calculate if any of those boxes crosses tile's borders. If so, I'll have to check if all those tiles are passable. It won't be that easy to programme (well, for me at least) and... yeah, here comes my dillema. Am I right that it would have much better optimalisation? Is it worth the effort?

What about saving this map? I can easily save the array with tiles, but how can I do it with units? Just save their positions or is there a better way to do it?

EDIT: I've tested the first idea (I've written script to create 256x256 map - that will be probably the biggest, and to move a camera). The map generates quite long (comparing to tiles without collider), but after that there isn't much difference in performance (it doesn't mean it won't cause problems when I add more features than moving a camera ;)). I can also attach colliders only to impassable tiles, not all. This should improve the performance even more. Still not sure if that's a good idea.

EDIT 2: I've just realised how bad my idea was. Let me visualise this:  So if you consider not the whole rectangle, but only a circle, it's not only easier to implement, but also more reasonable. You can now convert rhombus' vertices' position from isometric to cartesian like Bálint said:

```
CartX = ( 2 * IsoY + IsoX) / 2
CartY = ( 2 * IsoY - IsoX) / 2

```

You can also do it with circle's center point. Radius is equal to half of square (rhombus) side length OR sqrt(2) * square side length (when square is inscribed in circle).

So now I have a square grid and a circle. How can I check if all squares that this circle lays on are passable? What's the most optimal way to do it?

# Answer
One big thing about optimization is that you should avoid doing it until you're sure you have a problem, and even then only after measuring to see where the problem actually is. Static colliders in Unity are generally pretty efficient so you probably will have less of a problem than you think.

All that being said, this is a question and answer site and you asked a question, so lets get to the answering! :)

**Answering!**

Your best bet here, since you only need to do the check on the unit currently being moved/placed, is probably to **use the collider method**. If you're anxious about the number of colliders, what I would do is only put colliders on impassable tiles (unless you have need of knowing what kind of tile each unit touches) and then on placement/movement do a quick Physics.OverlapBox based on the unit's footprint (which could be different than the bounds of the sprite for that pseudo-3d look) to see what colliders are being hit and if the placement is valid. As an added bonus if you only put colliders on places where the units cannot be (or put all no-place colliders on the same layer and only check against that) you can skip the identifying the tile step and just go straight to collide = no placement. Not only that, but it will also work for any other non-tile things you think need to block placement, which is a handy bonus!

As some information you may find useful, when I had to do a lot of performance optimization I found static colliders only really cost when checks need to be made against them, which is primarily when dealing with nearby moving colliders, physics checks, and raycasts. A situation like what is listed above will be trivial compared to a situation with hundreds or thousands of moving colliders needing to have physics, collision, and response applied every physics timestep.

**Advice! (ignore if you wish)**

An exercise that would be worth doing would be trying the collision method you mentioned first before doing what I listed above. This will give you an actual worst case cost by looking at the profiler (or just feeling it out) which will be more informative than any stranger on the internet can be about where bottlenecks are or aren't in your game.

Of course even with negligible performance gain, Side benefits might still make various performance adaptations desirable, but that's up to you as the creator. There's a constant lure for engineers to make things leaner and faster (heck I've had to resist the urge to answer with a couple mathematical solutions which would be more difficult to implement but could skip the concept of colliding entirely) but it's important to know when you can go with the simple approach so you can spend your time on the more important bits. Good luck!
> 1 votes

# Answer
There's a way to convert isometric coordinates to cartesian ones:

```
x = (2 * mouseY + mouseX) / 2;
y = (2 * mouseY - mouseX) / 2;

```

Get the position using this formula, floor the values then check if the tile at that pos is walkable or not.

This is probably the fastest method, as it doesn't require any type of collision
> 0 votes

---
Tags: unity, tilemap, rts, map-editor
---


# Question
Title: How do I programmatically change the areaSize variable of an Area Light object in Unity?
I'm trying to change the `areaSize` property of an Area `Light` object, but it looks like it isn't exposed in the class, itself.

```
this.light.areaSize =
    new Vector2(this.areaLightWidthSlider.Value, this.areaLightHeightSlider.Value);

```

This code results in the error:

> error CS1061: 'UnityEngine.Light' does not contain a definition for 'areaSize' and no extension method 'areaSize' accepting a first argument of type 'UnityEngine.Light' could be found (are you missing a using directive or an assembly reference?)

---

The documentation says it exists, as an "editor only" property.

Is there any way to programmatically access and change this property, possibly using reflection or serialized properties?

I am using Unity 4.6, if at all relevant.

# Answer
> 2 votes
***Can I access `areaSize`, programmatically?***

Yes. That is not to say I can offer a *how*, but I *can* offer a *why would you?*.

You *need* to be asking yourself \*why is such a theoretically useful variable editor-only?

**TL;DR:** Because changing this value *in game* would have no effect on your area light, at all.

---

Let's take a look at the area light in the Unity Manual (emphasis mine):

> ### Area lights
>
> An Area Light is defined by a rectangle in space. (...) Since the lighting calculation is quite processor-intensive, ***area lights are not available at runtime*** and can only be baked into lightmaps.
>
> <sub>\- The Unity Manual: Lighting</sub>

---

**What does this mean?**

This means that area lights are *baked*; set up at the start, as *static* objects.

In reality, if you *did* change the values in-game, you would *not* see any effect on the actual light.

If you *did* have it change your area light, in game, it would significantly slow down your game; likely even crash lower-end computers that would otherwise run it. *That is why it is baked from the start*.

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


# Question
Title: Where does Unity save Inspector properties for objects in a scene?
If I add a collection of objects to my scene and configure Inspector properties on those objects (like name, layer, tag, transform parameters, attached Components and their parameters), where does the information about those Inspector properties get saved within my project?

Is it all saved within the scene's `.unity` file or are there other files I should look at?

# Answer
> 4 votes
While this question is a couple of months old, the existing answer is not correct.

It describes how to reveal and inspect Unity's `.meta` files, which by default are hidden. However, these do *not* contain the inspector properties of objects in a scene. Those are stored in the `.unity` files corresponding to the scenes themselves.

---

What `.meta` files contain:

* A file format version, for compatibility in reading the meta file itself.
* A GUID, used to identify assets when they're referenced within other assets.

This is why renaming an asset in Unity doesn't force all references to it to be updated or break - they're looked up by ID, which remains constant once an asset has been created, as long as you don't separate it from its `.meta` file.
* Import settings for asset files like textures, models, or sounds - these are the settings you see in the Inspector when selecting the resource in your Project folder.
* User data, creation timestamp, and asset bundle information for scene (`.unity`) or prefab (`.prefab`) files.
* Execution order, creation timestamp, and asset bundle information for script (`.cs` & `.js`) files.

---

So `.meta` files do *not* include any of the object properties mentioned in the question: "name, layer, tag, transform parameters, attached Components and their parameters."

How do we find these?

First, go to `Edit -> Project Settings -> Editor` and change "Asset Serialization Mode" to "Force Text," then save your scene & project. This takes scene and prefab data that would normally be saved in binary form and ensures it's written out in human-readable form in your project source files. (So far as I'm aware, this does not affect how assets are serialized in your compiled builds, but I have not tested this specifically)

Now, to find the object parameters for an object instance in one of your scenes, open that scene's `.unity` file in a text editor. Here you'll find data like this:

```
--- !u!1 &991079445
GameObject:
  m_ObjectHideFlags: 0
  m_PrefabParentObject: {fileID: 0}
  m_PrefabInternal: {fileID: 0}
  serializedVersion: 4
  m_Component:
  - 4: {fileID: 991079451}
  - 20: {fileID: 991079450}
  - 81: {fileID: 991079447}
  - 114: {fileID: 991079446}
  - 114: {fileID: 991079452}
  m_Layer: 0
  m_Name: Main Camera
  m_TagString: MainCamera
  m_Icon: {fileID: 0}
  m_NavMeshLayer: 0
  m_StaticEditorFlags: 0
  m_IsActive: 1
--- !u!114 &991079446
MonoBehaviour:
  m_ObjectHideFlags: 0
  m_PrefabParentObject: {fileID: 0}
  m_PrefabInternal: {fileID: 0}
  m_GameObject: {fileID: 991079445}
  m_Enabled: 1
  m_EditorHideFlags: 0
  m_Script: {fileID: 11500000, guid: 4911397511e5c054a92cf2f47bd376b6, type: 3}
  m_Name:
  m_EditorClassIdentifier:
  projection:
  - {x: 0.76, y: 0, z: 1425, w: 0}
  - {x: 0, y: 0.68, z: 0, w: 0}
  - {x: 0, y: 0, z: -1, w: -0.1}
  - {x: 0, y: 0, z: -1, w: 0}
  materialToAlter: {fileID: 2100000, guid: dfeebd5fa422c5144b13201e09d2b95b, type: 2}
--- !u!81 &991079447
AudioListener:
  m_ObjectHideFlags: 0
  m_PrefabParentObject: {fileID: 0}
  m_PrefabInternal: {fileID: 0}
  m_GameObject: {fileID: 991079445}
  m_Enabled: 1
--- !u!20 &991079450
Camera:
  m_ObjectHideFlags: 0
  m_PrefabParentObject: {fileID: 0}
  m_PrefabInternal: {fileID: 0}
  m_GameObject: {fileID: 991079445}
  m_Enabled: 1
  serializedVersion: 2
  m_ClearFlags: 1
  m_BackGroundColor: {r: 0.19215687, g: 0.3019608, b: 0.4745098, a: 0}
  m_NormalizedViewPortRect:
    serializedVersion: 2
    x: 0
    y: 0
    width: 1
    height: 1
  near clip plane: 0.3
  far clip plane: 20
  field of view: 60
  orthographic: 0
  orthographic size: 5
  m_Depth: -1
  m_CullingMask:
    serializedVersion: 2
    m_Bits: 4294967295
  m_RenderingPath: -1
  m_TargetTexture: {fileID: 0}
  m_TargetDisplay: 0
  m_TargetEye: 3
  m_HDR: 0
  m_OcclusionCulling: 1
  m_StereoConvergence: 10
  m_StereoSeparation: 0.022
  m_StereoMirrorMode: 0
--- !u!4 &991079451
Transform:
  m_ObjectHideFlags: 0
  m_PrefabParentObject: {fileID: 0}
  m_PrefabInternal: {fileID: 0}
  m_GameObject: {fileID: 991079445}
  m_LocalRotation: {x: 0.23492102, y: 0.16446818, z: -0.04036682, w: 0.9571483}
  m_LocalPosition: {x: -1.97, y: 2.95, z: -6.89}
  m_LocalScale: {x: 1, y: 1, z: 1}
  m_LocalEulerAnglesHint: {x: 27.58, y: 19.5, z: 0}
  m_Children: []
  m_Father: {fileID: 0}
  m_RootOrder: 0
--- !u!114 &991079452
MonoBehaviour:
  m_ObjectHideFlags: 0
  m_PrefabParentObject: {fileID: 0}
  m_PrefabInternal: {fileID: 0}
  m_GameObject: {fileID: 991079445}
  m_Enabled: 1
  m_EditorHideFlags: 0
  m_Script: {fileID: 11500000, guid: c1d02e8598764a64cbd19d248b4c9644, type: 3}
  m_Name:
  m_EditorClassIdentifier:
  material: {fileID: 2100000, guid: dfeebd5fa422c5144b13201e09d2b95b, type: 2}
  pass: -1

```

This describes my "Main Camera" object in a particular scene, as you can see from the line `m_Name: Main Camera`. You can see it has `Camera` and `Audio Listener` components attached, an associated `Transform`, and two custom `MonoBehaviour` scripts identified by GUID.

You'll find data with essentially the same format in the `.prefab` file corresponding to `GameObjects` you've saved as prefabs in your Project folders. When you include an instance of a prefab in a scene, the scene will reference that prefab by GUID, and include its local transform within the scene, as well as any parameters you changed on that instance without applying them back to the prefab.

# Answer
> -3 votes
They are hidden by default.

If you change "Edit/Project Settings/Version Control"'s value as Visible Meta Files instead of Hidden Meta Files, then you can see all values in the your project folder.

Example: You have a Player object. So, you will see "Player.meta file" inside the assets folder.

---
Tags: unity
---


# Question
Title: Why is the SFML shape not being displayed when I make it a member of the Game class instead of a local function variable?
I created a window successfully in SFML using a Game class which hold all of the key components of the game. I then tried to start rendering shapes on the screen. When I first rendered the shapes, I was creating local copies inside of the render function. Of course, that doesn't allow me to do much and it isn't good organization of code, so I moved the main shape of the game I have in mind to the Game class. Now the shape doesn't show up at all. The application doesn't crash but it just doesn't show the shape. I feel like this might have something to do with the scope of the shape, but I just can't make sense of it. I looked at "The white square problem" on SFMLs site but I do not feel like this relates since the shape is a member of the class (which I thought meant it shouldn't go out of scope until the instance of the class does). I'm using g++ and am on a iMac running El Capitan if that helps any. Any help at all is greatly appreciated! Please help me understand this if you can!

p.s. Feel free to comment on any part of my code that isn't even directly related to the question but rather should just be improved.

**Main.cpp**

```
#include "Game.hpp"

int main(int argc, char** argv)
{
    Game game;

    game.setup();

    while (game.isRunning())
    {
        game.events();
        game.update();
        game.render();
    }

    game.cleanup();

    return 0;
}

```

**Game.hpp**

```
#ifndef GAME_H
#define GAME_H

#include <SFML/Graphics.hpp>

class Game
{

private:
    enum GameState
    {
        GAME_STATE_RUNNING,
        GAME_STATE_CLOSING
    };

    sf::RenderWindow window;
    GameState state;
    sf::CircleShape leader;

public:
    Game();
    ~Game();

    void setup();
    bool isRunning();
    void events();
    void update();
    void render();
    void cleanup();

};

#endif

```

**Game.cpp**

```
#include <SFML/Graphics.hpp>

#include "Game.hpp"

Game::Game()
{
}

Game::~Game()
{
}

void Game::setup()
{
    this->window.create(sf::VideoMode(1000, 750), "Follo");

    this->leader.setFillColor(sf::Color::Black);
    this->leader.setPosition(100, 100);

    this->state = GAME_STATE_RUNNING;
}

void Game::events()
{
    sf::Event event;

    while (this->window.pollEvent(event))
    {
        if (event.type == sf::Event::Closed)
        {
            this->state = GAME_STATE_CLOSING;
        }
    }
}

bool Game::isRunning()
{
    return this->state != GAME_STATE_CLOSING;
}

void Game::update()
{
}

void Game::render()
{
    this->window.clear(sf::Color(203, 209, 219, 255));
    this->window.draw(this->leader);
    this->window.display();
}

void Game::cleanup()
{
}

```

**Makefile**

```
COMPILE         = g++ -c
LINK            = g++ -o
FLAGS           = -g -Wall -O2
O_FILES         = Main.o Game.o
LIB_PATH        = /usr/local/lib
INCLUDE_PATH    = /usr/local/include
LIBS            = -lsfml-graphics -lsfml-window -lsfml-system
EXE_NAME        = Follo

program: build
    ./$(EXE_NAME)

build: $(O_FILES)
    $(LINK) $(EXE_NAME) $(O_FILES) -L$(LIB_PATH) $(LIBS)

Main.o: Main.cpp
    $(COMPILE) $(FLAGS) Main.cpp

Game.o: Game.cpp Game.hpp
    $(COMPILE) $(FLAGS) Game.cpp

```

# Answer
You're not initializing `leader` explicitly in your game class constructor. That means it is default-constructed, and the default constructor for `CircleShape` creates a circle with a radius of 0.

You should do something like

```
Game::Game()
: leader(10.0f) {
}

```

for your `Game` constructor to give the circle a reasonable radius (in this case, 10).
> 1 votes

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


# Question
Title: Unity Multiplayer functionalities or Google's plug-in?
I want to add multiplayer matches to a game I'm making for Android/PC, and something echoed in my mind: would the network functionalities Unity provides work in Android? I ask this because Google has a free plug-in for their services, but Unity also offers possibilities. Also, using any of the above, do I need to pay to rent a server? Or, for example, since we need a paid developer account to register our game at Google Play Store, the servers are part of the deal?

# Answer
> 1 votes
Unity and Google offer different APIs/Services, but both are centred around a P2P (Peer to Peer) architecture.

Unity, as does Google, offers matchmaking and relay servers. These are ways to find players, and relay data between clients.

Unity's offering comes with a free "personal" licence, where as with Google's there seems to be some lack of information (free?).

As Unity is cross platform, it's tools and services are as well. The services provided by Google however only work on Android/iOS.

More information for Unity is here: https://unity3d.com/services/multiplayer

More information for Google is here: https://developers.google.com/games/services/common/concepts/realtimeMultiplayer

---
Tags: unity, google-play-services, unity-networking
---