# Question
Title: What's the most efficient way to deal with in-game messages in Allegro 5?
I have a little 2D game made with Allegro, and I want to introduce strings during gameplay. For example, I've just made it so a key is needed to open a door, so I'd need some tutorial text to appear when the player collides with the door that tells them they need the key first.
This is just a learning experience for me, really - the key is pretty visible but I would like to learn how to handle this sort of messages especially for tutorial purposes in a bigger, better game.

Right now, during gameplay, I have running `game_loop()` (which handles player movement, collisions etc) and `game_render()`, which obviously runs after it. To introduce these messages, what I have successfully done so far is to add a global `std::vector<const char*>` to which I `push_back` messages whenever appropriate.

My `message_renderer()` then goes like so:

```
static double t = 0, c = 0;

    if (!messages.empty())
    {

    for (unsigned int i = 0; i < messages.size(); i++)
    {

        al_draw_text(font18, al_map_rgb_f(255, 255, 255), wWidth / 2, wHeight - 50, ALLEGRO_ALIGN_CENTRE, messages[i]);
        if (t < 2)
         {
           t += get_dt();
           c += get_dt();
            if (c > 1)
                  c = 1;
          }
        else
        {
        t = 0;
        c = 0;
        messages.pop_back();
        }

    }
    }

```

I then call this `message_renderer()` in my `game_render()` after I've drawn everything else, to ensure that the message appears on top.

Now, again, this does work - the message displays for 2 seconds at render time once it's added to the `vector`. However, this solution doesn't really seem particularly neat to me, since as far as I know there are standardised ways of dealing with these sort of events - I just don't know what they are!

So my question is - is my current method efficient enough? Can it be improved, in Allegro (or generally, in logic!) and if so, how?

Thank you in advance!

**EDIT**: I've modified the code since posting the question, so it should now behave like expected - showing a message for 3 seconds. It does so, but when I have two strings in the vector at the same time they overlap - I thought the timer would work as "pause" between each iteration but I guess not... If someone could point me in the right direction for that too, it'd be much appreciated :)

# Answer
You can use `std::ostringstream`s to push anything (even non-char variables) into a stream and convert it to a string:

```
std::ostringstream ss;
ss << "Some text: " << some_variable;
//...
al_draw_text(font28, al_map_rgb_f(255, 255, 255), wWidth / 2, (wHeight / 2) - 28, ALLEGRO_ALIGN_CENTRE, ss.str().c_str());
ss.str(""); //Clear stream contents.

```
> 1 votes

# Answer
*This is to address your overlapped strings described in your edit*

`al_draw_text` contains arguments where you specify the position to start writing your string. Normally that means the first character will be at the specified position and the rest of the characters continue to the right (although this - the text alignment - can be changed via the `flags` argument).

However if you reuse this function to draw a second string without changing the position, it will not draw the second string to the right, or below the first string. It will draw the second string at the same starting position as the first string, resulting in overlapping text.

You have two options:

* If you simply want to draw the two strings as if they were one, join the strings first and draw the joined strings in one go.
* If you want to control the positioning yourself, specify a different position to draw the second string. If you want to make sure the text doesn't overlap, or for the layout to adapt to different fonts and sizes, you can use the drawn size of the first string by using `al_get_text_dimensions` or the related functions.
> 1 votes

---
Tags: c++, allegro
---


# Question
Title: How to set player rotation to direction the player is moving?
I'm having an issue with my click to move mechanic. I want the player to move to a specific position in the game when the mouse is clicked (and it does just that) but the issue I'm having is that the player doesn't face the **direction** in which it is travelling.

Lets say I click a position diagonally right to where the player is. Immediately after clicking that point, the character will face that direction and run to it, instead of facing the direction it has to take to get there... if that makes sense.

Here's my code snippet:

```
public void moveToTargetPosition() {
    Seeker seeker = GetComponent<Seeker>();
    seeker.StartPath (transform.position, targetPlayerPosition, OnPathComplete);

    transform.rotation = Quaternion.Lerp (transform.rotation,  Quaternion.LookRotation(targetPlayerPosition - transform.position), Time.fixedDeltaTime * lookSpeed);
}

```

Obviously I'm missing some modifier in here.

Any ideas?

Thanks!

# Answer
> 1 votes
In 2D you can use Atan2 (http://docs.unity3d.com/ScriptReference/Mathf.Atan2.html)

```
facing_angle = Mathf.Atan2( new_pos.y - old_pos.y, new_pos.x - old_pos.x);

```

Or using (X,Z) if that's how your world is oriented:

```
facing_angle = Mathf.Atan2( new_pos.z - old_pos.z, new_pos.x - old_pos.x);

```

Or Transform.LookAt (http://docs.unity3d.com/ScriptReference/Transform.LookAt.html)

```
public function LookAt(worldPosition: Vector3, worldUp: Vector3 = Vector3.up): void;

```

This will point your character toward `worldPosition`.

Your character might needs additional rotation if its 3D mesh was exported facing the "wrong" way, you can do this by adding to `localEulerAngles` in the transform or using quaternions but it's better to fix the source mesh if you can.

# Answer
> 0 votes
Your code would face towards the destination, and it seems like you're following some kind of path. The problem is that if the direction you're traveling isn't the same as the look at to the goal, it'll look odd.

You can solve this by either getting the direction you're traveling in and using that instead. (This is specific to how you're moving it, however if you use Physics(2D) you can use the velocity.)

Or if there's no way to get that, you can use a slight trick where you set the direction based on the delta position you've had since last step.

```
private Vector3 _previousPosition;
public void moveToTargetPosition() {
    Seeker seeker = GetComponent<Seeker>();
    seeker.StartPath (transform.position, targetPlayerPosition, OnPathComplete);

    Vector3 currPosition = transform.position;
    transform.rotation = Quaternion.Lerp (transform.rotation,  Quaternion.LookRotation(currPosition - _previousPosition), Time.fixedDeltaTime * lookSpeed);
    _previousPosition = currPosition;
}

```

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


# Question
Title: How do I create a message box that fires a callback on button press?
I need to create a message box with an "OK"-button. When the user touches the button, it should execute a callback. I'm new to this and couldn't find any articles in the docs.

# Answer
I need too often to show popup message in my games. so I've created a base class and I derived new popup message class from it and override `SetupUI()` in derived class to show my desired message. in fact you need to put a `MenuItem` in `SetupUI()` of new class to implement "ok" button simply.

**Note:** `CreateInvisibleBackgroundButton()` works for cocos2dx v2.x and `BlockPassingTouch()` is its equivalent for cocos2dx v3.x .

**Note2:** If you want to call different callback for same popup message, you can pass a callback `std::function<void(void)> _callbackFunc` (cocos2dx v3) as parameter to your dialog and call that when "ok" pressed.

If you need more description just tell me.

**PopupNode.h**

```
#ifndef __POPUP_NODE_H__
#define __POPUP_NODE_H__

#include "cocos2d.h"

class PopupNode : public cocos2d::Node
{
public:
    CREATE_FUNC(PopupNode);
    virtual bool init();    // subclass should have access to call it
    void ClosePopup();
private:
    void BlockPassingTouch();
    void SetupUI();
    void CreateInvisibleBackgroundButton(); //THIS FUNCTION IS OUTDATED. KEEP FOR COMPARING COCOS2D 2.X AND 3.X
};

#endif // __POPUP_NODE_H__

```

**PopupNode.cpp**

```
#include "PopupNode.h"
#include "Const/constants_z_order.h"

USING_NS_CC;

bool PopupNode::init()
{
    if ( !Node::init() )
    {
        return false;
    }
    //////////////////////////////////////////////////////////////////////////
    BlockPassingTouch(); //CreateInvisibleBackgroundButton();
    SetupUI();
    //////////////////////////////////////////////////////////////////////////
    return true;
}

void PopupNode::CreateInvisibleBackgroundButton()
{
    // Code below works with cocos2dx 2.x
    //////////////////////////////////////////////////////////////////////////
    ///////// THIS FUNCTION IS OUTDATED. KEEP FOR COMPARING COCOS2D 2.X AND 3.X
    //////////////////////////////////////////////////////////////////////////
    //////////////////////////////////////////////////////////////////////////
//  Size visibleSize = Director::getInstance()->getVisibleSize();
//  Vec2 origin = Director::getInstance()->getVisibleOrigin();
//  //////////////////////////////////////////////////////////////////////////
//  auto lock_menu = Menu::create();
//  //lock_menu->setTouchPriority(-1000); // get touch first
//  lock_menu->setPosition(origin);
//  this->addChild(lock_menu);
//  //////////////////////////////////////////////////////////////////////////
//  auto invisibleClose = MenuItemSprite::create(NULL, NULL, nullptr);
//  invisibleClose->setAnchorPoint(Vec2::ANCHOR_BOTTOM_LEFT);
//  invisibleClose->setContentSize( visibleSize );
//  invisibleClose->setPosition(origin);
//  lock_menu->addChild(invisibleClose );
}

void PopupNode::SetupUI()
{
    Size visibleSize = Director::getInstance()->getVisibleSize();
    Vec2 origin = Director::getInstance()->getVisibleOrigin();
    //////////////////////////////////////////////////////////////////////////
    auto cover = Sprite::create("Scene/PopUp/LoadingBackground.png");
    cover->setPosition(Vec2(visibleSize.width/2 + origin.x, visibleSize.height/2 + origin.y));
    this->addChild(cover, Z_BACKGROUND);
}

void PopupNode::BlockPassingTouch()
{
    auto listener = EventListenerTouchOneByOne::create();
    listener->setSwallowTouches(true);
    listener->onTouchBegan = [](Touch* touch, Event* event){
        if(event->getCurrentTarget()->isVisible() == false )
            return false;
        return true;
    };
    _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this);
}

void PopupNode::ClosePopup()
{
    this->removeFromParentAndCleanup(false);
}

```
> 1 votes

# Answer
You can create a new Layer with an box and an CCMenu with one CCMenuItem. The CCMenuItem will be your OK Button where you will set your callback method.

Something like...

> CCSprite \*box = \[CCSprite spriteWithFile:@"box.png"\];
>
> box.position = ccp(screen.width/2,screen.height/2);
>
> \[self addChild:box\];
>
> CCMenuItemImage \*okButton = \[CCMenuItemImage itemFromNormalImage:@"yes.png" selectedImage:@"ok\_button.png" target:self selector:@selector(okMethod)\];
>
> CCMenu \*menu = \[CCMenu menuWithItems:okButton,nil\];
>
> menu.position = ccp(box.boundingBox.size.width/2,box.boundingBox.size.height/2);
>
> \[box addChild:menu\];

Hope it helps, :)
> 0 votes

---
Tags: gui, cocos2d-x, callbacks, cocos2d-x-js
---


title: Basic Connections Through Socket Server

text:
# Question
Title: Basic Connections Through Socket Server
I'm designing a simple 2 player RTS with Stencyl, a program that uses blocks for coding. The current code updates lists whenever an actor moves (new X and Y), and I'd want the server to update the game state with each change to the list. However, to start off: I don't even know how to set up a socket server. Stencyl has taught me the basics of logic, but I've yet to learn any programming languages.

I've downloaded a Smartfox 2X socket server that I'm intending to use. Right now I'm only looking to make baby steps; I want to do something to this effect: "When someone connects to the server, open *insert file here*". How can I do this? My intention is to have this file be the game client. Is this "open file when connected" method the best way to go about this? When answering: assume that I know nothing, because really, though I have done research (I know that UDP\>TCP for real time), implementation-wise I know nothing.

# Answer
> 1 votes
This may not be relevant anymore but I found some useful information about this subject. The gist of it is that you need to program a server (in a programming language) in order to allow multiplayer for users of your game client (the game your users are running locally). The server allows users to to connect with one another (indirectly) and is required to store each user's state as well as send relevant information about each user's state to all users.

Writing a game server is outside the scope of one question by all means. It requires a basic understanding of Network programming which you could begin to learn by reading Beej's guide. Bassically, this is pretty advanced stuff.

1. If you are not a programmer, the first step would be to learn programming.
2. If you haven't done any network programming, the second step would be to learn from BeeJ's guide and write a simple file sending application (to get the hang of it).
3. Once you understand network programming, you need learn how to use SmartFox, start by making a simple application, like one that sends the mouse position to the server, so all users can see all the mouse cursors.
4. After this you can start building a simple game. Remember to test locally.
5. You need to find a decent place to host your game server, latency, availability, processing power and bandwidth are all relevant issues.
6. Do a beta phase for the game, fix errors, figure out how to prevent cheating and all that.
7. Release your game to the public.

# Answer
> 0 votes
I'm not particularly familiar with either of the mentioned frameworks, but after a small check, here are some pointers:

1. The client runs on your device, the server runs on the server machine, so there should be no need to open any files (i assume you mean execute) as the client is already running the game willing to play and the server merely detects the connection and transmits the data between clients. Your server should have an internal list of connected players (I assume SmartFox takes care of this).
2. The Smartfox 2x examples show how to connect to a server and how to join a room. You could use this as a way to find games and match players against each other. You might need a view in your game where you choose your opponent and "challenge" him to a game. Or if you're just doing this to try out network code, then you can just pick the first guy in the room and start a game with.
3. Your assessment of UDP\>TCP for real time is sorta correct depending on how much data you'll be moving. TCP is more reliable though. I don't exactly know how much nastiness they have removed in the APIs, but with UDP you generally need to be worried about some packets not making it through. Then again, I would imagine that the SmartFoxServer API takes care of this.
4. Depending on how your game is constructed, you might want to transmit the commands over the server and have the game synced up rather than updating all the positions of all the objects in the game all the time. This of course depends a great deal on a) what's easiest? and b) what's efficient? For this part of the communication and delta syncing etc. you can find a bunch of articles online.

I know nothing of Stencyl so I don't know how this integrates into it to begin with.

Hope this helped.

---
Tags: multiplayer, server, online, stencyl
---


title: Getting any type in Unity Inspector

text:
# Question
Title: Getting any type in Unity Inspector
I am developing a SaveManager system for my games. Basicly what it should do is;

1) Gets the "ANY" user created Serializable class by Drag&Drop to inspector. (save data).

2) Writes that class to a file using either BinaryFormatter or XMLSerializer.

I want to be able to use it in my future games. So it should be save data class(type) independant (like serializers). I will use it like an asset, import the SaveManager, give serialized class as parameter, and let it do the rest. But as i said, it should be able to use any user created serialized class.

So the problem is, since that "serialized class" will be written by the user in the "game project" (not in the SaveManager project), and i don't have that "serialized" class type in my SaveManager project, i don't know how to make the SaveManager, reference the class from inspector.

So lets say i create this class in the game project (not in the SaveManager project)

```
[System.Serializable]
public class SaveData
{
    public string Name = "Name";
    public int Number = 5;
}

```

Now when i import the SaveManager project (asset) into my "game" project, i should be able to drag and drop the script to the SaveManager inspector and let it do the rest. Since BinaryFormatter works for every Serializable type, the name of the type is actually doesn't matter. I mean BinaryFormatter is type free as long as the type is serializable. I want to use that feature, and make the SaveManager type free too.

So in future if i want to use, say "MyNewSaveData" serialized class, "in an another game", i want to be able to drag and drop this to SaveManager inspector and let it do the rest.

Now the thing is, if i use

```
public object _SaveData;

```

in SaveManager script, unity inspector doesn't show it.

if i use

```
public Object _SaveData

```

it casts the user created type to an Object, and i lose the type i need.

I tried to use System.Type, but unity doesn't show it too.

Basicly what i want to do is, get "any" serialized class as reference. Like

```
public SerializedClass _SaveData;

```

or something like

```
public Script _SaveData;

```

That reference should accept "any" serialized class. Gets it's type, then casts it to that type.

When i use

```
public Object _SaveData

```

if i use \_SaveData.GetType(), i get the type the "user created". I have the type, in my hands, but i can't cast Object to that type. I don't know how to use that type for casting.

What ever i do, it either doesn't show up in inspector, or it casted to another type and i lose the data.

What should i do?

# Answer
> 1 votes
Make a custom editor! Using the `EditorGUILayout.ObjectField()` Something like this:

```
using UnityEngine;
using UnityEditor;

[CustomEditor(typeof(SaveManager))]

public class SaveManagerEditor : Editor {

SaveData Data;

    public override void OnInspectorGUI(){

       Data = (SaveData)EditorGUILayout.ObjectField(Data, typeof(SaveData),true);
    }

}

```

Oh! Almost forgot the second question! You can save your data as ScriptableObject using this from the wiki.

Hope that helps

---
Tags: unity, serialization
---


title: Animated Energy/Combo Bar (Unity 4.6)

text:
# Question
Title: Animated Energy/Combo Bar (Unity 4.6)
How could I achieve the animated Combo bar effect used in Ski Safari / Ski Safari: Adventure time? Preferably with Unity 4.6 UI. General explanations also welcome!

Links to videos showing the wanted effect: https://www.youtube.com/watch?v=CnfCkqiM890#t=4m46s and https://www.youtube.com/watch?v=aqj61liRJ74#t=7m00s

# Answer
> 0 votes
Was able to accomplish this effect in Unity by using the Mask component in UI and adding an animated sprite to it as a child. Also, big thanks to Anko for help.

---
Tags: unity, animation, gui
---


# Question
Title: How can I chain together Stencil tests from the same re-occurring routine, but keep the tests separate?
Sorry for the bad title; I don't know how else to explain this.

I have a class called a `Container`. An instance of `Container` has other elements "inside" it. These elements have independent positions that are relative to the position of the container.

So if I move the container, the elements inside of it are moved along with it; but keep their distance relative to each other.

This `Container` is therefore like a window through which you can view it's contents.

So, I would like to use a Stencil buffer for this. I have the following code:

```
glEnable(GL_STENCIL_TEST);
glClear(GL_STENCIL_BUFFER_BIT);
glStencilMask(0xFF);    // everything is written to the buffer
glStencilFunc(GL_ALWAYS, 1, 0xFF);
glStencilOp(GL_KEEP,GL_KEEP,GL_REPLACE);
glColorMask(GL_TRUE,GL_FALSE,GL_FALSE,GL_FALSE);

glBindVertexArray(m_screenQuad->GetVAO());

glDrawElements(GL_TRIANGLES,m_screenQuad->GetMesh()->GetIndices()->size(),GL_UNSIGNED_INT,0);

glBindVertexArray(0);
glStencilFunc(GL_EQUAL, 1, 0xFF);
glStencilOp(GL_KEEP,GL_REPLACE,GL_REPLACE);
glColorMask(GL_TRUE,GL_TRUE,GL_TRUE,GL_TRUE);

// draw the things that are visible through this window. The window is defined by m_screenQuad

glDisable(GL_STENCIL_TEST);

```

This works great.

The problem I'm having arises when one of the things that are visible through the window, are also another window.

In the above example you can see that I didn't mask out the red channel, this was to reveal that when the bounds of an "interior" container went outside the edge of he exterior container, the whole stencil doesn't work as planned.

Here's some screen shots with the above code (again, note that the red it to show the different bounds being drawn by the `m_screenQuad` objects).

Here's another image where the object inside the first `Container` is a subsequent `Container`. Each calls the same code above, with the second one being called at the `// draw the things that are visible through this window. The window is defined by m_screenQuad` line.

As you can see, the bounding `m_screenQuad` being drawn in the same way by the internal `Container` overlaps with the external `Container`s `m_screenQuad` and effectively extends the Stencil Mask further than it should.

How do I separate these two different Stencil tests so that they don't affect each other? Consider that the internal `Container` may be smaller than the external one, so it would need to truncate/cut it's internal contents as well.

# Answer
> 1 votes
If all you're using are rectangular areas, consider using glScissor instead.

It is a lot faster as it clips primitives rather than test them per pixel reducing the number of primitives, pixel shader executions, and framebuffer pixels processed.

Stencil test is done at the pixel level, Scissor test is done at the primitive level before the pixel shader.

More complex clipping shapes can be processed using a geometry shader which is still faster than using the stencil buffer.

Otherwise, use all bits of the stencil buffer incrementing the value every time and test for equality.

```
int stencil_index = 0;

foreach(ui layer){

    int ui_layer_stencil_index;

    if(ui shape is complex) {
        ui_layer_stencil_index = ++stencil_index;

        if((stencil_index & ((1 << STENCIL_BITS)-1)) == 0){
            // we warped around, clear stencil to 0
            ui_layer_stencil_index = stencil_index = 1;
            glDisable( GL_SCISSOR_TEST );
            glClear(GL_STENCIL_BUFFER_BIT);
        }
        glStencilMask(-1u);    // everything is written to the buffer
        glStencilFunc(GL_ALWAYS, ui_layer_stencil_index, -1u);
        glStencilOp(GL_KEEP,GL_KEEP,GL_REPLACE);
    }

    glScissor( MAX RECTANGULAR UI LAYER AREA HERE );
    glEnable( GL_SCISSOR_TEST );

    ...

    // draw ui layer area here
    ...

    if(ui shape is complex) {
        glStencilFunc(GL_EQUAL, ui_layer_stencil_index, -1u);
        glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
        ...
    }

    ...

    foreach(elements on this layer)
       // draw objects on this UI layer

```

Note that this does not handle recursive clipping shapes, you can't properly handle all cases with this simple stencil test, you'll have to clear the stencil and process the clipping hierarchy every time.

If that is required it becomes more efficient to calculate the clipped geometry right on the CPU and submit batches of pre-clipped & ordered triangles to the GPU or generate a clipping shape on the CPU from the hierarchy and use the geometry shader to clip to that shape but there is a limit to the shape's complexity that can be processed.

# Answer
> 0 votes
If you need separate stencil tests, you have 8-bits worth of stencil to fool around with. Your code is not accumulating stencil values, it only performs binary set/clear, so that means you can do up to 8 boolean tests per-pixel with the proper masking logic.

Rather than testing for equality versus **1** using the mask `0xff`, you can use a more sophisticated mask to isolate the individual bits. The mask `0x2` and **2** for instance will test the 2nd bit, while `0x1` and **1** will test the 1st. Right now you are using the entire 8-bit stencil buffer to do a single boolean test, and that is not going to help you at all.

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


# Question
Title: How to make an object oscillate left and right?
I can't seem to make an object move left and right, back and forth, on room start whilst on solid ground.

Codes I used:

```
Step Event:

if image_index is greater than 5, then physics_apply_force (0,0,100,0) for the right

if image_index is less than 5, then physics_apply_force (0,0,-100,0) for the left

```

# Answer
It sounds like you desire Simple Harmonic Motion; if so, you must apply a force proportional to, but of opposite sign from, the displacement from the origin of the motion to have it be stable.

That is to say, apply a force with components Fx = - c * x and Fy = - d * y.
> 2 votes

# Answer
I have received help from a person on Youtube. He gave me an example, showing the code to be phy\_speed\_x=-10 for the object to move left or phy\_speed\_x=+10 to move right, whilst using physics. I was using the wrong code all along!
> 0 votes

# Answer
I don't understand what you're trying to do, but if you want an object to move back and forth somewhere in your room, you could multiply that object SpeedX variable by -1 in whatever Event you want it to bounce, this way it will invert its horizontal speed and make it go the other way.
> -1 votes

---
Tags: physics, movement, game-maker
---


title: memorizing button tap code iOS game

text:
# Question
Title: memorizing button tap code iOS game
I'm using a single view app in Xcode 6.1 for my game with Storyboards. Not unity or sprite kit. It's a small game not even 3MB. Anyways, I created un-lockable characters with a BOOLEAN.

```
-(void)hidden{
 if(scoreNumber  > 9  || HighScoreNumber >9){
 BlueChar=YES;
 }

 -(IBAction)Blue{

  bird.image=[UIImage imageNamed:@"BLUE.png"];

 if(BlueChar ==YES){       //BlueChar=BOOL
 BlueChar.hidden=NO;
 }

```

When you click on BlueChar button, the UIImageView is connected to BlueChar character. So when you tap START GAME button game starts and you play as BlueChar. Then when it's GameOver and you click START GAME button again, the BlueChar button that was clicked isn't saved and instead you play as Original Character.

How do I make it that if you click BlueChar button ONCE, now you can play as BlueChar forever unless you click on another button that represents another character? How do I make the game save the last button clicked unless user clicks on another button in Objective-C code?

# Answer
Don't rely only on the storyboard to do all the work in your game. You need some properties for which character is currently selected and other game states. Then in `viewDidLoad` and/or in the method for the Start Game button, set the `bird.image` to be blue if that's the status.

To save off this info between runs of the game utilize the messages for foreground / background state changes:

```
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(movingToBackground:) name:UIApplicationWillResignActiveNotification object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(movingToForeground:) name:UIApplicationDidBecomeActiveNotification object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateDefaults:) name:UIApplicationWillTerminateNotification object:nil];

```

Then create those methods to handle the app moving to the background and save off the game state.

Like this:

```
-(void) updateDefaults: (NSNotification *) notification {
    [defaults setObject:[NSNumber numberWithBool: BlueChar] forKey:@"BlueChar"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

```

But honestly. If you have more than one character to play you're not going to want it to be `BlueChar` as a `bool` because really you'll want something like `int currentChar` where `currentChar=BLUE_CHAR` and `#define BLUE_CHAR 1` so that you can also set `currentChar` to be `YELLOW_CHAR` or `ORANGE_CHAR`. Maybe the `BlurChar` bool is used to check if it's unlocked, and the `currentChar` int is used to store which one you're playing with. Depends. So instead of the above you'd do:

```
[defaults setObject:[NSNumber numberWithInt: currentChar] forKey:@"currentChar"];

```

That's one way to do it anyway.

Then on the `IBAction` you're going to set `currentChar` to be `BLUE_CHAR` (if it's unlocked). Then call a `setCharImage` method which could set it based on any number of options:

```
-(void)setCharImage:
    switch (currentChar) {
        case BLUE_CHAR:
        {
            bird.image=[UIImage imageNamed:@"BLUE.png"];
            break;
        }
        case YELLOW_CHAR:
        {
            bird.image=[UIImage imageNamed:@"YELLOW.png"];
            break;
        }
        ....

```

In my games I have a .h file where I stuff all the #defines like that. IMHO it's a toss up if you use those or enums. I personally prefer #defines. But I'm an old 80's C coder and I prefer those ways.
> 1 votes

---
Tags: game-design, ios, game-mechanics, objective-c, memory-efficiency
---


title: glVertexAttribPointer stride ambiguity

text:
# Question
Title: glVertexAttribPointer stride ambiguity
As a hobbyist junior game programmer, I have done multiple small OpenGL projects just to have fun with 3D. I've tested VBOs in C++ and in Java and I found something or rather understood Java tutorials differently than the C++ ones. When using the glVertexAttribPointer function in Java, it is told that the parameter stride (second from the end) is the size of an entire vertex.

```
void glVertexAttribPointer( GLuint index,
                            GLint size,
                            GLenum type,
                            GLboolean normalized,
                            GLsizei stride,
                            const GLvoid * pointer);

```

Considering the following my interpretation of the Java/OpenGL tutorial, this is what should be done (as example) in C++:

```
glVertexAttribPointer(vertexLoc, 3, GL_FLOAT, GL_FALSE, sizeof(MyVertex), BUFFER_OFFSET(0));
glVertexAttribPointer(normalLoc, 3, GL_FLOAT, GL_FALSE, sizeof(MyVertex), BUFFER_OFFSET(sizeof(float)*3));
glVertexAttribPointer(texCoord0Loc, 2, GL_FLOAT, GL_FALSE, sizeof(MyVertex), BUFFER_OFFSET(sizeof(float)*6));

struct MyVertex
{
    float x, y, z;
    float nx, ny, nz;
    float s0, t0;
};

```

Now I'm really confused because this works in my Java code. However, in my old C++ code, I was something like this:

```
glVertexAttribPointer(vertexLoc, 3, GL_FLOAT, GL_FALSE, sizeof(MyVertex) - sizeof(aPosition), BUFFER_OFFSET(0));
glVertexAttribPointer(normalLoc, 3, GL_FLOAT, GL_FALSE, sizeof(MyVertex) - sizeof(aNormal), BUFFER_OFFSET(sizeof(float)*3));
glVertexAttribPointer(texCoord0Loc, 2, GL_FLOAT, GL_FALSE, sizeof(MyVertex) - sizeof(aTextCoord), BUFFER_OFFSET(sizeof(float)*6));

```

My question is: should the stride parameter be the size of an entire vertex in bytes or should it be the number of bytes separating another vertex attribute of the same type, i.e. the size between two normals, positions, texture coordinates, ect?

# Answer
> 1 votes
I have successfully used stride as the size of the row (with interleaved attribute buffers), that is, size of entire vertex data struct. I know this is not a good answer, but even the description in documentation is bit unclear:

```
"Specifies the byte offset between consecutive generic vertex attributes."

```

(https://www.opengl.org/sdk/docs/man4/html/glVertexAttribPointer.xhtml)

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


# Question
Title: How can I deal with vertex precision errors between terrain chunks?
I am using OpenGL to render the following scene, using vertex data from one of the map files of a popular MMORPG. The data is chunked and the pictured scene is made up of 256 (16x16) chunks.

However between the chunks I am seeing what I believe to be glitches due to the float precision. Yet I am not doing any large translations and rendering very close to the origin, should I be seeing this problem? The glitches very noticeable as you fly over the scene with it flickering different points along the chunk edges.

I was wondering if I was overlooking something simple or there are tricks other games use to mask this problem. I guess the source data could be the reason for this problem but I am not aware of it happening in the original game.

View screenshots in a new window to see the issue.

# Answer
> 2 votes
The loss of precision happens due to the rotation in your **combined** view-model or projection-view-model\` matrix.

You will need to use a vertex shader (if not already using one) and apply the model matrix (or a plain translation in your case since those are axis-aligned chunks) before applying the view-projection **separately**:

```
uniform vec2 chunk_offset;

...

vec4 temp = vec4(chunk_vertex.xy + chunk_offset, chunk_vertex.z, 1) * projection_view_matrix;

```

The isue is because the +/- chunk offset gets **rotated first** and put into the translation part of the combined projection-view-model matrix causing an initial precision loss before being added to the also-rotated vertex coordinates (another precision loss).

Separating the operations avoid this loss of precision and your `+0.5 vertex` will match your `-0.5 vertex` \+ `1.0 chunk offset` perfectly giving the exact same value which will then be rotated with both hitting the same loss of precision in the projection-view matrix.

---
Tags: opengl, terrain, vertex, floating-point, precision
---


# Question
Title: What is the best way to keep track of time in a game?
I'm getting to the part in development where I'm noticing that timing is going to be an issue.

If I put my movement update in the same function where I draw the scene, then a low FPS means slower movement and a high FPS means very fast movement. But putting it in its own function that is called every 1/60th of a second still has problems. I'm starting to realize that there is no way you can rely on a scheduled function to keep track of time. It is just way too unreliable.

But I still need to be able to move at the same speed regardless of the FPS that a computer can handle. So what is the best way to keep track of time and move around?

# Answer
Well, I am not sure what language you use for your game so I'll explain it in C++, but you could use something called 'deltatime'

```
Uint32 last = 0;
Uint32 delay = 0;

void loop()
{
    Uint32 now = SLD_GetTicks();

    if(now > last)
    {
        delay = now - last;
        last = now;
    }

    moveUp(delay);
}

void moveUp(Uint32 delay)
{
    positionY += speed * delay; // This lowers or highers the speed depending on the delay.
}

```
> 2 votes

# Answer
This is how I do it in iOS games:

```
// get's called approx every 60th of a second but not always
- (void)drawViewLoop
{
    timeThisRound = CFAbsoluteTimeGetCurrent();
    deltaTimeThisRound = timeThisRound-lastTime;
    // don't let the delta get too big.  Even if the fps slows way down cap delta at 1/20th of a second
    if (deltaTimeThisRound > 0.05) {
        deltaTimeThisRound = 0.05;
    }
    [self drawScene];
    // present screen
    [self updateScene];

    lastTime = timeThisRound;
}

```

I usually don't let my delta get huge. Let's say some system thing happened, they put the app in the background, or whatever. If it's larger than .05 then I let things start dragging because to me that's better than having time jump forward 3 or 4 seconds and your ship blows up. Also a `deltaTimeThisRound` of say 3.0 would mess up all the physics math.

Some of my animations are frame based. So no matter how fast things are progressing it will show all N number of frames of that animation. For those each time I hit drawViewLoop I increment the frame of the sprite that you see.

Some of my animations are time and percentage based. Where p % through the move is calculated by taking `timeStart` of the move, `duration` of the move, and `timeThisRound - timeStart` to get a time from the start of the move. So `p = timeThrough / duration` with some clamping and completion handling on 0 and 1.0.

Some of my animations are physics based where `position += velocity * deltaTimeThisRound`. These are the ones that are effected by clamping my delta at .05.
> 1 votes

# Answer
Any answer that doesn't link to Glenn Fielder's Fix Your Timestep article isn't an answer at all. So first, read that, because it more than addresses your problem. Note that you do not have to implement his ultimate solution in order to have a reasonably well behaved simulation.

Yes, you *can* use a raw delta time, clamped or otherwise, as other answers have suggested, but this will ultimately lead to inconsistent simulations due to the inherently unpredictable fluctuation of the time between frames.

The root of the issue is that you are essentially utilizing Euler's method to solve an ordinary first order differential equation for **x** when you do this:

```
x = x + delta * rate

```

Aside from the fact that Euler's method isn't the best approximation of the actual solution, it's generally OK **as long as delta is the same every time**. If it's not, then your simulation will not be deterministic, or worse, completely screwed when you pass in some bonkers delta that sends your object through a wall.
> 1 votes

---
Tags: movement, optimization, fixed-timestep
---


# Question
Title: Why not just create very high resolution graphics and use them on all screens?
I'm creating a game with pretty basic graphics (numbers, blocks, words, and a few nice design elements for the logo and such). My question is: can I create everything in a very high resolution- say 2048x2048- and just let libGDX scale these depending on the screen size? The reason I ask is because I've seen questions that ask about creating a copy of the assets in various resolutions. What's wrong with just using one asset set that's a very high resolution on all devices?

# Answer
> 1 votes
I've never used libGDX but textures Cost a lot of memory in general. Which isn't a big deal on PC but you have to watch out with mobile devices which have limited resources.

Let's say you have a device with 256MB of memory, you have 10 textures in your scene and each texture is about 8MB (assuming we're using 2048x2048 32-bit png). Thats using about 30% of your total ram!

That and some devices have **hardware limitation on texture sizes**.

# Answer
> 1 votes
If you let your library scale down the textures and drop the originals from memory then you will not have any problems with memory consumption. Your load times will however increase drastically, along with the download size and storage space needed for your game.

If you are going to ship on phones then you should definitely scale your textures lower than you would for PC, the small phone screens simply don't benefit from very high resolution textures.

Some games have a high and a low resolution texture pack on the same platform, allowing those who don't need or want the high resolution textures to not download them at all. A simpler approach is to have the game generate the low resolution textures if needed, and then store them on disk so that they can be loaded directly next time, thus decreasing loading times.

---
Tags: libgdx, textures, graphics
---


# Question
Title: How to deform 2D tileable texture in XNA/MonoGame
I'm looking for a way to deform tillable texture in a 2D game I'm building using MonoGame but I'm not sure how this effect is called and searching the internet for "deforming textures" gives me mostly articles about 3D.

I want to texture procedurally generated terrain which can contain lots of little hills. Like on the following picture:

I've deformed this image using Photoshop's free transform tool and I would like to know how can I do this in code.
And also, I would like not to have this "obviously deformed" look with blurred areas where deformation occurred.

# Answer
> 1 votes
I assume your noise is outputting height values for the terrain - the style shouldn't matter, as that's applied after the noise is done with. Add a lower octave of noise and add (or otherwise combine) them together. The lower the octave (larger amplitude and lower frequency) the larger/longer the features it creates, so to add hills you need to add that sort of noise.

I can't help more specifically without seeing your noise generation code, but hopefully that's enough to get you on the right track.

Edit: I just realized, your terrain looks basically flat. It's only the texture that seems to be procedurally generated, yes? If that's the case, then you just need to do what I was assuming above, and generate a layer of noise that you use for terrain height and then make your "land tiles" vary in shape/size by that noise before even generating the texture.

# Answer
> 1 votes
All you need to do is first create a mesh and then distort it.

1. Create a mesh that's just a strip of triangles.
2. Texture the mesh using your terrain texture.
3. Deform each vertex of the mesh by using perlin noise. What I mean exactly is this:

```
// Deform a 3D vertex by noise
vertex.position.y += Perlin(vertex.position.x, vertex.position.y, vertex.position.z);

```
4. Draw the mesh.

You will want to mess with how you sample the noise to get the effect you want. You can even distort the vertex' `x` coordinate a little to give an interesting overhang effect.

---
Tags: xna, 2d, textures, monogame, terrain
---


# Question
Title: Why transforming coordinates in dimetric games?
What are the advantages of transforming coords, since you can still render isometric graphs having normal 2D coords?

# Answer
> 2 votes
You're using a transform one way or another.

With an isometric view you can pre-transform your entire scene but technically will still be using a transform if you do any scrolling. It'll be just a translation but it's still a transform.

Doing transform on the fly lets you move the camera. (Taking a page from the hitch-hiker's guide: you're actually moving the entire universe the opposite way.)

Cheers,

Edit: Having your world in 3D but projecting iso lets you rotate the camera, like many tactics games do:

---
Tags: isometric
---


# Question
Title: Advanced Cellular Automata to generate caves
I am trying to make caves in Unity. To do this, I am trying to use cellular automata. I found the following (Rouge Basin Cellular Automata for Caves) that resembles what I am trying to accomplish.

However, the tutorial is not entirely what I want. I want something like what is produced by this website(Don Jon Caves) with the "cavernous" setting (see image below).

As you can see in the image, everything is connected. I have tried numerous methods and libraries, however nothing has worked.

I have been struggling with this issue for a while, and I would appreciate any guidance what so ever.

Thanks

# Answer
> 4 votes
I am not sure the approach used by the example you show, but here is how I'd probably go about creating something similar...

First, create an undirected network graph, something like this...

You'd generate it from a set of randomly placed nodes, including at least one that represents your cave entrance/exit.

Now that you have this graph, imagine if you were to first open up a set of passages along each vertex - just simple straight passages, not irregular.

Now you've basically got a cave, but with very smooth walls. It would look something like this from the above graph...

So the thing to do then is take those walls and "erode" them to create rough and irregular walls. Taking the example here, this is what you might get...

And if in the process, you erode through into another hall, then no problem - you've just created a new cavern!

The original graph image is from http://mathinsight.org/undirected\_graph\_definition

# Answer
> 1 votes
one way to do this is to group all the caves with a disjoint set and then remove all but the biggest

```
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
public class DisjointSet
{
    private List<int> _parent;
    private List<int> _rank;
    public DisjointSet(int count)
    {
        _parent = Enumerable.Range(0, count).ToList();
        _rank = Enumerable.Repeat(0, count).ToList();
    }
    public int Find(int i)
    {
        if (_parent[i] == i)
            return i;
        else
        {
            int result = Find(_parent[i]);
            _parent[i] = result;
            return result;
        }
    }
    public void Union(int i, int j)
    {
        int fi = Find(i);
        int fj = Find(j);
        int ri = _rank[fi];
        int rj = _rank[fj];
        if (fi == fj) return;
        if (ri < rj)
            _parent[fi] = fj;
        else if (rj < ri)
            _parent[fj] = fi;
        else
        {
            _parent[fj] = fi;
            _rank[fi]++;
        }
    }
    public Dictionary<int, List<int>> Split(List<bool> list)
    {
        var groups = new Dictionary<int, List<int>>();
        for (int i = 0; i < _parent.Count; i++)
        {
            Vector2 p = PathFinder.Instance.TilePosition(i);
            if (PathFinder.Instance.InsideEdge(p) && list[i])
            {
                int root = Find(i);
                if (!groups.ContainsKey(root))
                {
                    groups.Add(root, new List<int>());
                }
                groups[root].Add(i);
            }
        }
        return groups;
    }
}

```

here is where i create my cellular list and sometimes remove the small ones i combine multiple lists sometimes and also use these lists for generating and outlining bodies of water and flora (patches of trees, flowers, grass) and fog

```
private List<bool> GetCellularList(int steps, float chance, int birth, int death)
{
    int count = _width * _height;
    List<bool> list = Enumerable.Repeat(false, count).ToList();
    for (int y = 0; y < _height; y++)
    {
        for (int x = 0; x < _width; x++)
        {
            Vector2 p = new Vector2(x, y);
            int index = PathFinder.Instance.TileIndex(p);
            list[index] = Utility.RandomPercent(chance);
        }
    }
    for (int i = 0; i < steps; i++)
    {
        var temp = Enumerable.Repeat(false, count).ToList();
        for (int y = 0; y < _height; y++)
        {
            for (int x = 0; x < _width; x++)
            {
                Vector2 p = new Vector2(x, y);
                int index = PathFinder.Instance.TileIndex(p);
                if (index == -1) Debug.Log(index);
                int adjacent = GetAdjacentCount(list, p);
                bool set = list[index];
                if (set)
                {
                    if (adjacent < death)
                        set = false;
                }
                else
                {
                    if (adjacent > birth)
                        set = true;
                }
                temp[index] = set;
            }
        }
        list = temp;
    }
    if ((steps > 0) && Utility.RandomBool())
        RemoveSmall(list);
    return list;
}

```

here is the code that removes the small groups from the list

```
private void UnionAdjacent(DisjointSet disjoint, List<bool> list, Vector2 p)
{
    for (int y = -1; y <= 1; y++)
    {
        for (int x = -1; x <= 1; x++)
        {
            if (!((x == 0) && (y == 0)))
            {
                Vector2 point = new Vector2(p.x + x, p.y + y);
                if (PathFinder.Instance.InsideEdge(point))
                {
                    int index = PathFinder.Instance.TileIndex(point);
                    if (list[index])
                    {
                        int index0 = PathFinder.Instance.TileIndex(p);
                        int root0 = disjoint.Find(index0);
                        int index1 = PathFinder.Instance.TileIndex(point);
                        int root1 = disjoint.Find(index1);
                        if (root0 != root1)
                        {
                            disjoint.Union(root0, root1);
                        }
                    }
                }
            }
        }
    }
}
private DisjointSet DisjointSetup(List<bool> list)
{
    DisjointSet disjoint = new DisjointSet(_width * _height);
    for (int y = 0; y < _height; y++)
    {
        for (int x = 0; x < _width; x++)
        {
            Vector2 p = new Vector2(x, y);
            if (PathFinder.Instance.InsideEdge(p))
            {
                int index = PathFinder.Instance.TileIndex(p);
                if (list[index])
                {
                    UnionAdjacent(disjoint, list, p);
                }
            }
        }
    }
    return disjoint;
}
private void RemoveSmallGroups(List<bool> list, Dictionary<int, List<int>> groups)
{
    int biggest = 0;
    int biggestKey = 0;
    foreach (var group in groups)
    {
        if (group.Value.Count > biggest)
        {
            biggest = group.Value.Count;
            biggestKey = group.Key;
        }
    }
    var remove = new List<int>();
    foreach (var group in groups)
    {
        if (group.Key != biggestKey)
        {
            remove.Add(group.Key);
        }
    }
    foreach (var key in remove)
    {
        FillGroup(list, groups[key]);
        groups.Remove(key);
    }
}
private void FillGroup(List<bool> list, List<int> group)
{
    foreach (int index in group)
    {
        list[index] = false;
    }
}
private void RemoveSmall(List<bool> list)
{
    DisjointSet disjoint = DisjointSetup(list);
    Dictionary<int, List<int>> groups = disjoint.Split(list);
    RemoveSmallGroups(list, groups);
}
private bool IsGroupEdge(List<bool> list, Vector2 p)
{
    bool edge = false;
    for (int y = -1; y <= 1; y++)
    {
        for (int x = -1; x <= 1; x++)
        {
            if (!((x == 0) && (y == 0)))
            {
                Vector2 point = new Vector2(p.x + x, p.y + y);
                if (PathFinder.Instance.InsideMap(point))
                {
                    int index = PathFinder.Instance.TileIndex(point);
                    if (!list[index])
                    {
                        edge = true;
                    }
                }
            }
        }
    }
    return edge;
}

```

or if you don't remove small just put your stuff in biggest cave

```
private List<int> Biggest(List<bool> list)
{
    DisjointSet disjoint = DisjointSetup(list);
    Dictionary<int, List<int>> groups = disjoint.Split(list);
    RemoveSmallGroups(list, groups);
    IEnumerator<List<int>> enumerator = groups.Values.GetEnumerator();
    enumerator.MoveNext();
    List<int> group = enumerator.Current;
    return group;
}

```

...

```
public int TileIndex(int x, int y)
{
    return y * Generator.Instance.Width + x;
}
public Vector2 TilePosition(int index)
{
    float y = index / Generator.Instance.Width;
    float x = index - Generator.Instance.Width * y;
    return new Vector2(x, y);
}

```

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


# Question
Title: How do OpenGL's texelFetch and texture differ?
I understand the main differences between `texelFetch` and `texture`, but have some questions about the details:

* Does `texelFetch` involve a performance penalty? Such as not using a cache or such?
* Are `texelFetch` and `texture` interchangeable when using `GL_NEAREST`?

# Answer
> 29 votes
`texelFetch` is quite different from `texture`.

`texture` is your usual texture access function which handles filtering and normalized (`[0,1]`) texture coordinates. `texelFetch` directly accesses a texel in the texture (no filtering) using unnormalized coordinates (e.g. `(64,64)` in the middle-ish texel in a 128x128 texture vs `(.5,.5)` in normalized coordinates).

# Answer
> 11 votes
Since there's no accepted answer I add some info, I wanted just to add things not already said by Sean in his answer.

**TexelFetch** treats the texture as a Image, so you can access exactly the content of pixels. You usually do that when you need exactly that content, which is in few but usefull occasions:

* Certain post processing filters (Guassian blur exploits texture sample interpolation and so it cannot use TexelFetch)
* When vertices needs to read data from textures and that is a operation dependent on 2 coordinates

**Tex2D** treat the texture as a texture. You don't want the exact content of a pixel, but you want the most realistic result. A standard texture read is a very complex operation and it involves reading interpolated data from one or more mipmap levels and then it interpolates again. All those expensive operations are to avoid visual artifacts.

GL\_NEAREST will not work the same because on farest polygons you are reading data in the smaller mipmap level, wich is not the same exact data you would read from a texel fetch.

There is one case where Tex2D (almost) work the same of TexelFetch:

1. filter is GL\_NEAREST
2. you are using a incomplete mipmap pyramid with 1 level
3. your UVs are not normalized vertex components (but you have to normalize them in the shader)

---
Tags: opengl, textures, performance
---


# Question
Title: How can I "publish" an Android game without Google Play?
I'm new to development and trying to get a sense for the obstacles to publication

If I need to circumvent the Google Play app store, can I publish a game to a website that people can visit in a mobile browser and download and install like any other app?

How does publishing "around" Google Play work? Are there any particular success stories, best practices or problems I should be aware of?

---

Apologies if there is an obvious answer. I believe I found the answer at one point, but I don't remember and can't find the link.

edit: Thanks everyone! I really appreciate the help. Definitely answers my questions. Looks like I have some options!

# Answer
Android is an open platform, so you are free to exchange APKs by other means—for instance by email. The Android Development Center discusses this.

The caveat: App installation from non-marketplace sources is disabled by default in the security settings of most Android distributions. Users must manually enable the option first.
> 28 votes

# Answer
Yes there are other platform where you can publish your game and they have huge market there.

Amazon App Store

Samsung Galaxy Apps
> 6 votes

# Answer
Apart from the usual communication methods (such as email, and just downloading it from a website) there are places you can upload an APK (like an alternate store. For example, Aptoide).

Naturally, these are (most likely) less well known than the Google Play Store, and probably get less traffic.
> 5 votes

# Answer
I'm using the Amazon App store, SlideME store, Aptoid, etc. and there are a lot of users doing the same. Uploading on one of those could be an option for you.
> 2 votes

---
Tags: android, distribution, google-play
---


# Question
Title: In HaxeFlixel, how do I avoid hard-coding dialogue?
I'm planning to develop a visual novel in Haxe Flixel and wanted to know if there is a easier way to add dialogue than to hardcode them in every square. I don't know if I can import a txt file with the dialogues or something like that so I can simple change the txt file instead of have to check the code for every typo.

# Answer
> -1 votes
You'd better use a script engine to do that. There are plenty of script engines in Flash AS3, but for Haxe, all I know is hscript. However, hscript doesn't have the handy ability to suspend in the middle of the scripting, which I think is very important in your case.

So you may need to find a script engine in Haxe that can suspend in the middle of its scripting like the BISE engine in AS3, or write your own in Haxe (Although I'm forking hscript to support that feature, I'm not sure when it'll be ready for a release), or switch to AS3 and use BISE.

# Answer
> 2 votes
`openfl.Assets.getText("assets/dialogs/exampleDialog.txt");` should do the trick.

# Answer
> 1 votes
Gama11's method is the one I would use personally. Basically you put all of your text inside a text file dialog.txt and split each dialog up with some special character or character sequence (i.e. @@).

------ dialog.txt ------

```
This is dialog for box 1.@@
Dialog for box 2.@@
And so on...@@

```

inside of your game use the following:

```
var dilog_boxes:Array<String> =
    openfl.Assets.getText(AssetPaths.dialog.__txt).split("@@");

```

now all you need to do is access the array for each specific block you need. If you need text for block 1, use dialog\_boxes\[0\], block 2 is dialog\_boxes\[1\], etc.

---
Tags: flixel, import, haxe, dialogue-tree, visual-novel
---


title: Box2D—how make character tilt

text:
# Question
Title: Box2D—how make character tilt
I have got a floating character, which should be a robot like thing, floating over the ground, whereby I am using the »hovercar« effect described here. Zhe Image below outlines the basic setup of the physics

The Green rectangle is the chassis, its not allowed to rotate and held up by the »hover-power«. Attached to this is the robots head with an revolute joint, and attached to the head is the robots body, with another revolute joint. There are some more distance Joints for damping this, but not of interest for now.

In the next image one can see how the body of the robot should be tilted when it is in motion to the right or left.

Right now, the movement of the character is implemented so that forces and impulses are applied to the chassis body. Especially if there is an Impulse to the left or right, the desired tilt of the robots body comes to happen, but it fades away when the velocity becomes more constant, or acceleration comes closer to zero.

What can I do to keep the robots body tilted, when it is in motion?

# Answer
The move of the body is due to the air resistance.
You should apply a -k\*v force to the lower part of the body.
Or even more accurate : project the speed vector on the frontmost line of the body : you now have Speed = (sx',sy'). Now apply two different coefficient, k1 and k2, for sx' and sy'. k1 would be the coefficient induced by some air coming face to the body, and k2 is the coefficient when the air comes from below the body (like 8 times smaller).
This way you'll have a realistic behavior : when going up the robot will be aligned, and the effect when going right or left will be the one you seek.

```
F = -k1 * sx ' * U - k2 * sy' *  V
Or :
F = - k1 * ( S • U ) * U - k2 * ( S • V) * V

```
> 1 votes

# Answer
Why dont you apply force during the render thread. You can set a boolean value start and stop the tilt, since its under the render thread it will probably stay tilted since that same force is being applied constantly
> -1 votes

---
Tags: box2d, character, motion
---


title: Referencing in unity

text:
# Question
Title: Referencing in unity
**Background:** We have two people in the team, one of which is a UI designer and the other is the Unity3d developer. The designer makes the 3d models in Maya and sends them to developer so that he can add interaction.

**Issue:** Once the developer starts putting the functionality on top of the model, we lose a lot of flexibility in terms of UI development. Specifically- any change in the textures/colours of the walls requires him to hook up the action scripts from scratch for the new model.

**Question:** Is there something like 'referencing' in unity3d so that we can keep improving the functionality and the aesthetics in parallel?

# Answer
> 3 votes
I think you're trying to use the model directly. i.e. attach script, modify the public parameters, tuning positions, etc.

So it looks like:

```
model (created by artist)
+- script
 \+-- other GameObject
 \+-- other GameObject
+- script (e.g. Character Controller)

```

I face this problem before when I (both programmer and designer) started creating game. I think the easy way to avoid this problem is not to attach these artifacts (scripts, etc) to the model. You can create an Empty object and attach the artifacts to the empty object instead. And this makes the model as just a 'display' thing that you control. It requires some changes though. So it should look like:

```
EmptyObject
+- script
 \+-- other GameObject
 \+-- other GameObject
+- script (e.g. Character Controller)
 \+-- model (created by artist)

```

At the iterations (e.g. artist change the model), you just remove and reattach the model. Hope this reduce your inflexibility.

~Poh~

---
Tags: unity, asset-workflow
---


# Question
Title: what is the very last element of a 4x4 transformation matrix for?
while its a similar value to its neighbour - Z translation (and I wont say if thats above or to the left for fear of sparking a religious war!) and it only seems to change when the Z translation value changes, however the value is not quite the same

Normally I just see either this value ignored or just a 1 in all the tutorials I've seen

Can someone explain exactly what this last element does ?

# Answer
> 4 votes
The value is for Homogeneous Coordinates. Using homogeneous coordinates makes it possible to use things like quaternions and projection matrices. The last entire row is actually for dealing with homogeneous coordinates.

Essentially, the coordinates transformed by a 4x4 matrix will be a 4x1 vector, with (X,Y,Z,W) components. The final values of (X,Y,Z) are determined by taking the homogeneous coordinates and dividing them by W.

E.g. 1

```
[4,2,1,2] is transformed to [2,1,0.5,1]

```

Wherein the final XYZ coordinates are then (2,1,0.5). Again, this is useful for dealing with quaternions and creating projection matrices.

E.g 2

```
Projection of point p onto the plane
 orthoganal to the Z axis and distance d
 from the 'camera'.

               .p
     d   |               <- given
c--------|------------>Z
         |

     d   |.p'
c--------|       <- desired projection
         |

p' = (d / p.z) * p

x' = dx / z
z' = d

d 0 0 0 * x = dx -> dx / z
0 d 0 0   y   dy    dy / z
0 0 d 0   z   dz       d
0 0 1 0   1    z       1

```

In the case of a projection matrix, homogeneous coordinates allow the projection of scene geometry onto a plane (the screen).

---
Tags: opengl, matrix, transformation
---


# Question
Title: How to implement this kind of ripples with a GLSL fragment shader?
So I have already implemented the reflection part:

```
uniform sampler2D texture;
uniform vec2 resolution;
uniform vec3 overlayColor;

void main()
{
vec2 uv = gl_FragCoord.xy / resolution.xy;

if (uv.y > 0.3)// is air - no reflection or effect
{
    gl_FragColor = texture2D(texture, vec2(uv.x, uv.y));
}
else
{
    // Compute the mirror effect.
    vec4 color = texture2D(texture, vec2(uv.x, 0.6 - uv.y));
    //
    vec4 finalColor = vec4(mix(color.rgb, overlayColor, 0.25), 1.0);
    gl_FragColor = finalColor;
}
}

```

source

Now the question is how are these ripples implemented?

# Answer
> 12 votes
I tried to implement what teodron suggested:

```
void main()
{
    vec2 uv = gl_FragCoord.xy / resolution.xy;
    float sepoffset = 0.005*cos(iGlobalTime*3.0);
    if (uv.y > 0.3 + sepoffset)// is air - no reflection or effect
    {
        gl_FragColor = texture2D(texture, vec2(uv.x, -uv.y));
    }
    else
    {
        // Compute the mirror effect.
        float xoffset = 0.005*cos(iGlobalTime*3.0+200.0*uv.y);
        //float yoffset = 0.05*(1.0+cos(iGlobalTime*3.0+50.0*uv.y));
        float yoffset = ((0.3 - uv.y)/0.3) * 0.05*(1.0+cos(iGlobalTime*3.0+50.0*uv.y));
        vec4 color = texture2D(texture, vec2(uv.x+xoffset , -1.0*(0.6 - uv.y+ yoffset)));
        //
        //vec4 finalColor = vec4(mix(color.rgb, overlayColor, 0.25), 1.0);
        gl_FragColor = color;
    }
}

```

It looks pretty close (it's hard to tell without the base image) but you can tweak the parameters.

You may see it in action there: https://www.shadertoy.com/view/Xll3R7

Some remarks:

* I had to invert the y coordinate since I was getting the image upside down, but it may depend of what you pass into resolution.xy; if the result is inverted for you, just uninvert uv.y
* I changed your uniform declarations so it works with shadertoy. You can ignore those changes.
* You will need however to add a uniform providing the time and use it in place of iGlobalTime (which is the time in seconds)
* I added a tide effect since it looks like there is one on your example but it's hard to tell (see sepoffset variable). You may remove it if you don't like it
* I removed the overlay color since it was not looking good, and your example didn't had one
* To tweak the effect to your taste:
    + change the factor of iGlobalTime to speedup/slowdown the effect (you can change each of them separately if you want, let's say accelerate the x movement and slow down the y movement)
    + change the cos() factor to amplify/attenuate the effect

EDIT: I changed the yoffset to include the modification from @cepro

---
Tags: 2d, shaders, glsl, water, reflection-rendering
---


# Question
Title: Where to store service urls for a Unity3D game
I have URL information for services (dozens of them) that I want to store in a Unity3D web player project. What is a good practice for storing it. (please don't say hard coding them)

I've recently joined a large scale Unity 3D project in the business world. I've noticed that there is no configuration file of any type. I.e. All URLs for service calls are hard coded. (among other configuration settings that are not typical for player editing)

While looking for a good solution to store/load, I'm seeing that: 1) Unity does not appear to have any kind of AppSettings. I.e. like Visual Studio dlls/exes/services might. (PlayerPrefs expressed in #3)

2) Web Player (which the project uses) does not support File IO, to store my own config.xml/config.json type file.

3) PlayerPrefs appears that it will remain isolated to the local machine. Updating the project does not replace the player prefs, and new variables are supposed to be hardcoded to populate the PlayerPrefs if those variables didn't already exist.

4) Hard Coding the values creates a hefty inconvenience, as we push our solutions from Dev to Test to Staging to Prod, we have to make sure to replace a code file. (typically systems are designed to change config files.) Additionally, once the code was built, we wouldn't be able to reasonably change the settings to experiment with different servers or other configuration changes.

What would you recommend?

# Answer
> 3 votes
We actually got over this problem in a non-game application by using an XML file (you could also use JSON if you prefer). This is compiled into our application so we don't use IO for it, we instead use XML. This does obviously mean you have to re-compile when making changes though.

Our file looked something like this:

services.xml

```
<services serverURL="https://services.our-api-url.com">
    <service>
        <label><![CDATA[GETSTATUS]]></label>
        <url><![CDATA[/status]]></url>
        <method><![CDATA[GET]]></method>
        <header></header>
        <type></type>
    </service>
    <service>
        <label><![CDATA[LOGIN]]></label>
        <url><![CDATA[/session]]></url>
        <method><![CDATA[POST]]></method>
        <header></header>
        <type></type>
    </service>
    <service>
        <label><![CDATA[LOGOUT]]></label>
        <url><![CDATA[/session]]></url>
        <method><![CDATA[DELETE]]></method>
        <header><![CDATA[x-spk-auth-token]]></header>
        <type></type>
    </service>
</services>

```

For every new service we add a new entry on here, then we simply search for a service with the matching label name that we pass into our little setup service call function. This function then extracts out the method, any headers that are required and types and append it all correctly to our serverURL that is pulled out first.

It's a nice little way of doing this that lets us really quickly change any URL's as required.

The other alternative is to hard code one service call in that pulls down this information and parses it into an object that's held around if you really can't use a json or xml file.

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


title: Cubemap faces rotation in GS shader

text:
# Question
Title: Cubemap faces rotation in GS shader
I Can't get correct rotations for cubemap faces. Thats should come to geometry shader, from camera "view" matrix I want make 6 faces for my cubemap, but seems I can't get it correctly...

My first guess that camera 'indent' matrix faces to '-z':

```
// +X //
 rot[0] = (mat4 (   0   ,  0    , -1.0  , 0 ,
                    0   ,  1.0  , 0     , 0 ,
                    1.0 ,  0    , 0     , 0 ,
                    0   ,  0    , 0     , 1.0 )) ;
// -X /
 rot[1] = (mat4 (   0   ,  0    , 1.0   , 0 ,
                    0   ,  1.0  , 0     , 0 ,
                    -1.0 ,  0   , 0     , 0 ,
                    0   ,  0    , 0     , 1.0 )) ;
 //+Y/
 rot[2] = (mat4 (   1   ,  0    , 0     , 0 ,
                    0   ,  0    , 1.0   , 0 ,
                    0   ,  -1.0 , 0     , 0 ,
                    0   ,  0    , 0     , 1.0 )) ;
 //-Y/
 rot[3] = (mat4 (   1   ,  0    , 0     , 0 ,
                    0   ,  0    , -1.0  , 0 ,
                    0   ,  1.0  , 0     , 0 ,
                    0   ,  0    , 0     , 1.0 )) ;
 //+z/
 rot[5] = (mat4 (   -1  ,  0    , 0     , 0 ,
                    0   ,  1    , 0     , 0 ,
                    0   ,  0    , -1    , 0 ,
                    0   ,  0    , 0     , 1.0 )) ;
 //-z/
 rot[4] = (mat4 (   1   ,  0    , 0     , 0 ,
                    0   ,  1    , 0     , 0 ,
                    0   ,  0    , 1     , 0 ,
                    0   ,  0    , 0     , 1.0 )) ;

```

EDIT: Correct for me: Using LookAt magic, finaly find correct order of rotation: NOTE: thats RH-coordinate system Column-major order (glsl default)

```
// +X
        rot[0] = (mat4 (    0   ,  0    , 1.0   , 0 ,
                            0   ,  1.0  , 0     , 0 ,
                            -1.0 ,  0   , 0     , 0 ,
                            0   ,  0    , 0     , 1.0 )) ;
// -X /
        rot[1] = (mat4 (    0   ,  0    , -1.0  , 0 ,
                            0   ,  1.0  , 0     , 0 ,
                            1.0 ,  0    , 0     , 0 ,
                            0   ,  0    , 0     , 1.0 )) ;
 //+Y/
        rot[3] = (mat4 (    -1  ,  0    , 0     , 0 ,
                            0   ,  0    , -1.0  , 0 ,
                            0   ,  -1.0 , 0     , 0 ,
                            0   ,  0    , 0     , 1.0 )) ;
 //-Y/
        rot[2] =(mat4 (     -1  ,  0    , 0     , 0 ,
                            0   ,  0    , 1.0   , 0 ,
                            0   ,  1.0  , 0     , 0 ,
                            0   ,  0    , 0     , 1.0 )) ;
 //+z/
        rot[4] = (mat4 (    -1  ,  0    , 0     , 0 ,
                            0   ,  1    , 0     , 0 ,
                            0   ,  0    , -1    , 0 ,
                            0   ,  0    , 0     , 1.0 )) ;
 //-z/
        rot[5] = (mat4 (    1   ,  0    , 0     , 0 ,
                            0   ,  1    , 0     , 0 ,
                            0   ,  0    , 1     , 0 ,
                            0   ,  0    , 0     , 1.0 )) ;

```

# Answer
To fix these kinds of issues create a test cubemap clearly marking each face directions and +/- XYZ you can then figure out which one(s) is(are) pointing the wrong way.
> 1 votes

---
Tags: opengl, shaders, glsl
---


# Question
Title: In Box2D, how can I check for bodies within a circle?
I'm trying to sample random positions to find one that is sufficiently far from other bodies.

Hence I'd need to test for bodies within a given circle. So far, I've used `b2World::QueryAABB` around my circle (which does what I want but for a rectangular area), then manually doing an intersection test with all the fixtures it gives me.

It seems to me like Box2D should already provide such functionality—is there a way that lets me do this without reinventing most of the wheel?

# Answer
I suggest using a sensor.

1. Create a circular body of the size of you choosing at the location you desire.
2. Set the Sensor flag to true.
3. Leave it there for a step. (The delta can be 0 units)
4. See if the sensors isTouching flag is set to true.

box2d Manual

> Sometimes game logic needs to know when two fixtures overlap yet there should be no collision response. This is done by using sensors. A sensor is a fixture that detects collision but does not produce a response.
>
> You can flag any fixture as being a sensor. Sensors may be static or dynamic. Remember that you may have multiple fixtures per body and you can have any mix of sensors and solid fixtures.
>
> Sensors do not generate contact points. There are two ways to get the state of a sensor:
>
> 1. b2Contact::IsTouching
> 2. b2ContactListener::BeginContact and EndContact
> 6 votes

# Answer
For completeness, I'll document the "reinventing the wheel" approach.

I recently wanted to do this too, but I wanted to do it statically (due to some code-structure decisions made before that I didn't want to break). So I didn't want to create a sensor body and `World.Step`, as previously suggested.

Instead, I figured that a *convex polygon* intersects with a *circle* if

* some of the polygon's corners are in the circle, or
* a raycast from the center of the circle toward its center hits in the circle

Both can be determined statically, with some simple math and `World.RayCast`.

**For the corners**: Get them by calling `fixture.GetShape().GetVertices()`. Make sure to transform them from the `Body`'s local coordinate space into world coordinates using `body.GetWorldPoint`. Then determine intersection by comparing their distances from the circle center to the circle's radius.

**For the sides**: `RayCast` a vector from the center of the circle toward the center of the tank with the length of the radius. If you get anything, it's a hit.

---

Why you need to check both cases:

If you only check the corners, a side between them might still intersect.

If your raycast toward the middle misses, a corner might still intersect.

Depending on your objects' relative dimensions and the required precision, doing just one of these could be a good approximation.
> 4 votes

---
Tags: c++, collision-detection, box2d
---


# Question
Title: Should I use textures that are the size of the object?
I've been reading but couldn't find an answer to my question:

If I have an object, let's say 30x30. Should I use a texture that is 30x30, 300x300, or even 3000x3000 or should I follow 'the powers of two' for textures?

I've been using 3000x3000 for a 30x30 object and it has been working, but I'm worried that it might not work for others.

# Answer
> 1 votes
Depends on what you do. For a 3D game you have to test it in practice - if it looks good when the camera is the closest - then the size is fine (you can even try to decrease the size of the texture to save memory/bandwidth). For a 2D game (orthographic camera) having textures in the same size (in pixels) as they appear on the screen might not be a bad idea but it all depends on your 2D camera settings and target device(s).

Btw, you know that Unity changes all textures' sizes to powers of 2 by default? It improves performance (at least on some devices) and from my experience it doesn't decrease the final images' quality. So I guess, unless you have a concrete reason to do otherwise, you can just stick to that.

# Answer
> 1 votes
3000x3000 is 9,000,000 pixels.

300x300 is 90,000 pixels.

30x30 is 900 pixels.

It all comes down to how much 'art' you want on the texture. I would use the smallest resolution needed to get your art to look correct at its optimal viewing distance from the game camera.

You also want to think about memory considerations. A 30x30 texture takes up less space than a 3000x3000 texture.

It's also good practice to keep textures as a power of 2 if you're using Unity as Unity will do its own compression to make it a valid power of 2 texture.

# Answer
> 1 votes
You should always do 3D textures in powers of 2. Just because of how video hardware operates, it is more efficient for them to deal with image dimensions in powers of 2; in most cases this processing difference won't be noticeable, but for complex graphics these little things can add up.

---
Tags: unity, textures
---


# Question
Title: Pygame - Increase and decrease the image size
I'm creating a 2D game where the player shoots cannonballs. To give the impression of movement, I want the cannonball to increase its size until half of the path, and then decrease it until it reaches the target (just like rampart game cannonballs).

Right now, I'm doing this in every draw, but the call doesn't increases:

```
self.CannonImg = pygame.transform.smoothscale(self.CannonImg, (10 + int(auxDistance / 10), 10 + int(auxDistance / 10)))

```

This is how the image shows up:

It doesn't scale smoothly, and the image is cut on the edges (over time, it starts to look a little bit transparent).

Is there any easy way to do it?

Also, I'm using images like the following. Though I've been reading, and found some people using sprites. What should I do?

```
self.CannonImg = pygame.image.load('Imagens/CannonBall.png')
self.surface.blit(self.CannonImg, self.Position)

```

Thanks!

# Answer
Most like :http://www.pygame.org/docs/ref/transform.html#pygame.transform.scale

If pygame use cpu rescale , you should make set of sprites offline (or make it on level load)

If you can use OpenGL directly, thats trivial task (just quard with texture) - video card will make it for you.
> 1 votes

---
Tags: sprites, python, pygame, scale
---


# Question
Title: Rendering objects with either normal maps, either specular maps, or with both, or with neither?
My hobby engine has a deferred renderer that supports normal maps and specular maps. Now, some objects may have normal maps, and some may have specular maps. In some cases, an object has both maps, and in some cases, it has neither.

The question is: how should I implement the rendering of these objects? Should I have a render queue for each different object type and render them with separate shaders like this:

```
Queue A: Objects without normal and specular map
Queue B: Objects with normal map, without specular map
Queue C: Objects without normal map, with specular map
Queue D: Objects with both normal map and specular map

// Render loop
bind shader for type 'A' objects
for each object in Queue A:
    render object

bind shader for type 'B' objects
for each object in Queue B:
    render object

// and so forth...

```

Or, should I use a single shader and bind a "default" normal map and specular map for those objects that do not have such maps? By a default map, I mean for example a normal map texture that's completely colored (128, 128, 255). This would be something like this:

```
bind shader
bind default normal map texture
bind default specular map texture

for each object in Queue A:
    render object

for each object in Queue B:
    bind object's normal map
    render object

bind default normal map texture
for each object in Queue C:
    bind object's specular map
    render object

for each object in Queue D:
    bind object's normal map
    bind object's specular map
    render object

```

Basically, the first approach would involve less texture binds and more shader binds, whereas the second approach would be the opposite. Is either of these a preferred way to approach the problem? Or have I missed something completely here?

You can assume the objects are queued correctly to the queues.

# Answer
You can use a tiny neutral texture to "disable" shader features you're not using which incurs a texture switch penalty but no shader switch penalty.

You can generate multiple shaders with all feature combinations and switch to the proper shader, this incurs a shader switch penalty but the simpler shaders execute faster.

Which ever is best depends on which is costlier: shader execution time due to code complexity or shader switch time.

On mobile GPUs (-2015) shader complexity tends to be more expensive than shader switch, On desktop GPUs it will depend on the GPU core speed. Low-end desktop GPUs can be more like mobile GPUs in that sense.

This will also vary depending on the 3D scene being rendered.
> 1 votes

# Answer
Big engines using 'premutation' that make many shaders for every specifited set of material features. But thats not solution for 'deffered' rendering, for deffered rendering you should implement material 'indexes'

Indexes will select proper render path, and all material caps. Usualy indexes created in matrial pipeline, when level builds. Small parts of shader , glues together in big Uber shader.

Modern gpus easy can handle dynamic branches. So you can have material features in uniform flag.

Thats all comes for desktop GPUs, don't sure for mobile.
> 1 votes

---
Tags: opengl, rendering, deferred-rendering
---


# Question
Title: Unity Physics Material - Character Slides Too Much
I am currently working on a 2D platformer in Unity. I am using a prefab from the AssetStore for my character (The last paragraph contains a link to the prefab). The character has a circle collider for his feet so that he can walk up slopes.

The problem I'm having is that because it is a circle collider, he also slides down any slope. I realize that I can add a Physics Material to the collider with a friction variable to stop (or at least resist) the sliding, but if I add any friction above ~0.1 the character can collide with a wall to stop himself from falling and yet 0.1 isn't even enough to stop him from sliding down slopes.

So my question is, how can I stop the character from sliding down slopes in a way that doesn't allow the player to stop himself from falling by colliding with walls?

The prefab that I'm using specifically is an asset found here, it's disk location is Sample Assets/2D/Prefabs/2D Character

# Answer
Sticking to walls is a problem mentioned in this Unity learning module around 8:45, and they set the friction of the ground to zero to solve it. However, they don't address the sliding down slopes problem.

Option 1: Give the character's body a frictionless rectangle collider that is just wider than the circle collider at it's feet, with its bottom positioned half way up the circle collider. The rectangle will hit the wall instead of the feet, and the character will slide right down. You could do 2 angled plane colliders instead of a rectangle, one on either side of the player, as a rectangle collider's bottom corners could get caught on the ground when falling off cliffs - angled planes wouldn't if positioned well.

Option 2: play with physics values. You can spend a lot of time playing with those values. Increasing the linear drag on the player's rigidbody would help, as that dampens its movement. But you'll also have to repeatedly tweak your gravity, mass, and the force applied to the character when the player moves it until you find a good balance.

Option 3: use a collider for the walls that has a friction of zero, and walking surfaces get a collider with a positive friction. This is obviously more resource intensive, but that might not be a problem for you.
> 1 votes

# Answer
I believe your character is more rolling than sliding, since it have circle collider.

You may try to set large angular damping for character's body when it receive no control forces.
> 0 votes

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


# Question
Title: When do you have inflation and when deflation in a virtual economy
In a virtual economy, you can calculate all the income and all the costs (money that sinks) from every user in the game. You can calculate the percentage of the new money on the system or the money that has been lost from the system by the income and the costs.

I believe that having a small positive percentage is not inflation, but from the other side, crucial for the economy. However, I was wondering if there are any rough limits of this percentage that could lead to an inflation or deflation for negative percentage.

For example, if you have every week a result of 1-2%, will not be a serious problem. But if you have 30% or -30%, obviously you will.

Have you found from your experience or from any research limits that could ring a bell?

# Answer
> You can calculate all the income and all the costs (money that sinks) from every user in the game

This is correct. You might also want to consider what players quitting or becoming inactive does to the amount of circulating currency as well if that is possible.

> I believe that having a small positive percentage is not inflation

This is not correct. Any change in the total amount of currency is inflation. You may have picked up the idea that small positive inflation is good because it is the opinion of some economists that it is indicative of a growing economy. This does not mean it is not inflation.

> Have you found from your experience or from any research limits that could ring a bell?

I have experienced playing games with virtual economies that experienced hyperinflation and there are lots of good questions here on Game Design about designing virtual economies but I can't find anything that points to a particular tipping point for inflation percentage. I can however suggest that you think about it as a problem of player perception and expectations. Inflation becomes a problem when player expectation of future currency value shifts cause undesirable behavior. When does that happen? That depends too much on the nature of the game to give a meaningful answer. That depends as much on how long and frequently players interact with the game and what their cash flow looks like as the global inflation rate.

For instance, if they don't typically save significant amounts of currency, their income is frequent enough to adjust with the rate of inflation and they interact with the game often then a pretty high inflation rate wouldn't be too bad. On the other hand, if they save a large amount of currency and interact infrequently, they may come back to the game after several cycles of inflation to find they've lost a lot of value - which might make them quit and destabilize the currency more.
> 3 votes

# Answer
I dont know what kind of simulation you are aiming for so it is difficult to give a specific answer.

Inflation is usually defined when well, inflation is \>0% and deflation is when inflation is negative. In many countries, the central bank aims to keep the inflation at a steady 2-3% per year through the use of monetary policy. Note however, inflation tends to be cancelled out by interest rates or raise in salary.

Also, a useful tool to understand the impact of inflation is the doubling time. Which is the number of inflations that will cause something to double. It can be approximated as 70/(inflation rate), thus, with a inflation rate of 2%, it will take roughly 35 such inflations to cause something worth 100 to be worth 200.
> 1 votes

# Answer
I am not confident that there is a good answer to this question without a lot more detail. It is true that by watching the income and sinks of the currency supply you can track overall currency in circulation, but that is not strictly the same as inflation. They may be (and usually are) related, but there's a lot of other factors that go into it. All you can really track that way is total net worth of all participants.

You could mean in a sense of buying power. (Ie: increase in the overall cost of most goods/services):

In this sense, it will depend strongly on how the money is being generated and sunk. Do all users want the same kinds of things? For example, in WoW, you wouldn't see a level 1 guy looking for the same weapons as a level 50 guy. In a situation like that, if the level 50 (presumably) is getting a bigger chunk of the increased money supply, then his items will inflate much faster than the items that the level 1 guy is interested in.

It also depends on how equitably the increased money is distributed. If only relatively few characters have a ton of money, prices will likely be very unstable. Everyone may want to sell items for very high prices banking on the one dude with a ton of money strolling through and buying it, not caring that it takes a while to sell. Or it may be the case that if those "big fish" aren't biting, prices remain the same for a long time because even though the currency supply is bigger, the average Joe doesn't get any of it.

Also how often are items sold back and forth? Is everyone a solid "producer" or are there people whose net worth is likely to just keep going up and others who will remain at a fairly steady net worth?

To hazard one practical useful answer: You want a little bit of inflation, otherwise there is no impetus to spend your money and the economy stagnates. This is especially true if there is deflation. However, you do not want so much inflation that money earned today evaporates before it can be spent. Let's assume everyone's income increases at roughly the same percentage rate.

The exact rate would have to be dependent on how fast you expect people to spend their money. Are they making daily purchases or are they likely to save up over a long time to make a few big purchases? With a mixture of both, I would probably go with a figure close to the real world value of 1-2% a year.
> 1 votes

# Answer
The main reason for hyperinflation in online games is when players have more money than they can reasonably spend on NPC items. The result is that the only thing to do with their wealth is to buy rare items from other players. When everyone is in that situation, the prices for rare items will skyrocket because too many players with too much disposable income will outbid each other.

To counter this, make sure that there is always something expensive to buy from NPCs. There are two nice, self-regulating mechanics for this purpose:

1. the raffle. Have a raffle where one (1) item is given out once per day/week/month which can not be obtained in any other way. Sell the tickets for a fixed price, but allow players to buy as many tickets as they want to improve their chance of winning. The more disposable money there is around, the more tickets players will buy. So the actual price of the item will always adjust itself to the amount of disposable income. This technique was used by Kingdom Of Loathing to get rid of huge amounts of ingame currency which got into the game through an exploitable bug.
2. the rare item dealer. Have a bunch of unique items which can only be bought from an NPC. They can be bought again and again. However, there is a catch: Everytime a player buys them, the price increases by a certain percentage - for everyone! This is a specialized money sink to keep the richest of the richest players at bay.

Counterintuitively, it can help against inflation when you have a sink not just for money but also for items. Add a mechanic which makes it necessary to regularly replace equipment, even the ultra-rare stuff. You would expect that this reduces the supply while the demand increases and as a results the prices increase. But when items don't last forever but need to be replaced regularly, players won't get into the "more money than I can ever spend" phase because they have a cost of maintaining their equipment.
> 1 votes

# Answer
Inflation is really the difference between growth of an economy and growth of a money supply. If your economy grows and you dont print any more currency, your economy will deflate. The opposite is true for inflation. Zero inflation occurs when your printing of currency matches your economic growth. So as player skill level increases, or population increases, you need to print more money to match it.
> 0 votes

---
Tags: game-design, economy
---


title: Mock Collision Object in Unity

text:
# Question
Title: Mock Collision Object in Unity
Problem:

I'm trying to set up some tests with mock collision objects, but i cannot construct collisions with custom objects. What I'm trying to do:

```
Collision2D col = new Collision2D();
col.gameObject = this.gameObject;

```

There seems to be no way to do this as col.gameObject has no visible setter. Is there a way to do this? I would like to script the passing of a collision to a mono-behavior via an event that gets handled by the OnCollisionEnter2D(Collision2D collision) inherited from mono-behaviors. Thanks for your time.

# Answer
This looks like a job for reflection:

```
public T MockType<T>(Dictionary<string,object> fieldValues, params object[] consParams)
{
    var type = typeof (T);
    var cons = type.GetConstructor(BindingFlags.NonPublic,
                                   Type.DefaultBinder,
                                   consParams.Select(p => p.GetType()).ToArray(),
                                   null);
    var result = (T)cons.Invoke(consParams ?? new object[0]); // invoke non-public constructor
    foreach (var fieldValue in fieldValues)
    {
        var field = type.GetField(fieldValue.Key, BindingFlags.NonPublic)
        field.SetValue(result, fieldValue.Value); // Set non-public field
    }
    return result;
}

// Example method demonstrating use:
public Collision2D MockCollision2D(Rigidbody2D rigidbody,
                                   Collider2D collider,
                                   Vector2 relativeVelocity,
                                   ContactPoint2D[] contacts)
{
    return MockType<Collision2D>(new Dictionary<string, object>
                                     {
// Use a decompiler like ILSpy to find out what the internal fields' names are:
                                         {"m_Rigidbody", rigidbody},
                                         {"m_Collider", collider},
                                         {"m_RelativeVelocity", relativeVelocity},
                                         {"m_Contacts", contacts}
                                     },
                                 new object[0]
        );
}

```

I haven't tested this, so it might need some tweaks. The game object the collision refers to is drawn from the collider field.
> 2 votes

# Answer
Do not `new MonoBehaviour` just add them as components. Your approach won't work.

EDIT: I still advise you against breaking the component and `Monobehaviour` approach. If you want testing then have a look at the Unity Testing Tools. They will provide you with everything you need including mocks and stubs for unit and integration tests.

Asset Store

Documentation
> -2 votes

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


# Question
Title: Minecraft - how do I add a PNG for a new Mob to either assets or resourcepacks
I've installed MCP and set up eclipse and successfully added my new monster to the game. It spawns properly and does everything I meant it to do. The only problem I still have is that the texture that I've indicated cannot be found. The game logs contains the following error:

```
java.io.FileNotFoundException: minecraft:textures/entity/spider/green_spider.png
       at net.minecraft.client.resources.FallbackResourceManager.getResource(FallbackResourceManager.java:51) ~[minecraft/:?]

```

I browsed various wikis and tuorials, some of which suggested that I need to add an asset folder to src/minecraft, but that didn't work. I found out that I could add my texture file to `[mcp]/jars/resourcepacks/` but that didn't work either.

Can you tell me to configure resource pack loading or what to run in MCP to add my asset files to the game?

# Answer
> 0 votes
As described in http://minecraft.gamepedia.com/Tutorials/Creating\_a\_resource\_pack, you should create a resource pack by copying the asset folder into a new directory, adding your files to the asset dir and creating an pack.mcmeta file, which you place next to the asset folder. Zip the whole lot and place it in your .minecraft/resourcepack dir. In the game, go to options, resource packs and add your resource pack to the selected pack list.

---
Tags: minecraft-modding, modding
---