# Question
Title: What's the difference between variables defined with and without the 'var' keyword?
I've been making my way through several tutorials on GameMaker: Studio at this point, and I've been trying to keep track of various aspects of the code used in them. One thing, however, confused me.

I have noticed that it's possible to define new variables in GM:S either with or without using the `var` keyword. I'm aware that you can use the `var` keyword to define multiple variables in one line, for example `var xx, yy;` (and, of course, defining null variables), but other than that, is there a particular reason why some variables don't need to use `var`? Is it all to do with functionality, or what? When, in that case, should I use `var` other than the example provided?

# Answer
Variables declared with the `var` keyword are local variables, whereas variables declared without `var` are instance variables. More information on scope: https://yoyogames.com/tech\_blog/41
> 5 votes

# Answer
If you say `var test = 0`, it is a local variable, and will be deleted at the end of the event.

If you say `test = 0`, it will be stored in that object until the game ends, or the object is deleted.

If you say `globalvar test = 0`, it will be stored until the game ends, and will not be deleted with the object. It can also be accessed in another object without typing `otherObject.test`.
> 0 votes

---
Tags: game-maker
---


# Question
Title: Why my images always change color when I use glDrawPixels?
I am doing a exercise for the college, where I need load a file 'ppm' but any picture does not load with correct colors. I tried change parameter of glDrawPixels, glBlendFunc, but nothing change for the correct colors. And some changes makes window do not show the picture. I don't know I need to do.

```
int CALLBACK WinMain(
__in  HINSTANCE hInstance,
__in  HINSTANCE hPrevInstance,
__in  LPSTR lpCmdLine,
__in  int nCmdShow )
{
    if (!glfwInit()) return -1;

    window = glfwCreateWindow(WIDTH, HEIGHT, "ParallaxGame", NULL, NULL);
    if (!window)
    {
        glfwTerminate();
        return -1;
    }

    glfwMakeContextCurrent(window);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluOrtho2D(0.0, WIDTH, HEIGHT, 0.0);
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();

    while (!glfwWindowShouldClose(window) && glfwGetKey(window, GLFW_KEY_ESCAPE) != GLFW_PRESS)
    {
       glEnable(GL_BLEND);
       glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
       functionTemp();

       glfwSwapBuffers(window);
       glfwPollEvents();
    }

    glfwTerminate();
    return 0;
}

void functionTemp() {
    vector<Image*> chars;
    base->load("sully.ppm");

    for (int y = base->getHeight() - 256; y >= 0; y -= 256) {
        for (int x = 0; x < base->getWidth(); x += 256) {
            Image *c = new Image(256, 256, 4); // width, height and channel
            base->cut(c, x, y);
            chars.push_back(c);
        }
    }

    for (int i = 0; i < chars.capacity(); i++)
    {
         glDrawPixels(256, 256, GL_BGRA_EXT, GL_UNSIGNED_BYTE, chars[i]->getPixels());
    }

}

```

Images:

Someone can help me please?

# Answer
Your images have a different color channel order than you are specifying to OpenGL. In the call to `glDrawPixels()`, you're passing `GL_BGRA_EXT` as the format. You should try `GL_RGBA` instead. Or at least, that's what I would try first. Swapping the channels in a photo editing app, it almost seems like blue is fine, but red and green are swapped. However, that would be extremely odd. I know of no file formats that accept something like GBR or GRB as pixel orders.

Is it possible your input image is CMYK? It almost seems like the channel order is reversed, and the pixel values are reversed. It would certainly explain the white vs. black background.
> 1 votes

---
Tags: opengl, c++, glfw
---


# Question
Title: Unity2D: How to save volume of audio source when game is restarted?
How do I save volume of my audio source (clicking the mute button) when game is restarted. You see I have one scene in my game and once the player dies there is a button the user can click on that resets the game, however it also resets the audio source, so when I play the game and click my mute button, the audio source volume is at 0 but when I die and click the reply button (the restart/reset button) the music is restarted as well, instead of staying muted (save the current volume). I tried using DontDestroyOnLoad(this) but my muted script is attached to my game over panel animation (the panel comes down when player dies) making the my game over panel animation not being destroyed when you restart the game. I tried other methods like putting my mute button script on a parent empty object and putting the object that has the audio source on under it as a child but it did the same thing. Anyway this is my mute button script:

```
private bool mute;

public void Muted ()
{
    mute = !mute;
    if (mute){
        gameObject.GetComponent<AudioSource>().volume = 0;
    }else
    {
        gameObject.GetComponent<AudioSource>().volume = 1;
    }
  }
}

```

And this is my restart level when button is pressed (p.s. I used the OnClick method activating methods):

```
public void NavigateTo(int scene)
{
    Application.LoadLevel ("Game Level");
}

```

Thank you in advance :)

# Answer
Adjusting the volume of the background music (or muting it altogether) is a typical player preference. As such, it should be saved in the PlayerPrefs class. PlayerPrefs is a key/value store. It allows you to store and retrieve variables (int, float or string) under string-keys of your choice. It uses a platform-appropriate persistent storage method, so it doesn't just survive scene reloads but also closing and relaunching the whole game application.

To use the player preference in your audio source, add a script to it which checks if a preference exists and if so apply it in the `Start` method. When you change the music volume, also change the corresponding value in PlayerPrefs:

```
void Start() {
    // check if the player has a music volume preference
    if (PlayerPrefs.HasKey("musicVolume")) {
        // if yes, apply it.
        GetComponent<AudioSource>().volume = PlayerPrefs.GetFloat("musicVolume");
    }
}

private bool mute;

public void ToggleMute ()
{
    AudioSource audioSource = gameObject.GetComponent<AudioSource>();

    mute = !mute;
    if (mute){
        audioSource.volume = 0.0f;
    }else
    {
        audioSource.volume = 1.0f;
    }

    // write new music volume preference to persistent storage
    PlayerPrefs.SetFloat("musicVolume", audioSource.volume);

  }
}

```
> 1 votes

# Answer
Instead of setting the volume of the AudioSource, you can play around with its mute field.

```
public bool mute{
        set{
            PlayerPrefs.SetFloat("muted", value ? 1 : 0);
        }
        get{
            return PlayerPrefs.GetFloat("muted", 0) == 0 ? false : true;
        }
}

```

So in your Muted method, you could just have 2 lines of code

```
mute = !mute;
    gameObject.GetComponent<AudioSource>().mute = mute;

```

But when you reset the level, you will lose the settings. So you want to set the mute value in Start or Awake as well

```
 gameObject.GetComponent<AudioSource>().mute = mute;

```

This will be a better option that setting the volume because you could have values in between 0 and 1 as well. By your method, you could only have no volume or maximum value.
> 0 votes

---
Tags: unity
---


title: Unity 5 - Occlusion culling at runtime

text:
# Question
Title: Unity 5 - Occlusion culling at runtime
I am creating a game in Unity where the game is rendered while playing. The game is made in a voxel style, and has thousands upon thousands of objects rendered while playing. Of course, this causes a huge amount of lag. Therefor I need to use occlusion culling, to make sure only the objects needed are rendered.

For occlusion culling, you need to bake the area, but I'm planning on creating a huge world. So, any tips on how I could do this?

# Answer
> 2 votes
Ok, so, voxels. Are you using a game object for *each* voxel? If so, there's your problem.

Minecraft (and clones) don't actually hold an object in memory that represents each individual block. They have an object that *describes* the block and then an array of IDs--usually integers, aka Block IDs (Stone is 1, dirt is 3, water is 9...)--used tor represent which block is in each location (and then a lot of lookups are performed). From there it computes a single mesh for an entire chunk based on visible sides (this is why X-ray cheats work). That way your entire render distance out to 160 meters is made up of only 441 actual objects (for the ground) each with 16k verts (depending).

This is a *much* easier problem to solve when it comes to occlusion culling. Namely: is it in front of the camera...or behind? And basically say "fsk it" about the underground spaces because the savings are slim.

---
Tags: unity, 3d, procedural-generation, voxels, occlusion
---


# Question
Title: Translating object from y to y smoothly in Unity 2D
I am trying to make a game that has an object on screen, which moves from one Y coordinate to another. Right now, I do it through translations, but that does it instantly. I want to do this as a kind of animation, where it transitions smoothly from one Y coordinate to another. What should I do?

Here is an image of what I'm talking about:

# Answer
> 2 votes
### `Vector3.Lerp`

What you want to be using is the `Vector3.Lerp` method1. Let's take a look at the Unity API.

> **Vector3.Lerp**
> `public static Vector3 Lerp(Vector3 a, Vector3 b, float t);`
> **Description**
> Linearly interpolates between two vectors.
> Interpolates between the vectors a and b by the interpolant t. The parameter t is clamped to the range \[0, 1\]. This is most commonly used to find a point some fraction of the way along a line between two endpoints (e.g. to move an object gradually between those points).
> When t = 0 returns a. When t = 1 returns b. When t = 0.5 returns the point midway between a and b.

---

### Using `Vector3.Lerp` for a transition

You will want to play around with the method, to reach the transition effect you desire. An example of its use, as you describe, is as follows:

```
// We need to know where we are going.
// Since you work that out, elsewhere, we do not need to go into how.
public Vector3 targetPostion;

public void Update()
{
    Vector3 currentPosition = gameObject.Transform.position;
    Vector3 newPosition = Vector3.Lerp(currentPosition, targetPosition, 0.2);

    gameObject.Transform.position = newPosition;
}

```

---

### Using `Vector3.Lerp` for a *smooth* transition

In the above example, we are transitioning towards the new position by 20%, per update. This is a good start, and useful to understand how the method works. Keep in mind that for smooth transition, you will want to account for the delta time; a smoother transition would look something like this:

```
public void SmootherTransition()
{
    Vector3 currentPosition = gameObject.Transform.position;
    Vector3 transition = 0.2 * Time.deltaTime;
    Vector3 newPosition = Vector3.Lerp(currentPosition, targetPosition, transition);

    gameObject.Transform.position = newPosition;
}

```

---

### Further Consideration

As stated, you will want to play around with the method, in order to reach the desired functionality.

As an example, you will initially find that the translation distance gets smaller, with each iteration. This is because each iteration sets a new `currentPosition`, which is naturally closer to the `targetPosition` than during the previous iteration. As a result, your working out the same fraction from a smaller distance, which in turn is itself a smaller distance. This becomes especially noticeable towards the end, where the object will appear to vibrate, as its movement distance becomes exponentially smaller and smaller. Simply checking for a minimum distance, and translating the object directly to the `targetPosition` if it is not outside of the minimum distance, should fix this problem.

---

1 You describe a 2D game, but since your game objects will still be using Vector3 positions by default, using `Vector3.Lerp` is more efficient. If you *are* in fact using Vector2 positions, you should be able to apply the exact same logic to `Vector2.Lerp`.

# Answer
> 1 votes
You have to move the object in every frame a bit until it is at its destination.

```
void Update()
{
    if (hasToMove)
    {
        if (transform.position.y - targetY > 0.1f)
            transform.position.y += 10.0f * Time.deltaTime;
        else
        {
            transform.position.y = targetY;
            hasToMove = false;
        }
}

```

You set `hasToMove` to `true` when you want the move to appear and `targetY` to your target. The script also assumes the script is attached to the moving object itself.

You can play a bit with the threshold`0.1f` and the speed `10.0f` until it fits your needs.

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


# Question
Title: Having trouble writing a controller class
Okay so I'm writing a controller class to expand the SFML joystick library capabilities. Since the different controllers I want to use for this game have different integer values mapped to different buttons, I want to be able to pass integer values to the class to map these values to buttons I have defined. As well, SFML can detect whether a button is pressed with `sf::Joystick::isButtonPressed(unsigned int joystick, unsigned int button)`. However, this only detects if a button is *currently pressed* and thus holding the button will just register as repeated presses. So I wrote my own code to detect for a button press without a hold.

So here's the issue: What is the proper way for the player (outside the class) to access the set of buttons without exposing data? I could have getters for the buttons, but then the `buttonPressed` method couldn't change the value of `held`. The only way I could see this working is if I gave full access to the `Button`'s. Or should I go about this a different way? Any help would be greatly appreciated. Here's the relevant code:

```
// Controller.h

class Controller
{
public:
    struct Button
    {
        unsigned int id;
        bool held;
    };

    // constructor which assigns a controller ID
    // and a set of buttons
    Controller(...);

    // Checks each frame for each button if
    // any are not held and sets held to false
    void update();

    bool buttonPressed(Button& button);
private:
    unsigned int controllerId_;
    Button A_, B_, X_, Y_, Z_, R_, L_,
    START_, D_PAD_UP_, D_PAD_LEFT_, D_PAD_DOWN_, D_PAD_RIGHT_;
};

```

---

```
// Controller.cpp

bool Controller::buttonPressed(Button& button)
{
    if (sf::Joystick::isButtonPressed(controllerId_, button.id) && !button.held)
    {
        button.held = true;
        return true;
    }
    else
    {
        return false;
    }
}

```

# Answer
I think the way to go here is let the player access the "virtual" key names, and ask for their current state. You would introduce an enum or a set of constants that map your `Button` instances to names that can be accessed. Something like the following would do the job:

```
enum class ButtonName
{
    A, B, X, Y, Z, R, L, START, D_PAD_UP, D_PAD_DOWN, D_PAD_LEFT, D_PAD_RIGHT
};

```

Now, instead of named members, your `Controller` class should store a map (or an array, if the enum values are continuous) that maps the button names to their `Button` representations. So replace your members with `std::map<ButtonName, Button> buttonMappings;`. Now, for initialization, you can either provide an utility method `Controller::MapKey(ButtonName, unsigned int buttonID);`, or perhaps just pass in an `std::map` to the constructor of the `Controller` instance.

Now, the part where the player accesses becomes really nice to the code that needs to check for controller button presses. You can simply call `if (controller.IsButtonPressed(ButtonName::D_PAD_UP)) { ... }`. The implementation for `IsButtonPressed` then simply looks up the `Button` value for the correct name. So something like the following:

```
bool Controller::IsButtonPressed(ButtonName name)
{
    Button& button = buttonMappings.at(name);

    if (sf::Joystick::isButtonPressed(controllerId_, button.id) && !button.held)
    {
        button.held = true;
        return true;
    }
    else
    {
        return false;
    }
}

```
> 2 votes

---
Tags: c++, sfml
---


# Question
Title: 2D simulating light sources (subtract a texture from an other)
I want to simulate a night and day cycle with SFML (plain 2D, no shadows). What I want is to get a smooth transition from day to night, and during night having some lights "on".

So the approach I've thought is adding a black layer on top and change its transparency with time, that gives the effect I'm looking for. For adding lights I can crop out circles out of that layer

```
sf::CircleShape lightCircle(200);
lightCircle.setFillColor(sf::Color(255, 255, 255, 1));

sf::RenderTexture renderTexture;
renderTexture.create(/* view size */);

while (window.isOpen()) {
  // ...

  // update light
  renderTexture.clear(sf::Color::Black);
  renderTexture.draw(lightCircle, sf::BlendNone);
  renderTexture.display();

  // draw
  window.clear();
  window.draw(sf::Sprite(renderTexture.getTexture()));
  window.display();
}

```

Now, what I would like to do is use my own image instead of a CircleShape. Say a circle or a cone with fading borders, some more realistic than just a circle. Like

I have tried with sf::Image and createMaskFromColor but I'm not able to handle the fading edges.

How can I get that?

Am I in the right path or is there a simpler approach?

# Answer
> 1 votes
The trick is defining a custom blend mode that substract the alpha pattern of the image from the render target

```
sf::BlendMode blendMode(
    sf::BlendMode::Factor::Zero,              // color src
    sf::BlendMode::Factor::DstColor,          // color dst
    sf::BlendMode::Equation::Add,             // color eq
    sf::BlendMode::Factor::Zero,              // alpha src
    sf::BlendMode::Factor::OneMinusSrcAlpha,  // alpha dst
    sf::BlendMode::Equation::Add);            // alpha eq

```

There might be a more straight forward way of doing this, but this one does the trick.

The code looks something like this

```
sf::RenderTexture renderTexture;
renderTexture.create(/* view size */);

sf::Texture lightTexture;
if (!lightTexture.loadFromFile("light.png")) {
return 1;
}
sf::Sprite light0(lightTexture);
sf::Sprite light1(lightTexture);

while (window.isOpen()) {
  // ...

  // update light
  renderTexture.clear();
  renderTexture.draw(light0, blendMode);
  renderTexture.draw(light1, blendMode);
  renderTexture.display();
  sf::Sprite night(renderTexture.getTexture());

  float luminosity = 200.0f;
  night.setColor(sf::Color(10.0f, 10.0f, 10.0f, luminosity));

  // draw
  window.clear();
  window.draw(background);
  window.draw(night);
  window.display();
}

```

---
Tags: c++, sfml
---


# Question
Title: How do I detect if two 3D box shapes are overlapping each other?
I'm creating a Unity game, and for my building system inside the game, I need to detect if 2 3d box shapes are overlapping each other. What I'm doing this for is, lets say I'm building a wall, I need to detect if its overlapping another wall, or another specified shape. There will be a UI that turns red or green depending on whether its overlapping another shape. I researched a little, and I came across SphereOverlap, but it is not accurate enough for my needs.

I'm talking about a 3D context, not 2D.

Code examples(in c# preferred) would be appreciated. Thanks!

# Answer
> 2 votes
I don't agree that this duplicates the linked question, because that one is about the 2D case. Although the method is similar in 3D, I think it's distinct enough to merit its own answer.

Samuel Ng's answer will work great if both objects have colliders attached.

However, there may be situations where you don't want the virtual wall-to-be-placed cursor to have a collider of its own, even a trigger. (For example, you might find it's setting off unrelated OnTriggerEnter methods elsewhere in your scene, and your layer setup may not make it easy to filter those out)

For a situation like this, you can use Physics.OverlapBox (or, for performance, Physics.OverlapBoxNonAlloc). These methods give you a list of colliders in your scene overlapping a 3D box with the position, size, and orientation you specify.

You can then reject the wall placement if that list is non-empty, or filter the list in more detail to ignore minor objects that shouldn't block wall placement.

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


# Question
Title: How to run code as an instance you just created in GML
Alright, I'm looking how to create an instance, and then run a chunk of code on the instance I just created, and not have that code run on any other duplicate instances.

Noob question, I know. Please help though?

# Answer
There are many ways. For example:

```
with instance_create(posx, posy, obj_enemy)
{
    direction = choose(0, 90, 180, 270);
    speed = 4;
}

```

Or you may separate creation and code:

```
var obj = instance_create(posx, posy, obj_enemy);
...
with obj
{
    direction = choose(0, 90, 180, 270);
    speed = 4;
}

```
> 1 votes

---
Tags: game-maker
---


# Question
Title: How to place text centered on the player? XNA
As I can make a text of the size of this, it is centered taking reference of the player?

Right now the following happens:

I want:

code:

```
spriteBatch.DrawString(Font, player.Name, new Vector2(player.position.X, player.position.Y - 12), Color.White);

```

PS: Sorry for my English.

# Answer
SpriteFont.MeasureString() returns

> The height and width, in pixels, of text, when it is rendered.

As such, positioning the text at the center.x - half text width should center the text:

```
float xOffset = player.position.X + (player.width / 2) -
(Font.MeasureString(player.Name).X / 2);

spriteBatch.DrawString(Font, player.Name, new Vector2(xOffset,
player.position.Y - 12), Color.White);

```
> 1 votes

---
Tags: c#, vector
---


title: 2D Push Forward/Sprinting effect?

text:
# Question
Title: 2D Push Forward/Sprinting effect?
A few weeks ago i watched a video and found a really cool 2d push forward/sprinting effect which looks like the following :

How this is made ? Is this effect included into the animation or just spawned as randomly sized dust clouds ? And how this would work ? Is there any pseudo code ?

# Answer
> 0 votes
Its difficult to see what you mean by 'effect' with a still image. I'll assume you mean the smoke effect.

If so.. Have a particle effect which takes random parameters for movement, fade out (alpha), scale and lifespan. When your character is sprinting, spawn a smoke effect at the characters coordinate using random parameters for movement, fade and lifespan. Sometimes lifespan may be determined by alpha ( when its fully faded out it dies)

---
Tags: animation
---


# Question
Title: Unity2D: wait for coroutine to finish to activate it again
is there a way to start another coroutine once the last coroutine is finish. I have a button that activates a coroutine, the button can be pressed any time you want, when pressed you activate a coroutine. However I notice that when you press the button twice the coroutine happens twice, which is not want I want. Is there a way to make sure that once my Boomerangeffect(coroutine) is activate the coroutine can't start (if button is pressed) until the present coroutine is finished.

```
public GameObject BoomerangOn, BoomerangOff;
public static int buttonCount = 4;
static int timesActivated =  0;

void Start()
{
    if (PlayerPrefs.HasKey ("boomerangbutton")) {
        buttonCount = PlayerPrefs.GetInt ("boomerangbutton");
    }
}

void Update()
{
    PlayerPrefs.SetInt("boomerangbutton", buttonCount);
}

public void Activated ()
{
    if(timesActivated < buttonCount)
    {
        timesActivated++;
        StartCoroutine(BoomerangEffect());
    }
}

IEnumerator BoomerangEffect()
{

        BoomerangOn.SetActive (true);
        yield return null;
        yield return new WaitForSeconds (10.0f);
        yield return null;
        BoomerangOn.SetActive (false);
        yield return null;
        BoomerangOff.SetActive (true);
        yield return null;
        yield return new WaitForSeconds (1f);
        yield return null;
        BoomerangOff.SetActive (false);
        yield return null;
}

```

# Answer
> 4 votes
**StartCoroutine** returns a reference to Couroutine object. Assign it then you can simply check if that reference is null or not, if its null, start couroutine, and when the coroutine ends, set it back to null.

```
Coroutine boomerangEffectCoroutine;
public void Activated ()
{
    if(timesActivated < buttonCount)
    {
        timesActivated++;
        if(boomerangEffectCoroutine  == null)
             boomerangEffectCoroutine = StartCoroutine(BoomerangEffect());
    }
}
IEnumerator BoomerangEffect()
{
    // your stuffs
    boomerangEffectCoroutine = null;
}

```

# Answer
> 0 votes
Just have a `bool` variable keeping track whether or not the coroutine has been started. The routine can only be called if this variable is `false`. When the coroutine is started, set the variable to `true`, when it is finished set it back to `false`.

Could look something like this:

```
...
private bool coroutineRunning = false;
...
public void Activated ()
{
    if(timesActivated < buttonCount && !coroutineRunning)
    {
        timesActivated++;
        StartCoroutine(BoomerangEffect());
    }
}

IEnumerator BoomerangEffect()
{
    coroutineRunning = true;
    BoomerangOn.SetActive (true);
    ...
    BoomerangOff.SetActive (false);
    yield return null;
    coroutineRunning = false;
}

```

---
Tags: unity
---


# Question
Title: Unity Controller to Make Reticle Orbit based on the right stick input
d platformer arena like game. Right now I have it so a reticle moves around the player based on a controller's right stick's horizontal movement using the rotate around function and while it works great on keyboard on it is funky on controllers since you have to hold it left to rotate counter clockwise and right to make it rotate clockwise. I've been working on changing this for well over a month and a half. I've tried coding it myself and then googling it like crazy but I came up with nothing. the input they give you based on vertical and horizontal is what perplexes me the most. in the debugger comes up like this from a debug.log when tilting it up- "H: 0.02528, V: -.9874454". Which makes sense but when going to the top right it looks like "H: 0.7592, V: -.842965". That's the part that confuses me. I can't find a way to use this data in any of the functions I have experience with and experimenting with new ones has gone nowhere. Any suggestions or ideas would help me greatly and would be even more appreciated!

Based on the above image I want my reticle to be placed in a spot on it's orbit around a player's center based on the right stick's position on the controller. So if I completely titled up my stick the reticle goes up but if I release it stays there. Then if I tilt it to the left bottom corner it will "teleport" there without moving along the orbit. So think of old school twin stick shooters where you can aim instantly in the direction of your choice.

This is my old code that used rotate around that slowly makes the reticle orbit as you hold the stick constantly left or right. I added a new axis called AV which is for vertical instead of just horizontal so now I just need a way to use these together somehow.

```
void AimControllers()
{
    if (currentControllerAimAxisH != null)
    {
        AH = Input.GetAxis (currentControllerAimAxisH);
        if (Mathf.Abs (AH) > stickTol)
        {
              reticle.transform.RotateAround(this.transform.position,new Vector3(0,0,-AH),orbitAngle);
        }
    }
}

```

# Answer
> 1 votes
I figured it out. I was going about it all wrong. It's not perfect due to how unity handles analog sticks but here's the code.

```
void AimControllers ()
{
    if (currentControllerAimAxisV != null && currentControllerAimAxisH != null)
    {
        AV = Input.GetAxis (currentControllerAimAxisV);
        AH = Input.GetAxis (currentControllerAimAxisH);

        //first make sure both stick vals are higher than the tolerance
        if((Mathf.Abs (AH) > stickTol || Mathf.Abs (AV) > stickTol))
        {

            //now check if both together are greater than one (1) so either one stick
            //is at max or both are close to the minimum tolerance
            if ((Mathf.Abs (AH) + Mathf.Abs (AV)) > 1)
            {
                reticle.transform.localPosition = new Vector3 (AH * aimScale, -1 * AV * aimScale, 0);
            }

        }
    }
}

```

The green shape is how the aiming will work not the black circle because the stick stays at 1 too long even when not directly up so it creates a flat area when on stick is at 1. That's another reason why my other attempts failed. I also didn't need the orbit function at all. I just needed to set the values at what the axis gives me and negate Y since it's inverted then scale it so it can be as close as to the max range when it's not entirely there but at least at a minimum max value of when the stick is diagonal.

---
Tags: unity, input, controllers, orbit, rotate
---


title: Maze algorithm with field counter

text:
# Question
Title: Maze algorithm with field counter
I am new to algorithms but currently creating a little game with the need for some.

I have a 2d grid/board with a start and a finish field. Between those two fields are several platforms which can be entered. Each platform has a counter on it. When going on a platform the counter is decreased by one. If the counter reaches zero the platform is gone. The goal is to go to the finish field AND destroy every platform field. A little exmaple:

```
0 1 0
1 2 1
1 0 F
S 0 0
```

S being the Start field and F being the finish field the right path would be going UP, UP, RIGHT, UP, DOWN, RIGHT, DOWN.

All I could find so far were algorithms getting paths for mazes without counter. Do you have any tips for a algorithm that can decide, if the current maze if solvable or not and maybe even get the correct path?

Thanks in advance!

# Answer
> 1 votes
One way would be to auto generate the maze by coding your own 'maze generation bot'. This would have the nice advantage of being quicker as you would not having to do them manualy. As well as knowing that it would always be solveable.

So the sequence of events for maze generation would be this.. Create an empty map, full of zero's pick random coord for 'S'. Pick random coord for 'F'. Put the bot on the 'S'

repeat:

pick a random direction ( up/down/left/right )

check the direction is within map coord and wont lead to an 'S'

Move the bot.

if the cell is 'f then end

otherwise increment the gridcell

repeat until 'f' is reached

You may have to run this a few times. As the bot could potentially create a 100 step sequence. So run it a few times and pick the one with an appropriate amount of steps depending on how difficult you need it to be.

So you may auto create 1st 10 maps with 6-12 steps the next 10 use 12-18 steps etc etc

---
Tags: algorithm, maze
---


# Question
Title: C# modal to represent Nesting JSON in Unity JSONUtility
I am wanting to build the C# data object to represent the following JSON. I am using unity's JsonUtility. I have used the JSONUtility before but only with a simpler JSON structure. However I am not sure nesting can be done as I have been searching for examples without any luck.

```
{
"datacharts":[{
    "0000000009":[{
            "dateTime": "2016-09-14 00:14:20",
            "seconds": "60.50"
        },
        {
            "dateTime": "2016-09-14 00:15:20",
            "seconds": "57.23"
        },{
            "dateTime": "2016-09-14 00:18:20",
            "seconds": "61.230"
        },
        {
            "dateTime": "2016-09-14 00:23:20",
            "seconds": "55.875"
        }
    ]
 }]
}

```

My current C# model.

```
[System.Serializable]
public struct Drivers
{
        public DateTime[] dataTime; //time stamp unique enough to group each points?
        public float[] seconds;
}

[System.Serializable]
public class DataCharts {
    public List<Drivers> driverIds;
}

[System.Serializable]
public class DataList{

public List<DataCharts> availableData;
}

```

I'm not sure this answer will help me as I don't understand what it's wrapping. https://forum.unity3d.com/threads/how-to-load-an-array-with-jsonutility.375735/#post-2585129

Should my Json be modal differently? I am wanting to save driver times to display in a bar chart. So every driver would have a timestamp and the lap time.

UPDATE: after reading this question/answer Communicate Unity application via a series of Json

I've remodelled the json and c#. Json

```
{
    "driverId": "0000000009",
    "dataPoints": [{
                "dateTime": "2016-09-14 00:14:20",
                "seconds": "60.50"
            },{
                "dateTime": "2016-09-14 00:15:20",
                "seconds": "57.23"
            },{
                "dateTime": "2016-09-14 00:18:20",
                "seconds": "61.230"
            },
            {
                "dateTime": "2016-09-14 00:23:20",
                "seconds": "55.875"
        }]
}

```

C#

```
[Serializable]
public struct Drivers
{
    public string driverId;
    public List<DataPoints> points;
}

[Serializable]
public class DataPoints {
    public string dateTime;
    public string seconds;
}

[Serializable]
public class DataList{
    public List<Drivers> availableData;
}

```

# Answer
I've come to realize the answer is that it's not meant to do nesting. Unity JSONUtility is for retrieving JSON data from a document database. I.E if you were using firebase you'd make your call server/datacharts/unique-driverid/. This would return all dateTime and values for that driver. Your class definition would just be;

```
{
    "driverId": [{
                "dateTime": "2016-09-14 00:14:20",
                "seconds": "60.50"
            },{
                "dateTime": "2016-09-14 00:15:20",
                "seconds": "57.23"
            },{
                "dateTime": "2016-09-14 00:18:20",
                "seconds": "61.230"
            },
            {
                "dateTime": "2016-09-14 00:23:20",
                "seconds": "55.875"
        }]
}

```

As I'm only saving the data locally, I had to flatten my data structure.

```
{
   "dataPoints": [{
                "dateTime": "2016-09-14 00:14:20",
                "seconds": "60.50",
                 "driverId": "0000000009"
            },{
                "dateTime": "2016-09-14 00:15:20",
                "seconds": "57.23",
                 "driverId": "0000000009"
            }]
}

```

Which on load of the JSON will have to loop through and build a List of "dateTime" and "seconds" objects for the "selected" driver. This is what I didn't want to have to due but is seems all that is possible.
> 0 votes

---
Tags: unity, json
---


title: Snow fall animation android

text:
# Question
Title: Snow fall animation android
I already got snow fall effect from here

the main activity for the snowfall

```
public class SnowFallActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        SnowFallView snowFallView = new SnowFallView(this);
        setContentView(snowFallView);
        snowFallView.setBackgroundDrawable(getResources().getDrawable(R.drawable.snow_bg));
    }

    private class SnowFallView extends View {
        private int snow_flake_count = 10;
        private final List<Drawable> drawables = new ArrayList<Drawable>();
        private int[][] coords;
        private final Drawable snow_flake;

        public SnowFallView(Context context) {
            super(context);
            setFocusable(true);
            setFocusableInTouchMode(true);

            snow_flake = context.getResources().getDrawable(R.drawable.snow_sprite_1);
            snow_flake.setBounds(0, 0, snow_flake.getIntrinsicWidth(), snow_flake
                        .getIntrinsicHeight());

        }

        @Override
        protected void onSizeChanged(int width, int height, int oldw, int oldh) {
            super.onSizeChanged(width, height, oldw, oldh);
            Random random = new Random();
            Interpolator interpolator = new LinearInterpolator();

            snow_flake_count = Math.max(width, height) / 10;
            coords = new int[snow_flake_count][];
            drawables.clear();
            for (int i = 0; i < snow_flake_count; i++) {
//                Log.e("sizeChange", " ang width = " + width + " the height = " + height);
                Animation animation = new TranslateAnimation(0, height / 10
                        - random.nextInt(height / 5), 0, height + 30);
                animation.setDuration(10 * height + random.nextInt(5 * height));
                animation.setRepeatCount(-1);
                animation.initialize(10, 10, 10, 10);
                animation.setInterpolator(interpolator);

                coords[i] = new int[] { random.nextInt(width - 30), -30 };

                drawables.add(new AnimateDrawable(snow_flake, animation));
                animation.setStartOffset(random.nextInt(20 * height));
                animation.startNow();
            }
        }

        @Override
        protected void onDraw(Canvas canvas) {
            for (int i = 0; i < snow_flake_count; i++) {
                Drawable drawable = drawables.get(i);
                canvas.save();
                canvas.translate(coords[i][0], coords[i][1]);
                drawable.draw(canvas);
                canvas.restore();
                Log.e("sizeChange", " ang width = " + coords[i][0] + " the height = " + coords[i][0]);
            }
            invalidate();
        }

    }
}

```

The AnimateDrawable Class

```
public class AnimateDrawable extends ProxyDrawable {

    private Animation mAnimation;
    private Transformation mTransformation = new Transformation();

    public AnimateDrawable(Drawable target) {
        super(target);
    }

    public AnimateDrawable(Drawable target, Animation animation) {
        super(target);
        mAnimation = animation;
    }

    public Animation getAnimation() {
        return mAnimation;
    }

    public void setAnimation(Animation anim) {
        mAnimation = anim;
    }

    public boolean hasStarted() {
        return mAnimation != null && mAnimation.hasStarted();
    }

    public boolean hasEnded() {
        return mAnimation == null || mAnimation.hasEnded();
    }

    @Override
    public void draw(Canvas canvas) {
        Drawable dr = getProxy();
        if (dr != null) {
            int sc = canvas.save();
            Animation anim = mAnimation;
            if (anim != null) {
                anim.getTransformation(
                        AnimationUtils.currentAnimationTimeMillis(),
                        mTransformation);
                canvas.concat(mTransformation.getMatrix());
            }
            dr.draw(canvas);
            canvas.restoreToCount(sc);
        }
    }
}

```

ProxyDrawable Class

```
public class ProxyDrawable extends Drawable {

    private Drawable mProxy;

    public ProxyDrawable(Drawable target) {
        mProxy = target;
    }

    public Drawable getProxy() {
        return mProxy;
    }

    public void setProxy(Drawable proxy) {
        if (proxy != this) {
            mProxy = proxy;
        }
    }

    @Override
    public void draw(Canvas canvas) {
        if (mProxy != null) {
            mProxy.draw(canvas);
        }
    }

    @Override
    public int getIntrinsicWidth() {
        return mProxy != null ? mProxy.getIntrinsicWidth() : -1;
    }

    @Override
    public int getIntrinsicHeight() {
        return mProxy != null ? mProxy.getIntrinsicHeight() : -1;
    }

    @Override
    public int getOpacity() {
        return mProxy != null ? mProxy.getOpacity() : PixelFormat.TRANSPARENT;
    }

    @Override
    public void setFilterBitmap(boolean filter) {
        if (mProxy != null) {
            mProxy.setFilterBitmap(filter);
        }
    }

    @Override
    public void setDither(boolean dither) {
        if (mProxy != null) {
            mProxy.setDither(dither);
        }
    }

    @Override
    public void setColorFilter(ColorFilter colorFilter) {
        if (mProxy != null) {
            mProxy.setColorFilter(colorFilter);
        }
    }

    @Override
    public void setAlpha(int alpha) {
        if (mProxy != null) {
            mProxy.setAlpha(alpha);
        }
    }
}

```

what i'm trying to achieve is to create different size of the snowflakes that im using..So far this is what i have tried to change the size of the snowflakes by creating a loop then using setbounds to a random number. Can someone help me to achieve my goal or point me to something easier to do this?Thanks in advance

```
 public SnowFallView(Context context) {
            super(context);
            setFocusable(true);
            setFocusableInTouchMode(true);

            snow_flake = context.getResources().getDrawable(R.drawable.snow_sprite_1);

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

                int width = snow_flake.getIntrinsicWidth();
                int height = snow_flake.getIntrinsicHeight() ;
                Random rand = new Random();
                if(i % 2 == 0){
                    width = width -rand.nextInt(5 - 1 + 1) + 1 - rand.nextInt(10);
                    height = height - rand.nextInt(5 - 1 + 1) + 1 - rand.nextInt(10);
                }else if(i % 2 == 1){
                    width = width + rand.nextInt(5 - 1 + 1) + 1;
                    height = height + rand.nextInt(5 - 1 + 1) + 1;
                }
                snow_flake.setBounds(0, 0, width, height);
            }

        }

```

# Answer
Try adding the following to the SnowFallView function:

```
snow_flake2 = context.getResources().getDrawable(R.raw.snow_glow);
snow_flake2.setBounds(0, 0, (int)(snow_flake.getIntrinsicWidth()/2), (int)(snow_flake.getIntrinsicHeight()/2));

```

This line practically make another snow flake context with 1/2 the size of the original snow flake. U can add a few more with different sizes if you want. Next, add the following line in the onSizeChanged function:

```
    int y=0;
    y=random.nextInt(2);
    if(y==0)
      drawables.add(new AnimateDrawable(snow_flake, animation));
    else
      drawables.add(new AnimateDrawable(snow_flake2, animation));

```

This will randomly select between the larger snowflake or smaller snowflake to draw in the canvas. Then the rest of the code stays the same.

Hope this helps. Thanks.
> 1 votes

---
Tags: android, animation
---


# Question
Title: Delay shooting till player has reached the correct rotation - Twin Stick
Like most Twin Stick shooters, my player both turns and shoots with the right stick. I use a Quaternion.Slerp() to smoothly rotate the player from the current rotation to the new rotation, however the player starts firing before reaching the new rotation. My question is what is the most optimal way to delay my player from shooting until they've reached the desired new rotation?

# Answer
> 1 votes
I think getting rid of Slerp or using a high t so that it's fast enough would be the best as far as gameplay goes.

However, I think this gets close to what you want: find the difference in rotation between the stick and the character and shoot only if the two are close enough. I think this is the closest thing to what you actually want.

Here are two ways you can do this:

If you have vectors for stick direction and character front, probably most efficient:

```
Vector3 stickDirection;
Vector3 characterFront;
float maxShootingAngleDifference = 10;
if (Vector3.Angle(stickDirection, characterFront) < maxShootingAngleDifference) {
    Debug.Log("Shoot!");
}

```

If you have rotations for stick and character:

```
Quaternion stickOrientation;
Quaternion characterOrientation;
float maxShootingAngleDifference = 10;
// documentation does not say, but if this can return negative, put it in Mathf.Abs()
if (Quaternion.Angle(stickOrientation, characterOrientation) < maxShootingAngleDifference) {
    Debug.Log("Shoot!");
}

```

This would make it fire after the character gets closer than 10 degrees to the stick direction.

---
Tags: unity, quaternion
---


title: Using a basic shader in libGDX

text:
# Question
Title: Using a basic shader in libGDX
Looking at https://github.com/libgdx/libgdx/wiki/Shaders, I have decided to try these shaders:

```
    String vertexShader = "attribute vec4 a_position;\n"+
                            "uniform mat4 u_projectionViewMatrix;\n"+
                            "void main()\n"+
                            "{\n" +
                            "gl_Position =  u_projectionViewMatrix * a_position;\n"+
                            "} ";
    String fragmentShader = "void main()\n"+
                        "{\n"+
                            "gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);\n"+
                            "}";
    ShaderProgram shader = new ShaderProgram(vertexShader, fragmentShader);
    _batch.setShader(shader);

```

> Exception in thread "LWJGL Application" java.lang.IllegalArgumentException: no uniform with name 'u\_projTrans' in shader

# Answer
There is nothing wrong with the shaders.

The error you're getting is due to somewhere in your program your calling a line similar to this:

```
shader.setUniformMatrix("u_projTrans", matrix);

```

Basically this error is thrown when either `u_projTrans` doesn't exist in that `shader` or it does exist in the `shader` but you don't use it. When it's not used the shader compiler will optimize away unused uniforms.
> 1 votes

# Answer
You are most certainly trying to use your shader in SpriteBatch. SpriteBatch is setting up the shader's projection matrices, which are by convention (as MadEqua answered) called u\_projTrans, not u\_projectionViewMatrix (see SpriteBatch source). SpriteBatch also uses some more uniforms which you must declare (and use, so they aren't optimized away).

However, there is a way how to stop libGDX from crashing when it is trying to set non-existent uniforms and that is by setting pedantic flag to false:

```
ShaderProgram.pedantic = false;

```
> 1 votes

# Answer
Your application is trying to find an `uniform` in the shader called `u_projTrans` to send it the projection matrix.

The simplest fix is changing this shader line:

`"uniform mat4 u_projectionViewMatrix;\n"+`

to

`"uniform mat4 u_projTrans;\n"+`

Then the variable names should match on both the application and shader sides.
> 0 votes

# Answer
As the others already pointed out in their answers, `SpriteBatch` expects specific uniforms in the shader and you should either rename them or set the pedantic flag to false.

**I just wanted to add**, that both those things didn't help me solve this error.

The solution was this paragraph from the documentation:

> You can ensure that the shader compiled properly via shader.isCompiled(). A compile log can be spit out using shader.getLog().

*Turned out, my shader didn't even compile properly, because it had a syntax error.* So, always make sure to call `shader.isCompiled()` and `shader.getLog()`
> 0 votes

---
Tags: libgdx, shaders
---


# Question
Title: Best way to do discontinuous animation? Or: Best way to animate a character with a jerky center of mass?
I am using Unity and need to know how to use it animation system properly for… well let me describe it below.

In this game I have this big 3D block-like character that moves in an unusual fashion compared to most game characters. In most games, the character moves along a straight line at a constant rate. However this character, and other characters in the game, does not move in a continuous fashion. Instead it is discontinuous and choppy in unique ways.

For example, here is how I want a big block character to move:

Basically the two corners in front of him are pivot points, and the character moves forward by alternating between these two points and rotating. How can I do this with Unity's animation system? For the most part the animations in Unity don't move the character but instead have an animation play, such as the "Run" animation, and then a script actually moves the character. Know I the animator has a “use root movement” or something that does exactly this, but I have heard that it can causes problems. I’ve been considering just programming all of the animations, since they are relatively simple. However that makes fine tuning them a nuisance, and have some animations programmed and others not is probably not a good practice. I kind of also fear that if I don’t end up programming it I will have troubles with detecting if a character can walk through a certain walkway, considering for example the above animation his “walk width” is greater than his actual width since he rotates side to side.

Also keep in mind that there are other animations that are discontinuous like this but work in different ways. For example, another block that hops but pauses between hops. Another might rock backwards and then slide forward on the forward rocking animation.

So I know there are multiple ways to tackle this, but my question is what is the best way to do this? How would you do it?

# Answer
> 1 votes
I don't have access to the Unity docs at the moment and didn't do very much with the built-in animation system, so I might have the names wrong, but it's a keyframe system, yes? "At this time, this object should be in this state," and the engine handles the in-between? Use that for the rotations. At time 0, box should be level. At time 15 (or whenever), box should be rotated 15 degrees around top-left corner. At time 30 (or whenever), box should be rotated 15 degrees around top-right corner relative to previous keyframe. The important thing here is you have to keep moving the pivot between keyframes - it may be necessary (again, can't test at this moment) to add an extra keyframe (at time 1 and 16, in the above example) just for moving the pivot, or the engine might decide to move it slowly over time.

So (each of these is relative to the previous state):

* T=0: Box rotation 0, pivot point centered.
* T=1: Box rotation unchanged, pivot point at top-left corner
* T=15: Box rotation +15 around X, pivot point unchanged
* T=16: Box rotation unchanged, pivot point at top-right corner
* T=30: Box rotation -30 around X, pivot point unchanged

---

Alternately, do you really need to make it an animation? Maybe make it actual movement. Comparable: A character who moves normally, their animation would be walking in place, while the model is moved horizontally by the game engine as a separate-but-simultaneous process. For this character, perhaps rotate the actual transform of the model - set the pivot point, rotate, repeat. In your example, the "script that actually moves the character".

It seems from your description that the unusual means of movement are actually a game mechanic, not purely cosmetic - generally, if you've got a game mechanic you want to handle it in the engine, i.e. with scripts, not in the animation system. There are probably exceptions, but they're not coming to mind.

Use animations for changes within a local frame of reference - if the box squishes or bends or changes color - but if the entire model is moving together, that's not a job for animation.

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


# Question
Title: Best format for model with double UV sets
I'd like to use first UV set as wrapping (or when some faces cover another on UV) diffuse color map and second UV set as baked ambient occlusion (packed to `islands`) map. It is possibly to use FBX or Collada .dae or other (what?) in this case? I read scene by Assimp library.

# Answer
Both FBX and Collada support multiple UV sets, as does Assimp as noted here: http://www.assimp.org/main\_features.html

> Loads multiple UV and vertex color channels (current limit is 8)

However, methods for exporting those file-types from 3D modelling software vary from each program to the next and is beyond the scope of this SE site.
> 2 votes

---
Tags: blender, assimp
---


title: Unity Vector3.Angle() direction

text:
# Question
Title: Unity Vector3.Angle() direction
I have a space fighter AI. I need to determine how to pitch, yaw and roll the craft to aim at the target.

---

**My current solution:**

To obtain the Yaw angle to position the target above the fighter, here are my steps:

1. Project the target vector onto the local XZ plane of the fighter.
2. Vector3.Angle(transform.forward, projectedVector)

The problem is that Vector3.Angle always return a positive angle

```
^ T        T ^
|/          \|
F            F

(F - Fighter, ^ - forward, T - Target)

```

both of these return the same angle

My current solution is to

1. Cross product `transform.forward` and `targetYawVector`
2. Dot the result against `transform.up`
3. if \< 0, its one direction, where \> 0 its the other. (switchable)

Same is done with roll and pitch

**Issue:**

This current solution does too much computation. Doing a stress test with ~300 units slows the simulation down to sub 30 FPS on a 3 year old computer. (I am assuming that players will have older computers)

---

**Question:**

Is there a better way to obtain the direction of an angle without needing to do all these?

# Answer
> 1 votes
For a direction on an angle in 3D space you need to pick what positive and negative mean in your context.

One simple method I've used in the past is to simply multiply the results of Vector3.Angle by the sign of dotting the target vector to the direction I want to be positive. For example if we assume the situation you described is top down:

```
^ T          T ^
|/            \|
F->            F->

(F - Fighter, ^ - forward, T - Target, > - right)

```

And your vectors are cast to the XZ plane as your first step describes then you can simply use

```
signedAngle = Vector3.Angle(transform.Forward, targetVector) *
              Mathf.Sign(Vector3.Dot(transform.Right, targetVector))

```

Mathf.Sign returns 1 if the value is \>= 0 and -1 if it is \< 0 so when multiplied with the result of Vector3.Angle this should give you an value from (-180, 180\] which sounds like what you want.

Another nice thing is since we only care about whether the dot is positive or negative and the angle is likewise unaffected (IIRC) we can get away without using normalized vectors, which I mainly call out as you mentioned performance issues.

Many times when I've seen performance issues on code using a lot of vectors, too much unnecessary normalization has been to blame or a good first suspect as it involves a number of square roots. While I do not know what your code looks like you should try to only normalize a vector once in a block of code, assuming you need it. A gotcha to pay attention to is that the vector.normalized property will re-normalize the vector *every time* it is called, so if you need the normalized value frequently and are seeing performance problems it can help to cache the result and use that instead.

# Answer
> 0 votes
I can guarantee you that one extra vector projection per frame for 300 units will not slow down your game. You could probably run thousands and thousands of these without noticing a performance dip. Your issue is elsewhere. To find out where you will need to do some profiling. Thankfully this is really easy since Unity 5.0 as you now have access to the profiler even as a free user.

Go to Window -\> Profiler to open the profiler window.Make sure "Record" is pressed and then play your game. You'll now be able to see what method is hogging your resources which may not be processor time, maybe you're running out of memory or have some other bottleneck.

---
Tags: unity, 3d, mathematics, vector, optimization
---


title: Unity Asset Store Tools Problem

text:
# Question
Title: Unity Asset Store Tools Problem
So I downloaded Asset Store Tools in the Unity Asset Store. When I upload my asset to my package, I get this popup:

> **Wrong project path** *The path selected must be inside the currently active project. Note that the AssetStoreTools folder is removed automatically before the package enters the asset store.*

My Unity is version **5.4.0b25**. I've tried other assets and reinstalled Unity, I still get the same popup.

Screenshot:

# Answer
> 1 votes
This question has been posted several times on the Unity forums, and while I should think one would run into it before posting on here, I will repost it just in case.

This one answer popped up across all iterations I could find, most commonly marked as the most useful answer.

> To quote:
>
> Hi :),
>
> just an adjucated guess<sup>*\[sic\]*</sup>: setting the category of your product to Complete Projects in the AssetStoreManager seems to do the trick.

---

The only user that did not find it useful later put it down to the fact that they were using an older version for the assets, and a *beta* version of Unity. If the above does not work, it would be a good idea to ensure you are uploading with the most recent *stable* release of the software.

---
Tags: unity, asset-management
---


# Question
Title: What are screen space derivatives and when would I use them?
I see the `ddx` and `ddy` glsl functions and the hlsl equivalents come up in shader code every now and then. I'm currently using them to do bump mapping without a tangent or bitangent but I basically copy-pasted the code. I don't understand what these functions actually are, what they do, and when I would look to use them.

So questions:

1. What are the screenspace derivatives functions?
2. What do these functions do? The input values and output values
3. What effects are they most commonly used for?
4. What sort of effects require that you look toward these functions?

# Answer
> 30 votes
First, it helps to know that GPUs always evaluate fragment/pixel shaders on 2x2 blocks of pixels at a time. (Even if only some of those pixels ultimately need to be drawn, while others are outside the polygon or occluded - the unneeded fragments are masked out instead of being written at the end).

The screenspace derivative of a variable (or expression) `v` in your shader is the difference in the value of `v` (at that point in the code) from one side of this 2x2 pixel quad to the other. ie. `ddx` is the value of `v` in the right pixel minus the value of `v` in the left, and similarly for `ddy` on the vertical. (Here I'm using the names for these functions in DirectX HLSL. In OpenGL GLSL, these are `dFdx` and `dFdy` respectively.)

This answers "how fast does `v` increase or decrease as we move horizontally (`ddx`) or vertically (`ddy`) across the screen?" - ie. in calculus terms, it approximates the partial derivatives of your variable (approximate because it uses discrete samples at each fragment, rather than mathematically evaluating the infinitesimal behaviour of the function)

For scalar quantities, we can also view this as a gradient vector `∇v = float2(ddx(v), ddy(v))` which points along the screenspace direction in which `v` is increasing most rapidly.

This type of information is often used internally to select an appropriate mipmap or anisotropic filtering kernel for texture lookups. For example, if my camera looks almost parallel to the vertical `uv` direction of a textured floor plane, `ddy(uv.y)` will be very large compared to `ddx(uv.x)` (since the vertical axis is foreshortened on the screen - one pixel stride vertically covers a longer stretch of texture space), which tells the texture sampling hardware that I need anisotropic filtering to blur the vertical texture direction more than the horizontal to avoid aliasing artifacts.

For most simple effects you don't need to use these derivatives, since the basic 2D texture sampling methods handle it for you. But as Maximus Minimus mentions in a comment above, when you're distorting your texture lookups, you might need to manually retrieve and/or massage the screenspace derivatives to use, to help the hardware select the appropriate filtering (eg. via `tex2Dlod` in HLSL).

This can come up when you're using polar or spherical coordinates to wrap a texture circularly. At the wrap-around point, adjacent pixels suddenly jump from -180° to +180° angles, which sit at opposite ends of the texture, so the screenspace derivative for the texture coordinate gets huge, and the default pipeline will try to select a tiny mip to hide the aliasing - introducing a blurry 2-pixel-wide seam. So we have to be aware of these derivatives to tell it otherwise (example for polar coordinates on a quad / example on a sphere in shader graph and in code).

I also had to muck with derivatives to avoid seams between tiles in this single-quad tilemap shader.

Screenspace decals are another such case, where a single 2x2 block can cover a large jump discontinuity in the calculated texture coordinate, leading to a smeared or aliased edge if you let the system calculate the filtering level naively. This article goes into detail about this artifact and approaches to mitigate it. This article shows a similar issue and fix when rendering a procedural scene with raymarching.

These derivatives can also be handy when you're using noise functions in procedural texture generation. If, say, you wanted to turn procedural noise into a normal map, `ddx` & `ddy` give a simple, if approximate, way to calculate how the noise value is changing in the vicinity of the current fragment, and which way it's sloping, so you can construct an appropriate normal.

Techniques for rendering antialiased lines or intersection highlights may also use screenspace derivatives, to ensure the thickness/falloff is consistent and not dependent on the geometry or view angle. (eg. drawing an antialiased circle / drawing topographical lines on a map or terrain / drawing crisp, vector-like sprites)

In this talk about sand rendering in Journey, the speaker mentions they could have used these derivative functions to control how sparkly the sand is along glancing edges...if they'd known about them at the time (instead they used a mipmapping trick, which under the hood is powered by these kinds of derivatives anyway)

One last note to be aware of: screenspace derivatives can be computed at "coarse"/low precision (meaning one pair of derivatives is shared by the whole quad) or "fine"/high precision (meaning each pixel is compared with only its immediate neighbours in the quad, which could give four distinct derivative pairs over the quad). Coarse is generally plenty, but if you notice you're getting visible 2x2 blocks in your effect, it's a good clue you want to switch to fine/high precision. ;)

(In the diagram at the top I used calculations for fine derivatives, but beware that just `ddx`/`ddy` on their own may default to coarse derivatives)

---
Tags: opengl, directx, glsl, hlsl, graphics-programming
---


# Question
Title: How can I reduce the sharpness of my generated terrain?
I am trying to generate a random low poly terrain for a 3D demo. I am using Perlin noise to generate the heights and then generate the 3D mesh, but the terrain generated is too sharp and unrealistic. It ends up looking like this:

But I'd like it to look more like this:

How can I smooth out my terrain so it looks more like the second image?

# Answer
> 6 votes
**Issue:** The scale of the terrain in the sample image seems to be much larger. A hill is represented by at least 10x10 vertices while your mountain is represented by at most 5x5 vertices.

**Solution 1:** Increase the sample density of your noise. This is effectively equivalent to having more vertices and thus have more detail to your terrain

**Solution 2:** Increase your noise scale. This is effectively equivalent to smoothing your values. This means that you won't have tall mountains or steep cliffs.

# Answer
> 2 votes
Without knowing the specifics of your algorithm here are a couple things you can try:

**If you want a simple method that keeps the same highs and lows; but has a greater amount of points fall in the middle range** you can simply generate your terrain off two samples of noise instead of one, and average the results (or sum them and use 2 * maxval as your max instead of maxval). This will lead to still having the occasional sharp peak/valley where the noise lines up but cause a smoother terrain overall.

**If you want to have what you have now but with specific shapes to your peeks and valleys** you can play around with a graphing calculator to find a curve that you like for the spread of results you can get. For example if you are using values between 0 and 1 for your height values then applying a function like (tanh(x)-1)/2 to the points will smooth off your extremes while giving a closeish to linear range around the middle band. Make sure if you chose this route to play with the values. doing things like halving or doubling x going in will effect the overall steepness of your terrain without impacting the max or min height and other changes will have other potentially useful effects.

As a side note, some of the apperance of sharpness come from your textures. If the style is not desired, addressing it could help. If you cannot afford an approach such as multisampling (blending between two textures based on height) I would make transition textures for small bands between the high contrast steps to avoid the hard zigzag lines.

# Answer
> 0 votes
Another way to do this is to generate your terrain as a height map and then low-pass filter it. Applying a gaussian or even box blur to it will give you more gentle transitions between peaks and valleys.

---
Tags: procedural-generation, procedural
---


# Question
Title: How to get GestureDetector to work?(Problem with GestureDetector class)
I am trying to write simple program which would get input from user by swiping in four capital directions.

I'm extending GestureDetector.java from libGDX and overriding fling method, but no matter how user swipes, velocityX and velocityY are positive values.

```
public boolean fling(float velocityX, float velocityY, int button){
            if(Math.abs(velocityX) < Math.abs(velocityY)) {
                if (velocityX > 0){
                    directionListener.onUp();
                } else {
                    directionListener.onDown();
                }
            }else{
                if (velocityY>0) {
                    directionListener.onRight();
                } else {
                    directionListener.onLeft();
                }
            }
}

```

Trying to get to the bottom of this I modified GestureDetector and for me the problem seems to be in VelocityTracker class:

```
static class VelocityTracker {
    int sampleSize = 10;
    float lastX, lastY;
    float deltaX, deltaY;
    long lastTime;
    int numSamples;
    float[] meanX = new float[sampleSize];
    float[] meanY = new float[sampleSize];
    long[] meanTime = new long[sampleSize];

    public void start (float x, float y, long timeStamp) {
        this.lastX = x;
        Gdx.app.log("Start()","lastX"+String.valueOf(lastX));
        lastY = y;
        deltaX = 0;
        deltaY = 0;
        numSamples = 0;
        for (int i = 0; i < sampleSize; i++) {
            meanX[i] = 0;
            meanY[i] = 0;
            meanTime[i] = 0;
        }
        lastTime = timeStamp;
    }

    public void update (float x, float y, long timeStamp) {
        long currTime = timeStamp;
        Gdx.app.log("update()","lastX : "+String.valueOf(this.lastX));
        deltaX = x - lastX;
        deltaY = y - lastY;
        Gdx.app.log("update()","x     : "+String.valueOf(x));

        lastX = x;
        lastY = y;
        long deltaTime = currTime - lastTime;
        lastTime = currTime;
        int index = numSamples % sampleSize;
        meanX[index] = deltaX;
        meanY[index] = deltaY;
        meanTime[index] = deltaTime;
        Gdx.app.log("update()","DeltaX: "+String.valueOf(deltaX));
        Gdx.app.log("--------------","---------------");
        numSamples++;
    }

    public float getVelocityX () {
        float meanX = getAverage(this.meanX, numSamples);
        float meanTime = getAverage(this.meanTime, numSamples) / 1000000000.0f;
        if (meanTime == 0) return 0;
        return meanX / meanTime;
    }

    public float getVelocityY () {
        float meanY = getAverage(this.meanY, numSamples);
        float meanTime = getAverage(this.meanTime, numSamples) / 1000000000.0f;
        if (meanTime == 0) return 0;
        return meanY / meanTime;
    }

    private float getAverage (float[] values, int numSamples) {
        numSamples = Math.min(sampleSize, numSamples);
        float sum = 0;
        for (int i = 0; i < numSamples; i++) {
            sum += values[i];
        }
        return sum / numSamples;
    }

    private long getAverage (long[] values, int numSamples) {
        numSamples = Math.min(sampleSize, numSamples);
        long sum = 0;
        for (int i = 0; i < numSamples; i++) {
            sum += values[i];
        }
        if (numSamples == 0) return 0;
        return sum / numSamples;
    }

    private float getSum (float[] values, int numSamples) {
        numSamples = Math.min(sampleSize, numSamples);
        float sum = 0;
        for (int i = 0; i < numSamples; i++) {
            sum += values[i];
        }
        if (numSamples == 0) return 0;
        return sum;
    }
}

```

It seems like lastX is set to 0 after update or start method are finished/started, output from log-ing is :

23459-23472/com.ssekav.myTestGame.android I/Start()﹕ lastX : 343.0 23472/com.ssekav.myTestGame.android I/TouchDragged﹕ 376.0:1402.0 23472/com.ssekav.myTestGame.android I/update()﹕ lastX : 0.0 23472/com.ssekav.myTestGame.android I/update()﹕ x : 376.0 23472/com.ssekav.myTestGame.android I/update()﹕ DeltaX: 376.0 23472/com.ssekav.myTestGame.android I/--------------﹕ --------------- 23472/com.ssekav.myTestGame.android I/TouchDragged﹕ 402.0:1388.0 23472/com.ssekav.myTestGame.android I/update()﹕ lastX : 0.0 23472/com.ssekav.myTestGame.android I/update()﹕ x : 402.0 23472/com.ssekav.myTestGame.android I/update()﹕ DeltaX: 402.0 23472/com.ssekav.myTestGame.android I/--------------﹕ --------------- 23472/com.ssekav.myTestGame.android I/TouchDragged﹕ 415.0:1383.0 23472/com.ssekav.myTestGame.android I/update()﹕ lastX : 0.0 23472/com.ssekav.myTestGame.android I/update()﹕ x : 415.0 23472/com.ssekav.myTestGame.android I/update()﹕ DeltaX: 415.0 23472/com.ssekav.myTestGame.android I/--------------﹕ ---------------

I feel like I am missing something basic here, however whole GestureDetection is exactly the same except for logging.

Edit: I Solved my problem with just moving deltaX and deltaY outside of VelocityTracker class, now it's working but I don't understand why it wouldn't work otherways.

# Answer
I know exactly what is the issue with your code even though you didn't post the part of code that caused the issue, because I had the exact same problem.

You must have instantiated the GestureDetector in the render() method, or any other subsequent method called in the render(), things like update(), handleInput() etc...

The result is that the gestureDetector is instantiated many times per second. It will still give you right X,Y, but anything related the deltaX, deltaY, velocity will be wrong.

This is because the last instantiated GestureDetector only knows the latest X,Y, and don't have records previous X,Y.
> 0 votes

---
Tags: java, libgdx, gestures
---


title: How would I make a game like diep.io?

text:
# Question
Title: How would I make a game like diep.io?
I started to learn how to code HTML, but apparently I need to use java for this one. Are there any good tutorials out there?

# Answer
> 1 votes
Any programming language will do. Please note that HTML is NOT a programming language.

If you are looking for a tutorial for any language, the best thing to do is start with a search like : `Java Tutorial` on Google, you will find more thant you need, even posts on SO telling which ones are the best.

---
Tags: java
---


title: Directional light type

text:
# Question
Title: Directional light type
I am currently trying to implement a specific directional light type.

This light type has been used in the game INSIDE and is called orthogonal spotlight (aka local directional light). I assume that this is a directional light which behaves like a spot light and have a squared or rectangular attenuation but I have some difficulties to integrate it in my deferred pipeline and get the general concept of this light type.

Implementing a simple directional light is simple `dot(worldNormal, lightDir)` but what kind of data should I use to constraint its application into a square or a rectangle ?

I hope that you'll be able to give me some clues. Thanks a lot !

# Answer
You have a box matrix, which is the orientation and the scale of your light. If you would apply that matrix to a unit box, then you would get your light box.

Now you need the inverse of that box matrix. Transform the pixel's world position with that inverse matrix, because that gives you the pixel's position in the light's local space. If that position is inside a unit box (meaning, the position's x,y,z coordinates are inside the (-1,1) range if your unit box's half extents are 1) then it is inside the light so you should apply the light contribution (multiply its color with the dot(worldNormal,lightDir)).

If you have that working, you could apply a nicer "falloff" by multiplying the light contribution according to how close the pixel's light space position is to the vector (0,0,0). That way you can get a nice gradient, not a simple cutoff.
> 1 votes

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


# Question
Title: Unity-Sharing values between functions invoked by buttons and the rest of the script
Ok so, here is the problem.

I am doing a multiplayer 2D game using UNET.

I have a script that kind of helps a player select an avatar to play with. The avatars are listed as a scrollview of buttons. These buttons invoke the function `setAvatar(int id)` that sets a player's avatar passing in an ID as argument. The function just sets the player's avatar using ID as index in a list of avatars.

Now the problem is this player is a prefab which is instantiated at the start of the playscene for Player A and Player B. So the `setAvatar(int sprid)` function assumes I am referring to the prefab whenever I use "gameObject"

So, I decided to store the local gameObject in a temporary variable.

Here's the full code,

```
public class Player2DController : NetworkBehaviour // Attached to player prefab
{
    public float moveForce = 2;
    Rigidbody2D myBody;
    Transform mainCamera;
    Shooting shscript;
    int i;
    public Transform joystick;
    GameObject temp;

    public Sprite[] spr;

    void Start ()
    {
        if (!isLocalPlayer)
        {
            Destroy (this);
            return;
        }

        temp = gameObject; // storing local gameobject in temp

        joystick = GameObject.Find ("MobileJoystick").transform;
        shscript = GetComponent<Shooting> ();
        mainCamera = Camera.main.transform;
        RotateCamera ();
        myBody = GetComponent<Rigidbody2D> ();

        if (isClient)
        {
            i = -1;
        }
        if (isServer)
        {
            i = 1;
        }

    }

    public void RotateCamera()
    {
        if (isClient)
        {
            mainCamera.rotation = Quaternion.Euler (new Vector3 (0f, 0f, 180f));
        }
        if (isServer)
        {
            mainCamera.rotation = Quaternion.Euler (new Vector3 (0f, 0f, 0f));
        }
    }

    void FixedUpdate ()
    {
        if (PauseMenu.isOn)
        {
            return;
        }
        Vector2 moveVec = new Vector2(CrossPlatformInputManager.GetAxis("Horizontal"),CrossPlatformInputManager.GetAxis("Vertical"))* moveForce;

        myBody.AddForce (moveVec * i);

        if (CrossPlatformInputManager.GetButton("Shoot"))
        {
            shscript.CmdFire ();
        }

    }

    public void setAvatar(int id) // called through the buttons in the avatar list
    {
        temp.GetComponent<SpriteRenderer> ().sprite = spr [id];//null pointer exception
    }
}

```

This code doesn't work. I get a null pointer exception on `temp` variable saying it is not assigned. But how can this be? I clearly assign it to active gameObject in `Start()` method. The only reason I can think of why this is happening is that since the button acts on the player prefab, it creates a separate instance of the script for the player prefab that doesn't get executed. So, when it invokes `setAvatar()`, it has a temp which is not initialized.

So that's the whole problem. Since this didn't work, I tried renaming the players as `clientPlayer` and `serverPlayer` and then accessing them using `GameObject.Find(name).GetComponent<SpriteRenderer>().sprite`. But this had no effect and no errors. I have no idea why.

So any ideas on how to go about this?

# Answer
It might be the case that the following part get executed and `temp` is never assigned to `gameObject`:

```
if (!isLocalPlayer)
{
    Destroy (this);
    return;
}

```

So make sure that you check for null before utilising this reference:

```
if(temp != null)
    temp.GetComponent<SpriteRenderer> ().sprite = spr [id];

```
> 0 votes

---
Tags: unity, 2d, multiplayer, scripting
---


title: Turn-based browser game

text:
# Question
Title: Turn-based browser game
I want to try to build a multiplayer turn-based browser game.

What technologies do you recommend me to use for server side considering I plan to host it on a shared host? Would PHP be fast enough?

# Answer
> 2 votes
Unless you expect to have millions of concurrent players, I don't think you have to worry about inherent performance differences of languages or technologies. That is even more true since your game is turn based, meaning you don't need real-time interactions, and it's not that bad if something takes a few milliseconds more here or there. If anything, the shared host environment would be a bigger source of problems than the tech you use, because you can't predict when and if your performance is affected.

The best advice is probably: use a language that you're comfortable with.

# Answer
> -2 votes
You should not let yourself be limited by language, choose the best tool for the job so you don't have to reinvent too many wheels. One possibility is to go with Unity. It can be programmed on either C# or Javascript, the latter should be easy to learn if you already know PHP.

Also, you can find ready made turn based strategy frameworks such as this one: https://www.assetstore.unity3d.com/en/#!/content/50282

---
Tags: browser-based-games, turn-based
---


# Question
Title: Turn-based strategy games where action happens in real-time?
Okay, this idea has come up for the 3rd time in conversation now, and it's been bugging me for years. The idea is a game where all players make decisions/issue orders to units while the game is in a paused state, and all the actions are executed at once, in real-time. This could be at any level from a TRPG (i.e. Final Fantasy Tactics), to a small-scale skirmish (i.e. Worms), to a game with bases and many units (i.e. Advance Wars), to a Risk-type game (i.e. Risk).

The main disadvantage to this I can see is that the player doesn't see the result of an action immediately. In a traditional turn-based or real-time strategy game, the user clicks "attack that fool" and there's an explosion straight away. There also might be weird situations (you send your unit to melee a unit running in the opposite direction, for example), but that's a low-level detail; a good game designer should be able to get around these things. Finally, there's the general paucity of turn-based games, but they offer a level of tactical depth impossible in real-time strategy games, and there's always a market for them (dozens of new TBSes appear each year).

* Are there any games out there that use this paradigm?
* Why aren't there more?
* What would be necessary to make this work?
* What potential issues could you foresee?

To clarify, I mean pure strategy. The commands are input beforehand, and the *resolution* is realtime, but it doesn't require realtime "twitch" input by players.

**EDIT:** Iain's answer pointed me to Laser Squad Nemesis, which basically answered the 2nd and 4th question ;-P -- If you want to know why this won't work, download the demo (It's 9MB) and click the first tutorial. OUCH! Of course, Laser Squad Nemesis's UI doesn't help (play and pause buttons? seriously? and why do I have to click "issue orders" every turn if that's the only thing I'm going to be doing?)

For simpler things (like the board games mentioned in a couple answers, or Zwok that Iain created), this paradigm works great! Issues seem to arise with a more traditional tactics/strategy game, because the lag between the entry of a command and the execution of the command is apparent. In fact Zwok - and some of the board games mentioned - work *because* off this lag, not in spite of it. You're encouraged to guess what your opponent will do next and "think ahead". However in a more traditional small-scale tactical strategy game, the frustration factor isn't worth it.

It might be interesting to see a game like this on a *really* large scale. For example, Lee and Napoleon didn't order their troops around in real-time, but rather made decisions based on information that was often hours old -- and it often took hours for those orders to get executed. Even today, generals don't have real-time top-down maps. But taking that "frustration factor" out would require some seriously deft game design.

# Answer
> 9 votes
I first encountered this technique on a game called Laser Squad Nemesis. I always thought it was a great idea, and used it when I developed Zwok for Sony. It allows Zwok to have 6 player multiplayer without ever having to wait in turn.

# Answer
> 25 votes
Why has no one mentioned Frozen Synapse? It's exactly as you describe. Turns are planned and played out at the same time. It works amazingly well.

http://www.frozensynapse.com/

# Answer
> 16 votes
The classic Diplomacy works like this, of course (I can't believe nobody mentioned it yet ...). It's a great rule book to study if you're interested in such game modes, in particular in how they deal with conflicting move orders. You can download the rulebook on the official site.

# Answer
> 8 votes
An example of a game that uses this paradigm is Flotilla. The space combat sequences start with a simple three-step setup for each ship (direction, speed, target). You get a "ghosted" preview of where your ship will move when the orders are executed. Once you've set up all your ships, you commit your actions, then the game runs real-time for 30 seconds. The only thing you can do during that time is sit and cringe as your plans go awry. Once the 30 seconds are up, everything freezes (including projectiles in mid-flight) and you repeat until all of the ships from one side are destroyed.

As you stated above, a primary reason that there aren't more of these games is the lack of instant gratification. A secondary reason might be the steeper learning curve: the feedback cycle for trial and error is *much* longer than in real-time games.

Perhaps to mitigate the feedback issue, you could allow very limited real-time tweaking of each individual unit. This would make it easier in the early game, where you are likely to have fewer units: you can spend your time on those few units with a shorter feedback cycle while still learning the larger strategies. The amount of real-time that you have remains constant, though, so as the number of units grow you would not be able to tweak more than a few units, downplaying the usefulness in the later game.

# Answer
> 7 votes
> Are there any games out there that use this paradigm?

"Turn-based" and "real-time" are not mutually exclusive, so if you're asking if this has been done before, it depends on how you define them.

There are plenty of turn-based games where all players write down (or enter, or program, or whatever) their commands for the turn, secretly and simultaneously, then reveal and resolve. The resolution may not count as "real-time" unless it's being shown on the computer, the idea being the players are just sitting and watching the turn play out. The board game RoboRally, the pencil-and-paper game Spellcaster (aka Waving Hands), the online TCG Sanctum all come to mind instantly. You could easily mod a lot of turn-based games: consider Chess where you write down moves simultaneously, using some custom rules to resolve situations where one piece moves into a square just as another moves out, or two pieces cross paths or move into the same square at once. Simultaneous-move is not anything special, but it is an elegant way of removing the first-player advantage.

If you're thinking instead of a game where you make turn-based moves, and then the resolution of those moves happens in real-time through some kind of mini-game, the archetypal game of that type is the classic Archon. The more recent Mario Party series of games are a much more casual version of the same basic theme: move on a board, then play a mini-game to resolve the turn.

If instead you want some kind of mixture of real-time and turn-based, where you give turn-based orders but can then modify them in real-time based on what the opponent is doing, the sport of American Football sounds like it would fit that description.

> Why aren't there more?

Who says there aren't?

> What would be necessary to make this work? What potential issues could you foresee?

Depends entirely on how you define the mechanics. Mostly, the tricky thing with mixing turn-based and real-time is that you run the risk of combining the disadvantages with none of the strengths. Hardcore strategy gamers might dislike the twitch-based nature of combat resolution, while action gamers might dislike the level of strategizing in between the 'fun' parts.

# Answer
> 6 votes
Simultaneous turn-based games are common enough, mainly in the wargame genre, where they're sometimes referred to as "WEGO" turn-based systems. As already mentioned, Laser Squad Nemesis would be the main example of a squad-level one. On slightly larger scales, the Combat Mission series from Battlefront would be a good example; http://en.wikipedia.org/wiki/Combat\_Mission\_%28video\_game\_series%29

Re problems with this approach, I think the main one would be the greater demands on the AI - the player's units have to be able to work autonomously and respond to unexpected situations well. Eg, the player send their squad around a courtyard, and mid-way through that, the opponent's guys appear around a corner. The player isn't going to be too happy if his squad just keeps on moving and gets taken out, so they have to be able to branch off from their original orders and respond appropriately - and just stopping on the spot, standing there and shooting probably won't suffice.

Obviously the AI opponents have to do that in any kind of turn-based game anyway, but it's a lot easier to convince the player that someone not under their control and not very visible has a game plan. Whereas if the player's own units mess up his carefully planned orders by coming apart when faced with unexpected (but reasonable) scenarios, you're going to lose your player pretty quick. That's the main issue I'd see, aside from gameplay concerns like balancing how long the execution phase is, how much can be done in it, etc.

# Answer
> 4 votes
Check out the design documentation and prototype for spacecrack, a simultaneous turn-based 4X space game. The docs are full of interesting observation on the nature of turb-based gaming and gaming in general, and make for a very interesting read.

In fact, all of Lost Garden is more than worth the trouble.

# Answer
> 4 votes
The idea of simultanous turn based gaming is quite old, actually. In industrial age around 1800, it has surfaced as *Kriegsspiel* \- german for wargame - and was used to train officers in the Prussian army. Also, the concept is well known in the board game community, with early game system titles like *Diplomacy* beeing released in 1959.

As for computerized versions of simultanous turn based system, the play by mail and then the play be email genre spawned many a game. Notable examples of more complex, large scale war-gaming that orginated in the 1980s and 1990s are *STARWEB* (by Rick Loomis, now remade as RSW-Game), *Olympia* (Shadow Island Games/Rich Skrenta), *Galaxy* and *Atlantis* (both by Russell Wallace), *Prometheus* (Mathias Kettner) and *Wolfpack Empire*. Order cycles usally were about one week due to the high amount of game units and order complexity e.g. 200 units with 5-6 orders each. A modern representation of this kind of game system is the open source game *Freeciv*.

All of these games use a certain degree of abstraction when it comes to the simulation of the player unit's action in the game world - some of them tend to simulate more, while others are more on the abstract side of this. As such, some games do not feature fully simultanous game actions, while others try to emulate this model as closely as possible. These beforementioned games represent very complex game systems that are not found anymore in todays strategy game shelves - mostly for market reasons and the problem of GUI - some of these games are still played by hard core strategy enthusiasts.

I advise to search for the games mentioned above to find out whether some instances are still running.

# Answer
> 3 votes
Neverwinter Nights and some of the Final Fantasy titles are turn-based *and* realtime simultaneously.

# Answer
> 3 votes
This sounds very similar to the combat mechanics of Star Trek: Birth of the Federation. That was actually the first 4X TBS game I ever played, and I was rather surprised to discover that combat in other 4X TBS games did not follow a similar model. I thought it worked very well. In fact, I'm developing an unofficial sequel to that very game, and I plan on implementing a very similar combat system.

Here's a breakdown of how it worked:

* The game itself uses simultaneous turn-based mechanics: all players issue orders at the same time and then signal their readiness to end the turn.
* As part of the turn processing, combat might occur.
* Combat occurs in rounds/turns. Note that these "turns" are different from game turns; entire combat sessions (i.e. battles) actually take place *between* game turns as part of the turn processing.
* During each combat turn, players issue orders to their fleets. These orders generally consist of a maneuver (e.g. charge, circle, fly over/under, etc.) and a target. The only exceptions I can think of are 'retreat' or 'avoid', which do not have a target associated with them.
* Once all players have issued their orders, the results of that turn play out in real time.
* This process repeats probably 3-6 times on average until a victor emerges, both sides retreat, or both sides open hailing frequencies in lieu of engaging in combat.

Personally, I think there are some very compelling reasons to go with such a system. In contrast to games like Civilization (in which combat progresses as a series of 1v1 skirmishes), it provides real-time cinematics of a grand battle where all units are engaging at once. I also tend to think it works better than completely real-time combat systems like the one in MoO3 because:

* It maintains the simultaneous turn-based mechanics of the game.
* By restricting the player to simple orders consisting of a maneuver and a target, combat time can be kept reasonably short (remember, other players are waiting on you!). In a system where players can issue real-time orders, it would be easier to draw combat out by luring enemy forces away, playing hide-and-seek via cloaking, etc.
* Because players issue simple maneuvers instead of setting a course themselves, it's easier to take advantage of combat in all three dimensions (if you're building a space-based strategy game). Instead of needing a clumsy 2D interface to plot an "attack from above" in 3D space, the player simply has to click "attack from above" and be done with it.
* It's a hell of a lot easier to develop ;).

# Answer
> 3 votes
I would say the main reason is simply that resolving conflicting orders is complicated. It's far easier to force each move to be made in isolation than to try and decide which of several moves that might contest the same position or resource should take precedence.

# Answer
> 2 votes
I think Dan Bunten's Global Conquest fits your definition. Players issued gave movement and action instructions to all of their units and then all of the orders were executed at once.

# Answer
> 1 votes
The board game Race for the Galaxy does this. All actions are chosen and placed face down, and then resolve "simultaneously". Apples to Apples also works like this in a way.

# Answer
> 1 votes
Of course, you can have actions queued up which simulates turns, but doesn't stop real-time action.

The Sims has a good implementation of this with actions appearing at the top of the screen and vanishing as they are performed.

# Answer
> 1 votes
My idea for how to implement this revolves around each turn, having units possess a specific amount of "energy" or "mana" or some other thing that allows a unit to do only so much during the real time resolution (think Civilization, or the Total War series)

That way, you might tell a melee unit to attack another unit, and if the other unit is told to move away, then the melee unit will move as close as it can, but may not necessarily get the attack off.

# Answer
> 1 votes
If you don't mind widening the scope a bit for examples, Scorched Earth has a mode like this, where everyone sets what they're doing for the turn before having everyone execute at the same time.

Also in an even looser sense, Grandia (RPG).

Whenever someone's turn crops up, it pauses on them, then when you assign the action they wait a specific amount of time during which they can be "canceled" by a hard hit (spells/abilities take longer than attacks which just take a moment). Once they are done building to the attack they go off to do it. This does mean shortly after they are done they have a tendency to just stand still, but it does make things like evasion (choosing to run to another point) and AoE (actually takes into account who's in the target area at the moment the spell goes off) have interesting effects.

Also if you queue up an attack, and the enemy takes off to attack someone elsewhere, your person will attempt to chase them down for a certain distance then stop. If they run by, they'll take a swipe at the target but depending on their attack animation/direction/speed they may or may not hit.

Both of these are not traditional Turn-Based Strategy, but elements of the gameplay you are looking for are shown in each. Might help give a different angle on bits and pieces of it.

# Answer
> 0 votes
Well-developed examples (i.e., little or no bugs) of a strategy game that combines both turn-based strategy and real-time strategy, and at the micromanagement level, can be found in Koei-developed strategy games.

Starting with Kakushin, the Nobunaga's Ambition series games allows you to pause the real-time gameflow so you can do some serious micromanagement over a really large map of Sengoku-era Japan: constructing buildings, drafting soldiers, buying and selling both food and military equipment, doing technology research, enhancing defensive emplacements, etc. During the pause, there are options to pursue diplomacy and even foreign intelligence.

With the real-time battles, units can be ordered to points on the map, target other units, and deploy special tactics. The only downside to Koei's approach, also found in a later game or two of the Romance of the Three Kingdoms series (similarly large map, but of Han-era China), is that there's no multiplayer option. Fans of the two game series enjoy the level of micromanagement and the serious absence of gaming bugs, and don't care about the absence of a multiplayer option.

Since Star Trek games have been mentioned above, a combination of both turn-based strategy and real-time strategy would be like Birth of the Federation and Armada put together, if not BOTF and Armada and the original Starfleet Command. Star Trek: Conquest is a low-budget combination of the two strategy genres, and so isn't as good on the turn-based end as BOTF, or on the real-time end as Armada.

Mike Strobel:

"By restricting the player to simple orders consisting of a maneuver and a target, combat time can be kept reasonably short (remember, other players are waiting on you!). In a system where players can issue real-time orders, it would be easier to draw combat out by luring enemy forces away, playing hide-and-seek via cloaking, etc."

If game developers eschewed a multiplayer option, there wouldn't be problems with prolonged combat in real time within a galactic game board, so to speak.

I mentioned the original Starfleet Command as an honorary mention, as incorporating that game's mechanics within a combination of turn-based and real-time micromanagement would really stress the micromanagement aspect: during each battle, players must engage in starship systems micromanagement while piloting one of up to three ships, and especially after each battle, players must spend credits won on repairing and resupplying the ships they have.

All of these can be done with little or no bugs, but without a multiplayer option.

# Answer
> -1 votes
I myself have been developing a multiplayer TBS game as a unique concept -- I will be using that term lightly from now on however. The difference with our game however is conflict and 'other' pertinent game progression mechanics are resolved with short arcade style action minigames in realtime. These range from Ikari Warriors style combat to Wave Race adrenaline fueled navigation.

Our reasoning behind this decision is we want to minimise the use of RNG's and A.I, having the player's strategy and sheer skill, control the events of the game as much as possible.

We too are running into design issues however, mainly in that we need to keep the game interesting. Even though we employ simultaneous issue of orders between players and have opted for the course of a day to be structured in an ORDERS \> RESOLVE, ORDERS \> RESOLVE kind of mechanic (it's deeper than that but for the sake of writing this...) what will make or break it is player engagement if they're not taking part during the RESOLVE phases of the game. We think we may have nailed this, because the opportunities to consult the board without a timer stressing you out are quite limited, and so players may use this much welcome time to plan, instead of spectate the battle.

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