title: Segmentation fault adding SDL_Surface

text:
# Question
Title: Segmentation fault adding SDL_Surface
I'm trying to add a new SDL\_Surface to my whack-a-mole clone code but even if I set it to null it wont let me.

game.h

```
#include<SDL2/SDL.h>
#include<SDL2/SDL_image.h>
#include<string>
 #include"diglet.h"
#include <list>

class Game{

public:
    SDL_Window  * window = NULL;
    SDL_Surface * screen = NULL;
    SDL_Surface * background = NULL;
    SDL_Surface * mallet = NULL;
    //SDL_Surface * winS = NULL;//this is the part that seg-faults

    SDL_Rect * malletREct;

    Game();
    int execute();

private:
    bool quit;

    static const int SCREEN_H = 250;
    static const int SCREEN_W = 500;
    SDL_Surface * loadSurface(std::string path);

    bool init();
    bool load();
    void cleanup();
    void loop();
    void renderMallet();
    void renderbg();
    void renderBadies(Diglet dig);
    void evenst(SDL_Event &e, Diglet dig[]);
    void close();

};

```

I havent even added it to the .cpp file yet it causes the seg-fault

game.cpp

```
Game::Game(){
}

//render game graphics
void Game::renderMallet(){
malletREct->h = 70;
malletREct->w = 50;
SDL_BlitSurface(mallet,NULL,screen,malletREct);

}

void Game::renderbg(){
    SDL_BlitSurface(background,NULL,screen,NULL);
}

//load game graphics
bool Game::load(){
    bool success = true;
    background = loadSurface("IMG/gameBoard.gif");
    if(background ==NULL){
        printf("unable to load background");
        success = false;
    }

    mallet = loadSurface("IMG/mallet1.png");
    if(mallet == NULL){
        printf("unable to load mallet");
        success = false;
    }
    /*winS=loadSurface("IMG/win.png");
    if(winS ==NULL){
         printf("unable to load mallet");
        success = false;
    }*/
    return success;

}

//load a surface
SDL_Surface * Game::loadSurface(std::string path){
SDL_Surface *loader = NULL;
    loader = IMG_Load(path.c_str());
    if(loader==NULL){
        printf("Unable to load surface %s ",path.c_str());
    }
    return loader;
}
//initiate game
bool Game::init(){
    bool success = true;
    if(SDL_Init(SDL_INIT_VIDEO)<0){
        printf("Unable to start video SDL_ERROR \n%s\n",SDL_GetError());
        success = false;
    }
    else{
        window = SDL_CreateWindow("MOLE BASH!!",
        SDL_WINDOWPOS_CENTERED,
        SDL_WINDOWPOS_CENTERED,
        SCREEN_W,SCREEN_H,
        SDL_WINDOW_SHOWN
        );
        if(window==NULL){
            printf("Unable to create window SDL_ERROR: \n%s\n",SDL_GetError());
            success = false;
        }
        else{
            screen = SDL_GetWindowSurface(window);
            if(screen == NULL){
                printf("Unable to load screen SDL_ERROR:\n%s\n",SDL_GetError());
                success = false;
            }
            else{

            }
        }
    }
    return success;
}

void Game::evenst(SDL_Event &e,Diglet dig[]){
     if(e.type ==SDL_QUIT){
        quit =true;
     }

     if(e.type == SDL_MOUSEMOTION){
        malletREct->x = e.motion.x-27;
        malletREct->y =e.motion.y-20;
     }
     if(e.type == SDL_MOUSEBUTTONDOWN){
        for(int i = 0 ; i < 5; i++){
            int width = dig[i].myRect.w + dig[i].myRect.x;
            int height = dig[i].myRect.h + dig[i].myRect.y;
            if(malletREct->x >= dig[i].myRect.x){
                if(malletREct->x<= width){
                    if(malletREct->y >= dig[i].myRect.y){
                        if(malletREct->y <= height){
                            dig[i].die();
                        }
                    }
                }
            }
        }
     }
}

void Game::close(){
    SDL_FreeSurface(mallet);

    mallet = NULL;
    SDL_FreeSurface(background);
    background = NULL;
    SDL_FreeSurface(screen);
    screen = NULL;
    SDL_DestroyWindow(window);
    window = NULL;
    SDL_Quit();
 }

 void Game::renderBadies(Diglet dig){
    dig.renderMe(screen);
    //printf("rendering diglet");
 }

int Game::execute(){
    bool win;

    if(!init()){
       printf("unable to initialize");
    }
    else{
        printf("initialized");
        Diglet dig [5]= {Diglet(60,65),Diglet(75,140),Diglet(170,70),Diglet(270,70),Diglet(210,140)};
        if(!load()){
            printf("unable to load");
        }
        else{
            printf("loaded");
            quit = false;
            SDL_Event e;
            while(!quit){
                SDL_ShowCursor(0);
                while(SDL_PollEvent(&e)!=0){
                   evenst(e,dig);
                }
                renderbg();
                for(int i = 0; i< 5;i++){
                    renderBadies(dig[i]);
                }
                renderMallet();
                win=true;
                for(int j = 0; j< 5;j++){
                    if(dig[j].alive ){
                         win=false;
                        printf("still alive\n");
                    }

                }
                 SDL_UpdateWindowSurface(window);
                 if(win){
                    quit= true;
                 }
            }
        }
    }
    close();
    return 0;
}

```

# Answer
By debugging the code I discovered that the malletRect * I created somehow was causing seg-faults, thaks everypne for your help. what I did was change the malletRect to a non pointer.
> 1 votes

# Answer
Since you're using SDL\_image, you should also be initialising it with IMG\_Init(). Depending on how you use it, your initialisation code might be:

```
if (!IMG_Init(IMG_INIT_JPG | IMG_INIT_PNG))
    {
        cerr << IMG_GetError() << endl;
    }

```

Other than that, it's not visibly clear what's wrong with the program unless you isolate the problem yourself with breakpoints. At first sight, you're not using winS, and one must ask what it is for.
> 0 votes

---
Tags: c++, sdl, sdl2
---


# Question
Title: What is the advantage of OpenGL's direct state access mechanism?
I've been reading about OpenGL 4.5 Direct State Access (DSA) at opengl.org and not sure if I'm getting it right.

It seems to imply, that the old way is less efficient:

```
glBind(something)
glSetA(..)
glSetB(..)
glSetC(..)

```

than the new way:

```
glSetA(something, ..)
glSetB(something, ..)
glSetC(something, ..)

```

From the looks of it now each `glSet` has to include `glBind(something)` inside of it and if OpenGL still being a state-machine cannot take advantage of streamed changes applied to a single `something`.

Please explain the reasoning behind and advantages of the new DSA.

# Answer
> From the looks of it now each glSet has to include glBind(something) inside of it

Not exactly. It's the other way around, as described several paragraphs below.

Even if it were true, remember that GL commands from the client app to the GL server (aka driver) have a lot of dispatch overhead compared to a regular function call. Even if we assume that the DSA functions are just wrappers around existing functions, they're wrappers that live inside the GL server and hence can have (a little) less overhead.

> if OpenGL still being a state-machine cannot take advantage of streamed changes applied to a single something.

GPUs aren't state machines. The GL state machine interface is an emulation that wraps DSA-like driver internals, not the other way around.

Removing one layer of wrapping - a layer that requires an excessive number of calls into the GL server - is clearly a win, even if a small one.

The state machine approach also doesn't make a ton of sense when dealing with multiple threads; GL is still terrible in this use case but drivers often use threads behind the scenes, and a state machine requires a lot of thread synchronization or really fancy parallel algorithms/constructs to make things work reliably.

The DSA extension continues to phrase its operation in terms of state changes because it is, after all, an extension to an existing state-based document and not an entirely new API, so it had to be ready to plug in to the existing GL specification document's language and terminology. Even if that existing language is pretty terribly suited to its job as a modern graphics hardware API.

> Please explain the reasoning behind and advantages of the new DSA.

The biggest reasoning is that the old way was a pain. It made it very difficult to compose libraries together that might each modify or rely on GL state. It made it difficult to efficiently wrap the GL API in an object-oriented or functional style due to its deep procedural state management roots, which made wrapping the API in various non-C languages difficult and also made it difficult to provide efficient graphics device wrappers that abstract OpenGL from Direct3D.

Second was the procedural state-machine API overhead, as described previously.

Third, the DSA functions changed semantics where appropriate from the old APIs that allowed for improved efficiency. Things that were previously mutable were made immutable, for instance, which removes a lot of book-keeping code from the GL server. Calls by the application can be dispatched to the hardware or validated sooner (or in more parallel fashions) when the GL server doesn't have to deal with mutable objects.

--

Additional justification and explanation is given in the EXT\_direct\_state\_access extension specification.

--

Hardware changes that are relevant to the API design are rather numerous.

Remember that OpenGL dates back to 1991. The target hardware wasn't consumer-grade graphics cards (those didn't exist) but big CAD workstations and the like. The hardware of that era had very different performance envelopes than today; multi-threading was rarer, memory buses and CPUs had less of a speed gap, and the GPU did little more than fixed-function triangle rendering.

More and more fixed-function features were added. Various lighting models, texture modes, etc. were all added, each needing their own piece of state. The simple state-based approach worked when you had a handful of states. As more and more states were added, the API started bursting at the seams. The API became more awkward but didn't diverge too far from hardware modes, as they were indeed based on a lot of state switches.

Then, along came programmable hardware. The hardware has become more and more programmable, to the point where now, the hardware supports a little state, some user-supplied programs, and a lot of buffers. All that state from the previous era had to be emulated, just as all the fixed-function features of that era were being emulated by the drivers.

Hardware also changed to be more and more parallel. This necessitated other hardware redesigns that made graphics state changes very expensive. The hardware works in big blocks of immutable state. Because of these changes, the driver couldn't simply apply each little bit of the state that the user set immediately, but had to batch the changes automatically and apply them when needed implicitly.

Modern hardware operates even further from the classic OpenGL model. DSA is one little change that was needed some 10+ years ago (it was originally promised as part of OpenGL 3.0), similar to what D3D10 did. Many of the hardware changes above need far more than just DSA to keep OpenGL relevant, which is why still more big extensions that drastically change the OpenGL model are available. Then there's the whole new GLnext API plus D3D12, Mantle, Metal, etc. not a single one of which keeps the outmoded state machine abstraction.
> 24 votes

# Answer
The overview justifies it by:

> The intent of this extension is to make it more efficient for libraries to avoid disturbing selector and latched state. The extension also allows more efficient command usage by eliminating the need for selector update commands.

I think "more efficient" here refers both to less bookkeeping overhead for library authors, and resulting higher performance. With current API, to be "well behaved" you need to query the state, stash it, change the state to do what you need, then restore the original state.

Like

```
oldState = glGet()
glBind()
glDoThings...
glSet(oldState)  // restore, in case anyone needs it just as they left it

```

Presumably, older hardware could be made more performant with the explicit state-changing API; it's a pretty strange ritual otherwise. This extension implies (and just look at the authorship list!) that avoiding that fetch, set, restore dance is now more of a performance win on current hardware, even with the additional parameter on each call.
> 1 votes

---
Tags: opengl
---


# Question
Title: Is normal mapping cpu overhead or gpu overhead?
In Unity3D Engine,

I usually apply normal mapping using fragment shader.

In this case,

this normal mapping is cpu overhead or gpu overhead?

# Answer
Normal mapping is calculated using a vertex and pixel shader, so it's GPU overhead.
> 1 votes

---
Tags: unity, normal-mapping
---


title: Create random polygon shapes

text:
# Question
Title: Create random polygon shapes
I want to make a random shape made out of points. I want the points to create a polygon shape. Is there a clever way to create a random shape like this? Im thinking going throug X points and giving them random positions but the problem is that they shoudl never intersect and the last point should connect to the first, which they always can do but the points should be somewhat evenly spread out. Im betting there are already good algorithms for this but i lack the words to know what to look for.

# Answer
Just winging it, here's two possible approaches...

**Constructively**

Build in such a way that lines cannot intersect. For example, take points spaced evenly alone a circle, and then randomize their radii. Could also randomize their angular position, within their pie wedge.

This won't make all possible polygons, the ones it makes will be non-self-intersecting.

**Test & Reject**

You could pick a set of ordered random points within the size you want, and then test if the polygon they form is suitable (in your case, non-self-intersecting), and if it passes, keep it. Else, try again.

A similar approach would be to start with 3 non collinear points, which must be a triangle. Then add a random fourth point. If it causes an intersection, reject it and try a different one. Repeat for as many vertices as you want, maybe a random number.
> 3 votes

# Answer
Some more options to consider:

**Convex Polygons:**

If you're OK generating only convex polygons, a fairly painless approach is to generate some number of random points and find the convex hull. Example **(by Mike Bostock)** here:

http://bl.ocks.org/mbostock/4341699

(Fairly easy to intuit that the fewer points you generate, the less "rounded" the hull will be.)

**Concave Polygons:**

If instead you want to allow concave polygons, it depends a lot on what kind of shapes you have in mind.

E.g., you could take a convex hull and cut out triangles to make it concave, like so:

1. Generate set of random points S
2. Calculate convex hull H
3. Calculate set of remaining points R, R=S-H
4. Until "concave enough" (however you want to define that)

* Select a pair of *adjacent* vertices A and B from the H
    * Select a random point C from R
    * Check whether the triangle formed by A, B, and C overlaps any previous triangles.
    * If not,

    + Record the triangle
        + Insert C between A and B

The "record the triangle / compare against previous triangles" bit is just to prevent self-intersecting polygons.

(This might be a little more complex, bookkeeping-wise, than david van brink's answer.)

Of course you could cut quads (or higher) instead of triangles. All depends on the look you've got in mind.

---

*Edit: Wanted to clarify that I did not implement the lovely example from bl.ocks.org, in case it wasn't obvious. Credit goes to (the very talented) Mike Bostock.*
> 6 votes

# Answer
This is a graph theory problem to determine the outerplanar graph from a random set of vertices. Professors Manuel Bodirsky and Mihyuan Kang of Humboldt University of Berlin considered this question in, *Generating outerplanar graphs uniformly at random*, 2006. Their work is made available to the public by researchgate here: link to PDF
> 0 votes

---
Tags: c#, unity, 2d, vector
---


title: Backtracking in A Star

text:
# Question
Title: Backtracking in A Star
Hello, can anyone tell me how can i implement backtracking in a a star search algorithm? I've implemented the a star search according to wiki, but it does not backtrack, what i mean by backtrack is that if the open list(green cells) contains 2,0 and 3,3 as shown in the picture, upon reaching 2,0 the current node would "jump" to 3,3 since the cost is now more than 3,3 and continue the search from there, how can it be done so that it would backtrack from 2,0-\>2,1-\>2,2... all the way back to 3,3 and continue?

# Answer
If you implemented A\* correctly then you would have a "open" list of nodes to search sorted by the expected cost of a path through that node or `d(start, node)+h(node, end)`

This means that the 2,0 node should still be in the list. But The algorithm should continue with 3,3.

If it doesn't then the way you select the next node to investigate is flawed.
> 1 votes

---
Tags: algorithm, path-finding
---


# Question
Title: How to determine whether a line intersects any other?
I have a collection of lines:

```
List<Line> _lines;

```

Each has the properties: X1, X2, Y1, Y2

How can I determine whether any given line in the list (Line\[n\]) intercepts, at any point, any other line in the list?

# Answer
> 2 votes
There is a sweeping algorith for this with logarithmic complexity, precisely (n+k)log(n).
The algorithm is described as follows:

* initialize priority queue = add every endpoint of your lines with priority of *x* coordinate
* while queue is not empty, pop one point, depending on type:
    1. If it is line segment start point, add to *y*-sorted-collection and test this with line segments directly below and above for intersection, if there is intersection, add it to the queue as future event.
    2. If it is line segment end point, test intersection between segments directly below and above, if there is an intersection, add it to the queue. Lastly remove this from *y*-sorted-collection.
    3. If it is previously added crossing(see above), swap the points below and above and test them for intersection with their new points below and above respectively. Remove crossing from *y*-sorted-collection.

it is quite simple and easy algorithm, but tricky to describe... Should you have difficulties with understanding, I am sure you can with tons of alternative resources describing this algorithm and probably even implementing it.

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


title: OpenGL light calculation

text:
# Question
Title: OpenGL light calculation
I want to add somebasic point lights to my OpenGL application. I read here that I have to caluclate the light in a pre-projection space:

> Lighting can be done in any pre-projection space (e.g., world coordinates or eye coordinates), as long as all the objects and lights are all in that same space.

And here is my problem. My Renderer currently looks something like this:

```
public void onDrawFrame(GL10 unused)
{
    GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT | GLES20.GL_DEPTH_BUFFER_BIT);
    Matrix.multiplyMM(camProjection, 0, projection, 0, camera, 0);

    for(int i=0; i < sceneObjects.size(); i++)
    {
        SceneObject object = sceneObjects.get(i);
        object.draw(camProjection);
    }

    // ...
}

```

As you can see I multiply my `projectionMatrix` with the `viewMatrix` and I think that is a good solution because I only have to do this once. To draw I give the `PVMatrix` to all objects and multiply it with their `modelMatrix` and then I push the finall `MVPMatrix` to the shader. This is a problem because I can not calculate the light direction in eye space in the shader because I do not have any pre-projection matrix here. Do I really have to push a `MVMatrix` to the shader and calculate the normals and so on with it? I think this is really inefficient because I have to do much more matrix multiplications, isn't it? What would you suggest to calculate this efficiently?

# Answer
Sending `MVMatrix` to the GPU and performing multiplication is not a problem. The GPU is very good at matrix multiplication that most of it is better moved from CPU to GPU, actually the GPU is designed as a vector processor to handle these operations. Newer GPUs can handle Giga Flops so don't worry about performance for simple light calculations. If your application took a performance hit, you first need to identify the bottleneck and optimize accordingly.

Sending both Projection and Model View matrix to the GPU is very common to perform light calculations, so don't worry.
> 1 votes

---
Tags: opengl, opengl-es, lighting
---


title: Averaging normals, or tangents

text:
# Question
Title: Averaging normals, or tangents
I am using a library to load an obj but it doest compute the tangets for each vertex, which I need for normal mapping and pom. I computed my tangets, and bitangents, everything appears to be fine, but I read that I need to average tangents if the vertices are the same (same position, uv, normal).

So for example if there is a vertex v that has the same pos,uv & norms as vertex v1 and v2, then the tangent for vertex v, v1, and v2 is normalize(v.t + v1.t + v2.t)?

I want to make sure I have the correct understanding before implementing.

# Answer
Normalizing would simply divide those combined values by their magnitude.

You just need to find the mean, of which you can add each individual component and thereafter divide by the total number of overlapping vertices.

(v.t + v1.t + v2.t) / 3
> 2 votes

---
Tags: opengl, c++, glsl, vector, normal-mapping
---


# Question
Title: How to restore purchases made with virtual currency from the App Store? (iOS)
I want to award coins for doing thing in my app and let users purchase things with the coins that are non-consumables. I also want to let users purchase coins as IAPs.

How do I keep track of what has already been purchased between app reinstalls / new device installs? I know that it's not required to share consumable purchases (coins) between devices.

Do I need to setup my own server to keep track?

Is it possible to do within the Apple ecosystem without the need for my own server?

Can I just use local storage and not worry about it?

# Answer
> 2 votes
I am not completely sure what you want to share across devices, the earned and bought coins or the purchased things (lets call them "hats").

I also do not have any experience with IAPs, iCloud and CloudKit, what I say here is only from observations and reading documentation.

IAPs can be restored, you can see that in almost any app that uses them to unlock features. If your bought coins cannot be consumed, that will help you get them back. If they can be consumed it will be a little trickier, especially since you will need to watch out for people modifying your data storage to cheat. In any case, unconsumed bought coins could be transferred like earned coins and hats (next paragraph).

Earned coins and hats need to be stored off-device somehow. You have several options here:

* iCloud: For a simple counter (coins) and a checklist of fixed / small size, you could simply store them in preference files (google "iCloud key value storage"). These will then be synced. From what I hear, KV-storage via iCloud works reasonably well.
* CloudKit: Storing data in iCloud using basically your own defined logic. More work than the above, but also more flexible. The storage limit should not matter for the problem you describe.
* Your own server: The most work, and the most flexible. Also frees you from the Apple ecosystem, allowing e.g. an Android version in the future, with cross-platform data transfer.

It all depends on your needs, really. Choose the topmost option that suits all of your needs. In any case, cross-device data transfer can not simply be done with local storage. Restoring a new device from a backup would transfer data, but deleting the app and reinstalling it would purge the data. And using both an iPhone and iPad is also only possible with some sort of cloud-based synching mechanism (leaving out user-initiated WiFi-transfers, I don't think you want that).

# Answer
> 1 votes
There's no need to have your own server. Apple provides the ability to restore purchases; details can be found here.

You can simply add a button which calls

`[[SKPaymentQueue defaultQueue] restoreCompletedTransactions];`

once you have an observer in your code, which looks like this:

`[[SKPaymentQueue defaultQueue] addTransactionObserver:self];`

and purchases will be restored.

More on the SKPaymentQueue class can be found here

# Answer
> 1 votes
Personally I use a shared keychain entry enabling Keychain Sharing in the Capabilities of your target. This makes life so much easier especially given that this file is backed up and thus if the user changes the device they will not lose anything.

---
Tags: ios, in-app-purchase
---


# Question
Title: Implementing single and muliplayer without messing everything up
I don't know a good way to implement single and multiplayer in a game without messing up the whole project structure.

Should I create separate classes for single and multiplayer entities or is there a clever programming pattern I can't find for this situation?

Let's make a simple example of my problem.

Let's say I want to make a pong clone with single and online multiplayer, how should I go about this? Make separate classes for both modes?

I read somewhere that the MVC pattern might be a good choice in this case but I'm not sure how to implement it correctly.

Should I create a Player data class and then multiple controller classes for example: PlayerControllerSingleplayer, AIController, PlayerControllerMultiplayerSelf, PlayerControllerMultiplayerOpponent.

And then a PlayerRenderer view class?

I've read some articles about mvc previously but still don't know really much about it or how to do it correctly in my case.

I will be using libgdx and probably kryonet for the networking if that might be important.

Thanks for every piece of advice in advance!

# Answer
> 3 votes
The MVC pattern is indeed a good solution here. You would need three different controllers:

* The `LocalPlayerController` which is sending commands to a paddle by listening to the local input devices. When you have multiple input devices (keyboard, mouse, gamepad...) it might be a good idea to further subclass it into the one it listens to. In any case, these class(es) should be used in both singleplayer and multiplayer, because it makes no difference for the control who you are playing against.
* The `AIController` which analyzes the current game state and sends commands to an ai-controlled paddle.
* The `RemotePlayerController` which listens to a network socket and interprets the incomming messages as commands to a paddle.

Regarding network output: This would not be another *Controller*, this would be another *View*. A view is not just something you see on the screen. It is any form of output representation of the model (the model in the context of game development would be the game state). It can be a graphical output on the screen or a data stream sent over the network. In this case the `NetworkView` would observe any paddles controlled by `LocalPlayerController`s or `AIController`s and translate their movement to the network.

# Answer
> 1 votes
* A Singleplayer game *is* a Multiplayer game with one human player.
* None-human players (often referred to as bots or AI), are a class or a group of classes that extends the base Player class. These classes compute the game state and output the moves the computer algorithm "considers" to be reasonable.

You could implement Multiplayer by itself and allow a player to run a solo server locally.

The "server" class accepts input from the Player class instances. Extend the player base class to implement AI controlled players (with different levels of difficulty). Remember that in online gaming (multiplayer or not), you need to compensate for the lag. You can still use the same code when gaming locally and latency free. Compensating for lag is a question in its own merit. The general idea is to consider when the actual input occurred and re-positioning the pong paddle in retrospective.

# Answer
> 0 votes
My approach to this is to build the Multiplayer/Networking aspect of the game first.

After a bit (not much, really) upfront cost (of building the network capabilities) you're primed for building an AI/Director agent that connects via the same "API" (the network communication API you set up to get Multiplayer working) and sends commands and responds to events very similar to another human player.

Incase it wasn't obvious, this does not necessitate an internet connection for single player, as you can (and should) simply have the AI (in single player/campaign, of course) connect on the loopback/localhost/127.0.0.1 address.

It's a pretty clean solution that I'm happy with. It prevents having to duplicate work, or write shims and maintain two separate subsystems.

The loopback or localhost interface bypasses the NIC so there is no hardware overhead. It's a great way to maintain a robust API between your game and agents which sets a solid groundwork for further expansion and maintenance.

Enjoy!

---
Tags: multiplayer, mvc, single-player
---


# Question
Title: How to make an object move and your player move in Unity
I am making a project in Unity 4.6.1 and I don't know how to make the enemy move to certain points. I would want it to move to 2 to 4 points or more. I also don't know how to make the player move (not First Person View). How do I fix these problems?

# Answer
You mentioned you want to have the game object move to 2, 4 or more points however you did not clarify on the behavior of this movement. You can follow jzx's solution but that would only allow you one movement point. So you can implement this in several different ways, one way would be to use an array of GameObject to move to the objects in sequence.

# Making an enemy move to predefined points

```
using UnityEngine;
using System.Collections;

public class MovementSequence : MonoBehaviour
{
    public Transform[] targets;
    public float speed;
    private int index = 0;
    void Update()
    {
        float step = speed * Time.deltaTime;
        transform.position = Vector3.MoveTowards(transform.position, targets[index].position, step);

        if( Vector3.Distance( transform.position,targets[index].position) < 0.01f)
        {
            if(index == targets.Length - 1)
                {
                     index = 0;
                }
            else
                index++;
        }
    }
}

```

Another more powerful way to implement this is using a graph but you need to do some research on how to use them correctly. A good place to look up graphs is http://www.vcskicks.com/representing-graphs.php
> 0 votes

# Answer
Attach this behavior to something to cause it to move (taken directly from Transform.Translate):

```
using UnityEngine;
using System.Collections;

public class ExampleClass : MonoBehaviour {
    void Update() {
        transform.Translate(Vector3.forward * Time.deltaTime);
        transform.Translate(Vector3.up * Time.deltaTime, Space.World);
    }
}

```

To move it to a specific point, attach this and set the target and speed fields to where you want it to go and how fast, respectively (from Vector3.MoveTowards reference):

```
using UnityEngine;
using System.Collections;

public class ExampleClass : MonoBehaviour {
    public Transform target;
    public float speed;
    void Update() {
        float step = speed * Time.deltaTime;
        transform.position = Vector3.MoveTowards(transform.position, target.position, step);
    }
}

```
> 2 votes

---
Tags: unity, motion
---


title: Speed dependent arc question

text:
# Question
Title: Speed dependent arc question
I'm currenlty working on an assignment and would appreciate any sort of help on the following implementation

The question follows

We are tasked to implement some heuristics but one of them is really confusing to me.

> *The following are a set of heuristics widely used by game developers for the movement of human characters while trying to reach a target*
>
> ## A. If the character is stationary or moving very slowly
>
> 1. If it is a very small distance from its target, it will step there directly, even if this involves moving backward or sidestepping
> 2. Else if the target is farther away, the character will first turn on the spot to face its target and then move forward to reach it.
>
> ## B. Else if the character is moving with some speed
>
> 1. If the target is within a **speed-dependent arc (like a narrow perception zone, or a cone of perception)** in front of it, then it will continue to move forward but add a rotational component to incrementally turn toward the target\**
> 2. Else if the target is outside its arc, then it will stop moving and change direction on the spot before setting off once more.

B2 I'm not entirely sure what a speed dependent arc is. I googled it and it bring it back to the textbook( Artificial Intelligence for video games). My question is : what is a speed dependent arc?

# Answer
> 1 votes
Hmm, a ***speed-dependent arc (like a narrow perception zone, or a cone of perception)*** , you say?

The text book pretty much has made up this term, it is not a standard term as far as I know.

What comes to mind is the following image...

"Speed-Dependent" brings up the idea that the 'cone' changes in size based on (aka 'dependent on') the current speed. For instance, the faster that you are going, the less 'amount' you can turn (and as per B2, if your target is not within this cones angle, then you need to stop the car, and turn slowly in the right direction.

In pseudo code, I think this is pretty much asking the following:

```
if(currentSpeed<slow){
    if(currentSpeed<distanceToTarget){
        moveCar(distanceToTarget);
    }else{
        turnCar(towardsTarget);
        moveCar(currentSpeed);
    }
}else{
    currentSpeedZone = maxTurningZone - (currentSpeed/maxSpeedOfCar*maxTurningZone);//or if you want to make 'speed lanes' (aka: <25=X turning angle, <50=Y turning angle, etc...) you can easily do that instead of generating a 'speedzone'
    if(angleToTarget<currentSpeedZone){
        moveCar(currentSpeed);
        turnCar(towardsTarget);
    }else{
        stopCar();
        turnCar(towardsTarget);
    }
}

```

I personally would add a lot of nuances with slowing down the car (if you are not just using unity's physics for instance), but that is the gist of what they are asking. Hope that helps!

# Answer
> 0 votes
'Speed dependent arc' is not a common term and has no specific meaning in game design. The textbook refers to cases where the character is already moving, but not necessarily directly towards the target. If the target is behind you, you would stop, turn around, and start moving again, but if you were moving in roughly the right direction before, you would not stop to do a small rotation. You would instead make the turn on the move.

To decide whether to go for option B1 or B2, you need to define the region in which the target is allowed to be for your current movement direction to be considered 'good enough'. The size and shape of this region (or 'arc', as the textbook incorrectly calls this) may or may not vary with your speed, hence 'speed dependent arc'.

---
Tags: unity, ai, heuristics
---


# Question
Title: Colour values of a pixel array from a spritesheet image wrong (C++, SDL2)
So basically what i want to do is create a 2D tile based rendering system in C++ that renders each pixel on the screen manually. Rendering an individual pixel on the screen works just fine (or render the whole screen blue for example). But i want to load the individual pixel colours of my sprites out of a spritesheet image and heres my problem:

I am able to create the image and access the pixels of the image, however the individual pixel values seem to be wrong. (I compared the pixel values with the supposed hexadecimals on paint.net)

Heres my code for the spritesheet:

```
    SpriteSheet::SpriteSheet(std::string path, int tileWidth, int tileHeight)
    :
    path(path),
    tileWidth(tileWidth),
    tileHeight(tileHeight)
{
    image = IMG_Load(path.c_str());

    if (image != NULL){
        width = image->w;
        height = image->h;
        pixels = (Uint32 *) image->pixels;
        std::cout <<std::hex <<  pixels[17] << std::dec << std::endl;

        //this prints out: 3030303 when it should be FF007F46

    }
    else{
        std::cout << "SpriteSheet couldnt be loaded!" << std::endl;
    }
}

```

Note that the pixel format is: AARRGGBB

Edit: I tried using a ".jpg" instead of a ".png" and i got different colour values again, but still not the right ones.

Edit2: I'm pretty sure the pixel format in which my image is getting loaded in is wrong. Any ideas how to get it to ARGB8888? I tried using `SDL_ConvertSurface` and `SDL_ConvertSurfaceFormat`but i can't seem to get it right.

# Answer
Don't assume the pixel format that `IMG_Load` gives you. Check its value; chances are it isn't ARGB8888 like you expected.

Instead, if you want that pixel format specifically, then use `SDL_ConvertSurface` on the loaded surface. Pass in your spritesheet surface's pixel format to guarantee that the two match.
> 1 votes

# Answer
I'm doing it using the following code:

```
BufferRef LoadImage(std::string filename, bool &success)
{
 SDL_Surface *surf = IMG_Load(filename.c_str());
 if (!surf)
  {
    success = false;
    std::cout << "Cannot load " << filename << std::endl;
    BufferRef r;
    return r;
  }
SDL_PixelFormat format;
format.palette = 0;
format.BitsPerPixel = 32;
format.BytesPerPixel = 4;
format.Rloss = 0;
format.Gloss = 0;
format.Bloss = 0;
format.Aloss = 0;
format.Rshift = 24;
format.Gshift = 16;
format.Bshift = 8;
format.Ashift = 0;
format.Rmask = 0x00ff0000;
format.Gmask = 0x0000ff00;
format.Bmask = 0x000000ff;
format.Amask = 0xff000000;

SDL_Surface *surf2 = SDL_ConvertSurface(surf, &format, 0);
BufferRef ref = CopyFromSDLSurface(surf2);
SDL_FreeSurface(surf);
success = true;
return ref;
}
BufferRef CopyFromSDLSurface(SDL_Surface *surf)
{
BufferRef buf = BufferRef::NewBuffer(surf->w, surf->h);
SDL_LockSurface(surf);
for(int y=0;y<surf->h;y++)
  for(int x=0;x<surf->w;x++)
    {
    Uint32 *ptr = (Uint32*)surf->pixels;
    int color = ptr[(surf->format->BytesPerPixel*x+y*surf->pitch)/sizeof(Uint32)];
    buf.buffer[x+buf.ydelta*y] = color;
    }
 SDL_UnlockSurface(surf);
 return buf;
}

```
> 0 votes

---
Tags: c++, sdl, pixel, sdl2
---


# Question
Title: Physics-based rotation with an array of pixels
Say I have a simple system, that has a large array of pixels with their own weight, velocity, coordinates etc. (by using classes) if each of those pixels can be connected to 4 other pixels (top, bottom, left, right) how could I let that object rotate, according to physics. An example of this is where I might have an array of pixels that makes a circle, and a slope, if I put the circle at the top of the slope, how would I compute the circle rotating while going down the slope?

# Answer
> 2 votes
One way you could do it is by simulating it as a grid of particles and springs, and then performing physics on each of the particles.

* For each filled pixel, if it has a filled neighbor pixel, add a spring with a rest length of 1 pixel, and a fairly high spring constant.
* Each filled pixel has a velocity, position, and mass.
* At each timestemp, move all of the pixels based on their velocities.

```
foreach pixel p_1:
    p_1.position += p_1.velocity * dt;

```
* For each pixel, check its neighbors and apply a spring force to its velocity:

```
foreach pixel p_2 in p_1.neighbors:
    // Compute vector from p1 to p2
    vector2 diff = (p_2.position - p_1.position);
    // This is the length of the spring
    float length = diff.length();

    // Compute the spring force between the two particles
    diff.normalize();
    diff *= (length - 1) * springConstant * dt;

    // Add a force to the particle based on the spring
    p_1.velocity += diff / p_1.mass;

```
* Also calculate gravity and collisions for each pixel:

```
 foreach pixel p_1:
     p_1.velocity += gravity * dt;
     p_1.velocity += p_1.get_collision_forces() / p_1.mass * dt;

```

From this numerical simulation, you will get some reasonable (but pretty buggy) physics. You will also get some nice squishiness to the simulation, which could be desirable. Depending on the size of the sprite, the spring-mass model might become infeasible. At that point, you will probably want to just represent your objects as polygons rather than pixels, by creating a convex decomposition of the sprite as polygons, and throwing it into a physics simulator such as box2d.

EDIT: I should also say that if what you're looking for is *rigid* physics, you can still use the spring model. Just compute the geometric moments of the particles, and use these as the rigid position/orientation of your object. Be warned: very computationally expensive!

---
Tags: physics
---


# Question
Title: Finding the side of a shape a ray intersects
For some simple 3D shapes (cubes, prisms) how can I determine which side a ray intersects, knowing the direction of the ray, and the normals of the shapes' sides.

I thought of using plane intersection for each side, but I'm sure there's a more efficient way.

Also, could this be done for a cylinder?

# Answer
> 0 votes
Most of your efficiency benefit can come from checking against a loose bound for your whole shape (box or sphere known to contain it). When you find that the ray "might" intersect it (because it intersects a sphere or box that's not much larger), then you pretty much need to check each face.

You can skip faces whose normals point away from the ray, since a different face of your closed solid would have to catch it first, if at all.

In some very specific cases, you can rule out whole faces. For example, consider unit cube centered on (0,0,0). If you're casting any ray from (0,0,100), the only face it could hit, if any, is the Z-positive one.

You mentioned "simple 3d shapes". For a complex shape with many faces, you might do broad rejection (sphere or box) for smaller pieces or individual faces of the shape.

---
Tags: raycasting, intersection
---


# Question
Title: Unity light object not affect some parts of a 3D model
So far I've used Unity only for 2D projects. But now I need to implement a 3D scene in my game. I downloaded a tree model from the asset store and placed it in my scene. I couldn't help but notice that my light objects do not affect some parts of such tree.

It affects the leaves, but the trunk remains dark. Even with a point light right next to the trunk, it doesn't seem to be affected by the light.

The tree I refer to is the Shanty Town one: https://www.assetstore.unity3d.com/en/#!/content/44

Since I don't know much about 3D, I've been meaning to ask if this is normal behavior (the fact that the tree's trunk is not affected by light objects) and if I am expected to see other models with the same issue. Is there a way to fix this? I have someone that will make some 3D models for my game, but now I am concerned that my light objects will not properly work on his models.

# Answer
> 0 votes
This may be related to a light problem in Unity, not a tree problem.

In Unity, the amount of point lights are limited.
If you have more than 4, the colors do not blend properly.
If you have way more than 4, the Unity choses to light up only the closest light.

This is very annoying, but it's a way to prevent Unity from crashing.

If you aren't using point lights, you should not be experiencing this problem.

---
Tags: unity
---


title: Migrate from NGUI to Unity UI

text:
# Question
Title: Migrate from NGUI to Unity UI
I used NGUI 2 and NGUI 3 for our UI. Now want to upgrade to Unity 4.6 and migrate all NGUI to Unity UI. Is there any tools? What's the best practice?

# Answer
To my knowledge there are no tools, they're completely separate systems. You could reuse the assets and any function calls through the UI etc so it wouldn't be a total redo but you'll have to remake it.
> 3 votes

---
Tags: unity, gui, ngui
---


# Question
Title: Do I necessarily need to write a vertex shader to use geometry instancing?
I've quickly read the GPU gem about geometry instancing, there are many wordings and I'm not sure I understand it well.

If I understand it well, when you use instancing, if you want to apply transformations to the instanced geometry, the only way to do so is to use a vertex shader, but it doesn't mean it's a requirement, it's only the case if you want to apply transformations.

For example, if I want to put houses, I don't need to use a vertex shader (static batching). If I want several walking robots, I will need a vertex shader.

Is static batching useful ? I mean it can save video memory.

EDIT:

https://www.opengl.org/wiki/Fixed\_Function\_Pipeline this goes further that what I thought I knew

# Answer
From what I know, it is needed since at some moment each object has do differenciate from the other at least by some parameter, in your case the position. So in the VS it adds the $\Delta pos$ it to the final pos.

I found this link useful http://www.gamedev.net/page/resources/\_/technical/opengl/opengl-instancing-demystified-r3226
> 0 votes

---
Tags: opengl, graphics, instancing
---


# Question
Title: How to approach 360 degree snake without having it "slide"
There's a great question here that helps me a little bit in what I want to do, and it explains it quite well:

How To Approach 360 Degree Snake

Basically, I want to have a smooth 360-degrees Snake game, where the snake follows along. I can easily do the same thing as described in the question above (video example), but as you can see that kind of "drags" or "slides" the snake along, which is not what I'm looking for.

I want the entire snake to follow the entire path that the head of the snake follows.

The only solution I can think of is to make some kind of "buffer" to store the rotations of the head, and then "lag" that behind on the other bodies.

Since I think that will end up way too complex, what's the correct way of implementing it?

Here's a screenshot of how my snake looks like right now, to get an idea of what exactly I want to move:

# Answer
One method is to have the head define a trail as it moves and position all other nodes at positions along this trail.

In this method you need to define the position of the body parts as a constant distance along the snake from the head.

So on each frame you want to;

1. update the position of the head.
2. add the current position of the head to a list of previous positions it occupied
3. for each node of the body
    1. get/calculate the distance the body should be away from the head
    2. traverse the trail by that distance
    3. set the body position to this position on the trail

The following is a C++03 program which shows how this can be achieved. It isn't perfect, but it demonstrates the idea;

```
#include <deque>
#include <string>
#include <sstream>
#include <iostream>
#include <math.h>

struct Vector3
{
  Vector3(double x = 0, double y = 0, double z = 0) :
    x(x),
    y(y),
    z(z)
  {
  }

  double x;
  double y;
  double z;

  Vector3 operator +(const Vector3 v) const
  {
    return Vector3
        (
          x + v.x,
          y + v.y,
          z + v.z
        );
  }

  Vector3 operator -(const Vector3 v) const
  {
    return Vector3
        (
          x - v.x,
          y - v.y,
          z - v.z
        );
  }

  Vector3 operator *(double scalar)
  {
    return Vector3
        (
          x * scalar,
          y * scalar,
          z * scalar
        );
  }

  double magnitude()
  {
    return sqrt(x*x + y*y + z*z);
  }

  void normalise()
  {
    double mag = magnitude();
    if (mag != 0.0)
    {
      x /= mag;
      y /= mag;
      z /= mag;
    }
  }

  std::string toString()
  {
    std::stringstream ss;
    ss << "(" << x << ", " << y << ", " << z << ")";
    return ss.str();
  }
};

class Trail
{
public:
  struct Point
  {
    Vector3 position;
    double distanceToNext;
  };

  Trail() :
    m_maxPoints(0),
    m_points()
  {}

  size_t maxPoints() const
  {
    return m_maxPoints;
  }
  void maxPoints(size_t size)
  {
    m_maxPoints = size;

    if (m_points.size() >= m_maxPoints && m_maxPoints != 0)
    {
      m_points.resize(m_maxPoints, Point());
    }
  }

  void addPoint(Vector3 vec)
  {
    Point p;
    p.position = vec;
    if (!m_points.empty())
    {
      p.distanceToNext = (vec - m_points.front().position).magnitude();
    }
    else
    {
      p.distanceToNext = 0.0;
    }
    addPoint(p);
  }

  void addPoint(Point point)
  {
    if (m_points.size() >= m_maxPoints && m_maxPoints != 0)
    {
      m_points.resize(m_maxPoints - 1, Point());
    }
    m_points.push_front(point);
  }

  Vector3 positionFromHead(double distance) const
  {
    for (size_t i = 0; i < m_points.size() - 1; ++i)
    {
      const Point& p = m_points[i];
      if (distance > p.distanceToNext)
      {
        distance -= p.distanceToNext;
      }
      else
      {
        // Lerp between last and current points.
        Vector3 offset = m_points[i + 1].position - p.position;
        offset.normalise();
        offset = offset * distance;
        return p.position + offset;
      }
    }

    if (!m_points.empty()) // is last point?
    {
      return m_points.back().position;
    }

    return Vector3(); // list is empty
  }

private:
  size_t m_maxPoints;
  std::deque<Point> m_points;
};

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

  trail.addPoint(Vector3(50, 0, 0));
  trail.addPoint(Vector3(10, 0, 0));
  trail.addPoint(Vector3(0, 0, 0));

  Vector3 posA = trail.positionFromHead(5);
  std::cout << " 5 units from head - Expecting (5, 0, 0) and got " << posA.toString() << "\n";
  Vector3 posB = trail.positionFromHead(10);
  std::cout << "10 units from head - Expecting (10, 0, 0) and got " << posB.toString() << "\n";
  Vector3 posC = trail.positionFromHead(25);
  std::cout << "25 units from head - Expecting (25, 0, 0) and got " << posC.toString() << "\n";

  return 0;
}

```

Of particular importance is this method which actually works out the position based on the distance;

```
  Vector3 positionFromHead(double distance) const
  {
    for (size_t i = 0; i < m_points.size() - 1; ++i)
    {
      const Point& p = m_points[i];
      if (distance > p.distanceToNext)
      {
        distance -= p.distanceToNext;
      }
      else
      {
        // Lerp between last and current points.
        Vector3 offset = m_points[i + 1].position - p.position;
        offset.normalise();
        offset = offset * distance;
        return p.position + offset;
      }
    }

    if (!m_points.empty()) // is last point?
    {
      return m_points.back().position;
    }

    return Vector3(); // list is empty
  }

```

In this instance each position on the trail is stored with a distance to the next one but this could be calculated on the fly. It's calculated in the addPoint() methods.

Note: don't use that Vector3 class. It was created only for this example to keep the dependencies down.

If the distance requested is longer than the list you'll just be given the position of the end of the trail.

If this were to be used you would need to make sure that you set maxPoints to an appropriate number or use 0 if you want it to be unbounded. To be clear, the maxPoints doesn't need to correspond to the number of bodies in your snake, you just want it to store enough to make a trail equal to the length of the snake.

You may want to consider limiting the max length with a max total distance instead of a max number of points. Also, if you set it to unbounded (0) it will consume more memory every frame so only use that when experimenting.

In practice you might do something similar but not exactly the same thing.
> 4 votes

# Answer
I've implemented the kind of smooth snake movement that you explain.

It's actually quite simple, but most of the examples I found while looking were the same kind as you encountered. And I don't think it's as easy to explain in plan words.

As you can see, my snake is a bit unusual, thats why providing implementation here is not really optimal. But I think it displays the movement patterns you want.

But try this:

-On each loop cycle, create a new "head" at the next proper position of the snake. (In other words, where the snake's current vector takes you).

-Transform the former head to a part of the body.

-"Fade out" the snake's body (reduce alpha as an example), so that along the tail, the snake
becomes more and more transparent, until the end, it's gone.

> So, you do not actually move the snake at all, you just keep creating new heads in the next position, and removing last element of the tail. At no point do you actually change the position of any existing segment of the snake.
> 2 votes

# Answer
I would recommend setting target positions for each of the snake parts allowing the part only move in that direction. Every time the part reaches the target position it sets a new target positon based on the position of the previous part. This should be done after fixed distances. Reducing the distances will make the movement appear smoother.
> 0 votes

---
Tags: objective-c, spritekit
---


# Question
Title: Organizing scene graph nodes that have multiple parents
I am trying to understand how, from an abstract sense, **scene graphs** should be organized.

Say that in a game, there is a scene where the user is inside a house. The house has four walls, and on one wall there is a painting. There is also a wood stove resting on the ground but with an exhaust pipe that extends up and "through" the ceiling. Also on the floor, there is a table with a pen and a piece of paper on it. **How might this particular scene graph be organized?**

```
house/
    wall_1/
    wall_2/
        painting
    wall_3/
    wall_4/
    floor/
        table/
            pen
            paper
        woodstove
    ceiling/

```

Here's the root of my question: the wood stove connects to both the floor **and** the ceiling, so which parent node should it be a child of?

# Answer
> 1 votes
Not everything can be represented as a tree... You're conflating "adjacency" with "hierarchy". Both may be useful concepts, depending what you're doing with your world.

(Also, just to mention, there's no "right way" to do it, it just depends on your needs.)

**Hierarchy** in your tree is probably useful for moving things around. For example, parenting the pen and paper to the table makes it easy to move the table, and a "reasonable" thing happens, that things on it move also.

For this purpose, perhaps parenting house-\>floor-\>walls-\>roof would give "expected" behavior. If you move the house, the floor (and table) and walls and roof move. If you move the walls, the roof moves but the floor wouldn't.

But that's just for-instance.

**Adjacency** might be a graph that isn't a tree. For example, if you shake one wall, you might want just the nearest other walls, floor, and roof to shake.

How you arrange your data really depends on how you need to use it.

# Answer
> 2 votes
I would say think about what implication your organization have.

E.g. the stow: If it where a top down game you would put the stow under the floor since if you go into the house you would like to make the ceiling invisible by making that node deactivated. If you would have put the stow under ceiling the stow would be goon to and that is not what you want.

Think what you would need to do with the graph for your game.

---
Tags: data-structure, scene-graph
---


# Question
Title: How to calculate the estimated time of arrival and control signal between two quaternion?
I'm trying to wrap my head around a control algorithm for a space game. If the user sets a target rotation I want to get a ETA counter and show the engine output. The only input to the system is a max delta angular velocity around the space ship local axis.

I uses Unity engine so I ave access to the quaternion of the rotation and global angular velocity. I can find the delta rotation between the two points as it's dQ = Qstart^-1\*Qtarget (from Qstart\*dQ=Qtarget).

But how Do I find the engine parameter at that frame and what is the ETA?

# Answer
It sounds like you are asking how to determine the time it takes to rotate from one orientation to another at a certain rate. That is a very simple equation, commonly known as Distance = Speed x Time. Your Distance is the angle between the two rotations. Your Speed is the "max delta angular velocity." Knowing those two, you can solve for Time.

I suggest that you refer to the documentation for Quaternion, Vector3, and Transform. Quaternion.Angle will provide the difference in degrees without needing to do the math yourself. Quaternion.Slerp could be used to actually rotate the ship transform, but there are other ways to do so. Calculate this during the Update method of a MonoBehaviour. Displaying the ETA to the user can be done minimally with GUI.Label during OnGUI method, but making it look nice is another challenge entirely.

If you need something more, please clarify your question. It is worded strangely. What do you mean by "show the engine output" and "find the engine parameter"?
> 1 votes

---
Tags: unity, quaternion, automation
---


title: How to serve user generated levels?

text:
# Question
Title: How to serve user generated levels?
What is the easiest way to store online and serve user-generated levels? What client-server architecture should I use? Will I need backend code, or just a database? What database would be the easiest to use with C++ front-end? Are there any suitable cloud services that would help to minimize the effort?

I am looking for something that can be used on both mobile and desktop.

The game we're going to make will be fairly simple, the levels can fit into one screen, each level is basically collection of integer coordinates of cubes of different types. Any tips on how and where to store such levels?

# Answer
> 0 votes
You will definitely need a proper server backend. Allowing your end-user client to access your database directly would be very dangerous, because databases systems usually do not support permission settings which are fine-grained enough to allow users to create, update and delete their own data but not the data of other users. Also you will definitely want some kind of plausibility check to make sure that user-submitted levels do at least fulfill the minimum requirements to be playable. That would be far too complex for most database systems.

Which database would be "the easiest one to use with C++ front-end" is very subjective, because it depends on how exactly you intend to use it. You could go with a classic SQL database or with one of the many, very different NoSQL solutions. The options for providers which offer different databases as a service are also plentiful, and they differ a lot in price and in the scale and quality of service. Which database to use and where to host it is a decision which depends on your personal requirements and preferences, so we can not help you to make it.

---
Tags: c++, cocos2d-x
---


# Question
Title: Problem with NGUI Unity 2D Sprite across devices
I have a problem with NGUI for Unity, using the `Unity 2D Sprite` objects.

First, have this image:

And then create an `NGUI Unity 2D Sprite` object in the scene. Apply this image and you get this:

Very odd. This doesn't happen if you use an `Unity UI Image` object or a `SpriteRenderer` component. But I really need to use NGUI's `Unity 2D Sprite`.

Then I ran the scene in several devices. Some of them display the sprite correctly - but others do not. Look:

* Top-left device: iPad Mini 1: The sprite is bad.
* Top-right device: iPad Mini 3: The sprite is good.
* Bottom-left device: iPhone 5c: The sprite is bad.
* Bottom-right device: iPhone 6 plus: The sprite is good.

I fail to understand what is the problem.

Again, this doesn't happen with sprites rendered with `SpriteRenderer` or Unity's builtin UI Sprite system. However, I need to do this with NGUI.

NGUI has a "NGUI Sprite" which I believe does work. But I don't want to use that one - I need to use the "NGUI Unity 2D Sprite" option.

Any ideas?

Unity 5.0.0b20

# Answer
Found the solution.

In the inspector, uncheck `Generate Mip Maps` and now it will work.

I do not know why did Mip Maps affect NGUI however. Either way I've reported this in their support forums.
> 1 votes

---
Tags: unity, ngui
---


# Question
Title: How can I generate a 2D mountain landscape procedurally?
Every level in my game needs to have a different mountain landscape background generated automatically (but the landscape must be the same for each level).

How could I generate such a landscape procedurally? Maybe fractals?

Note: I am using LibGDX and Java on Android

# Answer
> 6 votes
About 15 years ago I was quite satisfied with this algorithm for my Scorched Earth clone in Quick Basic (my first proper game).

Generate the landscape from left to right, pixel-column by pixel-column. Start at a random `height` value between your desired minimum and maximum height and with a random `steepness` value which is a negative or positive value in horizontal-pixels per vertical-pixel.

When you create the next column, add the current `steepness` value to the current `height`. Then change `steepness` by a random value which can be equally positive or negative.

Both steepness and height should be clipped (when they exceed the maximum or minimum, set them back to it). When you want to avoid plateaus at the minimum and maximum height, multiply the current steepness with -1 whenever the height exceeds the minimum or maximum, because this will create an instant peak/valley.

The larger the maximum steepness, the steeper your mountains will be. The larger the change of the steepness per column, the more jagged your landscape will be.

To make it possible to reproduce the results, use a random number generator which allows you to set a seed value. When you initialize it with the same seed and use the same parameters, it will create the exact same landscape.

**Edit:** I recreated the algorithm in Javascript. You can run it yourself to see the results. Unfortunately the build-in Javascript random number generator doesn't allow to set a seed, so it will be different everytime you run it.

```
 // javascript graphics boilerplate
 var canvas = document.getElementById("canvas")
 var context = canvas.getContext("2d");

 // parameters - change to your liking
 var STEP_MAX = 2.5;
 var STEP_CHANGE = 1.0;
 var HEIGHT_MAX = canvas.height;

 // starting conditions
 var height = Math.random() * HEIGHT_MAX;
 var slope = (Math.random() * STEP_MAX) * 2 - STEP_MAX;

 // creating the landscape
 for (var x = 0; x < canvas.width; x++) {
      // change height and slope
      height += slope;
      slope += (Math.random() * STEP_CHANGE) * 2 - STEP_CHANGE;

      // clip height and slope to maximum
      if (slope > STEP_MAX) { slope = STEP_MAX };
      if (slope < -STEP_MAX) { slope = -STEP_MAX };

      if (height > HEIGHT_MAX) {
          height = HEIGHT_MAX;
          slope *= -1;
      }
      if (height < 0) {
          height = 0;
          slope *= -1;
      }

      // draw column
      context.beginPath();
      context.moveTo(x, HEIGHT_MAX);
      context.lineTo(x, height);
      context.stroke();
 }
```

```
<canvas id="canvas" width=640 height=170> </canvas>
```

# Answer
> 0 votes
The trick is to have an a algorithm that produce something that looks good, while depending on random value from a PRNG (pseudo-random number generator, like srand and rand). Then, just seed the generator with the level number and be sure to not use your random number generator for anything else than the terrain.

Also, be deterministic: don't depend on timing or user input and you'll be fine.

For example, you could separate your terrain into n sections, pick a random point x,y, making sure each is in the i'th of the n section. Then linearly interpolate between each 2 consecutive points in between, in k sub points. Offset each such sub-point by some limited distance.

Then, in a loop, to smooth, randomly pick 3 consecutive points, and move the middle one a bit closer to the center between the two others. This will remove any hard edges.

By adjusting the various settings, number of sections, number of sub point, offset percentage, etc..., you'll get different looks.

From there, you need to tweak for your use-case. Moon-lander ? Add flat spots. Star-Wars, add cave for huge worms, you get the picture...

Also remember that if generating the whole terrain is expensive, you can do it in parts. The level seed can be used to generated sub-seed for each level section. So, in level 4, you use seed 4 to get, say 100 sub-seed. In each 100 parts of level 4, you use one seed to generate the terrain locally. You can nest as deep as you want.

See code and sample results below.

```
#include <iostream>
#include <stdlib.h>
#include <map>
#include <vector>

using namespace std;

const float WIDTH = 10000;
const float HEIGHT = 1000;
const float SHIFT = 200;
const int SECTIONS = 40;
const int SUB = 5;
const int SMOOTH_STEPS = 4000;

int main()
{
    int levelNumber = 42; //for example
    vector<float> xPos;
    vector<float> yPos;
    map<float,float> heights;

    srand(levelNumber);

    xPos.resize(SECTIONS * SUB);
    yPos.resize(SECTIONS * SUB);

    // random points, in a semi-regular fashion
    for(size_t i = 0; i < SECTIONS; i++)
    {
        xPos[i * SUB] = (rand() / (float)RAND_MAX) * (WIDTH / SECTIONS) + i * (WIDTH / SECTIONS);
        yPos[i * SUB] = (rand() / (float)RAND_MAX) * (HEIGHT);
    }

    // add points in between, letting them deviate only partly
    for(size_t i = 0; i < SECTIONS - 1; i++)
    for(size_t j = 1; j < SUB; j++)
    {
        float x = xPos[i * SUB] * (1 - (float)j/SUB) + xPos[(i + 1) * SUB] * ((float)j/SUB); // interpolate
        float y = yPos[i * SUB] * (1 - (float)j/SUB) + yPos[(i + 1) * SUB] * ((float)j/SUB);

       x += (rand() / (float)RAND_MAX) * SHIFT - SHIFT / 2;
       y += (rand() / (float)RAND_MAX) * SHIFT - SHIFT / 2;

       xPos[i * SUB + j] = x;
       yPos[i * SUB + j] = y;
    }

    // make smoother
    for(size_t i = 0; i < SMOOTH_STEPS; i++)
    {
        // pick a point not at an extremity
        size_t index = rand() % (SECTIONS * SUB - 2) + 1;

        float x0 = xPos[index - 1];
        float y0 = yPos[index - 1];
        float x1 = xPos[index];
        float y1 = yPos[index];
        float x2 = xPos[index + 1];
        float y2 = yPos[index + 1];
        xPos[index] = x0 * 0.05 + x2 * 0.05 + x1 * 0.90;
        yPos[index] = y0 * 0.05 + y2 * 0.05 + y1 * 0.90;
    }

    for(size_t i = 0 ; i < SECTIONS * SUB; i++)
    {
        cout << xPos[i] << " " << yPos[i] << endl;
    }
}

```

---
Tags: 2d, algorithm, procedural-generation
---


title: Open OBJ files with OpenGL c++

text:
# Question
Title: Open OBJ files with OpenGL c++
I need some help because i'm trying to open a obj file with Code Blocks. Im already downloaded the requirements for OpenGL and GLUT libraries. somebody knows some basic and specific steps to do it?

# Answer
OBJ is a fairly simple file format to read. But if you want to do a little bit more I found Assimp to be a good starting place. It's obviously an API that reads in a whole lot of 3d file formats. (I use .dae (Collada)) Setting up is fairly simple, download, link to project, then code.

Here are the includes

```
#include <assimp\scene.h>
#include <assimp\Importer.hpp>
#include <assimp\postprocess.h>

```

Here is the general code to read in

```
 const aiScene* aiscene = importer.ReadFile(fileName, aiProcess_OptimizeMeshes
    | aiProcess_Triangulate);

```

Then aiscene is a this big complex data structure holding whatever it is you need. (You might need to add some extra flags there depending on things like left handed or right handed coordinate system) http://assimp.sourceforge.net/main\_downloads.html
> 0 votes

---
Tags: c++
---


# Question
Title: Texture filtering: Is the minification or the magnification filter used when rendering at the exact texture size?
Suppose you have a texture where the minification filter is linear, but the magnification filter is nearest-neighbor (point filtering). If the texture is rendered at exactly 1:1 pixels, but at a non-whole-number pixel position, it is being neither minified or magnified.

Is there a convention for whether the min or mag filter will be used? What is the justification?

# Answer
> 3 votes
The OpenGL documentation specifies that OpenGL uses the magnification filter.

> The texture magnification function is used when the pixel being textured maps to an area less than or equal to one texture element.

https://www.khronos.org/opengles/sdk/docs/man/xhtml/glTexParameter.xml

I couldn't find any such documentation for Direct3D so if someone can confirm the D3D behavior it would be helpful.

---
Tags: textures, graphics
---


title: Finding break in voxel grid (3D array)

text:
# Question
Title: Finding break in voxel grid (3D array)
I am working at dynamic voxel engine in Unity (something like Space Engineers) where player can create object from voxels, push them, damage and split in to other object.

I store all data in 3D array, 1 mean voxel, 0 mean empty node.

So I looking for solution to break object (array). For example when I remove enough voxels object should split in to two.

```
00000000            00000    0000
01110110   ====>    01110    0110
01110110            01110    0110
00000000            00000    0000

```

In 2D example it should split like that.

I try to use BFS search but it not fast enough ;(. It works fine for small grids like 5x5x5, when I creat 5x5x50 grid it works few seconds before break arrays.

My algorithm: 1) First find empty node 2) When you find empty node start BFS from that node, collect all not empty nodes, when you cant find not empty node finish.

If break exist it will collect only one part of array so it find break, if there is no break it will return whole array.

The problem is speed of it ;/ How to make it faster?

# Answer
When you remove a node, take any solid nodes attached to it and do a connectivity test between each pair. If any of the solid nodes that were once connected to the solid node you just removed are no longer connected, then removing that node has just created two separate objects.

This algorithm isn't affected by the size of the grid, but rather the size of the objects. There are additional optimizations you can do for connectivity for large objects. (See this answer for some optimizations you can implement there). However, most of your searches are going to be very quick, because objects will still be connected with short paths.

I'll use a 2D example here for simplicity:

1. Our single object
2. We remove the red node and do connectivity checks between every green node with every other green node. We find they're all still connected.
3. We remove the red node and do connectivity checks between every green node with every other green node. We find that these nodes are no longer connected.
4. We have two separate objects. You can define these objects by taking the green nodes that were not connected and doing a BFS on each to determine the bounds of each completed object.
> 3 votes

---
Tags: voxels, search
---


title: How to trim a sprite?

text:
# Question
Title: How to trim a sprite?
I have a spritesheet:

```
var spriteSheet = new createjs.SpriteSheet({
    // ...
    frames: { width:520, height:600, regX: 260, regY:300 }
    // ...
});

```

I am computing it's physics body as follows:

```
var bounds = entity.sprite.getTransformedBounds();
halfWidth = bounds.width / 2,
halfHeight = bounds.height / 2,
// ... Create the physics body

```

The result:

The ground is a solid body, and the sprite is dynamic. I **would like** the sprite's feet to touch the actual ground and get rid of the whitespace around the sprite (above, below and sides).

The problem is that there is whitespace in the spritesheet. Each frame is `520x600` in the sheet. I have lots of frames and I would rather not go through each of them to figure out each one's exact dimensions.

Is this possible? Also I'm new to game dev, it's very fun. Is this what applications like TexturePacker are for?

# Answer
> 1 votes
Yes - you can use the Marching Squares algorithm to detect the bounds of the image within the frame, and then I would suggest storing the actual bounds (height/width) somewhere. Particularly if your sprites contain islands, as this can take a long time to locate all the little pieces in the frame.

Ideally, you would repack your spritesheets into an atlas so that you aren't wasting so much space on unused pixels and don't need to switch texture sources as much, but that is more relevant to hardware acceleration and probably premature optimization for small projects.

---
Tags: javascript, sprites, box2d, spritesheet, easeljs
---


# Question
Title: Unity game in edit the scene mode all of a sudden became incredibly slow/"laggy"
So I recently have been working on a game. So far I have very few assets in the game, which are a point light, a piece of terrain (which is textured), a player controller and a tree. Everything was going well until I put the tree in the scene. I made tree and started to add some branches I got to about 8 branches, and then I added 35 leafs. Then the edit scene started to become laggy. When I played the game it was running perfectly. But as soon as I changed the scene back to edit mode it became laggy again. I then deleted the tree to see if that would solve the problem but it seems to have done nothing at all. I would really appreciate if someone could explain why the edit scene is becoming laggy even though there are only a few assets within the game.

Thanks, Nova

# Answer
> 1 votes
This might be the solution:

When I was making a game, I have faced a similar problem.
Either in edit mode or game mode, it is the same.
If the camera is looking at a complicated texture, it will lag.
Maybe you are looking at a complicated texture in the edit mode, and the camera in play mode is looking at a non-complicated texture.
I was making a fps game, and when I stood on a particular box and looked down, it became glitchy.

Hope that helps!

---
Tags: unity, lag
---


# Question
Title: Collision detection of cicle and rectangle
How to find the collision detection of a moving rectangle on circular object? Here i have tried to junp rectangular object but the collision detection of a small rectangular object while jumping doesnt have smooth collision detection? Can anyone please help me ?

# Answer
As with anything in programming, there's multiple ways to do this. I'm not sure if what I would do is the best/fastest way, but it's a way to get the job done:

First, I would check if the circle and the rectangle are remotely close to eachother by checking
`if (vector2.distancesquared(circle.centerpoint,new vector2(rectangle.x,rectangle.y)) <= circle.radius^2 + rectangle.width^2 + rectangle.height^2)`

This simply checks if the distance between the centerpoint of the circle and the top left point of the rectangle (you could make it any point in the rectangle, doesn't matter), is smaller than or equal to the maximum distance between those two at collision. Notice I use distancesquared instead of just distance. This is because you don't want to get the square root of anything you don't need. It's a calculation that takes a lot of time and should be avoided when making something that's supposed to run smoothly (like a game). Also, I don't know what kind of circle class you're using, but I'm assuming it has some kind of centerpoint property. If it doesn't, you should still be able to find a way of getting the centerpoint.

After that, I would, for every point in the rectangle, check if it's in the circle: `if (vector2.distancesquared(circle.centerpoint, new vector2(rectangle.x,rectangle.y) <= circle.radius^2)`

This code only checks the top left corner, but you get the idea. If any of these points are in the circle, you have a collision. But be aware that if none of these points are on the circle, you might still have a collision. It could be that the circle is entirely inside the rectangle, or intersects with one of its sides. To check this, do the following:

`if((rectangle.x + rectangle.width >= circle.centerpoint.x - circle.radius) && (rectangle.x <= circle.centerpoint.x - circle.radius))`

As you can see, this checks if the right side of the rectangle lies to the right of the leftmost point of the circle, while the left side of the rectangle lies to the left of that point. If this is the case, check if that point on the circle is also between the top and bottom sides. Once you've done that, you've still only checked if it collides with the right side of the rectangle. Do this for all sides and you're done.

I deliberately didn't just fork over code and let that be it. I gave you an idea of how I would handle this situation. Again, it may not be the best way to do this, but I find it to be very readable. Try to finish the code on your own. If you can't seem to figure it out, ask away.
> 1 votes

# Answer
Depending on what you meant, try this:

Method 1: (if you are indeed working in 2D)
-Drawn from any angle, a BoundingSphere is a circle
-A BoundingBox with "0" height is a rectangle
-After constructing the two, use the .intersects method.

Method 2: (un-confirmed/tested)
-Bright red circles are circle(s) to be tested against the rectangle.
-Blue arrows represent CenterToCenterDirection
-Translate the circle(s)' center point(s) by (CenterToCenterDirection * radius)
-Test the new point against the rectangle using the .Contains method
> 0 votes

---
Tags: xna, c#
---


# Question
Title: Unity3D | Cost of accessing a script via a static reference to the instance
I saw this pattern around and I was wondering what would be the pros and cons about it. Does this suffer performance issues ? If so what would be a better alternative?

```
using UnityEngine;
using System.Collections;

public class SomeClass : MonoBehaviour
{

    public static SomeClass instance;

    void Awake ()
    {
        instance = this;
    }

}

```

And in an other script use it like so:

```
SomeClass.instance.SomeMethod();

```

# Answer
No, there is no performance issues with using static references. As it pertains to .net, you might even have better performance if you use static over instanced methods and fields (to such a little extent it is more a bit of trivia than something actually useful); I think the golden rule applies here: it is most important to make something that works and makes sense, and only after that should you worry about the optimization bit when and where it is needed. In some instances, having a static variable holding gameobjects/components makes perfect sense, and in those instances they are well suited.
> 1 votes

# Answer
Pros: You can access the same class from any script without connecting it.

Cons: There is a minimal overhead and if you have many scripts accessing the same singleton it can be messy to debug.

If you you use that pattern I would highly recommend making it more stable to prevent you from making mistakes in the future. There are however no run-time performance problems if you don't call this very often. If you implemented it as you diescribed in your post it would be slightly faster but that is of academic importance compared to the fact that you or some one else can mess up the code in the future. To solve the problem of having many instances:

```
//The instace
    private static SomeClass _instance = null;
    public static SomeClass instance{
        get{
            if(null==_instance){
                _instance = FindObjectOfType<SomeClass >();
                if(_instance==null){
                    throw new System.ApplicationException("No SomeClass found so no instance can be accessed.");
                }
            }
            return _instance;
        }
    }

    void Awake(){
        if(_instance!= null){
            Destroy(this.gameObject);
            return;
        }

        DontDestroyOnLoad(this.gameObject); //Keep the SomeClass even if loading level.
        _instance = this;
    }

```
> 1 votes

---
Tags: unity
---


title: Raycasting on Z in 2D

text:
# Question
Title: Raycasting on Z in 2D
I'm making an isometric game in Unity. So far I have managed to render a diamond shaped board, with tiles that are aligned on the x and y axis (and the camera looks down the Z axis).

I am spawning game objects for each tile with their own polygon collider and sprite renderer. I hope this is the correct way. They appear in front of each other naturally as you would expect them to in an isometric view.

I want to make a raycast from the player and forward on the z axis, to hit the sprite right under him. As you can imagine, I run in to problems when I do that, I imagine it's because they are all on the same 0.0f on the Z axis.

So my question is, does the raycast care about when a sprite is rendered in front of another, when it calculates what to hit, or is it just the physics engine handling this? And if so, how can I get around this? I guess I can translate the player coordinates to the board, but I just want to know how this works anyway.

# Answer
The 3D physics and the 2D physics are handled differently in Unity (for example 2D colliders do not collide with 3D colliders). As a result, 3D ray cast will not collide with 2D colliders.

However, you can mix and match so you could use a 3D raycast along the z-axis but you will need to attach 3D colliders to your objects.

Alternatively, if you want to check the collision of a point you can use the 2D ray cast of length 0 at the point you wish to check

```
Physics2D.Raycast(YourWorldPosition, Vector2.zero);

```
> 0 votes

# Answer
I dont know how raycast is implemented in Unity but it could very well be as you suspected, the raycast will not hit objects with same x, y or z. Imagine if you are implementing an overlap function that checks if (a,b) overlaps with (c,d), whether (1,2) overlaps with (2,3) is dependent on how you implements it.
> 0 votes

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


# Question
Title: Drawing sprites only under certain conditions - alternatives to using 'if statements'?
Within my game (which is Java/Android), I wish to draw a sprite only under certain conditions, so up until now, I've been using **if statements** to accomplish this. Something like so:

```
if (powerUpActive){

    draw(shieldSprite);

}

```

So the above, uses a simple boolean primitive (*powerUpActive*) and only draws the sprite (*shieldSprite*) when the boolean is true.

This works, however, my logic code is littered with *if* statements and I'm not sure this is a good thing. I keeps reading that too many *if* statements are a bad thing however, I can't work out how to accomplish this without using them.

Note, the above is just an example, I use many other boolean flags in my code

The only alternative that I can think of is to use a batch of sprites where I can specify the number to draw. (This is OpenGL ES 2.0 so I use a for loop to upload the vertices for the sprites I want to draw within the batch). If I simply set the number to draw to 0, it won't draw any. However, it seems a little overkill to use a batch when I know there will only ever be one sprite in it.

```
public void draw(){

    for (int i = 0;i < numberToDraw; i++){

        //Code here to upload vertices
    }

    //Code here to draw sprite (draws nothing if numberToDraw is set to 0)

}

```

So I'm really not if there is a better way do things in java on condition without using if's or switch statements.

# Answer
Great question!

Groo posted a fantastic answer to this question in a StackOverflow thread several years ago, which you can find *here*, which boils down to readability and future proofing is an enemy of the if statements.

That's not to say that you should always avoid if statements though! They have their uses, in simple, one off checks.

To answer your question, I would move

```
if (powerUpActive){

    draw(shieldSprite);

}

```

inside a function, in the class PowerUp like so:

```
class PowerUps {
    public void Check() {
        if (powerUpActive){

            draw(shieldSprite);

        }
    }
}

```

and just call

```
powerUp.Check;

```

from render.

To future proof this, I would also even change powerUpActive to something even more specific like a class Shield, inside class PowerUp and then check it's activity with shield.enable() like so:

```
class PowerUps {
    class Shield {
        private boolean active = false;

        public void enable() {
            active = true;
        }

        public void disable() {
            active = false;
        }
    }
    public void Check() {
        if (shield.active){

            draw(shieldSprite);

        }
    }
}

```

The purpose of this is two-fold -- you can enable/disable power-ups from a game event easily, by calling powerUp.shield.enable() *and* draw it without having to worry too much about backtracking.

This may seem like a lot of work for one shield power-up, but it's a question of future-proofing your code and saving yourself hours, upon hours of hard work later on, when you would eventually want to expand.

Just think think about how pretty your render function will look! And how easy it will be to expand your game without worrying if you've broken something! I don't know about you, but I'm excited already! :3

***NB***: *The examples I provided are just to elaborate on a point. In the real world you would probably want to use inheritance more actively and organize things even more, like keeping a reference to the shieldSprite inside the Shield class.*
> 1 votes

# Answer
I use C#, so I don't know the exact equivalents for your setup and you may already be well aware of these...

-Combine if's using shortcuts where appropriate:

```
"Orelse"
if (Condition1 || Condition2) //Condition2 is not evaluated if Condition1 tests true
{
...
}

"Andalso"
if (Condition1 && Condition2) //Condition2 is not evaluated if Condition1 tests false
{
...
}

```

-Test out-of-bounds/range first or early:

```
void ASDF()
{
if (SomethingInvalid) return; //immediately
if (SomethingOutOfRange) return; //immediately
... //Much to do, all of which is skipped upon return
}

```

Conditional branching is generally accepted everywhere but shaders. Other heavily-distributed processes may waste **more** time synchronizing thread-safe access to shared resources than was saved by threading them in the first place.
> 0 votes

# Answer
The logic will be easier to follow if you break it into different functions, i.e.

```
void update() {
   handleCollisions();
   handleShield();
   handleWeapons();
   handle...
}

void handleShield() {
   if(shieldActive) {
      // do shield stuff
   }
}

```

and when it comes to drawing, you're better off either building static actor graphics groups (nodes, whatever), so that they either always contain the shield, weapons, powerup and other effects sprites, and you regulate their alpha and visibility in your logic, OR you re-build the actor display groups when their state changes. That way your graphics code won't be iffing, but instead just looping unconditionally through display lists like it should.
> 0 votes

---
Tags: java, boolean
---


title: Backround turning, follow the character

text:
# Question
Title: Backround turning, follow the character
In my Unity2d-platformer, I need background to follow the character, so I just attach it. And when character turn left from right (or right-to-left), background turn too.

How can I make my background constant?

# Answer
Do not attach it to the character. An easy option would just be to have a script on the background that has it match the X position of the player transform.
> 1 votes

# Answer
Make a script that follows the cameras position or/and just make it a child of the camera depending on what you want to achieve. The script solution has the benefit of making it possible to make small adjustments depending on which direction the player is running.
> 0 votes

# Answer
I think you're looking for "Parallax Scrolling" http://unity3d.com/learn/tutorials/modules/beginner/live-training-archive/2d-scrolling-backgrounds
> 0 votes

---
Tags: unity, camera
---


title: explaining collision check code

text:
# Question
Title: explaining collision check code
I came across the following code in a game book but I can't get it, does it check if a point (left, top) in a rectangle?

```
bool CheckCollision(float left, float top,  float SpriteX, float SpriteWidth, float SpriteY, float SpriteHeight)
{
    return !((left >SpriteX + SpriteWidth) ||
            (top > SpriteY + SpriteHeight) ||
            (SpriteX > left + SpriteWidth) ||
            (SpriteY> top +SpriteHeight));

}

```

# Answer
I don't have enough reputation to comment, so I will post this as an answer.

To get the most out of this exercise, I suggest you take a piece of paper, draw a rectangle and then try to map out each check on the paper.

For example: if the left coordinate of my actor is bigger than the wall, it will look like so.

Hopefully you understand what I mean, it's hard to explain with words. :P
> 1 votes

---
Tags: c++
---


# Question
Title: Is there a way to scale a texture via GPU rather than by CPU?
For my game that I'm developing I want to have my cards dynamically drawn so if there is any changes done to them it could be drawn on the card itself.

What I have currently is that the cards are drawn to a RenderTarget at their originally designed size of 2100x1480 px. (I'll probably for game purposes have to scale that down to 1050x740 for its native size, but was designed that way to have 600 dpi for physical versions).

Anyway the way I want to do it is that after drawing everything to the RenderTarget I scale it down and store that scaled down texture to the card's texture (which will be 164 x 115 for the playing size, the 1050 x 740 is the zoomed in size that I want so players can view what the card does and stats). The issue that I'm facing is that the way I currently tried to do it was far too slow taking over 9 seconds to scale it down after drawing the original size to the RenderTarget.

Is there a way to scale a texture via GPU rather than by CPU? I'm currently using a CPU method as I'm new to working with textures and drawing.

# Answer
I'm not sure I understand the question correctly, but if you are asking only about how to draw the texture with a different resolution than the original, there is no need to change the texture itself.

XNA provides several overloads of SpriteBatch.Draw() method . Some take **destination rectangle** as the second parameter and allow you to specify the area in which the texture will be inscribed. Others contain **scale** parameter of type *float* or *Vector2*, which allows you to draw texture scaled proportionally or not. All rasterization operations performs GPU.

If this is the not answer to your question, please rephrase it more concretely, and best of all insert code snippet.
> 1 votes

# Answer
Simply drawing the texture to a smaller quad will scale it down automatically for you; there's no rule stating that the dimensions of the quad you draw a texture to have to be the same as the dimensions of the texture.

In your specific case, you can take a 2100x1480 texture and draw a 164x115 quad using it, and the MinFilter you specify in your sampler state (or shader code) will take effect, automatically scaling the texture down.

However, be aware that a typical linear MinFilter operates on a 2x2 block of texels, so it's only good for reducing to 50% of the size of the original; any lower and it will introduce noise.

The solution you need is therefore mipmapping. Instead of creating your texture with a single miplevel, you create it with a full mipmap chain, then use hardware mipmapping to generate the submips for it. Then when drawing you just specify the miplevel you wish to draw from, depending on the size of the quad you're drawing, and the GPU will do the rest.

Further reading: http://blogs.msdn.com/b/shawnhar/archive/2009/09/14/texture-filtering-mipmaps.aspx
> 0 votes

# Answer
Simply use the `SpriteBatch.Draw` overload which allows you to specify the destination rectangle:

```
public override void Draw(Microsoft.Xna.Framework.GameTime gameTime)
{
    spriteBatch.Begin(SpriteSortMode.Deferred);

    spriteBatch.Draw(
         texture: texture,
         destinationRectangle: destinationRectangle,
         sourceRectangle: null,
         color: Color.White);

    spriteBatch.End();
}

```
> 0 votes

---
Tags: xna, c#, textures
---


title: How Use loop's in cocos2d-x

text:
# Question
Title: How Use loop's in cocos2d-x
I've for loop which work well on Windows

```
double speed = 35;

    for(int i=0; i<60 ;i++){

        speed += 0.3;
        Sleep (1000); // sleep 1000 mili seonds

     }

```

But it responds an error on cocos2d-x.what should i do in cocos2d-x. In my code i want to increase my speed to N unit every X second.

```
auto Action = MoveBy::create(3  *   visibleSize.width,Point(-visibleSize.width * speed, 0));

```

My way is right or should I do something else

# Answer
> 0 votes
Here is another method, using a little bit more complex lambda:

1. First some setup, like initial movement speed and time between speed increases:

```
float speed = 0;
float delay = 1;

```
2. Here's the tricky part! I'm using `CallFuncN` since I want to run a new action (with new speed) every `delay` seconds. So I need to know to which Node I should attack new MoveBy action. Note that, this lambda is mutable, which means it might be changing it's capture values, and those changes should be retained between different calls.

```
auto moveFunc = CallFuncN::create([speed, delay](Node *target) mutable
{
    speed += 10;
    target->runAction(MoveBy::Create(Vec2(speed,0), delay));
}

```
3. As Droideka suggested, we should create a sequence. CallFuncN takes no time to complete, but we don't want object to be moved second or third time, while the first one is still in progress, so we just have to wait. Note that `nullptr` should be there in it's last argument, it means there are no more actions in the sequence.

```
auto sequence = Sequence::Create(moveFunc, DelayTime::create(delay), nullptr);

```
4. Also we don't want this to happen only once, or else we could simply run a `MoveBy` action. So we wrap the whole sequence inside a `Repeat` Action, which means this should be run more than once (in this code 5 times).

```
auto repeat = Repeat::create(sequence,5);

```
5. Finally we need to attack this whole thing to an object, for example our player. Note that you just need to call these once and everything will happen according to plan afterwards.

```
player->runAction(repeat);

```

# Answer
> 1 votes
Follow these steps:

1. Create an action with a callback to your function:

```
CallFunc *runCallback = CallFunc::create(CC_CALLBACK_0(Youclass::theFunc, this));

```
2. Create a delay With Delaytime class:

```
// for 1 second
auto delay = DelayTime::create(1);

```
3. Create a sequence with the delay and your runCallback function in the part of the code that you need to sleep it.

```
this->runAction(Sequence::create(DelayTime::create(yourDelayTime), runCallback, nullptr));

```

# Answer
> 0 votes
I'm not sure if this code work but what you need can be accomplished easily with a `Scheduler` as this:

```
Schedule( [&](float dt) {
                        speed+= 0.3;
                        if(speed==N) Unschedule("TimerID");
                        } , 1, "TimerID");

```

---
Tags: c++, cocos2d
---


# Question
Title: What is classified as a "High Level Design Decision"?
I'm a student studying game development and I have an assignment about level design due in a few days, the last question is about **identifying high level design decisions from a game scenario**, but the scenario is a very simple outline of a stealth game.

What is a "High Level Design Decision"?

# Answer
> 2 votes
High level decision could mean anything that is not too specific, but is clear enough to understand what is the idea of the game. This is to avoid your team making the wrong idea of what you have in mind for the game, since "Stealth game" is a too broad term.

For example in your case of a Stealth game, these are some questions that would lead to High Level Design Decisions:

-Will the game end once the character is discovered? If not, can you fight those who discover you? Or do you have to hide again having no combat at all?

-Is the game divided in levels, or there is one big map with different points of interes?

-Can the player disable/incapacitate those who are looking for them? Has he no power over his enemies?

You can go on and on. But the idea is that you should focus on the most important aspects of your game, so it's clear to your team what the game is about and how does it feel.

# Answer
> 0 votes
A few examples:

-Will the player face human opponents or AI's?
-Is it first-person, third-person, isometric, etc.?
-Can the player interact with and/or change the environment?
-Is it a 2D game or 3D game?
-How "far" is 1 unit of length?
-Can the game be modded now or possibly in the future?
-Is there a terrain? With gravity? Can the player jump?
-Can the player run instead of walk? How fast does he walk and how fast does he run?
-How many unique types of content will the game require? Models, textures, etc.
-Of all the things that *need* to be finished before the release date, what **must** be finished?
-Of all the things that **must** be finished, how many can you actually afford to finish on time?

"High-level design decisions" affect a large portion of the player/user's experience. Whether or not to add gravity needs to be decided up-front since it would interact with everything in the game world, including the user.

---
Tags: level-design
---