title: C# - Separating Overlapping Rectangles

text:
# Question
Title: C# - Separating Overlapping Rectangles
I'm trying to separate an arbitrary number of randomly sized rectangles, while still keeping them snapped to the grid, and somewhat packed together nicely. The goal is to start with something like this...

And end with something like this..

I've managed to get initial generation of random rectangles drawn in, that's the easy part; I've also done some reading up on separation algorithms but I can never seem to get things just right. They always spread out a bit (slowly, meaning lots of iterations) then just jitter around with massive gaps between them.

My (simple) separation function can be seen here, but it's very possible I'm doing something terribly wrong, or going about it all wrong! Here's also the current code in action (click/anykey to run the separation function)

Is there perhaps a better way to achieve this desired result, or something? Any help or suggestions would be great!

# Answer
> 1 votes
Please note that I'm only giving a rough starting point for an algorithm here. I can't say for sure if it will work, and you'll have to do a bit of legwork to implement this.

First, a few quick things: What do you define as "lots of iterations"? The TinyKeep demo you linked does it in around 40-50. Also, given that you are working with something 2D grid based, you should probably be working with a pair of integers (X and Y axis), rather than a floating-point `Vector3`.

Looking at your `Separate()` method, you don't seem to be taking into account the size of the rooms. This seems to be the primary issue. Because you need to be considering the penetration distance between pairs of rooms (which requires the size).

You only need to consider each pair of rooms once, so use a loop like this:

```
for(int i = 0; i < count; i++)
    for(int j = i+1; j < count; j++) // <- note how it starts at i+1

```

---

Here's a rough outline of the algorithm:

For each pair of rectangles, see if they intersect. Pick the axis with the *minimum* amount of penetration (so: left edge to right edge, right edge to left edge, top edge to bottom edge, bottom edge to top edge). Only use a single axis! Your current algorithm is considering both axes at once, based only on position.

**In other words, if you only had two rectangles, this would be the smallest amount you would need to shift them to separate them.** This amount could be split between the two rectangles in any ratio (but in opposite directions). This is a directional quantity, so store it as a vector (again: not as a `vector3`, but as a pair of `int`).

(This is basically a constrained version of the "separating axis theorem".)

The tricky bit, then, is to make this work for multiple rectangles in a way that can be iterated to a final solution. Without trying to implement it myself, I can't say for sure what this would look like. Here's what I would start with:

For each rectangle, store the maximum *(or minimum?)* separation vector by magnitude. When iterating over each pair, determine the minimum separation vector for that pair as explained above. Divide that separation vector evenly *(or randomly?)* between the two rectangles and replace the stored value for that rectangle if it is greater *(or smaller?)* in magnitude.

(Note: when dividing the integers, be aware that you must divide (for example) `5` into `3` and `2`. So divide for one value, and subtract that from the total for the other.)

And then, apply the stored separation vectors to each rectangle - similar to what you are already doing. Then iterate until all of the separation vectors are zero.

# Answer
> 0 votes
This is what works for me in 3D using flattened cubes for a "floor".

I make a cube prefab and attach this script:

```
using UnityEngine;
using System.Collections;

public class move : MonoBehaviour
{

  public int strength;
  private GameObject[] gO;

  // Use this for initialization
  void Start ()
  {
  }

  // Update is called once per frame
  void Update ()
  {
    gO = GameObject.FindGameObjectsWithTag ("Gen");
    foreach (GameObject a in gO) {
      if (a != this) {
        if (this.GetComponent<Renderer> ().bounds.Intersects (a.GetComponent<Renderer> ().bounds)) {
          Vector3 direction = transform.position - a.transform.position;
          direction.Normalize ();
          transform.position = new Vector3 (Mathf.Round (transform.position.x + (direction.x * strength)), transform.position.y, Mathf.Round (transform.position.z + (direction.z * strength)));

        }
      }
    }
  }
}

```

Then instantiate a bunch of them over a random range, but pretty close together. If they're all created at, say, (0,0,0) they won't organize.

---
Tags: c#, unity, mathematics, procedural-generation
---


# Question
Title: C++ Frogger game - Logs on Water bounding boxes?
I am making a Frogger game in C++ using SFML but have come across a problem. I have a block of water and log rectangles moving over it (All sprites) and would like the Frog sprite to do something when it hits the water, however with bounding boxes, even in the frog sprite moves onto a log it still passes the water bounding box and carries out the code for that. Is there any way to have the conditions so it intersects the water but only does something when it's not in collision with the log's?

Thank you.

# Answer
One way to do it would be to wait until all your collision detection is done before 'reacting' to it. You could then check if it touches only the water and not the log before 'reacting' to the event.

Example game loop:

1. Update from user imput
2. Move your game objects
3. Clear `frog-water collision flag` and `frog-log collision flag`
4. Perform collision detection
    1. Raise a flag if there is a frog-water collision
    2. Raise a flag if there is a frog-log collision
5. React to physics
    1. Perform the 'on hit water' code if `frog-water collision flag` is raised and `frog-log collision flag` is *not* raised

Obviously, this will depend on your implementation, but this could give you an idea on how it could be done.
> 0 votes

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


# Question
Title: Legal Implications of using Openal in Opentk Commercially
Myself and my friend are currently creating a game, which we plan on selling upon its completion. We are using opentk.

I read over this: http://www.opentk.com/node/532 , and it pretty well describes that this is perfectly legal. However, we are using the included openal standard included with opentk. The license that openal belongs to is somewhat ambiguous, I read in some places that it is under LGPL, and in other places that it is not. I've also heard about an "openal soft". I'm not entirely sure what the difference is, and which is included in opentk, and what I am allowed to do, and not to do with it.

Are we allowed to include the openal installer with our program so that the program will correctly launch for the user? Or will this incur possible legal implications?

Also, do we need to include legal information in/with the game regarding openal and its usage? Or are we fine simply using it?

Sorry for all the questions, and thank you anyone and everyone who responds to, and reads this, for your time.

# Answer
> 2 votes
OpenAL is an open standard (meaning anyone can read and use it) with several implementations, some of which are proprietary (generally *patent protected*). OpenAL Soft is one such implementation which is under the LGPL. Creative Technology maintains another confusingly called just OpenAL, which is now proprietary.

You must obtain a license from the developer for any *proprietary version* of OpenAL, but LGPL versions are free as in speech, but not necessarily open source, and that requirement doesn't extend to derivative works.

It is always a good idea to include any relevant license information pertaining to your software as distributed, but in this case you ***must*** include the LGPL license in the *combined work* (Section 4 - GPL). This is because the LGPL is based on the GPL (see LGPL Preamble):

> This version of the GNU Lesser General Public License incorporates the terms and conditions of version 3 of the GNU General Public License, supplemented by the additional permissions listed below.

Which states in Section 11:

> Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, **sell**, offer for sale, import and otherwise run, **modify** and propagate the contents of its contributor version.

And merely excepts Section 3 of the GPL, which is:

> When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures.

Vis-à-vis Section 1 of the LGPL:

> You may convey a covered work under sections 3 and 4 of this License *without* being bound by section 3 of the **GNU GPL**.

---
Tags: legal, opentk, openal, commercial
---


# Question
Title: Java Game How to find the x and y for a tile?
Hello I have a java game where you build houses I want to be able to dag my mouse form point a to point b and I want to fill that area with tiles when I release the mouse. What I cant do is get the first x and y coordinate of the selected area then put the tile there then move on to the next area I tried to do something like this:

```
    bx = Math.min((dragX / 20) * 20, (curX / 20) * 20);
    by = Math.min((dragY / 20) * 20, (curY / 20) * 20);
    w = Math.abs((curX / 20) * 20 - (dragX / 20) * 20);
    h = Math.abs((curY / 20) * 20 - (dragY / 20) * 20);

    if (dragging & w >= 20 && h >= 20) {
        g.setColor(new Color(26, 216, 26, 128));
        g.fillRect(bx, by, w, h);
        g.setColor(new Color(17, 142, 17, 255));
        g.drawRect(bx, by, w, h);

        int posx = play.bx * 20;
        int posy = play.by * 20;
        for (int i = 0; i <(play.w * play.h / 20) / 20 ; i++) {

            play.b.add(new wall((posx), (posy), play.selectedRot));
            posx +=20;
            posy+=20;
        }
    }

```

dragX and dragY is where it starts and curx and cury is where it is currently the tiles are 20x20 pixels so I place them every 20 pixels on the screen so it is like a grid. if I select an area that is 2 tile wide and 2 tiles high and each tile is 20 x 20 pixels that is 1600 pixels I divide that number by 20 and get 80 and then divide that by 20 again to find out how many tiles I need to place in total which in this case is four. what I don't know is how to find the x and y that I need to place that tile then I don't know how to move on to the next one. Please help me. Thx to everyone who reads this.

# Answer
> 1 votes
It's pretty simple. All you need is something like this:

```
// It's always good to keep variables around instead of inlining
// magic numbers.
int gridSizeX = 20;
int gridSizeY = 20;

// The rectangle starts getting dragged at startX, startY,
// ends dragging at endX, endY
// Like this:
// +-------------------------+
// | startX, startY          |
// |                         |
// |               endX, endY|
// +-------------------------+
// Note that since the player can drag up and to the left,
// its possible that startX > endX and startY > endY.
int startX, startY, endX, endY;

// Convert pixel to grid coordinates.
int startGridX = startX / gridSizeX;
int startGridY = startX / gridSizeY;
int endGridX= endX / gridSizeX;
int endGridY= endY / gridSizeY;

// Find the bounds in grid coordinates of the start
// and end. (minX, minY) will be in the top left, and
// (maxX, maxY) will be in the bottom right.
int minX = min(startGridX, endGridX);
int maxX = max(startGridX, endGridX);
int minY = min(startGridY, endGridY);
int maxY = max(startGridY, endGridY);

// Iterate through all the grid coordinates.
for (int x = minX; x <= maxX; x++)
{
    for (int y = minY; y <= maxY; y++)
    {
        // Place a tile at the given grid coordinate.
        // The arguments to this function should be in pixels.
        CreateTile(x * gridSizeX, y * gridSizeY);
    }
}

```

---
Tags: java
---


# Question
Title: Does a pong clone called "Ping" infringe on any copyrights or trademarks?
Long story short, I made a retro Pong clone and submitted it to the App Store as my first app. It survived for a bit, but I eventually received a message from Atari tell me to remove it. There was nothing more than that, I just took it down, and they made no other demands. Since then, it has remained removed.

I have become a much better programmer now and would now like to re-create my original app and upload it again. However, I'm afraid that something of the sort would happen again. Is remaking the game itself against any laws? If not, would using the name "Super Ping" instead of "Super Pong" be legal?

# Answer
## Pong is a registered trademark of Atari Interactive Inc.

From wikipedia:

> A trademark, trade mark, or trade-mark\[1\] is a distinctive sign or indicator used by an individual, business organization, or other legal entity to identify that the products or services to consumers with which the **trademark appears originate from a unique source**, and to distinguish its products or services from those of other entities.

As RogueThinking said, probably what instigated the take-down was your naming the product in such a way that Atari can argue it's conceivable someone will mistake it **for a product Atari made**. It seems like you're trying to piggyback off the Pong brand name. Which you cannot do.

But if you make a game with paddles and balls and **name it something totally different**, like

# **PADDLEBALLSUPERSMASHEM**

then Atari probably shouldn't have a problem with that.

Note a similar game existed in 2007 and was taken down by Atari, called **Plasma Pong**. Again he's repeating the same mistake - there's trademark infringement right in the name.
> 9 votes

# Answer
TLDR: depends where you live. Be more creative.

Instead of worrying about if it's legal or not, why don't you just come up with something more creative?

Pong is boring. Pong clones are boring too. I'm sure you can come up with a unique, interesting twist on it that will take it to the next level.

Heck, I need to do this too, since I'm working on a game with "pong" in the name :)
> 4 votes

# Answer
The issue is about "Brand". Atari has created a brand around 'Pong' and invested in the brand. If you are creating a game that wants to leverage that brand so that others will be interested in playing it, for example using 'Pong' in the name then you will likely draw the attention of the brand owner - in this case Atari. If the game is pong like but has different attributes I suggest naming it something that highlights those attributes. Keep in mind the more your game looks like - identical graphics - name - the more likely you are going to infringe on their 'brand'.
> 2 votes

# Answer
I guess it depends on what Atari put under copyright.. For example Tetris is not only copyrighted by the name, the shape of the blocks is copyrighted aswell as the size of the area where the blocks go. That means that if you do a Tetris clone you could call it any way you like, but if it uses the same shapes and the "wall area" has the same width and height, you are up for a copyright infringement

I wonder if there's some place where you could check if anything is copyrighted, like names for starters
> -3 votes

---
Tags: legal, copyright, appstore
---


# Question
Title: how to Move Player on "Z" Axis 2D Movement
I'm working on 2D mobile game, and I'm using the Standard Asset(Mobile) Single Joystick prefab to move the Player. Currently my player moves on the X and Y axis.

How can I move my player on the z axis?

This is Joystick Script fromStander Assets Mobile

```
using UnityEngine;

[RequireComponent(typeof(GUITexture))]
public class Joystick : MonoBehaviour
{
    class Boundary {
        public Vector2 min = Vector2.zero;
        public Vector2 max = Vector2.zero;
    }

    private static Joystick[] joysticks;                                  // A static collection of all joysticks
    private static bool enumeratedJoysticks = false;
    private static float tapTimeDelta = 0.3f;                               // Time allowed between taps

    public bool touchPad;
    public Vector2 position = Vector2.zero;
    public Rect touchZone;
    public Vector2 deadZone = Vector2.zero;                                         // Control when position is output
    public bool normalize = false;                                                  // Normalize output after the dead-zone?
    public int tapCount;

    private int lastFingerId = -1;                                                          // Finger last used for this joystick
    private float tapTimeWindow;                                                    // How much time there is left for a tap to occur
    private Vector2 fingerDownPos;
    //private float fingerDownTime;
    //private float firstDeltaTime = 0.5f;

    private GUITexture gui;
    private Rect defaultRect;                                                               // Default position / extents of the joystick graphic
    private Boundary guiBoundary = new Boundary();                  // Boundary for joystick graphic
    private Vector2 guiTouchOffset;                                         // Offset to apply to touch input
    private Vector2 guiCenter;                                                      // Center of joystick

    void Start() {
        gui = (GUITexture)GetComponent(typeof(GUITexture));

        defaultRect = gui.pixelInset;
        defaultRect.x += transform.position.x * Screen.width;// + gui.pixelInset.x; // -  Screen.width * 0.5;
        defaultRect.y += transform.position.y * Screen.height;// - Screen.height * 0.5;

        transform.position = Vector3.zero;

        if (touchPad) {
            // If a texture has been assigned, then use the rect ferom the gui as our touchZone
            if ( gui.texture )
                touchZone = defaultRect;
        } else {
            guiTouchOffset.x = defaultRect.width * 0.5f;
            guiTouchOffset.y = defaultRect.height * 0.5f;

            // Cache the center of the GUI, since it doesn't change
            guiCenter.x = defaultRect.x + guiTouchOffset.x;
            guiCenter.y = defaultRect.y + guiTouchOffset.y;

            // Let's build the GUI boundary, so we can clamp joystick movement
            guiBoundary.min.x = defaultRect.x - guiTouchOffset.x;
            guiBoundary.max.x = defaultRect.x + guiTouchOffset.x;
            guiBoundary.min.y = defaultRect.y - guiTouchOffset.y;
            guiBoundary.max.y = defaultRect.y + guiTouchOffset.y;
        }
    }

    public Vector2 getGUICenter() {
        return guiCenter;
    }

    void Disable() {
        gameObject.active = false;
        //enumeratedJoysticks = false;
    }

    private void ResetJoystick() {
        gui.pixelInset = defaultRect;
        lastFingerId = -1;
        position = Vector2.zero;
        fingerDownPos = Vector2.zero;
    }

    private bool IsFingerDown() {
        return (lastFingerId != -1);
    }

    public void LatchedFinger(int fingerId) {
        // If another joystick has latched this finger, then we must release it
        if ( lastFingerId == fingerId )
            ResetJoystick();
    }

    void Update() {
        if (!enumeratedJoysticks) {
            // Collect all joysticks in the game, so we can relay finger latching messages
            joysticks = (Joystick[])FindObjectsOfType(typeof(Joystick));
            enumeratedJoysticks = true;
        }

        int count = Input.touchCount;

        if ( tapTimeWindow > 0 )
            tapTimeWindow -= Time.deltaTime;
        else
            tapCount = 0;

        if ( count == 0 )
            ResetJoystick();
        else
        {
            for(int i = 0; i < count; i++) {
                Touch touch = Input.GetTouch(i);
                Vector2 guiTouchPos = touch.position - guiTouchOffset;

                bool shouldLatchFinger = false;
                if (touchPad) {
                    if (touchZone.Contains(touch.position))
                        shouldLatchFinger = true;
                }
                else if (gui.HitTest(touch.position)) {
                    shouldLatchFinger = true;
                }

                // Latch the finger if this is a new touch
                if (shouldLatchFinger && (lastFingerId == -1 || lastFingerId != touch.fingerId )) {

                    if (touchPad) {
                        //gui.color.a = 0.15;
                        lastFingerId = touch.fingerId;
                        //fingerDownPos = touch.position;
                        //fingerDownTime = Time.time;
                    }

                    lastFingerId = touch.fingerId;

                    // Accumulate taps if it is within the time window
                    if ( tapTimeWindow > 0 )
                        tapCount++;
                    else {
                        tapCount = 1;
                        tapTimeWindow = tapTimeDelta;
                    }

                    // Tell other joysticks we've latched this finger
                    //for (  j : Joystick in joysticks )
                    foreach (Joystick j in joysticks) {
                        if (j != this)
                            j.LatchedFinger( touch.fingerId );
                    }
                }

                if ( lastFingerId == touch.fingerId ) {
                    // Override the tap count with what the iPhone SDK reports if it is greater
                    // This is a workaround, since the iPhone SDK does not currently track taps
                    // for multiple touches
                    if ( touch.tapCount > tapCount )
                        tapCount = touch.tapCount;

                    if ( touchPad ) {
                        // For a touchpad, let's just set the position directly based on distance from initial touchdown
                        position.x = Mathf.Clamp( ( touch.position.x - fingerDownPos.x ) / ( touchZone.width / 2 ), -1, 1 );

                        position.y = Mathf.Clamp( ( touch.position.y - fingerDownPos.y ) / ( touchZone.height / 2 ), -1, 1 );
                    } else {
                        // Change the location of the joystick graphic to match where the touch is
                        Rect r = gui.pixelInset;
                        r.x =  Mathf.Clamp( guiTouchPos.x, guiBoundary.min.x, guiBoundary.max.x );
                        r.y =  Mathf.Clamp( guiTouchPos.y, guiBoundary.min.y, guiBoundary.max.y );
                        gui.pixelInset = r;
                    }

                    if (touch.phase == TouchPhase.Ended || touch.phase == TouchPhase.Canceled)
                        ResetJoystick();
                }
            }
        }

        if (!touchPad) {
            // Get a value between -1 and 1 based on the joystick graphic location
            position.x = ( gui.pixelInset.x + guiTouchOffset.x - guiCenter.x ) / guiTouchOffset.x;
            position.y = ( gui.pixelInset.y + guiTouchOffset.y - guiCenter.y ) / guiTouchOffset.y;
        }

        // Adjust for dead zone
        var absoluteX = Mathf.Abs( position.x );
        var absoluteY = Mathf.Abs( position.y );

        if (absoluteX < deadZone.x) {
            // Report the joystick as being at the center if it is within the dead zone
            position.x = 0;
        }
        else if (normalize) {
            // Rescale the output after taking the dead zone into account
            position.x = Mathf.Sign( position.x ) * ( absoluteX - deadZone.x ) / ( 1 - deadZone.x );
        }

        if (absoluteY < deadZone.y) {
            // Report the joystick as being at the center if it is within the dead zone
            position.y = 0;
        }
        else if (normalize) {
            // Rescale the output after taking the dead zone into account
            position.y = Mathf.Sign( position.y ) * ( absoluteY - deadZone.y ) / ( 1 - deadZone.y );
        }

    }

}

```

And This is My joystick input script

```
using UnityEngine;
using System.Collections;

public class JoystickInput : MonoBehaviour {

    public Joystick joysticks;           // Reference to joystick prefab
    public float speed = 10;             // Movement speed
    public bool useAxisInput = true;   // Use Input Axis or Joystick
    private float h = 0, v = 0;         // Horizontal and Vertical values

    // Update is called once per frame
    void Update () {
        // Get horizontal and vertical input values from either axis or the joystick.
        if (!useAxisInput) {
            h = joysticks.position.x;
            v = joysticks.position.y;
        }
        else {
            h = Input.GetAxis("Horizontal");
            v = Input.GetAxis("Vertical");
        }

        // Apply horizontal velocity
        if (Mathf.Abs(h) > 0) {
            rigidbody2D.velocity = new Vector2(h * speed, rigidbody2D.velocity.y);
        }

        // Apply vertical velocity
        if (Mathf.Abs(v) > 0) {
            rigidbody2D.velocity = new Vector2(rigidbody2D.velocity.x, v * speed);
        }
    }
}

```

i mean like this..

# Answer
> 3 votes
So what you're doing is a pseudo-3D game then. The world works in 3D coordinates, but you just display stuff in 2D.

To do things like these, you probably want to keep the character coordinates in 3D, and use these to calculate the sprite coordinates in 2D.

It's totally up to you how you want your game to be controlled, but if for example, you use the X axis in the controller to control horizontal movement, the Y axis to control depth movement, and a button to jump, then you would have something like this (in pseudocode)

```
-- characterPos, this is a 3D vector
vector3 characterPos

-- ground movement
if input.right then
    characterPos.x++
else if input.left then
    characterPos.x--
end
if input.up then
    characterPos.z++
else if input.down then
    characterPos.z--
end

-- super trivial jump+gravity
if input.button then
    characterPos.y++
end
characterPos.y -= 0.2
if characterPos.y < 0 then
    characterPos.y = 0
end

-- convert character coordinates to screen coordinates
-- x and y work as normal. z is represented as movement
-- in both x and y
-- We suppose y is positive upwards
vector2 spritePos
spritePos.x = characterPos.x + characterPos.z
spritePos.y = characterPos.z + characterPos.y

```

This uses a really trivial gravity implementation. If you want a more realistic gravity simulation, you may want to check this answer

How to implement this in your language and engine of choice is left as an exercise to the reader.

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


# Question
Title: In Unity for Android, how do I create touchable buttons?
I'm making a test game for Android in Unity 5, and I want to add left-right control buttons like the circles below, to move an object left or right.

<sub>(source: raywenderlich.com)</sub>

How can I do this?

Sorry if this question is basic. I'm new to Unity and I don't understand the methods of existing tutorials.

# Answer
Since Android devices don't have left/right buttons (well, a long time ago they used to, and if you use bluetooth keyboard/gamepads they will), what you want is **onscreen buttons**. If you search for that then you will find plenty of answers and tutorials.

The easiest method is to use the built-in `GUI.Button` class. There are many other ways to do it, such as detecting touch events and checking if they intersect some part of the screen.
> 2 votes

---
Tags: unity, android, touch, controllers
---


# Question
Title: How to prevent constant adjustments form collision?
I'm try to clone a popular 2D platformer as a project. For both the player character and enemies, whenever I constantly check to see if they are walking on the ground or floating platforms, they "vibrate" or "Bounce" instead of walking smoothly, as gravity pushes them downward, and the platform pushes them upward. I have tried searching for this problem, but can't seem to find anything relevant to my problems (which probably means I am searching the wrong thing because I'm sure everyone runs into this problem at some point.)

Essentially, the player and enemies are always effected by gravity, but the collision acts against it and pushes them upward. I tried having a boolean that was set once they appeared to be on solid ground, but this made them float artificially once they walked off of floating platforms.

Here is the code for enemy collisons:

```
public void EnemyBlockResponder(IEnemy enemy, IBlock block, Rectangle intersection)
{
    enemy.YLocation -= intersection.Height;
}

```

I'm currently assuming that a side collision with a block will never happen for debugging.

Here is the Update method for the enemy:

```
public void Update()
{
    if (currentDirection == Direction.LEFT)
    {
        xLocation--;
    }
    else if (currentDirection == Direction.RIGHT)
    {
        xLocation++;
    }
    if (NoFloor())
    {
        yLocation += 3;
    }

    goombaSprite.Update();
}

```

Where NoFloor is a method that checks all the blocks on camera to see if the enemy is colliding with any of them.

Where is this code causing the sprite to continually bounce? I appreciate any help and criticisms. Thanks.

# Answer
> 0 votes
Your bouncing is caused by calculus imprecision, mixed with the time integration component.

This kind of things happen with involvement of these components:

* contacts detection
* response impulses
* integration

Point 1 we don't know who does it in your code. I guess some framework feature, the result of the contact information is given to you in the `intersection` object so it seems. The `Height` component has an imprecision you need to aknowledge, and therefore you can't trust it to be a good corrector.

Point 2, you do it on this line `enemy.YLocation -= intersection.Height;`
this is an exact simplified impulse. You correct the position without going through a force integration step (impulse method) but it is the same thing.
This point too is imperfect, and you can't perfect it, don't strive for it, collision handling in games is not an exact science. But you can make it fault tolerant by introducing softness a bit everywhere. In the form of deltas, epsilons, gradients, spring forces, multi-iteration penetration solving, fixed step simulation, auto freeze, etc etc... lots of little bits of technique there and there that makes your whole collision handling smooth.

Your "gravity" integration `yLocation += 3`, I guess "freefall" simulation, is also sensitive to the fact that you need to rely on a `NoFloor()` method that is probably too strict (too correct numerically) which is yet another factor in your bouncing problem.

The final point is the integration, in the code snippets you give us, there is notion of delta time watsoever. You skip framerate issues, or physics simulation rate issues altogether. Maybe this is for snippet purity sake on stackexchange, maybe not. Anyway it matters, and introducing it will have you think about precision even more. Because here it almost seems like you're doing integer calculus, but I think the vector you manipulate must come from xna and therefore be floats ? `double` precision usually is not needed in absolute, BUT can help in these kind of domains, to increase smoothness.

Determinism, also helps in smoothness, when you fix your simulation timestep. see this link.

To talk a bit more about integration, when you will have introduced your "dt" (stuff that you multiply every unit to integrate into the next unit. Acceleration integrates into speed, and speed integrates into position). You use "dt" to multiply. If you do a simple multiply based on current values, this is called "Euler integration". If you use half of the current value, and half of the previous frame's value, this is called "Verlet integration".

Using Verlet will ALSO buy you smoothness and stability.

But really in your particular case, you need to focus on your "NoFloor()" resolution, this is the main culprit.
You have a feedback loop, because of numerical imprecision, you can't determine that for sure your character is "on the floor" after you corrected a penetration with your `-= intersection.Height` subtraction. So what you need to do, is cut some lack to your "NoFloor" function so that it says a little bit more often that the character is actually on the floor.

Next step, is to try to correct penetration by progressive and smooth forces integrated over time rather than a super hard direction position correction. Use dampers and spring forces which are evaluated in term of the "distance to ground". And let a few frames fix the position, it will get rid of your bouncing totally. Just make your spring "hardness" (usually noted `k`, or newton constant, in physics) very high to simulate the fact that you bump against a hard ground, and not some soft trampoline. But With any physics simulation, making so that every collision is solved in terms of soft interactions is always much more stable than truely hard interactions.

As a final point, I made a platformer demo that implements some of the ideas above, and the ground walking is perfectly smooth. You can check the code here.

---
Tags: c#, xna-4.0, collision-resolution
---


# Question
Title: How to change mobile device screen size in Unity for testing?
For an experiment I need to be able to dynamically adjust the screen size of my device. I'm using a Nexus 5 (5") and want to fake the screensize to 2", 3", 4",.. See images:

Is this possible using Unity? I'm aware that I can easily place some planes right in front of my camera, but I'm looking for a proper solution.

# Answer
> 0 votes
You should set the camera background color to black and make your game play in the specified area and then programmatically change the settings of camera like size etc.
You can find more information on how to play with camera here: http://docs.unity3d.com/ScriptReference/Camera.html

# Answer
> 4 votes
In the editor's Game view, you can set the size that you'll see when you hit Play. Across the top of that view are buttons for screen resolution; the far left side has setting for screen size, and the right side has Maximize on Play.

---
Tags: unity, viewport
---


# Question
Title: Unity3D - Cancel a build process (Windows, Unity 5)
I accidently pressed build for iOS and just realized that it might take a few hours to build the project. I tried to kill the unity process in the task manager, but on next start up unity instantly starts to build it again. Is there any option to cancel the build?

# Answer
> 1 votes
There is a cross button right next to build loading bar.

---
Tags: unity, ios, windows
---


title: Projectile Shoot three at a time

text:
# Question
Title: Projectile Shoot three at a time
In my game there is a bird flying and on touch it throws different artifacts projectile downwards. And these artifacts should hit the containers moving right to left on the screen. Now if user keeps on tapping rapidly it make a line of artifacts and it didn't miss a single container. So what I want to do is to restrict user to throw 3 artifacts at a time and when one of them got destroyed it'll make room for one more. Here is how I'm doing it:
In my `player.cs` I'm using a `static` `int` named `inventory` and then in `Update()` method I've the code where it increment the inventory.

```
if (Input.GetTouch(i).phase == TouchPhase.Began){
                OnShoot ();
                inventory++;
                Debug.Log ("Inventory: " + inventory);
            }

```

and in `OnShoot()` I'm checking `if (inventory < 4)` then `Instantiate` otherwise `if (inventory > 4)` set `inventory = 0;`.
Now in the `artifacts.cs` `if` it hit the container and get `destroyed` or got `destroyed` going out of the bound missing the container it should `Player.inventory--;`
This code works fine but if the user speed of tapping is more then it again started throwing like in a line form as described above.

# Answer
First of all, you should stop incrementing `inventory`, if you don't spawn more projectiles.

Example:

```
if (Input.GetTouch(i).phase == TouchPhase.Began){
    if(inventory < 3){ // spawn 3 at max
        OnShoot ();
        inventory++;
    }
}

```

Then decrease `inventory` whenever a projectile gets destroyed. Eg.

```
void OnTriggerEnter2D(Collider2D other) {
    if(Player.inventory > 0){
        Player.inventory--;
    }
}

```

Your `OnShoot` should no longer perform any checks against `inventory`, but just spawn a projectile instead...
> 0 votes

---
Tags: c#, unity, projection, touch
---


title: How to attach 2D object to a rope?

text:
# Question
Title: How to attach 2D object to a rope?
I was wondering, how I can attach a game object (player) to another object (a rope) when both came in contact in Unity. I think it should be done with a OnTriggerEnter2D, but doesn't know how I should implement this in code.

*UPDATE* After receiving a answer from @Timelord64, I tried to get it work. When the player came in contact with the rope, the trigger will be called and the code will does his job. But the problem now is, that the player will not be connected to the rope at the position he is jumping. The only thing it does now, is set the Player gameObject as a child of the rope. When the player gets in contact with the rope and after that the player will be in idle, you will see the player move a little bit to left and right, the same direction as the rope (rope has a hinge joint 2D component).

My question for know is, how I can attach the player directly to the object? Also is there a way you can jump from the rope to something else?

Code:

```
using UnityEngine;
using System.Collections;

public class Swing : MonoBehaviour {

    // trigger event within rope
    void OnTriggerEnter2D(Collider2D other) { // send in the other collider (should always work)
        if (other.gameObject.tag == "Player") { // used a tag to ID collider as player
            other.transform.SetParent(this.transform); // set gameobject as others parent
            other.gameObject.SendMessage("trigger send");
        }
    }

}

```

The code is a component from the rope game object.

# Answer
> 1 votes
First big thing to remember is that collider and trigger events should be called with the "collider other" in the brackets if we want to work with whatever caused the collision or trigger.

```
// trigger event within rope
OnTriggerEnter2D(Collider2D other) // send in the other collider (should always work)
{
    if(other.tag = "tagUsedToIdentifyRope") // used a tag to ID collider as player
    {
        other.Transform.SetParent(this.transform); // set gameobject as others parent
    }
}

```

Always good to check the tag. Use a system that makes it easy to tell between what we should be allowing to interact, and what shouldn't.

From there, we reference the transform of the "other collider", and set its parent to the ropes transform.

I have just used this system to randomly generate weapon pieces onto a main body, which in itself can access all the parts attached to it, so I hope this has helped. You may have to customize it to your suited needs.

For example, you will want to move the player transform to exactly where the player will be attaching to the rope, so it looks like they are actually swinging. My system works for a weapon base, attaching a barrel, scope, silencer and magazine, but it works best because all the parts move together as a whole from there on.

An easy way to get this working for player swinging on rope is to have a second gameobject placed right at the end of the rope, where the player is intending to grab. Use something like

```
GameObject anchor; // pivot point game object

```

to store an anchor point on the rope, and

```
other.Transform.SetParent(anchor.transform); // set anchor others parent

```

to set the anchor transform. Hope this helps

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


# Question
Title: xna - Render background and multiple sprites to a single texture
I currently creating a game and I am trying to render my background and a sprite to a texture.

Currently I have the background being rendered to a texture. But I am needing to render both my background and another sprite to a single texture. Thanks in advance.

```
    public class Game1 : Microsoft.Xna.Framework.Game
{
    GraphicsDeviceManager graphics;
    SpriteBatch spriteBatch;

    Effect blur;
    Texture2D background;
    Texture2D bubble;
    Rectangle bubbleRectangle;
    RenderTarget2D target;
    private Effect blurMapEffect;

    Texture2D attack;
    Rectangle attackRec;

    public Game1()
    {
        graphics = new GraphicsDeviceManager(this);
        //{
        // graphics.PreferredDepthStencilFormat = DepthFormat.Depth24Stencil8;
        // };
        Content.RootDirectory = "Content";
    }

    /// <summary>
    /// Allows the game to perform any initialization it needs to before starting to run.
    /// This is where it can query for any required services and load any non-graphic
    /// related content.  Calling base.Initialize will enumerate through any components
    /// and initialize them as well.
    /// </summary>
    protected override void Initialize()
    {
        // TODO: Add your initialization logic here

        base.Initialize();
    }

    /// <summary>
    /// LoadContent will be called once per game and is the place to load
    /// all of your content.
    /// </summary>
    protected override void LoadContent()
    {
        // Create a new SpriteBatch, which can be used to draw textures.
        // target = new RenderTarget2D(GraphicsDevice, this.GraphicsDevice.Viewport.Width, this.GraphicsDevice.Viewport.Height);
        blurMapEffect = Content.Load<Effect>("blurMapEffect");
        blurMapEffect.Parameters["BlurPower"].SetValue(0.55f);
        blur = Content.Load<Effect>("blur");

        spriteBatch = new SpriteBatch(GraphicsDevice);

        background = Content.Load<Texture2D>("background");

        attack = Content.Load<Texture2D>("attack1");
        attackRec = new Rectangle(50, 100, attack.Width, attack.Height);

        bubble = Content.Load<Texture2D>("Bubble - Blue13");
        bubbleRectangle = new Rectangle(250, 250, bubble.Width, bubble.Height);

        target = new RenderTarget2D(GraphicsDevice, GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height);
    }

    /// <summary>
    /// UnloadContent will be called once per game and is the place to unload
    /// all content.
    /// </summary>
    protected override void UnloadContent()
    {
    }

    /// <summary>
    /// Allows the game to run logic such as updating the world,
    /// checking for collisions, gathering input, and playing audio.
    /// </summary>
    /// <param name="gameTime">Provides a snapshot of timing values.</param>
    protected override void Update(GameTime gameTime)
    {
        // Allows the game to exit
        if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
            this.Exit();

        if (Keyboard.GetState().IsKeyDown(Keys.Left))
            bubbleRectangle.X--;
        if (Keyboard.GetState().IsKeyDown(Keys.Right))
            bubbleRectangle.X++;
        if (Keyboard.GetState().IsKeyDown(Keys.Up))
            bubbleRectangle.Y--;
        if (Keyboard.GetState().IsKeyDown(Keys.Down))
            bubbleRectangle.Y++;

        base.Update(gameTime);
    }

    /// <summary>
    /// This is called when the game should draw itself.
    /// </summary>
    /// <param name="gameTime">Provides a snapshot of timing values.</param>
    protected override void Draw(GameTime gameTime)
    {
        GraphicsDevice.SetRenderTarget(target);
        GraphicsDevice.Clear(Color.Transparent);

        spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, null, null, null, blurMapEffect);
        spriteBatch.Draw(bubble, bubbleRectangle, Color.White);
        spriteBatch.End();

        GraphicsDevice.SetRenderTarget(null);
        GraphicsDevice.Clear(Color.Transparent);

        blur.Parameters["BlurMapTexture"].SetValue(target);
        spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, null, null, null, blur);
        spriteBatch.Draw(background, new Rectangle(0, 0, this.GraphicsDevice.Viewport.Width, this.GraphicsDevice.Viewport.Height), Color.White);
        spriteBatch.Draw(attack, attackRec, Color.White);
        spriteBatch.End();

        spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend);
        spriteBatch.Draw(bubble, bubbleRectangle, Color.White);
        spriteBatch.End();

        base.Draw(gameTime);
    }

```

# Answer
Simply draw your sprite before the call to `GraphicsDevice.SetRenderTarget(null);`
> 1 votes

---
Tags: xna, c#, xna-4.0, rendering
---


# Question
Title: How can I derive hierarchical draw ordering for entities in an entity system?
How do you implement hierarchical render order in an entity system?

For example: two player entities each carry a gun entity. If you set the player entities to zindex = 0 and the gun entities to zindex = 1, then player 1 might render behind player 2 but his gun will render in front of player two.

I'm migrating a game from a scene-graph system where the order is self-evident from the parent/child relationship. The only way I can see of achieving the above is to simulate that parent/child relationship by giving every entity its own reserved range of z-indexes like so. player1 z=0 player1-gun z=1 ... player2 z=5 player2-gun z=6

This would require some kind of auto assignment system. Is this how it's done or is there some pattern I'm missing?

# Answer
> 1 votes
There isn't one way that "it's done," really; it sounds like you may be coupling you renderer and your entity system too tightly together (generally they don't really need to know about eachother). However, it seems like a straightforward solution to your problem is to introduce hierarchy to the appropriate components.

Presumably the gun entity has either a transform component or a visualization component with transform information. Or perhaps tranformation is considered important enough to be a first-class property of an entity in your system.

In any case, add the notion of a parent reference to whichever aspect of your system has the transformation information. They you can recover the Z order information you need from that hierarchical structure, just like you would in a graph system:

Order your top level components by whatever predicate you consider appropriate to break Z-order ties (such as by their screen height). Assign the first component the next available Z index, and then assign successive Z indices to its children before moving on to the next top-level component.

This will not solve every possible problem, but it will put you back into the same problem space as a graph-based solution.

---
Tags: rendering, entity
---


title: How to create a ladder script in Unity

text:
# Question
Title: How to create a ladder script in Unity
I tried to create a climb script and found some similar code. I would like to climb with my player on a ladder. I came up with the following:

bool canClimb = false; float speed = 1;

```
GameObject player;                          // Reference to the player GameObject.

void Awake () {
    // Setting up the references.
    player = GameObject.FindGameObjectWithTag ("Player");
}

void OnTriggerEnter2D(Collider2D other) { // send in the other collider (should always work)

    if (other.gameObject.tag == "Player") { // used a tag to ID collider as player
        canClimb = true;
        player.rigidbody.useGravity = false;

    }
}

void OnTriggerExit2D(Collider2D other) { // send in the other collider (should always work)

    if(other.gameObject == "Player"){
        canClimb = false;
        other.attachedRigidbody.useGravity = true;

    }
}

void Update () {

    if(canClimb == true){

        if(Input.GetKey(KeyCode.Z)){

            player.transform.Translate (Vector3(0,1,0) * Time.deltaTime*speed);

        }
        if(Input.GetKey(KeyCode.S)){
            player.transform.Translate (Vector3(0,-1,0) * Time.deltaTime*speed);

        }
    }
}

```

The above code will give a red mark on the `useGravity` in the line of `player.rigidbody.useGravity`. I doesn't know how to fix this.

# Answer
Unity 5 just came out, and they changed the API for a call like `object.rigidbody`

Specifically, every component shortcut other than `object.transform` has been removed, since the Transform component is the only one that all objects have. All the other shortcuts only applied a fraction of the time.

Now you need to access the Rigidbody component using GetComponent(), like so (C# code):

```
Rigidbody body = player.GetComponent<Rigidbody>();
body.useGravity etc.

```
> 3 votes

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


# Question
Title: How could I implement 3D player collision with rotation in LWJGL?
I have a problem with my current collision implementation.

Currently for player collision, I just use an AABB where I check if another AABB is in the way of the player, as shown in this code. (The code below is a sample of checking for collisions in the Z axis)

```
for (int z = (int) (this.position.getZ()); z > this.position.getZ() - moveSpeed - boundingBoxDepth; z--)
{
    // The maximum Z you can get.
    int maxZ = (int) (this.position.getZ() - moveSpeed - boundingBoxDepth) + 1;
    AxisAlignedBoundingBox aabb = WarmupWeekend.getInstance().currentLevel.getAxisAlignedBoundingBoxAt(new Vector3f(this.position.getX(), this.position.getY(), z));
    AxisAlignedBoundingBox potentialCameraBB = new AxisAlignedBoundingBox(this, "collider", new Vector3f(this.position.getX(), this.position.getY(), z), boundingBoxWidth, boundingBoxHeight, boundingBoxDepth);
    if (aabb != null)
    {
        if (potentialCameraBB.colliding(aabb) && aabb.COLLIDER_TYPE.equalsIgnoreCase("collider"))
        {
            break;
        }
        else if (!potentialCameraBB.colliding(aabb) && z == maxZ)
        {
            if (this.grounded)
            {
                playFootstep();
            }
            this.position.z -= moveSpeed;
            break;
        }
    }
    else if (z == maxZ)
    {
        if (this.grounded)
        {
            playFootstep();
        }
        this.position.z -= moveSpeed;
        break;
    }
}

```

Now, when I tried to implement rotation to this method, everything broke. I'm wondering how I could implement rotation to this block (and as all other checks in each axis are the same) and others. Thanks in advance.

# Answer
> 1 votes
The way I solved this a long time back (I forgot about this question entirely until now), was that I just basically checked if the boxes intersected, because the rotation was just for a first person camera. So it only would have effected the viewport and movement code, the actual collision was just checking for an intersection. Basically, it was just me over thinking things. If you actually **NEED** rotation in collisions, you might be able to resize the box every time it rotates on the X axis.

For Example

```
public void rotateX()
{
    rotation.x += Mouse.getDX();
    collider.size.x = baseColliderSizeX + (float) Math.toRadians(rotation.x);
}

```

Though I have no clue if that really works.

Also, the way I was trying to do it, was by doing continuous collision detection, which would check every possible position for a collision. But that isn't usually needed, as you can just bump the player/entity back to a point where they aren't going through the old object. If you really need continuous collision detection, I would really have not a clue what to do, because it would have to be based off of the players current direction.

# Answer
> 1 votes
AABBs (Axis-Aligned Bounding Boxes) are (as the name suggests) without rotation. What you need are OBBs (Oriented Bounding Boxes), there are many tutorials on the web but collisions in 3D space are always either not good enough ore a pain in the back.

Wikipedia provides a nice set of formulas ;) http://en.wikipedia.org/wiki/Bounding\_volume#Basic\_intersection\_checks

---
Tags: java, collision-detection, lwjgl
---


# Question
Title: What is the highest quality way to render warped text on Windows?
I need to render highly readable text, on par with DirectWrite+Cleartype+Truetype. The Cleartype system uses sub-pixel anti-aliasing. DirectWrite takes things a step further and moves letters around slightly (sub-pixel positioning, pixel snapping, etc.) to maximize readability and minimize distortions. This was important enough that every major web browser uses DirectWrite on Windows.

The obvious plan (with major shortcomings) is to render DirectWrite to a texture with cleartype disabled (because sub-pixel AA doesn't lend itself to transforms) and pixel snapping disabled (because that pixel "grid" is meaningless after transformation.) Unfortunately the text will look worse than it could if glyphs are enlarged or shrunk, and of course the lack of pixel snapping will hurt readability.

Ignoring performance, is there a higher quality way to draw warped text in Windows?

Edit: removed comment about disabling AA (DWRITE\_RENDERING\_MODE\_ALIASED).

# Answer
DirectWrite appears to support drawing glyphs directly

> Provides a low-level glyph rendering API for those who employ proprietary text layout and Unicode-to-glyph processing

Using this feature you would be able to load the glyphs from a font using the windows GDI function GetGlyphOutline, morph the quadratic bezier curve for your text and finally render these directly without missing any of the clear-type benefits.

You could also use a utility like Fontforge to convert your font into a simpler format like SVG.
> 1 votes

---
Tags: windows, text, antialiasing
---


# Question
Title: Endless level support in modern engines?
Do any of the "next gen" engines support endless 3d levels?

The general idea for my game will require the ability to stream a level seamlessly (no loading screens), similar to games like for example Minecraft, where land is dynamically created based on where the player is going to.

I could not find any information about whether or not engines like Unity 5, Unreal 4 or Cryengine 3 support this and would love to get some insight on this.

# Answer
> 1 votes
If Minecraft had the same capability, then Unity 5, Unreal 4, and Cryengine 3 have the same capabilities. You just have to learn how to make it in those engines. Just look up something like "voxel level unreal 4", "voxel level unity", or "voxel level cryengine 3". There is bound to be things written about it.

# Answer
> 1 votes
It is not the "engines". You can do it with anything, even if you program your game hard-code. First you need to learn "Procedurally-generated game content" and it isn't a new thing. Games before Elder Scrolls Arena games did that.

You can surely do that on demand (as the player explorer the level) but it will take a huge badass machine to not bottleneck the game as the maps get bigger.

As far as I know, Minecraft first create a huge map, them as the player explorer the limits of it, it creates chunks of the map(huge ones), and it's theoretically infinite if there is no hardware limitation. The consoles are caped up, and the PC gets buggier and buggier after you play it a while.

---
Tags: unity, unreal-4, cryengine
---


# Question
Title: Should I use octree or quadtree for my spacial data structures?
I would like to know the advantages and disadvantages of using octree or quadtree for spacial data structures? In a 3d gaming setting would you ever need more than 4 children nodes? Does it take longer to traverse through oct tree than quad tree? Is one of the two by all means faster than the other or is it a trade off sort of thing?

# Answer
I'm not really good at fabricating N- statements, but the minimum search times for an object at child\[0\] of every child\[0\] should be close to the same +- a dimension. If the object falls at child\[4\] of every child\[4\] the calculation for the octtree could be as much as N^2(?) longer.

Since you don't specify how/why the tree is being used, it's hard to give a definitive answer.
The advantage is based on your objects' perspective/degrees-of-freedom.

Here are two examples:

**Quad:**
If your world is a quad-based terrain-style game, and your objects are all earth-bound, there's no reason to add a third dimension to your search. That is to say that your objects all traverse the terrain by moving from (X, Z) to (X1, Z1), interpolating their Y-values from an arbitrary second source (height map). The Y value also provides hints to the objects about what is in-between them (line-of-sight/collision ray-casting). In all cases, down is down. From your objects' perspective, other objects may be higher or lower, but always appear in one of 4 quadrants.

An anti-example of this would be ray-casting the mouse cursor with an octtree in SimCity. Do you care if you are hovering the top-half of the building vs. the bottom half? You wouldn't save any time by sorting the top half of every sky-scraper into a separate search dimension. For SimCity, we need to know if any part of a building is hovered, or not. In SimCity, each building occupies an (X, Z) and has a variable height.

**Oct:**
If many of your objects can move in 3D, an octtree may make more sense. In a space simulator, objects could be out-of-range, or out-of-scope, in more ways (above/below). Culling things behind you is still necessary, but now your object's are able to orient arbitrarily; "down" is no longer down, "forward" is now down, and "down" is now backward. From your objects' perspective, other objects may appear in any one of the 8 quadrants.

Using C&C, a quad-based, terrain-style game with flying units ("down" is always down, even for aircraft), as an example, where all flying units still occupy an (X, Z) but maintain a height of (heightmap + 20), neglecting combat animations. While ray-casting through the extra dimension, even on a quad-based game, the node directly above your test-object contains only flying units. Air-to-air craft don't have to test against units in the same node as the terrain; in other words, when an air-to-air jet is testing for objects in front of it, any node returned that contains the terrain, can be skipped. Likewise, a bomber aircraft that can only target ground-based objects, can skip all nodes that do not contain the terrain. Surface-to-air missile launchers wouldn't need to test terrain nodes either.

A similar anti-example would be jet aircraft in Battlefield-style games. You can move up and down, but you must do so by only flying "forward". A jet in Battlefield cannot fly or shoot in any direction other than forward, so if you used an octtree while flying, you would always skip 4 of the 8 quadrants. Another jet shooting you from behind requires the same (only) 4 quadrants that you are using. A helicopter or VTOL, however, can move straight "down" and, if equipped with turrets, shoot in semi-vehicle-independent directions. The turrets can only see and shoot "forward".

**Round-up:**
Hopefully this highlights the differences in needs/advantages. Don't get locked into one or the other, use them when applicable.

One more edit:
Back to the Battlefield example, if you maintain separate air-only and ground-only octrees that are identical in every other way, neither the overall object count nor the overall dimension count increase, so overhead does not increase (neglecting the increased memory footprint). So, for a vehicle that can shoot "bullets" (at land and air vehicles) and can also shoot lock-on style anti-air missiles at only air-craft, the difference, for targeting purposes, is a matter of which tree(s) to test, not how long it will take (the node coordinates/dimensions are identical). A bullet from a jet can skip ground-nodes until the bullet enters a node that contains the terrain. A ground-node returned from the air-tree, could link directly to the corresponding node in the ground-tree, allowing the bullet to be "handed off" to the ground tree. Separating the objects into different, nearly-identical trees ahead of time may help your performance if your game has to frequently distinguish between the two. Indexing between two 3D trees is a 4D tree. (X, Y, Z, WhichTree)
> 6 votes

---
Tags: c++, octree, quadtree, tree
---


title: Minesweeper number placement

text:
# Question
Title: Minesweeper number placement
My professor gave us a project: make a minesweeper clone. However, he said that he will give bonus points for the 3 fastest algorithms for board generation. I'm currently doing the algorithm that places the numbers. How should I do it? I thought of doing something like

```
For every mine, increment the value of adjacent cells

```

or

```
For all cells, count the number of adjacent mines

```

Which is faster? Or could you recommend a faster method? Thanks

# Answer
> 2 votes
I think the fastest method will be by not generating the numbers at board generation (I know it's almost cheating). It's most likely fastest to only generate the number when the player clicks on a square rather then during board generation.

Secondly consider how you are going to generate mines, is each place on the board going to pass a check (loop over every square)? Or are you just going to generate random positions for each mine? How do you deal with someone entering that every single tile should be a mine? That's going to slow you down with the second type but the first one can be needlessly slow as well.

# Answer
> 1 votes
* Create two dimensional array
* Randomly place mines and place mine location to list
* Foreach mines and add +1 to adjacent cells

Mine creation

```
int x = random.next(min, max);
int y = random.next(min, max);
mineList.add(new XYClass(x,y))

```

Number calculation

```
Foreach(XYClass xy : mineList)
  addPlusOneToAdjacentCells(xy);

```

This way, you don't even have to loop through all the cells, just those that are important.

---
Tags: java, algorithm, minesweeper
---


# Question
Title: Why does glBindVertexArray sometimes fail (but mostly not)?
Quick outline:

* Test program that loads and displays big (3k x 4k) 16bit gray scale images (ca. 32MB).
* Using modern OpenGL (eg. 3.3 or so) with shaders VBOs VAOs etc.
* Running on Windows with OpenTK (WinForms inside WPF) - C#
* developing on ATI FireGL and Nvidia Quadro FX
* using MipMapping

My test program is actually working quite well (seems like I am doing not so much wrong). I've written a load test to find threading errors and resource leaks. So ater a while of loading and closing viewers and their images, sporadically `glBindVertexArray()` fails in one viewer instance and works in another viewer instance. Speak: Different OpenGL contexts, same graphics card, same process, same thread.

Visually I see my OpenGL HWND filled with a red cross and a red frame.

The failing viewers become more over time. Never the less some still keep working.

* My background loading of textures is currently disabled. So threading issues should be out of scope.
* I do 'MakeCurrent()' the context before I draw.
* As of WPF law, all my Viewers work in the same UI thread. (that's what I think)

**So what is wrong?**

It seems little like a resource problem... because the problems become more over runtime. But what could be the reasons why `glBindVertexArray()` fails. My workflow should be most of the time OK. So are there any data operations I have to `glFlush()` before I call?

Actually I tried to add a `glFlush()` before it but it did not resolve it.

My Program flow is a little convoluted by OO patterns but essentially boils down to that:

Creation of VAO:

```
int a =GL.GenVertexArray();
GL.BindVertexArray(a);
int b1= GL.GenBuffer();
GL.BindBuffer(BufferTarget.ArrayBuffer, b1);
GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)(BufferSize), data, BufferUsageHint.StaticDraw);

int b2= GL.GenBuffer();
GL.BindBuffer(BufferTarget.ArrayBuffer, b2);
GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)(BufferSize), data, BufferUsageHint.StaticDraw);
//->vertex data  (OO implication of multi calls)
GL.BindBuffer(BufferTarget.ArrayBuffer, b1);
GL.BindBuffer(BufferTarget.ArrayBuffer, b1);
GL.EnableVertexAttribArray(0);
//-> texcoords
GL.VertexAttribPointer(0, elements, attrType, normalized, stride, offset);
GL.BindBuffer(BufferTarget.ArrayBuffer, b2);
GL.BindBuffer(BufferTarget.ArrayBuffer, b2);
GL.EnableVertexAttribArray(0);
GL.VertexAttribPointer(0, elements, attrType, normalized, stride, offset);

```

consider *generic valid* parameters.

The Draw happens about like that sequence of calls (which I hopefully reflect correctly)

```
MakeCurrent();
GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);
GL.UseProgram(prg);

// Set texture uniform
GL.Uniform1(Handle);
GL.ActiveTexture(unitnumber);
GL.BindTexture(Texture2D, Handle);

//... set some more Uniforms...
GL.GetError(); // returns NoError
// then it is over
GL.BindVertexArray(a);  // <<-- this is where it crashes sometimes!!

// this is my LUT-data but does not matter after the failing call
GL.ActiveTexture(1);
GL.BindTexture(TexTarget.TextureArray, Handle);

GL.DrawArrays(PrimitiveType.TRIANGLES, first, count);

```

# Answer
Well.. sometimes you have to formulate a question and stop work until you find your answer yourself.

In the evening I had some thoughts about resource management. We're talking about .Net ... thus a GC is involved. What if the finalizer thread comes along at a wrong time or state. Well - that would be actually a double fault. Not more right therefore, though. We're talking about unmanaged (because external) resources that need management with `IDisposable`. This is also what I implemented. Unless I call `Dispose()` on removed viewers I'll run quickly in resource problems on the graphics card. So I do it and nothing seems wrong about it.

The real cause lies in my `Dispose()`-Implementation, though. And it only appears, if you use multiple viewers (thus multiple OpenGL contexts) at once. Accoring to the docs of OpenTK and it's `GLControl`, one has to call `MakeCurrent()` every so often as one uses GL-functions to work on the right context. This applies to `Dispose()` as well.

So what actually happened was this:

My VertexArrayObject was actually disposed (`GL.DeleteVertexArray(Handle);` )by another viewer that incidentally hat the same "name" in it's OpenGL-context. The *problem* is, my OpenGL-implementation has "name-tables" per context and so every VertexArrayObject allocated in a new viewer gets a name like 1,2,3,4 and collisions are *programmed*.

So changing my Dispose to something like that solved it:

```
    protected override void Dispose(bool disposeCall)
    {
        if (disposeCall)
        {
            this.MakeCurrent();
            _overlay.Dispose();
            _drawing.Dispose();
            _shaderProgram.Dispose();
            _texture.TryDispose();
            _lutTexBuffer.Dispose();
        }
        base.Dispose(disposeCall);
    }

```

Now I make sure to only delete my own resources to (colliding) names
> 1 votes

---
Tags: c#, opengl, windows, nvidia, vao
---


# Question
Title: Use pathfinding algorithm in a navmesh with several endpoints
I need to implement a pathfinding algorithm in a navmesh with several endpoints, and I would like to find the path to the closest endpoint. I suppose that Dijkstra algorithm is the best solution for that but it needs some adaptation. Is someone could help me please ?

# Answer
> 1 votes
It's not a massive change, just instead of `current_node == destination` it will be `destination_set.contains(current_node)`.

Otherwise you can reverse the search, go from the endpoints to the start.

That way you can use A\* (given a proper heuristic). You just need to start with all endpoints in the starting set.

---
Tags: path-finding
---


# Question
Title: How did Blizzard implement replay like in Warcraft 3 with not consistent data(attack damage)?
Units in wc3 has range of attack damage and it isn't consistent most of the time e.g critical hit and so on. Yet, they managed to make a replay that could even reconstruct bugs scene. I am just curious how they do it. It could be useful for fighting games or perhaps to easily submit evidence of recurring bugs. The best part is it's not even a big of a file and even could be used on a customize games. Come back to the title, how did they do it?

# Answer
They would include that damage (or the data needed to get to the damage value like the RNG state) in the replay information. Each attack is only a numerical value of the damage value, the id of the attacker and the id of the victim. That is 3 values with a limitation on number of units those IDs could be a single byte each.

Crucial information is often RNG seeds, player input and (most importantly) fully deterministic implementation. Anything not deterministic would otherwise need to be included in the replay stream. A perfect implementation would use the "replay" engine for actual real-time play. Where input is nothing but the RNG seed and player input as it comes in.

For scrubbing efficiency and a failsafe you can include full board snapshots, these would contain the location of all units and their health, position of the buildings and unit building progress, etc.
> 2 votes

# Answer
I found few documents, that describe the replay file, so from those you can figure out what kind of model they are using for commands etc.

They have to use some kind of command pattern. That means, that each command issued is capsuled in instance of command (or ICommand ). Thus, if everything in the game happens with those commands, you could just push them to the engine and see previous actions replayed ( ofcourse, initial position of everything has to be the same ).

This method is quite like the one that Half life uses for HLTV, it's simple, compact and efficient way to accomplish the streaming, replaying and undoing actions.

I found these documents, that you might be interested:
> 0 votes

---
Tags: game-design, software-engineering
---


title: Voice over programming language

text:
# Question
Title: Voice over programming language
I am looking for a voice over programming language. Instead of using people for voice over, I want to use a computer, which does voice over for different people. Is this type of thing possible, or is there any way that I can achieve this?

# Answer
> 2 votes
Yes it is possible. There are a bunch of speech synthesisers. And like Philipp said, many OSs provide such APIs.

For example, the **Speech Application Programming Interface** or **SAPI** is an API developed by **Microsoft** to allow the use of both **speech synthesis** and **speech recognition** within Windows applications.

But keep in mind that these synthesisers **DO NOT PRODUCE REALISTIC SOUNDS**.

This is a good question, and a good idea in case you are trying to enhance interaction. But it would only be used for a robot or an emotionaly dead character, (where you might need an intonation thats not normal, and possibly, difficult for real voice acting).

These might be useful: 1. Wikipedia, 2. SAPI docs, 3. Using SAPI in C# and VB.NET, 4. SO.

Hope this helped =)

# Answer
> 0 votes
It sounds like you're looking for a "Text to Speech" API or SDK that you can use with the programming language, framework and/or engine you'll be using for your game. Take a look at http://www.ispeech.org/ They provide APIs and SDKs for both text to speech and voice recognition. I saw that their mobile API is free, so you could use that if you wanted to make a game for Android or iOS. Since you didn't specify the platform you want to develop for, I figured I'd mention it.

# Answer
> 0 votes
Many operating systems (like Windows or MacOS) already have a text-to-speech API included. Search the respective documentations for more information. There are also several 3rd party speech synthesis technologies available as an alternative (some of them can even sing).

But keep in mind that the quality of todays text-to-speech software is not yet an appropriate replacement for real voice actors. It can create comprehensible voice output, but it can not convey emotions as well as a human actor can.

---
Tags: voice
---


# Question
Title: How to achieve smooth sprite movement with a scaled up canvas?
I'm developing a simple 2d platformer using haxe & openfl (currently targeting flash). To achieve the old school pixelation effect I draw 16x16 sprites over a 4x scaled up canvas. With this approach character movement is very jerky since it seems to consist of a sequence of 4px jumps.

So my question is: *how to be smooth & old school at the same time*? Thank you for your time.

# Answer
> 1 votes
From what you're describing, you seem to be scaling a translation as well as your sprites. You should scale your sprites when you load them, then translate them around. Or, if you apply all your transformations at the same time, you must make sure that the translation is applied before the scaling.

Another option for you would be to scale them offline and load these instead. This would be at the loss of disk space.

---
Tags: flash, haxe
---


title: Pack four alpha maps into one

text:
# Question
Title: Pack four alpha maps into one
I have read an article about texture splatting that says:

> Because the alphamap only has to be in a single channel of a texture, we can pack up to four alphamaps into a single texture – one in red, one in green, one in blue, and one in alpha.

But it does not mention a way to this. Can anyone tell me or point me to an article on how to do this? I've been googling it the whole afternoon but can't find any. Or maybe I just don't know the correct terms to search. :?

Thanks.

# Answer
You basically put a one alpha value in each channel.

For example you have `Alpha0 = 0.5`, `Alpha1 = 0.2`, `Alpha2 = 0.7`, `Alpha3 = 1.0`.

The "packed" texture would be `R = 0.5`, `G = 0.2`, `B = 0.7`, `A = 1.0`.
> 2 votes

---
Tags: alpha-blending, alpha
---


# Question
Title: Unity - C# - Overlapping Rectangles not separating
I am Instantiating a lot of Rectangles of different sizes (ranging from 3 to 18 units) and they all have attached this script, which should cycle through all the GameObject List which contains them.

It should automatically avoid any overlap, but unfortunately sometimes it gets stuck with some rectangles that remain moving and all the others stop. When this occurs, my program can't continue and blocks in an infinite loop.

Here's the script:

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

public class Cell : MonoBehaviour {

    private float squareDistance;

    float xShift = 0;
    float yShift = 0;

    //float globalStrength = 0;

    public bool hasStopped = false;

    private Vector2 oldPos = new Vector2();
    //private Vector2 oldPos2 = new Vector2();

    public Vector3 direction;

    // Use this for initialization
    void Start () {

    }

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

        if(Placer.work) {
            float strength;

            List<GameObject> cells = Placer.cells;

            for (int i=0; i < cells.Count; i++) {
                if(cells[i] != this.gameObject) {
                    if(isOverlapping(cells[i])) {

                        direction = transform.position - cells[i].transform.position;

                        strength = 1; //+ globalStrength;

                        /*if(globalStrength > 0) {
                            globalStrength = 0;
                        }*/

                        direction.Normalize();

                        xShift += strength * direction.x;
                        yShift += strength * direction.y;

                    }
                }
            }

            transform.position = new Vector3(Mathf.Round(transform.position.x + xShift), Mathf.Round(transform.position.y + yShift), transform.position.z);

            xShift = 0;
            yShift = 0;

            if (transform.position.x == oldPos.x && transform.position.y == oldPos.y) {
                hasStopped = true;
            } else {
                hasStopped = false;
            }
            //oldPos2 = oldPos;

            /*if(oldPos2.x == transform.position.x && oldPos2.y == transform.position.y) {
                globalStrength = 2;
                Debug.Log ("si2");
            }*/

            oldPos = new Vector2 (transform.position.x, transform.position.y);

            /*if(oldPos2.x == oldPos.x && oldPos2.y == oldPos.y) {
                globalStrength = 3;
                Debug.Log ("Si");
            }*/
        }
    }

    private bool isOverlapping(GameObject obj) {
        Vector2 size = new Vector2 (GetComponent<Renderer> ().bounds.size.x, GetComponent<Renderer> ().bounds.size.y);

        if (pointInside (obj, new Vector2 (transform.position.x + 1 - size.x / 2, transform.position.y + 1 - size.y / 2))) {
            return true;
        }

        if (pointInside (obj, new Vector2 (transform.position.x - 1 + size.x / 2, transform.position.y + 1 - size.y / 2))) {
            return true;
        }

        if (pointInside (obj, new Vector2 (transform.position.x + 1 - size.x / 2, transform.position.y - 1 + size.y / 2))) {
            return true;
        }

        if (pointInside (obj, new Vector2 (transform.position.x - 1 + size.x / 2, transform.position.y - 1 + size.y / 2))) {
            return true;
        }

        return false;

    }

    /**
     * With this method we verify if a Vector2 is inside a GameObject.
    */
    private bool pointInside(GameObject obj, Vector2 point) {

        Vector2 objSize = new Vector2 (obj.GetComponent<Renderer> ().bounds.size.x, obj.GetComponent<Renderer> ().bounds.size.y);
        if ((point.x >= (obj.transform.position.x - objSize.x / 2)) &&
            (point.x <= (obj.transform.position.x + objSize.x / 2)) &&
            (point.y >= (obj.transform.position.y - objSize.y / 2)) &&
            (point.y <= (obj.transform.position.y + objSize.y / 2))) {

            return true;
        }

        return false;
    }

    public bool getHasStopped() {
        return hasStopped;
    }

}

```

I have tried with some workarounds, which you can see commented in the code; none of them fixes completely the problem.

What can I do to fix it?

# Answer
> 3 votes
You seem to have rectangles that are sandwiched:

1. You have rectangles A, B and C
2. A directly above and is overlapping B, which is above and overlapping C.
3. The update for A is done, pushes it a bit up.
4. The update for B is done, pushes it a bit up because of C, and a bit down because of A.
5. B `hasStopped` because it did not move because your \[x|y\]Shift is cumulative for all of the neighbours.
6. Deadlock because this is the situation of a chain in your rectangles.

You might want to try and make sure you 'de-overlap' them one by one right when you create them.

Or you could try and push them only further away from the centre, never closer to it.

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


title: Change Tag of Instantiated Clone

text:
# Question
Title: Change Tag of Instantiated Clone
In my game there is a bird flying up and a stream of containers (baskets) is moving from right to left of the screen in the bottom. Baskets are being `Instantiated` on right and get destroyed when they reach the left side of the screen.
On The left there is an `EmptyObject` called Destroyer and anything that `collides` with it get destroyed. I'm not using out of bounds for the objects to get destroyed instead I'm using an `EmptyObject` with collide.
And on tap the bird throws an artifact `projectile` downwards and if it collides with the Basket it changes into another sprite. This is the code for that `transform.GetComponent<SpriteRenderer> ().sprite = changedBasket;`
The problem is that user is only allowed to miss `3` baskets losing more than `3` baskets will result in Game Over. So inside my `Basket.cs` I'm checking that `if(target.gameObject.tag == "Deadly")` then count it as a chance loose. **BUT** the `changeBasket` also act as it's the same basket.
The logic that I think will work is to change the `tag` after the artifact `collides` with the basket and on that type of tagged object deadly won't work. If I'm write kindly tell me how to implement this in `c#` of-course. Please note that the object is an `Instantiated Clone`

# Answer
> 2 votes
As this rapid google search states:

```
gameObject.tag="new_tag";

```

Obviously your "new\_tag" has to exist inside the editor.

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


# Question
Title: Unity UI square that fills width OR height
I'm trying to create a board with this requirements:

* It SHALL be square.
* It SHALL fit available width OR height.
* It SHALL be centered in the canvas.
* It MAY be wrapped into as many additional intermediate canvases as needed.

I am playing with anchors but I am not finding any combination to do that. The only solution I can think is script some kind of "OnResize" of the container and set the size of the board programmatically.

This is the original layout. (1) is the BoardCanvas. (2) is the Board.

I want that if the screen becomes taller, the square grows, but still is square:

Or reduces:

But, although those previous examples are snapping to the top and bottom edges, I also want that if the vertical space becomes taller than the available width, then the square limits its size depending on the left and right borders:

**Q1:** Is there a way to do this with the anchors/pivots? It's ok for me to create intermediate canvases in between the BoardCanvas and Board itself if that works.

**Q2:** If so, where should I position the anchors? Do I need intermediate objects?

**Q3:** If not, is scripting the solution? Is there any OnResize on the canvas to handle? I can't see any resizing event in the list, but maybe I dont know where to look for it. I feel that testing it at every frame seems a bit overkill, event driven seems better.

Thanks!

# Answer
> 17 votes
Finally I found a way to do it (tested in v5.0.0), in a way that:

* Does not need code, or conditionals to check orientation.
* Does not hack with scales and neither needs a reference resolution.

In the UI video tutorials, there is a big part missing, although well documented in the text-documentation: The "auto-layouts" system.

Auto-layouts are mechanisms made of "layouts" and "layout controllers". Layout controllers are components that one can attach to the UI Game Object. Controllers can resize `Rect Transform`s intelligently.

Certain controllers may resize the object where the component is applied to, whilst other controllers may resize the children of that object.

There a few built-in controllers. One of those is the `Aspect Ratio Fitter`.

First, I select my `Board` panel and I attach a new `Aspect Ratio Fitter` component:

The `Aspect Ratio Fitter` seems to aim to "maintain" the object's wanted aspect ratio. To do so, either the object can be set to "wrap" around a child object (while maintaning the aspect ratio), or either it can be set to expand and fit its container (while maintaining the aspect ratio).

I then select `Fit In Parent` option and I specify that I want a perfect square by setting the desired aspect ratio to 1:

This yields in a very similar layout than the one I wanted, but I didn't have to tell the board its dimensions. But still, it knows it must be square, as depicted:

If I shrink vertically or expand, the square follows the parent, while maintaining the aspect ratio:

Magically, when the change is donw by reducing the width, there is no script to attach and no property to change, as the "Aspect Ratio Fitter" does that for us automagically:

Finally, as I wanted a bit of margin there, I just place a container rect transform that acts as the spacer and move the `Board` from the `BoardCanvas` into the `MarginCanvas`:

# Answer
> 3 votes
This is possible, but with probably just a small line of code or two for defining whether or not the screen is landscape or portrait and changing a couple values.

On the Canvas, you need to make the Canvas Scaler's "Ui Scale Mode" be "Scale with Screen Size", and make "Screen Match Mode" be "Match Width or Height":

Assuming the default Reference Resolution of 800x600 is used, and assuming the screen's viewport is landscape (eg `Screen.width` is greater than `Screen.height`), the Match slider needs to be set all the way towards Height as `1`.

You're then going to want an Image on the Canvas using the middle/center anchor preset. You also want the Image's Width and Height to match your Canvas Scaler's Reference Resolution's Y value.

You can then resize the camera's viewport and see that the image retains its shape while stretching its height to match the viewport's height:

---

If the screen is portrait -- and this is where you'll probably need to code to check and/or change as required -- you need to make the Scaler's Match value be `0`, and change your Image's Height and Width to match the Reference Resolution's X value. (in the pictures below, the Image's Width and Height are both `800`)

---

If you're trying to fit a smaller image inside, you can "scale" the image by adjusting its width and height against the Reference Resolution's X or Y value (depending on landscape or portrait). So for example, I made a blue square that uses half of the Reference Resolutions' X value (since the viewport is portrait), and it scales and shrinks nicely:

And further, if you wanted a checkerboard or something, each image's X and Y position and Height and Width can be based on a percentage of the Canvas Scaler's Resolution to do whatever you please:

---
Tags: unity, gui, window-management
---


title: What type of loop code on game engines?

text:
# Question
Title: What type of loop code on game engines?
Recently I worked on a game on Spritekit Engine. My question is not about spritekit, but generaly about game engines. When I write a loop code and run it (eg while i\< 100000) my CPU usage goes to 100%, but when I run the test game there is no changes specially on CPU usage ,why is this so? (We know game engines runs in a loop that includes logic and graphic commands )

# Answer
The game engines will Sleep() or do something similar like pend on an event to not consume 100% cpu. Here is a Windows specific example that runs at a fixed frequency. On Windows XP, a Sleep(1) can take up to 2ms, so the loop takes that into account. The variables uPrev, uWait, and uRem are based on an original reading of a high speed counter, to prevent drift over time. dwLateStep is a debugging aid that is incremented every time a step has taken too long.

```
typedef unsigned long long UI64;        /* unsigned 64 bit int */
#define FREQ    400                     /* frequency */
DWORD    dwLateStep;                    /* late step count */
LARGE_INTEGER liPerfFreq;               /* 64 bit frequency */
LARGE_INTEGER liPerfTemp;               /* used for query */
UI64 uFreq = FREQ;                      /* process frequency */
UI64 uOrig;                             /* original tick */
UI64 uWait;                             /* tick rate / freq */
UI64 uRem = 0;                          /* tick rate % freq */
UI64 uPrev;                             /* previous tick based on original tick */
UI64 uDelta;                            /* current tick - previous */
UI64 u2ms;                              /* 2ms of ticks */
UI64 i;

    /* ... */ /* wait for some event to start thread */
    QueryPerformanceFrequency(&liPerfFreq);
    u2ms = ((UI64)(liPerfFreq.QuadPart)+499) / ((UI64)500);

    timeBeginPeriod(1);                 /* set period to 1ms */
    Sleep(128);                         /* wait for it to stabilize */

    QueryPerformanceCounter((PLARGE_INTEGER)&liPerfTemp);
    uOrig = uPrev = liPerfTemp.QuadPart;

    for(i = 0; i < (uFreq*30); i++){
        /* update uWait and uRem based on uRem */
        uWait = ((UI64)(liPerfFreq.QuadPart) + uRem) / uFreq;
        uRem  = ((UI64)(liPerfFreq.QuadPart) + uRem) % uFreq;
        /* wait for uWait ticks */
        while(1){
            QueryPerformanceCounter((PLARGE_INTEGER)&liPerfTemp);
            uDelta = (UI64)(liPerfTemp.QuadPart - uPrev);
            if(uDelta >= uWait)
                break;
            if((uWait - uDelta) > u2ms)
                Sleep(1);
        }
        if(uDelta >= (uWait*2))
            dwLateStep += 1;
        uPrev += uWait;
        /* fixed frequency code goes here */
        /*  along with some type of break when done */
    }

    timeEndPeriod(1);                   /* restore period */

```
> 3 votes

---
Tags: game-loop, cpu
---


title: Stop Lerp at relative location?

text:
# Question
Title: Stop Lerp at relative location?
In my Unity 2D platformer, I'm trying to move the camera down a bit when the character is crouching but not moving. I've done this with the following:

```
cameraPosition = mainCamera.transform.position.y;
cameraPosition = Mathf.Lerp(cameraPosition, cameraPosition - 0.8f, 3 * Time.deltaTime);
mainCamera.transform.position = new Vector3(mainCamera.transform.position.x, cameraPosition, mainCamera.transform.position.z);

```

This works, but it's causing the camera's y value to decrease continuously rather than just 0.8f, because `cameraPosition` is assigned a new value every frame. But `cameraPosition` has to be relative because its location depends on the player's location, so I can't figure out how else to write it.

# Answer
The turn my comment up there to an answer :

The "proper" way to use Lerp in your case would be that :

```
Vector3 originalCameraPosition;
bool hasBeenSet = false;
public void OffsetCamera() { //Call that every Frame

    if(!hasBeenSet ) originalCameraPosition = cameraPosition;
    cameraPosition = Mathf.Lerp(originalCameraPosition , originalCameraPosition - 0.8f, 3 * Time.deltaTime);

}

```

Copying my comment up there on why you do not get the proper result your way :

Lerp(A,B,C) returns the interpolated value placed at (C\*100) percents between A and B (in that order)

If you use what you wrote every frame this is what happen :

CameraPosition gets incremented, and then that incremented value is passed (in the next frame) as parameter to the next frame incrementation.

Lets admit that instead of Time.time you used 1, you would get : `CameraPosition = CameraPosition +0.8F;` every frame (Looks familiar?) Whatever the value of C because A = Lerp(A,A+x,C), A always increase!
> 1 votes

# Answer
It seems like what you want is a *camera target* attached to the character as a child, which your camera will continuously move to look at. When your character ducks, you'll move the *target* a certain amount relative to the character, instead of the camera itself.

Also, rather than lerping I would suggest using SmoothDamp to align the camera a fixed distance away. Just tweak the settings until your damping is right.

Then. within your camera's follow behavior, something like:

```
public Vector3 FollowDistance = new Vector3(0,0,10);
public GameObject Target;
public float SmoothTime = 0.3f;

private Vector3 _velocty;

void Update() {
    var cameraDestination = Target.Transform.Position - FollowDistance;
    transform.position = Vector3.SmoothDamp(transform.position,
                                            cameraDestination,
                                            ref _velocity,
                                            SmoothTime);
}

```
> 0 votes

---
Tags: unity, camera, lerp
---


title: OpenGL Framebuffer Object issue

text:
# Question
Title: OpenGL Framebuffer Object issue
I am struggling with implementing a proper Framebuffer Object .

glCheckFramebufferStatus is returning me: GL\_FRAMEBUFFER\_INCOMPLETE\_ATTACHMENT (36054).

What am i missing?

```
GLuint fbo, rboColor, rboDepth;

// Color renderbuffer.
glGenRenderbuffers(1,&rboColor);
glBindRenderbuffer(GL_RENDERBUFFER,rboColor);
// Set storage for currently bound renderbuffer.
glRenderbufferStorage(GL_RENDERBUFFER, GL_BGRA, _w, _h);

// Depth renderbuffer
glGenRenderbuffers(1,&rboDepth);
glBindRenderbuffer(GL_RENDERBUFFER,rboDepth);
glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT24, _w, _h);

// Framebuffer
glGenFramebuffers(1, &fbo);
glBindFramebuffer(GL_FRAMEBUFFER,fbo);
glFramebufferRenderbuffer(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,     GL_RENDERBUFFER, rboColor);
// Set renderbuffers for currently bound framebuffer
glFramebufferRenderbuffer(GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT,GL_RENDERBUFFER,rboDepth);

 // Set to write to the framebuffer.
glBindFramebuffer(GL_FRAMEBUFFER,fbo);

// Tell glReadPixels where to read from.
glReadBuffer(GL_COLOR_ATTACHMENT0);

GLenum e = glCheckFramebufferStatus(GL_DRAW_FRAMEBUFFER);//glCheckFramebufferStatus: check the completeness status of a framebuffer
if (e != GL_FRAMEBUFFER_COMPLETE) {
printf("\nThere is a problem with the FBO.");

}

```

# Answer
> 4 votes
First thing I would do is to figure out if any previous call to `glCheckFramebufferStatus` has failed. You are not calling `glGetError` at any point, which means you are probably missing a previous error that could help you figure out the problem. Make sure to add an error check after every previous GL call and log any error encountered. That will narrow down your search to the offending function.

That said, it is very likely that your renderbuffer allocations are failing. Probably the formats `GL_BGRA` or `GL_DEPTH_COMPONENT24` are not supported in the platform. If this is OpenGL-ES code, look in here to see the supported color and depth formats. This is kind of obvious, but also make sure the width and height are `> 0`!

**GL\_FRAMEBUFFER\_INCOMPLETE\_ATTACHMENT** is generated when:

> Not all framebuffer attachment points are framebuffer attachment complete. This means that at least one attachment point with a renderbuffer or texture attached has its attached object no longer in existence or has an attached image with a width or height of zero, or the color attachment point has a non-color-renderable image attached, or the depth attachment point has a non-depth-renderable image attached, or the stencil attachment point has a non-stencil-renderable image attached.

(source)

---
Tags: opengl, rendering, frame-buffer, fbo
---


title: Structure for attacking in RPG

text:
# Question
Title: Structure for attacking in RPG
I'm going over different ways to implement attacking in a "dungeon crawler".

What I have kind of abstracted out...

There are 2 kinds of people, The Player, and the enemies, these are both living creatures.

Living Creature will the the superclass for all living entitie's in the game(NPC is still a little murky...

Player and Enemy both use weapons, even it is only a fist.

I have decided that creating a Attack, on the weapon superclass, may be the best way to implement.

LivingCreature.Weapon.Attack(LivingCreature) will be the implementation.

This means no player attacks anything, the weapon itself will be the attacker. My question is, are there any negative side effects to this that I am not seeing. I have looked through some different design structures of games, and I haven't seen this exact implementation, and wasn't sure why.

To clarify-

Should Player have knowledge of how attacks works, or should the weapon know how attacks work.

# Answer
Generally, you want to avoid excessive hierarchy. What if a player wants to attack an object (such as a trap, or door?) How would a trap attack a player? What about environmental hazards?

I would suggest an entity-component system over inheritance here. Give everything that has health a `Health` component, and give everything that can attack a `Weapon` component. For the player, give things that are controllable a `Player` component. Then you can mix and match things as necessary whenever these situations arise.

EDIT:

That aside, I think your situation (weapon does the attack), makes perfect sense. But there are some things (namely, stats like STR, WIS, etc.) that have to get passed from the player to the weapon. A level 1 peasant is not going to do much damage even if he has a level 100 supersword, for instance.
> 4 votes

---
Tags: c#, data-structure
---