# Question
Title: Unity 2D, how to turn a bool true, after a set amount of time?
I have an enemy working to damage the player when they stay in collision for too long, at the moment, the enemy will attack about 30 times per second, however I want there to be a delay between each enemy attack, here is my current code:

```
void OnCollisionStay2D(Collision2D col){

    if (col.collider.CompareTag ("Player") && canAttack == true) {
        player.Damage (enemyDamage);
        canAttack = false;
        //wait 3 seconds or so
        canAttack = true;
    }
}

```

# Answer
> 3 votes
```
IEnumerator OnCollisionStay2D(Collision2D col)
{

    if (col.collider.CompareTag ("Player") && canAttack == true)
    {
        player.Damage (enemyDamage);
        canAttack = false;
        yield return new WaitForSeconds(3);
        canAttack = true;
    }
}

```

# Answer
> 1 votes
The easiest way would be to use the `Invoke` command.

```
void OnCollisionStay2D(Collision2D col){

    if (col.collider.CompareTag ("Player") && canAttack == true) {
        player.Damage (enemyDamage);
        canAttack = false;
        //wait 3 seconds or so
        Invoke("EnableAttack", 3f); // Invoke will call a given function after the time given in seconds.
    }
}

void EnableAttack() {
    canAttack = true;
}

```

# Answer
> 1 votes
An alternative solution to using the coroutine system is to store the time when the object attacked last in a private variable and compare it to the current time:

```
public class Attacker : MonoBehaviour {

    private float lastAttackTime;
    private const float ATTACK_DELAY = 0.1f; // 10 attacks per second

    void OnCollisionStay2D(Collision2D col){

    if (col.collider.CompareTag ("Player")) {
        if (Time.time > lastAttackTime + ATTACK_DELAY) {
             player.Damage (enemyDamage);
             // ... and other attack stuff
             lastAttackTime = Time.time;
        }
    }
}

```

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


title: UE4 Try Get Pawn Owner Node Location

text:
# Question
Title: UE4 Try Get Pawn Owner Node Location
Where is the Try Get Pawn Owner node located in BP? I can't find it anywhere. I'm following the answer here but cannot find this node anywhere. Using version 4.11.2.

Thanks!

# Answer
> 0 votes
OK so to make this node appear you have to uncheck the Context Sensitive box top right of the search field:

---
Tags: unreal-4
---


# Question
Title: What are the pros and cons of GameSalad versus Cocos2D?
I am currently using the Cocos2D framework for creating my game but I just happened to come across GameSalad and was amazed by this video.

GameSalad claims to allow you to create games without writing a single line of code. So I ask myself, what is the catch? What makes Cocos2D better than GameSalad? What are the pros and cons of GameSalad?

# Answer
> 3 votes
GameSalad is good for either quickly prototyping ideas, or if you want to develop an iPhone game on your own but don't know anything about programming. If however you have even a little familiarity with programming then GameSalad has many significant cons. The most significant con is that it is simply a very restrictive development tool; I haven't looked at it in a long time so I don't know what features it has now, but last time I looked it didn't even have arrays (if you think about it, how could you represent arrays without programming?) It's hard or impossible to access a lot of iOS features, like Game Center. And then there's poor performance.

Cocos2D is a much more flexible and powerful development tool, but on the downside it's also considerably more complex to use. Working with Cocos2D you will be programming in Objective C using XCode; you can implement literally any feature that iOS is capable of, but it'll be a lot of work.

There is a middle ground you didn't mention: mobile game development platforms like Corona and Moai. These are tools that aren't quite as flexible as Cocos2D but are considerably more flexible and powerful than GameSalad. Meanwhile they use Lua for all the programming so working with these tools is considerably simpler than using Cocos2D. If you haven't done so already, I would strongly suggest evaluating one or both of these.

# Answer
> 2 votes
The catch of Game salad is "write games without *coding*...". However it doesn't mean write games without **programming**! Just because you aren't coding doesn't relieve you from knowing the math and logic real programmers have to go through when developing apps!

# Answer
> 1 votes
I have experience with GameSalad and Cocos2D and GameSalad is an awesome tool for prototyping game and creation of simple games(think Pac man or Space Invaders), but they have no native support for the iOS controls such as keyboard, text fields etc. So the catch is that GameSalad makes it possible for non programmers to create games without writing a line of code.

But that is provided you intend to make simple games. But if you are looking to make the next Infinity Blade, then count GameSalad out as GameSalad does not play that way. I am always suspicious when a software mentions that they can create game without writing a single line of code as I have been developing mobile games for close to 10 years and every single software has it's pros and cons.

# Answer
> 0 votes
Nobody uses closed source drag and drop tools like GameSalad for serious game development. I don't recognize a single well known game on their site.

Go with Cocos2D or Moai. Open source, serious game development.

# Answer
> -3 votes
Here is the cons side of game salad. It has array-like stuff. Called table, and pretty powerful features. But cannot be 3d array. Cannot play sound based on array value, but text and image will go right.but the table can import csv which is nice.

Cannot play video, url goes outside game

Cannot create pop up notification also.those are some weaknesses, but it has so many good side.

---
Tags: iphone, cocos2d-iphone, ios, cocos2d, gamesalad
---


# Question
Title: How to rotate a triangle to look at a point?
Lets say I have a triangle defined by 3 vertices and a center point, how do I rotate the triangle so its normal is looking at a specified point?

# Answer
> 2 votes
Given points A, B and C of a triangle, the normal of the triangle is the cross product **AB**×**AC** (or possibly **AC**×**AB** depending on the vertex order). If the point on the triangle is M and the point towards which to look is P, you then have an infinite number of rotations that cause **AB**×**AC** to be in the direction of **MP**. The shortest rotation of them all can be computed using a quaternion from two vectors method. The final tranformation is therefore:

* subtract M from all triangle points so that the triangle centre is at the origin
* rotate all points using the quaternion described above
* re-add M to all triangle points

In pseudocode:

```
tranform = translate(OM) * rotate(quaternion(cross(AB,AC), MP) * translate(MO)

```

---
Tags: vector, mesh, trigonometry
---


title: Why do my trees share the same health?

text:
# Question
Title: Why do my trees share the same health?
My trees keep on falling at the same time and I am not sure why! I am new to Unity3D javascript.

Here is my script:

```
#pragma strict

//INTS
var health = 5;
//GAMEOBJECTS
var tree : GameObject;
var log : GameObject;

function Start () {

tree = this.gameObject;

}

function Update () {

if(Input.GetKeyDown(KeyCode.Mouse0) && Player_script.axehave && health >= 1 && Camera_script.tree){
health -= 1;
}

if(health == 0){
tree.GetComponent.<Animation>().Play();
Destroy();
}

}

function Destroy(){

yield WaitForSeconds(2);
Destroy(tree.gameObject);

}
```

# Answer
> 1 votes
Nothing in this code snippet makes a distinction between *this* tree vs. the tree the player is looking at.

Unless that's what `Camera_script.tree` is supposed to do, but at long as that variable isn't null, the if-check will be true.

I think what you want there is `Camera_script.tree == this.tree`

---
Tags: unity, javascript
---


# Question
Title: Is the TCP protocol good enough for real-time multiplayer games?
Back in the day, TCP connections over dialup/ISDN/slow broadband resulted in choppy, laggy games because a single dropped packet resulted in a resync. That meant a lot of game developers had to implement their own reliability layer on top of UDP, or they used UDP for messages that could be dropped or received out of order, and used a parallel TCP connection for information that must be reliable.

Given the average user has faster network connections now, can a real time game such as an FPS give good performance over a TCP connection?

# Answer
I would say no. Spacial information of game objects need to be as fast as possible, and for that it's better to use UDP, because reliability is not 100% crutial. Even on modern connections, UDP is still slow enough that you have to make some special considerations for interpolation and such. Even just in terms of the amount of data transferred, TCP would add significant overhead to this.

However, TCP is perfectly acceptable for non-realtime things, such as multiplayer negotiation, chat messages, score updates, etc.
> 37 votes

# Answer
As Flash doesn't support UDP, by looking at multiplayer Flash games you can get a pretty good idea of what's possible with TCP/IP and what isn't. Basically you can create real time games, as long as they don't rely on lightning-fast response times. A couple of examples:

http://www.xgenstudios.com/play/stickarena

http://everybodyedits.com/

If you have the option of using UDP, you really should, but with Flash you sadly don't get that option.
> 11 votes

# Answer
It depends.

Games like World of Warcraft use TCP for their communication, because you circumvent many problems by using it. There may be a higher ping as a result, but for many games, this is acceptable. You need to do spatial interpolation even when you use UDP as your protocol.
> 8 votes

# Answer
If your client/server architecture is clean, the transport layer (almost) doesn't matter.

TCP has some drawbacks, but these are easily cirumvented.

So yes, TCP and a brain is all you need.

With common network setups (proxies, firewalls, etc) today UDP is pretty much useless for all but local (read: LAN) games.
> 6 votes

# Answer
Its perfectly acceptable to use TCP instead of UDP - if you turn off the Nagle's algorithm.

Once you turn off Nagle, you have most of the speed of UDP and will be **fully able to make a twitch reaction game**. Indeed, I have made such a game using TCP in Flash:

http://2dspacemmo.wildbunny.co.uk

Hope that helps!
> 6 votes

# Answer
For FPS games we always use UDP. Especially if you are doing a twitch shooter where pings matter.
> 4 votes

# Answer
It depends on the kind of game.

Some games such as RTS, play much better over TCP and typically use TCP all the time.

The real problem with TCP is that if you get packet loss - even a small amount - then the connection "stalls" until retransmission happens. The OS can't deliver out-of-order data to the application (this breaks TCP's guarantees, but also, TCP does not show the application frame boundaries). The connection stall means that late data subsequently arrive. But in a (e.g.) FPS game, out-of-date data are useless.

With UDP, the application gets to choose what it does with late or out-of-order data. It can (and for a game such as FPS, usually does) ignore old data and just take the latest ones. An occasional lost packet doesn't delay subsequent packets at all. If a delayed packet eventually arrives, it can be ignored by the game.
> 4 votes

# Answer
Don't just accept a straight "yes or no cuz I said so" type answer here as you may be opening up yourself to having to fight a bunch of problems with UDP that actually you don't need to face.

None of the other answers here state the obvious way to prove this.

**Take some simple facts**

* An IP header is 20 bytes no matter what protocol you use.
* UDP headers are 4 bytes
* TCP headers are 20 bytes

So each time you send a message of 1 byte down the line you have actually sent either 25 or 41 bytes depending on protocol assuming an IP header is also needed.

sources:

**My advice**

Take your situation where you need client server interaction, estimate the number of clients then do the math based on the data you actually send between the 2.

**An Example**

Lets say I send 10 messages that are 1 byte each per update in my game and i'm updating around 60 fps so I need to send 60 * 10 = 600 bytes per second of actual message data + the relevant headers.

Now depending on the game I could send that all as a single message so my overhead from the TCP layer is just 40 bytes (effectively a cost over UDP of 20 bytes per second), not having that overhead is a potential cost of 600 bytes (because I may have to resend the whole message stream).

If however it's vitally important that every message be sent on its own the very instant its ready to be sent, I have 600 messages (also 600 bytes) + 40 * 600 = 24k worth of TCP overhead or ~14k of UDP overhead per second + 600 bytes of message data.

Again, we ask the questions, how vital are those messages, how frequent are they, and can they be batched up in some way to reduce the overheads?

That's just based on a bunch of single byte messages, typically you would do something very different but without knowing the raw data being sent its hard to prove either way if TCP is a better fit to your situation than UDP.

**So, will it work?**

Well, if you have a typical fps, and position is important (to avoid cheating or incorrect decisions), you need to know that your network stream is realiable, but 32 players each streaming that 24k + message bytes back and forth (so 768KB/s + messages) ... that's about a 10mb/s broadband line just for individual headers based on sending at least 1 message per frame from each client to all the other clients via a server.

You obviously won't code your server and client to work that way and the message sizes are very likely to be a lot bigger and probably a bit less frequent than 1 byte per frame in most situations so it's hard to say without seeing a real world "this is the data I need to send" example.

**My case**

I have made the call in my case that its a reasonable overhead but that's based on how I build my message streams so I don't have huge overheads compared to some designs.

TCP works fine and I have a scaleable MMO server and client framework but I don't need to stream lots of data ever frame or lots of small packets because I can batch my calls.

for others: TCP just won't do, and they can only use UDP but have to accept that it won't give them assurances about what they get (ordering / arrival guarantee).

**Other considerations**

Many poorly coded game engines handle everything on the main thread on the cpu so the cpu is often only given a very small amount of time to handle networking code, a decent implementation of both the serve and the client would be entirely async and possibly push and pull messages in batches.

There are some good networking libraries out there but as seen here, many seem to have an opinion that UDP is "just better", well factor in your own needs first and that may not be the case, and finding a library that doesn't factor in things the way you do may result in a poorly coded TCP setup in comparison to the UDP variant in the same lib (i'm just saying i've seen this, and load tests have proven it).

Build something first a technical base of the data you want to be sending and test it then do the math to scale it up, worst case load test it by deploying to a cloud and have 50 computers run a test client to see if it can handle your limit of 32 players per game (or whatever limits you may have).
> 3 votes

# Answer
I don't think so... Games where data transfer is very frequent (on mouse-move or key-down), should use UDP. It'll lag even on LAN if TCP is used.
> 2 votes

---
Tags: networking
---


# Question
Title: Calculate XP needed for next Level using this simple algorithm?
I am currently calculating the Levels in my game using the following forumla:

```
player.level = mathFLOOR(mathMAX(1, 0.05 * mathSQRT(player.score)) * (1 + player.kd / 10));

```

So the level is based on the persons total score and their kd. However I am now trying to figure out a formula for calculating the percentage of the score/kd you need to progress to the next level. If this is not possible, how could I do it with just this formula:

```
 player.level = mathFLOOR(mathMAX(1, 0.05 * mathSQRT(player.score)));

```

Thank you for your time.

# Answer
Unless I missed something here doing this ...

```
var progress = 0.05 * mathSQRT(player.score)) * (1 + player.kd / 10);

```

... will get you a value of how far the user has "progressed".

The level is that value rounded down to the nearest integer or 1 with ...

```
player.level = mathFLOOR(mathMAX(1, progress));

```

.. the progress between the current level and the next is therefore something like ...

```
var toNextLevel = progress - player.level;

```

... that will give you something like 0.1 for 10% or 0.34 for 34%
> 3 votes

---
Tags: mathematics
---


# Question
Title: Why does my imported FBX animation not display correct in game?
This issue seems to arise with joint rotation animation.

```
//------------------------------------------------------------------------------
// Fuction Name:
//      FbxConverter::ProcessJointsAndAnimations
// Arguments:
//      FbxNode *inMesh     // In Mesh
// Return Value:
//      void
// Description:
//      Processes Joint and Animation Data
// 説明:
//      スケルタルとアニメーションデータを処理する
//------------------------------------------------------------------------------
void FbxConverter::ProcessJointsAndAnimations( FbxMesh* inMesh )
{
    // Get Mesh Data
    // メッシュデータを習得
    FbxNode* currNode = inMesh->GetNode();

    // Node Geomtric Transformation
    // ノードのジオメトリー変換行列
    FbxAMatrix geometryTransform = GetGeometryTransformation( currNode );

    // Get Number of Deformers
    // Deformerの数を習得
    unsigned int numOfDeformers = inMesh->GetDeformerCount();

    // Loop through Node Deformers for Skins to get Cluster Data
    // スキンを探して、クラスタデータを習得
    for( unsigned int deformerIndex = 0; deformerIndex < numOfDeformers; ++deformerIndex )
    {
        // Check if Deformer is a Skin
        // スキンかどうかを確認する
        FbxSkin* currSkin = reinterpret_cast<FbxSkin*>( inMesh->GetDeformer( deformerIndex, FbxDeformer::eSkin ) );
        if( !currSkin )
        {
            continue;
        }

        // Get Number of Clusters in Skin
        // スキン内のクラスタ数を習得
        unsigned int numOfClusters = currSkin->GetClusterCount();

        // Process Cluster Data
        // クラスタデータを処理する
        for( unsigned int clusterIndex = 0; clusterIndex < numOfClusters; ++clusterIndex )
        {
            // Get Cluster from Skin
            // クラスタデータを習得
            FbxCluster* currCluster = currSkin->GetCluster( clusterIndex );

            // Get Joint Name
            // 関節の名前を習得
            std::string currJointName = currCluster->GetLink()->GetName();

            // Get Joint and Joint Index from Name
            // 名前で関節と関節インデックスを習得
            ModelObject::Joint* joint = nullptr;
            unsigned int jointIdx = FindJointIndexUsingName( currJointName, &joint );

            // Matrices
            // 行列
            FbxAMatrix transformMatrix;                 // Mesh Tranformation at Binding Time
            FbxAMatrix transformLinkMatrix;             // The Transformation of the Cluster(joint) at Binding Time from Joint Space to World Space
            FbxAMatrix globalBindposeInverseMatrix;     // Bindpose Inverse Matrix

            // Get Matrix Data
            // 行列を習得
            currCluster->GetTransformMatrix( transformMatrix );
            currCluster->GetTransformLinkMatrix( transformLinkMatrix );
            globalBindposeInverseMatrix = transformLinkMatrix.Inverse() * transformMatrix * geometryTransform;

            // Update Joint Matrix Data
            // 関節の行列データを更新する
            joint->globalBindposeInverse = FbxAMatrixToMatrix44( globalBindposeInverseMatrix );

            // Associate Each Joint with the Control Points it Affects
            // 関節と制御点データの関連を付ける
            unsigned int numOfIndices = currCluster->GetControlPointIndicesCount();
            for( unsigned int idxCount = 0; idxCount < numOfIndices; ++idxCount )
            {
                ModelObject::BlendingIndexWeightPair currBlendingIndexWeightPair;
                currBlendingIndexWeightPair.blendingIndex = jointIdx;
                currBlendingIndexWeightPair.blendingWeight = currCluster->GetControlPointWeights()[ idxCount ];

                // If Blending Weight is Above Minimum Value
                // ウェイトが十分大きかったら
                if( currBlendingIndexWeightPair.blendingWeight > 0.1f )
                {
                    // Get Control Index
                    // 制御のインデックスを習得
                    int ctrlIdx = currCluster->GetControlPointIndices()[ idxCount ];

                    // Get Model Blend Data Index
                    // モデルのブレンドのインデックスを習得
                    int blendIdx = 0;
                    for( blendIdx = 0; blendIdx < 4; blendIdx++ )
                    {
                        if( m_meshHold.ctrl.data[ ctrlIdx ].blendingInfo[ blendIdx ].blendingWeight == 0 )
                        {
                            // Add Blending Data to Control Point
                            // 制御点にブレンドのデータを追加する
                            m_meshHold.ctrl.data[ ctrlIdx ].blendingInfo[ blendIdx ] = currBlendingIndexWeightPair;
                            break;
                        }
                    }
                }
            }

            // Get Animation Data
            // アニメーションのデータを習得
            // ( Currently only Supports one Take )
            // ( 現在、一つのアニメーションしか対応していない )
            FbxAnimStack* currAnimStack = m_fbxScene->GetSrcObject<FbxAnimStack>( 0 );

            // Get Animation Name
            // アニメーションの名前を習得
            FbxString animStackName = currAnimStack->GetName();
            m_animationName = animStackName.Buffer();

            // Get Take Info using Animation Name
            // アニメーションの名前でテーク情報を習得
            FbxTakeInfo* takeInfo = m_fbxScene->GetTakeInfo( animStackName );

            // Get Animation Length
            // アニメーションの長さを習得
            FbxTime start = takeInfo->mLocalTimeSpan.GetStart();
            FbxTime end = takeInfo->mLocalTimeSpan.GetStop();
            m_animationLength = end.GetFrameCount( FbxTime::eFrames24 ) - start.GetFrameCount( FbxTime::eFrames24 ) + 1;

            // Create Frames Based on Animation Length
            // アニメーションの長さによってモデルのフレームを作成する
            joint->animation = new ModelObject::Frame[ ( int )m_animationLength ];

            // Process Animation Data
            // アニメーションのデータを処理する
            int animCount = 0;
            for( FbxLongLong frameCount = start.GetFrameCount( FbxTime::eFrames24 ); frameCount <= end.GetFrameCount( FbxTime::eFrames24 ); ++frameCount )
            {
                // Set Frame Time
                // フレームの時間設定
                FbxTime currTime;
                currTime.SetFrame( frameCount, FbxTime::eFrames24 );

                // Save Frame Number
                // フレーム番号を保存
                joint->animation[ animCount ].curFrameNum = ( int )frameCount;

                // Get Global Transform Matrix
                // グローバル変換行列を習得
                FbxAMatrix currentTransformOffset = currNode->EvaluateGlobalTransform( currTime ) * geometryTransform;
                FbxAMatrix globalMtx = currentTransformOffset.Inverse() * currCluster->GetLink()->EvaluateGlobalTransform( currTime );
                joint->animation[ animCount ].globalTransform = FbxAMatrixToMatrix44( globalMtx );

                // Increase Animation Array Count
                // アニメーションのカウントを増やす
                animCount++;
            }
        }
    }
}

```

# Answer
> 1 votes
I found one solution. The model's transformation were not frozen when made which caused the issue. Freezing the transformation will allow for correct animation in game. The next step would be to fix the above code to allow for unfrozen models

---
Tags: animation, directx, maya, fbx
---


# Question
Title: Will points on path with width intersect
I want to be able to check if a list of points will hit a screwed rectangle (rhombus i think).

I start out with 2 point P and T, i want to create a rectangle between the 2 points. I have used https://stackoverflow.com/questions/7854043/drawing-rectangle-between-two-points-with-arbitrary-width to do this. This gives me 4 points A, B, C and D of the new rectangle.

I then want to check if the point M is withing this rectangle.

The two black dots are my points P and T, the black box is the rectangle i want to generate between the two dots, being X wide. I then want to test if the red dots are withing the black box.

# Answer
There are lots of algorithms to check whether a point is inside or outside a polygon. The simplest being the ray casting algorithm.

The idea is, you cast a ray (assume a line) from your point to either the left or the right. Then for each side of your polygon, you test whether the ray intersects it, and if it does, you add 1 to a counter. At last, if the number of times the ray intersected with a side is odd (that is if `counter % 2 == 1`), your point lies inside the polygon.
> 1 votes

---
Tags: mathematics
---


# Question
Title: 4-player arena game networking model : dedicated servers?
So my question is not technically limited to 4-player games, but there has been a lot of games on steam lately (brawlhalla, duck game etc) that seem to be quite popular lately.

My question is, are these games hosted on a separate server, or do one player host the game, and the game developers just providing a match-making service?

If it's hosted by one of the player, how do they get around with NAT issues? If hosted by some server somewhere - that sounds like it's super expensive to run?

Also, for these games, what kind of networking model is "standard"? Are there any articles about this I can read?

# Answer
There is no golden bullet "this is how you do it" type answer to this other than to say, generally speaking you have 2 options TCP or UDP.

Given the fact that you are only ever dealing with 4 players TCP might be a better choice as you get some additional protocol level checks that help ensure reliable networking.

Net up is for you to decide how you want your game to work.

If you want to have dedicated servers then do that, if you want users to be able to setup and host their own games do that, we can't tell you how to design your game.

That said some form of async socket on both the server and clients will likely be the way you go so I would start there by getting 2 console apps to talk to each other then look at how to implement that in your game.

**EDIT**

That said unless you are building your own game engine it's likely that the engine you are using has some options for this that you may want to consider.

And you may wish to consider things like ...

* TCP is more resource intensive (on server not net) compared to UDP.
* There is UDP hole punching if you want to let players behind nat host the game.
> 1 votes

---
Tags: networking, multiplayer, game-state
---


# Question
Title: How can I scale my UI elements to the lesser screen dimension in Unity 5?
I want to create a custom mobile pad for my game. The mobile pad consists of two parts (both inside an ui canvas):

* The D-Pad, which will be anchored to the bottom-left side.
* The button group will be anchored to the bottom-right side.

I would like to resize the element on different resolutions, so that the element (in my case, the D-Pad is an image):

* Has a size of 20% of the minimum of the width and the height.
* Has pivot of x=0.5, y=0.5.
* Having anchor of left-bottom, its coordinates are (15%, 15%) wrt the minimum of the width and the height.

What I tried is to use an Aspect Ratio Filter in the D-Pad image with ratio=1, but it did not work as intended (the coordinates led the image to an unexpected place).

*Note: I am a n00b to Unity. I don't know whether it is right but my Canvas Scaler scales by Constant Pixel Size*

These images should illustrate what I want to achieve:

What should I do to make it work like in the pictures?

**Edit** I attached this behavior, based on answer, to handle the change by runtime:

```
[RequireComponent(typeof(UI.CanvasScaler))]
class CanvasSmartScaler : MonoBehavior {
    private CanvasScaler _scaler;
    void Start() {
        _scaler=GetComponent<CanvasScaler>();
    }
    void Update() {
        //OMITTED CODE: here I set the scale mode as in the Editor but right now i am in my mobile device and cannot remember the exact lines
        if (Screen.currentResolution.width < Screen.currentResolution.height) {
            _scaler.matchWidthOrHeight=0;
        } else {
            _scaler.matchWidthOrHeight=1;
        }
    }
}

```

And attached that behavior to the canvas. However, for my debug exe (just for debug purposes) it always picks the 1-case regardless how do I resize the window. What am I missing?

# Answer
On the canvas scaler try :

UI Scale Mode = Scale With Screen Size Then give a reference resolution. I like to use the standard 1920 x 1080. Screen Match Mode = Match Width or Height with a Match value of 0.5.

Also you might want to checkout how to make your UI image into a 9 sliced type. Check this out.

You can get a reference to the canvas scaler.

```
using UnityEngine.UI;
CanvasScaler scaler;
GameObject canvasGameObject;

void Start()
{
 scaler = canvasGameObject.GetComponent<CanvasScaler>();
}

```

I'm writing this code directly off the top of my head so it might not work. Let me know.
> 1 votes

---
Tags: unity
---


# Question
Title: UE4 Blueprint OnActorBeginOverlap not working
I am following the tutorial here entitled "Making a Pickup". I have created a Blueprint class from the Statue SM:

I have set the SM Collision Preset to OverlapAll per the instructions. In the Event Graph I have the following:

When I run the simulation and run into the statue, nothing happens. If I monitor the Blueprint I see no triggering. I have wired the everything to trigger from EventBeginPlay and it all works as expected, but the ActorBeginOverlap node never triggers.

What am I missing?

# Answer
> 1 votes
OK found it, I need to have the Generate Overlap Events box checked in the Collision pane:

---
Tags: unreal-4
---


# Question
Title: C# Integer limits for Scriptable Objects
I am experimenting with `Scriptable Objects` in Unity. In the following example how can I limit the range of accepted values?

```
public class AScriptableObject : ScriptableObject
{
   public uint damage;
}

```

Since it's a `uint` the lowest value is `0` but how can I limit the max value to 500 for example? Can I use `if` statements?

# Answer
If you want to be able to set it both via editor and script and have it always clamp the value you can write it this way

```
public class AScriptableObject : ScriptableObject
{
    private const int MyMaxValue = 500;
    [SerializeField]
    [Range(0, MyMaxValue)]
    private uint m_damage;

    public uint damage
    {
        get
        {
            return m_damage;
        }
        set
        {
            if (value >= MyMaxValue)
                value = MyMaxValue;
            m_damage = value;
        }
    }
}

```

Note it won't allow you to have MyMaxValue \> int.MaxValue because the range attribute only takes in an int, and not a uint
> 2 votes

# Answer
```
[Range(0,500)] public uint damage;

```

Should do the trick. This will be show as a slider in the inspector that goes from 0 to 500.
> 2 votes

# Answer
You can use Unity's MathF.Clamp() method. If you use this method each time you give a value to your integer, it resctricts the value between your min and max values.

For example: if you take a 400 value and use Clamp() method like this;

Mathf.Clamp(400, 0, 300); it returns 300.

http://docs.unity3d.com/ScriptReference/Mathf.Clamp.html
> 0 votes

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


# Question
Title: Why are my click events being fired many times for every click?
I am working on a game in unity where a user will click a button to gain coins and clicks over a lifetime of clicking the button but the code is making the clicks go up by a lot instead of just 1 each time it is clicked like here are the values returned the first 3 clicks `247 731 2111` anybody have an idea why it produces this behavior and how i can fix it?

```
using UnityEngine;
using UnityEngine.UI;
using System.Collections;

public class GameManager : MonoBehaviour {
    public Button clicker;

    public Text coinsSec;
    public Text ltClicks;

    private float baseClick = 2;
    private float coins = 0;
    private float lifeTimeClicks = 0;
    private float coinsPerSec;

    private void Start(){
        UpdateTxt ();
    }

    private void Update(){
        UpdateTxt ();
        Clicker ();
    }

    private void Clicker(){
        clicker.onClick.AddListener (delegate {
            coins += baseClick;
            lifeTimeClicks++;
        });
    }

    private void UpdateTxt(){
        coinsSec.text = "Coins/s: ";
        ltClicks.text = "Lifetime Clicks: " + lifeTimeClicks.ToString ();
    }
}

```

# Answer
You are adding the listener function inside Clicker(), which is getting called from Update(). Update() happens *every* frame, which means every frame you are adding a new listener. If you click once, and it adds 256 to your coins, then that means you have 128 listeners waiting for that click (since a click adds 2). Try calling Clicker only once from Start instead of Update and see if that fixes your problem.
> 4 votes

# Answer
Short answer, move the call to Clicker to be in Start(),

Longer answer Update gets called once every frame (which ideally is at least 30 times per second), so by putting it in update you are registering a new delegate every frame. So after 10 frames, the anonymous delegate would get created 10 times. Meaning when you click the button, it would increment lifeTimeClicks by 10, then 20 frames later when you click the button again, the delegate will have been registered 30 times, causing the lifeTimeClicks to increase by 20
> 2 votes

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


title: Main Controller dont destroy on load

text:
# Question
Title: Main Controller dont destroy on load
I would like to have a Main Controller class that should exist in many scenes. I used DontDestroyOnLoad and in runtime an object associated with this class is present in hierarchy. However, how can I use this script if its only visible in runtime? How can I assign the coresponding game object to button if I cant see It until I run the game?

# Answer
> 1 votes
You could always create a **Bootstrap** scene that would hold MainController *(and anything else that you would like to exist through out the scenes)*. Keep in mind that bootstrap scene will have to be the first scene to run.

You might want to override Unity's default play button to always load from Bootstrap into whatever scene you're currently on. Here's a nifty little script.

There are also easier solutions, check out the answers on this question.

---
Tags: unity
---


title: Unity 3d shooter tutorial animation

text:
# Question
Title: Unity 3d shooter tutorial animation
I'm following this tutorial. I cannot get even simple animations to work. Here's a very simple case that was supposed to work but did not:

1. Add an animator component to the 'player' prefab
2. Create an animator controller and drag it to the corresponding field in the player animator component.
3. Open the 'animator' tab (right click on animator controller -\> open), and drag an animation clip. This automatically becomes the default state.
4. Click play. Nothing happens. In the animator tab I can see a blue progress bar in the 'default' state (the only animation I dragged to the state machine). But the game screen shows no animation.

### The player prefab inspector:

### The very simple state machine

This is driving me nuts.

# Answer
Removing the player prefab and re-adding it did the trick When I added the player again, the 'player' avatar was automatically assigned to it. I did not have to do it manually. And this 'magically' solved the issue somehow.
> 0 votes

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


# Question
Title: How do I detect whether mouse (or touch) is being pressed over thecurrent gameObject in Unity 5?
I have a Canvas set as Screen Overlay, and an Image there. I want my image become an 8-direction custom pad, so I wanted to make a component script for the image.

In such behavior I would like to detect, on each frame (`Update()`) whether the mouse (or touch 0) is being pressed over the current object, say:

```
public class MyBehavior : MonoBehavior {
    void Update() {
        if (Application.isPlaying && Input.GetMouseButton(0)) {
            // TODO Verify the mouse is pressing over this.gameObject
        } else if (Application.isMobilePlatform && Input.touchCount > 0) {
            Touch touch = Input.GetTouch(0);
            if (touch.phase != TouchPhase.Canceled && touch.phase != TouchPhase.Ended) {
                // TODO Verify the touch is pressing over this.gameObject
            }
        }
    }
}

```

What I need is:

1. Determine the pressed-over UI object is actually `this.gameObject` and not one which is overlapping in front.
2. Determine the position of the click, in the same coordinate space as the image being clicked.
3. My goal is to calculate the appropriate direction of the click (angle) wrt the pivot of the image. I will process that direction value. I will also calculate the appropriate distance to the pivot, and process it.

How can I achieve that goal?

(*Notes: The test I want to do for standalones and mouse are actually for debug purposes*)

# Answer
Please see the following.

1. In order to make sure that the user clicks on the required image, you can adjust the sort order of the canvas component containing the image.
2. For finding the coordinate of the click, you can use the RectTransformUtility.ScreenPointToLocalPointInRectangle() method.
> 1 votes

---
Tags: unity
---


# Question
Title: Can I create an 2D texture array with different sizes for each textures?
I'm making a 2D game engine, and I need a way to batch all textures into one so I only make one `glBindTexture` call throughout a scene. I am trying to use 2D texture arrays, but they only support textures of the same size.

Do I have to conform to this, or is there a workaround?

# Answer
> 5 votes
What user1118321 says is true -- all the textures need to be the same size.

But that doesn't mean you need to USE all the space. For a small set of standalone textures, it's not a big deal to waste some space.

You can simply store the U/V coordinates of where a smaller texture ends and use that. When creating the array, just set a max size and make sure everything is \<= that.

Here's some code from my project that I use to do this -- it uses some data structures not presented here, so you'll have to modify it a bit, but the idea should help. This works in 3.3 + a common extension or two (I forget which ones) or 4.3 (4.4?) without any (I think).

```
// this takes a vector containing the raw image data from the files (I use lodepng) as well as some sizing data also returned from lodepng
// max width/height are the actual size of the textures to be created
GLuint Graphics::make_texture_array(std::vector<ArrayTextureData> &
textures, size_t max_width, size_t max_height, bool repeatable) {
    GLuint texture_name;
glGenTextures(1, &texture_name);
glBindTexture(GL_TEXTURE_2D_ARRAY, texture_name);
std::vector<u_int32_t> clear_data(max_width * max_height, 0);

//  printf("Creating texture array with %d textures and  max texture width %d and max texture height %d\n", (int)textures.size(), max_width, max_height);
    glTexStorage3D(GL_TEXTURE_2D_ARRAY, 3, GL_RGBA8, max_width, max_height, textures.size());

    for (int i = 0; i < textures.size(); i++) {
        auto & texture = textures[i];
//      printf("Loading texture into array at position %d actual texture w: %d actual texture h: %d with %d bytes\n", i, texture.width, texture.height, (int)texture.data.size());
        assert(texture.width <= max_width);
        assert(texture.height <= max_height);
        // set the whole texture to transparent (so min/mag filters don't find bad data off the edge of the actual image data)
        glTexSubImage3D(GL_TEXTURE_2D_ARRAY, 0, 0, 0, i, max_width, max_height, 1, GL_RGBA, GL_UNSIGNED_BYTE, &clear_data[0]);
        glTexSubImage3D(GL_TEXTURE_2D_ARRAY, 0, 0, 0, i, texture.width, texture.height, 1, GL_RGBA, GL_UNSIGNED_BYTE, &texture.data[0]);
        CHECK_GL_ERROR;
        texture.min_u = 0;
        texture.min_v = 0;
        texture.layer = i;
        texture.max_u = texture.width / static_cast<float>(max_width);
        texture.max_v = texture.height / static_cast<float>(max_height);
        texture.texture_id = texture_name;
    }
    if (repeatable) {
        glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_WRAP_S, GL_REPEAT);
        glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_WRAP_T, GL_REPEAT);
    } else {
        glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
        glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
    }

    // makes enlarged textures run faster but look awful
    glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MIN_FILTER, GL_NEAREST_MIPMAP_LINEAR);
    glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glGenerateMipmap(GL_TEXTURE_2D_ARRAY);
    CHECK_GL_ERROR;

    //Unbind texture
    glBindTexture( GL_TEXTURE_2D_ARRAY, NULL);

    return texture_name;
}

```

# Answer
> 1 votes
I'm not sure what you mean by "so I only make one glBindTexture call throughout a scene." What advantage does that get you?

2D texture arrays require the textures to be the same size. I don't know of any way around that.

One other option you have is to use a texture atlas. You can make a single texture that contains all of your assets and simply pass the appropriate texture coordinates for each texture use. I found this tutorial. It uses OpenGL ES 2, but it should give you the general idea.

# Answer
> 0 votes
If you're willing to restrict yourself to drivers which expose Bindless Textures you can make all the textures you want resident, put their handles in an uniform or structured buffer as `sampler2D` values and use those transparently in your shader.

If not, you could have a series of texture arrays, one for each size and in your shader code branch to select the correct array.

---
Tags: opengl
---


title: Invalid AABB aabb

text:
# Question
Title: Invalid AABB aabb
```
Invalid AABB aabb
UnityEditorInternal.InternalEditorUtility:CalculateSelectionBounds(Boolean,
                                                                   Boolean)

```

I've got this error when I place any convex `mesh collider` in scene. **What does it mean?**

Game object also has `rigidbody` with `Use Gravity = true` and after run the scene i've got error:

> transform.position assign attempt for 'gameobject1' is not valid. Input position is { NaN, NaN, NaN }.

# Answer
> 1 votes
It does not seem like you have made the mistake (If your gameobject has a `transform`) Try restarting Unity, rebooting your computer, reinstalling Unity.

# Answer
> 3 votes
So the aabb is the axis aligned bounding box and so if it is giving you errors about it that means that unity couldn't calculate the aabb of an object because either it's too small or to big or has some kind of negative size or doesn't have a transform. Your other error is probably causing the invalid aabb error as the aabb does rely on the position of the object and is probably being thrown because you don't have a transform component on the object.

# Answer
> 0 votes
```
    HealthBar.GetComponent<RectTransform>().sizeDelta = new Vector2(InitialWidthHealthBar * Player.pInstance.Health /
        Player.pInstance.MaxHealth,HealthBar.GetComponent<RectTransform>().sizeDelta.y );

```

This is the code that produced the same error.Where the Player.pInstance.MaxHealth is 0. It means 100 / 0 , which cause mathematical error.I changed the Value to 100.its Working now.and i read the same will happen with tranform too.

---
Tags: unity, physics, aabb, meshcollider, convex
---


# Question
Title: Bullet holes on curved surfaces and corners
So right now I am making an FPS game where the gun creates bullet holes (plane with texture) on impact, but there is a problem with that, if I shoot at the edge the plane will stick out and also bullet holes will not look proper when I shoot at a curved surface. I know there's at least 2 ways one is shaders and another mesh manipulation, but I could not find any tutorials on how to do it and never understood neither of them. Is anyone able to explain in detail exactly how I would achieve the effect? Thanks in advance.

# Answer
> 2 votes
I think unity can use stencil buffer though I never used it, if you are not able to do that I'll investigate deeper, One way to achieve that is to cut-out pieces of walls using some lowpoly spheres and stencil buffer, then fill that holes with an "hole" 3d model, so ask an artist to make a hole model wich looks like a cone so it can fir in a variety of holes and use normals to orient that hole.

Take a wall corner, if you paint a sphere in the stencil buffer before the wall, and after the wall then you will have a spherical shape carved out, after that you disable stencil buffer and you render in the wall the hole cone (the cone is designed arounr a sphere so that it will always fit any empty space).

the hardest part I think is finding the normal for the shot, the short way would be to do some ray casts around the hitted point to find out if all normals are equals or not, then you average them.

# Answer
> 0 votes
What I've done in the past is to simply not place the decal close to the edge. I know it sounds a bit cheap but its fast simple and can look fine under some circumstances. Just Move the decal in a bit :)

---
Tags: c#, shaders, unity, mesh
---


# Question
Title: How do I add a PIXI container into a Phaser Game?
How do I add a PIXI container into a Phaser Game?

I have a game made ONLY with PIXI. but now i would like to port it to a Phaser.

All my game content happens inside a pixi container "screenContainer". I tried to add a pixi container like this.

```
var created = function() {
       screenContainer = new PIXI.DisplayObjectContainer();
       var sprite = m.game.add.existing(screenContainer);
}

var.game = new Phaser.Game(gameWidth, gameHeight, Phaser.AUTO, "divId", { create: created });

```

but it stops here

```
"phaser.js" line 33067
/**
* The core update - as called by World.
* @method Phaser.Group#update
* @protected
*/
Phaser.Group.prototype.update = function () {
var i = this.children.length;

while (i--)
{
    this.children[i].update(); // UPDATE IS UNDEFINED
}

};

```

because Pixi.Container, does not have "update" method.

Is there any other way to add a pixi container inside a phaser game?

# Answer
All Phaser display objects (group, sprites...) are based on PIXI ones. PIXI objects can be rendered in phaser render tree. the only problem is the update and postUpdate function.

I solved it adding this simple patch:

```
PIXI.DisplayObject.prototype.update = function () { };
PIXI.DisplayObject.prototype.postUpdate = function () { };

```

this patch adds a empty function for "update" and "postUpdate" methods in PIXI displayObjects prototype. In that case Phaser update tree founds a function to execute.
> 1 votes

---
Tags: javascript, html5, phaser
---


# Question
Title: Opentk hdr rendering with framebuffer white screen problem
I am trying to do hdr rendering with two shader programs: one simply draws a hdr texture on a fullscreen quad and the other one does tonemapping. I am trying either linear tonemapping

```
colorOut = colorIn/(colorIn+1)

```

or exposure with gamma correction

```
colorOut = pow(1 - exp(-colorIn*exposure), 1/gamma)

```

I am currently using OpenTK 1.1.2225 and Magick.NET-Q16-HDRI-AnyCPU. Shader programs are correctly loaded by my LoadShaderProgram function.

The c# code is:

```
class MyClass: GameWindow
{
    int textureID, colorBuffer, rbo, shaderProgram, tonemapProgram quadVAO;
    float exposure = 1.0f;

    float[] quadVertices = {
         // Positions        // Texture Coords
         -1.0f, 1.0f, 0.0f, 0.0f, 1.0f,
         -1.0f, -1.0f, 0.0f, 0.0f, 0.0f,
         1.0f, 1.0f, 0.0f, 1.0f, 1.0f,
         1.0f, -1.0f, 0.0f, 1.0f, 0.0f,
     };

    public MyClass() : base(1000,700,new GraphicsMode(),"My Title",GameWindowFlags.Default)
    { }

    protected int LoadShaderProgram(string VSSource, string FSSource)
    {
        //tested code, returns the program id
    }

    protected override void OnLoad(System.EventArgs e)
    {
        try
        {
            VSync = VSyncMode.On;
            GL.Enable(EnableCap.Texture2D);
            GL.Enable(EnableCap.DepthTest);
            GL.DepthFunc(DepthFunction.Less);

            // Setup quad VAO
            quadVAO = GL.GenVertexArray();
            int quadVBO = GL.GenBuffer();
            GL.BindVertexArray(quadVAO);
            GL.BindBuffer(BufferTarget.ArrayBuffer, quadVBO);
            GL.BufferData(BufferTarget.ArrayBuffer, quadVertices.Length * sizeof(float), quadVertices, BufferUsageHint.StaticDraw);
            GL.EnableVertexAttribArray(0);
            GL.VertexAttribPointer(0, 3, VertexAttribPointerType.Float, false, 5 * sizeof(float), 0);
            GL.EnableVertexAttribArray(1);
            GL.VertexAttribPointer(1, 2, VertexAttribPointerType.Float, false, 5 * sizeof(float), 3 * sizeof(float));

            MagickImage img = new MagickImage(@"../../Cubemaps/GravelPlaza_REF.hdr");
            int width = img.Width;
            int height = img.Height;
            float[] data = img.GetPixels().ToArray();

            //Load lat/long hdr map
            textureID = GL.GenTexture();
            GL.BindTexture(TextureTarget.Texture2D, textureID);
            GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgb32f, width, height, 0, PixelFormat.Rgb, PixelType.Float, data);
            GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapS, Convert.ToInt32(TextureWrapMode.Repeat));
            GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapT, Convert.ToInt32(TextureWrapMode.Repeat));
            GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, Convert.ToInt32(TextureMinFilter.Linear));
            GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, Convert.ToInt32(TextureMagFilter.Linear));
            GL.BindTexture(TextureTarget.Texture2D, 0);

            //Setup color buffer of framebuffer
            colorBuffer = GL.GenTexture();
            GL.BindTexture(TextureTarget.Texture2D, colorBuffer);
            GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba32f, ClientSize.Width, ClientSize.Height, 0, PixelFormat.Rgba, PixelType.Float, IntPtr.Zero);
            GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapS, Convert.ToInt32(TextureWrapMode.ClampToEdge));
            GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapT, Convert.ToInt32(TextureWrapMode.ClampToEdge));
            GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, Convert.ToInt32(TextureMinFilter.Linear));
            GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, Convert.ToInt32(TextureMagFilter.Linear));
            GL.BindTexture(TextureTarget.Texture2D, 0);

            //Setup renderbuffer of framebuffer
            rbo = GL.GenRenderbuffer();
            GL.BindRenderbuffer(RenderbufferTarget.Renderbuffer, rbo);
            GL.RenderbufferStorage(RenderbufferTarget.Renderbuffer, RenderbufferStorage.DepthComponent32, ClientSize.Width, ClientSize.Height);
            GL.BindRenderbuffer(RenderbufferTarget.Renderbuffer, 0);

            ErrorCode er = GL.GetError();
            Console.WriteLine(er.ToString());

            //Setup framebuffer
            hdrFBO = GL.GenFramebuffer();
            GL.BindFramebuffer(FramebufferTarget.Framebuffer, hdrFBO);
            GL.FramebufferTexture2D(FramebufferTarget.Framebuffer, FramebufferAttachment.ColorAttachment0, TextureTarget.Texture2D, colorBuffer, 0);
            GL.FramebufferRenderbuffer(FramebufferTarget.Framebuffer, FramebufferAttachment.DepthAttachment, RenderbufferTarget.Renderbuffer, rbo);
            if(GL.CheckFramebufferStatus(FramebufferTarget.Framebuffer) == FramebufferErrorCode.FramebufferComplete)
            {
                Console.WriteLine("framebuffer ok");
            }
            GL.BindFramebuffer(FramebufferTarget.Framebuffer, 0);

            //Load tonemap shader programs
            string vsource = new StreamReader(@"../../Shaders/TonemapVertexShader.glsl").ReadToEnd();
            string fsource = new StreamReader(@"../../Shaders/TonemapFragmentShader.glsl").ReadToEnd();
            tonemapProgram = LoadShaderProgram(vsource, fsource);
           //Load quad shader programs
            vsource = new StreamReader(@"../../Shaders/quadVshader.glsl").ReadToEnd();
            fsource = new StreamReader(@"../../Shaders/quadFshader.glsl").ReadToEnd();
            shaderProgram= LoadShaderProgram(vsource, fsource);

    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
    }

}

    protected override void OnRenderFrame(FrameEventArgs e)
    {
        GL.ClearColor(Color.Purple);
        //HDR PASS
        GL.BindFramebuffer(FramebufferTarget.Framebuffer, hdrFBO);

            GL.UseProgram(shaderProgram);
            GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);
            GL.ActiveTexture(TextureUnit.Texture0);
            GL.BindTexture(TextureTarget.Texture2D, textureID);
            GL.BindVertexArray(quadVAO);
            GL.DrawArrays(PrimitiveType.TriangleStrip, 0, 4);
            GL.BindVertexArray(0);
       GL.BindFramebuffer(FramebufferTarget.Framebuffer, 0);
      //TONEMAPPING
      GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);
      GL.UseProgram(tonemapProgram);
      GL.ActiveTexture(TextureUnit.Texture0);
      GL.BindTexture(TextureTarget.Texture2D,colorBuffer);
      GL.Uniform1(GL.GetUniformLocation(tonemapProgram, "exposure"), exposure);
      GL.BindVertexArray(quadVAO);
      GL.DrawArrays(PrimitiveType.TriangleStrip, 0, 4);
      GL.BindVertexArray(0);
      SwapBuffers();
      }

    public static void Main()
    {
        try
        {
            using (MyClass p = new MyClass())
            {
                p.Run(60);
            }
        }
    }
}

```

quadVShader and TonemapVShader are the same, they just set glPosition on the screen and pass texcoords:

```
#version 400
layout(location = 0) in vec3 position;
layout(location = 1) in vec2 texCoords;

out vec2 TexCoords;

void main()
{
    gl_Position = vec4(position.x, position.y, 0.0f, 1.0f);
    TexCoords = texCoords;
}

```

quadFShader is rather simple, just samples the hdr image and writes the color in:

```
#version 400
out vec4 color;
in vec2 TexCoords;

uniform sampler2D hdrBuffer;

void main()
{
   color = vec4(texture(hdrBuffer,TexCoords).rgb, 1.0f);
}

```

In TonemapFShader I comment out the method I'm not using:

```
#version 400
out vec4 color;
in vec2 TexCoords;

uniform sampler2D hdrBuffer;
uniform float exposure;

void main()
{
    const float gamma = 2.2;
    vec3 hdrColor = texture(hdrBuffer, TexCoords).rgb;

    // reinhard
    //vec3 result = hdrColor / (hdrColor + vec3(1.0));
    // exposure
    vec3 result = vec3(1.0) - exp(-hdrColor * exposure);
    //gamma correct
    result = pow(result, vec3(1.0 / gamma));

    color = vec4(result, 1.0f);
}

```

Various error checking don't return any error message and "framebuffer ok" is printed.

What I tried in order to debug is checking the values of result, with the linear tonemapping I get all ones (vec3(1f)), with the exposure+gamma one I get values between 0 and 1 but one problem is that they are all the same while they are being sampled from a texture which is not monochromatic. The second problem is that the screen is completely white, in both cases, even when "result" has components between 0 and 1.

P.S. I checked the code 100 times before posting, I hope there are no typos but I'm not perfect, please don't get mad if you think you got the answer but it's really a typo and I tell you.

# Answer
> 2 votes
Turned out exposure = 1.0f was way too high for the image I was using. The results of tonemapping with these two formulas I found on this tutorial are not so pretty with real hdr images, just with analytic lights.

I got a very bad, but at least visible, result with exposures around 10e-5.

---
Tags: c#, opengl, opentk, frame-buffer, hdr
---


title: numeric identifiers associative array

text:
# Question
Title: numeric identifiers associative array
**edit:** clarified my question. I also realized that I didn't pick a very conclusive question title, which unfortunately I cannot change anymore, sorry.

Hey everyone,

to improve my programming skills a little and getting familiar with good design patterns, I'm trying to program a litte turn based strategy game, and I am at the point to choose a good data structure for the configuration of different terraintypes and unittypes etc. which do exist.

What I have implemented so far is a big "Game Object" with knowledge about everything in the game, and many of its properties are big associative arrays (I'm using PHP, but my question doesn't really have to do much with the language), for example an arrays of units, a map array.... What my array structure is comparable to is the type object pattern mentioned here.

Example: A single unit is of a certain type, say 'Infantry', and shares many data with all the other infantry untis on the field. Instead of copying all these values, I give every unit a "type" so it can look up the details there. Similar with terraintypes. Example:

```
terraintypes = array()
terraintypes[0] = array()
terraintypes[0]['name'] = 'Forest'
terraintypes[0]['capturable'] = false

unittypes = array()
unittypes[0] = array()
unittypes[0]['name'] = 'Infantry'
unittypes[0]['movecost'] = array()
unittypes[0]['movecost'][0] = 5 //Movementpoints needed for forest
unittypes[0]['movecost'][1] = 7 //Movementpoints needed for terraintype 1

```

A specific unit or tile on the map wouldn't know its movement costs or name, but would be able to look that up in the `unittypes` array. Example:

```
sometile = array();
sometile['owner'] = whatever
sometile['type'] = 0; //this tile is a forest

someunit = array()
someunit['type'] = 0 //This is an "Infantry".

```

The problem is that getting any kind of information will produce very verbose code, for example finding out how much it costs for a `unit` to move onto a `tile` will be

```
unittypes[unit['type']]['movecost'][tile['type']]

```

I am trying right now to move to using more objects and classes, so if I give a unit a reference to its unittype, it can lookup information itself, for example

```
terraintypes[0] = new Terraintype('Forest')
unittypes[0] = new Unittype('Infantry')
someunit = new Unit(unittypes[0])

```

Now, if I ask a unit something only its unittype would now, the unit can look it up itself, e.g. `someunit.getName()` will be implemented in the unit like `this.unittype.getName()`.

So far so good. However, how could a unittype store its movecost on the different terrains? Basically I would need an array indexed with terraintypes, but as that is not possible, I will have to swhich back to translate everything to numeric keys, and have a movecost value for every pair (terraintype, unittype).

Who assigns these numeric keys and where? Will every single unittype need to store some kind of identifier which is unique among all the unittypes? Should I use some constants like `const FOREST = 0; const ROAD = 1; const INFANTRY = 0; const VEHICLES = 1` etc?

Another of my problems for finding a good data structure is that if I don't give the game all the data directly, but break everything down to smaller parts, then many parts will need to know about the same objects.

For example, if the Map object knows about all tiles of the map and the units on it, then the game doesn't really know anything about the units, it only knows about the map, and every command in the game which affects a unit needs to be passed to the map, even though its not actually a "map task", like healing units.

This seems like breaking the single responsibility pattern. However, storing references to all the units in several places (so both the Map and something else store references to units) seems to be troublesome with bookkeeping.

To **sum it up** a little, can you hint me to data structure which are suitable to represent what I am describing? Thanks in advance!

# Answer
> 0 votes
First your organization of data is pretty good. Using arrays or objects does not really matter much although an object is cleaner, as it provides a clean interface and avoids simple problems like unset properties. I don't think that verbosity of yours a bad thing. `unittypes[unit['type']]['movecost'][tile['type']]` can easily be encapsulated, so you need it only once. And for that it's ok.

@Draco18s answer only changes where you store the data. In your case you store the instances in global arrays. Storing them in the class itself as static data might be cleaner. Storing them in an array might actually be the better option, as this allows iterating and hence searching them. So you could do `TerrainType::GetTerrain("Forest")` or the like. You could also store integer references by doing something like:

```
public class TerrainType {
    public static FOREST = AddTerrain("Forest",false,0.25f);
    public static PLAINS = AddTerrain("Plains",true,0.75f);
    public static ROAD = AddTerrain("Road",false,1.5f);

    public static terrains = array();
    private AddTerrain(params...){
        idx = len(terrains);
        terrains[idx] = TerrainType(params...);
        return idx;
    }
}

```

Or store the ID in the `TerrainType` itself.

As for the mapping from Units to Movement speeds I'd note that this is a mapping: `f(Unit, Terrain): speed`. You could store this in either the Terrain or the unit or in both. Easiest way would be: Store a unit "base" speed and a terrain "multiplier". Then when unit x is on terrain y you multiply them to get the actual speed (at that point you do have access to both the `UnitType` and the `TerrainType` or something is wrong ;-) )

Otherwise you would need to maintain a table and I'd make it a table: `Speed[UnitType][TerrainType]` however maintaining/creating this might be quite cumbersome due to the NxM relationship here which easily explodes as you add more units/terrains. Note that you have integer keys which you can use as indices into that table if you use the above code. Of course the mapping needs to be done with the constants assigned during TerrainType/UnitType initalization. If you have arrays, you could have a `GetIdx` method that scans the array and returns the index. As this would also need to be done when accessing a speed, you want to encapsulate this into `GetSpeed(UnitType, TerrainType)`

Last about passing messages from Game-\>World-\>Unit: Nothing bad about this either. Just make it layered. E.g. `Game.MoveUnit(unitId, X, Y) -> World.MoveUnit(unitId, X, Y) -> Unit.Move(X, Y)` Or more abstract messages. Each message has an ID and data. Like `UnitMessage("Move", X, Y)`. The game passes all messages it does not understand to the world, which would then pass it to the unit.

# Answer
> 0 votes
I would create a custom data type (a "class") for your terrains. You'd end up with something like this:

```
public class TerrainType {
    public static FOREST = new TerrainType("Forest",false,0.25f);
    public static PLAINS = new TerrainType("Plains",true,0.75f);
    public static ROAD = new TerrainType("Road",false,1.5f);

    //I am not sure how PHP handles readonly fields
    public final string name;
    public final bool capturable;
    public final float move_cost;

    private TerrainType(string name, bool capture, float move_speed) {
        this.name = name;
        this.capturable = capture;
        this.move_cost = move_speed;
    }
}

```

This gives you a singleton-like structure that holds your terrain types and their associated properties without making your code stringly typed.

Then your map object can consist of a 2D array where each position holds a reference to its terrain type. e.g. `mapArr[x][y] = TerrainType.FOREST;` although your map might be another class as well, holding the terrain type, who owns the tile, and the units there.

---
Tags: data-structure
---


# Question
Title: Why should a FPS game use a "floating arms" approach over full body one?
I've seen many first person shooter games both single and multiplayer using a set of floating arms and a gun instead of using the whole body model.

What is the advantage of floating arms? You are technically doubling the work making two meshes and two animations for each action.

# Answer
> 3 votes
Because it's more simple.

Player's avatar arms are one thing to tweak and make look right in a 3d world. If you add the full body, it takes more resource to accomplish, and does not always add much to the gameplay.

If you use only the arms, you can have the arms and the gun in the frame of the camera; while if you use a 3d body as well, you'll have to tie it to the world frame. You then have to take a *lot* of things into consideration: what if there is an explosion and the player's avatar gets launched in the air? Would the motion of the camera AND the motion of the body of the avatar match and be adequate in their look and feel?

Also, consider mouselook. If you use only the arms, you'll have less limitations that if you use the full body. If using full body, the designer might want to restrict the player from being able to target their own feet ("Dude! I'm shooting my own feet and I'm not even losing health!!"). Simply making an animation that looks and feel right when the player looks all around is, again, more expensive than just using the arms.

---
Tags: animation, first-person-shooter
---


# Question
Title: Finding Game Object with Regular Expressions
Is there a way to use a Regular expression in the GameObject.Find() method?

I'm making a checkers game and I've got pieces named Red Piece (x,y) and White Piece (x,y) (where x & y are actual integer coordinates). I want to destroy a piece at a certain x,y. So what I'm trying to do is something like

```
Destroy(GameObject.Find(Regex.Matches("(Red)|(White) Piece (" + x + ","+ y + ")")));

```

I need it to find any object with a name that contains "Piece (x,y)" whether it's a red piece or a white piece, and destroy it. Any ideas?

# Answer
**No, not using `GameObject.Find`.**

You could, maintain your own list of object names, and search that using regex. Then pass the found string into `GameObject.Find` to get the actual game object from the name.

However, I'm not really clear on why you're naming checkers pieces to include their location (since checkers pieces move). But you can find game objects at a specific location, using something like a raycast. But I'd recommend simply reorganizing the way you manage objects. There are a few ways to do that. Maintain a 2D array that contains references to all the gameobjects for the pieces. Or keep better information about how you're moving pieces, to include the spaces they're "jumping".
> 3 votes

# Answer
`Find` cannot do this. You could try using `FindObjectsOfType` to get an array of `GameObject`s, and then manually filter that list by rejecting any with a name that doesn't match your pattern.

However, it seems like you could be solving the issue at a higher level. For example, if you're just trying to remove all "piece" game objects from the world, leaving behind any other game objects you're using for other things, you could consider:

* tagging each of those objects when you *create* them (or otherwise perform the manipulation on them that gets them ready to be deleted), and then using `FindObjectsWithTag`
* similarly, put them into a `List<GameObject>` called `pieces` (or something) so that you can find them all later to destroy them.

The last option is potentially far, far more efficient than having to traverse *every* game object in the world and perform a regex, or even just a substring comparison, against them.
> 2 votes

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


# Question
Title: Logical math behind jumping in a 3D world
I'm unsure if I should ask the mathematic part of StackOverflow or the gamedev part. I'm trying to figure out how the gravity changes the position of an element in a 3D world. I've been trying to rescript the gravity in a game so I could attach it to every element I want.

As far as I know; The movement of the player has something to do with the current position ( obviously ), the velocity, the gravity and Delta Time. As far as I'm concerned too, I know that when an element makes some kind of jump, he should go up since the velocity is still positive. Each frame should update the player's position, depending on the current position and velocity, the new position will be created. I've been able to create it in a platformer ( 2D ) but I haven't succeeded to do this in a 3D game. As far as I came, the object just flew into the air at a massive speed and ended up landing in another galaxy..

I'm currently working with Lua, if you were trying to explain something in a language. If you're working with another language and want to give me an example in that.. feel free to do so. I'm known with a lot of languages ( programmer here. ). It's just about the logic behind it, the actual math.

Thanks in advance

# Answer
> 2 votes
It's the same as you'd do it for 2D, just with an extra axis. Use the same exact equations you do for a 2D game, something similar to the equations of motion or the kinematics equations.

* For each axis (X, Y, Z)
    + Sum the forces for that axis (gravity, jump force, weapon knockback, etc. Keep in mind, some of these forces will be 0 on some of the axis, like gravity is only likely to affect one axis)
    + Calculate the velocity for that axis (force for that axis * delta time)
    + Calculate the new position for that axis (velocity for that axis * delta time)

After all these calculations have been done, you'll have a new velocity and position in 3D space. All three of these values can be stored in something like a `vector3`. This is just an object that contains three scalar values, in this case, one for each axis. Each calculation only affects the axis you're currently working with. i.e. force.x -\> velocity.x - \> position.x.

Simply removing one of these axis would result in your object being restricted to movement in a 2D plane. Removing two axis results in movement along a single line. All the axis still work, independent of each other.

---
Tags: mathematics, lua, jumping
---


title: Moving at constant speed and angle

text:
# Question
Title: Moving at constant speed and angle
The picture illustrates

I cannot figure out the math on this. The "arrows" should move at the same speed in both examples.

# Answer
You are moving at a constant speed in terms of the **y-axis**. To move a constant speed in terms of the **vector direction**, you would need to calculate the distance to be traveled (in purple in your first diagram), and if you know how far you want to go per run, divide the total distance by that distance to get how many loops it will take to traverse the vector to the goal position. Now divide the y-change by that number of loops and you now know the amount to add/subtract from the y in every increment. Now, use your formula: y=mx, and instead of incrementing y by 1, increment it by that incement value you just found. I hope you can understand all that.

The formula for distance is sqrt(|x1 - x2|^2 + |y1 - y2|^2).
> 1 votes

---
Tags: c++
---


title: Java- Trig based movement

text:
# Question
Title: Java- Trig based movement
I have been trying to create a smooth movement technique that would allow me to move in all directions, not just the 8 cardinal directions. I have tried to use this doing trig, and while the coordinates are being calculated correctly, drawing anything onto graphics requires me to use integers. Because of the rounding, the movement is reduced to the 8 cardinal directions again. How can I get around the draw methods only using integers?

I calculate the movement by taking the current x position, and adding the product of the speed and sin/cos of the angle of movement

```
public void moveForward(Block b) {

        b.x += speed * Math.sin(angle);

        b.y += speed * Math.cos(angle);
}

```

Here is the Block class:

```
import java.awt.Graphics;

public class Block {
int x, y;
public Map() {
    x=0;
    y=0;
}

public void Draw(Graphics g) {
    g.drawRect(x,y,100,100);
}

```

And this is the panel class that draws the movement:

```
import java.awt.Graphics;
import java.awt.event.ActionEvent;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JPanel;
import javax.swing.KeyStroke;

public class Panel extends JPanel{
Block block;
Movement movement = new Movement(0);
boolean mforward,mback,rright,rleft;

public Panel() {
    block = new Block();
    setKeyBinds();
    game.start();
}

Thread game = new Thread(){
    public void run(){
        while(true){
        if(mforward)
            movement.moveForward(block);
        if(mback)
            movement.moveBack(block);
        if(rright)
            movement.addangle(1);
        if(rleft)
            movement.addangle(-1);
        repaint();
        try {
            Thread.sleep(50);
        } catch (InterruptedException e) {}
        }
    }
};

public void paintComponent(Graphics g){
    super.paintComponent(g);
    block.Draw(g);
    movement.Draw(g);
}

//Following code is for setting up keymapping

private void setKeyBinds() {
    getInputMap().put(KeyStroke.getKeyStroke("UP"), "MOVEUP");
    getInputMap().put(KeyStroke.getKeyStroke("DOWN"), "MOVEDOWN");
    getInputMap().put(KeyStroke.getKeyStroke("LEFT"), "MOVELEFT");
    getInputMap().put(KeyStroke.getKeyStroke("RIGHT"), "MOVERIGHT");
    getInputMap().put(KeyStroke.getKeyStroke("released UP"), "STOPUP");
    getInputMap().put(KeyStroke.getKeyStroke("released DOWN"), "STOPDOWN");
    getInputMap().put(KeyStroke.getKeyStroke("released LEFT"), "STOPLEFT");
    getInputMap().put(KeyStroke.getKeyStroke("released RIGHT"), "STOPRIGHT");
    getActionMap().put("MOVEUP", moveforward);
    getActionMap().put("MOVEDOWN", moveback);
    getActionMap().put("MOVELEFT", rotateleft);
    getActionMap().put("MOVERIGHT", rotateright);
    getActionMap().put("STOPUP", stopup);
    getActionMap().put("STOPDOWN", stopdown);
    getActionMap().put("STOPLEFT", stopleft);
    getActionMap().put("STOPRIGHT", stopright);
}
AbstractAction moveforward = new AbstractAction() {

    @Override
    public void actionPerformed(ActionEvent arg0) {
        mforward=true;
    }

};
AbstractAction moveback = new AbstractAction() {

    @Override
    public void actionPerformed(ActionEvent arg0) {
        mback=true;
    }

};
AbstractAction rotateleft  = new AbstractAction() {

    @Override
    public void actionPerformed(ActionEvent arg0) {
        rleft=true;
    }

};
AbstractAction rotateright = new AbstractAction() {

    @Override
    public void actionPerformed(ActionEvent arg0) {
    rright=true;
    }

};
AbstractAction stopup = new AbstractAction() {

    @Override
    public void actionPerformed(ActionEvent arg0) {
mforward=false;
    }

};
AbstractAction stopdown = new AbstractAction() {

    @Override
    public void actionPerformed(ActionEvent arg0) {
        mback=false;
    }

};
AbstractAction stopleft = new AbstractAction() {

    @Override
    public void actionPerformed(ActionEvent arg0) {
        rleft=false;
    }

};
AbstractAction stopright = new AbstractAction() {

    @Override
    public void actionPerformed(ActionEvent arg0) {
        rright=false;
    }

};

}

```

# Answer
> 0 votes
Use floats for your logic & cast or round then to integers as you pass them to the drawing methods.

---
Tags: java, movement, trigonometry
---


title: Failed to load QCARWrapper.dll

text:
# Question
Title: Failed to load QCARWrapper.dll
I am using unity 5.1.0f(64 bit) and Vuforia SDK Version: vuforia-unity-5-0-5

The web cam is operating normally in windows but in unity in Play Mode not.

I am getting an error message "failed to load QCARWrapper.dll: expected 64bit architecture..."

Can anybody help out solving this issue?

# Answer
**Vuforia 5.0** supports the **32bit** version of the Unity Editor on **Windows**, and the **64bit** version **on Mac**.

So, **There are two possible solutions:**

1. you just need to install and use the Unity 5 32bit Editor, on Windows.

***OR***

2. Create a new folder **"x86"** inside

**Assets\>\>Plugins**

inside your unity project structure Then move the following files from **"Plugins"** to newely created **"x86"** folder.

* QCARWrapper.lib
    * QCARWrapper.dll
    * QCARWrapper.dll.signature
    * QCARWrapper.exp

After that check log message, If you see the log like:

```
Setting platform to 'Editor' for plugin: Assets/Plugins/x86/VuforiaWrapper.dll
UnityEngine.Debug:Log(Object)
Vuforia.EditorClasses.ExtensionImport:UpdatePluginSettings() (at Assets/Vuforia/Editor/Scripts/ExtensionImport.cs:43)
UnityEditor.EditorApplication:Internal_CallUpdateFunctions()

```

Then , **Congrats !! You are ready to Go!**

**FYI More Info:**

You need to use the Installer to download and install the additional Android support component, by selecting it from the list of the available components in the Installer wizard;
> 2 votes

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


# Question
Title: How to resolve push block physics in a 2D side scroller puzzle
I've been working on a 2D tile-based side scroller puzzle game in Unity with obstacles such as doors, keys, fans, portals, etc., but one type of obstacle, push blocks, is giving me some issues. Here is how it is supposed to work:

* The player (an certain other obstacles) can push the block from either side, and it should move smoothly until it is either blocked by another obstacle or there is no ground beneath it
* If it is pushed off an edge, it should fall into whatever hole is there, even if it is a snug fit. *(left picture)*
* The top of the block should be flush with other blocks or surfaces when they are at the same level of height. There are no slopes in the tileset, so this would happen often. Motion across the combined surfaces should be smooth, with no way to wiggle between adjacent blocks. *(right picture)*
* It must be able to respond to other forces in the game such as fans and gravity switches.

I have been using Unity's built-in physics engine, which has worked great for all other components of the game, but sometimes allows blocks to jump over holes, and sometimes blocks get stuck between other blocks when they shouldn't, so I have tried abandoning Unity's physics and made my own. It just made the rest of the game more glitchy and still failed to resolve the block problems.

If I change just the way the blocks physics work, I may be able to lock its position to a grid, where it cannot be left between tiles. That way I could get the more snug collisions to work. If I did this though, it would cause problems with the rest of the interactions. A floating block with a fan underneath it bounces around too much to be locked to a grid. Does anyone know a design that would allow all these requirements of be met?

# Answer
> 1 votes
I had the same issue with my first game. I fixed the alignment issue by placing a Trigger in the hole that detects whenever a block touches it when that happens the block touching the Trigger gets destroyed and spawns a box just above the hole that would fall straight down.

# Answer
> -1 votes
why not set triggers that say.. ok the block is close enough.. turn off the rigid body and lerp it over the opening then drop down my increments until its in a desired position?

---
Tags: unity, 2d, physics, tiles, side-scroller
---


title: Ways to present levels overview

text:
# Question
Title: Ways to present levels overview
I'm working on a game that will have lots of (more than 100) levels. The player has to finish a level before she can play the next one, but also can play levels again that are already finished.

Now I'm looking for ways on how to present an overview of the levels to the player. A simple list (with a small graphic showing the level) is of course a possibility, but I wonder what other, perhaps less boring, ways there are.

# Answer
> 6 votes
I can share my experience from a mobile game that had 10 worlds with 10 levels each so 100 levels in total. We displayed each world as a map with a winding road on it. Each level had a badge with its number and the badge resembled in a way the signs on US highways. All the maps were then put into a single slide controller so that the user can easily snap between maps. Levels that were not played and locked were tinted darkly. Unlocked but not played levels had a light shade of green and completed levels had a dark shade of the same green. Testing the user experience yielded positive result as all users even small kids found it easy to navigate and choose the appropriate level.

# Answer
> 4 votes
Put your levels into logical groups. Then have the player select the group, and on the next screen select the level from that group.

Grouping can be either by theme or by difficulty. Here is a mockup:

First screen:

When the user clicks on a tile:

When it makes sense in the context of your game, you could also use a map of the game world to represent the overworld where the player selects the region they want to play in and then show them a regional map where the player picks the level.

---
Tags: game-design, user-experience
---


title: Lerp vs. Animation

text:
# Question
Title: Lerp vs. Animation
I've read a few posts regarding lerp and animation, but none seemingly fully answer my question - or I'm not reading into them correctly.

Lets say I have a box in a game. This box has a lid, and the only way it opens is via user interaction (eg. put aside physics if it were to hang upside down; a user presses 'E' and the box opens).

Now, I can achieve this one of two ways.

1) I animate the model of the box with an "Open" animation - the box lid rotating on it's X axis until the model constitutes an 'open' box; OR

2) I lerp the box lid from closed to open over time using rotation on it's X axis until again, the model constitutes an 'open' box.

Apart from the post here showing that:

> ...through script, MoveTowards method caused up to 0.10 ms latency while playing regular animation almost made no change. If there was anything it could be something between 0.1 and 0.3 ms.

Is there any reason why one would be preferred over the other? I personally would prefer to use Lerp as that way, I can make a generic 'Open' class that I can attach to the box lid, and then to a door, just changing the axis on which it pivots.

Any ideas, thoughts or explanations would be greatly appreciated.

# Answer
The `Lerp` solution works well for this one animation for this one box.

But what if your graphics department gets the idea to replace the box with one which has a more fancy opening animation with far more moving parts?

Doing that as an animation in the 3d modeling program might be far easier than animating all the sub-models with scripts. It also allows to simply replace the 3d model with a differently animated one in a simple drag-and-drop manner without having to change any code.

But when you don't plan to have such complex animations in your game, then using the animation system might be overkill.
> 1 votes

---
Tags: unity, animation, lerp
---


title: iOS build size is too large in Unity

text:
# Question
Title: iOS build size is too large in Unity
I have finally completed my game and ready to upload my game to the App store, but my build size is too large.

I have checked log statement and it is roughly **13.3 mb** but when i build my game and test on iOS device it is **80.0 mb**.

Also

`Scripting Backend` is 'Mono2x'

`Stripping Level` is 'use micro mscorlib'

`Script Call Optimisation` is 'Fast but no Exception'

My Game size must be around 15 to 20 mb why it is too large?

What i am missing?

# Answer
> 3 votes
There is a unity guide for general optimisation on the unity website.

To summarize it quickly (read the article):

* Reduce texture sizes (You can have specific settings Just for IOS)
* Compress meshes and animation
* Remove any DLLs that the platform your building for doesn't use
* Reduce .NET API size (player Settings-\>IOS-\>Other Settings-\>Api Compatibility Level Set to ".NET 2.0 Subset")

You can see the larger assets in that image you linked above, Look at those and make sure that you compress them appropriately for IOS (see the unity website from above for a guide on that)

Note there is a great question that might help you here about the web player being too large

---
Tags: unity, ios, scripting, build-process
---


# Question
Title: Why have a publisher on Steam now, when you can self-publish and the Greenlighting process is the same?
I can't find a definitive answer to whether putting up your game on Steam via a publisher helps somehow, other than bringing some popularity due to publisher's other games/apps. It seems that Greenlight procedure doesn't change or speed up if you have a publisher, or decide to publish yourself (at least according to Steam itself, officially, but who knows what goes on behind the scenes).

The general sentiment on the internet seems to be that you should "cut out the middleman" and save your money that would otherwise go elsewhere, for almost nothing.

People are comparing the Steam publisher to other game, music and video publishers (networks), saying they exist to help distribute your product by making physical copies (optical discs, usb drives, third-party stores), but this doesn't seem to apply to Steam, as there's nothing physical involved.

There's also a matter of advertisement, community management and posting news, updates, etc to create more visibility, which you can also manage on your own, if you wish.

So besides that, are there any important benefits to having a publisher on Steam?

# Answer
> 1 votes
One reason to have a publisher is safety.
If you have a contract with a publisher you have good chances the publisher pays you money before you release your game. Of course this only happens after the publisher has had a good idea on your concept and decides it's worth selling it. As a developer this helps you pay rent and salaries of your employees. Publishers also have lots of resources for marketing and will help you with it or might even do it completely for you. The publisher will have good contacts with all relevant medias (magazines, websites and maybe even TV channels).
As suggested by Philip here are some risks when working with publishers: There are usually strict contracts involced when working with publishers. If you can't deliver the promised product on a tight schedule you might have to pay back lots of the money the publisher has given to you in advance. What exactly might happen depends on the publishing contract you have signed. There are all kinds of things you have to consider. Also publishers often want to hold shares of your company and the legal rights to own the finished product. That means even if you finish the product the publisher might want to produce a sequel with another team and you are not allowed to create any games in the unviverse you have created.

When you decide to go without a publisher you have to do everything yourself. This might be impossible if you don't have huge cash reserves or get a loan. All the risk is resting entirely on you. Steam Greenlight and sites like Kickstarter may help you get money to earn money before the project is finished. But it is easy to run out of money and you have no guarantees to earn enough money to cover your expenses. Game development is very expensive even if you have a small team. It's different if you don't work on it full time of course. Also doing PR costs lots of time and money but is very important for success.

There are many pros and cons for having a publisher. Each team and project has to weight them and decide if they go with a publisher or try self publishing. Also a team has to carefully choose a publisher and involve a lawyer when signing the contract.

---
Tags: steam
---


title: TCP Slow Start in Network Games

text:
# Question
Title: TCP Slow Start in Network Games
I'm getting latency issues in bandwidth intensive level transitions part of my game that are proportional to the distance to the server. I believe I'm hitting TCP Slow Start issues. It's also fine when I spam level transitions in quick succession but the problems re-appears. Note that I'm not breaking the TCP connection.

Effectively the transfer rate of my game is very bursty and remote users are experiencing a high latency (0.8 second) during these events. Some of the data I need to send during these bursts are dynamic so I can't pre-exchange it.

Is there anything I can do to mitigate the problem? Sending dummy data to keep the TCP window size is pretty much not a solution.

All the data needs to be received in-order so UDP isn't really appropriate here.

# Answer
> 1 votes
Turns out I needed to set tcp\_slow\_start\_after\_idle:

```
/sbin/sysctl -w net.ipv4.tcp_slow_start_after_idle=0

```

Looks like SPDY suggests the same for similar reasons.

# Answer
> 1 votes
Cache the non dynamic stuff perhaps or use other mechanisms for the "burst" situation its hard to say without knowing more about the data.

Profiling the traffic may tell more about the behvaiour of the request lifecycle, if an event is coming up can your client start streaming before the event is actually triggered?

I tend to have a large buffer throughout and keep it fairly large just in case this situation arises, I use more ram on both ends but the system expects it

...

Lots of guessing here

---
Tags: networking
---


title: Treat uninitialized values as 0

text:
# Question
Title: Treat uninitialized values as 0
Does Gamemaker have a way to treat uninitialized values as 0?

# Answer
> 1 votes
GameMaker has an option to turn on "Treat uninitialized variables as 0" in the error options. See the documentation here.

---
Tags: game-maker
---


# Question
Title: How can I draw multiple lines connected via "nodes" in libgdx Scene2D?
I have two Vectors which indicate the ending points of each line. I am trying to draw similar lines to football formation lines like these:

My main problem using ShapeRenderer is:

1. ShapeRenderer coordinates are relative to screen coordinates and not Scene/Table/Stack. This creates varying coordinate points in different screen sizes. Although I can fix it, I still experience get varying line width in different screen sizes.
2. ShapeRenderer performance issues as it is mainly intended for debugging.
3. ShapeRenderer draws over all Actors.

I have tried drawing the lines as a Pixmap and adding them to the scene as an image. This is part of the constructor to my custom class which extends Group.

```
pixmap = new Pixmap( 16, 16, Pixmap.Format.RGBA8888 );

    pixmap.setColor(Color.RED);
    pixmap.drawLine(Ax, Ay, Bx, By);
    Texture pixmaptex = new Texture(pixmap, Pixmap.Format.RGB888, false);
    Image pixmapimg = new Image(pixmaptex);
    pixmapimg.setPosition(x, y);
    this.addActor(new Image(pixmaptex));
    pixmap.dispose();

```

I am trying to draw using this but it just draws a square with the pixmap width and height at (0,0) of the stack. Which is the best class to extend to draw this lines? I am expecting to write a custom class if this doesn't work.

# Answer
> 1 votes
According to this post you can draw a rotated quad. The line texture could be a 1x1 colored pixel.

```
public static void drawLine(Batch batch, float x1, float y1, float x2, float y2, float lineWidth, TextureRegion lineTexture) {
  float xdif = x2-x1;
  float ydif = y2-y1;
  float l2 = xdif*xdif+ydif*ydif;
  float invl = (float)(1/Math.sqrt(l2));
  //dif is vector with length linewidth from first to second vertex
  xdif*=invl*lineWidth;
  ydif*=invl*lineWidth;

  float floatBits = batch.getColor().toFloatBits();
  //draw quad with width of linewidth*2 through (x1, y1) and (x2, y2)
  float[] verts = new float[]{x1+ydif, y1-xdif, floatBits, lineTexture.getU(), lineTexture.getV(),
                       x1-ydif, y1+xdif, floatBits, lineTexture.getU2(), lineTexture.getV(),
                       x2-ydif, y2+xdif, floatBits, lineTexture.getU2(), lineTexture.getV2(),
                       x2+ydif, y2-xdif, floatBits, lineTexture.getU(), lineTexture.getV2()};
  batch.draw(lineTexture, verts, 0, 20);
}

```

---
Tags: opengl, libgdx
---


# Question
Title: Why does my initial screen disappear quickly in my iOS build, in my Unity game?
I'm developing a game in Android and iOS platforms. I've an initial screen and I'm trying to get next menu scene after a delay of 4 seconds. It works ok in Android but in iPhone, the initial scene disappear in 1 second or less.

Can anyone help me?

This is my code (in C#) right now:

```
public class CargaPantallaInicio : MonoBehaviour {

    IEnumerator Start () {
        yield return new WaitForSeconds(4f);
        Application.LoadLevel("Menu");
    }
}

```

# Answer
Currently Unity on iOS starts while the splash screen is still visible. Your scripts are already started in the background.

You will just have to make your delay longer on iOS builds.

```
IEnumerator Start () {
#if UNITY_IOS
    yield return new WaitForSeconds(10f);
#else
    yield return new WaitForSeconds(4f);
#endif
    Application.LoadLevel("Menu");
}

```

It's not ideal as the timing may change in the future but it should work as long as Unity doesn't change the splash screen behaviour in an update and/or you don't update Unity.
> 1 votes

---
Tags: unity
---


# Question
Title: 2D Sprite batching in OpenGL: How to send transformation data to GPU
OpenGL newbie here.

So I'm trying to implement sprite batching to draw ~100 sprites per draw call. I've created a VBO that contains texture coordinates, vertex coordinates, color data (for tinting), and a mat4 matrix for transforms.

So far, so good, right? Well, everything is working but the transform portion of my VBO. My theory is that I could push a mat4 with all of the rotation, scaling, flipping, and world location data applied to it, so that it gets multiplied in with viewports (see glsl code below).

```
#version 130

//Vertex position attribute
in vec2 vertexPos;

//Texture coordinate attribute
in vec2 texCoordIn;
out vec2 texCoord;

// Vertex color
in vec4 textureColorIn;
out vec4 textureColor;

// Matrix transformations for the sprite
in mat4 transformation;

void main()
{
    //Process texCoord
    texCoord = texCoordIn;

    // Process texture color
    textureColor = textureColorIn;

    //Process vertex
    gl_Position =  gl_ProjectionMatrix * gl_ModelViewMatrix * vec4( vertexPos.x, vertexPos.y, 0.0, 1.0 ) * transformation;
}

```

So here's my question, if you were to send transform data to the GPU, how would you do it? Sending a mat4 over the wire per vertex seems like overkill.

# Answer
Transform them in software using the CPU and give the GPU only the final vertex coordinates.

The savings in bus bandwidth by reducing the VBO size will be greater than the cost of the transform on the CPU which can be greatly simplified by combining the sprite expansion and transform into a single step, no heavy matrix multiplication needed.

2D rotation, scaling, flipping only needs two 2D vectors: **up** and **right**.

```
vertex[0] = center + up - right;
vertex[1] = center - up - right;
vertex[2] = center - up + right;
vertex[3] = center + up + right;

```

**right** is equivalent to the first row of the 4x4 matrix you would have sent over to the GPU, **up** the 2nd row of the same matrix, **center** is the 3rd row (translation) of the 4x4 matrix

**up** and **right** are not normals, they are half-sizes vectors of the sprite's up direction (half height) and right direction (half width).
> 1 votes

---
Tags: opengl, 2d, sprites, optimization, vbo
---