title: Clicker economy and bonus system

text:
# Question
Title: Clicker economy and bonus system
How is an economy system implemented in clicker games? Obviously, you can't store values like 1 Quintilian in long type. I understand that there might be some string operations or even better, some int array where every index has it's value, though I'm curious if there are better methods and what they are.

Also, how to make this system generic and reusable for any other clicker or not clicker game.

And about bonus system, for example, 50 000% increase, I bet it's a bad idea to multiply this value every frame for every other kind of object that generates game currency.

How is this system implemented as well? If you have different sources of bonuses, do you have modifier object that multiplies values?

# Answer
> 10 votes
There are data types that handle these situations, like C#'s `BigInteger`:

> The BigInteger type is an immutable type that represents an arbitrarily large integer whose value in theory has no upper or lower bounds.

Which I would guess is actually just `int[]` with some nice features wrapped around it. Being immutable could certainly be a problem for lots of calculations, as you'd need to create new values frequently.

However, attempting to keep track of the *exact* value in a clicker game probably wouldn't be how I'd do it. I'd probably use something like a`long` for the significant digits and keep track of the exponent separately. As the number grows, increase the exponent and shift the significant digits down.

You can store your insignificant values as you shift them out, so you can restore them when the exponent on your economy comes down.

When you're making a quintillion dollars a second, does it matter that you're not making a quintillion and one dollars a second?

BTW, a `double` will take you all the way up to a Uncentillion.

# Answer
> 6 votes
In my implementation I use a `double` to store the value. A double can store really large values (up to 1.8 × 10308 in case of an `IEEE 754 64-bit double`, i.e. 180 Uncentillion) so you shouldn't have to worry about hitting the cap. To put that number into perspective if you gave your player 1 Quintillion \[whatever\] every second it would take you 5 Trenonagintillion years to reach that value! And the downside of precision is negligible when you're dealing with such large numbers.

I've also experienced that using a `double` is faster than `BigInteger` or similar data structures. So in case performance is required it should be preferred.

---

As for how you handle bonuses what I did was separate the logic into two steps:

1. The prediction
2. The calculation

The calculation would only be performed every once in a while depending on how much you're making **and** how much you currently have (greater values = fewer updates). For example at over 1 quintillion I only update once every second.

The prediction however would save objects such as `Multiplier` (increases value by a Multiplier such as `* 2`) and `FlatIncrease` (increases value by a flat value such as `+ 10`). These would be saved and then applied to the calculation when you need the exact value. First the `FlatIncrease` would be added then the `Multiplier` would multiply the value.

# Answer
> 3 votes
You don't have to update resources every tick.

Instead, it's enough to just store the formula that lets you compute how many resources you will have at any given time. And then you only ever bother doing so when the value is *actually needed*.

When the player gets a bonus to production, it's simply a matter of updating the formula to account for it.

---
Tags: architecture, clicker
---


# Question
Title: Reading from a staging 2D texture array in DirectX10
I have a DX10 program, where I create an array of 3 16x16 textures, then map, read, and unmap each subresource in turn. I use a single mip level, set resource usage to *staging* and CPU access to *read*. Now, here is the problem:

* Subresource 0 contains 1024 bytes, pitch 64, as expected.
* Subresource 1 contains 512 bytes, pitch 64.
* Subresource 2 contains 256 bytes, pitch 64.

I expect all three to be the same size. Debugging output is enabled, but not reporting any warnings or errors. Am I missing something, or might this be some sort of driver issue?

Here is the code. The language is Nemerle, but C# and C++ would look almost the same. I have looked through the generated code, and am fairly confident the problem is not language-related.

```
def cpuTexture = Texture2D
    ( device
    , Texture2DDescription() <-
    {
        Width     = 16;
        Height    = 16;
        MipLevels = 1;
        ArraySize = 3;
        Format    = Format.R32_Float;
        Usage     = ResourceUsage.Staging;
        CpuAccessFlags    = CpuAccessFlags.Read;
        SampleDescription = SampleDescription(count = 1, quality = 0);
    }
    );
foreach (subresource in [0 .. 2])
{
    def data = cpuTexture.Map(subresource, MapMode.Read, MapFlags.None);
    Console.WriteLine($"subresource $subresource");
    Console.WriteLine($"length = $(data.Data.Length)");
    Console.WriteLine($"pitch  = $(data.Pitch)");
    cpuTexture.Unmap(subresource);
}

```

# Answer
You're forgetting to consider mipLevels. When creating a texture, usually miplevels will be generated so you will not find texture element 2 at subresource 2 (there is a mipLevel in it, which is half of original texture and so on).

Use this function to get the right subresource index.

```
    ID3D11Texture2D *cpuTexture = NULL;

    D3D11_TEXTURE2D_DESC cputextdesc;
    memset(&cputextdesc,0,sizeof(cputextdesc));

    cputextdesc.Width = cputextdesc.Height = 16;
    cputextdesc.ArraySize = 3;
    cputextdesc.MipLevels = 1;
    cputextdesc.Format = DXGI_FORMAT_R32_FLOAT;
    cputextdesc.Usage = D3D11_USAGE_STAGING;
    cputextdesc.CPUAccessFlags = D3D11_CPU_ACCESS_READ;
    cputextdesc.SampleDesc.Count = 1;
    cputextdesc.SampleDesc.Quality = 0;

    device->CreateTexture2D(&cputextdesc,NULL,&cpuTexture);

    int text1 = D3D11CalcSubresource(0,0,1);
    int text2 = D3D11CalcSubresource(0,1,1);
    int text3 = D3D11CalcSubresource(0,2,1);

    D3D11_MAPPED_SUBRESOURCE mres1,mres2,mres3;

    icontext->Map(cpuTexture,text1,D3D11_MAP_READ,0,&mres1);
    icontext->Map(cpuTexture,text2,D3D11_MAP_READ,0,&mres2);
    icontext->Map(cpuTexture,text3,D3D11_MAP_READ,0,&mres3);

    // (assert row and depth pitch are equals)

    icontext->Unmap(cpuTexture,text1);
    icontext->Unmap(cpuTexture,text2);
    icontext->Unmap(cpuTexture,text3);

```
> 0 votes

# Answer
We can begin by stating that this problem is certainly either language-related or a SlimDX bug; it is absolutely **not** a driver bug. Let's see if we can find out which.

The canonical implementation of ID3D10Texture2D::Map is described on MSDN, and we see that the method signature is:

```
HRESULT Map(
  [in]  UINT                   Subresource,
  [in]  D3D10_MAP              MapType,
  [in]  UINT                   MapFlags,
  [out] D3D10_MAPPED_TEXTURE2D *pMappedTex2D
);

```

When we look at the D3D10\_MAPPED\_TEXTURE2D struct we see that it contains the following members:

```
typedef struct D3D10_MAPPED_TEXTURE2D {
  void *pData;
  UINT RowPitch;
} D3D10_MAPPED_TEXTURE2D;

```

From this we can categorically state that the Length member you are accessing (`data.Data.Length`) **does not exist** in Microsoft's Direct3D runtime and therefore cannot be provided by the driver.

When we cross-check with the SlimDX source code we see that the return from `Map` is indeed constructed by SlimDX itself:

```
int mipHeight = GetMipSize( mipSlice, desc.Height );
int sizeInBytes = mipHeight * mappedRect.RowPitch;
if (Utilities::IsCompressed(desc.Format))
    sizeInBytes /= 4;

return gcnew SlimDX::DataRectangle( mappedRect.RowPitch, gcnew DataStream( mappedRect.pData, sizeInBytes, true, true, false ) );

```

**This is therefore a SlimDX bug**.

Looking over the SlimDX code I've linked I don't immediately see anything that could cause it, so I would suggest updating you download of SlimDX as a first troubleshooting step, as it may be a bug that has been fixed by a more recent version.
> 0 votes

---
Tags: directx, directx10
---


# Question
Title: Setting resolution of multiple display screens
in my unity project I have multiple screens. How can I set resolution of each screen? I know `Screen.SetResolution(1366,768,true);` sets the resolution of a single screen but what about multiple screens?

I disabled unity pop up option before starting the game. Does unity choose maximum resolution by default?

# Answer
You need to use the `Display` class to activate and change resolution of additional displays.

You can access the additional displays using `Display.display[i]`, where `i` is the display index (main = 0, 2nd = 1, etc.).

Use `Display.display[i].Activate(display_width, display_height, display_refreshRate)` to activate the additional displays.

Edit: to answer your question in the comment, to make a secondary display go fullscreen, you just need to set its resolution to the native one:

```
Display.displays[1].Activate();
Display.displays[1].SetRenderingResolution(Display.displays[1].systemWidth,
                                           Display.displays[1].systemHeight);

```

or, directly,

```
Display.displays[1].Activate(Display.displays[1].systemWidth,
                             Display.displays[1].systemHeight, 60);

```

if the refresh rate is 60 (with the second method, you can't read inside Unity the refresh rate of the secondary display, so you need to know it before hand, or just use `SetRenderingResolution` to let the graphic card drivers choose it without bothering).

Another important info that I forgot to mention: when inside the Editor, the number of displays reported by the `Display` class will **always** be one, the correct number will be reported only in a standalone build (and it only works for PC/Mac/Linux builds).
> 6 votes

---
Tags: unity, screen-management
---


# Question
Title: Move component to: where to with child components?
I have a simple static mesh attached to a scene in a blueprint. I want to move the component back to (0,0,0). If a component is not attached to any other component other than the default scene root, I just type in (0,0,0) as the Target Relative Location.

To be precise, I don't want it to go to (0,0,0) but head there and stop, so I just give it the world location and then multiply X, Y and Z by 0.67 (could be any value).

But now I have a few child components attached to an extra scene. This scene is moved (-2460, 3070, 2600). Now to make matters worse, it's ALSO rotated (0°, 0°, 90°) and every component I try to move is ALSO rotated by (0°, 90°, -90°). The numbers themselves aren't hard to crunch but I have no idea what "Target Relative Component" should be now.

I tried adding vectors, subtracting vectors (both relative and world from both the parent and every child component I want to move), inverting transforms, transform directions, rotating the resulting vectors, unrotating the resulting vectors, nothing seemed to work, at least not the combinations I tried.

How do I get the correct Target Relative Location?

# Answer
There's a method (a.k.a. "node" in Blueprint lingo) called Move To World Position, where I can define the exact point where I want my element to be. To get a smooth transition I discovered Timelines (duh, right - but I'm new to UE4) so that problem is solved: Create a float track in the timeline, then connect the float pin to a "Lerp (vector)" node and set the Lerp A pin to the current world position and the B pin to where you want it to be. Then the lerp vector output goes to Move to World Position.

Works with relative positions too.
> 0 votes

---
Tags: movement, vector, unreal-4
---


# Question
Title: How can I create lit-up areas during night-time in a top-down 2D game?
I am trying to implement a super simple day/night cycle. It works fine, at 9pm it gets dark, and at 6am it gets bright.

However, I am "creating" darkness by simply setting the alpha of a black Image that covers the entire screen, ie:

```
if(NightTime){
    Color tempColor = dayNightImg.color;
    tempColor.a = 0.5f;
    dayNightImg.color = tempColor;
    isDark = true;
}

```

So, in order to create the Illusion of light, I would have to be able to ignore part of this Dark Image, i.e "Light it up", for example in a circle around my character. Is there some way I can do this? Or Is my approach too simple for this effect?

Here is an example of what I want:

# Answer
> 5 votes
There's a quick and dirty way to do this.

Just create, outside Unity, an image, completely black except for a circle in the center.

With Gimp, follow these steps:

* Create a new image, larger than the maximum resolution you'll use in the game
* Fill it with black
* Add alpha channel to the layer
* Create an elliptic selection in the center
* Press delete to remove the circle
* Export the image in png format

You'll have something like this:

Now, back in Unity:

* Create a new 2D Sprite
* Set this image as its `Sprite`
* Set its Z position in order to put this in front of the camera, before any other sprite of your scene.

Et voilà, now you have a full, black mask with an "always on" center, and you can change the alpha channel of the sprite via script/Inspector in order to modify the opacity of the black mask.

Another way is to use an appropriate Shader, but since you're still a beginner, I would start with this simple solution. ;)

**Edit**:

Link to a simple example for multiple spotlights with intensity controlled by script: https://github.com/Galandil74/Unity-Spotlights-Example

I prefer to use `Directional` lights for the spots because of their uniformity, and the fact that their intensity is added to the ambient lighting of the scene. Everything is handled via script, ambient light, spotlights, number of lights, etc.

All sprites affected by the lights must have a `Sprites/Diffuse` shader, the `Sprites/Default` shader isn't affected by lights, but only by post-effect shaders.

Sample image with 5 lights:

# Answer
> 5 votes
Extending my comment to an answer...

To achieve this kind of effect, follow the steps

1. Change the **ambient color** from **Window -\> Lightning -\> Settings** to black.
2. If you're using sprites then you need to change the materials of Sprites, which you want to be affected by Lights (Sprite-Default is not affected by lighting, I don't know why though), to an empty material
3. Create a spotlight, and make it a child of player object and play around with it's settings to get your desired effect.
4. Change the ambient color from code to achieve your day-night effect.

Note : I'm not very experienced with Lights, this is what I achieved. If there's any error or fault here, please do point it out.

---
Tags: unity
---


# Question
Title: Why does the pitch affect the x component of the front vector?
In every tutorial for implementing a camera in OpenGL, the front vector is calculated with something like this :

```
front.x = cos(pitch)*cos(yaw);
front.y = sin(pitch);
front.z = cos(pitch)*sin(yaw);

```

What I don't understand is why the pitch affects the x component? Shouldn't it just be :

```
front.x = cos(yaw);

```

Also, for the z component, why do we multiply cos(pitch) with sin(yaw). I understand that the pitch and the yaw both affect the z component, but why multiply? Why not add or something else?

# Answer
"Why does pitch affect the x component?"

Short answer: because you could be looking left or right.

Now, you may say if yaw is zero (or ±π), then `front.x = cos(pitch) * cos(yaw)` is `cos(pitch) * 1`, so pitch is affecting the x component even with no yaw at all!

This is a bit of an artifact of the yaw convention they've chosen to use. OpenGL examples I've found seem to base this off of a version of Euler/Tait-Byran angles, where yaw is measured as the angle between forward and the positive x-axis:

This threw me for a loop at first too - I'm used to 0 yaw meaning we have applied zero rotation about the vertical axis (Unity uses this convention), but these articles take 0 yaw to mean "facing along the positive x axis."

Once we adapt to this slightly-turned way of looking at things, the formulas make sense again. When yaw is zero or ±π, our camera is looking along the x-axis, and so naturally pitching up or down should foreshorten the x component of the forward vector.

To see where these particular formulas come from, we can work it through as a pair of transformation matrices.

Starting with a matrix that, when `pitch` is zero gives the identity matrix, and as we increase pitch the y+ and z+ axes spin through the unit circle:

(Here I'm using a right-handed coordinate system where positive pitch tips "upward," and assuming vectors will be multiplied in from the left side)

```
              ┌   1       0           0       ┐
PitchMatrix = |   0   cos(pitch)  sin(pitch)  |
              └   0  -sin(pitch)  cos(pitch)  ┘

```

We can see, again according to your intuition, the x axis (first row) is unaffected by \`pitch alone.

Then the yaw matrix is similar, just shuffled and with cos exchanged with -sin to satisfy the rule that "0 yaw = local z- rotates to face x+"

```
              ┌ -sin(yaw)  0   cos(yaw)  ┐
  YawMatrix = |     0      1       0     |
              └ -cos(yaw)  0  -sin(yaw)  ┘

```

Now, to get the combined result of both these matrices on a vector, we can multiply the vector by each one in turn:

```
TransformedVector = LocalVector * PitchMatrix * YawMatrix

```

(Note that contrary to Bálint's remark, I'm actually applying the `YawMatrix` to the vector *after* the `PitchMatrix` has been applied. This ensures we pitch about the *local* x, and yaw about the *global* y axis, which is typically how we want to use this. For example, a common Euler/Tait-Bryan angle multiplication order is z first, then x, and y last)

Subbing this in with localVector = (0, 0, -1)...

```
                                 ┌ 1      0          0      ┐┌ -sin(yaw) 0   cos(yaw)┐
TransformedForward = [ 0  0  -1 ]| 0  cos(pitch) sin(pitch) ||     0     1      0    |
                                 └ 0 -sin(pitch) cos(pitch) ┘└ -cos(yaw) 0  -sin(yaw)┘

```

Starting from the right, the first multiplication effectively selects the bottom row:

```
                                ┌ -sin(yaw) 0  cos(yaw) ┐
= [ 0  sin(pitch)  -cos(pitch) ]|     0     1     0     |
                                └ -cos(yaw) 0 -sin(yaw) ┘

```

Again we can see this satisfies our intuition - the x coordinate was untouched and is still zero. Following through with the yaw rotation...

```
= [ cos(pitch) * cos(yaw)    sin(pitch)    cos(pitch) * sin(yaw) ]

```

Now we have the formulas we started with:

```
front.x = cos(pitch)*cos(yaw);
front.y = sin(pitch);
front.z = cos(pitch)*sin(yaw);

```

You don't strictly have to use these rotation conventions. There's a million ways to form a coordinate system, and in all honesty the mess above is not my favourite way - so just use the conventions that make the most sense to you.
> 2 votes

# Answer
Yaw is applied first, then pitch, you can see this on the following gif (I first rotate the pitch, then I do the same but I change the yaw too):
> 1 votes

---
Tags: opengl, rotation, transformation, euler-angles
---


title: Elegantly enter and exit a loop android

text:
# Question
Title: Elegantly enter and exit a loop android
I'm designing a board game (Settler of Catan) in which you should be able to use resources to build constructions like roads, settlements, etc.

I have a View in which i draw my map on, also a button `Build`. If a player wants to build something, he/she should click it and should be able to choose which tile he/she wants to build it on.

The thing is i'm wondering if i should start a new Activity just for this Build -Action or should i implement a methode that runs a `while`\- loop until the user has chosen in which tile he/she wants to build the thing on.

In my mind, a while-loop has never been a good way because the programm has to check the condition almost always -\> maybe a problem of performance.

I'm thankful for any suggestion to solve this problem.

# Answer
The software architecture pattern you are looking for is a state machine.

Your user interface should have different modes (or "states") in which it shows different UI elements and reacts differently to user input.

When the user clicks on "Build", your UI should switch to the "select build tile" state where the tiles where the user can build are highlighted. When the user clicks a tile, switch to the "Select building" state. In that state the selected tile gets highlighted, no other tile can be selected, but the player can select what to build. When the player selected the build option, apply it and return back to the default UI state. Each of these modes should also have some way to navigate back to the previous state, in case the player changes their mind or selected the wrong tile.

There are different ways to implement this architecture-wise.

A common one is to implement each state with an own class. Have all the state-classes implement an interface with a method `enter` (which shows all state-specific UI elements and sets up their event handlers) and `leave` (which hides everything state-specific and deactivates the event-handlers). Your main UI handling class should have a public method `switchState(state)` which `leave`s the current state and `enter`s the new one.

When developing native Android applications, you might be able to get away with implementing each state with nothing but a different `View`. Put the code for entering or leaving a view into the `onAttachedToWindow()` and `onDetachedFromWindow()` event handlers. Have the main UI handler detach the current view and attach the new one.
> 0 votes

---
Tags: android
---


# Question
Title: How do I make instances of enemies spawn after every three keypress movements?
I am making a game, where two zombies will spawn after every three moves my character makes. The problem is that I have no idea how to do this.

I have my character moving correctly, in each key press event, so I want the game to count each time one of these events are triggered, and perform the action after every third trigger. Perhaps I need a global variable/counter that can count these events?

How do I make instances of enemies spawn after every three keypress movements?

# Answer
Here is some pseudocode:

```
If keypress do
    KeyPressCounter++
End
If KeyPressCounter%3 == 0 do
    Action ()
End

```

This preforms a modulo operation which will detect numbers divisible by 3.
> 2 votes

# Answer
If you want to create this type of event, I suggest this :

If your character moves with the directional keys, then create four Keypress event : one for each key (Up, Down, Right, Left). Create a variable in `Create` event, and increment this variable in the four event previously created. Then, in the `Step` event, check if the variable is equal at 3. If yes, do your action and set the variable at 0. If not, do nothing.

Here what it looks in code :

Create event :

```
number_key_pressed=0;

```

Key press left event :

```
number_key_pressed+=1;

```

Key press right event :

```
number_key_pressed+=1;

```

Key press up event :

```
number_key_pressed+=1;

```

Key press down event :

```
number_key_pressed+=1;

```

Step event :

```
if(number_key_pressed==3)
{action();
number_key_pressed=0;}

```
> 0 votes

---
Tags: game-maker
---


# Question
Title: How should I separate drawing from system collision?
Well, in my game while I'm drawing I have to verify the collision between the views. After a collision, I have to draw some things. But I can't draw them with a batch but with a stage. So I have to begin and end a lot of batches and this makes my game very slow.

Here is the part of code which I talked about:

```
for(int i=0;i<1000;i++)
    {
        if(i<999)
            list.get(i+1).xTubo = list.get(i).xTubo + list.get(i).distanza;

        for(int j=0;j<=60;j++)
        {
            if( (xPersonaggio==list.get(i).xTubo + j || xPersonaggio==list.get(i).xTubo-j*3)&& yPersonaggio<=list.get(i).altezza-50)
            {
                batch.begin();
                if(ySalto==0)
                    batch.draw((TextureRegion) animation.getKeyFrame(time, true), orthographicCamera.position.x - 300, 60 + ySalto);
                else
                    batch.draw(textureAtlas.createSprite("h"), orthographicCamera.position.x - 300, 60 + ySalto);
                scrittaHaiPerso.draw(batch,"HAI PERSO!",orthographicCamera.position.x-50,500);
                menu.draw(batch,"MENU",orthographicCamera.position.x,300);
                batch.end();
                stage.draw();

                fineGioco=true;
            }
        }
        batch.begin();
        batch.draw(spriteTuboVerde,list.get(i).xTubo,-30,120,list.get(i).altezza);
        batch.end();
        if(xPersonaggio>list.get(i).xTubo+50)
            tubiSaltati++;
    }

```

In this cycle I draw a lot of views, as you can see at the bottom. At the top I have my very rudimental collision system. When a collision happens, an imagebutton appears on the screen and I have to draw it with a stage. So I have to begin and ends a lot of times the batch and this doesn't go well at all. How can I write less batches?

NOTE: The order of drawing has to be this

# Answer
> 1 votes
Generally your collision should be handled separately from your rendering. In your update you should be having your object manager checking collision and handling flags inside said objects to mark whether the objects should be rendered or not based on their interactions. The render should be handling just the rendering portion. Ie. if the render flag of this object is set, render it. It doesn't have to know anything else besides that and you should be able to just wrap all the renders in one single begin and end.

---
Tags: libgdx
---


# Question
Title: Detecting collisions with a wall before Update
I'm making a script in unity to control (movement) a character in 3rd person and 3D space.

For that I'm using the `CharacterController` component.

All pretty standard: inside the update method a `Vector3` which will be passed to `CharacterController.move` is crafted based on the input and collisions, movement and jumping are perfectly fine but I ran into an issue when trying to make a wall jump.

There are 3 steps involved in this:

1. Get the wall to jump of.
2. Check if the player pres the jump button.
3. Move the player in the desired direction.

An this is how I'm doing it:

```
void OnControllerColliderHit(ControllerColliderHit hit) {
   if(mController.collisionFlags==CollisionFlags.Sides) {
       //Get wall normal
       wallNormal=hit.normal;
       isOnAWall=true;
   }
}

```

Now inside `Update`

```
if(Input.GetButtonDown("Jump")&isOnAWall) {
    //jump...
}

```

And this work fine in most cases but only if player is giving input or last wall has a similar `normal` as current so obviously the `normal` isn't refreshing properly, but why?

Well, after some testing, I discovered that the `OnControllerColliderHit`is called **after** the `Update` method, and this is what *I think* is happening:

* Physics engine detect the collision and stops the player
* Update method not having any input just send it downwards
* The `OnControllerColliderHit` method is not triggered(this part I am sure)

Are my conclusions correct?

How can I fix this? (make the player jump without need to move the stick and just with the button)

# Answer
> 1 votes
If you think the process is resolving backwards, then simply flip your logic. Instead of checking for the collision and setting a flag for the input to check, make the input set a flag and have the collision check for it.

---
Tags: unity
---


# Question
Title: How can I detect hex edges and corners for Catan map?
The following messy code implements a decent hex map, but I have no way to detect edges and corners:

```
function blankMap($scenario_array){
    $hexMap = null;
    $hexCss = "<style media=\"screen\" type=\"text/css\">#map {
        position: relative;}
      #map li {
        margin: 0; padding: 0; list-style: none;
        position: absolute;}
      #map li, #map a {
        height: 300px; display: block;}";
    $hexCount = 1;
    $row = 1;
    $top = 0;
    $left_pad = 10;
    $first_fifth = 0;
    $second_fourth = 0;
    if($scenario_array[0] == 'basic'){

      $hexMap .= "<ul id=\"map\">";
      foreach($scenario_array[1] as $x){
        //set horizontal placement
        $first_fifth = 149;
        $second_fourth = 75;
        if($row == 1){
          $left_pad = $first_fifth;
        }elseif($row == 2){
          $left_pad = $second_fourth;
        }elseif($row == 3){
          $left_pad = 0;
        }elseif($row == 4){
          $left_pad = $second_fourth;
        }elseif($row == 5){
          $left_pad = $first_fifth;
        }
        for($i=0;$i<$x;$i++){
          $hexMap .= "<li id=\"hex".$hexCount."\"><a href=\"".$hexCount."\"></a></li>";
          $hexCss .= "#hex".$hexCount." {left: ".(($i*150)+$left_pad)."; width: 225px; top: ".$top."; background: url(./images/wheattile.png); background-repeat: no-repeat; }";
          $hexCount++;
        }
        $row++;

        $top += 127;
      }
      $hexMap .= "</ul>";
      $hexCss .= "</style>";
      echo $hexCss.$hexMap;
    }
}

```

How do I move on from here so that I can click on edges and corners of the hexes?

# Answer
> 2 votes
I recommend reading this blog. Assuming you know the middle point coordinate and the width of every hexagon, from the linked blog you can easily calculate corner points. It is essential to know minimally these two.

I'm not sure if what you are referring as edges are the lines between points or the free space between the hexagons. Regardless, the blog shows you how to calculate it in the Size and Spacing section.

# Answer
> 0 votes
I googled css layers and came up with a lot of useful resources, for example: This one

What you could do is take another loop over your gameboard, and fill it with fully transparent edges and corners, layering it on top of your current board.

---
Tags: css, hexagonal-grid
---


# Question
Title: I need help with my explosion in bomberman
I am trying to recreate bomberman so far i have my players moving i can place bombs the hard part for me is the explosions because i need them to fill out one til to these directions : Right - Left - Up - Down

I found something that might be useful but not sure how to implement it

```
   for (int i = 0; i < explosion.powerUps.power; ++i)
    {
        tiles[actor.tileX - i][actor.tileY].explode(); //left
        tiles[actor.tileX + i][actor.tileY].explode(); //right
        tiles[actor.tileX][actor.tileY -i].explode(); //up
        tiles[actor.tileX][actor.tileY + i].explode(); //down
    }

```

I want to implement this for the explosions....

This is my code now:

```
window.addEventListener('load', pageLoaded);

var keys = {
    keyP1Up: false,
    keyP1Down: false,
    keyP1Right: false,
    keyP1Left: false,
    keyp1Bomb: false,
    keyP2Up: false,
    keyP2Down: false,
    keyP2Right: false,
    keyP2Left: false,
    keyP2Bomb: false,
    muteSound: false
};
var bombTimer = 2000;
var gameSound;
var myText;
var game = {};
var tiles = null;
var lives = 2;
var playerOne;
var playerTwo;
var level = 0;
var explosionSS;
var powerUps = {
    speed: 3,
    bombs: 1,
    power: 1
}
var bomb = {
    width: 59,
    height: 59
}
var playerOneBombs = [];
var playerTwoBombs = [];

function explosion(bomb) {
    game.stage.removeChild(bomb);
    createjs.Sound.play('bombAudio');
    console.log('Explosion sound');
    // Explosion sprite

    var explosionSS = new createjs.SpriteSheet(game.q.getResult('fire'));
    var bombExplosion = new createjs.Sprite(explosionSS, "fire");
    game.stage.addChild(bombExplosion);
    bombExplosion.width = 60;
    bombExplosion.height = 60;
    bombExplosion.x = bomb.x;
    bombExplosion.y = bomb.y;
    bombExplosion.addEventListener('animationend', function () {
        console.log("explosion over");
        game.stage.removeChild(bombExplosion);
    });
    console.log(bombExplosion);
    console.log('explosion');

}

```

I have only put in my code for my Explosions and my vars if needed more just tell me im really stuck and i dont really know how to implement my explosion so it goes to all the directions

# Answer
> 1 votes
You want to make two lines : A vertical one and a horizontal one and make sure the player's cell does not explode.

You want to iterate every cell on the actor's row and make it explode except the actor's cell.

```
for(i = 0; i < GRID_WIDTH; i++)
{
    if(i != actor.x)
        tiles[i][actor.y].explode();
}

```

And you want to do the same thing for the vertical bombing line

```
for(i = 0; i < GRID_HEIGHT; i++)
{
    if(i != actor.y)
        tiles[actor.x][i].explode();
}

```

# Answer
> 0 votes
Basically the example you found is assuming you have an object to represent your tiles. The tile objects are saved in a matrix and likely contain information on players on the tile, if the tile is passable, and if the tile is currently exploding or not. You can then use that information to tell when a tile should be playing its explosion animation and also when a player is colliding with an exploding tile.

---
Tags: javascript
---


# Question
Title: Is it illegal to decompile Unreal Engine maps from games?
I am currently in the process of learning to use Unreal Engine 4, and want to learn how certain games design their components. I know about the issues with decompiling Unreal Engine 3 to Unreal Engine 4, and are aware of the limitations. Is it legal to decompile maps for my own use, just as a learning opportunity, and not to profit from it in any way?

I searched online for advice, but the answers are wide and varying. Some claim that there is illegality, depending on where you live. Others claim nothing is illegal, as long as no attempt is made to profit from it, or claim it as your own.

# Answer
> 3 votes
As a disclaimer, please note that I am not a lawyer. As such, this should not be accepted as legitimate legal advice; always consult a lawyer, when it comes to legal issues that concern you.

## You might be covered by "Fair Use"

In general, you might be covered by "Fair Use". You are using the derived maps for your own personal use, and you are not profiting off them; nor are you misrepresenting the original authors or owners, in any way.

As long as you ensure private, personal use; you *should* be fine. That said, I am assuming you have legal rights to the game, to begin with; it is certainly *not* legal if said game was illegally acquired for this purpose.

## There are *always* exceptions

That being said, your location of residence *does* make a difference. Some locations have laws that differ to others, and depending on the circumstances, your legal requirements may differ.

In most cases, you can *also* be sued for *anything*. Assuming the company acting as the "claimant" wishes to pursue legal action, you still have to go to court to prove that you have a legitimate claim to use the files in that way. In many cases, you could be in trouble with the sheer legal fees involved in having such claims thrown out.

As such, the best advice is always to *consult a lawyer*. If the cost of said consultation out weights the cost of finding an alternate solution, find an alternate solution. Consider that a lawyer *might* advise you to find an alternate solution, anyway, due to the sheer fickle nature of copyright law.

## This is very unlikely to become a criminal case

I feel that I should make a final point, in regards to another answer. It is *very* unlikely that your actions could be considered *criminal*; even then, doing so would be a long stretch. Assuming legal action, at worst, you would be required to pay damages to a party.

Assuming legal action, assuming you *comply* with said legal action; this is *not* an issue that would lead to a jail sentence; at least, not of its own merit.

---
Tags: legal
---


# Question
Title: InvalidCastException when instantiating a prefab on the network using Photon
As stated in the title, I get this error when I try to instantiate a game object using Photon:

> InvalidCastException: Cannot cast from source type to destination type.
>
> NetworkingPeer.DoInstantiate (ExitGames.Client.Photon.Hashtable evData, .PhotonPlayer photonPlayer, UnityEngine.GameObject resourceGameObject) (at Assets/Photon/Photon Unity Networking/Plugins/PhotonNetwork/NetworkingPeer.cs:3069)
>
> PhotonNetwork.Instantiate (System.String prefabName, Vector3 position, Quaternion rotation, Int32 group, System.Object\[\] data) (at Assets/Photon/Photon Unity Networking/Plugins/PhotonNetwork/PhotonNetwork.cs:2493)
>
> PhotonNetwork.Instantiate (System.String prefabName, Vector3 position, Quaternion rotation, Int32 group) (at Assets/Photon/Photon Unity Networking/Plugins/PhotonNetwork/PhotonNetwork.cs:2437)
>
> GunController.EquipGun (.Gun gunToEquip) (at Assets/Scripts/Gun/GunController.cs:38)
>
> GunController.init () (at Assets/Scripts/Gun/GunController.cs:19)
>
> NetworkPlayer.Start () (at Assets/Scripts/Network/NetworkPlayer.cs:20)

Old, working code:

```
equippedGun = Instantiate(gunToEquip, weaponHold.position, weaponHold.rotation) as Gun;
equippedGun.transform.parent = weaponHold;

```

New code, using Photon:

```
equippedGun = PhotonNetwork.Instantiate(gunToEquip.name, weaponHold.position,
                                        weaponHold.rotation, 1).GetComponent<Gun>();
equippedGun.transform.parent = weaponHold;

```

(I do GetComponent, as normal instantiate returns Object and PhotonNetwork.Instantiate returns GameObject)

* equippedGun is by default an empty variable of type Gun
* gunToEquip is again a Prefab variable of type Gun that gets passed into the function. (PhotonNetwork.Instantiate takes in the name of the prefab, not the actual prefab, thus gunToEquip.name)

In this particular case, gunToEquip is the default gun that fails to instantiate, which is set by the unity inspector
* weaponHold is just a transform variable, again set by the inspector.

I somehow managed to fix it for my player prefab, I have no idea how. I was just changing and reverting stuff until it magically worked. How can I resolve this error?

Not sure if it is the problem, but I've attached the prefab settings:

# Answer
As per an answer I got on Unity answers:

> There is a little bug in the current PUN version which will be fixed with the next update. For now you can apply this fix yourself.
>
> Open PhotonNetwork class and look for all variants of the Instantiation function. These functions can be found (PUN version 1.84) in line 2435, line 2450 and line 2510. For each of this three functions look for the group parameter and change its type from int to byte.
>
> Now open the NetworkingPeer class and look for SendInstantiate function. In PUN 1.84 this function can be found in line 3001. Do the same like before and change the type of the group parameter from int to byte.

It worked like a charm, I'm leaving it here so other people with this problem can find it.
> 0 votes

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


# Question
Title: How do I get an Android device's screen size in exact pixels?
On every single android device {emulators} from ldpi to xxhdpi, both DisplayMetrics and native JNI EGL return width:320 and height:526. Even on actual HTC ONE mobile it returns something like 320x526. This is annoying. I need to know the exact pixel dimensions of the GL rendering surface {framebuffer/renderbuffer etc}. How can I do that ?

From Java activity class I am doing:

```
DisplayMetrics metrics = getResources().getDisplayMetrics();
int widthPixels = metrics.widthPixels;
int heightPixels = metrics.heightPixels;

```

From the JNI C++ code I am going following with NO luck (again output: Size = 320 x 526):

```
int W, H;
EGLDisplay display = eglGetCurrentDisplay();
EGLSurface surface = eglGetCurrentSurface(EGL_READ);
eglQuerySurface(display, surface, EGL_WIDTH, &W);
eglQuerySurface(display, surface, EGL_HEIGHT, &H);

LOGI("JNIGlue.cpp:Init:EGL-Width : %d", W);
LOGI("JNIGlue.cpp:Init:EGL-Height: %d", H);

glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_WIDTH, &W);
glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_HEIGHT, &H);

LOGI("JNIGlue.cpp:Init:RB-Width : %d", W);
LOGI("JNIGlue.cpp:Init:RB-Height: %d", H);

```

So how do I get the exact OpenGL rendering surface/buffer size ?

# Answer
> 2 votes
Not sure about doing it with JNI/C++ but in Java I just query the `GLSurfaceView` for it's size with surface.getWidth() and surface.getHeight(). This provides the exact pixel dimensions of the view/surface.

# Answer
> -1 votes
Does this work for you ?

```
    sp<IBinder> mainDpy = SurfaceComposerClient::getBuiltInDisplay(
                        ISurfaceComposer::eDisplayIdMain);
    DisplayInfo mainDpyInfo;
    err = SurfaceComposerClient::getDisplayInfo(mainDpy,
                                                &mainDpyInfo);

```

Essentially what we are doing here is:

1. Getting a reference to the built in display (main screen) in the form of a binder (a mechanism for IPC)
2. Then we query the display subsystem about the properties of the display that we queried in Step 1. This returns the data in the form of a structure DisplayInfo which has the following members:

struct DisplayInfo { uint32\_t w; uint32\_t h; PixelFormatInfo pixelFormatInfo; uint8\_t orientation; uint8\_t reserved\[3\]; float fps; float density; float xdpi; float ydpi; };

You should have the info you require. See this

---
Tags: android, opengl-es2, resolution, egl
---


title: How to resize a D3D11Texture2D?

text:
# Question
Title: How to resize a D3D11Texture2D?
I would like to scale a D3D11Texture2D to make it smaller.

I'm using AcquireNextFrame to get an output of my desktop but it's on FullHD resolution. I just want to scale the texture because I need then to send the buffer over network.

Here is my code :

```
if (mRealTexture == nullptr) {
        D3D11_TEXTURE2D_DESC description;
        texture2D->GetDesc(&description);
        description.BindFlags = 0;
        description.CPUAccessFlags = D3D11_CPU_ACCESS_READ | D3D11_CPU_ACCESS_WRITE;
        description.Usage = D3D11_USAGE_STAGING;
        description.MiscFlags = 0;
        hr = mDevice->CreateTexture2D(&description, NULL, &mRealTexture);
        if (FAILED(hr)) {
            if (mRealTexture) {
                mRealTexture->Release();
                mRealTexture = nullptr;
            }
            return NULL;
        }
    }
    mImmediateContext->CopyResource(mRealTexture, texture2D);

    if (mScaledTexture == nullptr) {
        D3D11_TEXTURE2D_DESC description;
        texture2D->GetDesc(&description);
        description.CPUAccessFlags = D3D11_CPU_ACCESS_READ | D3D11_CPU_ACCESS_WRITE;
        description.BindFlags = D3D11_BIND_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE;
        description.Width = 1440;
        description.Height = 585;
        description.MipLevels = 4;
        description.ArraySize = 1;
        description.SampleDesc.Count = 1;
        description.SampleDesc.Quality = 0;
        description.Usage = D3D11_USAGE_DEFAULT;
        hr = mDevice->CreateTexture2D(&description, NULL, &mScaledTexture);
        if (FAILED(hr)) {
            if (mScaledTexture) {
                mScaledTexture->Release();
                mScaledTexture = nullptr;
            }
            return NULL;
        }
    } //How to copy the mRealTexture to the mScaledTexture and get the new buffer ?

    D3D11_MAPPED_SUBRESOURCE mapped;
    hr = mImmediateContext->Map(mRealTexture, 0, D3D11_MAP_READ_WRITE, 0, &mapped);
    if (FAILED(hr)) {
        mRealTexture->Release();
        mRealTexture = NULL;
        return NULL;
    }
    unsigned char *source = static_cast<unsigned char *>(mapped.pData);

```

Thank you very much for your help.

# Answer
> 2 votes
CopyResource does not support scaling.

Mapping would work, but:

1. You would need to write your own scaling algorithm
2. You would need to download the data from GPU to system memory before scaling,
3. You would need to re-upload the data back to the GPU after scaling.

Two ways spring to mind.

**One**

Create the texture with D3D11\_BIND\_RENDER\_TARGET, use ID3D11DeviceContext::GenerateMips, then send one of the miplevels; miplevel 0 is the full resolution texture, miplevel 1 is half resolution in each dimension, miplevel 2 is quarter resolution in each dimension, etc.

**Two**

Draw the texture to a lower-resolution rendertarget, then use that rendertarget instead of the original source texture.

---
Tags: 2d, textures, directx11, gpu
---


title: Unity 5.6 unsafe code not working

text:
# Question
Title: Unity 5.6 unsafe code not working
I am using C++ plugins and passing out array ptrs in my function. Unity 5.6 keeps complaining about unsafe code. I added every type of .rsp file with the "-unsafe" keyword, but none of it works. Anyone figure this out for unity 5.6?

# Answer
> 2 votes
Are you sure that unsafe code cannot be enabled?

* You must create the file **mcs.rsp** (with *-unsafe* inside of the file).
* You must also change Api Compatibility level to .net 2.0 subset
* Restart both Unity/Visual Studio to make it work.

(See this answer for a detailed explanation)

However, if none of these works, there is another (untested) way.

* Create a .net dll, compiled with unsafe flag (Tick "Allow unsafe code" in VS Project Settings)
* Place your unsafe code in that dll
* Then just call your unsafe function from Unity

Please note this is untested and is better to try the 1st way

In any case, make sure your function has the unsafe keyword at the definition:

```
 public unsafe intPtr myUnsafeFunction() // just an example

```

Or wrap your unsafe code with unsafe { }

```
 unsafe {
      // your unsafe code
 }

```

Hope that helps

---
Tags: unity, plugin
---


# Question
Title: How to Create A Vertex Buffer Object from Wavefront Data
I have written my own Wavefront Model parser, which I have been using for quite some time to render meshes in immediate mode. However, I now wish to upgrade my system to `Vertex Buffer Objects`. I was doing a lot of reading online about how to create `Vertex Buffer Objects`, but most(really all) of the links I found online did not seem to exactly answer the question of how to upload the indices(or in my case, Faces); it's entirely plausible that my Google Kung-Fu has just been lacking though.

I'm interested in taking my current Wavefront Model implementation, tweaking it if necessary, and creating a VBO out of the data that it contains, and then rendering it. *I'm certain that the only real issue is how I store the Indice data(I do so in Faces), which I think needs to be implemented as a single array.* Again, I'm not very knowledgable in modern OpenGL, so I don't know how to proceed or what modifications are required going forward.

Here is my implementation:

**WavefrontModel.cs**

```
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using GrimoireEngine.Framework.Maths;
using GrimoireEngine.Framework.Rendering.OpenGL.Texturing;
using GrimoireEngine.Framework.Rendering.OpenGL.Utilities;
using OpenTK;
using OpenTK.Graphics.OpenGL;

namespace GrimoireEngine.Framework.Rendering.OpenGL.Modeling
{
    public class WavefrontModel
    {
        /// <summary>
        /// The String Identifier of this Model
        /// </summary>
        public string Identifier { get; set; }
        /// <summary>
        /// The Vertices of this Model
        /// </summary>
        public Vector3[] Vertices;
        /// <summary>
        /// The TexCoords of this Model
        /// </summary>
        public Vector2[] TexCoords;
        /// <summary>
        /// The Normals of this Model
        /// </summary>
        public Vector3[] Normals;
        /// <summary>
        /// The Faces of this Model
        /// </summary>
        public Face[] Faces; // May be entirely deprecated.

        /// <summary>
        /// Testing some shit.
        /// </summary>
        public List<int> Indices;
        /// <summary>
        /// The Original File Source
        /// </summary>
        public string ModelSource { get; set; }

        /// <summary>
        /// The Material of this Model
        /// </summary>
        public Material Material { get; set; }

        /// <summary>
        /// The Triangle Count of this model.
        /// </summary>
        public int TriCount
        {
            get
            {
                return Faces.Length;
            }
        }

        public WavefrontModel()
        {

        }

        public WavefrontModel(string modelPath, Material material, bool load = true)
        {
            this.ModelSource = modelPath;
            this.Material = material;
            if (load)
            {
                Load(modelPath);
            }
        }

        public WavefrontModel(string modelPath, bool load = true)
        {
            this.ModelSource = modelPath;
            this.Material = null;
            if (load)
            {
                Load(modelPath);
            }
        }

        public WavefrontModel(string[] data)
        {
            this.Material = null;
            Load(data);
        }

        public WavefrontModel(string[] data, Material material)
        {
            this.Material = material;
            Load(data);
        }

        /// <summary>
        /// Loads a model from the desired Wavefront.obj source given
        /// at constructor initialization.
        /// </summary>
        public void Load()
        {
            Load(this.ModelSource);
        }

        /// <summary>
        /// Loads a model from a Wavefront.obj located on disk.
        /// </summary>
        /// <param name="file"></param>
        public void Load(string file)
        {
            Parse(File.ReadAllLines(file));
        }

        /// <summary>
        /// Loads a model from a Wavefront.obj located on disk.
        /// </summary>
        /// <param name="data"></param>
        public void Load(string[] data)
        {
            Parse(data);
        }

        /// <summary>
        /// Sets the internal Model Arrays to null.
        /// </summary>
        public void Clear()
        {
            Vertices = null;
            TexCoords = null;
            Normals = null;
            Faces = null;
        }

        /// <summary>
        /// Parses Wavefront data from desired array.
        /// </summary>
        /// <param name="data"></param>
        public void Parse(string[] data)
        {
            // Create File Manifest
            int totalVertices = 0;
            int totalNormals = 0;
            int totalTextureCoordinates = 0;
            int totalFaces = 0;
            for (int i = 0; i < data.Length; i++)
            {
                char firstChar = data[i][0];
                switch (firstChar)
                {
                    case 'v':
                        char secondChar = data[i][1];
                        switch (secondChar)
                        {
                            case ' ':
                                totalVertices++;
                                break;
                            case 't':
                                totalTextureCoordinates++;
                                break;
                            case 'n':
                                totalNormals++;
                                break;
                        }
                        break;
                    case 'f':
                        totalFaces++;
                        break;
                }
            }
            // Create the Buffers
            Vertices = new Vector3[totalVertices];
            Normals = new Vector3[totalNormals];
            TexCoords = new Vector2[totalTextureCoordinates];
            Faces = new Face[totalFaces];
            // Create File Reading Buffers
            string[] fileBuffer = new string[20];
            string[] indiceBuffer = new string[3];
            Vertex[] vertexBuffer = new Vertex[3];
            // Iterators
            int verticesIterator = 0;
            int normalsIterator = 0;
            int textureCoordinatesIterator = 0;
            int facesIterator = 0;
            for (int line = 0; line < data.Length; line++)
            {
                SplitStringFast(data[line], ' ', fileBuffer);
                char firstChar = data[line][0];
                switch (firstChar)
                {
                    case 'v':
                        char secondChar = data[line][1];
                        switch (secondChar)
                        {
                            case ' ':
                                Vector3 vertex = new Vector3
                                {
                                    X = Single.Parse(fileBuffer[1]),
                                    Y = Single.Parse(fileBuffer[2]),
                                    Z = Single.Parse(fileBuffer[3])
                                };
                                Vertices[verticesIterator] = vertex;
                                verticesIterator++;
                                break;
                            case 't':
                                Vector2 textureCoordinate = new Vector2
                                {
                                    X = Single.Parse(fileBuffer[1]), // U
                                    Y = -Single.Parse(fileBuffer[2]) // V (Inverted)
                                };
                                TexCoords[textureCoordinatesIterator] = textureCoordinate;
                                textureCoordinatesIterator++;
                                break;
                            case 'n':
                                Vector3 normal = new Vector3
                                {
                                    X = Single.Parse(fileBuffer[1]),
                                    Y = Single.Parse(fileBuffer[2]),
                                    Z = Single.Parse(fileBuffer[3])
                                };
                                Normals[normalsIterator] = normal;
                                normalsIterator++;
                                break;
                        }
                        break;
                    case 'f':
                        for (int i = 0; i < 3; i++)
                        {
                            SplitStringFast(fileBuffer[i + 1], '/', indiceBuffer);
                            Vertex indices = new Vertex
                            {
                                VertexIndice = GrimoireMathHelper.ParsePositiveInt32Fast(indiceBuffer[0]) - 1,
                                TextureIndice = GrimoireMathHelper.ParsePositiveInt32Fast(indiceBuffer[1]) - 1,
                                NormalIndice = GrimoireMathHelper.ParsePositiveInt32Fast(indiceBuffer[2]) - 1
                            };
                            vertexBuffer[i] = indices;
                        }
                        Faces[facesIterator] = new Face(vertexBuffer);
                        facesIterator++;
                        break;
                }
            }
        }

        /// <summary>
        /// A custom implementation of String.Split(). Realistically, this
        /// function is not much faster than what .NET offers; it gains speed
        /// more from a preset buffer mechanism. There is no bounds checking done
        /// for the buffer, which is done by design to assure optimal performance.
        /// </summary>
        /// <param name="value"></param>
        /// <param name="delimiter"></param>
        /// <param name="buffer"></param>
        /// <returns></returns>
        private static void SplitStringFast(string value, char delimiter, string[] buffer)
        {
            int resultIndex = 0;
            int startIndex = 0;
            for (int i = 0; i < value.Length; i++)
            {
                if (value[i] == delimiter)
                {
                    buffer[resultIndex] = value.Substring(startIndex, i - startIndex);
                    resultIndex++;
                    startIndex = i + 1;
                }
            }
            buffer[resultIndex] = value.Substring(startIndex, value.Length - startIndex);
        }

        /// <summary>
        /// Renders the Model using deprecated immediate mode. This
        /// function exists only for testing purposes.
        /// </summary>
        public void DrawImmediate()
        {
            //GL.Enable(EnableCap.Texture2D);
            GL.Color3(Material.AmbientColor);
            Material.Bind();

            GL.Begin(PrimitiveType.Triangles);
            for (int i = 0; i < Faces.Length; i++)
            {
                /**
                 * One
                 */

                GL.Normal3(Normals[Faces[i].One.NormalIndice]);
                //GL.VertexAttrib2(1, TexCoords[Faces[i].One.TextureIndice]); // For use with shaders.
                GL.TexCoord2(TexCoords[Faces[i].One.TextureIndice]);
                GL.Vertex3(Vertices[Faces[i].One.VertexIndice]);
                /**
                 * Two
                 */
                GL.Normal3(Normals[Faces[i].Two.NormalIndice]);
                GL.TexCoord2(TexCoords[Faces[i].Two.TextureIndice]);
                //GL.VertexAttrib2(1, TexCoords[Faces[i].Two.TextureIndice]); // For use with shaders
                GL.Vertex3(Vertices[Faces[i].Two.VertexIndice]);
                /**
                 * Three
                 */
                GL.Normal3(Normals[Faces[i].Three.NormalIndice]);
                GL.TexCoord2(TexCoords[Faces[i].Three.TextureIndice]);
                //GL.VertexAttrib2(1, TexCoords[Faces[i].Three.TextureIndice]); // For use with Shaders
                GL.Vertex3(Vertices[Faces[i].Three.VertexIndice]);
            }
            GL.End();
            //GL.BindTexture(TextureTarget.Texture2D,0);
            //GL.Disable(EnableCap.Texture2D);
        }

        /// <summary>
        /// Compiles this WavefrontModel into a VertexBufferObject
        /// </summary>
        public void Compile(BufferUsageHint bufferUsageHint)
        {
            /**
             * This is where I'm starting to create my VBO's...I just don't really
             * know how to proceed.
             */
            int vboHandle;
            int size;
            // Vertices
            GL.GenBuffers(1, out vboHandle);
            GL.BindBuffer(BufferTarget.ArrayBuffer, vboHandle);
            GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)(Vertices.Length * BlittableValueType.StrideOf(Vertices)), Vertices, bufferUsageHint);
            GL.GetBufferParameter(BufferTarget.ArrayBuffer, BufferParameterName.BufferSize, out size);
            if (Vertices.Length * BlittableValueType.StrideOf(Vertices) != size)
            {
                throw new ApplicationException("Vertex data not uploaded correctly");
            }
            //
            // How do I handle indices?
        }

        /// <summary>
        /// Draw the VBO
        /// </summary>
        public void Render()
        {
            throw new NotImplementedException("Rendering VBO's not yet implemented!");
        }
    }
}

```

**Face.cs**

```
using System;

namespace GrimoireEngine.Framework.Rendering.OpenGL.Modeling
{
    public struct Face : IEquatable<Face>
    {
        public Vertex One;
        public Vertex Two;
        public Vertex Three;

        public static Face Empty
        {
            get
            {
                return new Face();
            }
        }

        public Face(Vertex[] vertexIndices)
        {
            this.One = vertexIndices[0];
            this.Two = vertexIndices[1];
            this.Three = vertexIndices[2];
        }

        public Face(Vertex one, Vertex two, Vertex three)
        {
            this.One = one;
            this.Two = two;
            this.Three = three;
        }

        public bool Equals(Face other)
        {
            return One == other.One && Two == other.Two && Three == other.Three;
        }

        public override bool Equals(object obj)
        {
            return obj is Face && Equals((Face)obj);
        }

        public static bool operator ==(Face f1, Face f2)
        {
            return f1.Equals(f2);
        }

        public static bool operator !=(Face f1, Face f2)
        {
            return !(f1.Equals(f2));
        }

        public Vertex[] ToArray()
        {
            return new[] { One, Two, Three };
        }

        public override int GetHashCode()
        {
            unchecked
            {
                int hashCode = One.GetHashCode();
                hashCode = (hashCode * 31) ^ Two.GetHashCode();
                hashCode = (hashCode * 31) ^ Three.GetHashCode();
                return hashCode;
            }
        }
    }
}

```

**Vertex.cs**

```
using System;

namespace GrimoireEngine.Framework.Rendering.OpenGL.Modeling
{
    public struct Vertex : IEquatable<Vertex>
    {

        public int VertexIndice;
        public int TextureIndice;
        public int NormalIndice;

        public static Vertex Empty
        {
            get
            {
                return new Vertex();
            }
        }

        public Vertex(int[] indices)
        {
            this.VertexIndice = indices[0];
            this.NormalIndice = indices[1];
            this.TextureIndice = indices[2];
        }

        public Vertex(int vertexIndice, int normalIndice, int textureIndice)
        {
            this.VertexIndice = vertexIndice;
            this.TextureIndice = textureIndice;
            this.NormalIndice = normalIndice;
        }

        public bool Equals(Vertex other)
        {
            return VertexIndice == other.VertexIndice &&
                   TextureIndice == other.TextureIndice &&
                   NormalIndice == other.NormalIndice;
        }

        public override bool Equals(object obj)
        {
            return obj is Vertex && Equals((Vertex)obj);
        }

        public static bool operator ==(Vertex v1, Vertex v2)
        {
            return v1.Equals(v2);
        }

        public static bool operator !=(Vertex v1, Vertex v2)
        {
            return !(v1 == v2);
        }

        /// <summary>
        /// Order = VertexIndice, TextureIndice, NormalIndice
        /// </summary>
        /// <returns></returns>
        public int[] ToArray()
        {
            return new[] { VertexIndice, TextureIndice, NormalIndice };
        }

        public override int GetHashCode()
        {
            unchecked
            {
                int hashCode = VertexIndice;
                hashCode = (hashCode * 31) ^ TextureIndice;
                hashCode = (hashCode * 31) ^ NormalIndice;
                return hashCode;
            }
        }
    }
}

```

***My Question:*** How can I modify this implementation to create `Vertex Buffer Objects`? Or, if applicable, how can I use this implementation to create and render a `Vertex Buffer Object`? Thank you for your time and assistance!

Questions like this that I feel don't answer my question:

https://stackoverflow.com/questions/21845613/writing-wavefront-obj-parser-for-use-with-opengl-indexed-vertex-buffer-objects

# Answer
The good news is that you already have most of the code that you need to do this. It's easy to take glBegin/glEnd code, modify it to write to a memory buffer instead of making direct glTexCoord/glVertex/etc calls, then send to a buffer object (using glBufferData) and finally set up your vertex attrib pointers/etc.

For example, let's say that you have the following glBegin/glEnd code. I'm going to use C/C++ style syntax here but it should be obvious what the C# equivalent is:

```
glBegin (GL_QUADS);

glTexCoord2f (0, 0);
glVertex2f (10, 10);

glTexCoord2f (0, 1);
glVertex2f (10, 74);

glTexCoord2f (1, 1);
glVertex2f (74, 74);

glTexCoord2f (1, 0);
glVertex2f (74, 10);

glEnd ();

```

How to convert that to use a buffer object instead?

Let's begin by defining a vertex structure:

```
struct Vertex
{
    float TexCoord[2];
    float Position[2];
};

```

4 vertices make a quad so let's declare 4 of them:

```
Vertex vertices[4];

```

Then we'll write out the data:

```
vertices[0].TexCoord[0] = 0;
vertices[0].TexCoord[1] = 0;
vertices[0].Position[0] = 10;
vertices[0].Position[1] = 10;

vertices[1].TexCoord[0] = 0;
vertices[1].TexCoord[1] = 1;
vertices[1].Position[0] = 10;
vertices[1].Position[1] = 74;

vertices[2].TexCoord[0] = 1;
vertices[2].TexCoord[1] = 1;
vertices[2].Position[0] = 74;
vertices[2].Position[1] = 74;

vertices[3].TexCoord[0] = 1;
vertices[3].TexCoord[1] = 0;
vertices[3].Position[0] = 74;
vertices[3].Position[1] = 10;

```

Compare each of these blocks to each glTexCoord/glVertex pair above and you should see what's happening.

Finally we can write the result out to a buffer object:

```
glBufferData (GL_ARRAY_BUFFER, 4 * sizeof (Vertex), vertices, GL_STATIC_DRAW);

```

And draw it:

```
glDrawArrays (GL_QUADS, 0, 4);

```

Just ensure that you build the buffer once-only (at loading time) rather than every frame and you'll be good.
> 2 votes

---
Tags: c#, opengl, vbo
---


# Question
Title: Using a vector to measure an angle relative to the screen / camera
My game is supposed to have an object that changes it sprite depending on which way the mouse faces. programming this has become a challenge, because I want to calculate the angle relative to the center of the screen using the X axis.

To explain what I mean, pretend that under a sprite in the center of a screen is a protractor.

I want to measure the angle that's formed between the cursor and the center. If I use the X axis as a base, I should get an angle between 180° and -180°.

How would I achieve this? I've tried `vector.angle(reference-vector)`, but that doesn't seem to give the desired result.

# Answer
You can get the angle in radians using the Math.atan2 method shown below:

```
double angleRadians = Math.atan2(mousey-spriteCentery,mousex-spriteCenterx);

```

You can then convert this using MathUtils

```
float angleDegrees = angleRadians * MathUtils.radiansToDegrees;

```

Edit: Updated to reflect suggestion by DMGregory for correct axis direction.
> 2 votes

# Answer
I assume you're basically trying to make the sprite face a different diagonal based on which quadrant of the screen your mouse is in. Since you likely don't require the specific angle but rather simply which quadrant the mouse is in simply get the vector between the player and the mouse.

* If both x and y are positive the mouse is in the upper right quadrant.
* If x is negative, and y is positive the mouse is in the upper left.
* If both are negative the mouse is in the bottom left.
* if x is positive and y is negative it's in the bottom right.

Using the information on which quadrant the mouse is in you can just use that to update the state of your sprite.
> 0 votes

---
Tags: libgdx, algorithm, sprites, geometry
---


# Question
Title: Saving Very Little Data But for Lots of Objects
Imagine 50 instances of one type of object and 25 instances of another. Both types of object needs to remember a simple Boolean or int for their own purposes that can be saved to file and reloaded. For the life of me, I cannot find any help on the interwebs regarding the best way to do this. I already know and understand how to use serialization and deserialization, but I cannot figure out how to organize this. I obviously don't want 75 save files but I can't think of a good way to combine their data to one save file--especially since not everything is serializable. Any help??

# Answer
> 0 votes
After weeks of trying to figure out the best way to save data that is spread out in a ton of objects, I've finally come to a good solution! I've seen lots of other people ask a similar question yet they all remain unanswered for some reason. Hopefully this helps!

First, I created a new data type I called SaveVar. If I want something saved, I use a SaveVar. I made it a template so I could use it for multiple data types. I have to imagine something this basic already exists, but I don't know what it is. The reason I created this new type is so that it can be passed, stored, and monitored as a reference in a SaveData dictionary.

```
[System.Serializable]
public class SaveVar<T>
{
    T val;

    public SaveVar(T v)
    {
        val = v;
    }

    public T get()
    {
        return val;
    }

    public void set(T v)
    {
        val = v;
    }
}

```

So once I have a SaveVar anywhere I want in the code, I can "register" it to my save data so that it can be saved and recalled at load. I register my SaveVar with a unique string ID that I can set in the inspector (i.e. "Dungeon1\_Room8\_Door2"). The door will register that string with an instance of a SaveVar which will be stored in a serializable Dictionary. I couldn't find a way to use only one dictionary and I couldn't seem to create functions that would allow all types of SaveVar. So for now I'm creating unique functions for each type of SaveVar I want to save. Almost defeats the purpose of the template. If someone knows a better way, by all means let me know :-).

```
[System.Serializable]
public class AllData
{
    private Dictionary<string, SaveVar<bool>> bools = new Dictionary<string, SaveVar<bool>>();
    private Dictionary<string, SaveVar<bool>[]> boolArrays = new Dictionary<string, SaveVar<bool>[]>();

    public void registerBool(string s, SaveVar<bool> sv)
    {
        // if upon registering we find that it exists already (i.e. was loaded) then grab the value and put it in the SaveVar passed in.
        if (bools.ContainsKey(s))
        {
            sv.set(bools[s].get());
            bools[s] = sv;
        }
        else
        {
            bools.Add(s, sv);
        }
    }

    public void registerBoolArray(string s, SaveVar<bool>[] sv)
    {
        // if upon registering we find that it exists already (i.e. was loaded) then grab the value and put it in the SaveVar passed in.
        if (boolArrays.ContainsKey(s))
        {
            SaveVar<bool>[] ba = boolArrays[s];
            for (int i = 0; i < ba.Length; i++)
            {
                sv[i].set(ba[i].get());
            }
            boolArrays[s] = sv;
        }
        else
        {
            boolArrays.Add(s, sv);
        }
    }
}

```

So my AllData class now contains all the data within my game that I want to save. When I register my SaveVar, I'm effectively loading it as well. So right after registering, I just check its value and "unlock" the door if it is true. When the door unlocks, it will change the value of SaveVar which is already registered so, upon saving, it will already have the updated value. All that's left is the actual saving it and loading it.

Save (upon some event):

```
    Debug.Log("Saving SaveData");
    BinaryFormatter bf = new BinaryFormatter();
    FileStream file = File.Create(Application.persistentDataPath + "/SaveData.dat");
    bf.Serialize(file, data);
    file.Close();

```

Load on Awake in a SaveController MonoBehaviour:

```
    if (File.Exists(Application.persistentDataPath + "/SaveData.dat"))
    {
        Debug.Log("Loading SaveData");
        BinaryFormatter bf = new BinaryFormatter();
        FileStream file = File.Open(Application.persistentDataPath + "/SaveData.dat", FileMode.Open);
        data = (AllData)bf.Deserialize(file);
    }

```

---
Tags: savegame, serialization
---


# Question
Title: Instantiate a GameObject in front of (snap to grid) my character
In a 2d top-down game, what would be the best approach to Instantiate a GameObject in front of my player as he moves around and I, for example, plant a tree.

I was thinking about creating a small trigger-collider that will always be 1 unit in front of my player, then get the `Mathf.Round` position of the ground-object that collider is currently overlapping, and place the tree there.

However the more I think about it the uglier that solution seems, is there some better way? Performance wise and just design wise. Maybe I could somehow get the wolrdposition of my player, his direction, and the amount of units in front I want to place the object (1), and Instantiate it there. But with this approach I cant check if I already planted a tree in the location, since I dont have a collider. i.e this approach would not know what GameObject is in front of the player.

Is my first approach okay or is there some better way?

# Answer
> 1 votes
From your description of a 'ground-object' I am under the impression that your game is tile-based and the tiles have information on what objects the tile may contain? If that is the case, the tile should be aware that the player is on it, or the player should be aware of the tile he is located on. Use that information and the player's facing information to get the direction you would like to check tiles in. Check the tile if it contains an object already, and if not plant the tree. If I am misunderstanding please provide a little more information on what a ground-object is and how you are storing location information.

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


# Question
Title: Unity prefabs, are these common patterns?
I am developing an arcade racing game. And I'd like to know why you'd make a prefab for every car vs creating a single prefab for all cars. Here are some examples:

Project 1: This project uses a main prefab (CompelteTank) as a Controller, managing everything, spawn, control, physics, etc. And add a Layout prefab according to the select Tank model, applying the weight by this same model id.

Project 2: This project uses different prefab for each car, I believe this follows the standard of car games like simulators.

# Answer
These examples represent two common approaches. Essentially, there's a spectrum between **programmatic** and **manual** asset creation. The first project is closer to the programmatic end of the spectrum and the second is closer to the manual end of the spectrum.

Choosing between the two will depend on how you want your project organized and the level of coding you're comfortable with.

Personally, I would choose option one. There are a few major benefits with creating cars more by script than with prefab:

1. Cars can be generated purely from an external data file. This means you (or your users) can add additional cars later on, simply by loading in new data to your "CarGenerator" prefab.
2. Changes to scripts can be merged much easier than changes to a prefab. This is especially important when working in a team environment like you are. If two people made changes to a prefab, it's going to be harder to merge the changes between two prefabs (it gets easier by forcing text serialization in the project settings).
3. You can more easily make changes to all your cars, by just changing one car. Consider if you created a new script that needed to be attached to cars. You'd have to attach that script to each of your car prefabs. In the case of using a single prefab that generates all cars, that's only one car prefab that needs modifying.

On the other side of things, having a prefab for each car has benefits as well:

1. It's much less scripting work. This means it's likely faster to for a team that doesn't have a lot of coding experience to add new cars.
2. It's less complex. You make it once and it is always going to be generated in the way you made it. This simplifies the creation of assets.
> 1 votes

---
Tags: unity, design-patterns
---


title: Simple wandering chicken AI in Unity

text:
# Question
Title: Simple wandering chicken AI in Unity
I have a very minor NPC. A chicken. My target is for it to move a random amount, in a random direction for a random time then wait a random amount of time before moving again. Like a chicken. But I do not want it to be to complicated. Still as I am very new in Unity and C# it really got me (it was easier to make a controllable character)

**This is my code:**

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

public class CockBrain : MonoBehaviour {

    public float duration;    //the max time of a walking session (set to ten)
    float elapsedTime   = 0f; //time since started walk
    float wait          = 0f; //wait this much time
    float waitTime      = 0f; //waited this much time

    float randomX;  //randomly go this X direction
    float randomZ;  //randomly go this Z direction

    bool move = true; //start moving

    void Start(){
        randomX =  Random.Range(-3,3);
        randomZ = Random.Range(-3,3);
    }

    void Update ()
    {

        //Debug.Log (elapsedTime);

        if (elapsedTime < duration && move) {
            //if its moving and didn't move too much
            transform.Translate (new Vector3(randomX,0,randomZ) * Time.deltaTime);
            elapsedTime += Time.deltaTime;

        } else {
            //do not move and start waiting for random time
            move        = false;
            wait        = Random.Range (5, 10);
            waitTime    = 0f;
        }

        if (waitTime < wait && !move) {
            //you are waiting
            waitTime += Time.deltaTime;

        } else {
        //done waiting. Move to these random directions
            move = true;
            randomX = Random.Range(-3,3);
            randomZ = Random.Range(-3,3);
        }
    }

}

```

What is happening: they are "vibrating" and rotating randomly, then stop after duration and never move again. **The prefab is set up like this**.

# Answer
It seems like the reason the chicken never starts moving again is because you never reset your elapsed time, so you instantly go back into your else that stops the movement again.

I believe the reason your chicken vibrates is because you randomize his movement every frame even while he's still moving. change your else to an else if.

```
else if(!move){
    move = true;
    elapsedTime = 0f;
    randomX = Random.Range(-3,3);
    randomZ = Random.Range(-3,3);
}

```
> 5 votes

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


# Question
Title: How to deal with weapon power-creep in an RPG?
***Power creep*** *is a process that sometimes occurs in games where new content slowly outstrips the power of previous alternatives. This leads to players abandoning previous options in favour of the latest and more powerful alternatives, resulting in an inevitable increase in power throughout the game.*

I am developing a private RPG that has approximately 10 players. Although the scale of the game is very small, it is falling victim to power-creep. Four players have reached the current "end-game" weapon and armor set and are running out of things to accomplish in terms of collecting the most powerful items.

I have a lot of great ideas planned, but many of them involve releasing weapons that are not stronger than the current strongest. The negative of this is that the players who have already achieved something greater don't look forward to the content update, and tend to come online less often. I don't want to release a weapon that is stronger, because this releases a lot of new issues with balancing in other areas of the game.

I have a couple of ideas that could slow this issue:

* Although the new weapons may hit less damage, they may perform different effects that benefit the player in different ways
* Reduce the damage of all weapons, so the slot for the previously-strongest weapon opens up for a new weapon.

**How do I slow/stop power-creep of weapons and armors? (This question is *not* about finding ways to keep players online longer).**

# Answer
Instead of expanding your game vertically (creating more and more powerful content) consider expanding it horizontally (creating more and more *versatile* content).

Introduce weapons which aren't more powerful *per se* but instead use different game mechanics which make them more useful in some situations but less useful in others. Then release weapons of this new kind for all tiers of your game, so everyone can experiment with the new game mechanic.

Another option is to simply raise the level ceiling. Give the players more powerful items, but also add new, more difficult content which means they will need them.

And when that's no longer an option, consider to give some incentive for players to start over from the beginning. Give those who have reached max level the option to start fresh from level 1 with no equipment (no loopholes by trading your equip to someone else), but with some little permanent bonus which will mean that when they reach max level again, they will just be a tiny bit stronger than before.
> 3 votes

# Answer
Create new enemies that are resistant to existing weapon types. The new weapons can be more effective on the new enemies, but not necessarily more powerful overall.
> 0 votes

---
Tags: game-design
---


title: Instancing mirrored geometry

text:
# Question
Title: Instancing mirrored geometry
I'm rendering mirrored geometry by flipping it's world matrix. Before rendering mirrored geometry I set `CULL_FRONT` rasterizer state (for normal geometry it's `CULL_BACK`). This works perfectly.

However, I've started implementing instancing and would like to instance mirrored and not mirrored geometry together. What's optimal way to do it?

So far I've considered:

* `CULL_NONE`, but it has huge impact on shading performance
* Geometry shader to flip triangles, but GS is generally slow

Is there any other option? I've found `SV_IsFrontFace`, but there's not much documentation about it. I would like to tell GPU in VS: Hey, this triangle should be flipped.

# Answer
I would sort the instances mirror/no mirror. Make the first draw call, update the rasterizer with the cull mode you want then render the mirror'd instances. Its overhead on CPU, but it shouldnt be much.

If you need to multiply the mirrored by some inversion matrix, then I would pass this in a constant buffer and get the GPU to multiply this in VS.
> 1 votes

---
Tags: directx, directx11, sharpdx, instancing
---


# Question
Title: How do I implement A* pathfinding for enemies to follow the player?
The enemies in my game are supposed to follow the player in order to cause damage to it. Right now, I have it where the enemy just goes in the direction that will bring it closer to the player, and this works fine, but the enemy gets caught on obstacles and solid tiles. The `Collision.tileCollision` methods check to see if there is or will be a collision with any solid tiles, by adding the speed of the enemy to its current coordinate, in order to look ahead for collisions. If there is no collision, and the direction its checking will bring the enemy closer to the player, then it goes in that direction.

```
if (Collision.tileCollisionRight(this.thisEnemy, this.thisEnemy.getSpeed(), currentLevel)
    == false && (Math.abs((this.thisEnemy.getX() + this.thisEnemy.getSpeed())
    - this.player.getX()) < Collision.getXDist(this.thisEnemy, this.player)))
{
    //Should/Can go right
    this.thisEnemy.setX(this.thisEnemy.getX() + this.thisEnemy.getSpeed());
}
else if (Collision.tileCollisionLeft(this.thisEnemy, this.thisEnemy.getSpeed(), currentLevel)
    == false && (Math.abs((this.thisEnemy.getX() - this.thisEnemy.getSpeed())
    - this.player.getX())) < Collision.getXDist(this.thisEnemy, this.player))
{
    //Should/Can go left
    this.thisEnemy.setX(this.thisEnemy.getX() - this.thisEnemy.getSpeed());
}

if (Collision.tileCollisionDown(this.thisEnemy, this.thisEnemy.getSpeed(), currentLevel)
    == false && (Math.abs((this.thisEnemy.getY() + this.thisEnemy.getSpeed())
    - this.player.getY()) < Collision.getYDist(this.thisEnemy, this.player)))
{
    //Should/Can go down
    this.thisEnemy.setY(this.thisEnemy.getY() + this.thisEnemy.getSpeed());
}
else if (Collision.tileCollisionUp(this.thisEnemy, this.thisEnemy.getSpeed(), currentLevel)
    == false && (Math.abs((this.thisEnemy.getY() - this.thisEnemy.getSpeed())
    - this.player.getY()) < Collision.getYDist(this.thisEnemy, this.player)))
{
    //Should/Can go up
    this.thisEnemy.setY(this.thisEnemy.getY() - this.thisEnemy.getSpeed());
}

```

I have heard that the A\* search algorithm is good for path finding, but I have no idea how to implement the algorithm into my program in order for the enemies to not get stuck on walls when following the player. How would I go about doing such a thing? My program *is* tiles based for obstacles such as walls, but entities like the player and enemies have free movement. This is where I'm confused; I understand how it would work, if the entities also did tile based movements, but that is not how my game is set up. I don't want to check every pixel on the screen for a path, because that would take forever, and be extremely inefficient.

# Answer
> 1 votes
A\* works on graphs, and graphs are discrete nodes and edges. Free movement isn't discrete, so you'll need to come up with a **map representation**. Read this article by amitp which explains everything in great detail.

You need to choose a type of representation, and each has pros and cons. If you're going for shortest path, the obvious answer is a **polygonal graph** like this:

That is, for each obstacle, create nodes out of each corner of each obstacle, create start and end nodes, and connect everything up based on visibility. The shortest (Euclidean) path is guaranteed to be within this graph.

The problem is that such graphs can become very complex, as you can have lots of nodes connected to each other:

This is why lots of real games use other approaches, like manually placing **waypoints**, or **navigation meshes**. **Grid-based** ones are fine too. Also consider **hybrid approaches**. For example, in one of my games, everything is tile-based but movement is (almost) free. I use A\* over the tile grid, but then smooth out the paths by removing nodes in between if they are visible to each other. This allows the AI to move diagonally when following the path.

---
Tags: java, collision-detection, path-finding
---


# Question
Title: When I drag a JLabel, why is it appearing in a different location?
I am making a checkers game, and it is behaving very strangely. As of now, I am just trying to get the basics, such as grid layout, and getting the pieces laid out and moveable. My 8 by 8 grid opens just fine, and all of the pieces are laid out on the panels correctly, using two components:

* *PANELS*: `JPanels` made in a seperate class, 64 total colored black and white, and filled into a `centerPanel` using `GridLayout`. Each panel has a specific row and column value(`checkerPanel[row][col]`).
* *PIECES*: they are actually `JLabels` with the text "•" They are enlarged so that they fill the panel. They are placed on white panels in the first 3 rows for the red team, and placed in the last 3 rows for the gray team.

When I try to drag a piece, a new piece opens from the top left piece. When the piece from the top left is dragged over the old piece, which does not move, the old one is erased and the new one takes its place. How can I make the pieces behave correctly, moving from their old place, not the top left? Would it be easier to look into `java.awt.Graphics`?

---

I have looked at this StackOverflow question, and searched the Oracle JavaDocs, but can still not figure out what is wrong. Here is my current program:

```
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class Checkers extends JFrame {
    private static final long serialVersionUID = 1l;
    private static final int GRIDSIZE = 8;
    private CheckerPanel[][] checkerPanel = new CheckerPanel[GRIDSIZE][GRIDSIZE];

    public Checkers() {
        initGUI();
        setTitle("Checkers");
        pack();
        setLocationRelativeTo(null);
        setVisible(true);
        setResizable(true);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    private void initGUI() {
        JLabel titleLabel = new JLabel("Checkers");
        Font titleFont = new Font(Font.SERIF, Font.BOLD, 32);
        titleLabel.setFont(titleFont);
        titleLabel.setHorizontalAlignment(JLabel.CENTER);
        titleLabel.setBackground(Color.BLACK);
        titleLabel.setForeground(Color.WHITE);
        titleLabel.setOpaque(true);
        add(titleLabel, BorderLayout.NORTH);

        JPanel centerPanel = new JPanel();
        centerPanel.setLayout(new GridLayout(GRIDSIZE, GRIDSIZE)); // makes 8*8 grid
        add(centerPanel, BorderLayout.CENTER);

        for (int row=0; row<GRIDSIZE; row++) {
            for (int col=0; col<GRIDSIZE; col++) {
                JLabel grayPiece = new JLabel("•");
                JLabel redPiece = new JLabel("•");
                Font font = new Font(Font.SANS_SERIF, Font.PLAIN, 70);
                grayPiece.setFont(font);
                redPiece.setFont(font);
                grayPiece.setForeground(Color.GRAY);
                redPiece.setForeground(Color.RED);
                // used so that the pieces are not offset
                grayPiece.setBorder(BorderFactory.createEmptyBorder(-27, 0, 0, 0));
                // used so that the pieces are not offset
                redPiece.setBorder(BorderFactory.createEmptyBorder(-27, 0, 0, 0));
                checkerPanel[row][col] = new CheckerPanel(row, col);

                final MouseAdapter ma = new MouseAdapter() {
                    // Clicked label.
                    private JLabel selectedLabel = null;
                    // Location of label in panel when it was clicked.
                    private Point selectedLabelLocation = null;
                    // Panel's click point.
                    private Point panelClickPoint = null;

                    public void mousePressed(final MouseEvent e) {
                        final Component pressedComp
                            =  centerPanel.findComponentAt(e.getPoint());

                        if (pressedComp != null && pressedComp instanceof JLabel) {
                            selectedLabel = (JLabel) pressedComp;
                            selectedLabelLocation = selectedLabel.getLocation();
                            panelClickPoint = e.getPoint();
                            centerPanel.setComponentZOrder(selectedLabel, 0);
                            selectedLabel.repaint();
                        }
                        else {
                            selectedLabel = null;
                            //selectedLabelLocation = null;
                            panelClickPoint = null;
                        }
                        if (selectedLabel != null && selectedLabelLocation != null
                            && panelClickPoint != null) {
                            final int newX = selectedLabelLocation.x;
                            final int newY = selectedLabelLocation.y;
                            selectedLabel.setLocation(newX, newY);
                        }
                    }

                    public void mouseDragged(final MouseEvent e) {
                        if (selectedLabel != null && selectedLabelLocation != null
                            && panelClickPoint != null) {
                            final Point newPanelClickPoint = e.getPoint();
                            // The new location is the press-location plus
                            // the length of the drag for each axis:
                            final int newX = selectedLabelLocation.x
                                + (newPanelClickPoint.x - panelClickPoint.x),
                                      newY = selectedLabelLocation.y
                                + (newPanelClickPoint.y - panelClickPoint.y);

                            selectedLabel.setLocation(newX, newY);
                        }
                    }
                };
                centerPanel.addMouseMotionListener(ma); //For mouseDragged().
                centerPanel.addMouseListener(ma); //For mousePressed().

                if ((row%2 == 0 && col%2 == 0) || ((row+1)%2 == 0 && (col+1)%2 == 0)) {
                    checkerPanel[row][col].setBackground(Color.WHITE);
                    checkerPanel[row][col].isWhite = true;
                }
                else {
                    checkerPanel[row][col].setBackground(Color.BLACK);
                    checkerPanel[row][col].isBlack = true;
                }
                if (row < 3 && checkerPanel[row][col].isWhite) {
                    checkerPanel[row][col].add(redPiece);
                    checkerPanel[row][col].isPiece = true;
                }
                else if (row > 4 && checkerPanel[row][col].isWhite) {
                    checkerPanel[row][col].add(grayPiece);
                    checkerPanel[row][col].isPiece = true;
                }
                centerPanel.add(checkerPanel[row][col]);
            }
        }
    }

    public static void main(String[] args) {
        try {
            String className = UIManager.getCrossPlatformLookAndFeelClassName();
            UIManager.setLookAndFeel(className);
        }
        catch (Exception e) {}

        EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Checkers();
            }
        });
    }

    class CheckerPanel extends JPanel { //the following class makes Panels
        private static final long serialVersionUID = 1L;
        private static final int SIZE = 50;
        public boolean isBlack = false; //if the panel is white
        public boolean isWhite = false; //if the panel is black
        public boolean isPiece = false; //if the panel has a piece

        public CheckerPanel(int row, int col) {
            Dimension size = new Dimension(SIZE, SIZE);
            setPreferredSize(size);
        }
    }
}

```

Here's a screenshot of the window. When a piece is dragged, a new one comes out from the same place as the red top left piece.

# Answer
This effect is caused by a number of issues in your code.

First, note that you're creating your `MouseAdapter` inside two nested for-loops. In effect, this means you're not just creating *one* `MouseAdapter`, you're actually creating `GRIDSIZE x GRIDSIZE = 64` instances of `MouseAdapter`.

But that's not the cause of the problem. Rather, it has to do with how you find the piece that the user clicked on. At the top of `mousePressed(...)` you're calling `centerPanel.findComponentAt(e.getPoint())`. However, due to the way this method is defined, it will not actually find the piece you're after. Why is that?

`findComponentAt` internally works like this: on the `Container` it is invoked on, iterate over all child components. If a child is itself an instance of `Container`, recursively call `findComponentAt` on that child; otherwise check if the given point lies inside the child's boundaries. The problem with that method is that (a) when no child passes the test, it returns `this` (rather than, say, `null`) and (b) `JLabel` inherits from `Container`. These two points combined mean: the first leaf in the component tree under `centerPanel` that is either a non-`Container` and contains `e.getPoint()` OR *is simply a `Container`* will be returned. And since your pieces are `JLabel`s and `JLabel`s are containers, `findComponentAt` will always return the first piece, no matter if it actually contains the given point or not.

But wait, there's more! As a matter of fact, these are still not the only issues in the your current version of your code. Even if you replaced the call of `findComponentAt` with something that actually finds the right piece, like say, the following:

```
private JLabel findPiece(Point point) {
    for (int row = 0; row < GRIDSIZE; row++) {
        for (int col = 0; col < GRIDSIZE; col++) {
            CheckerPanel cp = checkerPanel[row][col];
            Point cpPoint = cp.getLocation();

            for (Component comp : cp.getComponents()) {
                if (comp instanceof JLabel &&
                    comp.contains(point.x - cpPoint.x, point.y - cpPoint.y)) {
                    return (JLabel) comp;
                }
            }
        }
    }

    return null;
}

```

you still have a problem due to the way your component hierarchy is organized. Your `centerPanel` contains 64 `CheckerPanel`s which in turn may or may not contain a `JPanel` piece. Unfortunately, though, that means that you cannot draw a proper piece movement from one panel to the next because for drawing, child components (the `JLabels`) are confined to the boundaries of the parent container (`CheckerPanel`) which they're a child of. You've tried to circumvent that by calling `centerPanel.setComponentZOrder(selectedLabel, 0)`. However, if you look at the documentation of `setComponentZOrder` you'll note the following:

> If the component is a child of some other container, it is removed from that container before being added to this container.

This applies to your situation here: `selectedLabel` initially is not a child of `centerPanel` but of some `CheckerPanel` instance. Thus by calling `setComponentZOrder` you're removing it from that `CheckerPanel` and adding it to the `centerPanel` which basically sabotages your whole data structure in which the `centerPanel` contains `CheckerPanel`s which contain `JLabel`s.

In my opinion, you can make your own life a lot easier if you forget about a component hierarchy altogether for your game. Components are really made for traditional GUIs in desktop applications: menus, buttons, drop-down lists etc. Instead, you will get rid of a lot of problems if you implement `centerPanel` in such a way that you override its `paintComponent` method in which you draw the complete board with all the pieces yourself, i.e., `CenterPanel` and the pieces do not inherit from any AWT or Swing classes anymore but are purely for data structuring -- if you need theses classes at all!

If you want to go one step further and have animations such as dragging a piece be especially smooth, you may even forget about `paintComponent` and instead use a `BufferStrategy` to actively draw at a chosen frame rate, rather than repaint when some event occurs. However, this is again a bit more involved and for a Checkers game done purely for practice, you could certainly stick to the `paintComponent` approach of the previous paragraph.
> 1 votes

---
Tags: java, swing
---