# Question
Title: DirectX 12 Questions about the command queue and command list?
I have been wondering this question for a while. Would this command

```
ThrowIfFailed(m_command_list->Reset(m_command_allocator.Get(), nullptr));
m_command_list->ResourceBarrier(1, &CD3DX12_RESOURCE_BARRIER::Transition(m_depth_stencil.Get(), D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_DEPTH_WRITE));
ThrowIfFailed(m_command_list->Close());

```

get sent to the command queue and not be executed?

Also how would I set the command list back into a recording state?

# Answer
> 1 votes
Here nothing gets sent to any queue at all.

To have a command buffer executed you would do

```
ThrowIfFailed(queue->ExecuteCommandLists(1, &m_command_list));

```

setting the command list back in the recording state is simple, just `Reset` it.

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


# Question
Title: Lighting in Minecraft/Block-esque worlds
Chaps, I'm sure we all know at a high level how Minecraft's lighting engine works. Light sources flood surrounding blocks with light, which themselves flood their neighbors and so forth. However, I believe this doesn't fully explain the picture. For example, consider this image:

Image 01

Clearly the vertical faces of the sand are lower light level than the horizontal faces. With the left faces being even darker than the front faces. I'm unable to see how any incarnation of the above method would produce such results - all faces are exposed to sunlight, they should all be the same brightness surely...

Does Minecraft use an additional layer of OpenGL diffuse lighting? If so, where is the light source? The Sun? What about in caves? Any insight on this would be much appreciated - Many Thanks!!!

# Answer
> 0 votes
Last time I checked the cel based approach was popular (and I believe minecraft does something similar)

That said here's a previous answer to this problem:

How can I implement lighting in a voxel engine?

---
Tags: opengl, lighting, minecraft-modding
---


# Question
Title: How do I create an Ubuntu snap for a MonoGame application?
I've been going through the snapcraft documentation and examples and I'm still really confused about how to go about creating my snapcraft.yaml file.

Basically I have a folder with my game in it. The folder contains all the files that are needed to run it.

I just want it to copy the files onto the end user's computer and have the shell script that launches the game targeted.

Here is my yaml file: https://gist.github.com/c349bc23febbe73a6976b83b7757f887

Here are the contents of my directory: https://github.com/SoundGoddess/OpenSolitaire/releases/download/0.9.2/OpenSolitaire.Classic.0.9.2.Linux.tgz

When I execute "snapcraft snap" I get the following error: 'NoneType' object has no attribute 'lstrip'

It looks like the parts folder gets generated ok, but then it fails on the build:

```
kati@linux:~/Development/OpenSolitaire.Classic$ snapcraft snap
Skipping pull opensolitaire-classic (already ran)
Preparing to build opensolitaire-classic
Building opensolitaire-classic
'NoneType' object has no attribute 'lstrip'

```

Any help would be greatly appreciated :)

# Answer
> 1 votes
Here is the proper format:

https://gist.github.com/02f1566736b10e3796d148eb4084bb15

I was missing a '.', thanks to @didrocks in #snappy on freenode for clarifying what I needed to do.

Since the bug was unclear, I posted a bug report here:

https://bugs.launchpad.net/ubuntu/+source/snapcraft/+bug/1587455

---
Tags: monogame, linux
---


title: Unity UI-Animations possibilities

text:
# Question
Title: Unity UI-Animations possibilities
I'm doing some stuff with UI-Animations the past days, but I never figured out, whether it is possible to do stuff like this with Unity : https://d13yacurqjgara.cloudfront.net/users/107759/screenshots/1623679/menu.gif

I would guess, that this is not possible, but maybe I just missed some feature :)

# Answer
> 1 votes
There are several way's you could attempt to do this:

1. Create a sprite containing the individual frames (tutorial for animating it)
2. Use the GIF directly in Unity (script and tutorial)
3. Use three Line Renderer and animate their properties

Currently there is no support direct for animated Vector graphics in Unity.
Even though there are plugins to import SVG into Unity, they don't support Animated SVG.
Maybe this will work, but I don't know.

# Answer
> 1 votes
Well there isnt a ready feature for these types of animation. But you can certainly do it with Unity. The Top and bottom bar seem to be just rotating and scaling a bit. For the middle one you will need to substitute it with another sprite that is a circle and use the radial fill feature to simulate the motion. Another approach would be do to a frame by frame animation. Perhaps make the animation in After Effects or something and export all the frames.

---
Tags: animation, unity, ui-design
---


# Question
Title: How does zooming in affect collision detection?
So I'm pretty new to DirectX, currently going through some tutorials to get an understanding of it. Now that I'm getting a small grasp onf graphics programming, I'm wondering how simple AABB bounding box collision would work, if the Z factor on quads was being changed for a zoom effect.

Say I have 2 quads set up, a texture applied to both, a bounding box around each and their positions set overlapping each other. I have an orthographic camera set up. Will zooming in scale the textures and quads so the boxes around them are no longer representative of them?

# Answer
> 7 votes
It shouldn't have any impact.

You should not be implementing zoom by scaling or otherwise messing with 'the Z factor' (whatever that is) of your objects in the world. You should be implementing zoom by adjusting properties of the camera and projection (field of view, camera position). The camera and projection properties only come into play when you transform objects from world space to eye and then eventually clip space.

All of your collision, in contrast, will generally be done in world space (or earlier). Thus, "zooming in" on objects should have no impact on the collision geometry at the point at which collision is detected.

---
Tags: 2d, collision-detection, directx11
---


title: How to draw text.Label().draw to FBO?

text:
# Question
Title: How to draw text.Label().draw to FBO?
I just started OpenGL (PyopenGl) & Pyglet 3 weeks ago, and decided to read the Red Book. So sorry if my question shows my lack of comprehension...

My question is: Is it possible to display/write text using `text.Label().draw` in an FBO ?

What I want to do is use `text.Label().draw` to generate a texture and use that texture when I need it. But so far I haven't been able to do it. I know that text in OpenGl is usually done by Bitmap Fonts, Outline Fonts or Texture Mapped Text, but I was wondering if the method I am thinking of could be a shortcut.

# Answer
> 1 votes
It is possible with Pyglet (even without PyOpenGL), I've successfully done it with the following code (slightly modified). However, my Pyglet version is a little behind.

With the code you can create a valid Pyglet texture which you can use as a render target. Set the render target to None when you want to draw to the screen again.

```
import pyglet, traceback, math, ctypes
from pyglet.gl import *

SCREEN_WIDTH = 1024
SCREEN_HEIGHT = 768
FBO = None

def SetScreen(self, left, top, right, bottom):
    glMatrixMode(GL_MODELVIEW)
    glLoadIdentity();
    glMatrixMode(GL_PROJECTION)
    glLoadIdentity()
    glOrtho(left,right,bottom,top,-1.0,1.0)
    glMatrixMode(GL_MODELVIEW)

def SetRenderTarget(texture=None):
    if not texture:
        # use screen when no texture was specified
        glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0)
        glViewport(0,0,SCREEN_WIDTH,SCREEN_HEIGHT)
        SetScreen(0,0,SCREEN_WIDTH,SCREEN_HEIGHT)
    else:
        # create FBO object once
        if not FBO:
            FBO = GLuint()
            glGenFramebuffersEXT(1, ctypes.byref(self.FBO))

        # bind the frame buffer
        glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, FBO)

        # check that the texture has a depth render-buffer (not strictly neccessary)
        try: _t = texture.DepthRB
        except:
            texture.DepthRB = GLuint()
            glGenRenderbuffersEXT(1, ctypes.byref(texture.DepthRB))
            glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, texture.DepthRB)
            glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, GL_DEPTH_COMPONENT16, texture.width, texture.height)

        # bind texture and depth buffer to FBO
        glBindTexture(texture.target, texture.id)
        glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, texture.target, texture.id, 0)
        glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, texture.DepthRB)

        # clear FBO and set some GL defaults
        glEnable(GL_BLEND)
        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
        glEnable(GL_DEPTH_TEST)
        glDepthFunc(GL_LEQUAL)
        glClearDepth(1.0)
        glClearColor(0.5, 0.0, 0.5, 0.0)  # set clear color yourself!
        glViewport(0,0, texture.width, texture.height)
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
        SetScreen(0, 0, texture.width, texture.height)

        # simple error checking
        status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT)
        assert status == GL_FRAMEBUFFER_COMPLETE_EXT

def CreateTexture(size=512, fmt=GL_RGBA, data=None):
    if type(size) == int:
        w = size
        h = size
    else:
        w = int(size[0])
        h = int(size[1])

    tid = GLuint()
    target = GL_TEXTURE_2D

    glGenTextures(1, byref(tid))
    glBindTexture(target, tid.value)
    glTexParameteri(target, GL_TEXTURE_MIN_FILTER, GL_LINEAR)

    if not data:
        blank = (GLubyte * (w * h * 4))()
        data = blank

    glTexImage2D(target, 0,
                 fmt,
                 w, h,
                 0,
                 GL_RGBA, GL_UNSIGNED_BYTE,
                 data)

    return pyglet.image.Texture(w, h, target, tid.value)

```

# Answer
> 0 votes
You can render piglet.text.label into a frame buffer object, but you will need to manage the FBO and rendering the label into it yourself. Pyglet does not provide primitives for manipulating and rendering to FBOs.

However, assuming that you are considering this for performance reasons, I would generally advise that you use batching instead. Pyglet includes robust batching support, and piglet.text.Label can be initialized with a Batch object, which will provide significantly improved performance when rendering the same text for multiple frames.

---
Tags: opengl, python, pyglet
---


# Question
Title: How can I change my script execution order programmatically?
I have a script that I want to run before any other script. I want to change its execution order settings. I could do that using the Script Execution Order Settings option from within Unity, but I want to do this programmatically.

The reason I want to do this programmatically is because the script has an abstract class, and I want to avoid requiring the user to change the execution order every time they extend the class. Changing the execution order of an abstract class is not an option in the Script Execution Order Settings. My abstract class has reference to every class that extends it.

How can I change the execution order of a MonoBehaviour? An example of what I am looking for would be along the lines of:

```
MonoBehaviour myBehaviour = GetMyMonoBehaviour();
myBehaviour.ExecutionOrder = -100;

```

# Answer
You can set the order via scripts using the MonoImporter class, specifically, the method `SetExecutionOrder`:

```
MonoScript myScript = MonoScript.FromMonoBehaviour(yourMonoBehaviour);
MonoImporter.SetExecutionOrder(myScript , -100);

```

However, I haven't seen this in the documentation post 5.0, so it may be depreciated if you're using the latest version.
> 3 votes

# Answer
If you're running this script every frame, you could consider using Update and LateUpdate across different scripts. Depending on what you're looking for, you might do the "early" calculation at the end of a LateUpdate call as described here.
> -1 votes

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


title: Fast Flood Fill in Pygame?

text:
# Question
Title: Fast Flood Fill in Pygame?
I am creating a simple game in Pygame for my kids. It involves intersecting random complex curves. Some of the intersections can be coloured in different colours. I have implemented a flood fill algorithm which works well for handling areas created by intersecting complex curves, but is very slow.

Couple of questions:

* Is there a built-in flood fill algorithm I should be using (I could not find one) that can handle the above use case?
* If not, then outside of algorithm improvements, how could I dramatically speed up a flood fill to make it near instantaneous to the human eye? (I am thinking about going low level but not sure how to go about this)

Flood Fill code:

```
# replaces all points of same starting colour,
# with a new colour, up to a border with
# different starting colour
def do_flood_fill(surface, x, y, newColor):
    theStack = [(x, y)]
    oldColor = surface.get_at((x,y))    # Get starting colour
    while len(theStack) > 0:
        x, y = theStack.pop()
        if surface.get_at((x,y)) != oldColor:
            continue
        surface.set_at((x,y),newColor)
        # pygame.display.update()   # Show fill - very slow
        theStack.append( (x + 1, y) )  # right
        theStack.append( (x - 1, y) )  # left
        theStack.append( (x, y + 1) )  # down
        theStack.append( (x, y - 1) )  # up

```

# Answer
> 0 votes
Read the docs, they can be very helpful. For both `get_at` and `set_at`, there's this comment:

> Getting and setting pixels one at a time is generally too slow to be used in a game or realtime situation. It is better to use methods which operate on many pixels at a time like with the blit, fill and draw methods - or by using surfarray/PixelArray.
>
> This function will temporarily lock and unlock the Surface as needed.

The reason why `get_at`/`set_at` are slow is partly hinted at here:

* They temporarily lock/unlock the `Surface` every call
* They require conversion from the underlying pixel format to the standard pygame `Color` class

Both of which aren't bad, but become very slow when you're doing a flood fill, which could involve hundreds or thousands of pixels.

One of the recommended approaches is to use `PixelArray`. It can be constructed from a `Surface`, then you update it as if it's a 2D array, preferably using integer pixel values instead of `Color`s to minimise conversions (hint: convert `newColor` using `map_rgb()`). Here's some example code:

```
pxarray = pygame.PixelArray(surface)
pxarray[x, y] = 0xFF00FF

del pxarray

```

> https://stackoverflow.com/a/12959670/2038264

Fortunately for flood fill, you don't need to know the exact `Color` you're filling into, only if the next pixel has the same value, so you can avoid conversions in the inner loop.

Finally, delete the `PixelArray`. This is because it implicitly locks/unlocks the `Surface` during its lifetime. This is covered in the docs but can be easy to miss; read them carefully:

> During its lifetime, the PixelArray locks the surface, thus you explicitly have to delete it once its not used anymore and the surface should perform operations in the same scope. A simple : slice index for the column can be omitted.

Just for completeness, make sure to catch `IndexError` which occurs when you try to access pixels outside the `Surface`, which is easy to do in a flood fill algorithm.

In general, when you need to update a bunch of pixels in one go, it's best to lock the whole surface once, perform pixel operations in the underlying format, then unlock at the very end. This applies to pygame surfaces as well as SDL surfaces, GDI images and DirectX textures, as it relates to how graphics hardware works.

# Answer
> 0 votes
You can try first finding the points next to the border, storing them in a list and then using the list on `filled_polygon` function.

Make sure to not reappend points already seen to the `theStack`. Poping from stack and ignoring the repeated ones costs some valuable processing.

Based on my recent knowledge in SDL, manipulate points on a Texture/Surface tends to be slow because wrapping functions in pygame probably (*not sure, not looked at the source. If you can, look and correct this answer*) need to lock the Surface, manipulate the pixel and then unlock the Surface at each time you use the `set_at`/`get_at` wrapping functions.

---
Tags: pygame
---


# Question
Title: Is there a way to have an ai characters ask my questions so that a player can choose, leading to different story lines?
Character asks "Do you choose A or B?". Player chooses "B" . Story line changes based exclusively on the conversation.

# Answer
> 1 votes
Yes. You can do this by storing the result of the player's choice in some fashion.

If your game is basically a simple branching conversation, you can simply implement the entire dialog as some kind of tree or graph structure, where the current gameplay state is represented by a reference to that current node in the tree. Each response is associated with an edge to another node; when the player chooses that response you advance the state reference to the node at the end of that response's edge.

Most games don't consist *entirely* of branching conversation trees though. So a more common, generalized approach is to create a system of "stuff done flags," or "progress bits." A set of booleans (or other types, if you get fancy) that represent actions the player has taken. A very simple implementation can be a big array of booleans, which each index in the array associated with a particular event or action:

```
enum StuffDoneLabels {
  TalkedToTheSheriff,
  FoundMagicRing,
  ToldTheOgressSheWasUgly,
  KilledTheOgress,
  LootedTheOgressTreasureCave,
};

```

You can then associate dialog responses with a flag, or set of flags, that they set or clear when that dialog response is taken (for example, telling the evil ogress that she isn't very pretty). You can also have systems to set these flags when you pick up items, discover or enter areas, et cetera.

Then, elsewhere, you can check the state of various flags to see if actions should be taken. Perhaps if the player enters a specific cave, the game checks to see if you killed the ogress and if so spawns her sister in to take revenge.

---
Tags: unity
---


# Question
Title: How do I select a portion of the window using Love2d
I want to be able to divide the window of the game in, lets say, 3 places, and when the mouse (or touch) click one of those places, execute some code.

Do I have to make each portion a button-like object? or is there a way for me to use love.mouse.getPosition() and give different instructions to specifics range of coordinates?

# Answer
Let's say you want to figure out if the user clicked/touched the left or right side of the window, and that your window is `800` units wide. Then the code is very simple; in your click handler (typically `love.mousepressed()`) check if the `x` position of the mouse is less than or greater than half that, `400`:

```
function love.mousepressed(x, y, button, istouch)
   if button == 1 then
      if x < 400 then
          -- left side clicked
      else
          -- right side clicked
      end
   end
end

```

But if you're doing anything more complex than that, like a GUI, this quickly becomes unmaintainable. Think about adjusting those GUI elements, adding new buttons, resizing them, changing the layout, and calculating those magic numbers... yuck! Then it's best to look at a proper GUI library, or code your own. But under the hood the library will be doing the same thing - checking the mouse press against coordinate numbers.
> 0 votes

---
Tags: lua, mouse, touch, love2d
---


title: When to calculate AABB collisions

text:
# Question
Title: When to calculate AABB collisions
I was wondering if collisions are usually calculated the exact moment an object is moved or if it is calculated in the game loop. I haven't been able to find anything on this.

Thanks

# Answer
Almost everything happens *in the game loop* somewhere, so that distinction is a bit moot.

What you seem to be asking is "when you change the position of an object, do you check for collision there, or do you check for collision later." It depends on the specific needs of your game, but in general it's probably better to do the calculation later.

Code that sets an object's position doesn't always have access to all the other potentially-colliding objects. For example, if you're thinking of doing the collision checks inside `setPosition`:

```
void GameObject::setPosition(float x, float y) {
   m_x = x;
   m_y = y;
   // ...check for collisions here...
}

```

That will require `GameObject` to have access to every other `GameObject`, which is not generally a great design. Right there, that answers your question for you.

But let's say for the sake of argument `GameObject` does have this access, or that you're thinking instead of doing something like:

```
someObject.setPosition(newX, newY);
// ...check for collisions here...

```

That's also not a great idea. It's highly likely this snippet of code isn't the *only* place object positions get updated, and indeed any given game object might have its position updated more than once during any given update frame. If that's the case, you'd be wasting time doing a bunch of extra collision detection tests (only the last one will actually matter).

Further, if you're doing the collision *detection* you may as well do the collision *response*. Collision response involves moving things, which involves setting positions, which if you're using the first `setPosition` up there, is causing recursive collision detection and response cascades that will either deadlock your whole frame or at least kill your frame time. You'd have to cart around a bunch of state about which objects have been checked for collision response everywhere you might trigger response by moving objects, and it will get ugly fast.

Finally, it's generally preferable to do operations in bulk. Dedicating a whole slice of your update to loop doing collision detection *once* for all objects can be far more efficient than trying to sprinkle it "randomly" around the frame in a way that completely negates any gains to be had from cache-coherent access to the full set of data (all the objects).

So in general, you should allow objects to have their desired positions determined. Then, you should check for collision between all objects all in one go, and you should resolve collisions between all objects all in one go, adjusting everything to final positions afterwards.
> 1 votes

# Answer
Collisions are always calculated in the game loop, but you can do some things to just check collisions between a bunch of items instead of checking the interactions between all the objects array (n^n). First of all, i strongly recommend you to research/implement a quadtree based collision technique (great doc here), limiting in this way the number of elements to calculate.

After that, you can use other techniques like calculating the "position mesure" or firing webworkers/threads
> 1 votes

---
Tags: collision-detection, aabb
---


# Question
Title: How can I ensure a grid can be filled with Tetris-like pieces?
I'm thinking of making a puzzle game where the objective is to fill a grid with shaped puzzle pieces (for example, the classic Tetris shapes).

How can I go about generating a set of pieces that can be guaranteed to be used to fill the grid, leaving no gaps? How could I adapt this algorithm to scale the difficulty of the resulting puzzle?

# Answer
> 8 votes
This is a known hard problem, determining what rectangles can be tiled with certain pieces.

However, if you're building puzzles and can control the pieces, it's the opposite, constructive problem, and easier...

Build a solution constructively. Take a few pieces you like, and fill the puzzle however you want. Then throw in enough single-squares to fill it out, and you have guaranteed that there is at least one solution. Or rather, include some small pieces in your allowed set of pieces.

As for solving/laying out the pieces, a typical brute force approach is to fill it from left to right, then top to bottom. Find the first open cell (numbered L-R, T-B) and try to put in your allowed pieces in their allowed orientations (8 orientations for an asymmetric piece if you allow flipping). Perhaps check first large allowed pieces, and resort to smaller ones if necessary. When you reach a state you don't like (dead end, too many small pieces, or what not) then backtrack. If a given grid/piece set doesn't meet your criteria, that is, it backtracked all the way without finishing, try a different rectangle and piece set.

One way to make a puzzle "easier" could be to trade bigger pieces for more smaller pieces like monominoes and dominoes, since this will leave more ways to fill in the last holes. Or, equivalently, build a solution that favors those smaller pieces.

Some noted polyominologists include:

==\> http://ee.usc.edu/faculty\_staff/faculty\_directory/golomb.htm Golomb originally coined the term "Polyomino"

==\> http://www.eklhad.net/polyomino/ Dahlke has solved quite a few rectangles filled with identical pieces (a particularly rare tiling form)

# Answer
> 5 votes
This article (page 11-13, disclaimer: I'm one of the authors) describes an algorithm that uses dynamic programming to uniformly generate perfectly tiled rectangular regions of width *w* and height *h*, in time which is linear in *h* after a preprocessing that takes about 2<sup>(*w*.*D*)</sup> time/space (*D* being the longest dimension of an individual shape, eg 4 in the case of Tetris pieces).

The idea is similar to the one described by David above, and focuses on the *upper strip*, placing pieces that do not create *holes*. The key thing here is that is to start by precomputing the allowed alternatives for each state of the upper-strip, so that you no longer pay for the combinatorial explosion when you generate the regions.

The algorithm works for any set of (convex) shapes.

Also, an interesting aspect of a uniform random generation is that it ensures maximal diversity between consecutive generations (but you can also constrain the generation in any way you want). Here are some typical outputs:

Feel free to ask if you're having trouble with the implementation (I might even have a Python quick and dirty implementation lying around somewhere...)

# Answer
> 2 votes
Here's a technique we've used in the past to cheat a bit on more confined hardware. It's not as pure as the more complex solutions, but has the distinct advantage of being much easier to implement and works every time.

Rather than focusing on the entire puzzle, break it into smaller, **uniform units**. Each of these units is composed of a set number of pieces that fit together to form squares or rectangles which are much easier to fill into a puzzle. Choose randomly from the different configurations to fill up the width of the puzzle (samples below, but there are many, many configurations). Below are 4x4s, a 5x4, and even a 10x4 example.

The idea is that you "stripe" the puzzle ... choose the widths randomly based on the available remaining room. Once a "stripe" is finished, start a new stripe.

You release pieces one stripe at a time by randomizing within each "stripe" set. If you want to increase the difficulty, randomly release from two or more stripes at a time.

Using this technique, not only have you guaranteed that the puzzle is solvable, you've also helped "cheat" the order of release to make it easier to stay alive. Of course in practice, players aren't able to perfectly solve each stripe and so chaos ensues.

Keep generating stripes until the player loses. Of course, my example is a stripe 4 blocks high, but you can choose something larger and more complex:

---
Tags: algorithm, puzzle
---


# Question
Title: Is correct to calculate values in percentage, using the total number of iterations?
Trying to clarify the problem.

Imagine a factory that produce soccer balls; if you produce 1 ball, it will take a certain amount of game cycles. For sake of simplicity, let's say it could take between 5 and 15 cycles (depending from various conditions, like number of workers, quality of workers and so on). Once you make a certain amount of soccer balls, the process is considered done.

Now, I want to display a value in percentage for costs, and a value of defective balls made. with "cost", I am trying to display how much did I spent (materials, workers wage and so on), at the moment. The number in currency is self esplicative, but I believe a percentage value could help to know if you are using too many workers, or burning too many resources, resulting in a waste of money.

To calculate the percentage of defective is relatively simple, since every X amount of time, when I refresh, I can check the balls produced against the defective ones, and the result should be

```
Total produced * 100 / defective = percentage of defective.

```

But for the costs, things are different; so I was planning to use the number of cycles to calculate percentage for costs:

```
cycles * 100 / current costs = percentage of costs

```

Would this be considered correct? Since the number of cycles for a whole batch of balls may vary slightly, this may represent that when there are less cycles, it means that you spent less money, henche the percentage will be smaller.

# Answer
The cost and time for creating the defective products needs to be added to the cost and time of sellable products.

When x% of your products are defective, the cost and time of the sellable ones is multiplied by `100 / (100 - x)`. Example: 75% of your products are defective, so you need to pay for the production of four products (100 / 25) for each one you can sell. It also will take four times as long to produce `n` non-defective products.
> 1 votes

---
Tags: game-design
---


# Question
Title: Move Sprite in constant speed on squircle
I'm creating a game and i need to move a sprite on `squircle` path.

```
https://en.wikipedia.org/wiki/Squircle

```

i created the path using the equation :

```
    angle -= Gdx.graphics.getDeltaTime()*speed ;
    float x = (float) (R*Math.pow(Math.abs(MathUtils.cos(angle)),1/10f)*sgn(MathUtils.cos(angle)))+a;
    float y = (float) (R*Math.pow(Math.abs(MathUtils.sin(angle)),1/10f)*sgn(MathUtils.sin(angle)))+b;
    sprite.setPosition(x,y);

```

the result is :

My question is how to make the sprite move in a constant speed

Edit : i used the formula found on Wikipedia :

# Answer
> 2 votes
If you want to make your sprite move at a constant speed alond the squircle, you should transform it into a vectorial path, in order to calculate its linear speed instead of the angular speed as you did.

If you want to work with angular speed, there's no problem as it will be a good approssimation anyway.

Although you used the formula found on Wikipedia, the one you implemented is slightly different from it. Try using the following for your sprite position:

```
// a = horizontal axis; b = vertical axis
angle -= Gdx.graphics.getDeltaTime()*speed;
float x = Math.pow(Math.abs(MathUtils.cos(angle)),0.5f)*sgn(MathUtils.cos(angle))*a;
float y = Math.pow(Math.abs(MathUtils.sin(angle)),0.5f)*sgn(MathUtils.sin(angle))*b;
sprite.setPosition(x,y);

```

or, alternatively:

```
// R = max radius, equal to having a=b in the previous script
angle -= Gdx.graphics.getDeltaTime()*speed;
float x = Math.pow(Math.abs(MathUtils.cos(angle)),0.5f)*sgn(MathUtils.cos(angle))*R;
float y = Math.pow(Math.abs(MathUtils.sin(angle)),0.5f)*sgn(MathUtils.sin(angle))*R;
sprite.setPosition(x,y);

```

This snippet reflects the geometric definition in polar coordinates of the squircle, if the effect isn't what you expect you can change the `speed` value when increasing/decreasing the value of `angle`.

---
Tags: libgdx, movement
---


# Question
Title: "Your android setup is not correct" error on Unity showing up even after reinstalling OpenSSL (Using Facebook SDK)
I want to build for Android and today one error popped up after building.

> Your Android setup is not correct. See Settings in Facebook menu. UnityEditor.HostView:OnGUI()

Important things about this problem:

* The only error in the inspector I can see is

> OpenSSL not found. Make sure that OpenSSL is installed and that it is in your path.

Even tho I have installed it and added it to my path

* When I open the inspector in Facebook\> Edit Settings, unity becomes very unresponsive
* This error has not popped up before today
* I still get a APK even if I get errors

# Answer
> 2 votes
There is actually a major bug with the latest version of Facebook SDK and the OpenSSL. Every time you click on Facebook/Settings Unity hang and becomes unresponsive.

I had to download openssl-0.9.8k\_X64.zip found here and the problem was solved.

The proper solution was provided on SO.

# Answer
> 1 votes
This question has been answered multiple time at least here.

Here are steps.

1. Download the OpenSSL installer
2. Download the lastest x64 JavaSDK here. I have installed the latest Java 8 SDK.
3. Make sure to use the latest Facebook SDK. Take a look here.
4. Now you have all the needed files.
5. So start installing OpenSSL on "C:/OpenSSL" and go to "Control Panel \> System \> Advanced system settings \> Environment Variables" and select the Variable "Path" in the "System variables" window and click Edit. And finally, add the path to your OpenSSL bin folder to the end of the "Variable value" after a ";". For example, using "C:/OpenSSL" install folder, you'll type `;C:\OpenSSL\bin`.
6. You'll have to do the same for JavaSDK. Install it and then add the environment variable. Using Java8, I have putted `;C:\Program Files\Java\jdk1.8.0\bin` just after openssl one.
7. Adding these variables make prompt commands working (like "keytool" or "openssl") but to make it work in Unity, I have had to restart Windows. The problem was here. When I was testing some solutions without restarting, they didn't work. But if you install these packages and configure environment variables like I did and after that, restart windows, when you'll create a new Unity project using the last Facebook SDK, you'll probably not get the warning message telling you "keytool" or maybe "openssl" is not founded.

---
Tags: unity, facebook
---


title: Why I can't do a build for Linux?

text:
# Question
Title: Why I can't do a build for Linux?
I'm using Unity 5.3.x (free version) on a Windows machine. I would like to build my simple desktop game either for Windows and Linux, but Linux (and Mac) build is disabled. Am i missing something ?

Thanks

# Answer
You have to install support for each platform you want to build for when you download the engine. Looks like this:

Make sure you click Linux Build Support. To fix your installation, you can re-run the download assistant for the version of Unity you have, and just select the build support ones and it will add them.
> 18 votes

---
Tags: unity
---


# Question
Title: Will a better CPU (or one with more cores) reduce Unity script compile time?
It usually takes 10-15 seconds to compile for small changes in any of the scripts in my project. The project contains over hundred scripts, which are in C#.

# Answer
> 1 votes
Faster CPU speeds will result in faster compile times, yes.

Looking at Windows Task Manager when compiling, mono.exe maxes out only one of my CPU cores, so multiple cores probably won't help.

---
Tags: unity
---


# Question
Title: How can I simulate thousands of things at high frame-rates?
I'm working on a simulation game like SimTower where I'd like to keep track of thousands of items at once.

Other games like this, appear to have hundreds or thousands of rooms with elevators with what looks like hundreds or thousands of people. I'm concerned about achieving the same thing in my game.

How can I realistically keep track of each individual person/room/elevator in the game? I assume I can only render what's on the screen, but how can I afford to constantly simulate everything that is off the screen?

# Answer
*Thousands* of things probably isn't that big of deal. As you note, even older games like SimTower could do this pretty reasonably. Consequently the first thing I'd suggest you do is the simple, straightforward option:

```
foreach(Thing t in AllOfTheThings) {
  t.Simulate(elapsedTime);
}

```

Once you've done that, if your game still runs acceptably, then you're done. If it doesn't, or if it starts to slow down, profile the game to make sure you're actually bottlenecking on entity simulation code. If you aren't, solve *that* problem instead.

But after all that, if you *are* bottlenecking on entity simulation, there are some techniques you can employ.

* You can adjust the tick rate of entities. Instead of ticking all of them every frame, tick half of them one frame and half of them the other (for example, odd numbered entities on odd frames, even numbered ones on even frames). The delay in any individual entity update will not likely be noticed by the player, but you will have reduced your per-frame workload by half.
* Similar to the above, you can tick entities differently based on how far away they are from the player's current camera focus. This is common in open-world games like Skyrim, which always simulates active NPCs, but does so far less frequently for NPCs that are far away from the player because the player can't see or interact with them.
* The above two methods are ways of reducing the level of detail in the tick rate; you could instead reduce level of detail in the *simulation*. If an entity is too far away from the player's focal point, you can drop some highly-detailed aspects of their update to save time. You may not need to accurately simulate their pathfinding, for example. Instead, switch them to a coarser simulation that just makes sure their basic needs are met: Should I sleep? Teleport to bed instead of bothering to try to walk there. Should I shower? Teleport to the bathroom. Pathfinding can be expensive so this can save some time.
* If entities cannot affect eachother during their simulation, or you can identify isolated groups of entities that will not affect entities outside of that group during simulation, you can offload the processing of those entities or groups to worker threads, running them in parallel.
* Ensure your entities and the update system they use are designed to take advantage of cache coherency in their data. It can be a huge performance win.

All of these methods have pros and cons, and must be adapted to your specific scenario and the needs of your game. You may need to employ all of these methods, or maybe none, or maybe you can select a few that work best for the profiling data you've gathered.

One last piece of advice is to start your simulation relatively simple. You may be surprised as how complex simple simulations can end up looking in practice once you introduce sufficient scale and some basic randomization. You may be surprised to discover much of the "complicated" simulation you think is going on in SimTower and similar games really isn't all that complicated and ends up being quite trivial for a modern machine to perform at scale.
> 10 votes

# Answer
Almost every game fakes what ever it can get away with. The important thing is the impression of actual people going about their day. I would not do anything with the offscreen action. Instead when the player scrolls to a different location, I would spawn the people at random location but with some probability to where they were last time the player saw them. The same way should be done with what the people are doing. If this is done correctly and used together with the time of day, what the people has done allready in the day, what they prefer to do and other ideas you might have, it can seem they really do things outside the screen.
> 0 votes

---
Tags: frame-rate, simulations
---


title: Point welding on generated terrain

text:
# Question
Title: Point welding on generated terrain
I am converting two 2D images (A Voronoi graph and a Diamond Square noise map) into a 3D object.

However when finding the corner points of the Voronoi I am left with gaps, so I thought to drop these by calculating adjacency to existing nodes before creating the vertex. However no matter which algorithm for the weld I use, or the tolerance level of the distance I can't seem to get it to work.

This has led me to believe I am doing something wrong.

Image of the issue:

These gaps do not appear if I run without the weld, they are created by the weld jumping to spots, but then later welds not finding that spot.

I have even tried to increment the weld distance to a maximum of 10, if a suitable node wasn't found. But this is far to aggressive and has the effect of simplifying the mesh instead and creating more gaps.

My Repo for the full code is here: https://github.com/HughAJWood/TerrainGenerator

```
private void CalculatePolys()
{
    var nodesForEdges = new List<VNode>();
    foreach (var region in _regions)
    {
        foreach (var point in region)
        {
            if (point == null)
            {
                continue;
            }
            // We calculate where the voronoi node corners are, and pass them into the region
            var diff = ColoursDifferent(point);
            if (diff > 1)
            {
                RenderNodePointsOnImage(point);

                // Points are 2D, so to translate to 3D they are set to the Z property of the 3D node
                var node = new VNode
                {
                    X = point.X,
                    Z = point.Y
                };
                // Weld points within 1 unit from each other by determining if we already have one that exists
                // then using the existing node instead
                // A weld is calculated by determining the X,Z distance to see if we have a node stored already
                // that is within 2 units of the node we are creating
                VNode existingNode = Nodes.FirstOrDefault(n => n.Adjacent(node));
                if (existingNode == null)
                {
                    // Optimise node creation by skipping perlin lookup and ID iteration for only when needed
                    node.ID = VNodeId;
                    node.Y = _perlin.GetPixel(point.X, point.Y).R;
                    Nodes.Add(node);
                    Mesh.ControlPoints.Add(new Vector4(node.X, node.Y, node.Z, 1));
                }
                else
                {
                    node = existingNode;
                }
                nodesForEdges.Add(node);
            }
        }
        //if (i++ > 20) return;
        AddNodesToMeshAsPolys(nodesForEdges);
        nodesForEdges.Clear();
    }
}

```

The adjacency method is currently simplified to the fact I want to ignore the height of the node.

```
internal static bool Adjacent(this VNode a, VNode b, int tolerance = 3)
{
    var distance = Math.Abs(a.X - b.X) + Math.Abs(a.Z - b.Z);
    return distance < tolerance;
}

```

\[UPDATE\]

I have tried sorting the points by distance and fuzzy distance, both sort in the correct order. Then I tried taking the first point and using that as the welding point. Same effect.

I tried to average the points at the intersections at the image level and pass that back as the point every time, then weld. Same effect.

Clearly there are many approaches I can take for this, the problem arises when there are 2 points close to each other on the edge of a voronoi region. Sometimes they weld and create a gap. Sometimes however in some variances of the algorithm that the points don't weld even though their X,Z coordinates are very close to each. I'm still stumped as how to approach this.

# Answer
Shouldn't your adjacent function be like this:

```
internal static bool Adjacent(this VNode a, VNode b, int tolerance = 3)
{
   var distance = Math.Sqrt(Math.Pow(a.X - b.X, 2) + Math.Pow(a.Z - b.Z, 2));
   return distance < tolerance;
}

```

**EDIT:**

After reviewing your project a little, I would suggest some changes to make it more easy to spot any bugs.

* Leave performance issues for later. It has a tendancy to make the code more difficult to follow.
* Add unit-testing. I think it works greate with this kind of project, when you want to be sure every math and algorithm does what it should. (I like to use it when trying to boost performance too.)
* Don't generate your maps when you are trying to find what's wrong, reload previously saved ones. It's much more easy to pinpoint the problem when your input is the same.
* Output your own file of the polygons for debugging, it can be just a textfile with one polygon for each row. Just to be sure their is no problem with the usage of the third party library (Aspose3D).
> 2 votes

---
Tags: 3d-meshes, vertex, .net
---


# Question
Title: Player jittering against wall when held down button
So, I'm making a top down RPG.

Everything's going excellent, but this problem is quite annoying. Now, when the character moves against the wall, the player jitters back and forth. I'm guessing it's because the player is trying to move into the wall, and then the wall collision is pushing it back, which makes an annoying back and forth movement. My question is obviously, **how do I stop this from happening?**

Thanks!

*PS: I'm using transform.translate to move the player, and I'm using C#.*

*EDIT*: I'm also using a 2D Rigidbody, and 2Dbox colliders on both.

# Answer
> 49 votes
The jittering is happening because you're warping the player into the wall using Transform.Translate, and the physics step is saying, "Hey, we're in the wall. Let's solve this collision issue and push the player back out of the wall."

To avoid this, when using a Rigidbody2D, it's advisable to use Rigidbody2D.MovePosition. This ensures you won't have overlapping colliders when moving. If a collider and rigidbody can't move because something's in the way, it won't jitter.

Using Rigidbody2D.MovePosition, you may want to set the Rigidbody2D.interpolation value to keep the movement looking smooth.

However, if Rigidbody2D.MovePosition isn't ideal for your game for some reason and you still want to use Transform.Translate, use Physics2D.Raycast (or other Physics2D casts) to see if moving would make you hit a wall or not, and only move if no wall is hit.

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


title: How to give a mesh collider gravity 5.0

text:
# Question
Title: How to give a mesh collider gravity 5.0
I was trying to make a simulation of an object that needs gravity to work, a hydraulic movement-assistance system for disabled people. All parts are aligned properly, all objects have mesh colliders and rigidbodies, but still gravity does not affect the limb and it floats in the air. How can I make gravity affect it?

# Answer
> 0 votes
As you said that rigid-body kinematic property is true then you should need to remember that

> It ignores the gravity if isKinematic == true.

If this is not the case then, that leaves three options.

1. it's colliding with something and can't fall.
2. it's so big that you can hardly see it move.
3. the visible object isn't the object being affected by gravity.(ref)

As you mention in comments how to move object without physics then you can use different solutions like 1. using translate 2. MoveTowards \- movement toward specific target 3. by changing position

---
Tags: unity, mesh, rigidbody, meshcollider
---


# Question
Title: How should I implement card effects in a card game?
I've been trying to program a video game adaptation of the popular trading card game "Magic: The Gathering". If you've played MTG before, you'll know most cards have an effect, which is activated at a certain time, usually when it's played. But I'm unsure how to implement effects into my game.

I'm thinking of creating a method that assigns a card its effect when it's played based on the card's name, but that doesn't really work when a card's effect isn't supposed to be activated when it's played, like in the case of *Deathrattle* cards, or when it's a continuous effect. I've thought of creating a thread for each effect which activates it whenever needed, but... that's a LOT of unique threads. I haven't found any similar java programs anywhere, so I wanna ask here. How do you think card effects should be handled?

# Answer
> 1 votes
Threads would definitely be overkill here. I would use event listeners.

First, make an ICommand interface. (The param is so that you can optionally pass data to your command)

```
public interface ICommand{
    public void execute(Object param);
}

```

Then make sure you clearly define every scenario in which a card will activate and create a ICommand variable in your Card class essentially creating a "slot" for each event type.

```
//Card class
ICommand onDeathrattleCommand;
ICommand onCardPlayedCommand;
//... other event types

```

When you create each card type, you initialize the appropriate event slots

```
Card deathrattleCard = new Card();
deathrattleCard.onDeathrattleCommand= new ICommand(){
   public void execute(Object param){
       foreach(Card opponentCard: opponentsCards){
           opponentCard.applyDamage(6);
       }
   }
};

```

Then trigger these events at the appropriate time

```
//Card class
public void onPlayed()
{
    if(onCardPlayedCommand != null){
       onCardPlayedCommand.execute(null);
    }
}

public void applyDamage(int damage)
{
   hp -= damage;
   if(hp <= 0 && onDeathrattleCommand != null){
     onDeathrattleCommand.execute(null);
   }
}

```

# Answer
> 0 votes
The representation of game state should be the core of your architecture, because it ties everything else together. Player actions, the sequence of events in a turn, card effects are strictly layered on top of game state.

For example, you can have an index of triggered abilities by the type of event that triggers them, and when anything happens you could

1. Enumerate all relevant triggered abilities for the event (e.g. a permanent enters the battlefield, a player draws a card, a creature deals combat damage, etc.)
2. Check if they actually trigger (e.g. "when a creature enters the battlefield" doesn't trigger for a land)
3. Ask the players in which order they want to stack the triggers
4. Put trigger ability objects on the stack
5. And the rest is the common procedure of giving priority to players, resolving stack contents, checking state-based actions, etc.

---
Tags: java, software-engineering, card-game
---


title: glViewport offset and ortho projection

text:
# Question
Title: glViewport offset and ortho projection
In all tutorials I found about creating projection matrix based on viewport size all of them assumed that left bottom coordinates of viewport will be (0,0).

Now I want to draw to the different parts of the screen and for that purpose I want to switch viewports accordingly:

```
glViewport(0,0,windowWidth/2, windowHeight/2); //left bottom
glViewport(0,windowHeight/2,windowWidth/2, windowHeight/2);//left top
glViewport(windowWidth/2,0,windowWidth/2, windowHeight/2);//right bottom
glViewport(windowWidth/2, windowHeight/2,windowWidth/2, windowHeight/2);//right top

```

Now I have a problem with defining my projection matrix. Without having any (x,y) offest I was using this code for calculating my ortho projection matrix:

```
float m_fWindowSize = 15.0f;

if (m_WindowWidth > m_WindowHeight)
{
    auto viewportAspectRatio = (float)m_WindowWidth / (float)m_WindowHeight;

    m_ProjectionMatrix.m_fLeft = (-1.0f) * m_fWindowSize * viewportAspectRatio;
    m_ProjectionMatrix.m_fRight = m_fWindowSize * viewportAspectRatio;
    m_ProjectionMatrix.m_fBottom = (-1.0f)*m_fWindowSize;
    m_ProjectionMatrix.m_fTop = m_fWindowSize;
    m_ProjectionMatrix.m_fNear = -(10.0f)*m_fWindowSize;
    m_ProjectionMatrix.m_fFar = (10.0f)*m_fWindowSize;

    m_fMoveSpeed = static_cast<GLfloat>(m_fWindowSize * 2 / static_cast<float>(m_WindowHeight));
}
else
{
    auto viewportAspectRatio = (float)m_WindowHeight / (float)m_WindowWidth;

    m_ProjectionMatrix.m_fLeft = (-1.0f)*m_fWindowSize;
    m_ProjectionMatrix.m_fRight = m_fWindowSize;
    m_ProjectionMatrix.m_fBottom = (-1.0f)*m_fWindowSize * viewportAspectRatio;
    m_ProjectionMatrix.m_fTop = m_fWindowSize * viewportAspectRatio;
    m_ProjectionMatrix.m_fNear = -(10.0f)*m_fWindowSize;
    m_ProjectionMatrix.m_fFar = (10.0f)*m_fWindowSize;

    m_fMoveSpeed = static_cast<GLfloat>(m_fWindowSize * 2 / static_cast<float>(m_WindowWidth));
}

```

And this works fine UNTIL I will add any (x,y) offset to my viewport. The effect is following when using `glViewport(0, m_WindowHeight/2, m_WindowWidth/2, m_WindowHeight/2)`:

And with `glViewport(0, 0, m_WindowWidth/2, m_WindowHeight/2)`:

**So how I can change projection matrix accordingly to the viewport offset?**

# Answer
You don't have to change your projection matrix accordingly to the viewport.

Have you considered to render the scene to a fbo and then render the fbo fullscreen (from -1, -1 to 1, 1) with `glViewport(width / 2, height / 2, width / 2, height / 2)`? This will took a quarter of the screen (top right).

In my current project, i can freely set the offset of `glViewport` without any problem and without changing my projection matrix. So i suppose the problem lies in your projection matrix or somewhere else.

Edit: On second thought, i just realize you didn't set up the matrix manually. Well that's harder for me.. *lol*. By the way, the person answering your question on StackOverflow is right, aspect ratio is `width / height`. Probably not going to fix your problem, but good to know.
> 1 votes

# Answer
I finally found the solution to my problem: **I have to set the viewport to begin at origin when I render to framebuffer**.

I didn't mentioned that I was rendering my scene to the framebuffer, because I thought it was irrelevant and apparently that casued the problem.

In my case viewport transfromations accumulated: first when rendering to texture using framebuffer and second time when rendering this texture to screen.

So the result was that when I set offset in glViewport() as windowWidth/2 or windowHeight/2 my whole texture was shifted by windowWidth or windowHeight and rendered outside the screen.

What I had to do in my rendering pipeline was basicly that:

```
glViewport(0,0,windowWidth, windowHeight);
//*************************
//render stuff to the framebuffer
//*************************
glViewport(windowWidth/2, windowHeight/2,windowWidth/2, windowHeight/2);

```

And the effect is as expected:
> 0 votes

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


title: Is there a way to make this better?

text:
# Question
Title: Is there a way to make this better?
So was experimenting in making a rotating ring puzzle like the one to get into the mechanical age in Myst. I came up with a solution that will rotate the rings and when the button is released it brings then smoothly back to a set position. Their is obviously a better way to do this but I for some reason can see it.

The CheckRotation function checks were the ring is and give the angle that it should be at to the ResetRotator function and sets face (a public int) to the face that is currently facing the player. The isResettingOne variable stops the user from being able to bush the button that causes the rotation whilst the ring is resetting.

```
void CheckRotation()
{
    StopCoroutine(ResetRotator(lastPassed));

    yRotation = gameObject.transform.eulerAngles.y;

    if (yRotation >= 337.5 && yRotation < 359.9 || yRotation >= 0 && yRotation < 22.5)//0
    {
        StartCoroutine(ResetRotator(0));
        lastPassed = 0;
    }
    else if (yRotation >= 22.5 && yRotation < 67.5)//45
    {
        StartCoroutine(ResetRotator(45));
        lastPassed = 45;
    }
    else if (yRotation >= 67.5 && yRotation < 112.5)//90
    {
        StartCoroutine(ResetRotator(90));
        lastPassed = 90;
    }
    else if (yRotation >= 112.5 && yRotation < 157.5)//135
    {
        StartCoroutine(ResetRotator(135));
        lastPassed = 135;
    }
    else if (yRotation >= 157.5 && yRotation < 202.5)//180
    {
        StartCoroutine(ResetRotator(180));
        lastPassed = 180;
    }
    else if (yRotation >= 202.5 && yRotation < 247.5)//225
    {
        StartCoroutine(ResetRotator(225));
        lastPassed = 225;
    }
    else if (yRotation >= 247.5 && yRotation < 292.5)//270
    {
        StartCoroutine(ResetRotator(270));
        lastPassed = 270;
    }
    else if (yRotation >= 292.5 && yRotation < 337.5)//315
    {
        StartCoroutine(ResetRotator(315));
        lastPassed = 315;
    }
}

IEnumerator ResetRotator(int desiredRotation)
{
    yield return new WaitForSeconds(0.001f);
    reset = (int)gameObject.transform.eulerAngles.y;
    resettingOne = true;

    if(reset == desiredRotation)
    {
        gameObject.transform.rotation = Quaternion.AngleAxis(reset, Vector3.up);
        resettingOne = false;
    }
    else if(desiredRotation == 0 && reset >= 0 && reset < 22.5)
    {
        face = 1;
        reset = reset - desiredRotation;
        reset = reset - 1;
        gameObject.transform.rotation = Quaternion.AngleAxis(reset, Vector3.up);
        CheckRotation();
    }
    else if(desiredRotation == 0 && reset >= 337.5 && reset < 359.9)
    {
        face = 1;
        reset = reset + 1;
        gameObject.transform.rotation = Quaternion.AngleAxis(reset, Vector3.up);
        CheckRotation();
    }
    else if (reset >= 22.5 && reset < 67.5)//45
    {
        face = 2;
        if(reset >= 22.5 && reset < 45)
        {
            reset = reset + 1;
            gameObject.transform.rotation = Quaternion.AngleAxis(reset, Vector3.up);
            CheckRotation();
        }
        if(reset > 45 && reset < 67.5)
        {
            reset = reset - 1;
            gameObject.transform.rotation = Quaternion.AngleAxis(reset, Vector3.up);
            CheckRotation();
        }
    }
    else if (reset >= 67.5 && reset < 112.5)//90
    {
        fcae = 3;
        if (reset >= 67.5 && reset < 90)
        {
            reset = reset + 1;
            gameObject.transform.rotation = Quaternion.AngleAxis(reset, Vector3.up);
            CheckRotation();
        }
        if (reset > 90 && reset < 112.5)
        {
            reset = reset - 1;
            gameObject.transform.rotation = Quaternion.AngleAxis(reset, Vector3.up);
            CheckRotation();
        }
    }
    else if (reset >= 112.5 && reset < 157.5)//135
    {
        face = 4;
        if (yRotation >= 112.5 && yRotation < 135)
        {
            reset = reset + 1;
            gameObject.transform.rotation = Quaternion.AngleAxis(reset, Vector3.up);
            CheckRotation();
        }
        if (reset > 135 && reset < 157.5)
        {
            reset = reset - 1;
            gameObject.transform.rotation = Quaternion.AngleAxis(reset, Vector3.up);
            CheckRotation();
        }
    }
    else if (reset >= 157.5 && reset < 202.5)//180
    {
        face = 5;
        if (reset >= 157.5 && reset < 180)
        {
            reset = reset + 1;
            gameObject.transform.rotation = Quaternion.AngleAxis(reset, Vector3.up);
            CheckRotation();
        }
        if (reset > 180 && reset < 202.5)
        {
            reset = reset - 1;
            gameObject.transform.rotation = Quaternion.AngleAxis(reset, Vector3.up);
            CheckRotation();
        }
    }
    else if (reset >= 202.5 && reset < 247.5)//225
    {
        face = 6;
        if (reset >= 202.5 && reset < 225)
        {
            reset = reset + 1;
            gameObject.transform.rotation = Quaternion.AngleAxis(reset, Vector3.up);
            CheckRotation();
        }
        if (reset > 225 && reset < 202.5)
        {
            reset = reset - 1;
            gameObject.transform.rotation = Quaternion.AngleAxis(reset, Vector3.up);
            CheckRotation();
        }
    }
    else if (reset >= 247.5 && reset < 292.5)//270
    {
        face = 7;
        if (reset >= 247.5 && reset < 270)
        {
            reset = reset + 1;
            gameObject.transform.rotation = Quaternion.AngleAxis(reset, Vector3.up);
            CheckRotation();
        }
        if (reset > 270 && reset < 292.5)
        {
            reset = reset - 1;
            gameObject.transform.rotation = Quaternion.AngleAxis(reset, Vector3.up);
            CheckRotation();
        }
    }
    else if (reset >= 292.5 && reset < 337.5)//315
    {
        face = 8;
        if (reset >= 292.5 && reset < 315)
        {
            reset = reset + 1;
            gameObject.transform.rotation = Quaternion.AngleAxis(reset, Vector3.up);
            CheckRotation();
        }
        if (reset > 315 && reset < 337.5)
        {
            reset = reset - 1;
            gameObject.transform.rotation = Quaternion.AngleAxis(reset, Vector3.up);
            CheckRotation();
        }
    }
}

```

# Answer
> 2 votes
As far as I can tell the purpose of your code is to always round to 45° increments. So you can use the function Mathf.Round. It always rounds to the nearest integer. When you want to round to the nearest multiply of 45, you need to divide the angle by 45, apply the rounding and then multiply it again:

```
float newAngle = Mathf.Round(yRotation / 45.0f) * 45.0f;
StartCoroutine(ResetRotator(newAngle)
lastPassed = newAngle;

```

The same technique can be applied in the ResetRotator method itself. The face can be calculated by dividing the angle and then using Mathf.FloorToInt and whether you need to increment or decrement the `reset` variable (whatever it means) can be found out by comparing the original angle with the rounded one.

---
Tags: algorithm
---


# Question
Title: Another way of writing 2D arrays on Game Maker Studio?
I'm making a map in an array, something like this :

```
mapa[23,26]=4;mapa[25,28]=3;mapa[21,28]=3;mapa[22,30]=3;mapa[24,30]=0;
mapa[22,27]=5;mapa[23,27]=0;mapa[24,27]=0;
mapa[22,28]=1;mapa[23,28]=0;mapa[24,28]=0;
mapa[22,29]=0;mapa[23,29]=0;mapa[24,29]=0;
mapa[23,33]=0; mapa[23,32]=0; mapa[23,31]=0;mapa[23,30]=0;

```

This is tedious. In other languages 2d arrays can be written like :

```
int[][] myArray = {  {0, 1, 2, 3},
                     {3, 2, 1, 0},
                     {3, 5, 6, 1},
                     {3, 8, 3, 4}  };

```

Can I write in Game Maker Studio 2Darrays like this?

# Answer
> 1 votes
I strongly suggest keeping as many resources/data in files rather than hard-coded/compiled into executable.
For example, the csv format should be suitable for storing data simple as like 2D arrays of integers are and there should not be any problems finding a csv reader for GameMaker or implement csv reader yourself easily(+-20 lines)

```
mapa.txt:
0, 1, 2, 3
3, 2, 1, 0
3, 5, 6, 1
3, 8, 3, 4
//MUCH cleaner and flexible code
mapa = loadCSV(mapa.txt); //loadCSV not part of gamemaker, need to download/implement

```

---
Tags: game-maker
---


title: Game Maker Error (Step HP)

text:
# Question
Title: Game Maker Error (Step HP)
I keep getting this error now in Game Maker:

> `FATAL ERROR in`
> `action number 1`
> `of Step Event0`
> `for object base_enemy:`
>
> `Variable base_enemy.hp(100013, -2147483648) not set before reading it.`
> `at gml_Object_base_enemy_StepNormalEvent_1 (line 2) - if(hp <= 0){`

I understand that it's not finding the variable `hp` in the object `base_enemy` during *Step Event*, but I'm not sure why. I think that the parenting I did has something to do with it, because it found `hp` before further edits to the code. It's set up like this:

`base_enemy` (top parent);
`base_grunt` (first child);
`obj_grunt` (second child)

The `hp` variable is set in the *Create Event* of the second child of each unit. Is it possible that the *Step Event* is checking for `hp` before the variable is declared?

# Answer
> The `hp` variable is set in the *Create Event* of the second child of each unit.

That means you are declaring variable `hp` in the *Create Event* of `base_grunt`, according to the hierarchy you exposed.

But the error Game Maker keeps displaying refers to object `base_enemy`, which is the parent object of `base_grunt` in your inheritance hierarchy.

In fact, you are testing a variable before it is declared. Object `base_enemy` *must* have variable `hp` declared in its *Create Event*, first of all because it's testing it in its *Step Event*, and then because health is a common trait of enemies, and due to inheritance a parent object should be in charge of anything (variables, scripts, ...) its children can have without writing the same code over and over again.

The YoYo compiler won't tell you anything about `hp` missing in the *Create Event*, because it can't know if you are declaring such variable after the object is created as long as it is before *Step Event* occurs.

Solution is: put `hp = 0;` in the *Create Event* of the very top parent (`base_enemy`, I guess), this way any child will have its own variable `hp` and variable testing won't return fatal errors anymore.

Also, I suggest you to give a chance to the built-in variable `health`, which is included in every single instance, and it has dedicated functions and events in the Game Maker environment.
> 1 votes

---
Tags: game-maker
---


# Question
Title: How to only allow a certain amount of the same instance in Game Maker?
I am creating a simple jump n' run game. For some reason my game sometimes spawns two instances of the same enemy on top of each other. So you can't tell there are two of him until he uses his attack where he shoots a barrage of bullets in random directions.

So now when the game spawns two of them, there are also twice as many bullets which makes the game too difficult to play.

I don't know what causes the game to spawn two. It only happens very rarely. I would just make it so that if there are two instances of the same enemy, it destroys one of them.

That would solve the problem.

# Answer
> 1 votes
This is an answer to your question but it is NOT how you should solve your problem. I noticed in the comments that you are aware of that and would like this solution anyway.

Put this in the step event of an object that always exists when you want this to happen:

```
if (instance_number(OBJECT) > MAX_OBJECTS) {
     with (instance_find(OBJECT, MAX_OBJECTS)) {
           instance_destroy()
     }
}

```

Where MAX\_OBJECTS is the maximum number of instances allowed to exist and OBJECT is the name of the object you are checking for. This will destroy the last created instance just after it is created.

Notice that this is not how you should solve this problem, you should simply stop making more of an object once you hit the limit, but this is what you wanted.

# Answer
> 0 votes
A way you could solve it is by checking how many of the object that exist int the create event.

So for example if you put this code in the create event

```
if(instance_number(OBJECT) >= MAX_OBJECTS)
{
   instance_destroy()
}

```

OBJECT Is the object type that you are looking for, in this example it should be the same object as the create even it is put in. MAX\_OBJECTS Is the amount of objects that should be allowed.

This is not maybe the best way to do it to solve your cause you haven't really solved that problem problem, just fixed the symptom but this way works also if you for some reason wan't to limit the amount of one object and because it is in the create event it will only run when needed.

---
Tags: game-maker
---


# Question
Title: How to achieve sprite reflection effect in libgdx
I am currently working on an open world game similar to Pokemon using libgdx. I am currently stuck on this effect that I really want to be done before moving to other features of my game. How can I achieve the following water reflection effect?

I also want it to shimmer like in this video:

"Pokémon Sapphire | Reflections in the water | Episode 4" - 3:38

# Answer
You can use the method `sprite2.setAlpha(float)` to make your sprite slightly tinted and `sprite2.setFlip(boolean x, boolean y)` Set the sprite's flip state regardless of current condition thus making it look like a reflection
> 1 votes

# Answer
I suggest to create a "CharacterReflection" object in your game that updates his sprite and position based on the character's current sprite and position, and is drawn only if character is above water. I mean, in every update() call of this new object, you set the sprite to be the copy of the character's sprite and then reflect it on Y axis. The reflection position coordinates will always be the same as the character for X axis and a fixed Y position below the character. Obviously, before drawing the reflection sprite you'll need to check if there is water below the character. Sorry for not putting examples of code but i'm at work at the moment.
> 0 votes

# Answer
To achieve the water reflection and shimmering effects, you need to work with two sprite properties only: *alpha level*, and *width scale*.

* **Alpha level:** the reflection on the water surface shouldn't be opaque, like on a perfectly clean mirror. You can use `sprite.setAlpha(float a)` with a value between `0.5` and `0.8` (in my opinion) to get a semi-transparent reflected image;
* **Width scale**: in the video you put a link to, the reflection is actually stretching horizontally slowly, over and over again. You can achieve this result updating your sprite with `sprite.setScale(float scaleX, float scaleY)`, where `scaleX` is a value which changes, for example, between `0.9` and `1.1` over the time, whilst `scaleY` is equal to `1` because you don't want the height to change.
Alternatively to `setScale()`, here comes `setSize(float width, float height)` which may give you more precision about sprite transformation: if your sprite is 64 pixels wide, you may want its reflection on the water to vary between 60 and 68 pixels over the time; so, you can call `sprite.setSize(width+widthDelta,height);` making sure `widthDelta` value is updated with a number between `-4` and `4`.
> 0 votes

---
Tags: libgdx, graphic-effects
---


title: How can i show all edges in monogame?

text:
# Question
Title: How can i show all edges in monogame?
I am using `Monogame 3.5` and i have simple model of cube. I use `BasicEffect` to draw it. I want it transparent so i use `effect.Alpha = 0.5f`. Is it possible to show all edges something like on picture?

# Answer
> 1 votes
Perhaps you could change the RasterizerState fill mode.

```
RasterizerState rasterizerState = new RasterizerState();
rasterizerState.FillMode = FillMode.WireFrame;
GraphicsDevice.RasterizerState = rasterizerState;

```

---
Tags: c#, 3d, xna-4.0, monogame
---


# Question
Title: I have my mouse coords converted to world coords. Now how do I detect objects with it? (C++, OpenGL, FreeGlut)
I found a way to convert my mouse coordinates to world coordinates that I can easily understand but now I need to know how to use it to check if the mouse is currently over any of my rendered objects.

Here is my mouse click code that converts the mouse coordinates to screen coordinates when the left mouse button is clicked.

code:

```
void mouseClick( int button, int state, int x, int y ){

//if any mouse button was pressed
if (button == GLUT_LEFT && state == GLUT_DOWN) {

GLint viewport[4]; //hold the viewport info
    GLdouble modelview[16]; //hold the modelview info
    GLdouble projection[16]; //hold the projection matrix info
    GLfloat winX, winY, winZ; //hold screen x,y,z coordinates
    GLdouble worldX, worldY, worldZ; //hold world x,y,z coordinates

    glGetDoublev( GL_MODELVIEW_MATRIX, modelview ); //get the modelview info
    glGetDoublev( GL_PROJECTION_MATRIX, projection ); //get the projection matrix info
    glGetIntegerv( GL_VIEWPORT, viewport ); //get the viewport info

winX = (float)x;
winY = (float)viewport[3] - (float)y;

//get the world coordinates from the screen coordinates
    gluUnProject( winX, winY, 0.0, modelview, projection, viewport, &worldX, &worldY, &worldZ);
    gluUnProject( winX, winY, 1.0, modelview, projection, viewport, &worldX, &worldY, &worldZ);

}
}

```

I've tested it to make sure that the coordinates are converting successfully, and it works fine!!!

As for the near and far planes I did double check that their coordinates are the same as defined in my glorthro.

# Answer
If you have multiple object, then of course you must check each.

However, you can first get the closest object to the cursor, and then check if it's inside.

```
Object closestObj = null; // no object selected
float closestDist = 50; // all objects are smaller than that,

Object currentObj;
float currentDist;

for each currentObj in sccne
{
   currentDist = dist (mouse, currentObj)
   if (currentDist < closestDist)
   {
     closestObj = currentObj;
     closestDist = currentDist;
   }
}

```

Of course, currentDist must be enough that it's true for every mouse cursos position that is inside the object.
> 0 votes

# Answer
"I need to know how to use it to check if the mouse is currently over any of my rendered objects."

Suppose that your object is a rectangle with the following attributes:

* posX: horizontal distance from left of the screen to the first pixel of the object.
* posY: vertical distance from top of the screen to the first pixel of the object.
* sizeX: horizontal size.
* sizeY: vertical size.

In other words, the object is a rectangle that goes from (posX) to (posX + sizeX) in the horizontal axis, and from (posY) to (posY + sizeY) in the vertical axis.

Suppose that the mouse cursor position is (cursorX, cursorY). To check if the the cursor is inside the rectangle, four conditions must happen:

* The cursorX is to the right of the rectangle's left border -\> (cursorX \>= posX).
* The cursorX is to the left of the rectangle's right border -\> (cursorX \<= posX + sizeX).
* The cursorY is below the rectangle's top border -\> (cursorY \>= posY).
* The cursorY is above the rectangle's bottom border -\> (cursorY \<= posY + sizeY).

So connect the four conditions with ands, and voilá!
> 0 votes

# Answer
Now, if the object is a circle, you must use another formula.

Suppose that the circle is centered on (centerX, centerY) and its radius is radius.

The mouse cursor is inside the circle if...

(cursorX - centerX)^2 + (cursorY - centerY)^2 \< radius^2

If it's an ellipse where the horizontal radius is radiusX and the vertical radius is radiusY, then the mouse cursor is inside the ellipse if...

((cursorX - centerX) / radiusX)^2 + ((cursorY - centerY) / radiusY)^2 \< 1
> 0 votes

---
Tags: opengl, c++, glut
---


# Question
Title: Calculating required force for pushing a body to a desired position at once in Unity
In a 3D world I simulate that a coin is being pushed over a plane (applying a force in his rigidbody where y-axis = 0) using a top-down view.

Some time ago but using Box2D, I was able to calculate the amount of force required to stop the coin in a desired position with just one push.

Box2d-js

```
var fps=60;
var groundFriction = 0.01;
var force= new Box2D.Common.Math.b2Vec2(distance.x * coin.box2dBody.GetMass() * fps * (groundFriction * fps),
      distance.y * coin.box2dBody.GetMass()* fps *(groundFriction * fps));
coin.box2dBody.ApplyForce( force, coin.box2dBody.GetWorldCenter(), true );

```

In order to simulate the friction, during the update, I substracted the groundFriction(0.01) to the linearvelocity of the objects in movement in every frame.

Now using Unity with a more complex physics engine I cant replicate the same.

Unity3d

```
Vector3 posFinal = transform.position + direction * distFinal;
Vector3 distanceVecFinal = posFinal - transform.position;
float fps= 1/Time.fixedDeltaTime //50 fps
Vector3 force = new Vector3(distanceVecFinal.x  * myBody.mass * fps, 0,
     distanceVecFinal.z  *    myBody.mass * fps);
myBody.AddForce(force);

```

I think that in the final formula I should add the friction of the objects, but I am not sure how to do it. Maybe this is not the only thing that I should change.

I need help pls!

tl&dr Calculate the required force for making move an object to a desired position in a plane with just one push.

# Answer
> 0 votes
Your Box2D method sounds great, but that kind of stuff only works when you understand exactly how the engine works.

You could You start with a strong push force, and then you use an opposite force, which you increase while you get closer to the desired place.

But if you want to move an object to a specific position, I think that the best way is to do it manually. On each frame, you move the object a small step, and you reduce that step over time to simulate deceleration.

---
Tags: physics, unity
---


# Question
Title: How to handle interaction with the map in a 2D-RPG-typed TileMap?
Sorry if this is a long post, but I'd like to explain the context before asking my question ^^"

I'm currently working on my "first" game (the more advance one, at least). It'll be a **2D-ARPG** where the **player** will be able to **interact** with the **map**, by doing things like **chopping tree**, **farming**, **mining**, *etc...*

As it is my first game, I didn't really know where to go so I started by implementing basics functionalities, and i added more while the game took shape.

With that in mind, the first thing I did is implementing a TileMapReader that take JSON files generated by *Tiled*, and render it on screen. I've kept the structure *Tiled* use (*github.com/bjorn/tiled/wiki/JSON-Map-Format*) in order to store the tiles : The Map have a list of Layer, and each Layer as a list of "gid", corresponding to a Tile in the Tile Set. I generate my map directly from the Tile Set, without creating a Tile Object ... **So my map really is just a bunch of Integers, corresponding to a Tile id.** I generate then the display by pasting the right piece of the Tile Set at the right place on the map.

After that, I start implementing a Camera that could be move around the Map, and then a Player character who can move around too. Currently, the player is an instance of a "Body" class that is store with a x;y location in a field on the Map Object, and is display on a specific empty Layer like any other Tiles (except the sprites come from other external pictures, and not the Tile Set). I linked the control and the Camera to the character, and here I go ! *Walking-in-forest simulator 2016* !

So now, I want to start implementing **interaction** like **collision** and so. The problem is that I really can't decide how to do this. The two first thing I'd like to add to the game are interactions with the trees : **collisions** and **chopping**.

Since the beginning, trees are just **collections of tiles** on **different Layers**, like the rest of the map. But I think I have to make them as **Object entity**, just like my "Body" ...

To do so, I've thought of servals ways :

* I could **parse my Map** Tile by Tile, and **store my tree-tile's position** in order to create my tree, but I find it way to difficult since I don't really know wish Tiles in the Tile Set are the tree-tiles, so **I don't know theirs gid**. Moreover, a tree is composed of **servals Tiles**, placed on **servals Layers**. So it'll be a pain to locate a single tree correctly on the map. Finally, the problems multiplies themselves if I add **other entity** like **water** or **rocks** ...
* Another idea was to **create another Map** in which I **store all the entity as Objects** (and use the tile map for ground and water only). But if I do that, would the Tile Map really be useful ? wouldn't it be better to just randomly-generate a Map entity-full directly ? And since I want to add farming in the future, grass tiles would be passed on the Object-Map too, right ? So the Tile Map will become completely obsolete ...

I decided to go with the **second one**, but here again, I had to pick a way to **store this second Map**. I wanted to go with a **Tree-like Graph** in which I would separate different sections of the map (like each node is 1/2 of it's parent node, and the last Nodes are the different entity with their positions). That would help a lot for the collision's detection, but I think it still really complicate to implement ...

So here my questions : **is my approach on this player-world interactions correct ?** since it is my first "big" game, **I really would like to know if I'm doing it right or not** ... and if not, **how can I handle this interactions properly ?**

I'm posting these here, hopping that there is a simple answer to it (even "just do it" would do ^^ (even if some explanation would be really nice)) and that this post will not be be closed for being too broad ^^"

# Answer
The method I would choose for this is to just use your existing map for as much as possible. This is essentially your first approach. Yes, you will need to figure out the IDs of trees (and other relevant objects), but on the plus side you don't need to make any changes to how you're creating maps, storing them, loading them, rendering them...

**Regarding collision.** You don't need to search for the trees and store them as different objects, necessarily. All you really care about is the locations of the tree base, the other tiles of the trees don't effect collision as you can walk behind them. You will need to encode this data somewhere that the id for tree base (or water, or rock) is a non-passable tile. Using your existing layers (it looks like multiple layers will have non-passable tiles), as your player is walking around you can iterate through the layers to check if they are about to walk into a non-passable tile and stop the movement. If you plan on using layers that you can both walk under and on (eg- bridges that you can across and under) then you will need to adjust which layers you're checking for collision.

```
int[] SolidTiles = { 1, 2, 5 }; // You may consider loading this from a data file.

// Determines whether the tile at (x,y) can be passed through.
bool IsTilePassable(int x, int y)
{
    for (int i = MinLayer; i <= MaxLayer; i++)
    {
        int tile = Map.GetLayer(i).GetTileAt(x, y);
        if (SolidTiles.Contains(tile))
        {
            return false;
        }
    }
    return true;
}

```

**Regarding interaction.** Let's extend this approach to accommodate interactions with the tiles. Instead of using some array of IDs, you can create some objects that contain as much information as you want. Then you just need to query these objects to find out about them. You only need to create as many info objects as you have different types of tiles. 100 trees on your map? No need to create 100 objects to track them, they're all the same type of object, just use a single info object which contains information common to them all (heck, maybe even different kinds of trees can use the same shared info object). As these objects hold only common shared information, note that they do not contain information like the tile's position. The map already knows where the tiles are.

```
class TileInfo
{
    // Returns whether a tile can be passed through.
    bool IsSolid();

    // Returns an object describing the interaction possible with this tile.
    InteractionInfo GetInteraction();
}

```

Now your collision method can look something like this:

```
// Determines whether the tile at (x,y) can be passed through.
bool IsTilePassable(int x, int y)
{
    for (int i = MinLayer; i <= MaxLayer; i++)
    {
        int tileId = Map.GetLayer(i).GetTileAt(x, y);
        // This TileInfoFactory is essentially a Dictionary of int -> TileInfo.
        // At some point earlier you would initialize these objects, possibly
        // loading them from a file.
        // It may be useful to create a default TileInfo which it can fall back on when an
        // ID is not defined. This will allow you to skip writing definitions for
        // some tile types and only write definitions for ones that actually have an impact
        // (eg- trees, rocks).
        TileInfo tile = TileInfoFactory.GetTileInfo(tileId);
        if (tile.IsSolid())
        {
            return false;
        }
    }
    return true;
}

```

Now interacting with tiles is basically the same logic as colliding with them:

```
// Interacts with the tile located at (x, y)
void Interact(int x, int y)
{
    for (int i = MinLayer; i <= MaxLayer; i++)
    {
        int tileId = Map.GetLayer(i).GetTileAt(x, y);
        TileInfo tile = TileInfoFactory.GetTileInfo(tileId);
        InteractionInfo interaction = tile.GetInteraction();
        if (null != interaction)
        {
            // You will need to decide how your engine performs an interaction.
            interaction.Execute();
            return;
        }
    }
}

```

The interaction info object can contain information like what kind of player animation to show (eg- chopping) as well as how it effects the world state. For instance, once you interact with a tree, it may be chopped down and thus not on the map anymore, so you need to update the map.

```
class InteractionInfo
{
    List<MapChange> _mapChanges;

    // Called when the player has finished interacting with the tile at (x, y)
    void Finished(int x, int y)
    {
        foreach (MapChange change in _mapChanges)
        {
            change.Apply(x, y);
        }
    }
}

class MapChange
{
    int _layer;
    int _offsetX;
    int _offsetY;
    int _newTileId;

    void Apply(int x, int y)
    {
        Map.GetLayer(_layer).SetTileAt(x + _offsetX, y + _offsetY, _newTileId);
    }
}

```

Finally, I assume you will want to save your map between play sessions. Simply serialize it back into JSON and save it on disk. I recommend using a different filename than what the base state is saved as so you can start your game over. When you load the game, you can first check if, say, "map-saveslot1.json" exists before defaulting to the base "map.json"
> 2 votes

---
Tags: java, 2d, collision-detection, tilemap, data-structure
---


# Question
Title: Is there any difference between the reading of sensors in Unity5 and Android/Java?
I'm an `Android/Java` developer, and I'm new to `unity5`. I have a program written in `Android/Java` that uses the readings of three sensors( `Accelerometer`, `Magnetometer` and `LinearAccelertion` ).

I'm now developing my first game in `unity5`, and I want to use the algorithm that uses the three sensors readings in my game.

In `Android/Java`, sensors readings are normally row data, which means that I must make some calculations on these data to be able to use them in my program.

Do I also have to make these calculations in `unity5`? Are the reading of sensors in `Android/Java` and `unity5` the same or different?

If they are different, how can I use them?

# Answer
> 0 votes
**Disclaimer:** so far my experience with motion control in Unity has been with devices not supported by the Input class, so I've always rolled my own sensor fusion as you describe. The description below is based on the docs - I'd welcome corrections or further details from anyone with hands-on experience.

Unity provides a few ways to access the motion of the device without needing to do the fusion yourself:

* Input.gyro.attitude (Quaternion) gives the orientation of the device in space. It's unclear to me from the docs whether this includes magnetic heading information when available, or if it might be prone to yaw drift.
* Input.gyro.userAcceleration (Vector3) gives the local linear acceleration of the device, with the estimated contribution due to gravity subtracted out.
* Input.gyro.rotationRateUnbiased (Vector3) gives the local gyroscope rotation rate readings in radians per second, after compensating for biases.
* Input.compass.magneticHeading (float) gives the heading in degrees from the top of the screen (in its current orientation) to magnetic north.
* Input.compass.trueHeading (float) gives the heading in degrees from the top of the screen (in its current orientation) to geographic north, once you've enabled location updates by calling Input.location.Start()

Note that to use these methods you'll need to enable the gyroscope or compass respectively.

I don't know how these compare in terms of performance or accuracy compared to rolling your own sensor fusion, but like most of Unity I'd expect they'd at least provide a solid starting point for prototyping.

---
Tags: android, unity, sensor-fusion
---


# Question
Title: How to find a point of taking into account the distortion of the projection
I can not find the material that will help me to implement the algorithm of coordinate transformation based on the distortion of the projection.

I am creating a code recognition algorithm (similar to qr-code). After recognizing the image I get the three points.

My problem that image have different projection distortion, size and angle.

How do I find the k point, knowing the coordinates of p1, p2, p3 with distortion and without distortion of the projections.

Help me to understand! Perhaps there are ready-made algorithms or literature that will help implement it.

It is very important for me. Thank you!

# Answer
> 1 votes
Unfortunately this is quick to answer: You can't from a single image.

To determine the intrinsic camera parameters (like lens distortion) you'll need at least a few pictures and more known points.

If you want to read more about it, Google for "camera calibration" or lookup how some libraries do that, e.g. OpenCV.

From a single image all you could get are extrinsic camera patterns (position and rotation), ignoring distortion. This would leave you with some error margin though. QR code fights this with some tricks, like knowing that the whole pattern has to be quadratic. This allows the Chevron of some distortions or simply ensure that they're not too significant.

---
Tags: 2d, mathematics, coordinates, projection, raytracing
---


title: Triangle-Plane intersection in 3D space

text:
# Question
Title: Triangle-Plane intersection in 3D space
I would like to clip a triangle if its bounds lie partially out of a cube. I guess I would need some kind of Triangle Plane intersection code - I'm not well versed with math but I do have the points of the triangle in 3d space (P1, P2, P3).

How do I get the 2 points of intersection of the triangle with one of the planes of the cube?

# Answer
> 5 votes
If cube is axis-aligned, then it's easy.

You can compare each vertex of triangle with each face (plane) of cube. If it's out of cube (just compare apropriate coordinates), then find two new points, which lie on line connecting two other vertices with that one out of cube and which lie on plane (their coordinate is same as the plane). This is common linear interpolation. So I think you would handle it.

But you should be aware of case, which is on picture. Everytime choose point, which is closer to vertex, which is not out of cube (inner vertex). Choose green point, not red (which is closer to vertex out of cube).

Well. And if cube is not axis-aligned, you can look here: http://www.softsurfer.com/Archive/algorithm\_0105/algorithm\_0105.htm#Triangle-Plane

There is intersection of triangle and plane (not axis aligned). You can use it and test it with all cube faces.

I hope I answered your question. If not, then punch me and ask again :)

# Answer
> 0 votes
A good explanation of a solution can be found at http://geomalgorithms.com/a06-\_intersect-2.html:

1) Use the dot-product to determine whether the triangle lies fully on one side of the plane and does not intersect the plane at all.
2) If there is an intersection, use a line-plane-intersection-algorithm for the two edges hitting the plane (algorithm on the same page)

---
Tags: 3d, geometry, intersection
---


title: Mesh Chunk Combining and Extruding

text:
# Question
Title: Mesh Chunk Combining and Extruding
So I'm working on a proceduraly generated level, that is composed of multiple chunks, so you don't go over the maximum amount of verts allowed in Unity Meshes. Another function is the ability to raise/lower the mesh to modify it on click.

However, the borders of the chunks break this functionality. And I can't edit both at the same time. Currently to raise/lower, i have a raycast returning the mesh that you are clicking on, and extruding those points. However, this dosen't allow me to edit overlapping boundaries.

Any ideas on a better solution?

Thanks for the help!

# Answer
> 1 votes
Usually people solve this by having an underlying dataset and modifying that, having a border region of extra data in that set around the actual region you want to mesh will solve this as the mesh edges essentially need to be aware of the portion of mesh that is connected to them to line this up right.

Also:

when editing a portion of the data on a meshing edge you should regenerate both meshes.

---
Tags: unity, c#, terrain, mesh, procedural
---


title: SVG—rendering performance

text:
# Question
Title: SVG—rendering performance
I have created a jump'n'run browser-game based on SVG. The »World« grew large (~80px * ~20000px, before scaled to viewport height) and rendering went slow. In consequence I included a range searching algorithm to exclude elements from the render tree, if they are out of the visible area. To get all elements inside the viewport, I am using a range query on a AVL-Tree.

Basically the approach was very effective and increased the performance up to 40%, unfortunately it also results in flickering of the graphic if the player is in motion.

The initialization looks like this:

```
//for each element of type: path, rect, polygon, line, circle, polyline,use,text or tspan

var box = bbox.call(this, element, mtr),
  data = {
    style:    element.style,
    x1:       box[0].x,
    x2:       box[1].x,
    visible:  false
  }
this.tree.insert(box[0].x, data);
this.tree.insert(box[1].x, data);
element.style.display = 'none';

```

whereby `bbox()` creates gets the bounding box in global coordinates.

Each time at `rendering` the following is done:

```
var x1      = this.viewBox.x - 1,
    x2      = this.viewBox.x + this.viewBox.width + 1,
    result  = this.tree.query(x1, x2),
    visible = this.visible,
    i       = 0,
    n       = result.length,
    data;

for (; i < n; i++) {
  data = result[i];
  if (!data.visible) {
    data.style.display = 'block'
    data.visible = true;
  }
}

for (i = 0, n = visible.length; i < n; i++) {
  data = visible[i];
  if (data.x1 > x2 || data.x2 < x1) {
    data.style.display = 'none';
    data.visible = false;
  }
}

this.visible = result;

```

As mentioned above, the framerate increased between 20% and 40% on each platform, but flickering and kind of sloppy rendering began.

What could I do to gain a more fluent rendering?

# Answer
> 1 votes
There are several performance issues with the code sample you supplied.

Consider using pop to increase performance

```
for (; i < n; i++) {
  data = result[i];

```

vs

```
while((data = result.pop()) != null) {...

```

If it can't be destructive which I think looking at your code it can be then you can clone using

```
var clone = myArray.slice(0);

```

Performance is between 260% and 15000% (Jsperf is no longer up to show you sorry)

Dereference variables before loops, each reference adds around 7ms per reference in the chain on my 4.6GHZ i7.
if (!data.visible) { data.style.display = 'block' data.visible = true; } }

Again dereference, the visible.length is referenced every run

```
for (i = 0, n = visible.length; i < n; i++) {
  data = visible[i];
  if (data.x1 > x2 || data.x2 < x1) {
    data.style.display = 'none';
    data.visible = false;
  }
}

```

Also use

```
requestAnimationFrame(delegate);

```

Request animation frame explained

When drawing to prevent DOM redraws.

\[Source\] : I'm an internationally renowned code analysis expert who studies code performance.

---
Tags: rendering, performance, browser-based-games, svg
---