title: How to tween to move an object in arc?

text:
# Question
Title: How to tween to move an object in arc?
Okay, so I think I need to use a tween in order to move an object in my game. I have some little green dudes that need to move in an arc (bezier) to a location that is clicked by the user. My game functions by having the mouse point raycast to the screen giving my character a position to move to. They don't just run though, they fire off their jetpacks and should travel in an arc to the target position. I'm pretty new to Unity but all I can come up with is using a tween to do this. Am I missing something? That being said, I'm totally confused on what a tween actually is. I can't wrap my head around how the object can be moved outside of an update function. I'm using the "free from the asset store" LeanTween package. I feel like there should be some sort of easier way to achieve the desired behavior.

How can I have my character move from Vector3 A to Vector3 B in an arc?

# Answer
I went ahead and made it since I think it could be useful for me in the future. This implementation uses ellipses to determine the object location. All you have to provide is the speed, height of the ellipse, and start and end locations.

Edit: I modified it to support slowing down near the end. It uses new decayStart and decayAmount variables. Both of these variable should be between 0 and 1. If you ever want it to slow down near the beginning as well you could do something similiar to this.

```
using UnityEngine;
using System;

public class Jetpack : MonoBehaviour {

    private JetPackPath path;
    private double speed = 1, height = 5, decayStart = .75, decayAmount = .25;
    private bool jetPackOn;

    private void FixedUpdate() {
        MoveWithJetPack();
    }

    private void Update() {
        GetJetPackOn();
    }

    private void MoveWithJetPack() {
        if (jetPackOn) {
            transform.position = path.GetPosition();
            if(path.IsFinished()) {
                transform.position = path.GetEndPosition();
                jetPackOn = false;
            }
        }
    }

    private void GetJetPackOn() {
        if(!jetPackOn && Input.GetMouseButtonDown(0)) {
            InitializeJetPackSequence();
        }
    }

    private void InitializeJetPackSequence() {
        Vector3 startPosition = transform.position;
        Vector3 endPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        path = new JetPackPath(startPosition, endPosition, speed, height, decayStart, decayAmount);
        jetPackOn = true;
    }
}

public class JetPackPath {
    private Vector3 startPosition, endPosition, distance;
    private double height, width;
    private double position, speed;
    private double decayAmount, decayStart, decayWindow;

    public JetPackPath(Vector3 startPosition, Vector3 endPosition, double speed, double height, double decayStart, double decayAmount) {
        this.startPosition = startPosition;
        this.endPosition = endPosition;
        this.speed = speed;
        this.height = height;
        this.decayStart = decayStart;
        this.decayAmount = decayAmount;
        distance = endPosition - startPosition;
        width = .5;
        decayWindow = 1 - decayStart;
    }

    public Vector3 GetPosition() {
        position += GetSpeed() * Time.fixedDeltaTime;
        return startPosition + new Vector3((float)GetXPosition(), (float)GetYPosition(), (float)GetZPosition());
    }

    public double GetSpeed() {
        if(position >= decayStart) {
            double decay = position - decayWindow;
            double proportion = decay / decayWindow;
            return speed - (proportion * speed * decayAmount);
        }
        return speed;
    }

    public Vector3 GetEndPosition() {
        return endPosition;
    }

    public bool IsFinished() {
        return position >= 1.0;
    }

    private double GetXPosition() {
        return position * distance.x;
    }

    private double GetYPosition() {
        double yOffset = distance.y * position;
        double yPosition = GetSquareRoot();
        if (double.IsNaN(yPosition)) yPosition = 0;
        return yPosition + yOffset;
    }

    private double GetZPosition() {
        return position * distance.z;
    }

    private double GetSquareRoot() {
        double fraction = Squared(position - width) / Squared(width);
        double toBeSquareRooted = (1 - fraction) * Squared(height);
        return Math.Sqrt(toBeSquareRooted);
    }

    private double Squared(double value) {
        return Math.Pow(value, 2);
    }
}

```
> 3 votes

---
Tags: unity, beziers, tweening
---


# Question
Title: Convert Flash game to work on Android devices
Is there any way to convert a `Flash games`(file with .swf extention) to work with android devices? I want the game to use Android device native controls like `sensor`, `accelerometer`, etc.

# Answer
> 7 votes
petr's answer assumes you already know how to deploy a Flash app on Android; maybe you already know that, but you don't mention it in your question so I want to point out that you can package a Flash .swf as an Android .apk using AIR.

Once you are actually deploying your in-development game as an Android app then you get to the higher level concerns of adapting your game logic to the new input devices.

# Answer
> 5 votes
You can convert a Flash game to run on an Android device if you package it up with Adobe AIR, with the Android SDK through terminal using -apk and you can script / code in the #import features that allow you to do some native control for the game. However, from personal experience ; I've made a couple AIR / Android games and the problem with AIR is that it doesn't handle very well. I say this that you won't be able to have an "hell-shooter" with 600 things going off on screen at once. AIR handles games decently such as Machinerium because it isn't GPU / CPU intensive. Anything above a simple point and click starts to chug.

AIR won't magically convert your game. You'll have to get your hands dirty, and change a lot of things around in AS3.

AIR though, is great for making quick prototypes for mobile games though. Just download Flash-develop and it comes with automatic AIR / Android projects.

# Answer
> 2 votes
I don't think it's possible in some "automatic" or even semi-automatic mode. The only way is to manually convert game logic into other platform. Quite possible it will be pretty strightforward process for logic part if both games use standard game loop structure. However draw, sound and input implementation can differ significantly between platforms.

# Answer
> 0 votes
At the time of this answer the only way of doing (I\`m aware of) will result in an iPhone game trough Stencyl http://www.stencyl.com/. In the game I converted from Flash to Android we had to do as Petr Abdulin suggested and we even created our company own engine. However you can wait until Stencyl launch their Android/Html5 publishing build.

If you stick with converting yourself, which isn\`t that difficult, I strongly recommend to pick andengine, CoronaSDK or other engine to help you, that will make your life easier.

Good luck!

# Answer
> 0 votes
Yes, you can convert swf to apk (Android), ipa (iOS) and bar (Rim) in a single pass. You *can* do it directly from the swf without having source (see here), but most of time you have to modify your program to handle portrait/lanscape, multitouch, et cetera.

# Answer
> 0 votes
As long as I understand it, You can convert an Actions script 2 .swf, if it is predefined for the size of a mobile device, so it would fit in the mobile screen. But if you have to use the mobile interaction like touch, slash, etc, You'll have to do it from scratch on action script 3.

# Answer
> 0 votes
It is absolutely not possible at the moment. The best results that I have seen are with Swiffy which is Google's conversion tool, but unfortunately it works only on small files, approx 1 MB which is not enough for most flash games.

The biggest challenge would be to automatically generate software buttons for touch screen from of flash game controls.

My advise is to leave it. There's no way around it. That's the best you can do at this point. Some say Chrome will drop Flash soon anyway...

---
Tags: android, flash
---


# Question
Title: Transformation by right vector using TransformPoint return an identical position
I think the following code should work. I'm trying to set the position of a GameObject where the pointer currently is, I mean, where the player is looking currently:

```
public void SetTransform (Transform callerTransform) {
   Debug.Log("original position: " + transform.position);
   Debug.Log("caller GameObject position: " + callerTransform.position);
   transform.position = callerTransform.TransformPoint(Vector3.right);
   Debug.Log("result position: " + transform.position);
}

```

Unfortunately it seems that TransformPoint is doing absolutely nothing as we can see on the logs. Vector3.right has been not change the position:

* original position: (0.0, 1.2, 1.0)
* caller GameObject position: (0.0, 1.0, 0.2)
* result position: (0.0, 1.0, 0.2)

I also have tried the following code with the same result:

```
GetComponent<RectTransform>().position = callerTransform.TransformPoint(Vector3.right);

```

But it seems senseless for me (callerTransform is not a RectTransform, gameObject.transform is a canvas).

# Answer
Unity doc says about `Transform.TransformPoint`:

> \[...\]Note that the returned position is affected by scale. \[...\]

And from the same doc, `Vector3.right` is just a:

> Shorthand for writing Vector3(1, 0, 0).

So `callerTransform.TransformPoint(Vector3.right);` does nothing because a transformation with a right vector would only affect the x-axis, but as long as it is affected by scale, it does nothing when your initial x value is 0, which is your case.

I suggest to try what the method doc suggests:

> \[...\]Use Transform.TransformDirection if you are dealing with direction vectors.\[...\]

For example, the following code is working:

```
// The new position will be nine times to the right of callerTransform.
Vector3 vectorPointingToTheRightOfCallerTransformInTheWorldSpace = callerTransform.TransformDirection(Vector3.right);
callerTransform.position = callerTransform.position + (vectorPointingToTheRightOfCallerTransformInTheWorldSpace * 9);

```
> 2 votes

---
Tags: transformation, unity
---


title: Collision Detection in Wander behaviour

text:
# Question
Title: Collision Detection in Wander behaviour
briefly, this is the overall look and feel of my game:  I have a player and I have an enemy in my map. i tried to learn collision from SaladRaider Youtube channel. collision using chasing method works fine but because of adding Chase and Wander behaviour i implement MSDN Sample on my project instead of the previous simple chasing method. everything works correctly except collision detection for my enemy. when the enemy collides with wall, it just stop at there. this is the code for my collision: the Collision function :

```
    public bool Collision(Vector2 pos, Obj obj)
    {
        Rectangle newArea = new Rectangle(area.X, area.Y, area.Width, area.Height);
        newArea.X += (int)pos.X;
        newArea.Y += (int)pos.Y;

        foreach (Obj o in Items.objList)
        {
            if (o.GetType() == obj.GetType() && o.solid)
                if (o.area.Intersects(newArea))
                    return true;
        }
        return false;
    }

```

and my Checking collision function for wander behaviour:

```
    public void WanderPushTo(float pix, float dir)  //pix is speed, dir is direction
    {
        float newX = (float)Math.Cos(dir);
        float newY = (float)Math.Sin(dir);
        newX *= pix;
        newY *= pix;

        if (!Collision(new Vector2(newX, newY), new Wall(Vector2.Zero)))
        {
            float MYnewX = (float)Math.Cos(dir);
            float MYnewY = (float)Math.Sin(dir);
            enemyPosition.X += pix * (float)MYnewX;
            enemyPosition.Y += pix * (float)MYnewY;
        }
        else if (enemyState == enemyAiState.Wander)
        {
            float MYnewX = (float)Math.Cos(-dir);
            float MYnewY = (float)Math.Sin(-dir);
            enemyPosition.X += pix * (float)MYnewX;
            enemyPosition.Y += pix * (float)MYnewY;
        }
    }

```

as you see, i just tried to make the direction as negative when it has a collision with wall ( and the reason is when my enemy was collides with wall, it just stop at that place and doesn't move. i added that "else if" to solve the issue. now it just trace the wall instead of stopping at that position). but unfortunately it just solve my issue when i collide with wall from up and down. it doesn't work when i collide with wall from left and right. to solve this issue, i think i have to turn the pix as negative instead of dir when my enemy collides with wall from left or right. but i don't know how i can check whether my enemy collides from left or right. (fyi, on chasing method, it works without any issue, because the direction is always on the player. but in wander, the direction is random. that's why it doesn't work) do you have any suggestion how to check whether the enemy collides from left or right of the wall ? this is my Chase and Wander Update function:

```
        public void UpdateEnemy(Vector2 playerPosition)
    {
        // First we have to use the current state to decide what the thresholds are
        // for changing state, as described in the doc.
        float enemyChaseThreshold = enemyChaseDistance;
        float enemyCaughtThreshold = enemyCaughtDistance;

        if (enemyState == enemyAiState.Wander)
        {
            enemyChaseThreshold -= enemyHysteresis / 2;
        }
        else if (enemyState == enemyAiState.Chasing)
        {
            enemyChaseThreshold += enemyHysteresis / 2;
            enemyCaughtThreshold -= enemyHysteresis / 2;
        }
        else if (enemyState == enemyAiState.Caught)
        {
            enemyCaughtThreshold += enemyHysteresis / 2;
        }

        float distanceFromPlayer = Vector2.Distance(enemyPosition, playerPosition);
        if (distanceFromPlayer > enemyChaseThreshold)
        {
            enemyState = enemyAiState.Wander;
        }
        else if (distanceFromPlayer > enemyCaughtThreshold)
        {
            enemyState = enemyAiState.Chasing;
        }
        else
        {
            enemyState = enemyAiState.Caught;
        }

        // Third, once we know what state we're in, act on that state.
        float currentEnemySpeed;
        if (enemyState == enemyAiState.Chasing)
        {
            ViewDirection = enemyOrientation = TurnToFace(enemyPosition, playerPosition, enemyOrientation,
                enemyTurnSpeed);
            currentEnemySpeed = MaxEnemySpeed;
        }
        else if (enemyState == enemyAiState.Wander)
        {
            Wander(enemyPosition, ref tankWanderDirection, ref enemyOrientation,
                enemyTurnSpeed);
            currentEnemySpeed = .25f * MaxEnemySpeed;
        }
        else
        {
            currentEnemySpeed = 0.0f;
        }

        WanderPushTo(currentEnemySpeed, enemyOrientation);
    }

```

and my Wander function :

```
        private void Wander(Vector2 position, ref Vector2 wanderDirection,
                        ref float orientation, float turnSpeed)
    {

        wanderDirection.X +=
            MathHelper.Lerp(-.25f, .25f, (float)random.NextDouble());
        wanderDirection.Y +=
            MathHelper.Lerp(-.25f, .25f, (float)random.NextDouble());

        if (wanderDirection != Vector2.Zero)
        {
            wanderDirection.Normalize();
        }

        orientation = TurnToFace(position, position + wanderDirection, orientation,
            .15f * turnSpeed);

        float distanceFromScreenCenter = Vector2.Distance(Game1.screenCenter, position);
        float MaxDistanceFromScreenCenter =
            Math.Min(Game1.screenCenter.Y, Game1.screenCenter.X);

        float normalizedDistance =
            distanceFromScreenCenter / MaxDistanceFromScreenCenter;

        float turnToCenterSpeed = .7f * normalizedDistance * normalizedDistance *
            turnSpeed;

        orientation = TurnToFace(position, Game1.screenCenter, orientation,
            turnToCenterSpeed);

        ViewDirection = orientation;

    }

```

# Answer
i've solved my problem. the answer is in a way that if Cos(dir) and Sin(dir) is positive, then we can apply collision detection from up and down, but if one of them is negative, then the can deduct the value from the actual position. this is the latest WanderPushTo() function:

```
    public void WanderPushTo(float pix, float dir)
    {
        float newX = (float)Math.Cos(dir);
        float newY = (float)Math.Sin(dir);
        newX *= pix;
        newY *= pix;

        if (!Collision(new Vector2(newX, newY), new Wall(Vector2.Zero)))
        {
            float MYnewX = (float)Math.Cos(dir);
            float MYnewY = (float)Math.Sin(dir);
            enemyPosition.X += pix * (float)MYnewX;
            enemyPosition.Y += pix * (float)MYnewY;
        }
        else if (enemyState == enemyAiState.Wander)
        {
            if ((float)Math.Cos(dir) >= 0 && (float)Math.Sin(dir) >= 0)
            {
                float MYnewX = (float)Math.Cos(-dir);
                float MYnewY = (float)Math.Sin(-dir);
                enemyPosition.X += pix * (float)MYnewX;
                enemyPosition.Y += pix * (float)MYnewY;
            }
            else
            {
                float MYnewX = (float)Math.Cos(-dir);
                float MYnewY = (float)Math.Sin(-dir);
                enemyPosition.X -= pix * (float)MYnewX;
                enemyPosition.Y -= pix * (float)MYnewY;
            }

        }
    }

```
> 0 votes

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


# Question
Title: Can I use sin or cos for the non uniform rotation in unity 5?
I have few objects which I have to rotate on an ellipsoidal track and speed is changeable at the run time because its a betting game in which racing will be done so speed values will come from the server and I have to handle run time speed as well as the rotation angle at the curved path within the track.

And I would like to clarify one thing that we don't have to give any output to the objects make run just as we play the game the objects start running till the end point without giving an input.

So how do I rotate the objects within the curved area according to change in speed at the run time?

# Answer
> 1 votes
Consider the function `sin(t)` this is a nice regular wave.

Now suppose you have some "speed function" `s(t)` which returns any value.

Now `sin(s(t))` has rate of change `s'(t)cos(s(t))`

If `s(t)=t` then we see the rate of change is a nice smooth regular `cos(t)`

---

If we take `s(t)=t^2` then the rate of change becomes `2t cos(t^2)` which as you can hopefully tell becomes "sharper".

I encourage you to experiment with such things in a spreadsheet and plot a graph.

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


# Question
Title: Do I have to resize and manually move the checkbox with a Unity Toggle?
I have a Toggle UI element (the stock one from Unity 5.2), and when I resize it to make the text legible, the checkbox doesn't resize or move:

Am I missing something, or is the control implementation incomplete?

# Answer
> 2 votes
You need to adjust the anchors of the Background and Checkmark GameObjects so they get resized when you resize the Toogle gameobject.

You can do it using the RectTransform component:

Click first in the upper left icon, then in the lower right one

---
Tags: unity
---


title: Tech Tree layouts for games?

text:
# Question
Title: Tech Tree layouts for games?
I'm trying to do a tech tree GUI for my game, but i have limited width and the tree has alot of branches, the problem is if I make them small to fit the width, the tech tree is too small to read.

For example the AOE one is very large (in width):

I could allow scroll bar but as its web based, scrolls are quite ugly. So i was wondering how to deal with branches which slowly cause the tech tree to get wider as you go down the tech tree and how you would fit such a design in a limited space.

Are there different known designs for tech trees that any one knows of so i can look at their types. I don't know the names given to the types of tech tree layouts. But am hoping to find one that is not overly complex for the user aswell.

# Answer
> 2 votes
You could use an indented tech tree, assuming you don't have too many layers. It is probably easier to show what I mean than it is to explain it. An excerpt from an example AoE2 tech tree below:

* **Barracks (I)**

+ Militia (I)
        - Man-at-Arms (II)
            * Long Swordsman (III)
                + Two-Handed Swordsman (IV)
                    - Champion (IV)
    + Spearman (II)
        - Pikeman (III)
            * Halberdier (IV)
    + Eagle Warrior (III)
        - Elite Eagle Warrior (IV)
    + *Tracking (II)*
    + *Squires (III)*
    + **Archery Range (II)**

    - Archer (II)
            * Crossbowman (III)
                + Arbalest (IV)
        - Skirmisher (II)
            * Elite Skirmisher (III)
        - Cavalry Archer (III)
            * Heavy Cav Archer (IV)
        - Hand Cannoneer (IV)
        - *Thumb Ring (III)*
        - *Parthian Tactics (IV)*
    + **Stable (II)**

    - Scout Cavalry (II)
            * Light Cavalry (III)
                + Hussar (IV)
        - Knight (III)
            * Cavalier (IV)
                + Paladin (IV)
        - Camel (III)
            * Heavy Camel (IV)
        - *Bloodlines (II)*
        - *Husbandry (III)*
* **Mining Camp (I)**

+ *Gold Mining (II)*
        - *Gold Shaft Mining (III)*
    + *Stone Mining (II)*
        - *Stone Shaft Mining (III)*
* **Lumber Camp (I)**

+ *Double-Bit Axe (II)*
        - *Bow Saw (III)*
            * *Two-Man Saw (IV)*

Of course, if you can code the tree so that it is possible to expand the list (eg have the technologies within the Mining Camp hidden unless expanded), and display detailed information (such as cost, time, etc. on mouse hover), you would be able to put even more information into a small space. The only problem with this design is that it still needs a scroll bar, but I have seen some working scroll bars online. Be aware that my knowledge of web coding is rather limited though, so I am afraid I can't help much on implementation.
I hope that helps.
Mmarss

# Answer
> 0 votes
You can use more then one picture ie. your agro advancements can be on one graph wile your writing advancements can be on another and when it gets to confusing to put on 1 graph split them up again

---
Tags: gui, graphics-design, user-experience
---


# Question
Title: Improve (adding randomness) minmax algorithm for Connect Four
I have implemented the minmax algorithm for the Connect Four game. It works well (almost...), but if the player does the same moves, the computer will do the same moves as well, for each match. There is no randomness in the computer choices. This is the code for the minmax:

```
private int[] minmax(int depth, Seed player) {
    // Generate possible next moves in a List of int[2] of {row, col}.
    List<int[]> nextMoves = generateMoves();

    // mySeed is maximizing; while oppSeed is minimizing
    int bestScore = (player == mySeed) ? Integer.MIN_VALUE : Integer.MAX_VALUE;
    int currentScore;
    int bestRow = -1;
    int bestCol = -1;

    if (nextMoves.isEmpty() || depth == 0) {
        // Gameover or depth reached, evaluate score
        bestScore = evaluate();
    } else {
        for (int[] move : nextMoves) {
            // Try this move for the current "player"
            cells[move[0]][move[1]].setContent(player);
            if (player == mySeed) { // mySeed (computer) is maximizing player
                currentScore = minmax(depth - 1, oppSeed)[0];
                if (currentScore > bestScore) {
                    bestScore = currentScore;
                    bestRow = move[0];
                    bestCol = move[1];
                }
            } else { // oppSeed is minimizing player
                currentScore = minmax(depth - 1, mySeed)[0];
                if (currentScore < bestScore) {
                    bestScore = currentScore;
                    bestRow = move[0];
                    bestCol = move[1];
                }
            }
            // Undo move
            cells[move[0]][move[1]].setContent(Seed.EMPTY);
        }
    }
    return new int[] { bestScore, bestRow, bestCol };
}

/**
 * Find all valid next moves. Return List of moves in int[2] of {row, col}
 * or empty list if gameover
 */
private List<int[]> generateMoves() {
    List<int[]> nextMoves = new ArrayList<int[]>(); // allocate List

    boolean[] columns = {false,false,false,false,false,false,false};

    // If gameover, i.e., no next move
    if (hasWon(mySeed) || hasWon(oppSeed)) {
        return nextMoves; // return empty list
    }

    // Search for possible moves and add to the List
    for(int row = GameMain.ROWS - 1; row >= 0; row--) {
        for(int col = 0; col < GameMain.COLS; col++) {
            if(columns[col] == false && cells[row][col].getContent() == Seed.EMPTY) {
                columns[col] = true;
                nextMoves.add(new int[] { row, col });
            }
        }
    }

    return nextMoves;
}

/**
 * The heuristic evaluation function for the current board
 *
 * Counts open 3 in a row for each player
 */
private int evaluate() {
    int score = 0;

    // very good move for computer
    if(hasWon(mySeed)) {
        return Integer.MAX_VALUE;
    }

    // very bad move, player wins!
    if(hasWon(oppSeed)) {
        return -Integer.MIN_VALUE;
    }

    // counts open 3 in a row for the computer and the player
    int myThree = openThree(mySeed);
    int oppThree = openThree(oppSeed);

    score = myThree - oppThree; // if negative, player advantage, otherwise computer advantage

    return score;
}

```

I have omitted the *openThree* method for brevity.

Bug: the computer skips his turn when is destined to lose.

Ps: the main code for minmax is taken from a tutorial.

This is a situation in which the computer skips his turn:

Red is the player, blue is the computer.

The computer does not freeze, he can continue to play, but not always. For example in this situation if i place my red circle over 15, the computer will skip his turn again, while if i place my red circle over 9, the computer will win placing his blue circle over this last one placed by me.

Project zip

# Answer
I'm not going to read your code but I will talk about how (old) electronic chess sets do it.

When they're searching for a move to play often they will choose **the** best move they've found, however for variation (which usually you don't want, but I play chess really quite well, a lesser player may get bored or something) you can put them in modes where they'll do something like:

* Choose a move with the same "score" as the one you just made (effectively balancing the game)
* Choose a random move from the best at most 4 moves found, provided those moves all have similar scores. (Say there are only 2 good moves, the rest = insta-loose, it'd be STUPID if by random chance it choose a stupid move)

Hope this helps.
> 2 votes

---
Tags: java, algorithm, ai
---


# Question
Title: Why do adventure game puzzles often have a single clue/solution?
When recently playing an adventure game (*Dreamfall Chapters*) it hit me that most adventure games I've played have had only a single solution to the "puzzles" they require you to solve. This frequently means a single clue the player has to "get" or they may be in for a long session of "brute force" combing through everything they can find in the game world. (I remember this happening to me several time in classics such as *Sam & Max Hit the Road*.)

In comparison, a frequently cited piece of advice for Game Masters that want the players to follow clues in a tabletop roleplaying game is the Rule of Three, which basically states that every conclusion should be supported by (at least) three clues that the players see. As a corollary, every "chokepoint" problem should have three ways to solve it.

Is there a game design reason for why a similar rule isn't necessary for video games? Or are single-solution puzzles just lazy design?

# Answer
Yes, it's lazy design. But you have to understand that, apart from laziness, time and budget constraints may play a factor in how in-depth a game's puzzle-solving is. Each solution needs to be developed, coded, and tested, and the more you add, the more you have to deal with. Witness how buggy today's games get and you'll have an idea.

There's also the notion that what may have been clear to the designer may not be clear to the player, and what they think is an easy puzzle may stump you for months. (F'rex, the "monkey wrench" puzzle in Monkey Island 2 relied on a pun that flew over the heads of a lot of non-English speakers.) Since the designer isn't there to clarify or give extra hints the way a GameMaster is, the amount of stonewalling due to a bad puzzle is even worse.

FWIW, not all adventure games were like this. Maniac Mansion, for example, had multiple solutions/endings based on who you chose and what they did in the mansion.
> 11 votes

# Answer
The rule of three sounds like good advice, but often times some of the funnest or best things go against practical advice and yet are still somehow fun or good.

For instance, many argue that you need to hand hold a player into a game with an intro sequence that orients the player to their abilities. Legend of Zelda for nes dropped you into a world without a sword and gave you no introduction whatsoever - you could even miss the cave to get the sword! - yet the lack of hand holding added to the sense of exploration.

Back to the adventure games, I feel like there is an element of humor to their way of doing things. Defining humor is hard but one type of humor makes a previously confusing thing very obvious. I remember in monkey island you had to get a head for a cannibal's soup. Couldn't figure it out and eventually realized (by random chance) you had to read the book "how to get ahead in navigation".

Basically, there are rules that are good guidelines, but some of the fun of games can come from breaking the rules, and I think that is part of the fun of those games that gave them their distinctive style.

Know what the rules are but know when to break them I guess (:
> 7 votes

# Answer
Another thing to consider is that every 'solution' has to be planned out, developed, and tested. With the world being as it is, time and money can drive a lot of decisions in development.

If you've given a player a puzzle and set up a solution, when you have 10 more puzzle-solution combinations to make are you going to get on to them or worry about making 3-5 other possible ways that the user could complete said puzzle?

Ideally yes, a user should be able to complete any one puzzle in any combination of ways that make sense, but sometimes the time constraints or the engine that the game runs on simply can't handle that.
> 0 votes

---
Tags: game-design, puzzle
---


# Question
Title: How do I add the "tween-engine-api" to my libGDX game?
I finished now my first game at LibGDX (I am using Eclipse). I run the game in the desktop launcher and it works. I now want to run my game on Android and iOS.

From some guides I have read, I understand that for running the game on devices I must have the tween-engine library in my project. I tried but couldn't add it to my project.

Can someone help me? (I already tried to do that at "add jars", but it only shows me my project and not the tween-engine library)

# Answer
Here's how I get the tween engine in all my games (assuming you're talking about Aurelien Ribon's Universal Tween Engine here: http://www.aurelienribon.com/blog/projects/universal-tween-engine/)

~~Create a new folder in the project root named **libs/** and copy the two tween engine api jars into this directory (*tween-engine-api.jar* and *tween-engine-api-sources.jar*)~~

Add the following line to the root level *build.gradle* in the '**dependencies**' sections in each of the following projects: **core**, **android**, and **ios**

~~compile fileTree(dir: "../libs", include: "\*.jar")~~

---

**Update April 2020**

Tween engine is now available from Maven central, so rather than copying the jars manually it should be possible to add the following to *build.gradle* rather than `compile fileTree(...)` as described above:

```
implementation "org.mini2Dx:universal-tween-engine:6.3.3"

```

<sub>(note that this uses the newer Gradle configuration `implementation` instead of `compile`, which is deprecated)</sub>

---

Finally, if you want the tween engine to work in the HTML build as well, you have to add the following line to both the *GdxDefinition.gwt.xml* and *GdxDefinitionSuperDev.gwt.xml* files in the **html** project (under html/src/com.things.stuff/):

```
<inherits name='aurelienribon.tweenengine' />

```

You'll probably have to do a gradle refresh after this to update everything in your IDE. This has worked for all my games using IntelliJ, and since it is all using gradle I imagine it would work just fine in Eclipse too.

Good luck!

Edit: Looks like you may also have to right-click those two tween engine api jars and choose 'Add to build path' in Eclipse (based on the answer here)
> 2 votes

---
Tags: libgdx
---


# Question
Title: How to load a spherical planet and its regions?
I'm designing a game partially composed of planets exploration. I want to use pseudo-random generation for them, regenerating from a defined seed when I have to load them rather than store every detail, which would be too heavy. So I will just store in a file the random seed and modifications done by the player if any.

The player must be able to see the planet from orbit (with very low level of details, then go down to the ground, increasing slowly the level of details of the region where he/she is landing, and unloading the ones on the other sides of the planet, which go outside the player's field of view.

If I had to do it on a plane ground, I would do it easily with a square chunk system. But the problem here is that planets are - almost - spheres.

So what would be the best way to load ground details (relief and grounded objects) around a precise point ?
I already though on two solutions, but both have a weak point:

### 1. Cutting the sphere in square chunks.

Once the player is close enough of the ground, I just have to improve details of closest squares from his/her position.
If it is not enough, I still can cut each square in sub-squares to load when the players is on or really close of the ground.

But as you can see on the picture, there is a problem if the player try to land on a pole: squares become very slim rectangles, or even triangles for the last line, and additionally to the fact that they would be many to load, generation would appear distorted.

### 2. Starting from an icosahedron.

Here, I could just increase triangle tessellation around player's position when he/she is getting close.

But I don't know how to locate triangles close than player's position. I heard Cartesian coordinates could be usefull in that case, but I don't know how to use them.

---

I'm using C++/OpenGL for it, so the main thing to generate and load here are vertices representing the surface relief and color/texture.

# Answer
Okay, so I wrote it out here:

http://www.maths.kisogo.com/index.php?title=Notes:Spherical\_coordinates

(I needed the math-markup and also it's really quite long)

---

## Applying the document

The document starts by introducing the notion of a manifold, a manifold is this thing where chunks of it are "homeomorphic" (basically: the same as) chunks of R^n (R^2 is the x/y plane, as you might know)

A chart covers some (possibly all, although in the case of a sphere it CANNOT cover all) of a manifold.

In the article I develop 4 charts for the sphere that preserve angles, that is they keep regular distance.

As you've found out giving coordinates to points on a sphere is actually quite difficult! What we do instead (although on a circle in the example) is give each point a coordinate of the form (i,x,y) where i is a number between 1 and 6 for a sphere, 1 and 4 for a circle. This is the chart number.

The x and y refer to the angles on that chart (or just x if it's a circle).

The 6 charts of a sphere are the top/bottom hemispheres, left/right and front/back hemispheres.

---

# Coordinates

Now you can give evey point a "nice" coordinate that is well behaved. In mathematical terms the domains of the charts are "open" maps, this means there exists some positive number such that a ball around each point is also in the set. For example the range (0,1) (the set that contains x if 0\< x\<1) is open, take any p in (0,1) (for example 0.001) then there is a number (for example 0.0005) such that any point within 0.0005 of 0.001 is also in (0,1).

What this means is you can pass directions through charts.

Now there is 45 degrees of overlap in the charts we develop. This means if you have a feature at coordinates (i,x,y) you can SAFELY specify points of the form (i,x+a,y+b) as long as `a` and `b` are between -45 and +45 (in degrees)

Any point of the form (i,x+a,y+b) can be easily transformed to a point in "normal" 3-dimensional space without problem.

---

## Implementation

You now have a way to store coordinates for something on a sphere, and denote regions large swaths of space with these coordinates, they also behave like coordinates, they're open for example (which is a problem if you use 2 angles instead)

You can also totally discard "how to create a regular sphere" answers now because all you have to do is do 6 planes, and make sure the edges of them align (which is trivial) and the result is:

**You'll have a nice sphere with easy to use coordinates**

Any questions please comment, I've tried to assume little prior knowledge. I'm also new to teaching people
> 5 votes

# Answer
As you've already shown, there are a number of solutions to this problem, but none 100% ideal. Spheres are tricky.

**Cube-based**

One common route, used by Spore and quite likely other games (though it's hard to tell for certain without peeking under the hood), is to project the sphere onto a cube, and use a square grid over each cube face.

(This is what Alec Teal and dnk drone.vs.drones are describing in the comments above)

(Image from this post which describes using a cubic representation for LoD)

This has a lot of the advantages of the latitude-longitude method, with much less peak distortion. It's easy to convert back-and-forth between positions on the face grid and positions on the sphere, by either normalizing a vector or dividing by its greatest component in absolute value. It also aligns nicely with cube mapping texturing techniques, which can be useful when viewing the whole planet from a distance.

The typical mapping approach is called gnomonic projection, and it still has a density mismatch problem as you can see in the image above. The grid is much more dense near the cube corners than at the centers of the faces. If uniformity is important, you can reduce this with the right mapping formulae, but this usually makes the mapping harder to reverse.

In all cases, you'll still have an angular distortion at the corners, where an ordinary grid intersection of four squares with 90-degree angles becomes a meeting of 3 rhombuses with 120-degree angles.

**Icosahedron-based**

My personal favourite aproach would be the icosahedral version that you described, because it makes the peak angular distortion as small as possible. Where the triangular grid would ordinarily have six triangles meeting at 60-degree angles, the icosahedron vertices have 5 triangles meeting at 72-degree angles. So each one has less distortion than the squares in the cube example.

It's not quite as familiar territory as the squares of the cube version, which is probably why it's not as popular. It takes a bit more math to work through.

Identifying nearby points isn't quite as tricky as it might appear though. Any icosahedron-based geodesic sphere can be flattened onto a regular triangular grid:

And a regular triangular grid can be treated like a square grid, as discussed here.

So once you determine which face of the icosahedron you're on (which can be done with a raycast against an icosahedral mesh - I don't know of any clever mathematical way to simplify that part), the surroundings can be filled in using familiar grid traversal. :)

**Edit:**

If you use a Class-I geodesic, you can unwrap your planets into five rectangular charts for storing level chunks/textures/heightmaps efficiently, similar to the six square charts you'd use for storing a cube-based version:

(This may help address the concern raised by Fuzzy Logic in another answer. This is also possible but a little more complicated for Class-II geodesics. I haven't investigated Class-III)

The trick is that the axes of these charts aren't really perpendicular in use, so existing authoring and streaming tools/tech won't support it out of the box. If you're planning on writing your own chunk streaming anyway or using on-the-fly procedural generation then that might not be an issue. You might also be able to work around the authoring problem by generating your source maps in higher resolution than you need using more conventional tools, then running them through a baking process that samples along the chart grid to build a dense, efficient representation that plugs directly into the icosahedral structure.
> 13 votes

# Answer
Quad-sphere with chunked LOD is the preferred method if you want to be able to go from space to ground with any level of detailed terrain, either procedural or predefined heightmapping and textures.

Icosasphere provides a more uniform mesh and is easy to tessellate but poses problems trying to map textures and heightmaps which you will need to cache and won't be very compact or simple that way.

Quad-sphere has pinch points but with enough tessellation you won't see them anyhow. Then you can map textures and implement DLOD effectively as if each region (chunk) is a square grid with little problem. This is simpler to implement compared to an icosasphere and will be more efficient, both in computation and resources.

See Sean O'Neil's articles about generating a procedural universe on Gamasutra:
\- Part 1 *Perlin Noise and Fractal Brownian Motion for heightmaps and textures.*
\- Part 2 *ROAM Algorithm for procedural mesh with DLOD for planet generation. **Suffers from performance problems.** Not recommended but good for educational value.*
\- Part 3 *Addresses problems with massive scale, optimization and floating point issues. Mainly related to universe scale but also applicable for planets when transitioning from scales of light years to centimetres if you want.*
\- Part 4 *Discusses implementation of Quad-sphere with chunked (quad-tree) DLOD for planet generation* **\<-- see this article in particular**
> 4 votes

# Answer
I'm no expert on programming, but you could have some sort of checkpoint. While you are cleared through a security checkpoint, with animation of course, the surface of the planet can load, and vice versa.
> 0 votes

---
Tags: opengl, c++, procedural-generation, optimization, sphere
---


# Question
Title: Unity 5 Dynamic Button Creation with Event Parameters
According to the documentation, you cannot instantiate buttons except via prefab instantiate.

http://docs.unity3d.com/Manual/HOWTO-UICreateFromScripting.html

> You might wonder why we don’t have a API methods to create the various types of controls, including visuals and everything. The reason is that there are an infinite number of way e.g. a button could be setup. Does it use an image, text, or both? Maybe even multiple images? What is the text font, color, font size, and alignment? What sprite or sprites should the image use? By letting you make a prefab and instantiate that, you can set it up exactly the way you want. And if you later want to change the look and feel of your UI you can just change the prefab and then it will be reflected in your UI, including the dynamically created UI.

What I'm trying to do is dynamically create a table of buttons, each one going to a level in my game. The amount of button depends on how many levels the user has unlocked.

I can create a prefab for a button, that's fine, but how do I go about assigning an OnClick event to each of these buttons with an appropriate 'levelIndex' parameter?

I can not find any scripting method to do this, and I'd like to avoid hacky solutions like creating 50 buttons and only showing the first N children.

# Answer
> 0 votes
After much pain I've found my answer.

It turns out there actually IS an API in the UnityEngine.UI namespace. I believe the documentation may have meant it doesn't have a way to create GUI elements with no reference to instantiate.

UnityEngine.UI.Button has everything I need, no need for a custom class mentioned in the previous answer which wouldn't have allowed me to change the text of the button anyway.

# Answer
> 2 votes
Atach a script like this in your button prefab

```
using UnityEngine;
using System.Collections;

public class ExampleClass : MonoBehaviour {

    public string levelName;

    void OnMouseDown() {
        Application.LoadLevel(levelName);
    }
}

```

after button instantiation, access to levelName property via script (you can also add a public method setLevelName..)

---
Tags: gui, events, unity
---


title: Soft Body Collision with Box2d (libGDX)

text:
# Question
Title: Soft Body Collision with Box2d (libGDX)
I've made a few classes to create soft body objects in libGDX using Box2D (specifically a circle and rectangle similar to these links).

The objects are constructed of a number of circle shaped Box2D bodies (hereafter deform points) connected together by distance joints which allow the object to "deform" when the deform points move around. Collision works more or less fine when the objects are colliding with other standard Box2D rigid bodies such as a box polygon (what they're sitting on):

The problem starts when two soft bodies collide. As you can probably guess from the way they're constructed, the two often pass through each other since the deform points for which Box2D handles collision are small and spaced apart, so they easily don't collide when the two soft bodies should. If the two bodies are placed like seen on the left in the following image, the circle passes through the square, rather than bouncing off the top of it as it should:

I've tried solving the problem (methods shown below) by tessellating the bodies more so that the deform points are closer together (left), which seems far too resource intensive and didn't affect much anyway. Then I tried enlarging the size of the deform points to fill the gaps (middle), which worked perfectly for the collision but as you can see caused problems mapping the texture to the object since the textures don't appear to collide. After that I tried to bound the outside of the object using polygon bodies connected between deform points using revolute joints, this works with the texture better and does prevent objects from falling through each other, but it stops the object from deforming properly.

I can't think of any more ways to tackle this problem, but I'm very new to Box2D and libGDX and maybe I'm overlooking a much more simple solution. I'll give any ideas a shot.

# Answer
> 0 votes
If the middle one works physically and the only problem is the mapping of the texture onto the deform points (and since the deform points don't account for the outer edge of the soft body), wouldn't it be possible to map the texture to points that are offset from the deform point by some value?

Try locking rotation of the deform points, you can do that by setting `fixedRotation` to `true` on the `BodyDefinition`, then for each deform point associate it with a `Vector2` that is the offset from the center of the deform point to the point where the texture will be mapped. Unless you're already using it you could potentially use the `setUserData` to store the offset vector on the deform point.

---
Tags: collision-detection, libgdx, box2d, soft-body-dynamics
---


# Question
Title: How can I change the anchor point of a Pyglet sprite?
while trying to make my game, I noticed that you can't change the anchor point of sprites in pyglet.
I use some convoluted way (see bottom of the post) to draw my minimap (WIP) so that the rooms are centered and lined-up correctly, however, I thought of the following occurrence.

I'll be using the mouse pointer to direct a 2D person from the top. However, if the anchor point of a sprite is the bottom-left corner of the original image, how can you make it feel as though the anchor point is in the middle of the sprite?

This may not be so important for the player, but it would be hell to algorithmically control the NPC's that fight.

Any help and input appreciated.

Code:

```
pic_img = image.load(imgPath)
picX, picY = window.width/2,window.height/2
pic = pyglet.sprite.Sprite(pic_img, x=picX, y=picY)
pic.rotation = roomType.ImageRotation

if pic.rotation == 0:
    picX = picX - pic.width / 2
    picY = picY - pic.height / 2
elif pic.rotation == 90:
    picX = picX - pic.width / 2
    picY = picY + pic.height / 2
elif pic.rotation == 180:
    picX = picX + pic.width / 2
    picY = picY + pic.height / 2

elif pic.rotation == 270 or pic.rotation == -90:
    picX = picX + pic.width / 2
    picY = picY - pic.height / 2
pic.x,pic.y = picX, picY

```

# Answer
Literally a few seconds after posting this I found the solution(Thought of it while typing actually)

after the loading of the image, but before assigning to the sprite, you change the anchor point for the image, which fixes the issue(if the width of your image is even, it works perfectly)

updated code:

```
        pic_img = image.load(imgPath)
        pic_img.anchor_x = pic_img.width // 2 ##this line is new
        pic_img.anchor_y = pic_img.height // 2 ## and this line also
        picX, picY = window.width/2,window.height/2
        pic = pyglet.sprite.Sprite(pic_img, x=picX, y=picY)
        pic.rotation = roomType.ImageRotation

```
> 4 votes

---
Tags: python, pyglet
---


# Question
Title: What organic traffic can I expect from publishing on Google Play, without other marketing?
I've just published a new Android game on Google Play. It has been a bit over 48 hours. It's active in the store, and I can search for it by name to get to it. However, I've had 0 organic downloads thus far, only a couple from my friends. As far as I know, it has not been shown in the "new games" list yet, and the only store listing views in the stats are the ones from myself and friends.

Is there some time by which I can expect some "organic" exposure, or will I ever? Is promoting my game by other channels the only option?

I'm not asking for advice on promoting my game. I'm only asking about what organic exposure I can expect on Google Play.

# Answer
Just throwing an app into an app store (however it is called on your platform) and waiting for people to download it is not enough to have a game take off. The usual user behavior is to either listen to recommendations from off-store resources (friends, websites, social media etc...) or just browse the top sellers and top-rated games in different categories. Some users will search by keywords, but will usually only look at the first few results, and result ranking also depends on number of downloads and rating. That means to attract new users through the app store you already need to have a large userbase.

A good presentation of your game in the app store can help (good screenshots, good descriptions, relevant keywords etc.), but it is very unlikely that you will get any downloads at all just by having it there.

When you want your game to be successful, you will have to promote it outside of the app store. Paid advertising is one option, but far from the only one. For details, check the question How can I promote my game?.
> 5 votes

---
Tags: android, marketing, publishing, google-play
---


# Question
Title: In unity, how do I rotate a vector in relation to the player?
I am making a radar script in a unity FPS game project I am making for class. I already have a working example of a radar script that works in relation to the player's position. However the rotation is in relation within the world map, not the player's view.

In code I have it kinda like this (not actually my code, as I don't have it with me right now, but basically the same algorithm)

```
if (isPlayerInViewRange(otherPlayer[i]){
    //these are both normalized Vector
    dir = getDirectionFromPosition(player, otherPlayer);
    dir = rotateDirectionInRelationshipToPlayer(player, dir); //problem here
    dir = new Vector3(dir.x, dir.z, 0);

    dir.Scale(MapToRadarPosition, 0, MapToRadarPosition);
    radarDot[i] = dir;
    radarDot[i].setActive(true);
} else {
    radarDot[i].setActive(false);
}

```

Any ideas what I am missing, I feel like I am missing some obvious function to do it.

# Answer
Use Transform.TransformDirection() method where Transform is your player transform.

```
// Calculate the x-axis relative to the camera
camera = Camera.main.transform;
cameraRelativeRight = camera.TransformDirection (Vector3.right);
// Apply a force relative to the camera's x-axis
rigidbody.AddForce (cameraRelativeRight * 10);

```
> 4 votes

---
Tags: unity, c#, rotation, vector, linear-algebra
---


# Question
Title: Synchronisation on a non authoritative networked peer to peer scene
I currently have a piece of coursework that requires 3 or more 3d simulations connected via p2p to maintain a simulation that is visually consistent amoung all peers. A big issue is that I'm not allowed to use any form of authoritative server/peer logic and I'm struggling with potential designs.

The coursework has the following relavant constraints

* each peer must be connected at the start and will have the same initial empty simulation
* The network will be LAN only
* Hardware is consistent in all computers in the network

I'm thinking about implementing it along the lines of

1. Each peer will regularly create a snapshot of all objects that have moved since the last snapshot
2. Each peer will maitain a local copy of the snapshot in addition to broadcasting it to all other peers
3. Each peer will combine the other snapshots possibly via averaging and and adding it to the current local state. I'm thinking I could also possibly use timestamps of each snapshot to weight the combination.
4. each peer runs their local simulation briefly then repeat the process

Can anybody see any potential problems with this or recommend anything?

# Answer
The key to large-scale synchronization is determinism. Basically, if you can plug X into a function and get the same Y on all computers, you can send X instead of Y.

For example the de facto RTS game sends commands rather than health, positions, rotations, etc. since syncing 500+ positions can use up quite a bit of bandwidth.

For example, the command "Units {6,13,15,19,102}: move to -\> (32,-7)" is sent. This command gets sent by the caster then received and interpreted on everyone's computer.

For something like a tower with balls falling through, you can send commands like "Ball 1: Apply velocity -\> (2,3)". Once the message reaches everyone, the velocity is applied. Things like gravity don't need to be synced - only information that not everybody has.

Note that this networking system, called Lockstep, is considerably more difficult to implement than simulating physics locally and sending out the resulting data. If you don't have too many simulation objects, you can simply simulate everything on 1 player's computer then distribute that information. I'm not too sure about "hashing" the game state but serializing everything in 1 neat package per sync frame will definitely work. Don't worry about averaging or anything - simply interpolate the data on everyone's computer except the guy producing it.

With a bit more work though and the same hardware, I think you can make Unity's PhysX produce the same output given the same input. From my tests, Box2D leans towards the arbitrary side even on the same platform.

---

Here's an example implementation I've been working on: https://www.youtube.com/watch?v=VvhKNWOML2c. If you need a cross-platform deterministic 2D physics engine, I might be able to help you with that.
> 1 votes

# Answer
JPtheK9 makes a good point about sending a command to move the objects in the simulation, but my 2 cents would be that I think you are on the right track.

So each time it runs, i will call that a step to make it easier, since it will send changes and save the snapshot after each step. As far as the design goes, this is how i would set it up to run.

Using what you wrote, it can be broken into a few processes on each simulation. This assumes the simulations have connected, so i will skip that part.

Create beginning snapshot \> If objects were randomly created, send snapshot to each sim \> simulation runs \> *while sim runs, run loop* (update snapshot \> send and receive snapshots \> update sim)

So basically, while the sim runs, either in between each step or as it receives changes, it will create a snapshot, send/receive, then update the sim. If you need to, set up a queue to collect all the commands, then run through it on each update. Hope this helps or gives you any other ideas to work with.
> 0 votes

# Answer
Try a hash of your entire "synchronized game state" instead of averaging data. There are some nice benefits to it, and is basically the standard for the RTS genre.
> -2 votes

---
Tags: networking, simulations, synchronization, peer-to-peer
---


# Question
Title: Embed a real city in a game and use data to find and display paths
First of all this question is gigantic but it's mainly about Unity, maps, pathfinding, and real data.

**The problem.**

In my game the player sees the map of a real city (in 2D), it’s exactly the same kind of view you have on Google Maps. The map is “almost” real, as I will probably have to modify some street names, point of interest, or exclude some streets. But the fact is that it’s based on a real “big” city (think of Paris, France or London, UK), with too many streets or roundabouts. The player knows where she is and can travel throught ways / streets in a car (no pedestrian ways, parks, forests... are useful here).

I need to display itineraries to the player. At some point she will be able to say “*I’m on Foobar street and I want to go on Blah street.*” and I must show her several possible itineraries (at least 3 when possible).

**The restrictions.**

* The game is made with Unity 5.X
* Game must be playable on Windows/Mac/Linux
* Game will probably, at some point, be playable on smartphones / tablets
* Being connected must not be mandatory
* More than 5 frames per seconds would be appreciated :)

**The tricky questions.**

* How to embed an entire “real” city in a game?
* How to compute itineraries?
* How to display the map?
* How to display the itineraries?

**What I have in mind so far.**

* *How to embed an entire city in a game?*

Using SQLite.

SQLite is a database made to be embedded with software. After some researches it happens that SQLite can be used with Unity, however I haven’t tested for portability on smartphones / tablets. SQLite database can be used with a scheme called SpatiaLite. This scheme is made to help users working with GIS to save all the information they need. Also as OpenStreetMap.org offers some city dumps I have access to the city I want and can import it all in SQLite. After that it’s all about making the right request to know where a specific street or a specific point of interest is.

* *How to compute itineraries?*

To be honest I still don’t know. I don’t know what SQLite can offer on this topic, but I’m sure someone, on the dark side of the Interwebz has already answered this.

Also, maybe a texture showing the "walkable ways" could be used alongside the database for pathfinding purpose. A simple A\* or Djikstra on it could do the trick...

* *How to display the map?*

2 options here. Either I generate meshes to draw EVERY streets of the map using SQLite data at runtime (meh… the CPU will burn), or I can use a tile system (it’s how map systems usually work). The trick with a tile system would be to be sure that the coordinate of the tiles match the coordinates of the information in the database. Tools like TileMill can export a set of tiles for different zoom levels.

* *How to display itineraries?*

So, let’s say that I find how to display the map correctly. Let’s admit that I find how to compute itineraries based on the database. And let’s say that everything works like a charm. I can’t figure the best solution to display itineraries… Generate meshes based on DB data points and display them directly on the map? Won’t it be overkill? I don’t know.

---

Well now you know has much as I do.

My question is simple: **how would YOU do it?** Forget the method I have in mind right now, if tomorrow someone would ask you to answer this problem, what solution would you go for?

THANKS A LOT in advance for your time and your help.

# Answer
> 1 votes
I think you have effectively 2 options to create all the roads/buildings : by hand (openstreetmap give you all the different waypoint coordinates), or download tiles directly from an api like a mapbox/osm server.

Apparently you want to have access to all the city, maybe you can use the bounding box from osm API

http://wiki.openstreetmap.org/wiki/Bounding\_Box http://wiki.openstreetmap.org/wiki/Xapi#Query\_Map

It gives you all the informations (positions of each buildings walls, waypoints, and a lot of informations) for an area given (and let s say for a city). You save all the differents buildings/roads in the database (why not), save only the informations needed. Now I think you need to cut this through tiles. For a tile you need somehow to take the right buildings/roads/...

Take in the db the right tile you want (and maybe the bordered tiles), And create it in 2d (here some polygon triangulation for the buildings (cutting ears algorythm or whatever), the buildings may be oriented clockwise or counterclockwise, you need to take caution of this when you will set the vertices point to unity. And some other triangulation for the roads). Load other tiles when you user quit the actual tile.

For itineraries, you saved all the waypoints roads, so you can use them as pathfinding waypoints with some A\*/Djikstra, I think that should do the trick, and when you compute the actual tile you need to save somewhere(in the information of a road waypoint for example) that this list of waypoint is an actual path to render it as you want in the world.

Hope my point of view helps.

---
Tags: unity, path-finding, tilemap, maps, databases
---


# Question
Title: Camera Rolling when Implementing Pitch and Yaw
I am implementing a camera in opengl for an android game and am having problems getting the pitch/yaw/roll of the camera correct. I have read many tutorials on quaternions and have implemented a basic camera based on this link.

Everything works well except for when I pitch and yaw I get unwanted roll. I have read things that say I need to apply the pitch/yaw rotation together to prevent this, and other things that said not to track individual changes to angles, but I'm not sure what they mean or how to extend this implementation to mine. I am new to this type of math so any help would be appreciated.

My goal is to have a camera that can rotate similar to how a space ship would rotate - I want the camera to be able to rotate 360 degrees in all directions and turn upside-down - which is why I was rotating the upVector too.

Any suggestions on what I can do to not have the camera roll when rotating around the y and y axes?

Thanks!

Here is the code that translates user input into two angles, and rotates the lookVector, upVector, and rightVector of the camera. My problem is the camera is also rolling when I just pitch and yaw.

```
// Java
// Camera uses a position vector, lookAt vector, and upVector
// eventually calls Matrix.setLookAtM()

Camera c = mRenderer.theCamera;

// PVector is a class that implements a 3 dimensional vector

float thetaX = getTouchChange(...); // set by the user touching the screen
float thetaY = getTouchChange(...); // set by the user touching the screen

// I keep 3 vectors in the camera class, one points up, one points right,
// and the 3rd is the point I am looking at

///////////////////////////////////////////////
// Pitch - rotate the up and look around right
///////////////////////////////////////////////
// get up and look vectors
PVector lookVector = PVector.sub(c.getLookAtPoint(), c.getLocation());
PVector otherVector = c.getUpDirection();
// get axis
PVector rAxis = c.getRightDirection();
rAxis.normalize();
// rotate look
PVector rotated = Quaternion.rotateVector(lookVector, rAxis, thetaY);
// Add back camera location to convert vector to actual look points
rotated.add(mRenderer.theCamera.getLocation());
c.setLookAtPoint(rotated);
// rotate up
rotated = Quaternion.rotateVector(otherVector, rAxis, thetaY);
rotated.normalize();
c.setUpDirection(rotated);

///////////////////////////////////////////////
// Yaw - rotate the look and right around up
///////////////////////////////////////////////
// get up and look vectors
lookVector = PVector.sub(c.getLookAtPoint(), c.getLocation());
otherVector = c.getRightDirection();
// get axis
rAxis = c.getUpDirection();
rAxis.normalize();
// rotate look
rotated = Quaternion.rotateVector(lookVector, rAxis, thetaX);
// Add back camera location to convert vector to actual look points
rotated.add(mRenderer.theCamera.getLocation());
c.setLookAtPoint(rotated);
// rotate right
rotated = Quaternion.rotateVector(otherVector, rAxis, thetaX);
rotated.normalize();
c.setRightDirection(rotated);

```

In my rendering code I update the camera orientation by calling the following

```
// called in onSurfaceChanged
Matrix.frustumM(m3DProjectionMatrix, 0, -screenRatio, screenRatio, -1, 1, 1, 70);

// called in onDrawFrame
Matrix.setLookAtM(m3DViewMatrix, 0,
    theCamera.getLocation().x, theCamera.getLocation().y, theCamera.getLocation().z,
    theCamera.getLookAtPoint().x, theCamera.getLookAtPoint().y, theCamera.getLookAtPoint().z,
    theCamera.getUpDirection().x, theCamera.getUpDirection().y, theCamera.getUpDirection().z);

Matrix.multiplyMM(m3DMVPMatrix, 0, m3DProjectionMatrix, 0, m3DViewMatrix, 0);

// m3DMVPMatrix is eventually passed to the shader along with the shape data

```

# Answer
*I am having the exact same problem with my openGL app in C#. I have been reading about it and some people have suggested that this is actually realistic.*

In the local frame of reference changing the x and y axis at the same time will also cause a z rotation. You can test this with a pen. Point it up in the air with the clip facing you. Rotate it so the point is facing you and the clip is pointing down. Then rotate it so the point is facing right and the clip still down. Then rotate it so the point is facing up. The clip is now facing right, that was a z rotation even though in the pens frame of reference you only performed x and y rotations.
> 2 votes

---
Tags: opengl, android, camera, quaternion
---


# Question
Title: Can I use PARSE for creating turned based Game?
I am working on creating a Turned - Based game similar to "Draw Something". I want to replace the Game Center feature with my own server using PARSE. Replace in terms of all game logic like Match making, Notifying Turns etc in PARSE Server. I have used PARSE to create app like similar to Instagram where user will have their account and they do stuff within. However I am wondering if I can put logic of match making in PARSE Server to get match for any of player. More of features of Game Center might needed to be build in PARSE Server.

Kindly let me know any suggestions if anyone has used PARSE as Game Server. Thanks in Advance.

# Answer
You can use PARSE for gaming. I made proof-of-concept a while ago for a tic-tac-toe game. Things like push notifications to notify change of turns and things like that all worked nicely. I stored the turn delta's in PARSE to keep the amount of data going back and forth to a minimum (keeping in mind that not everyone is on a 4G+ or Wifi network in a mobile environment).

The only downside may be a long term one, the amount of requests etc. may outgrow the 'free' model so keep that in mind in pricing your game. Design your game to keep requests etc at a minimum. On the other hand, this rings true for any application where you need a centralized server, as a centralized server (physical or virtual) usually costs money if traffic becomes numerous.
> 1 votes

---
Tags: game-design, ios, turn-based
---


title: Daily quest system

text:
# Question
Title: Daily quest system
I am creating a game for Android/iOS. The game has a server that communicates with my appengine database. I want to implement **daily quests** as motivation for the players to return every day, but I need some help on how create a smart solution for this.

So far this is my thought process:

1 - Randomly pick a quest from the DailyQuests table

```
DailyQuests
ID | Quest                |Goal
1  | Win 3 games in a row | 3
2  | Win 2 rounds of "ex" | 2
...

```

2 - Add entity "q\_progress" (maybe q\_ID) to a table storing user stats

3 - Display Quest and progress `userStats.q_progress / dailyQuests.goal`

4 - After a game (consisting of 5 rounds Bo5) is finished - Save the progress somehow. How do I keep track of consecutive wins? how do I save the progress if the quest has some specific requirement like "win 2 rounds of "ex""

Is the only way to do an `if-statement` for like quest-ID after each game is finished? Like:

```
if(q_id == 1){
    consecutiveWins += 1;
    userStats.saveProgress(consecutiveWins);
}
else if(q_id == 2){
    rockDodgerWins += 1
    userStats.saveProgress(rockDodgerWins);
}
...

```

I feel like this is highly unpractical and might not even work in practice if I really think about it, I only bring it up to maybe give a better view of where my head is at right now.

I don't need any code or anything like that, just someone who is smarter than me that might have experience with something similar or can think of a smart way to accomplish what I need.

# Answer
> 1 votes
You could make your list of if-statements much shorter by storing the game type id as well.

```
for (i = 0; i < quests.length; i++) {
  if (q_id == i) {
    wins += 1;
    // Save consecutive wins for a certain mini-game, i is the id and wins is the amount of wins
    userStats.saveProgress(i, wins);
  }
}

```

Basically, the code above loops through all game types and saves the wins. You should probably access `userStats` like `userStats.load(gameType);` and it should return the amount of wins.

# Answer
> 0 votes
if you just want to save the progress and keep track of it, i would assume you are storing the user stats in the database on the server. Take advantage of this, since if you store it in the database, in a separate table, you can store progress for everyone and reset it every day by clearing out the 1 table.

In the code you could use something like this:

```
if(goalUpdate){

// increment wins in database
userStats.saveProgress(1,q_id); // 1 isn't necessary, but useful for items

}

```

Then lets say for the saveProgress() function, you do something like:

```
// qId is just used to pass the current q_ID the player completed, i is optional
saveProgress(int i, var qId){ // var means whatever variable you need, or C# var

  if(qId = userData.q_ID){ // check if quest completed was for daily quest
    // if statement is only needed if you didn't check before now
    currentWins += i;
  }

saveUserData(); // save all or part of userData to store currentWins for q_ID

checkProgress(currentWins, qId); // check if goal is met, if so run function to complete

}

```

That will hopefully give you an idea how to handle it, but just remember when the game loads to initalize or load the userData with the Daily Quest variables. If you initialize it, that would be the best time to create a random Daily Quest for the player.

For clearing the database table, i would just setup something on the server to at a specific time every night to run a database script to clear the 1 table, so it is blank.

---
Tags: game-design, game-mechanics, logic
---


# Question
Title: Per pixel collision for scaled textures in Monogame Windows Phone 8
I have some serious trouble with pixel-collision in my game. I am using the Matrix Scale parameter in `Spritebatch.Begin` method, to scale the content for each device's resolution correctly.

```
SpriteBatch.Begin(
  SpriteSortMode.Deferred,
  null,
  null,
  null,
  null,
  null,
  Managers.ResolutionManager.ScaleMatrix );

```

I am using Per Pixel Collision detection, because I have transparent textures, and I want to make the exact collision between moving textures. On the resolution, that the game was initially, made for: **800 x 480** the per/pixel collision is working perfectly, but when I am testing on a real device, with resolution 1080 x 1920 (lumia 930) or on any bigger resolutions than the initial one, the per pixel collision doesn't work properly. I, as a player, can pass through moving textures without colliding, at the good point.

I have made the adjustments for moving texture's rectangles, if the game is playing on bigger resolutions, but still, any difference.

Here is my Per pixel collision function:

```
public bool CheckCollision(
  Rectangle rect1,
  Rectangle rect2,
  Color[] textureData1,
  Color[] textureData2)
{
  if (rect1.Intersects(rect2))
  {
    int top     = Math.Max(rect1.Top, rect2.Top);
    int bottom  = Math.Min(rect1.Bottom, rect2.Bottom);
    int left    = Math.Max(rect1.Left, rect2.Left);
    int right   = Math.Min(rect1.Right, rect2.Right);

    for (int y = top; y < bottom; y++)
    {
      for (int x = left; x < right; x++)
      {
        Color color1 = textureData1[(x - rect1.Left) + (y - rect1.Top) * rect1.Width];
        Color color2 = textureData2[(x - rect2.Left) + (y - rect2.Top) * rect2.Width];

        if (color1.A != 0 && color2.A != 0)
        {
          return true;
        }
      }
    }
  }
  return false;
}

```

Here are the rectangles, this player's rectangle

```
TextureData = new Color[(int)(
  Texture.Width *
  Managers.ResolutionManager.MatrixX *
  Texture.Height *
  Managers.ResolutionManager.MatrixY)];

Texture.GetData<Color>(
  0,
  new Rectangle(0, 0, frameWidth, frameHeight),
  TextureData,
  0,
  TextureData.Length);

Bound = new Rectangle(
  (int)((Position.X - frameWidth / 2) * Managers.ResolutionManager.MatrixX),
  (int)((Position.Y - frameHeight / 2) * Managers.ResolutionManager.MatrixY),
  (int)(frameWidth * scale * Managers.ResolutionManager.MatrixX),
  (int)(frameHeight * scale * Managers.ResolutionManager.MatrixY));

```

And this is obstacle's:

```
TextureData = new Color[(int)(
  Texture.Width *
  Managers.ResolutionManager.MatrixX *
  Texture.Height *
  Managers.ResolutionManager.MatrixY)];

Texture.GetData<Color>(TextureData, 0, TextureData.Length);

Bounds = new Rectangle(
  (int)(Position.X * Managers.ResolutionManager.MatrixX),
  (int)(Position.Y * Managers.ResolutionManager.MatrixY),
  (int)(Texture.Width * Managers.ResolutionManager.MatrixX),
  (int)(Texture.Height * Managers.ResolutionManager.MatrixY));

```

Basically, it is almost the same code.

In my opinion it has to be something in `CheckCollision` function, because I checked the collision only with rectangles and it worked.

I'm out of ideas; any solution?

# Answer
> 1 votes
The basic idea for resolution scaling, is that it only happens on the draw phase. Your internal logic should use the fixed resolution your game is designed for. So remove the resolution logic from your game logic- that should do the trick.

---
Tags: c#, xna, monogame, windows-phone-8
---


title: Image target display in unity Vuforia

text:
# Question
Title: Image target display in unity Vuforia
I am using unity 4.5.1f3 and using the Vuforia sdk 5.0.5.I have downloaded the sample project from the Vuforia site.When I tried to run the sample of Imagetarget project,it asked to add license key.Then I added licensed key to the app.Then when I runned the project again its showing me and error

```
MissingMethodException: Method not found:   'UnityEngine.Behaviour.get_isActiveAndEnabled'.
Vuforia.VuforiaAbstractBehaviour.UpdateStatePrivate (Boolean forceUpdate, Boolean reapplyOldState)
Vuforia.VuforiaAbstractBehaviour.Update ()

```

The Image marker detection can run but the camera video doesn't show in the background. can anybody help me solving the issue?

# Answer
> 1 votes
If you are running the x64 bit version of unity on a PC you will need to run the x86 version for your webcam to work correctly in the editor.

You may also have to set some of the plugin files to run x86 also for your project to run correctly.

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


title: Clip shadow frustum to scene bounds

text:
# Question
Title: Clip shadow frustum to scene bounds
I have a global light in my scene. It casts shadows using shadow mapping and has an associated camera (for rendering to the shadow map). I'm going to refer to it as my "shadow camera" from now on.

I need to find a way to place my shadow camera's near plane as close as possible to my scene's bounding box (clip it to the scene bounds).
I need to do this so the shadow casters are never clipped by the shadow camera's near plane (otherwise I'd get holes inside of shadows) and to make sure I don't accidentally cull any shadow casters behind the camera. This would also allow me to increase the shadow mapping precision, because it lets me move the near and far planes closer together.

**Example 1 (possible to do using a simple plane check):**

**Example 2 (NOT possible to do using a simple plane check):**

* The black box is the scene's AABB (but it would be nice if this would work for OBBs or other shapes too).
* The yellow arrow represents the light direction.
* The green box is the shadow camera's frustum without any modifications.
* The red box is my desired result.

At the moment I'm constructing the red box by projecting the black box onto the global light's direction vector and use the closest vertex's distance to compute the shadow camera's near plane. But this makes it impossible to get something as seen in the 2nd image. Instead the red box starts above the scene's AABB.
I have thought of using SAT for this, but it doesn't seem to be the solution.

# Answer
This is how I'd do it:

1. Generate convex hull from all planes
    * Note: this includes both light frustum and scene AABB planes, so there should be a total of 12 planes
    * Note: make sure all planes have matching orientation (normal outwards or inwards - doesn't matter much but it has to be consistent across all data and functions)
    * Intersect every three planes (all possible combinations) to try and get an intersection point
        + One way: plane\[1\]/plane\[2\] -\> ray; ray/plane\[3\] -\> point
        + ...but you might be able to find better algorithms for this, for example...
    * Remove those generated points that are not in the hull (they're behind any of the planes)
2. Project hull on axes to generate OBB
    * this is just dot(point,axis) for a list of 6 axes (or if you need just the near plane, then 1 axis) and all hull points
> 2 votes

# Answer
Here's the approach I ended up implementing:

1. Generate the regular shadow camera frustum (the green box from my question) and only extract the four side planes (up, down, left, right). I only use the four side planes because I want to offset the near and far planes.
2. Convert the scene bounding volume into a triangle mesh (if it's an AABB =\> 12 triangles, but it works with any kind of mesh).
3. Iterate through all triangles and for each:
    * **A**: Iterate through all planes and for each:
        1. Check if the triangle and plane intersect. If they do, calculate the line segment on the triangle that is formed by the cut. If the triangle and plane don't intersect, continue with the next plane.
        2. Iterate through all the remaining planes (start with the first one again), but skip the plane that produced the triangle cut (because it's redundant and leads to numerical precision errors). Each additional line segment vs plane check will either:
            + shorten the line segment (the plane intersects the line segment, and we only care about the segment in front of the plane)
            + not do anything (the line segment is in front of the plane =\> contininue with the next plane)
            + discard the line segment (the line segment is completely behind the plane =\> go back to **A** and continue with the next plane).
        3. Now you have the shortest line segment. Use it to reposition the near and far planes (using the signed distance between the plane and the end points). I use two offsets (one for the near plane, one for the far plane) which are continuously updated using the shortest line segments. After the algorithm finished, I add the offsets to the near and far planes.

---

If you render all the line segments produced by the algorithm, you should end up with something like this (The green lines are the line segments created by the algorithm. The shadow map camera encompasses the main camera frustum and the four side planes pass through the green lines.):

There might be some possible optimizations and simplifications and I'd gladly hear about them.
> 1 votes

---
Tags: collision-detection, shadow-mapping, frustum, frustum-culling
---


# Question
Title: Libgdx RotateToAction does not directly rotate between 179 and -179
It took me a bit of debugging to realize why I'm having trouble with my rotations and it seems that rather than just moving the 2 degrees between 179 and -179, it prefers to rotate all the way in the other direction, the full 358 degrees.

Is there any way to make it go the short way in this case?

Code I have so far:

```
public void rotateTo(float targetRotation)
    {
        RotateToAction rotateToAction = new RotateToAction();
        rotateToAction.setRotation(targetRotation);
        rotateToAction.setDuration(2f);
        if(Math.abs(this.getRotation()-targetRotation) > 180)
        {
        /*failed attempt to force rotation*/
            SequenceAction sequenceAction = new SequenceAction();
            RotateToAction rotateToAction2 = new RotateToAction();
            rotateToAction2.setRotation(180);
            rotateToAction2.setDuration(1f);
            sequenceAction.addAction(rotateToAction2);
             sequenceAction.addAction(rotateToAction);
            this.addAction(sequenceAction);
        }
        else
        {
            this.addAction(rotateToAction);
        }
}

```

# Answer
> 1 votes
I'm not sure exactly how the code works and this obviously won't work if any methods require an angle between -180 and 180 degrees, but rather than setting the target rotation to -179, could you instead set it to 181 degrees? To my (very limited) understanding that is the same angle as -179 degrees.

# Answer
> 0 votes
I have never used this library but a google search later I came up with following:

```
RotateToAction rotateToAction2 = new RotateToAction();
rotateToAction2.setReverse(true);
rotateToAction2.setRotation(180);
rotateToAction2.setDuration(1f);

```

I hope this works :)

# Answer
> 0 votes
I ended up creating my own action using the RotateToAction source code as a template.

Essentially just added any of the code involving the number 360 ;)

```
public class DirectRotateAction extends TemporalAction
{
    private float start, end;

    protected void begin()
    {
        start = (this.getActor().getRotation()+360)%360;
        if (start - end > 180) end += 360;
        if (end - start > 180) start += 360;
    }

    protected void update(float percent)
    {
        this.getActor().setRotation((start+(end-start)*percent)%360);
    }

    public float getRotation() {
        return end;
    }

    public void setRotation(float rotation) {
        this.end = (rotation+360)%360;
    }
}

```

---
Tags: libgdx, rotation
---


# Question
Title: Can I have a fixed-angle sprite with a non-fixed-angle CircleCollider2D?
In Unity2D, can I have a fixed-angle sprite with a non-fixed-angle CircleCollider2D?

I would like to move my character using the circle physics (without fixed-angle), but display him always as if he wasn't rotated (as if he had fixed-angle).

I thought I could just let the collider rotate, and then rotate-back the sprite in the `LateUpdate`, however since the collider's center isn't `0,0`, it "rotates sideway" and doesn't end up in the "original" position.

My knowledge on matrices and quaterions is null, and trigonometry is only slightly above zero, so I'm a bit at a loss... how can I achieve the desired effect?

---

In order to prevent a X/Y problem, I want to do that since with box colliders sometimes the characters got stuck: if a platform had even just 1 pixel step, the character couldn't walk over it. Also, slopes were a big problem. Changing the collider to a Circle was the obvious consequence; I also tried to detect and add a small vertical speed but it didn't work very well and was becoming a mess.

# Answer
Maybe you can just turn off the SpriteRenderer script so only your invisible collider still there and rotating, then make a new separate Sprite game object just for displaying the character. (Make sure this separate sprite is not a child of your collider or they will still rotate together.) Then attach a script that keep updating Sprite's transform.position to the same of your rotating collider.
> 1 votes

# Answer
I\`ve created script to set each frame rotation on SpriteRenderer to zero. Works for me.

```
public class YourObject: MonoBehaviour
{

    public SpriteRenderer spriteRenderer;

    void Awake()
    {
        spriteRenderer = GetComponent<SpriteRenderer>();
    }

    private void Update()
    {
        spriteRenderer.transform.rotation = Quaternion.identity;
    }

}

```
> 0 votes

---
Tags: unity, rotation, physics, platformer
---


# Question
Title: How to find resources location regardless of working directory?
I am working on a resources loader for my personal C++/OpenGL ES engine. My resources are in a `resources` folder separated trough different sub-folders (`shaders`, `textures`, etc).

I am currently giving a path to this folder when I want to load a file. My code looks like this:

```
texture.load("../../resources/textures/dirt.png");

```

The problem is - in addition to not be gracious - it depends of the current working directory and of the final binary location when I execute it.

How can I store the complete path to the resource when I call the `load` function to be able to load it regardless of working directory? I would like to be able to use the following line:

```
resourcesManager.loadTexture("dirt.png");

```

Regardless of where I am compiling nor executing my game, as long as I told to the texture manager where is the resources folder.

---

I tried to find a solution using `__FILE__` macro, because I can get the complete path to the compiling file with it, but it would be the path to the source file, not the path to the binary.

I'm trying to make it cross-plateform, so I would prefer a solution not working through an external editor or IDE.

# Answer
You can create a separate variable called `dataPath` which gets initialized on applications launch and stores your data/resources path root. If you plan that resources can be located in different locations - just pick the right one and store it. What you get in `dataPath` is, for example:

> C:\Program Files\MyGameStudio\MyGame\bin\
>
> sdcard\0\game\game\resources\

or just anything else.

After that it is simple `resourcesManager.loadTexture(dataPath + "textures/dirt.png");`.
> 3 votes

# Answer
In C++, you can get the path of the binary with the `argv[0]` parameter that is passed to the `main()` function.

You will need to define `main()` as...

```
int main(int argc, char* argv[])

```

You will want to store `argv[0]` somewhere, so you can reference it outside of `main()`.

Then you can prepend it to your relative paths to build the full path to your resources.
> 1 votes

---
Tags: c++, architecture, assets
---


title: Shader value remap - Blend Falloff

text:
# Question
Title: Shader value remap - Blend Falloff
I would like to know if there's a way to remap a value that goes from 0 to 1 constantly like this.

Into those values (those are examples).

This might be some function transformation but I can't find the way to do that. I've tried using a lookup texture but in my opinion this is not the best solution.
Thank you very much.

# Answer
As @dari said, the **smoothstep** function is the best solution to achieve what I need.
> 1 votes

# Answer
Okay so what you have is something like `f(t)=(colour from gradient)` as `t` goes from `0` to `1`

This gives a nice smooth gradient, Where as if you take an auxiliary function, say `a(t)=t^2` you'll notice this also goes between 0 and 1 (as `t` goes from `0` to `1` but it starts much slower then gets much faster.

You can compose the two, by using `f(a(t))` this "alters the speed" that `t` changes if you will.

---

If `f(t)` has gradient `1` (uniformly, as the gradient increases at a constant rate, it must be 1 to go from the far ends of the colour gradient over a time of "1")

then `f(a(t))` has gradient `a'(t)f'(a(t))` which if `a(t):=t^2` gives a rate of change of:
`2t` which at `t=0.25` has gradient `0.5` (half the rate of change of the "normal" gradient) and at `t=0.75` it has a gradient of `1.5` which is 50% faster than the usual one.

Using different `a(t)` you can get different effects

(someone else was asking about altering rates of change earlier, Can I use sin or cos for the non uniform rotation in unity 5? but for some reason I got a comment-less downvote, this is a similar question right?)

---

## !!!CAUTION!!!

Take a function like:

```
f(t) = { 5t              if 0<= t < 0.1
       { 0.5+5(t-0.1)/9  if 0.1 <= t <= 1

```

This will have a shape like:

```
1                  1
|             ___/ |
|        ____/     |
|   ____/          |
|  /               |
| /                |
|/                 |
+------------------+
0                  1

```

It'll rise really sharply as we go from 0 to 0.1 then increase slowly to 1.

If we differentiate this we get:

```
f'(t) = { 5    if 0<= t < 0.1
        { 5/9  if 0.1 <= t <= 1

```

Which has a graph something like this:

```
|
|   _________
|
|___
|
+------------

```

Notice the jump, it is NOT continuous, which will be apparent in the result.

Don't fret though, there are plenty of "smooth" functions to choose from!
> 2 votes

---
Tags: opengl, shaders, directx, glsl, hlsl
---


title: Creating a GUI Countdown Timer Unity5

text:
# Question
Title: Creating a GUI Countdown Timer Unity5
This was originally posted as a follow-up comment to https://stackoverflow.com/questions/30714357/guitext-in-unity-5-need-an-alternative , but I'm asking it here as a dedicated question as per the community's recommendation.

**What I'm trying to do:** display GUI Text on screen as a countdown timer that counts down in real time

**What I've done so far:**

* watched YouTube tutorial: "Unity Scripting Tutorial 7 - A Countdown Timer" by VR Enthusiast.
* GameObject --\> UI --\> Text --\> renamed: TimerText
* Wrote the Timer script in C#

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

 public class Timer : MonoBehaviour

public float seconds = 59;
public float minutes = 0;

void Update() {

    if (seconds <= 0) {

        seconds = 59;
        if (minutes > 1) {

            minutes--;

        } else {

            minutes = 0;
            seconds = 0;
            GameObject.GetComponent<GUIText>().text = minutes.ToString("f0") + ":0" + seconds.ToString("f0");

        }

    } else {

        seconds -= Time.deltaTime;

    }

    if(Mathf.Round(seconds) <= 9) {

        GameObject.GetComponent<GUIText>().text = minutes.ToString("f0") + ":0" + seconds.ToString("f0");

    } else {

        GameObject.GetComponent<GUIText>().text = minutes.ToString("f0") + ":" + seconds.ToString("f0");

    }

}

```

}
* placed the TimerText object in the GUI Text object reference

Then I got this error:

```
"MissingComponentException: There is no 'GUIText' attached to the "TimerText" game object, but a script is trying to access it. You probably need to add a GUIText to the game object "TimerText". Or your script needs to check if the component is attached before using it. Timer.Update () (at Assets/Timer.cs:40)"

```

I essentially placed The object GUI Text object itself (TimerText) as its own scripting reference in Unity's Inspector. Not sure where to go from here. Any advice on what I can do next? Any help would be appreciated.

# Answer
There are basically two ways to access the GUIText.

One way would be a public reference in the class or, like you already did, *GetComponent*.

The advantage of using a public reference is, that you do not have to attach the timer on the **GameObject** with the **GUIText** component. You just declare the variable like so:

```
public class Timer : MonoBehaviour
{
    public GUIText timerText;

    ...
}

```

You can then replace all GetComponent calls with timerText. To set this variable, simply drag and drop the GameObject that contains the GUIText component onto the **Timer Text** field in the Editor.

The *GetComponent* method, requires you, that the **Timer** script is attached to the same **GameObject** that contains the **GUIText**, *or* it is called on a **GameObject** on which has **GUIText** attached. It is also recommended, to use *GetComponent* just once, in the *Start* function of your **Timer** class, and store it in a variable.
> 2 votes

---
Tags: gui, unity, timer
---


# Question
Title: Is it bad practice to for the server to request data for a client from another client?
I'm making a collaborative whiteboard app so that when someone is drawing and uses a rectangle for example, a rectangle packet is sent to the server with parameters like `x, y, width, height, color` and then that packet is sent to everyone else in the room so that a rectangle is drawn on their screen.

So far everything works perfectly and there's also a stack on each client of all the commands thus far for infinite undo and redo. However, there server does not contain this stack because all it has to do is forward commands to clients in the room.

Everything is working perfectly so far and everyone can see everyone else drawing in real time but I'd like to implement a feature where if someone joins a room late they can see the current whiteboard. That is, the entire command stack would have to be sent to someone. However, this data isn't stored on the server, but each client has their own (identical copy).

Would it be bad for when someone joined to have the server ask one of the clients (which? round-robin?) to send his command stack to the server and have the server forward it to the client? My concerns are the delay and teh amount of data being sent in one go (congestion).

What do you all think? Are there any other options?

# Answer
Unfortunately, there is a flaw in what you're suggesting.

If ClientA starts the session, does stuff, then gets disconnected for any reason, then ClientB joins the session, who's going to send the stack to ClientB?

You should store the stack on the server and send it to the clients as they join. This will have also the advantage of preventing around with messing with the stack.

And you'll probably eventually filter out commands on the server for any reason. So you should keep you server as 'the authority'.
> 1 votes

---
Tags: javascript, client-server, node.js, websocket, packet
---


# Question
Title: Local avoidance together with any-angle types of A* Pathfinding
Recently I have been implementing the Block A\* any-angle path-finding algorithm in a project I have, for which I need extremely efficient results due to the large number of NPCs. However, I still do not know exactly how to handle the problem of local avoidance between the NPCs moving at the same time in the same scene.

So, my question is this: what is the best method to implement local avoidance with any-angle path-finding? Just testing for LOS and steering to the tangent of the predicted encounter is a good enough solution or should a specific AI implementation be included within the pathfinding routine?

I would highly appreciate references (academical or not) with state-of-the-art implementations of local avoidance for me to explore the most recent developments in that field.

Many thanks.

# Answer
I have no academical references but when I faced this problem I integrated local avoidance AI into my path finding.

Assuming that from your path finding you have a "next point to bee reached" call it NEXT, in the ai while reaching NEXT cast one or more short rais forward of your NPC :

If its blocked by another NPC chose a near point left or right (so that NEXT is still "visible"), reache the near point then procede to NEXT. You can also decelarate/stop for a random time waiting for less traffic.
> 1 votes

---
Tags: unity, c#, ai, path-finding, steering-behaviors
---