title: Question about segment of code in XNA

text:
# Question
Title: Question about segment of code in XNA
Basically when the code says

```
public static Camera Instance
{
// Code and something with get statement
}

```

Is it declaring a method? I don't think it is a method because there is no parenthesis to indicate the area to put in parameters. Here is the full class:

```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;

namespace ScrollingTest
{
    public class Camera
    {
    private static Camera instance;
    public static Camera Instance
    {
        get
        {
            if (instance == null)
                instance = new Camera();
            return instance;

        }

    }
}
}

```

# Answer
> 2 votes
```
public static Camera Instance
{
    get
    {
        if (instance == null)
            instance = new Camera();
        return instance;

    }
}

```

This is called a Property.

---
Tags: xna-4.0, monogame
---


# Question
Title: Collision, triggering, and range detection in an RTS. What are the optimal solutions for unit spatial awareness?
I've finally ran into the problem of multiple triggers and collisions within my 2D RTS. Up till now I've been using unities sphere colliders as a way of simulating spatial awareness. To trigger when objects have entered and exited a specific area around a unit or building so that they can be appropriately targeted.

This became a performance problem when I started having hundreds of colldiers overlapping each other. Since the units are aware of projectiles as well as other units/buildings, this becomes very expensive very fast. I've found that I can only manage to have a couple hundred projectiles and about 100 colliders within close proximity of each other before the game slows to a crawl just from PhysX. (hundreds of projectiles entering and exiting 100 collliders all the time)

I did some research and found spatial partitioning mentioned all over the place. Is this a solution to the problem I am currently presented with? Are there other solutions for objects to have spatial awareness of potentially hundreds of other objects at a time without bringing my CPU to it's knees?

# Answer
You will probably need a hybrid between a btree, and quad-tree. (to get you Googling)

A few things to consider when partitioning:
-Surface-to-air missiles do not need to test against ground units
-Likewise with air-to-surface and air-to-air
-Buildings don't move and shouldn't test against other objects; other objects should test against buildings
-Projectiles only move forward (even when following a curved path); no need to test objects behind and/or too far left/right

The logical divisions like air/ground will be separate buckets within the leaf-nodes of the tree you make. With said tree, any projectile can quickly query for nodes that are in range and within a FOV of it's "forward" direction. The node can return all of its contained objects, or any individual bucket. For example, air-to-air missiles will query only the air buckets out of the nodes in front of them. Likewise, tanks only need to consider the ground-unit and building buckets.

**Very quickly/roughly (more or less C#, apparently):**

```
class TreeNode
{
   void AddAirUnit(AirUnit unit) {...}
   void AddUnit(UnitTypes unitType, Unit unit)
   {
      m_allUnits.Add(unit);
      foreach (TreeNode child in m_nodes)
      {
         //Parent can test whether each child should own unit
         //Or each child can ignore units that don't actually belong to it
         child.AddUnit(unitType, unit);
      }
   }
   virtual AirUnit[] GetAirUnits() {...}
   virtual LandUnit[] GetLandUnits() {...}
   virtual Unit[] GetUnits(UnitTypes unitType) {...}
   virtual Unit[] GetAllUnits() {...}
   TreeNode[4/8] m_nodes; //Quad/Oct
   List<AirUnit> m_airUnits;
   List<LandUnit> m_landUnits;
   List<Unit> m_allUnits;
   //Vector3 m_centerPoint; //Things we might need?
   BoundingBox m_boundingBox; //Things we might need?
}
class Tree : TreeNode
{
   //If not obvious, the tree should contain only references, not copies.
   //One reference may be deposited into more than one bucket through recursion.
   //If the children should be tested (according to query), but return 0 items,
   //the parent should/would also return 0 items, so just return the empty bucket.
}

```

**Tree usage:**

```
void UseTree(Ray mouseRay)
{
   Tree tree = Tree();
   //populate tree

   tree.GetAllUnits();
   //GetXXX functions already provide logical sorting, how will you spatially sort?
   s_filter = mouseRay; //Presumably, a filter/query would be either set(static)
   tree.GetAirUnits();
   tree.GetAirUnits(mouseRay); //or passed as a parameter.
   //m_nodes should be private, but for explanation:
   tree.m_nodes[0].m_nodes[0].m_nodes[0].m_nodes[0].m_nodes[0].GetAirUnits();
}

```

Additional implementation details may be extrapolated from this example:
> 2 votes

---
Tags: unity, rts, space-partitioning
---


# Question
Title: How to draw multiple large background images using libgdx?
I have developed a basic lunar lander-style game using Slick2D and dyn4j and am now redeveloping it using libgx for various reasons. I am having problems drawing the background (i.e. everything, but the main spaceship) using libgdx and am not sure if I am doing this correctly.

In the Slick2D version of the game I have 3 layers to the background, which are all 4096 by 1440 pixel Image objects (this to allow for suffient variety in layers 2 and 3 as per below). The layers are:

* Layer 1 = stars (black background, with white pixels that vary in brightness so that they appear to twinkle)
* Layer 2 = mountains (black background with deep blue filled landscape) (static image)
* Layer 3 = foreground (black background with foreground landscape, a simple line drawing, with landing sites that vary in brightness over time)

I map where the ship (and therefore the screen) sits within the background images and then extract portions of the images to paint on the screen (this allows for wrapping across the top, the sides or the corners of the background images (note only the stars wrap across the top/bottom – the mountains and foreground only need to wrap side-to-side and across corners). I then extract a portion of the image using the getSubImage() method and draw this to the screen using the draw() method, e.g. as follows:

```
stars.getImage().getSubImage(x1, y1, width, height).draw(0, 0);

```

In separate method calls in each update() loop I update the star and foreground images so that the stars and landing sites vary in intensity. This is done by drawing directly to the background Images.

Using this approach the game performs at over 400FPS using Slick2D and dyn4j if I allow it to run unrestricted.

In the libgdx version I have created the backgrounds as Pixmap objects and then extracted portions by drawing a subsection to a new Pixmap object, which is the same size as the screen. I then convert this to a Texture and draw it to the screen using a SpriteBatch. Having read the documentation, it seems like this might be a very inefficient way to do things and, in practice, is too slow using just the star background (layer 1) without either of the other two layers.

There doesn’t appear to be a way to do this using Textures since I want to be able to draw to these to vary star and landing site intensity over time (unless I fundamentally re-write the game and use Sprites to draw the flashing stars and landing sites and just use a flat, static background Texture for everything else...)

So, my question is what is the correct way to do this using libgdx so that I get an effective level of performance? Can I replicate the logic that I have used in the Slick2D version of the game or do I need to do a fundamental re-think?

Note the game is designed for the desktop only and is not intended to be run an Android or iOS.

# Answer
After a lot of research and continuing development using Slick2D, I have decided that the only way to do this in libGDX would be a fundamental re-write. After some tests, it also turns out that this is a Good Thing.

The solution I have tried is to hold the data for the graphics in arrays, use TreeSet indexes to be able to quickly locate which items should be on screen at any one time and then draw these once per loop. Per loop, this removes the getSubImage() call and repaint of this sub-image to the main graphics canvas. Having tested the approach with both the old graphics-based class and the new array/TreeSet-based class the difference in performance is significant. Using the graphics approach the game runs unchecked at about 205 FPS. Using the new array/TreeSet approach it runs at around 280 FPS.

I've included an edited version of my Stars class here to show how this works in practice. This is the simplest case since the stars are simply dots on screen. It gets more complicated for other shapes, but the logic is essentially the same except for having to check for objects being partially on-screen, i.e. check all vertices. I've also included a small class below that I use for the TreeSet indices used to search for on-screen objects. Both use dyn4j (physics engine) co-ordinates for the stars and also for the edges of the screen (picked up as an Observer of another class) to calculate what should be shown on-screen.

```
public final class Stars implements PlanetObserver {

    private Color dots[];                                   // Colours for different star intensities

    private final Settings settings;
    private final int bWIDTH;
    private final int bHEIGHT;
    private final int sWIDTH;
    private final int sHEIGHT;

    private int scrLeftX;                                   // Where screen is in world co-ordinates
    private int scrTopY;

    private int[][] star_array;                             // Array of stars
    private TreeSet<Index> xIndex;                          // Index of x values
    private TreeSet<Index> yIndex;                          // Index of x values
    private static final Integer MAX_STARS = 500;

    /* Static placeholders for values held in star_array include:
     x co-ordinate of star
     y co-ordinate of star
     intensity of star brightness
     speed of star update
     direction of update - up or down
     */
    private static final int STAR_X = 0;
    private static final int STAR_Y = 1;
    private static final int STAR_INTENSITY = 2;
    private static final int STAR_SPEED = 3;
    private static final int UP_DOWN = 4;
    private static final int DOWN = 0;
    private static final int UP = 1;

    public Stars(Settings setts) {
        settings = setts;                                   // Global settings class
        bWIDTH = settings.getbWIDTH();                      // Width of buffer for star field
        bHEIGHT = settings.getbHEIGHT();                    // Height of buffer for star field
        sWIDTH = settings.getsWIDTH();                      // Current screen width
        sHEIGHT = settings.getsHEIGHT();                    // Current screen height
        init();
    }

    public void init() {
        settings.getPlanetObj().registerObserver(this);     // Register for scrTopLeftX/Y updates

        // Create star images - saves recreating them each cycle
        dots = new Color[11];
        dots[0] = new Color(110, 145, 230, 0f);             // Match sky colour at 1000m altitude
        for (int i = 1; i < 11; i++) {
            dots[i] = new Color(110, 145, 230, (float) (i / 10f));
        }

        // Create the star field
        star_array = new int[MAX_STARS][5];                 // Array of star values: x, y, intensity and update speed
        xIndex = new TreeSet<>();                           // Set up new indices for x and y axes
        yIndex = new TreeSet<>();
        Random rand = new Random();                         // Random number generator
        rand.setSeed(System.currentTimeMillis());           // Seed random with current time

        for (int i = 0; i < MAX_STARS; i++) {
            star_array[i][STAR_X] = rand.nextInt(bWIDTH);   // x co-ordinate
            star_array[i][STAR_Y] = rand.nextInt(bHEIGHT);  // y co-ordinate
            star_array[i][STAR_INTENSITY] = rand.nextInt(11);// intensity 0 to 10, where 0 = black and 10 = white
            star_array[i][STAR_SPEED] = rand.nextInt(3);    // glow speed 0 to 2, where 0 = slow, 1 = medium, 2 = fast
            star_array[i][UP_DOWN] = rand.nextInt(2);       // Direction of glow travel - 0=down, 1=up
            // Add entries to indices for x and y values
            xIndex.add(new Index(star_array[i][STAR_X], i));
            yIndex.add(new Index(star_array[i][STAR_Y], i));
        }
    }

    public void update() {
        // Loop through star array and increment/decrement intensity as appropriate
        for (int[] star : star_array) {
            if (star[UP_DOWN] == UP) {
                star[STAR_INTENSITY]++;
                if (star[STAR_INTENSITY] > 10) {
                    star[STAR_INTENSITY] = 9;
                    star[UP_DOWN] = DOWN;
                }
            } else {
                star[STAR_INTENSITY]--;
                if (star[STAR_INTENSITY] < -5) {            // Minus numbers allow for period where str is 'off'
                    star[STAR_INTENSITY] = -4;
                    star[UP_DOWN] = UP;
                }
            }
        }
    }

    public void render(Graphics g) {
        // Calculate screen bottom-edge Y taking into account values > bHEIGHT
        int scrBtmY = scrTopY - sHEIGHT;
        if (scrBtmY >= bHEIGHT) {
            scrBtmY = scrBtmY % bHEIGHT;
            if (FastMath.abs(scrBtmY) == bHEIGHT) {         // Wrap-around bug at y == bHEIGHT
                scrBtmY = 0;
            }
        }

        // Get x and y co-ordinate values that are in range of on-screen World co-ordinates
        Index index;
        index = new Index(scrLeftX, 0);
        Index xLower = this.xIndex.ceiling(index);
        if (xLower == null) {
            xLower = this.xIndex.last();
        }

        if (scrLeftX + sWIDTH <= bWIDTH) {
            index = new Index(scrLeftX + sWIDTH, 0);
        } else {
            index = new Index((scrLeftX + sWIDTH) - bWIDTH, 0);
        }
        Index xUpper = this.xIndex.floor(index);
        if (xUpper == null) {
            xUpper = this.xIndex.first();
        }

        index = new Index(scrBtmY, 0);
        Index yLower = this.yIndex.ceiling(index);
        if (yLower == null) {
            yLower = this.yIndex.last();
        }

        if (scrBtmY + sHEIGHT <= bHEIGHT) {             // Check if range of y values wraps around top of buffer
            index = new Index(scrBtmY + sHEIGHT, 0);
        } else {
            index = new Index((scrBtmY + sHEIGHT) - bHEIGHT, 0);
        }
        Index yUpper = this.yIndex.floor(index);
        if (yUpper == null) {
            yUpper = this.yIndex.first();
        }

        // Extract y value pointers to star_array into  a temporary TreeSet
        TreeSet<Integer> yPointer = new TreeSet<>();
        SortedSet ySet = new TreeSet();
        if (yLower.xyValue < yUpper.xyValue) {
            ySet = this.yIndex.subSet(yLower, yUpper);
        } else {                                            // Wrapping occured - extract 2 ranges and join
            ySet.addAll(this.yIndex.tailSet(yLower, true));
            ySet.addAll(this.yIndex.headSet(yUpper, true));
        }
        for (Iterator it = ySet.iterator(); it.hasNext();) {
            Index i = (Index) it.next();
            yPointer.add(i.pointer);
        }

        // Create list of x value index elements that might be on-screen
        ArrayList<Integer> result = new ArrayList<>();
        SortedSet xSet = new TreeSet();
        if (xLower.xyValue < xUpper.xyValue) {
            xSet = this.xIndex.subSet(xLower, xUpper);
        } else {                                            // Wrapping occured - extract 2 ranges and join
            xSet.addAll(this.xIndex.tailSet(xLower, true));
            xSet.addAll(this.xIndex.headSet(xUpper, true));
        }

        /* Check if x value pointers exist in y pointer list - if
         so then point is on screen: store in results list
         */
        for (Iterator it = xSet.iterator(); it.hasNext();) {
            Index i = (Index) it.next();
            if (yPointer.contains(i.pointer)) {
                result.add(i.pointer);
            }
        }

        // Draw the stars on-screen that are in the results list
        for (Integer pointer : result) {
            if (star_array[pointer][STAR_INTENSITY] >= 0) {
                g.setColor(dots[star_array[pointer][STAR_INTENSITY]]);
                int x = star_array[pointer][STAR_X] - scrLeftX;
                int y = sHEIGHT - (star_array[pointer][STAR_Y] - scrBtmY);
                g.drawLine(x, y, x, y);
            }
        }
    }

    @Override
    public void updateScreen(float topLeftX, float topLeftY, int xoffset, int yoffset) {
        scrLeftX = (int) topLeftX;
        scrTopY = (int) topLeftY;
    }
}

```

.. and here is the class for the Index elements used in the TreeSets:

```
public final class Index implements Comparator<Index>, Comparable<Index> {

    public final int xyValue;
    public final int pointer;

    public Index(int val, int p) {
        xyValue = val;
        pointer = p;
    }

    @Override
    public int compare(Index o1, Index o2) {
        return o1.xyValue - o2.xyValue;
    }

    @Override
    public int compareTo(Index o) {
        return this.xyValue - o.xyValue;
    }
}

```
> 0 votes

---
Tags: java, libgdx, slick
---


# Question
Title: How do I determine if I'm allowed to use an asset from the web in my game?
I need to incorporate other people's work into my game project. I must admit (with a little embarassment) that I am almost completely ignorant about copyright. I only have a vague idea of what it is, what it protects, or what it means when I see Ⓡ or © or ™. Since English is not my native language, reading all those Wikipedia pages full of legal jargon only gave me an headache.

I'm looking for images (sprites, backgrounds, UI elements mostly) and sound. I intend to publish the game (Google Play and Flash/HTML5 game websites, maybe the iPhone App Store). I don't plan to "sell" it directly, but I do intend to insert ads and/or in-app purchases.

I will most likely need to edit the content before including it in my game. Probably just scaling/rotating, but the greater degree of freedom I have, the better.

So, what should I look for, to be sure I have the rights to use the media I find the way I need to (like "royalty free" or "copyright free")? In which cases do I have to ask for "permission" to use that media, and how? Like, send the owner of the site an e-mail?

# Answer
You need to look for a document or text describing the license of the work you want to use. These can take many forms and there's no exhaustive list of all potential licenses, but there are common ones (such as the ones that open-source software projects are released under, or more commonly for art and related assets, the Creative Commons set of licenses).

Unless the work includes a license stipulating appropriate terms for your reuse of the asset, you effectively *cannot use it*. While copyright law varies from jurisdiction to jurisdiction, it's going to be difficult to tell which jurisdiction applies when you're looking at stuff on the internet and so you should assume the worst-case scenario for yourself: US jurisdiction, which grants copyright to the author of a work implicitly as soon as that work is placed in a fixed, tangible form. Thus a work without an accompanying license or stipulation that the work is in the public domain, is unusable unless and until you negotiate a license for yourself with the copyright holder.

Similarly, unless the terms of the license say you can *modify* and *redistribute* the modification, you can't actually change the work at all and must use it in it's original form. It's unclear to me what constitutes such a "change," legally (does rescaling count? does changing the image file format count?) and thus you should consult an actual lawyer to be sure.

In fact, when in doubt, *consult a real lawyer*; a real lawyer should in particular help you go over the terms of any licensing deal you may strike up. They are often not as expensive to talk to as people assume, and many will happily answer simple IP law questions for you for free if it means they might establish a relationship with you that will eventually lead to a paying client. There are a number of lawyers who routinely do legal-related AMAs on the game development sub-reddit, for example, who will happily point you in the direction of a local colleague if they have one.

---

Ⓡ and ™ refer to *trademarks*, not copyright, and are *for the most part* likely to be irrelevant to your asset search; a trademark is basically a recognizable symbol or design used to identify a corporation or brand. This means, for example, the Nintendo logo or similar.

The © symbol indicates copyright, although it is not necessary to include it (in the US it was required up until the late 80s, but that no longer applies).
> 2 votes

# Answer
Here's an academic and global perspective. This is deliberately less practical than Josh's answer, but is hopefully a useful reading guide.

I'm also not a lawyer though. You should talk to a proper one to make sure you understand it right, especially because (as we will see) the exact laws differ between countries.

## What is copyright?

Having copyright to a thing means being the only one who is allowed to decide when and how it is copied. This means you are allowed to say who is allowed to use it, and how.

This also means you are allowed to give other people some of that right, if you want to. If you ask the copyright holder of a thing if you are allowed to use it for a particular thing or for a particular time, and they say yes, congratulations, you can use it. But you have to ask them, and you have to do it on their terms. It doesn't matter very much how you ask them, as long as you really ask *them specifically* and their response is clear.

## How do I get a copyright?

In most countries, you automatically gain copyright to things that you create, because most countries have signed the TRIPS Agreement, which promises these things.

## What happens to my copyright when I die?

The TRIPS agreement says you should have copyright for at least 20 years after you die. Some countries have decided to make that time longer. Here's a list of how long it is in various countries.

## Where does a copyright apply?

Your copyright applies in all countries that have signed the Berne convention, as long as it's published in one of those countries first. (That includes almost all countries.)

## What copyright exceptions exist?

The TRIPS agreement also requires signing countries to have exceptions to copyright for fair use. The description for this (given by the Berne three-step test) is:

> It shall be a matter for legislation in the countries of the Union to permit the reproduction of such works in certain special cases, provided that such reproduction does not conflict with a normal exploitation of the work and does not unreasonably prejudice the legitimate interests of the author.

It's quite vague, so countries have created slightly different variations of "fair use" laws. However, in most places, this includes uses for critique, education and some non-profit cases. Any project that makes money (or makes it even a little bit harder for the copyright owner to make money) *very rarely* gets an exception.
> 2 votes

---
Tags: assets, copyright
---


# Question
Title: Cocos2dx - Physics - Abort() When Changing Dynamic PhysicBody to Static?
I just learned cocos2dx v3.3 integrated chipmunk physics engine.

Here ,as you see, I create a simple circle with physic as:

```
auto sprite = Sprite::create("circle.png");
auto body = PhysicsBody::createCircle(sprite->getContentSize().width / 2);
body->setContactTestBitmask(-1); //active collisions event
sprite->setPhysicsBody(body);
sprite->setPosition(...);
this->addChild(sprite);

```

When I toggle this circle static/dynamic in normal situation everything work fine and when circle become static it stop in its position (as we expect gravity don't move it longer). here is a toggle code which works fine:

```
body->setDynamic(false);
scheduleOnce([=](float dt){body->setDynamic(true);},3,"Back to Dynamic Mode Timer");

```

**PROBLEM BEGINS**

But I want when the circle collide with something else ( in my case screen edge with is not important part of scenario), it become static then. so I use below code:

```
auto contactListener = EventListenerPhysicsContact::create();
contactListener->onContactBegin = [=](PhysicsContact &contact) -> bool
{
    return true;
};
contactListener->onContactPostSolve = [=](PhysicsContact& contact, const PhysicsContactPostSolve& solve)
{
    contact.getShapeA()->getBody()->setDynamic(false); // ==> Cause Abort() !
};

_eventDispatcher->addEventListenerWithSceneGraphPriority(contactListener, this);

```

But I just face a abort() message and game exit.

The call stack ( God bless it) show that the error is comming from line 300 in `CCPhysicsBody.cpp`:

```
if (_world != nullptr)
{
    cpSpaceRemoveBody(_world->_info->getSpace(), _info->getBody());
}

```

# Answer
I wonder if chopmunk allows the object to be made static inside a callback issued from the guts of the physics engine. What if you set a flag on the object and after updating physics you set things static? It would be worth checking the documentation on cpSpaceRemoveBody.

I looked into the source code for chipmunk, and here's the relevant function:

```
void
cpSpaceRemoveBody(cpSpace *space, cpBody *body)
{
        cpAssertWarn(cpSpaceContainsBody(space, body),
                "Cannot remove a body that was not added to the space. (Removed twice maybe?)");
        cpAssertSpaceUnlocked(space);

        cpBodyActivate(body);
        cpSpaceFilterArbiters(space, body, NULL);
        cpArrayDeleteObj(space->bodies, body);
        body->space = NULL;
}

```

From https://code.google.com/p/chipmunk-physics/source/browse/trunk/src/cpSpace.c

My guess is that it is dying because the space is not 'Unlocked'. You will have to queue it somehow to be changed from dynamic to static when it isn't locked.

I do not know if chipmunk has this facility. If not, just put the object in a list and right after the physics is stepped for the frame, run your list and change objects to static.

**Update**

In response to your feedback, I could not find a place where Chipmunk's `addPostStepBlock` is exposed to the library. I assume you have seen this page, and want to reproduce it's behavior:

https://www.makegameswith.us/gamernews/367/make-a-dynamic-body-static-in-cocos2d-30-with-chi

However, I did look at their wrapper class, and I wonder if you could do the following.

On contact, remove the object from the world. Set it to Static, and add it back. There are a series of functions that wait until the update is finished:

Internally, PhysicsWorld::AddBody() calls PhysicsWorld::addBodyOrDelay(). I wonder what would happen if you called PhysicsWorld::RemoveBody(), set it static, and then PhysicsWorld::AddBody(). Likely it will still blow up, but you can try.

Alternatively, since Cocos2dx is open source you could add methods to get access to the addPostStepBlock call inside chipmunk, but I can't help with that as I have never done it before.
> 1 votes

# Answer
If you only want to change the physicsBody to static, you can do this using cocos2d-x **scheduleOnce** with delay = 0.0f.

You might have to manually schedule the physics step but it should work in any case.

For instance, let's say you want to make shapeA static when a collision is detected:

```
bool HelloWorldScene::onContactBegin(PhysicsContact& contact)
{

    scheduleOnce([&](float dt)
    {
        contact->.getShapeA()->getBody()->setDynamic(false);
    }, 0.0f, "YourTag");
    return true;
}

```

And that's it.
> 0 votes

---
Tags: physics, cocos2d, cocos2d-x, chipmunk
---


# Question
Title: Decoupling rendering pipeline (for UI responsiveness): Multithreading and multiple contexts?
*Warning! Wall of text* (see **\<TL;DR\>** paragraphs below for short version)

I have been noticing something in quite many games (most recently in cutting-edge RTS games such as Uber Entertainment's Planetary Annihilation, which is amazing by the way) that I think has room for improvement.

That is, the rendering system is synchronous in the sense that input event loops are apparently "bound" to the rendering loop. So the consequences are that e.g. mouse movements and keyboard events are usually queued up and processed only once a frame is finished rendering.

This may not be a completely accurate account of what's actually happening. What is certainly clear is that for example the mouse cursor movement updates no faster than the graphics in the game render, and obviously when keyboard events are fired, and their consequences are not visible in the game until the next frame renders.

The delay of that frame, if the framerate is very low, will very much be felt, and I want to emphasize that the same low frequency of response applied to input is a much bigger problem than if we are only talking about its impact on animation smoothness.

Of course Planetary Annihilation is a game that is still in beta, and is (as we are told) still rather unoptimized. But since this game makes a point of not having a unit cap, it is basically a fact of life that once a battle gets big enough and once there are enough units in existence, the sheer computational load will bring any computer, eventually, to 10, 5, or even 2 frames per second.

The interesting bit is that the game is still sort of playable since it isn't an FPS, but the first problem with a 2 fps rendering rate is not so much the choppiness of movement (which cannot really be helped without more dynamic rendering LOD or culling which is outside the scope of this question) but rather in the distinct lack of responsiveness that is caused by the synchronous nature of the mouse and keyboard input handling behavior, i.e. the mouse is rendered at the same limited frame rate. In fact what I very much expect to be happening is that the frame takes e.g. 500ms to render, and during that period the mouse event queue is piling up with about 500 mousemove events (due to my 1000Hz mouse) and perhaps a few keyboard events, and then this queue only gets a chance to flush and be handled when that frame finishes drawing, when the swapbuffers/glFinish/glFlush/etc. function returns.

That is the best case scenario. I imagine a lot of games could simply just ignore the entire queue altogether and drop a bunch of events, leading to even more unplayability at low loop frequencies. The reason for this is that upon light testing at a regular 60fps, most if not all events will still be properly handled with a faulty system like this.

One of the primary problems is that this can make certain fast actions impossible to perform. Suppose I want to drag to select a group of units in order to give them a command, but I complete the click, drag, release motion of the mouse within 500ms. If the event loop handler code does not update its state in a proper way then what effectively just happened is my entire selection command would just fail, and the best case scenario is the selection would be properly deducted but there still would never have been a frame drawn that showed the actual selection box itself (since it came into and went out of existence *within the course of rendering a single frame*).

Indeed what PA appears to do is only update the "I am now selecting" state once in the entire loop, so I have to click, drag, and release across a minimum of 3 separate frames in order to achieve an actual selection command. Consider this: It effectively physically limits the player to 20 APM (actions per minute).

There are a lot of gesture based controls that can exist especially in the world of tablets. In my opinion, being bound to the render loop will make for a severe responsiveness handicap.

I feel like I've over-explained the introduction by now. So the solution is clearly to decouple the UI from the render loop.

I want to render cursor position and key input and touches, with some reasonable set of UI elements, **separately** from my primary 3D scene. The question is, what is the best way to accomplish this?

I can think of two ways to approach it, and there may be more.

1. No multithreading. Main GL loop flushes input queue and draws UI, and does not necessarily update 3D scene. Design 3D rendering pipeline to draw fragments of the scene at a time into an alternate render buffer or texture, one piece at a time. This sounds a little impractical because it's not clear how the rendering should be split up. Tiles? scanlines? How big will they be? With a super heavy workload that normally renders at 2fps, I'd want to split the scene into 500ms/16.667ms = 30 chunks, but there's definitely no guarantee that each chunk would take the allotted 16.67ms. It also sounds like adjusting the chunk number will result in shuffling around resources on the GPU, and basically lead to a bunch of extra overhead.
2. **\<TL;DR #1\>** Two GL contexts, two threads. Thread #1 flushes input queue and draws UI, periodically updates texture on which 3D scene is drawn, draws 3D scene with full-screen-quad, and handles buffer swapping to ensure vsync smoothness. Thread #2 renders 3D scene to texture shared with Thread#1. Requires use of ping-pong scheme to facilitate resource sharing. Thread #2 flips a bit which Thread #1 will read on its next cycle to determine if it needs to flip the texture.

Option 2 sounds like the way to go here... Since option 1 still needs to read from the previously rendered frame in order to display something while still updating the UI responsively, it still needs to employ a ping-pong scheme with that texture. So I think option 2 wins on pretty much all fronts, speed and memory, and option 1 seems fraught with complexity.

However I am also seeing a few nontrivialities with option 2, because it's not clear how to make it perform properly when the 3D rendering **is** keeping up with the screen refresh rate -- thread #2 sort of has to wait for thread#1 to be done flipping the texture before it can start rendering to the new one. It seems like I have to dynamically switch back to a simpler "basic" pipeline if the rendering isn't taking too long.

The architecture that is emerging looks to me like an additional abstraction of a front and back buffer. The *real* front and back buffer are now decoupled from the heavy 3D render task so they are now continuously updated at refresh rate so long as the UI rendering can complete in time, and the flip rate of new buffer pair is the "real" framerate.

**\<TL;DR #2\>** My question is... can this be done in a cleaner way? Is there an engine design that can achieve this perhaps without requiring two contexts? I know that for example on iOS you are required to set up an OpenGL ES context for each thread, and as far as I can tell the only sane way to handle this is with threads.

I realize that one possible way "around" the problem is to just cheat by using whatever external interface system exists. For example, on Windows in an SDL application in windowed mode (or maybe even in fullscreen mode...) the default OS cursor is used by default and it should really stay responsive regardless of how quickly the buffer swaps in the GL window.

Or on iOS, you can have regular UI widget overlay views that go on top of the EAGLView which I would expect to be responsive as they bypass the GL rendering since they're not part of it.

But I am talking about a unified graphics pipeline that has UI integrated into it, where this UI is drawn with the same context used for drawing the 3D scene. This is for portability reasons. Even though I have labeled the question with OpenGL the topic obviously is applicable to DirectX for academic purposes.

# Answer
I agree that option 2 (two render threads running at different frequencies) would be the most "logical" way to deal with this kind of situation, but it makes a big assumption: the GPU and driver have to support—or rather, *simulate*—pre-emptive multitasking. What you want is that the UI drawing commands from thread 1 should get high priority and get finished immediately even though thread 2 is in the middle of drawing. In other words, you don't want the GPU/driver to have to wait for thread 2's rendering to be finished before servicing thread 1.

However, you're at the mercy of the driver as to whether this works and how well. GPUs today are single-threaded devices at the top level: they only process one command buffer at a time, and they don't support pre-emption; you can't pause the GPU in the middle of a command buffer and switch to another one. So the driver pretty much has to do your option 1 internally. When you issue GL calls, it buffers up your commands then dispatches them to the GPU at some point, and it can switch between contexts only at the boundaries of these buffers.

The point here is that depending on how the driver decides to slice up command buffers, your UI commands from thread 1 might get stuck behind a long command buffer from thread 2.

My guess is that you'll find your option 2 works OK on some combinations of GPU and driver, and not on others. You might be able to help the situation by sprinking `glFlush()` calls into your thread 2 rendering, which hint to the driver to go ahead and finish up a command buffer, giving it the opportunity to switch contexts.

It's kind of like in the bad-old-days of non-preemptive CPU multitasking, where you'd have to explicitly yield to the OS by calling `Sleep(0)` or some such, or else a long-running operation would lock up the whole system. That's where we're at with GPUs today. Hopefully, GPUs (and graphics APIs) of the future will better support multitasking, but it's a really tough engineering problem to solve.
> 4 votes

# Answer
It seems to me there may be a design issue in the game itself if the frame rate regularly drops to 2fps and that's considered normal. Some turn-based games might take a while to render and present the next screen as basically "static" plus some simple interactive rendering on top of it, but then that's the game style itself. Typically if your game is real-time interactive, then it has a minimum playable rate. Playability is not just animation rate, but also UI feedback rate. Of course you can always cut back on rendering detail if it's under load, but sounds like a lot to drop if starting from potentially 2fps.

Sorry if I misunderstood the question; it was fairly long :)
> 0 votes

---
Tags: opengl, opengl-es, input, multithreading
---


title: Spritekit water flowing

text:
# Question
Title: Spritekit water flowing
I'm wondering if there is a way in spritekit to implement water flowing through a path?

like this water flow

Right now I'm generating the path using UIBezierPath and PaintCode

Any suggestion?

Thanks.

# Answer
> 8 votes
This is a very interesting topic.

You can build the water effect using SpriteKit and its integrated physics engine.

## Step 1

1. Create a Physics World
2. Create many little circular SKSpriteNode(s), each one will have a circular physics body matching the graphics representation

## Step 2

Then every frame you'll need to:

1. Draw all the sprites on a buffer
2. Apply a blur effect
3. Apply a threshold effect
4. Draw the buffer on the screen

You can get a better understanding of the process by playing with this interactive demo: http://www.patrickmatte.com/stuff/physicsLiquid/

---
Tags: objective-c, spritekit, xcode, fluid-dynamics
---


# Question
Title: How can I detect a perfect passageway for collision detection?
The problem is when I move diagonal it moves fractions of units and therefore my coordinates might be a fraction of a unit say (40,400) might be actually (40.12,400.40) but another problem is my pink square might be moving really fast. Below is a screenshot where you can see I can make it past a pixel perfect passageway with my pink square but the other passageway with the white square is very difficult if not impossible to make it through (I have by zooming in and moving REALLY slow but sometimes it impossible for the reasons listed above) Suppose in the example above I am holding the up and left arrows how can I make it so the pink square slides across the yellow rectangle and detects it can move upward and begins to move up?

The code I am using right now looks like this

```
float d45 = (float) (1 / Math.sqrt(2));
moveX = -d45;
moveY = d45;
moveX = moveX * t * speed;
moveY = moveY * t * speed;
        for (Stuff s : collidables) {
            if (overlaps(s, moveX, 0)) {
                collidedX.add(s);
                x += moveX > 0 ? s.x - width - x : s.x + s.width - x;
            }
        }
        if (collidedX.size < 1) {
            x += moveX;
        }
        for (Stuff s : collidables) {
            if (overlaps(s, 0, moveY)) {
                collidedY.add(s);
                y += moveY > 0 ? s.y - height - y : s.y + s.height - y;
            }
        }
        if (collidedY.size < 1) {
            y += moveY;
        }

```

I check for collision twice once on the Y axis and another on the X axis so that it can still slide to the left even if you are pushing the up and left arrow. The problem is it skips over the 100 unit passage to the left of the picture above. If I create a passage that is 110 units wide it will slide up fine but this isn't really cool because I like how it looks where it slides perfectly. Any ideas?

# Answer
> 2 votes
Collision detection like this can be tricky. However - I do see a way around your problems.

First, you definitely want to round off your "collision" position. In most cases, decimal numbers will cause collision problems when you're working with pixels (which are measured in whole numbers, usually).

Here are two methods I thought up, in image form: (sorry everybody I know this makes my answer hard to edit... if you notice an error with the image please comment - I can correct it, thanks!)

# Answer
> 1 votes
The easiest way to side-step this is:

```
x = (int)x;
y = (int)y;

```

or

```
x = round(x);
y = round(y);

```

Are either of these acceptable, visually?

Edit:

Diagram of modified SuperDoggy "Method 1" using floats:
Precise overlap amount given by colliders

Since you have so many cases, it may be helpful to make a helper for jiggling the rect:

```
class CollisionHelper
{
   CollisionHelper(Collider1,Collider2);
   RECT original;
   RECT test;
   void MoveUp();
   void MoveDown();
   void MoveLeft();
   void MoveRight();
   void ResetRect();
   void Test();
   bool wasValid[4];
   ...
}

```

This would also encapsulate any flags needed to make multiple tests in one frame and any frame-to-frame flags that might be useful. It should make the if/switch more manageable.

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


# Question
Title: How do you calculate the nearest point on 2 curves?
Given the points of a line and a quadratic bezier curve, how do you calculate their nearest point? .... Similarly, given the points of 2 curves, how do you get the nearest point?

# Answer
Here is my try. The following algorithms are **far from perfect**, but they are simple and I believe you should start with this, check whether they work in your situation, and switch to something faster and/or more accurate later.

The idea is the following:

* Sample the Bézier curve, find the nearest point on that sample
* Sample a neighbourhood around the found point, find a new nearest point
* Continue until the point no longer changes much

### Algorithm for distance from Bézier curve to line

The Bézier curve is parametrised by a function `F(t)` using a set of control points and a varying parameter `t`. The number of generating points is unimportant.

The line is parametrised by two points `A` and `B`.

1. Let `SAMPLES = 10` for instance
2. Start with `t0 = 0` and `t1 = 1`
3. Let `dt = (t1 - t0) / SAMPLES`
4. If `dt < 1e-10` (or any other accuracy condition you see fit), **algorithm is finished and answer is `F(t0)`**.
5. Compute a list of `SAMPLES + 1` points on the Bézier curve:

* `L[0] = F(t0)`
    * `L[1] = F(t0 + dt)`
    * `L[2] = F(t0 + 2 * dt)`
    *
    * `L[SAMPLES] = F(t0 + SAMPLES * dt)`
6. Find which point in `L` with index `i` is closest to the line. Use any point/line distance method you know, for instance the square distance `||AB^L[i]A||² / ||AB||²` where `^` denotes cross product and `||…||` is the distance.
7. If `i == 0`, set `i = 1`; if `i == SAMPLES`, set `i = SAMPLES - 1`
8. Let `t1 = t0 + (i + 1) * dt` and `t0 = t0 + (i - 1) * dt`
9. Go back to step 3.

### Algorithm for distance from Bézier curve to Bézier curve

This time we have two Bézier curves, parametrised by `F(t)` and `G(t)`.

1. Let `SAMPLES = 10` for instance
2. Start with `t0 = 0`, `t1 = 1`, `s0 = 0` and `s1 = 1`
3. Let `dt = (t1 - t0) / SAMPLES`
4. Let `ds = (s1 - s0) / SAMPLES`
5. If `dt < 1e-10` (or any other accuracy condition you see fit), **algorithm is finished and answer is `F(t0)`**.
6. **IF** this is the first run of the loop:

6.1. Compute a list of `SAMPLES + 1` points on `F` (*see above*).

6.2. Compute a list of `SAMPLES + 1` points on `G`.

6.3. Find which pair of points are closest to each other.

6.4. Update `t0`, `t1`, `s0`, `s1` as seen above.
7. **ELSE**: alternatively compute a list of points on `F` **OR** a list of points on `G`, then find which point on `F` is closest to `G(s0)` and update `t0` and `t1`, **OR** which point of `G` is closest to `F(t0)` and update `s0` and `s1`.
8. Go back to step 3.

### Issues

By design, these algorithms will always converge to a local minimum. However, there is no guarantee that they will converge to the best solution. In particular, the Bézier curve algorithm isn't very good at all, and in the case of two curves being close to each other at many places you may unfortunately miss the solution by a long shot.

But as I said, before you start thinking about more robust solutions, you should first experiment with those simple ones.
> 3 votes

# Answer
1) Translate everything to one axis,so instead of needing to calculate the length of one point to, the 'line', the 'line' is, say, the Y-Axis.

Then, uh, given a bezier curve I'd say it's up to the number of control points.

If there are three, (beginning, 'control' and end) I'd do some sort of scan (say each a couple of percent and then refine between the closest ones (with say a 'binary' approach).

More points I'd try out the couple that were closest to the (translated Y-Axis).

I am sure a math-guy can give you the exact solution (in mathematics) but if you want to find the/a solution in a video game you might be better off with a slightly ok solution as the real solution might contain several answers (I'm not even talking about processing power).
> 0 votes

# Answer
Some answers from the Algorithmist blog page, which correctly finds the closest point on the given quadratic bezier curve.

Demo.
> 0 votes

# Answer
For the Bezier curve - straight line case, the most accurate way to find the answer is to do the following:

1. Transform the problem so that the straight line is always horizontal at Y=0. This is done by multiplying all the control points by an appropriate affine matrix. (I assume you are familiar with representing affine transformations of the plane with 3x3 matrices with 3 fixed entries.)
2. Inspect the Y coordinates of the control points. If they don't all have the same sign, there can be an intersection with the line. Compute the roots of the Y part of the Bezier curve. You can use any root finding method for polynomials, there are plenty of them in the literature. For example, google "convex hull marching" - this is a reasonably good method for the polynomials used in Bezier curves. Every root you find is a time value of an intersection with the line, where the distance is zero - your work is done.
3. If all Y coords have the same sign, compute the derivative of the Y part of the Bezier curve. You can ignore the X coordinates of points, since they make no difference - the target line is horizontal. Find the roots of that derivative. These are the time values at which the curve is locally closest to the line.
4. Explicitly evaluate the Bezier curve for all roots you have found in the previous step and report the root which gives the smallest distance from the line. You also need to check the endpoints - they might give a smaller distance than any root.
> 0 votes

---
Tags: mathematics, geometry, lines, beziers, curves
---


# Question
Title: Determine which face of a cube is facing the camera
I have a Cube with a unique color for each face. I made a script where I can swipe and rotate the Cube in increments of 90 degrees in each direction. what's the best way to determine which face of a the Cube is facing the camera.

# Answer
**Iterating through the faces:**

```
faceNormal[i].dot(-worldViewVector) > 0.8 //(should actually be >0.9999)

```

**If you do an if/switch to apply a rotation to the cube(or camera):**
Just update and store a value indicating the front face at the same time.

This actually works the same for non-snapping angles such as your scene view. In the orthogonal mode, the dots just happen to be convenient, namely 1,0,0,0,0,-1, so the front face is obvious. Also consider that if you happen to find the back face first, the front face is the one opposite one; a little shortcut.

**If (-worldViewVector) is always (0,0,1) (toward the user)(camera fixed, cube rotates):**
You can just apply the inverse of the cube's rotation matrix to (0,0,1) and should end up with a unit direction vector indicating the front face (relative to the initial front face). This modifies the iteration:

```
foreach(cube)
{
   thisCubesDirection = (0,0,1) * cube.RotationOnlyMatrix;
   if (thisCubesDirection.X > 0.999) ...
   else if ...
}

```
> 2 votes

---
Tags: unity, mathematics, camera, rotation
---


# Question
Title: Check for collision without any built-in collision functions
Is it possible to check for a collision between gameObjects without using the built-in functions `OnCollisionEnter`, `OnCollisionStay`, or `OnCollisionExit`? Preferably a solution without the use of raycasting.

# Answer
> 2 votes
I have looked for this before and there is no easy, built in, way to do this. What I have done is in my objects that have a need for these checks to add a list and then on enter add to the list and on exit remove from the list.

Also, if you can be more specific as to why you want to check for a collision I may be able to provide a better answer... But it will still not be a built in solution.

---
Tags: c#, unity, collision-detection
---


# Question
Title: How to modify the Unity sprite renderer (or create a custom one) that can display the sprites on the X-Z plane?
Prefix: I am NOT trying to rotate a sprite 90 degrees by it's transform, this changes what is up/down and forward/backwards for the object. I need the sprite displayed on the X-Z plane in comparison to the default X-Y plane in it's natural state in the game world with rotation transforms of 0.

I'm trying to use 2D sprites on the X-Z plane, how do I go about either modifying the built in sprite renderer to do this, or creating my own custom sprite renderer component?

# Answer
> 1 votes
You need to do this as a hierarchy. Have a main Object that you move and run all your code on, and then add the sprite as a child object and rotate the sprite object only so it aligns the way you want it to.

---
Tags: unity, 2d, sprites, rotation, axis
---


title: 2D Hidden Object Silhouette Shader

text:
# Question
Title: 2D Hidden Object Silhouette Shader
Right now I am not using any depth information in my engine, but I just found out that it would be neat to be able to render the silhouette of important game objects that are "behind" something with a shader, though I am quite at a loss how to do this in a 2D scene with little to no depth information. I will propably have to use depth information for something like that, but I am not quite sure how.

I guess the abstract concept would be:

```
zn = depth of pixel that should be rendered
zc = depth of pixel at current position in some sort of buffer
if(zn < zc)
    render pixel with a "silhouette" color
else
    render pixel with it's intended color

```

Is this a proof of concept I can follow in my next few workhours? How can I use and access stuff like the Z buffer of the current framebuffer in the shader?

As an example, I most recently saw this in Titan Souls:

Also remember that I am thinking 2D only, so application of the painter's algorithm might or might not be desirable.

EDIT: So right now, from comments and such, I got the following proof of concept:

```
activate stencil mechanism to set stencil
render obscuing objects
deactivate stencil
render scene, using painter's algorithm or depth checks to obscure
activate stencil mechanism to check weather or not something got rendered within the stencil area
render important objects again, using a different fragment shader to render pixels within the stencil as a dark shadow

```

amirite?

# Answer
**Using the stencil buffer:**

When writing:

```
dsDesc.StencilEnable = true;
dsDesc.StencilReadMask = D3D11_DEFAULT_STENCIL_READ_MASK;
dsDesc.StencilWriteMask = D3D11_DEFAULT_STENCIL_WRITE_MASK;
dsDesc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS; //Always Pass
dsDesc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_INCR; //Increment
dsDesc.FrontFace.StencilFailOp = D3D11_STENCIL_OP_KEEP; //Doesn't matter
dsDesc.FrontFace.StencilDepthFailOp = D3D11_STENCIL_OP_INCR; //Increment

```

When reading:

```
dsDesc.StencilEnable = true;
dsDesc.StencilReadMask = D3D11_DEFAULT_STENCIL_READ_MASK;
dsDesc.StencilWriteMask = D3D11_DEFAULT_STENCIL_WRITE_MASK; //Or 0 to disable all writes
dsDesc.FrontFace.StencilFunc = D3D11_COMPARISON_GREATER; //Only greather than REF
dsDesc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP; //No writes
dsDesc.FrontFace.StencilFailOp = D3D11_STENCIL_OP_KEEP; //No writes
dsDesc.FrontFace.StencilDepthFailOp = D3D11_STENCIL_OP_KEEP; //No writes

```

Render the scene as usual with the stencil buffer active, incrementing.

```
g_d3dContext->OMSetDepthStencilState(stencilWriteState, 0x00);
Draw(...);

```

Then, render a full-screen quad, using the stencil buffer as a reference to apply the pixel shader effect only to pixels with stencil(\>1).

```
g_d3dContext->OMSetDepthStencilState(stencilReadState, 0x01);

```

**If you know ahead of time, which "important objects" are behind others:**
Render them separately, and first, with the stencil active. Then disable the stencil for the remainder of the (occluding) objects. Finally, render the full-screen quad to apply the shader to pixels with stencil(\>0).

```
g_d3dContext->OMSetDepthStencilState(stencilReadState, 0x00);

```

Example usage:
> 1 votes

---
Tags: shaders, glsl, graphic-effects, jogl
---


# Question
Title: Why the size of my game increased on deploying it to Android using Unity3D?
When I deployed the game to '**Web Player**', it's size was just **2.4 MB** but when I deployed it to '**Android**', it's size got increased to **38 MB**.

Why this happened? I can't provide any more information or code.

# Answer
The web player uses a browser plugin to do its work. That means there is X amount of functionality that is already downloaded by the user before they ever download your game (tens of megabytes). On android, the game is a standalone application so has to include all the functionality needed inside of itself.
> 3 votes

---
Tags: unity, android
---


# Question
Title: Unity only rendering certian parts of 3d building model from certian angles
So I made a couple modular building sections in blender, modular in the sense that I can insert build a floor at a time. I transferred them into Unity and then I got a rendering error that I have gotten many times before. I will put the object in the game world and then certain chunks of the building will only be visible from on direction and the other it will be completely invisible. I have been having trouble with this bug for a long time and I really would like if someone could point out what's causing this problem. I will include pictures below to help show my problem.

Thanks, Nova

# Answer
> 1 votes
The second image appears to have been taken from inside the building. If so, all of the triangles are reversed and you are only seeing the faces that should be culled. Likewise, faces that should be visible are being culled.

Ordinarily, meshes are drawn from the outside-inward so, when you are inside, looking outward, the triangles that were clock-wise from the outside, now appear counter-clockwise and are culled.

Anytime you are inside of a mesh, you most-likely need to reverse the culling.

http://docs.unity3d.com/ScriptReference/Rendering.CullMode.html

---
Tags: unity, rendering, 3d-meshes
---


# Question
Title: How to create a smooth rotation with a constant angle?
I am trying to make a game where the player can only rotate to 4 angles. Something like this

I cannot use `Quaternion.Rotatetowards` because the player's position is not constant, but I don't have the problem with movement. The problem I am having is that when I use `transform.Rotate` of 90 degrees it creates a sudden rotation. I would like to have that rotation smooth. I have tried using Slerp but I don't think I quite get the syntax I need to use.

Both `Vector3.Slerp`, and `Quaternion.Slerp` interpolate between two different **positions**, when my player turns I would like him to keep his current position, and only turn his "face" towards the desired position. I would appreciate the help. Thanks.

# Answer
You simply lerp between these angles.

Here is a part of my third person character controller script, that smoothly rotates the model in the direction that it's moving:

```
Vector3 angle = Vector3.zero;
if(moveDirection.x != 0)
{
    if(moveDirection.z == 0)
    {
             if(moveDirection.x > 0) angle.y =  90;
        else if(moveDirection.x < 0) angle.y = -90;
    }
    if(moveDirection.z > 0)
    {
             if(moveDirection.x > 0) angle.y =  45;
        else if(moveDirection.x < 0) angle.y = -45;
    }
    if(moveDirection.z < 0)
    {
             if(moveDirection.x > 0) angle.y =  135;
        else if(moveDirection.x < 0) angle.y = -135;
    }
}
else if(moveDirection.z < 0) angle.y = 180;
angle.y = Mathf.LerpAngle(character.transform.localEulerAngles.y, angle.y, 10 * Time.deltaTime);
character.transform.localEulerAngles = angle;

```

This is for any of 8 possible direction, based on ASDW keys, with x axis being AD and z axis being SW. Using angle.y rotates the object on a flat 3d surface. For a 2d game you should rotate the z axis of your object.
You can make it work for 4 angles only if you remove conditions for +-45/135 degrees.

But if you want to lerp between one of 4 random angles you could make an array of angles and use LerpAngle to switch between them.
> 1 votes

---
Tags: c#, rotation
---


title: Loading Screen And Coroutines Unity

text:
# Question
Title: Loading Screen And Coroutines Unity
When I want to load another scene and show my loading screen to the user - my loading screen is a game object holding a canvas, I use coroutines, but when I type something like this: `LoadingScreen.Show ();
 Application.LoadLevel ("PlayerMenu");`

Loading screen is shown less than a second, so I wanted to use coroutines, I typed this:

```
IEnumerator LoadLevel(string levelName) {
    LoadingScreen.Show ();
    yield return new WaitForSeconds (2f);
    Application.LoadLevel (levelName);
}

```

The problem when calling the coroutine is that my LoadingScreen.Show() code is not executed, so basically I'm just waiting 2 seconds looking at the background of my current scene and then it goes to another scene, I'm confused here as to what is going on, shouldn't my LoadingScreen.Show() code be executed and then I would see the loading screen and wait 2 seconds and the next scene will appear. Anyone has an idea?

# Answer
If your level is loaded fast, but you want to show a splash screen for a while what you can do is show the splash screen at the end of one level, call LoadLevel right after and have the splash screen shown at the start of the other level.
You should have a variable saying after what time to remove the splash screen.

This way would be much more practical, because you have bigger control of how long it is shown.

Oh and the way I save variables between levels is by using a class with static variables. Because those variables don't change when you switch scenes.
> 1 votes

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


# Question
Title: Handle a canvas in a windows form application
I want to create a level editor, i've started it on XNA but finally it would be better using a WindowsFormApplication.

Here is the layout that i want to achieve:

BLUE -\> Windows form control

PURPLE -\> Canvas, handled differently (Yeah, Windows forms controls too, but not for the same use of it)

I have a problem though, how to render the Canvas in a proper way without using a thread ?

(Look at my other thread here in stackoverflow: https://stackoverflow.com/questions/29463393/access-object-from-other-thread?noredirect=1)

I thought about a timer, but it seemed to be a bad idea for me (Refreshrate).

Ideally a thread would be nice but Windows doesn't like the fact that you want to interact between thread so it's messed up to be polite.

If you know how to achieve that, well, thanks ! :)

# Answer
> 3 votes
You don't want a thread for this. It doesn't really make sense to get another thread to do timing for you, when you could just use your existing thread for that.

There's a good blog post on the available techniques here. Note the use of the XNA WinForms sample.

If you want the ticking to behave just like the real XNA, use the third method. The gist of it is: Handle the `Application.Idle` method, and sit in a loop ticking, while using win32's `PeakMessage` (via P/Invoke) to exit your loop whenever Windows needs you to respond to some other message. (Once WinForms has responded, it will call `Idle` again to re-enter your loop.)

Note that, if you have more than one `GraphicsDeviceControl`, you need to ensure there's only one handler for `Application.Idle`, which then dispatches ticks to all controls.

Finally, to play nice with the system, and to be more like XNA, check whether your application is active (ie: the foreground window). If it is inactive, call `Thread.Sleep(20)` in your idle loop.

---
Tags: c#
---


# Question
Title: Get position of currently instantiated object
I have Variable Temp which is Vector3. And i have variable next which is of type Transform. In the inespector, i have dragged an empty gameobject to "next".

In my update, i have:

```
temp=new Vector3(Random.Range (dmin, dmax), -3f, 0);
        next.position = next.position + temp;

        GameObject go = Instantiate (pillar,next.position,Quaternion.identity)as GameObject;

        next.position = go.gameObject.GetComponent<Transform> ().position;

```

when i run this, get error that object reference is not set to an instance of an object. The error is generated by the last line.

I'm just trying to instantiate an object that is at a random distance from the currently instantiated object.

How can i fix this?

# Answer
> 1 votes
try this:

```
next.position = go.transform.position;

```

# Answer
> 1 votes
It worked after i changed type of pillar to GameObject.

Also, my temp had -3f for the ycomponent. So it was getting drawn lower and lower and i couldn't see it.

---
Tags: unity
---


# Question
Title: How can I manually syncronize render calls with a monitor's refresh rate in Direct3D 9?
I have an application that utilizes Direct3D 9 to render 3D graphics. I'm trying to manually control the number of frames rendered in a given second. Here is pseudocode:

```
while( bInGame )
{
    // handle window stuff
    dispatchEvents();

    // handle d3d9 stuff
    if( !windowMessages )
    {
        // process animation
        OnD3D9FrameMove(GetElapsedTime());

        // when work is done render a frame (30 frames per second)
        while(GetElapsedTime() < 0.03333333f){ Thread.Sleep(1); }
    }
}

```

The above code is very rough but explains what I'm trying to do. I want to allow time between frames to process work( i.e. visibility, animation, etc. ). The actual code works well except for one problem. Screen anomalies occur due to rendering frames out of sync with the screen's refresh rate. The anomalies are best described as horizontal tearing, an undesirable result.

When I activate vsync while using this code the screen anomalies do not appear. However, I can't use vsync because it prevents my game loop from continuing until the frame is rendered and thus consumes the spare time that I would like to set aside for work.

How can I get around this problem? I would like to sync with the monitor using my application rather than the Direct3D API. This way I can control the work flow...Any ideas?

# Answer
> 1 votes
```
fixedTimeStep = false; //wide-open throttle
vsync = false;         //wide-open throttle

void OnD3D9FrameMove(float elapsedSeconds)
{
   Update(elapsedSeconds); //every frame
   static float oneFrameTime = (1.0f / 30);
   static float renderTime;
   renderTime += elapsedSeconds;
   if (renderTime >= oneFrameTime)
   {
      Render(renderTime); //All at once; skip animation frames after lag
      renderTime = 0;
      //Render(oneFrameTime); //Render exactly one frame's-worth of time
      //renderTime -= oneFrameTime; //But will render every frame to get caught up
   }
}

```

And avoid sleep(), obviously.

---
Tags: c++, directx, directx9, screen
---


title: Framerate is affecting speed of object

text:
# Question
Title: Framerate is affecting speed of object
I'm experimenting with building a game engine from scratch in Java, and I have a couple questions. My main game loop looks like this:

```
        int FPS = 60;
        while(isRunning){
            /* Current time, before frame update */
            long time = System.currentTimeMillis();
            update();
            draw();
            /* How long each frame should last - time it took for one frame */
            long delay = (1000 / FPS) - (System.currentTimeMillis() - time);
            if(delay > 0){
                try{
                    Thread.sleep(delay);
                }catch(Exception e){};
            }
        }

```

As you can see, I've set the framerate at 60FPS, which is used in the `delay` calculation. The delay makes sure that each frame takes the same amount of time before rendering the next. In my `update()` function I do `x++` which increases the horizontal value of a graphics object I draw with the following:

`bbg.drawOval(x,40,20,20);`

What confuses me is the speed. when I set `FPS` to 150, the rendered circle goes across the speed really fast, while setting the `FPS` to 30 moves across the screen at half the speed. Doesn't framerate just affect the "smoothness" of the rendering and not the speed of objects being rendered? I think I'm missing a big part, I'd love some clarification.

# Answer
> 21 votes
You're moving the circle by one pixel per frame. It should not come as a big surprise that, if your rendering loop runs at 30 FPS, your circle will move 30 at pixels per second.

You basically have three possible ways to deal with this issue:

1. **Just pick one frame rate and stick to it.** That's what a lot of old-school games did — they'd run at a fixed rate of 50 or 60 FPS, usually synced to the screen refresh rate, and just design their game logic to do everything necessary within that fixed time interval. If, for some reason, that didn't happen, the game would just have to skip a frame (or possibly crash), effectively slowing both the drawing and the game physics to half speed.

In particular, games that used features like hardware sprite collision detection pretty much *had to* work like this, because their game logic was inextricably tied to the rendering, which was done in hardware at a fixed rate.
2. **Use a variable timestep for your game physics.** Basically, this means rewriting your game loop to look something like this:

```
long lastTime = System.currentTimeMillis();
while (isRunning) {
    long time = System.currentTimeMillis();
    float timestep = 0.001 * (time - lastTime);  // in seconds
    if (timestep <= 0 || timestep > 1.0) {
        timestep = 0.001;  // avoid absurd time steps
    }
    update(timestep);
    draw();
    // ... sleep until next frame ...
    lastTime = time;
}

```

and, inside `update()`, adjusting the physics formulas to account for the variable timestep, e.g. like this:

```
speed += timestep * acceleration;
position += timestep * (speed - 0.5 * timestep * acceleration);

```

One problem with this method is that it can be tricky to keep the physics (mostly) independent of the timestep; you really don't want the distance players can jump to depend on their frame rate. The formula I showed above works nicely for constant acceleration, e.g. under gravity (and the one in the linked post does pretty well even if the acceleration varies over time), but even with the most perfect possible physics formulas, working with floats is likely to produce a bit of "numerical noise" that, in particular, can make exact replays impossible. If that's something you think you might want, you may wish to prefer the other methods.
3. **Decouple the update and draw steps.** Here, the idea is that you update your game state using a fixed timestep, but run a varying number of updates between each frame. That is, your game loop might look something like this:

```
long lastTime = System.currentTimeMillis();
while (isRunning) {
    long time = System.currentTimeMillis();
    if (time - lastTime > 1000) {
        lastTime = time;  // we're too far behind, catch up
    }
    int updatesNeeded = (time - lastTime) / updateInterval;
    for (int i = 0; i < updatesNeeded; i++) {
        update();
        lastTime += updateInterval;
    }
    draw();
    // ... sleep until next frame ...
}

```

To make the perceived movement smoother, you may also wish to have your `draw()` method interpolate things like object positions smoothly between the previous and next game states. This means you need to pass the correct interpolation offset to the `draw()` method, e.g. like this:

```
    int remainder = (time - lastTime) % updateInterval;
    draw( (float)remainder / updateInterval );  // scale to 0.0 - 1.0

```

You would also need to have your `update()` method actually calculate the game state one step ahead (or possibly several, if you wish to do higher-order spline interpolation), and have it save previous object positions before updating them, so that the `draw()` method can interpolate between them. (It's also possible to just extrapolate predicted positions based on object velocities and accelerations, but this can look jerky especially if objects move in complicated ways, causing the predictions to often fail.)

One advantage of interpolating is that, for some types of games, it can allow you to significantly reduce the game logic update rate, while still maintaining an illusion of smooth motion. For example, you might be able to update your game state only, say, 5 times per second, while still drawing 30 to 60 interpolated frames per second. In you do this, you may also wish to consider interleaving your game logic with the drawing (i.e. having a parameter to your `update()` method that tells it to only run *x*% of a full update before returning), and/or running the game physics / logic and the rendering code in separate threads (beware of synchronization glitches!).

Of course, it's also possible to combine these methods in various ways. For example, in a client–server multiplayer game, you might have the server (which does not need to draw anything) run its updates at a fixed timestep (for consistent physics and exact replayability), while having the client do predictive updates (to be overridden by the server, in case of any disagreement) at a variable timestep for better performance. It's also possible to usefully mix interpolation and variable-timestep updates; for example, in the client–server scenario just described, there's really not much point in having the client use shorter update timesteps than the server, so you can set a lower limit on the client timestep, and interpolate in the drawing stage to allow higher FPS.

(Edit: Added code to avoid absurd update intervals / counts, in case, say, the computer is temporarily suspended or otherwise frozen for more than a second while the game loop is running. Thanks to Mooing Duck for reminding me about the need for that.)

# Answer
> 7 votes
Your code is currently running each time a frame renders. If the frame rate is higher or lower than your specified frame rate, your results would change as the updates don't have the same timing.

To solve this, you should refer to Delta Timing.

> The purpose of Delta Timing is to eliminate the effects of lag on computers that try to handle complex graphics or a lot of code, by adding up to the speed of objects so that they will eventually move at the same speed, regardless of lag.

To do this:

> It is done by calling a timer every frame per second that holds the time between now and last call in milliseconds.

You would need to then multiply the delta time by the value you want to change by time. For example:

```
distanceTravelledSinceLastFrame = Speed * DeltaTime

```

# Answer
> 5 votes
That's because you limit your frame rate, but you only do one update per frame. So let's assume the game runs at the target 60 fps, you get 60 logic updates per second. If the frame rate drops to 15 fps, you'd only have 15 logic updates per second.

Instead, try accumulating the frame time passed so far and then update your game logic once for every given timespan that passed, e.g. to run your logic at 100 fps you'd run the update once for every 10 ms accumulated (and subtract those from the counter).

Add an alternative (better for visuals) update your logic based on the time passed.

---
Tags: java, frame-rate, double-buffering
---


# Question
Title: Given a ray-intersect position on morphed mesh, how to compute that position at each morph target?
I'm working on an annotation system that allows a user to click on a mesh to attach a pin with a label hanging off it.

It must be possible to pin an annotation on an object that's being morphed with keyframe morph targets, so that the pin will move with the surface of the mesh.

It's mainly pretty simple, where I do a ray-intersect to find the pin position on the mesh, for the shape of the mesh at the current time within the morph targets.

Then I have, for that time instance:

1. the 3D coordinates of the pin
2. the triangle (ie. the indices and vertex positions of the triangle's vertices) that the pin is within
3. the time instant

Now, if I had the 3D coordinates of the pin at each of the morph's targets, then I can simply tween the pin position, to animate it in synch with the morph.

However, the challenge I is to somehow compute the position of the pin at each of the morph targets, from these three pieces of information.

Intuitively, it seems to be a matter of somehow finding some sort of coefficient (or set of coefficients) that indicates the pin's position relative to the vertices of its enclosing triangle, at the instant within the morph sequence that we attach the pin.

Then, for each other target within the morph sequence, given the morphed positions of the triangle vertices, which could be anything, somehow use the coefficient(s) to find the updated pin position, relative to the triangle's current vertex positions.

Anybody got any ideas? Math pointers etc?

cheers!

# Answer
You have the position of the pin and a triangle index. Compute the barycentric coordinates of the point on the triangle, with the triangle vertices in the tweened position. These barycentric coordinates can then be used to compute the position of the pin in any other tweened position by taking the triangle vertices in that new position and computing the point as:

```
p_transformed = tri.p0 + u * (tri.p1 - tri.p0) + v * (tri.p2 - tri.p0)

```

where tri is the transformed triangle, `u`,`v` are the calculated barycentric coordinates, and `p_transformed` is the tweened pin position. Some raycast algorithms will directly give you the barycentric (also called UV!!) coordinates, but if not you will need to calculate them from the position and (transformed) vertices using this answer.
> 1 votes

---
Tags: 3d, animation, raycasting
---


# Question
Title: Problems with Rotation Matrices on Certain Axes
Here is what my rotation matrix looks like:

```
public Matrix4f initRotation(float x, float y, float z)
{
    Matrix4f rx = new Matrix4f();
    Matrix4f ry = new Matrix4f();
    Matrix4f rz = new Matrix4f();

    x = (float)Math.toRadians(x);
    y = (float)Math.toRadians(y);
    z = (float)Math.toRadians(z);

    rz.m[0][0] = (float)Math.cos(z);rz.m[0][1] = -(float)Math.sin(z);rz.m[0][2] = 0;                rz.m[0][3] = 0;
    rz.m[1][0] = (float)Math.sin(z);rz.m[1][1] = (float)Math.cos(z);rz.m[1][2] = 0;                 rz.m[1][3] = 0;
    rz.m[2][0] = 0;                 rz.m[2][1] = 0;                 rz.m[2][2] = 1;                 rz.m[2][3] = 0;
    rz.m[3][0] = 0;                 rz.m[3][1] = 0;                 rz.m[3][2] = 0;                 rz.m[3][3] = 1;

    rx.m[0][0] = 1;                 rx.m[0][1] = 0;                 rx.m[0][2] = 0;                 rx.m[0][3] = 0;
    rx.m[1][0] = 0;                 rx.m[1][1] = (float)Math.cos(x);rx.m[1][2] = -(float)Math.sin(x);rx.m[1][3] = 0;
    rx.m[2][0] = 0;                 rx.m[2][1] = (float)Math.sin(x);rx.m[2][2] = (float)Math.cos(x);rx.m[2][3] = 0;
    rx.m[3][0] = 0;                 rx.m[3][1] = 0;                 rx.m[3][2] = 0;                 rx.m[3][3] = 1;

    ry.m[0][0] = (float)Math.cos(y);ry.m[0][1] = 0;                 ry.m[0][2] = -(float)Math.sin(y);ry.m[0][3] = 0;
    ry.m[1][0] = 0;                 ry.m[1][1] = 1;                 ry.m[1][2] = 0;                 ry.m[1][3] = 0;
    ry.m[2][0] = (float)Math.sin(y);ry.m[2][1] = 0;                 ry.m[2][2] = (float)Math.cos(y);ry.m[2][3] = 0;
    ry.m[3][0] = 0;                 ry.m[3][1] = 0;                 ry.m[3][2] = 0;                 ry.m[3][3] = 1;

    m = rz.mult(ry.mult(rx)).getM();

    return this;
}

```

And here is how I've been implementing it for tests (using default orthographic perspective):

public class Renderer {

```
private WorldMesh mesh;
private Mesh _mesh;

private Matrix4f transform;

private Shader shader;

public Renderer(){

//Setup Meshes

    mesh = new WorldMesh();

    _mesh = ResLoader.loadMesh("pyramid.obj");

    mesh.addToBuffers(_mesh);

//setup Shader

    shader = new Shader();

    shader.addVertexShader(ResLoader.loadShader("basicVertex.vs"));
    shader.addFragmentShader(ResLoader.loadShader("basicFragment.fs"));
    shader.compileShader();

    shader.addUniform("transformation");

//temporary transformation matrix

    Matrix4f tran = new Matrix4f().initTranslation(0, 0, 0);
    Matrix4f rot = new Matrix4f().initRotation(0, 0, 0);     //problem is definitely with the rotation matrix;
    Matrix4f scale = new Matrix4f().initScale(1, 1, 1);

    transform = tran.mult(rot.mult(scale));

}

public void update(){}

public void render(){

    RenderUtils.clearScreen();

    shader.setUniform("transformation", transform);

    shader.bind();

    mesh.draw(true);
}

```

}

and finally here is my vertex shader:

```
#version 330

layout (location = 0) in vec3 position;

uniform mat4 transformation;

void main(){

    gl_Position = transformation * vec4(position, 1.0);
}

```

The problem is that setting a rotation on any other axis other than Z (for some reason z axis rotation is working fine) does not function properly. An X axis rotation seems to be doing both an x and y rotation at the same time, causing a weird stretching affect. A Y axis rotation causes the mesh to completely disappear.

The funny thing is that I've used this code over and over again and some projects don't give me a problem.

The order of multiplication seems in order, and I made sure that OpenGL knows to transpose the matrix I give it when setting the uniform.

Any ideas as to what could be causing the x and y axis rotations to completely fail?

# Answer
> 1 votes
Ok the problem turned out to be a typo in the way meshes were being loaded. It caused the Z terms of each vertex to be resolved to the X term... If anyone comes across this and wants to know here is my properly working mesh loader method.

```
public static Mesh loadMesh(String fileName){

    String[] splitArray = fileName.split("\\.");
    String extension = splitArray[splitArray.length -1];

    if(!extension.equals("obj")){
        System.err.println("Model file type not supported: " + extension);
        System.exit(1);
    }

    ArrayList<Vertex> vertices = new ArrayList<Vertex>();
    ArrayList<Integer> indices = new ArrayList<Integer>();

    BufferedReader modelReader = null;

    try{

        modelReader = new BufferedReader(new FileReader("./res/models/" + fileName));
        String line;

        while((line = modelReader.readLine()) != null){
            String[] tokens = line.split(" ");
            tokens = Utils.removeEmptyStrings(tokens);

            if((tokens.length == 0) || tokens[0].equals("#")){
                continue;
            }
            else if (tokens[0].equals("v")){
                vertices.add(new Vertex(new Vector3f(Float.valueOf(tokens[1]),
                                                     Float.valueOf(tokens[2]),
                                                     Float.valueOf(tokens[3]))));
            }
            else if (tokens[0].equals("f")){
                indices.add(Integer.parseInt(tokens[1]) -1);
                indices.add(Integer.parseInt(tokens[2]) -1);
                indices.add(Integer.parseInt(tokens[3]) -1);
            }

        }

        modelReader.close();

    }catch(Exception e){
        e.printStackTrace();
        System.out.println("Model Failed to Load" + fileName);
        System.exit(1);
    }

    Vertex[] vertexData = new Vertex[vertices.size()];
    vertices.toArray(vertexData);

    Integer[] indexData = new Integer[indices.size()];
    indices.toArray(indexData);

    Mesh res = new Mesh(vertexData, Utils.toIntArray(indexData));

    return res;
}

```

# Answer
> 0 votes
Can't comment yet so I post it as an answer, but it appears that you should have a `-` at `ry.m[2][0]` and `+` at `ry.m[0][2]` when looking at the 3d rotation matrices. Does not make a difference though for an x-only rotation as both of these evaluate to 0.

---
Tags: opengl, glsl, rotation, matrix
---


title: Blending vs Texture Sampling

text:
# Question
Title: Blending vs Texture Sampling
Lets say I want to blend two textures together:

* A texture containing the result of the SSAO calculation.
* A texture containing the rendered scene.

I could do it in two ways:

1. Use a shader that samples both the SSAO and scene textures, blends them together and outputs the final color to a render target.
2. Render to the texture containing the scene and use a blending mode to blend the SSAO texture on top of it. Only the SSAO texture will be sampled inside the shader.

Is it possible to give a general answer about which version is faster, or is it highly hardware dependent?

# Answer
> 2 votes
It is actually a very interesting question. Initially I thought that a definitive answer does not even exist; after all, it is only certain that speed difference between these methods deviates based on hardware and driver version, just like it does for every other thing.

But what exactly makes that speed deviation? Lets look at the difference between old-fashioned fixed-function blending and custom fragment program blending. Maybe some kind of conclusion will arise.

**Rough comparison**

Fixed-function blending uses one of the predefined equations to mix fragment color outputs with the framebuffer color values:

1. render first texture to the framebuffer;
2. set blending function and parameters for a simple alpha blending;
3. render second texture to the framebuffer. Note that fixed-function blending is performed directly on the framebuffer, sampling it and modifying it at the same time.

Shader-based blending uses custom fragment program to turn a fragment into colors and a depth value:

1. render first texture to a previously allocated texture buffer;
2. change shader program to one with custom blending of any complexity;
3. render second texture to the framebuffer while reading texture buffer from step 1.

**What gives?**

It may seem that fixed-function blending should be faster, due to GPU's special hardware for simple blending, direct framebuffer reads and lack of an additional memory buffer.

However, nowadays video memory is usually abundant, and hardware is really optimized for customizable pipeline, so there is no gain on read speed. GPU's speed for simple blending is highly hardware dependent, but so is the shaders performance.

There is one important detail still missing: **framebuffer blending has its own stage in rendering pipeline** — it is independent from fragment shaders. Which means fixed-function blending can be generally considered being "always faster" simply because it can perform blending operations while custom fragment shader program is processing later fragments.

This also means that **fixed-function blending contributes to your ROP count and, consequently, framebuffer bandwidth**. And **fragment shaders contribute to your fragment shading costs**. Frame-buffer bandwidth is a function of GPU memory clock, and fragment-shading speed is a function of the GPU core clock.

**So in case of performance problems with two concerned techniques it is possible to be ROP-bound or fragment-shading-bound.** (Actually, there are other possible resource bounds, like limit on vertex transformations, but these does not matter in context of the question.)

Just for the sake of completeness and possible effects on the texture sampling performance, it is also worth noting that **texture bandwidth is consumed any time a texture fetch request goes out to memory**. Texture bandwidth is also a function of GPU memory clock.

**Conclusion**

In conclusion, use blending for simple blending operations or when you need to blend something with entire framebuffer, and you are not ROP-bound. Use texture sampling when needed or when it suits your code better, and you are not fragment-shading-bound.

Obviously, if you are texture-bandwidth-bound, it is better to avoid unnecessary texture samples, so framebuffer-based blending is preferrable.

**Your specific case**

As long as you are not bound on those three things mentioned earlier, relative speed of your two methods should be identical. #1 would be easier to tweak and fix, in my opinion.

Also, I have not seen your code, but generally SSAO should be applied only to ambient part of lighting, so blending it over the final scene sounds wrong. All the more reason to sample SSAO texture in your lighting shader.

# Answer
> -1 votes
The standard answer to "which is faster" is "profile it and see". Because everything varies a lot by platform, coding pattern, &c. (Method 2, with blending mode, might have direct hardware support... but you never know. Modern cards, behind the scenes, might do exactly the same work as you'd do with your shader.)

Method 1 might, overall, "block" for three draws (color, ssao, combine), while method 2 only waits on two draw (color, ssao-with-blendmode). But how this affects the performance would need to be measured.

This is the sort of thing you'll do once per frame, probably, so it won't be the most important thing to optimize. Either is almost certainly fine.

Using method 1 will give you more flexibility for how to combine the two screens, since you do all the math in your shader. This might be even more valuable to you than counting cycles, as it lets you control the look of your product.

---
Tags: opengl, textures, glsl
---


title: Implementing pausing functionality

text:
# Question
Title: Implementing pausing functionality
I'm working in LWJGL and trying to implement pausing when the user presses the 'P' key. Thus far I have this:

```
boolean gamePaused = false;
    while(!Display.isCloseRequested()){

        if(Keyboard.isKeyDown(Keyboard.KEY_P) && !gamePaused)
            gamePaused = true;
        if(Keyboard.isKeyDown(Keyboard.KEY_P) && gamePaused)
            gamePaused = false;

        if(gamePaused){
            while(true){
                System.out.println("Game paused.");
                if(Keyboard.isKeyDown(Keyboard.KEY_P)){
                    gamePaused = false;
                    break;
                }
            }
        }
        //...game logic
    }

```

My problem is that it continues playing even when I press the P key.

# Answer
> 8 votes
Look at your if statements. You set paused to true, then the next statement evaluates true (because there's no way to not press p for a short enough time and you just set paused to true), and it sets it to false. Try:

```
if(Keyboard.isKeyDown(Keyboard.KEY_P) && !gamePaused) {
    gamePaused = true;
} else if(Keyboard.isKeyDown(Keyboard.KEY_P) && gamePaused) {
    gamePaused = false;
}

```

**EDIT** I like Gustavo's suggestion, it's much cleaner and is actually what I do with my booleans:

```
if(Keyboard.isKeyDown(Keyboard.KEY_P))
    gamePaused = !gamePaused;

```

# Answer
> 3 votes
The point made by Byte56 is true (you need an else if or this won't work), but you should also check that the key was not down last frame before doing anything with it. So something like:

```
if(Keyboard.isKeyDown(Keyboard.KEY_P) && pWasNotDown) {
    gamePaused = true;
}

```

Your inner loop is confusing and makes it all more complicated, too. You should really just say

```
if(!gamePaused) {
// game logic
}

```

If the game is paused, the code will just skip over that part to the end of the big while loop. At the end of that loop, set

```
pWasNotDown = Keyboard.isKeyDown(Keyboard.KEY_P)

```

You'll come back to the beginning of your while loop, and then the variable will be properly set to ignore isKeyDown the next frame.

This is a problem that comes up with input a lot. There are tons of input events that you only want to occur once per button/key press, and for each of those you'll have to do logic like this. Ideally, you would extract this all into an inputmanager so you can say InputManager.isKeyDown(KEY\_P) && !InputManager.wasKeyDown(KEY\_P) (or better yet, InputManager.wasJustPressed(KEY\_P)). But that's outside the scope of this question, and just something to think about as you continue developing your game.

# Answer
> 1 votes
I'd like to talk about an alternative that doesn't seem applicable from your example, but is actually very common and should be worth sharing - It's how I have always implement pausing in my games.

Have you ever used a **stack based game state management system** such as this to divide your game into states or screens? Besides being extremely useful at organizing and transitioning between multiple states (e.g. title screen, options screen, game screen, scores screen) it also makes pausing your game extremely easy - *just push a new pause state on top of your current one*.

For instance, here's what such a state could look like (in pseudocode):

```
class PauseState : GameState
{
    void Update()
    {
        if(OnKeyDown("P")) PopState();
    }

    void void Draw()
    {
        // Draw fullscreen black quad at 50% opacity
        // Draw "Pause" message in the middle of the screen
    }
}

```

And afterwards you could pause your game from *any* state just by doing:

```
if(OnKeyDown("P")) PushState(new PauseState());

```

Just set up your state manager so that it calls `Draw` on all states on the stack, but only calls `Update` on the topmost state. *That's the most important bit*.

# Answer
> 1 votes
I managed to implement a pause funcionality that works perfectly well in my game, based on this tutorial:

1. Create a `volatile boolean` variable in `StartingClass`

```
private volatile boolean isPaused = false;

```
2. Inside the `run()` method, use `wait()` surrounded by a try-catch.

```
// GAME IS PAUSED

try {
    if (isPaused) {
        synchronized (this) {
            while (isPaused) {
                wait();
            }
        }
    }
} catch (InterruptedException e) {
    e.printStackTrace();
}

```
3. Outside `run()`, create a new method `resumeGame()`

```
public synchronized void resumeGame() {
    isPaused = false;
    notify();
}

```
4. Inside `Keypressed`, define the key to pause and resume. (the `p`-key in this example).

```
case KeyEvent.VK_P:

    if (isPaused == false) {
        isPaused = true;
    } else {
        resumeGame();
    }
    break;

```

# Answer
> 0 votes
use isKeyPressed instead, that way, holding down the "p" button for a very small time won't re-trigger the if statement.

# Answer
> 0 votes
I'm not quite sure how to do this in standard Java, but in LWJGL I made an extremely simple method to check if the game is paused or not. Also, instead of having the gamePaused as a boolean it could be an enum.

```
 while(Keyboard.next()){
        if(Keyboard.getEventKeyState()){
            switch(Keyboard.getEventKey()){

            case Keyboard.KEY_P:
                gamePaused = !gamePaused;
                System.out.println(gamePaused);
            }
        }

```

I suggest looking up some ways people implemented gamestates into their games, so that way you can have a title screen and a menu (pause screen).

# Answer
> -1 votes
tHere's how I did it:

```
while (true) {
  if (gamePause == false) {
    // Game logic here...
  }
}

```

edit: I believe your problem is caused by pause check. You can use this to toggle it false or true:

```
gamePause = !gamePause;

```

I use key listener and have no experience with the command you are using for keys but i can say that you don't need to check for the value of the gamePause. Just toggle the gamePause whenever the p key is pressed.

edit 2: You first check for the pause then start the loop. Once the loop starts there is no way for it to check it again. My suggestion is to put the boolean check (if gamePause == false) inside of the loop.

---
Tags: java, input, lwjgl
---


# Question
Title: Unity skips menu screen and goes to next scene
I am using Unity 4.6.1 and I am working on a game project. I created a JS script with *Application.LoadLevel* to go to the next scene. Here is my code for OnGUI:

> function OnGUI () {
>
> {
>
> Application.LoadLevel ("Level1");
>
> }
>
> }

When I tested the game the first time, everything worked fine, but the second time, it shows the menu for a few seconds and goes directly to the first level. I did the same thing with another scene and another JS script then changed my build settings to see if that would help. It did the same thing like the first JS script. How can I fix this so that the level loads then the player presses a button instead of it loading immediately?

# Answer
You may want to create a button for the script.

```
void OnGUI() {
    if (GUI.Button(new Rect(10, 10, 150, 100), "Go to Level1"))
        Application.LoadLevel ("Level1");

}

```

For more information about the GUI scripting, check this out: http://docs.unity3d.com/Manual/gui-Basics.html
> 3 votes

---
Tags: unity, 3d, javascript
---


# Question
Title: How do I calculate force from collision between 2 rigidbodies in 2D?
I have a physics engine based on the **Game Physics Engine Development** by Ian Millington. In chapter 7.1.1, it provides the formula:

V = (pA.Velocity - pB.Velocity) * (pA - pB).normalized

where V is the resulting closing velocity and pA and pB are the colliding bodies, and the * operator is multiplication between the values of the same position in the vector(i.e. vA * vB = new vector (vA.x * vB.x, vA.y * vB.y).

This work only if the normalized unit vector direction has both positive values.

I'm also having trouble with getting units to not apply extreme amount of force when a unit is inside another, for example, when spawning 2 units on the same position. I'd like to have the effect SC2 has when 2 units overlap where they shift apart from each other instead of pushing each other very far away.

Currently, I have mass and velocity implemented for my rigidbodies and applying a force modifies the velocity by force/mass.

In summary, what I'm asking is how do I resolve collisions in a semi-realistic way?

# Answer
> 0 votes
I think you've misinterpreted the formula.

You should review the *Section 2.1.7 - The Scalar Product*. The dot (·) represents a dot product (or scalar product (please use one of these terms because it's what it is)).

The scalar product is defined like this: with vectors a and b, and scalar value s,

s = a · b = axbx \+ ayby

And, as defined, it gives a scalar, not a vector.

---

The 'explosion' you see when two units spawn at the same location is a normal behaviour with collision engines.

To try to avoid this situation, you can try and limit the maximum distance each unit can travel each frame.

---

**Edit:**

I'm not sure you'd want to write a whole physics engine from scratch, as it's one of the most complex parts of a game. I would suggest you to learn and use one that is already written for your target platform if you need that. Re-writing the wheel is often a waste of time when it's not required.

You can take a look here to find one that *seems* like a good start.

You have only vaguely stated your requirements so the question *how do I resolve collisions in a semi-realistic way?* is too vague to be given a good answer.

---
Tags: collision-resolution, rts, physics
---