# Question
Title: Can steam features be used in a game bought on an alternate distribution platform?
We're in the process of game development where we need to integrate with the Steamworks API for multiplayer matchmaking, achievements, player stats, etc. We also have a rudimentary implementation integrating with the Steam Workshop in order to distribute player-authored content.

However, I have a remit that the game should be publishable on other distribution platforms such as GOG.

* **If we were to distribute on an alternative platform such as GOG, is it acceptable to rely on steam features?** I presume this would mean the player purchasing on GOG and being forced to install steam and set up a steam account before playing. (I'm also aware that GOG are very much anti-DRM which might entail a separate build version too, if even possible).
* **If not acceptable, what's the alternative?** Are developers expected to employ platform-specific or a proprietary network system for multiplayer matchmaking for instance? How is this achieved in other games?

# Answer
To some extent, the answer depends on how you are defining your terms. My interpretation of the docs is that it's okay to:

* Sell Steam keys through other venues provided you are doing so in a way that's generally comparable to how you sell on Steam
* Games using Steam keys can use the Steam infrastructure (servers, bandwidth, etc), even if those keys were not sold directly through Steam.

I was not able to find definitive info (edits to the contrary are welcome) addressing whether or not, you cannot make use of the Steam infrastructure without a Steam key. I could see this being allowed for things like cross-platform play, but wasn't able to determine if this was being done on Steam or 3rd party servers. On the other hand, it seems reasonable to assume that Steam doesn't want to bleed out money or assume legal liability for content completely outside their ecosystem. They pitch use of their infrastructure as way of "enhancing the value of legitimate copies."

If the documentation doesn't address your concerns, I suggest reaching out directly to Steam for additional clarification.

Here is an excerpt taken from the public facing documentation on Steam keys:

> **Overview**
>
> Steam keys are meant to be a convenient tool for game developers to sell their game on other stores and at retail. Steam keys are free and can be activated by customers on Steam to grant a license to a product.
>
> Valve provides the same free bandwidth and services to customers activating a Steam key that it provides to customers buying a license on Steam. We ask you to treat Steam customers no worse than customers buying Steam keys outside of Steam. While there is no fee to generate keys on Steam, we ask that partners use the service judiciously.
>
> ...
>
> **Steam Key Rules and Guidelines**
>
> You should use keys to sell your game on other stores in a similar way to how you sell your game on Steam. It is important that you don't give Steam customers a worse deal.
>
> It's OK to run a discount on different stores at different times as long as you plan to give a comparable offer to Steam customers within a reasonable amount of time.

Here is an excerpt taken from the public facing documentation on Steam DRM:

> **Overview**
>
> The Steam DRM wrapper is an important part of Steam platform because it verifies game ownership and ensures that Steamworks features work properly by launching Steam before launching the game.
>
> The Steam DRM wrapper by itself is not is not a anti-piracy solution. The Steam DRM wrapper protects against extremely casual piracy (i.e. copying all game files to another computer) and has some obfuscation, but it is easily removed by a motivated attacker.
>
> We suggest enhancing the value of legitimate copies of your game by using Steamworks features which won't work on non-legitimate copies (e.g. online multiplayer, achievements, leaderboards, trading cards, etc.).
> 1 votes

---
Tags: steam, distribution
---


title: Overlaying Menus with a State Machine

text:
# Question
Title: Overlaying Menus with a State Machine
I'm working on developing a game with C++, SDL, and OpenGL. I created the engine from scratch, and implemented my own state machine to handle menus and general gameplay. Each State gets pushed into a stack and the last one gets updated and drawn, after initialization on entry. They also handle input on a per-State basis. Right now I have a State for entry point, a 'Press Any Key' prompt, a main menu, as well as a new game menu where the player enters their name. I also batch my Sprites together for easy drawing. I simply pass a vector of Sprite pointers (as some animated sprites may be mixed in as well) to the drawing function which uploads the Sprites to a buffer and draws them. These vectors of Sprites are organized by batch type - mostly based on texture.

I'm moving on to the Exit Game menu, which displays a confirmation that the game will close and the player will be returned to their desktop. I wanted this menu to display on top of the Main Menu with a transparent black layer that darkens everything but the exit game prompt. I can figure out the drawing part easily enough, but the problem is that the Sprites are local to the same State that created them. I am having troubles trying to decide how to 'share' the main menu sprites with the Exit Game State. Likewise, I have the title screen background and logo. The logo animates as well. These two Sprites are visible to every title screen State. Which means I again need some way of continuously displaying a select few Sprites until further notice, such as on entry of the main game. When I get to cutscenes, I will typically need every Sprite used by the gameplay part of the game as well.

One idea I had was to store Sprites in the State Machine as opposed to the State itself. This would mean all Sprites are visible to every State, and the current State would decide which Sprites to delete and which to keep. This means that accessing the Sprites through the State would be a little more roundabout - some sort of access function through the State Machine.

EDIT: I've started implementing the first solution but putting Sprite batches into my Game Engine. The drawback is the scope of each Sprite is not so clearly defined per-State, they need to be directly deleted by the following State to determine which Sprites to keep and delete. It does also make identifying Sprites a little more difficult on transition, though I'm thinking of implementing a std::map of strings to Sprites as I'll need a naming system for cutscene scripting anyway.

I had another idea that would involve 'inheriting' Sprite batches from the previous State but that would also complicate identification of the Sprites.

ANOTHER UPDATE: I'm thinking of getting rid of AnimatedSprite as a distinct class. It just complicates the storage part. By merging it in with regular Sprites, Sprites can be animated but don't need to, and as for the extra storage needed for animations, I'm not too concerned as almost every one of my Sprites animates in some way. With this edit I store my sprites in a vector for batching, a map for naming, and a third optional pointer in my States that optimizes some menus by directly accessing Sprites rather than using map lookup. Going to try that and see how it works out.

# Answer
> 1 votes
One solution to this problem is by executing EACH state on the state machine, or having speicfic states (or transition states) that are defined to execute one before another. A typical implementation of this might include a stack to maintain the "current state" as it's top. This implementation gives you some nifty things out of box, at certain costs (if you don't work around them) in even the trivial case. However usually those costs would be minimal, unless you're stacking entire levels or large scenes in each state.

The way this works is like so, assuming that whatever state is currently pushed is now on the top of the stack, always render the top of the stack:

```
Game starts -> Main Menu scene is pushed
Click start game -> Game scene is pushed (now the stack has two scenes pointed)
You die -> Either the game scene is popped, and a game over screen is pushed, or simply a game over scene is pushed, which when popped you'd re-enter and restart the previous scene (the game scene) giving you a "restart" functionality for free.

```

How this translates to your code may not be eminently clear so I'll specify: Why only have one "current scene?" maybe scenes can be marked with `transparent=true` and the entire stack is checked in order from bottom to top, only being drawn when it should be. This would give you what you're looking for, plus more abilities for free. It should be worth noting of course that the stack would be maintaining all of your sprites and other things. Exactly what you want, however still worth noting that keeping multiple levels or large scenes this way stacked on top of each other isn't really what this pattern is designed for, and for that you should have some kind of scene that knows how to swap scenes like a SceneManager or LevelLoader scene.

---
Tags: c++, spritebatch, game-state
---


title: Frustum Culling bug in program

text:
# Question
Title: Frustum Culling bug in program
I did Frustum Culling in my engine, but it does not work correctly. All shown in the video:

Video

If the approximation is too close, the model disappears. On the right in the console you can see that one model is rendered less. With what it can be connected?

**Frustum creation code:**

```
bool FrustumCulling::update(ID3D11Device* device, const Camera & view, float angle, float ratio, float _near, float rear)
{
    Vector3 pos = (Vector3)view.getViewPosition();
    Vector3 d = pos - (Vector3)view.getViewDirection();
    d.normalize();
    Vector3 right = (Vector3)view.getViewHeight();
    right = right.cross(d);
    right.normalize();
    Vector3 up = Vector3::cross(d, right);
    // get h and w near and rear planes
    float val = angle * 0.5;
    float tang = (float)tan(val);
    float nh = _near * tang; // near height
    float nw = nh * ratio; // near width
    float rh = rear * tang; // rear height
    float rw = rh * ratio; // near width
    // generate 8 vertex frustum
    Vector3 fc = pos - d * rear;
    Vector3 ftl = fc + up * rh - right * rw; // ftl - Far(rear) Top Left
    Vector3 ftr = fc + up * rh + right * rw;
    Vector3 fbl = fc - up * rh - right * rw;
    Vector3 fbr = fc - up * rh + right * rw;
    Vector3 nc = pos - d * _near;
    Vector3 ntl = nc + up * nh - right * nw;
    Vector3 ntr = nc + up * nh + right * nw;
    Vector3 nbl = nc - up * nh - right * nw;
    Vector3 nbr = nc - up * nh + right * nw;
    // generate 6 planes frustum
    Plane3 p(ntr, ntl, ftl);
    data.planes[TOP] = PlanesFrustum(p.getPlane());

    p = Plane3(nbl, nbr, fbr);
    data.planes[BOTTOM] = PlanesFrustum(p.getPlane());

    p = Plane3(ntl, nbl, fbl);
    data.planes[LEFT] = PlanesFrustum(p.getPlane());

    p = Plane3(nbr, ntr, fbr);
    data.planes[RIGHT] = PlanesFrustum(p.getPlane());

    p = Plane3(ftr, ftl, fbl);
    data.planes[FARP] = PlanesFrustum(p.getPlane());

    p = Plane3(ntl, ntr, nbr);
    data.planes[NEARP] = PlanesFrustum(p.getPlane());
}

```

**Model verification code (cube bbox) to hit frustum:**

```
bool modelCheckFrustum(Vector3 * v)
{
    for(int k = 0;k<8;k++)
    {
        Vector3 p0 = v[k];
        int isFrustum(0);
        for(int l = 0; l<PLANES_SIZE;l++)
        {
            Vector4 n = planes[l].pl; //
            float value = shortDistanseFromPointToPlane(n, p0);
            if(value > 0.f) // point in current plane
                ++isFrustum;
        }
        if (isFrustum == PLANES_SIZE)// point in frusrtum
            return true; // model in frustum
    }
    return false; // model not in frustum
}

```

*PLANES\_SIZE* \- count planes, == 6

*planes* \- array planes frustum

*planes* \- Vector4, when x,y,z - a,b,c, and w - d

**Method shortDistanseFromPointToPlane:**

```
float shortDistanseFromPointToPlane(Vector4 p, Vector3 p0)
{
    return p.x*p0.x + p.y*p0.y + p.z*p0.z + p.w;
}

```

**Distance to the front and rear planes:**

```
float SCREEN_DEPTH = 1000.f;
float SCREEN_NEAR = 0.01f;

```

Creating a matrix of perspectives:

```
matrixProjection = Matrix::CreatePerspectiveFovLHMatrix(GeneralMath::PI / 4, w / (float)h, SCREEN_NEAR, SCREEN_DEPTH);

```

w, i - width and height window

How to fix this nasty bug? Thank.

P.S.: I did frustum culing in this lesson.

**UPD1**:

I created a model frustum, and it shows that not a single BBox vertex got inside the frustum. Now I know the reason, it remains to come up with a solution to this problem :)

Image:

# Answer
> 1 votes
I solved this problem. I added an extra *sphere - test*. Although the method has errors, but it solves my problem completely. Since this is an editor, it is appropriate here. But there will be a collision in the game, and there will be no such need there. The essence of the method is as follows:

```
int testBSphereInFrustum(float3 p0, float3 cen) //  p0 - coord BBox model, cen - center BBox model
{
    float radius = length(p0 - cen); // get radiuse sphere around the model
    float sCenterToPlaneNearCenter = length((float3)centerNear - cen); // get length center BBox model and center near plane frustum
    int res = sCenterToPlaneNearCenter <= radius ? 1 : 0;
    return res; // return result
}

```

I measure the radius of the sphere around the model and the distance from the center of the model to the center near the plane of the frustum. If the radius is less than or equal to - then the test is passed.

---
Tags: c++, directx, directx11, frustum, frustum-culling
---


# Question
Title: Why does the drag fail when I move too fast?
I got this code that drags a 2d sphere when i touch the screen:

```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Dragstick : MonoBehaviour {

    private Vector3 offset;

    void Update()
    {
        if (Input.touchCount > 0)
        {
            Vector3 touchPosWorld = Camera.main.ScreenToWorldPoint(Input.GetTouch(0).position);
            Vector2 touchPosWorld2D = new Vector2(touchPosWorld.x, touchPosWorld.y);

            RaycastHit2D hitInformation = Physics2D.Raycast(touchPosWorld2D, Camera.main.transform.forward);
            if (hitInformation.collider != null)
            {
                GameObject touchedObject = hitInformation.transform.gameObject;
                switch (touchedObject.tag)
                {
                    case "Player":
                        Debug.Log("Touched Sphere " + touchedObject.transform.name);
                        touchPosWorld.z = 0f;
                        transform.position = touchPosWorld;
                        break;
                }
            }
        }
    }
}

```

Thing is, if I move my finger too fast, the drag stops and the sphere drops... also it runs kind of slow when i execute it...

Any help about what am I doing wrong? Maybe I'm making things too complex, drag and drop of a sphere should be really easy but functions in unity have changed a lot.

Thanks in advance!

# Answer
> 4 votes
The only possible problem I see with the code is that you're checking for a raycast hit constantly. Since your finger "moves too fast" it's no longer casting a ray on the object and your collider is now null.

Instead of checking for the object constantly, check for it on your finger down and then move it until the finger is lifted. This is the snippet / pseudo-code I would use for this job:

```
Touch touch = Input.GetTouch(0);
switch (touch.phase)
{
//When a touch has first been detected, change the message and record the starting position
    case TouchPhase.Began:
        // "Pick up" the ball
        // put the gameobject in some variable global for this script
        message = "Ball picked up ";
        break;

    //Determine if the touch is a moving touch
    case TouchPhase.Moved:
        // Move the ball to current position of your cursor how you want.
        message = "Ball moved ";
        break;

    case TouchPhase.Ended:
        // "Drop" the ball and remove it from the global gameobject you're using
        message = "Dropped ball ";
        break;
}

```

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


# Question
Title: most compact way to represent dice face translations rolling in cardinal directions
I'm making a 2-D dice rolling game in BASIC (think mechanics similar to Devil Dice on the Playstation, but top-down 2D graphics). I'm trying to accurately represent the transitions of a die when rolling it from one face to another along the cardinal directions. I can look up the current value of a die at a given position but I'm not maintaining actual object representations corresponding to a physical die, so modeling the 3D dice in game is out.

I can think of two ways to do this, but can't quite implement either correctly.

1. Make a lookup table given a die face, orientation, and direction of roll that returns the new correctly oriented die face.
2. Something about bitwise arithmetic I don't understand from answer #3 on this page. Seems like it could be harder to implement but possibly smaller, more elegant code. I don't, however, need anything to do with spinning or edges or animation, just fetching the next face up.

I'm trying not to prematurely optimize, but eventually the code should be able to be made as compact as possible. BASIC, so I'm not using any complicated 3D libraries or game engines, I want to keep this close to the bare metal as far as logical physics simulation goes.

# Answer
I think a lookup table indexing each of the 24 orientations is likely to be the most compact you can get. Then your current orientation is a byte and you can look up the values of the faces as quickly as single read.

But if you'd like to use code logic instead, here's one strategy you can use to exploit the symmetric structure and work on a compact representation:

* Store the value shown on the side of the die facing the x+ direction, and y+, and z+
* Rotating about a given axis...

+ keeps the side facing along that axis the same
    + interchanges the faces on the other two axes, and
    + replaces one of those two interchanged sides with its opposite (ie. `side --> (7 - side)`)
    (which one gets flipped depends on whether you're rotating +90 or -90)

...so you could either write these as 4 operations, or a single one that treats the axis like an index to select which array elements / bits to swap around.

You can store this list of sides very compactly. One side of a die (1-6) fits in 3 bits, so you could fit two in a single byte if you wanted to, and compute the third side on demand:

```
// These just make what follows a bit more legible
static int Opposite(int side) { return 7 - side; }

static int Axis(int side) { return side <= 3 ? side : Opposite(side); }

static int ComputeFacingX(int facingY, int facingZ) {
    int axis = 6 - Axis(facingY) - Axis(facingZ);
    if ((facingY < facingZ) ^ (facingY > Opposite(facingZ)) ^ (((facingY + facingZ) & 1) == 0))
        return Opposite(axis);
    return axis;
}

```

Or since 6\*6\*6 = 216 \< 256, you could even store all 3 sides in a single byte, though you'd need some integer division rather than a fast bitmask to decode them from that packed form.
> 1 votes

# Answer
I would create a lookup for each of the die faces with their neighbors in each direction. So the center is the faceup:

```
       n
     +---+
     | 4 |
 +---+---+---+
w| 5 | 1 | 2 |e
 +---+---+---+
     | 3 |
     +---+
       s

```

When rolling, one need to keep in mind how this orientation changes what N-E-S-W is. Basically the die face can rotate 90 degrees either direction because of the rolling motion.

So I model a DieFace, where you can keep track what is the current north orientation is, and facing values for each direction and (counter)clockwise rotate operation:

```
public class DieFace
{
    private int[] adjecentNumbers = new int[4];
    private int north = 0;

    public DieFace(int north, int east, int south, int west)
    {
        adjecentNumbers = new int[] { north, east, south, west };
    }

    public int North
    {
        get { return adjecentNumbers[north]; }
    }

    public int East
    {
        get { return adjecentNumbers[(north + 1) % 4]; }
    }

    public int South
    {
        get { return adjecentNumbers[(north + 2) % 4]; }
    }

    public int West
    {
        get { return adjecentNumbers[(north + 3) % 4]; }
    }

    public void TurnCW()
    {
        north = (north + 1) % 4;
    }

    public void TurnCCW()
    {
        north--;
        if (north < 0)
            north = 3;
    }

}

```

Next the difficult bit. Modelling the die itself:

```
        Die = new DieFace[7]; // 1-indexed so the index correspond to the face up value.
        Die[1] = new DieFace(4, 2, 3, 5);
        Die[2] = new DieFace(4, 6, 3, 1);
        // this takes some figuring out what the correct initial values are I guess.

        currentFaceUp = 1;

```

For example, when you roll *North*, a couple of things happen:

* the side facing south becomes the new face up value
* the side East rotates clockwise
* the side West rotates counterclockwise

```
  switch(rolldirection)
  {
      case RollDirections.North:
             int east = Die[currentFaceUp].East;
             int west = Die[currentFaceUp].West;

             Die[east].TurnCW();
             Die[west].TurnCCW();

             currentFaceUp = Die[currentFaceUp].South;
             break;

       //and so on...
   }

```

Code could be optimized- but this should illustrate the basic idea.
> 0 votes

---
Tags: physics, 3d, matrix, simulations, movement-prediction
---


# Question
Title: What strategies and patterns exist to handle large amounts of game entities?
I've been wondering this for some time now: Let's say you have a builder game like Anno and let's say you're in the very late game. You have literally thousands of production facilities placed. Each one of these needs base resources and time to produce an output. Also there's modules you can place onto the facility that give some sort of bonus.

Now: How would you make the game check each one of these and act accordingly (look if job is done, when done deliver output, start new job if resources available)?

The simplest I can think of is a loop over each of the facilities. But that just doesn't feel like a good idea due to the amount of facilities and the frequency on which game loops run.

Another thing I can think of is eventing. The facilities could inform the game core about state changes, but I'm having troubles seeing eventing and a game loop together.

As you probably can now tell I have no exp in game development but would like to get some input on that topic.

# Answer
I would push all those events onto a priority queue (with the priority based on task completion time) and the event carries all the info it needs to perform its task, even to queue up new tasks if it's a repeating action. Then the main loop only needs to check the queue against the game time to see what needs to pop and process.

The actual work of building your program now becomes simpler, each event can be developed independently of any others and you don't need to modify the main engine at all to add new activities.

As a side note, if you **design the game as a data model and views onto that model** then "seeing eventing and a game loop together" makes much more sense. A simulation has a much different main loop from an action title.
> 5 votes

# Answer
Don't overcomplicate. Thousands of facilities might sound hard to calculate for you, but it really isn't. In the worst case, it's just a bunch of equations. Computers are amazing at that.

If you want some sort of optimization, push everything sorted by the time it gets finished to a queue (insertion sort). Then you'll be able to only check the jobs up until you encounter something that hasn't finished yet, since everything after that finishes even later.
> 4 votes

---
Tags: architecture, design-patterns
---


# Question
Title: XNA 4.0 How to combine triangles vertices 3D
## *Preview for the problem:*

I'm making a similar game to Minecraft (a game that it's world is made by cubes), but the fps of the game is getting low only by rendering a little amount of cubes in the world.

So I decided to use the Combine/Margin technique to improve it. I want to combine cubes that are from the same type and there positions are next to each other.

Lets say I have 4 faces of cubes that are next to each other in that order:

\[+\] \[+\]

\[+\] \[+\]

**Right Now:** I am rendering each face with 2 triangles so in total I render all of the faces with 8 triangles.

**Improvment That I Want To Make:** I want to render these faces with only 2 triangles but to keep the textures where they are at. Which means to use only 2 tringles for 4 faces and to use 4 textures in that area.

## *OUT OF THE TOPIC:*

Currently I'm using:

* Frustum culling.
* Not rendering cube faces that are on each other.

Which fps improvment techniques do you recommend me to use? Currently when I'm rendering only 1500 faces at the same time \[3000 triangles\] my game is getting to about 25~ fps.

# Answer
> 1 votes
It's not possible sadly to have multiple textures without also dividing it using vertices. However, improvements can be made.

Don't divide the cubes into faces, the overhead of this approach outweighs the performance gain. Instead use indexed rendering and draw every visible cube at once. A cube is visible if one of the 6 neighbours is transparent. The faces you'd save using the divide approach will usually get backface culled (turn that on if it isn't).

Draw everything starting from the player's position to allow z-culling to cut even more fragments.

Another performance optimization used by minecraft is to divide the world into 16x16x16 chunks and use a fill algorithm to check whether sorrounding chunks are completely occluded or not.

If you want to go even further, only send points to the GPU and generate the cubes using a geometry shader. This can combine the pros of every technique, including leaving occluded faces out.

---
Tags: c#, xna, monogame, xna-4.0, vertex
---


# Question
Title: How can I put multiple actors on a Button?
I like to have an Button with a Text and some Pictures in it.

Is there something out of the box to that ?

I mean I would like to add a Table into a button, so I could add anything I need to the table.

# Answer
> 0 votes
A `Button` extends `Table` so you can treat it just like a normal **libGDX** `Table` and add any `Actor`s you want to it.

---
Tags: libgdx
---


# Question
Title: How can I remap Unreal's Editor default movement (WASD) keys for a non-QWERTY keyboard
I am using a French (AZERTY) keyboard, and as such my "usual" game movment keys are ZQSD instead of WASD. I have been trying to change Unreal Editor's default keys to those I am accustomed to but I can't figure out how to do it.

Using UE 4.19.1

Here are the settings I've tried so far:

# Answer
> 1 votes
Using the Top menu:

```
Edit --> Project Settings --> Engine / Input --> Bindings

e.g. Move Forward (W, S, Up, down)

```

This totally worked for me. Obviously you will want to use the keyboard menu there.

ref: https://docs.unrealengine.com/en-us/Engine/UI/ProjectSettings

---
Tags: unreal-4, control
---


# Question
Title: How to store information about a simulated sport match in a browser game?
There is a browser game called Soccerstar where users play in a soccer team and compete in matches against other teams. Matches are scheduled at specific times of the day and played automatically and when the user logs in he can watch an animation representing the last played match.

Now, I want to implement a similar feature: a match is simulated on the server based on the players statistics and tactical choices and the information about the match progression is stored in the database. Please note that I want the outcome of the players actions (tackles, shots etc.) not to be completely deterministic because I want to introduce some randomness. Once the match has been simulated and stored, the client can retrieve the information and generate the animation at any time.

My main doubt is how to represent and store the information about the match progression: what would be the smartest way to do it?

# Answer
> 1 votes
Most pseudorandom number generators can be initialized with a seed value. When you initialize it with the same seed, you get the same sequence of random numbers. That means even an algorithm which uses pseudorandom numbers can be reproduced exactly if you seed the RNG with the same value.

That means you just need to store the seed value in your database and you can exactly reproduce the whole match with all of its random events.

However, there is an additional problem in your case: The game is played asynchronously. When a player watches a match a few hours after the others played it, then some variables which affect the outcome of the match might have changed. For example, the opponent might have changed their team composition. So you need to make sure the match is always simulated with the game state at the point in time where the match was scheduled, not the current game state.

If your data model has a build-in history (which can also be useful for a lot of other reasons), that's trivial to do. If your data model does not keep a history, then you need to store all parts of the game state which are relevant for the outcome of the match together with the RNG seed.

Another problem occurs when you decide to change the algorithm which is used to decide matches when your game is already public. When one player watches the game before you release the update and another player watches it after the release, they will get different results. You can avoid that problem by keeping your old match algorithms around and always decide matches according to the algorithm which was the current one when the match was scheduled.

---
Tags: random, browser-based-games, storage
---


# Question
Title: How can I use the colours of a swatch in a script?
In Unity's editor I have set a swatch with some colours that are used throughout our game:

This swatch is saved in a file in the project's Assets folder:

```
\ProjectFolder\Assets\Editor\Main Colors.colors

```

I would like to use the colours in this swatch somewhere in a script:

```
GetComponent<Graphic>().color = SomethingHere.MainRed;

```

What is the best way to do this? Or is it not possible?

**Reflection**

I also think that I'm doing something really strange? I couldn't find any answer to this question online. But having the same colour library in the scripts as I use in the editor would be really nice.

# Answer
> 2 votes
Better solution would be just to create ScriptableObject, with `List<Entry>`:

```
class Colors: ScriptableObject
{
    [System.Serializable]
    public class Entry
    {
         public string name;
         public Color color;
    }

    public List<Entry> colors = new List<Entry>();

    public Color GetColor(string name)
    {
         var entry = colors.Find(c => c.name == name);
         if (entry != null) {
              return entry.color;
         }
         return Color.white;
    }
}

```

and later set that scriptable object anywhere you want.

```
Colors colors_db;
var color = colors_db.GetColor("MainRed")

```

Color preset you've saved is basically the same, but it's Editor only object.

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


# Question
Title: How can I Intercept object with a circular motion
I am creating a 2d space game and need to make the spaceship intercept a planet. I have working code for straight line intercepts but cannot figure out how to calculate the planets location in a circular orbit.

The game is not scientifically accurate so I am not worried about inertia, gravity, elliptical orbits, etc.

I know the spaceships location and speed and also the planets orbit (Radius) and speed

# Answer
An analytic solution to this is difficult, but we can use binary search to find a solution to within the required accuracy.

The ship can reach the closest point on the orbit in time **t\_min**:

```
shipOrbitRadius = (ship.position - planet.orbitCenter).length;
shortestDistance = abs(shipOrbitRadius - planet.orbitRadius);
t_min = shortestDistance/ship.maxSpeed;

```

The ship can reach ANY point on the orbit in time less than or equal to **t\_max**:

(Here, for simplicity, I assume the ship can drive through the sun. If you want to avoid this then you will need to switch to non-straight-line paths for at least some cases. "Kissing circles" may look nice and orbital mechanics-y, without changing the algorithm by more than a constant factor)

```
if(shipOrbitRadius > planet.orbitRadius)
{
   t_max = planet.orbitRadius * 2/ship.maxSpeed + t_min;
}
else
{
   t_max = planet.orbitRadius * 2/ship.maxSpeed - t_min;
}

```

If our orbital period is short, we might be able to improve on this upper bound by choosing the `t_max` to be the first time after `t_min` that the planet makes its closest approach to the ship's start position. Take whichever of these two values of `t_max` is smaller. See this later answer for a derivation of why this works.

Now we can use binary search between these extremes, **t\_min** and **t\_max**. We'll search for a t-value that gets the **error** close to zero:

```
error = (planet.positionAtTime(t) - ship.position).squareMagnitude/(ship.maxSpeed*ship.maxSpeed) - t*t;

```

(Using this construction, error @ t\_min \>= 0 and error @ t\_max \<= 0, so there must be at least one intercept with error = 0 for a t-value in-between)

where, for completeness, the position function is something like...

```
Vector2 Planet.positionAtTime(float t)
{
  angle = atan2(startPosition - orbitCenter) + t * orbitalSpeedInRadians;
  return new Vector2(cos(angle), sin(angle)) * orbitRadius + orbitCenter;
}

```

Note that if the planet's orbital period is very short compared to the ship's speed, this error function may change signs several times over the span from t\_min to t\_max. Just keep track of the earliest +ve & -ve pair you encounter, and continue searching between them until the error is close enough to zero ("close enough" being sensitive to your units and gameplay context. The square of half the frame duration may work well - that ensures the interception is accurate to within a frame)

Once you have a nice error-minimizing t, you can just point the ship at planet.positionAtTime(t) and go full throttle, confident that the planet will reach that point at the same time you do.

You can always find a solution within Log\_2((2 * orbitRadius/ship.maxSpeed)/errorThreshold) iterations. So for example, if my ship can traverse the orbit in 60 frames, and I want an intercept accurate to within one frame, I'll need about 6 iterations.
> 3 votes

# Answer
Let's not over-complicate this. This is not a "perfect" solution but should work for most games and any imperfection should be invisible to the player.

```
if(!OldTargetPoint)
  TargetPoint = PlanetPosition;
else
  TargetPoint = OldTargetPoint;
Distance = CurPosition - TargetPoint;
TimeNeeded = Distance / Speed;
TargetPoint = PlanetPositionInFuture(TimeNeeded);
SteerTowards(TargetPoint);
[...repeat this every AI update, for example every second...]

```
1. Calculate the time needed to reach the target point.
2. Calculate at what position the planet will be at the calculated time.
3. Move towards the calculated point.
4. Repeat

This works because the nearer the spacecraft gets towards the lower the error becomes. So the calculation becomes more stable over time.

The error is the difference between the calculated needed time to reach the planet (TimeNeeded) and the actual time needed to reach the planet (after taking into account the new TargetPoint).
> 11 votes

# Answer
Let's start off by taking a look at the math behind the problem.

# Step 1:

Finding the intersection between a line and a shape is just a matter of inserting the equation of the line in the equation of the shape, which is a circle in this case.

Take a circle with center **c** and radius **r**. A point **p** is on the circle if

$$ |p - c|^2 = r^2 $$

With a line expressed as \\$p = p0 + \mu v\\$ (where **v** is a vector, http://en.wikipedia.org/wiki/Euclidean\_vector), you insert the line into the circle formula and get

$$|p0 + \mu v - c|^2 = r^2$$

The squared distance can be rewritten as a dot product (http://en.wikipedia.org/wiki/Dot\_product).

$$(p0 + \mu v - c)•(p0 + \mu v - c) = r^2$$

Define \\$a = c - p0\\$ and rewrite to \\$(\mu v - a)•(\mu v - a) = r^2\\$

Perform the dot product and we get \\$\mu ^2(v•v) - 2\mu (a•v) + a•a = r^2\\$

Assume that \\$|v| = 1\\$ and we have

$$\mu ^2 - 2\mu (a•v) + |a|2 - r^2 = 0$$

which is a simple quadratic equation, and we arrive at the solution

$$\mu = a • v +- sqrt((a • v)^2 \*a^2 – r^2)$$

If \\$\mu \< 0\\$, the line of the ship in your case does not intersect with the planets orbit.

If \\$\mu = 0\\$, the line of the ship will simply touch the circle in one point.

Otherwise, this gives us two \\$\mu \\$-values that corresponds to two points on the orbit!

# Step 2:

So we can define a line for the ship, and out of that we get either 0, 1 or 2 \\$\mu \\$-values. If we get 1 value, use that one. If we get 2, simply choose one of them.

What can we do with this? Well, we now know the distance the ship has to travel and what point it will end up in!

\\$p = p0 + \mu v\\$ gives us the coordinate, and the \\$\mu v\\$-component gives us how far is will have to travel. Simply divide this last component with the speed of your ship to get how much time it will take for it to get there!

Now, all that is left to do is to calculate where the planet should be when the ship begins coming towards it's orbit. This is easily calculated with so called **Polar coodinates** (http://mathworld.wolfram.com/PolarCoordinates.html)

$$x = c + r\*cos(θ)$$

$$y = c + r\*sin(θ)$$

And since you had the speed of you ship, and we have the time it will take for the ship to reach the orbit, and where it will collide, we simply move the planet back \\$t\*angularVelocity\\$ degrees in it's orbit, and we are done!

# Summary

Choose a line for your ship, and run the math to see if it collides with the planets orbit. If it does, calculate the time it will take to get to that point. Use this time to go back in orbit from this point with the planet to calculate where the planet should be when the ship starts moving.
> 3 votes

# Answer
Here are two slightly "out of the box" solutions.

The question is: given that the ship moves in a straight line at a given velocity, and the planet moves in a circle of given radius at a given angular velocity, and the starting positions of the planet and ship, determine what direction vector the ship's straight line should be in to plot an intercept course.

Solution one: Deny the premise of the question. The quantity that is "slippable" in the question is the angle. Instead, fix that. Point the ship straight at the center of the orbit.

* Calculate the *position* at which the ship will encounter the planet; that's easy.
* Calculate the distance from the ship to the intercept position ; also easy.
* Calculate the time it will take until the planet next reaches the intercept position. Easy.
* Divide the distance from the ship to the intercept by the time until the planet gets to the intercept.
* If that is smaller than or equal to the maximum speed of the ship, you're done. Set the ship moving at that speed straight towards the sun.
* Otherwise, add the orbital period of the planet to the time and try again. Keep doing that until you get a speed that is within reason for the ship.

Solution two: Don't do it on autopilot at all. Make a mini-game where the player has to use thrusters to approach the planet, and if they hit it at too high a relative speed, they blow up, but they have limited fuel as well. Make the player learn how to solve the intercept problem!
> 2 votes

# Answer
Here's part of a solution. I didn't get to finish it in time. I'll try again later.

If I understand correctly, you have a planet's position & velocity, as well as a ship's position and speed. You want to get the ship's movement direction. I'm assuming the ship's and planet's speeds are constant. I also assume, without loss of generality, that the ship is at \\$(0,0)\\$; to do this, subtract the ship's position from the planet's, and add the ship's position back onto the result of the operation described below.

Let:

* \\$s\_s\\$ = the ship's speed (\\$s\_s.x, s\_s.y\\$, likewise)
* \\$s\_a\\$ = the ship's bearing (angle of movement, **what we want to calculate**)
* \\$p\_p\\$ = the planet's initial position, global coords
* \\$p\_r\\$ = the planet's distance (radius) from the center of orbit, derivable from \\$p\_p\\$
* \\$p\_a\\$ = the planet's initial angle in radians, relative to the center of orbit
* \\$p\_s\\$ = the planet's angular velocity (rad/sec)
* \\$t\\$ = the time to collision (this turns out to be something we must calculate as well)

Here's the equations for the position of the two bodies, broken down into components: $$ ship.x = s\_s.x * t * cos(s\_a) $$ $$ ship.y = s\_s.y * t * sin(s\_a) $$ $$ planet.x = p\_r * cos(p\_a + p\_s * t) + p\_p.x $$ $$ planet.y = p\_r * sin(p\_a + p\_s * t) + p\_p.y $$

Since we want \\$ship.x = planet.x\\$ and \\$ship.y = planet.y\\$ at some instant \\$t\\$, we obtain this equation (the \\$y\\$ case is nearly symmetrical):

$$ s\_s.x * t * cos(s\_a) = p\_r * cos(p\_a + p\_s * t) + p\_p.x $$ $$ s\_s.y * t * sin(s\_a) = p\_r * sin(p\_a + p\_s * t) + p\_p.y $$

Solving the top equation for \\$s\_a\\$:

$$ s\_s.x * t * cos(s\_a) = p\_r * cos(p\_a + p\_s * t) + p\_p.x \\ \implies s\_a = \frac{arccos((p\_r * cos(p\_a + p\_s * t) + p\_p.x)}{(s\_s.x * t))}$$

Substituting this into the second equation results in a fairly terrifying equation that Wolfram alpha won't solve for me. There may be a better way to do this not involving polar coordinates. If anyone wants to give this method a shot, you're welcome to it; I've made this a wiki. Otherwise, you may want to take this to the Math StackExchange.
> 1 votes

# Answer
If you dont' want to use polar coordinates, consider that the all the possible positions of the ship form a cone in \\$(x, y, t)\\$ space. The equation for this is

$$ t \cdot v = \sqrt{x^2 + y^2} $$

where \\$v\\$ is the the ship velocity. It is assumed the ship starts at zero.

The position of the planet in space and time can be parametrized by e.g.

$$ \begin{align} x &= x\_0 + r \cdot cos(w \cdot u + a) \\ y &= y\_0 + r \cdot sin(w \cdot u + a) \\ t &= u \end{align} $$

where \\$u\\$ goes from \\$0\\$ upwards. \\$w\\$ is the angular speed and \\$a\\$ is the starting angle of the planet at time zero. Then solve where the ship and planet could meet in time and space. You get an equation for \\$u\\$ to solve:

$$ \begin{align} u \cdot v &= \sqrt{ (x0 + r \cdot cos(w \cdot u + a))^2 + (y\_0 + r \cdot sin(w \cdot u + a))^2 } \implies\\ u^2 \cdot v^2 &= (x\_0 + r \cdot cos(w \cdot u + a))^2 + (y\_0 + r \cdot sin(w \cdot u + a))^2 \implies\\ u^2 \cdot v^2 &= {x\_0}^2 + {y\_0}^2 + r^2 + 2 \cdot x\_0 \cdot r \cdot cos(w \cdot u + a) + 2 \cdot y\_0 \cdot r \cdot sin(w \cdot u + a) \end{align} $$

This equation needs to be solved numerically. It may have many solutions. By eyeballing it, it seems it always has a solution
> 1 votes

# Answer
I would fix the location at which to intercept (graze the circle, at the "outgoing" side of the orbit.)

Now you just have to adjust the spaceship's speed so that planet and ship reach that point at the same time.

Note that the rendez-vous could be after N more orbits, depending how far away the ship is, and how fast the planet is orbiting the star.

Pick the N that in time, comes nearest to the ship's journey duration at current speed.

Then speed up or slow down ship to match the timestamp for those N orbits exactly.

In all this, the actual course is already known! Just not the speed.
> 0 votes

---
Tags: 2d, mathematics, physics
---


title: How do force fields scale?

text:
# Question
Title: How do force fields scale?
**Setting**

I am designing a 2d game in which a \\$1/r^2\\$ force acts between moving charged particles, and the number \\$n\\$ of particles is very large. To calculate the force between all pairs of particles is about \\$n^2/2^2\\$.

**Questions**

* How well does this scale in practice when there are hundreds or thousands or particles? (And considering that graphical output is simple, so that we want to compute the positions of all particles ~60 times per second.)
* If scaling is bad, how can I simplify the game design such that – in practice – it's not an issue any more? (For example, I have thought of constraining all particles to a lattice of discrete sites, but then I don't know how movement in arbitrary directions would work).

# Answer
This is what I do in my N-Body simulation: particles far away can be aggregated in combined cells on a grid. (Multi-resolution Grid.)

I use gravity calculations, but I am sure that charged attraction/repulsion works similarly over distance: it has the same 1/(r\*r) scale.

So particles in the same cell, or neighbour cell, you need to fully compute the influence. Particles that are far away, are aggregated. Just pretend there is a virtual particle with aggregate properties in that cell. So you only do one computation for that aggregated region.

In the video in the linked article, I describe it in more detail.

I find that 60K particles at still doable at interactive frame rate. Depending on the clumping, it can still be done at 60Hz.
> 7 votes

---
Tags: 2d, physics, game-design, physics-engine
---


# Question
Title: My method for switching between cameras in Unity does not change the main camera
I would like to be able to switch between a variable number of cameras in my scene.

The common approach requires toggling the active camera's 'enabled' property to true and setting the others to false. This is an issue when iterating through the 'Camera.allCameras' array as it doesn't contain the inactive cameras.

I therefore thought that I could get around this by creating a local array of cameras during initialisation and then iterate through that:

```
using UnityEngine;
using System.Collections;

public class CameraSwitcher : MonoBehaviour
{
    int cameraIndex;
    Camera[] cameras;

    void Start()
    {
        cameraIndex = 0;

        // Assumes that all cameras are initially active in the scene
        cameras = new Camera[Camera.allCameras.Length];

        int i = 0;

        while (Camera.allCameras.Length > 0)
        {
            cameras[i++] = Camera.allCameras[0];
            Camera.allCameras[0].enabled = false;
        }

        // Does not get recognised as main camera when activated
        cameras[cameraIndex].enabled = true;
    }

    void HandleInput()
    {
        if (Input.GetKeyDown(KeyCode.F1))
        {
            cameras[cameraIndex].enabled = false;

            cameraIndex = ++cameraIndex == cameras.Length ? 0: cameraIndex;

            cameras[cameraIndex].enabled = true;
        }
    }

    void Update()
    {
        HandleInput();
    }
}

```

The two problems with this approach are:

1) I assume that all cameras in the scene are initially active

2) Setting the camera's 'isenabled' to true in the local camera array does not set the main camera and it therefore remains 'null'

How can I store all the cameras in the scene, regardless of their active status, iterate through the array and set the main camera based on the array index?

# Answer
I think you are only forgot to set the **tag** `MainCamera`. Accordingly to the documentation Camera.main will reference the first enabled camera with `MainCamera` tag. So this should fix the problem:

```
cameras[cameraIndex].tag = "MainCamera";
cameras[cameraIndex].enabled = true;

```

---

Edit:

There are several ways of finding objects (or Component attached to object) in a given scene. The simplest (and slowest ) way is using FindObjectsOfType.

Generally it's better to avoid find methods, or eventually use them only in initialization (`Awake` or `Start`). Because of your cameras are all already present in the scene (aren't they?), you can eventually serialize an array of references to `Cameras` in your `CameraSwitch` component, and assign them from the inspector.

```
public class CameraSwitcher : MonoBehaviour
{
    int cameraIndex;
    [SerializeField]
    private Camera[] cameras;

```
> 2 votes

# Answer
I had same issue with this; even tho I changed the new active camera's tag to MainCamera, you have to first disable the first active camera's tag just @Kelly Thomas said.
> 0 votes

---
Tags: unity, camera
---


title: How to increase MagicaVoxel size limit?

text:
# Question
Title: How to increase MagicaVoxel size limit?
I need to increase the size of the field you make models in by at least 20. It really doesn't make sense why you cannot go beyond 126x126x126 because in the MagicaVoxel viewer, there are sample models of 1000x1000 so there's gotta be a way to make larger models in MagicaVoxel. Anyone know how?

# Answer
> 1 votes
You can't, really. 126x126x126 is MV's limit. You can combine two scenes together using MV\_Import and MagicaVoxel Viewer, but SLAB6 supports 256x256x255, and Paint 3D can support all the way up to 1024x1024x512. I highly recommend you check out the tutorial I linked if you want to keep using MagicaVoxel (I mean, it's free, so why the heck not), but SLAB6 and Paint 3D are your best bets if you feel like switching tools.

# Answer
> 1 votes
If you switch to world editor (the "⇄" button) you can create multiple objects and arrange them in a bigger scene.

This was added in version 0.99 - 11/23/2017.

# Answer
> 0 votes
The problem is when you export the separate boxes as objs, they all are all located in the world center. I had to align them manually in another software

---
Tags: models, voxels, magicavoxel
---


# Question
Title: Whats the general method developers to implement FPS multiple weapon handling animations?
I'm trying to create a first person shooter and I'm lost on what's a good, efficient methodology to implement the whole weapon handling animation system.

Now, I know that I could have a unique animation for every weapon, but this sounds very expensive. Do people use IK to modify hand positions so that they can reuse the same animations for similar weapons?

Also, How does recoil work? Is it baked into the animation? Or is it applied via script? In counterstrike it looks like it's baked into the animation (since they use hip firing), however, in COD it looks like

Id really appreciate any opinions because I am lost!

Thank you

# Answer
There is a wide range of ways to handle this, starting from the obsolete use of sprites up to fully rigged bodies with inverse kinematics and everything in between.

So, to begin with, you can have textures. Recoil and reload animations are of course 2D animations. They can even be made to look good in a modern setting by having high resolution and using prerendered deph buffer... however that is likely not worth the effort in modern games.

---

For good while, weapons in first person view where designed only to look good from that first person view (could even have partial geometry and not be fully textured), and if hands where visible, they would be just floating there... in fact, there would be no body in first person view... if you were to hack the camera position you would only see some hands and a gun floating around.

This makes it very easy to animate recoil, reload, even having the weapon lag behind the direction you aim, adding shake and other effects. In fact, good animation will also include walking animation that serve as a form of character expression.

You can figure out if you have no body in a first person shooter game very easily: look down. Where are your feets? Can you find them by turning around? What if you go to a corner? If they are not there, the game does not have a body for the player in first person.

That of course is only true for the player in first person, not for enemies, nor for other players connecting via network or couch multiplayer.

I would suggest to start here if you are working on a single player first person shooter game. Mainly because the situations where you would need to worry about the first person view of another character or the third person view of the player avatar would be scarse.

---

Next step up is to use the same animations for single player and multiplayer. Old implementations would turn the head of the avatar in first person view invisible to avoid accidental clipping (some would use other tricks like make it small or turn out of view). That is only really needed if the game will run in platform that may not handle face culling properly, however these kind of tricks are still in use when they are needed for only a brief moment, often in cutscene.

Games of this age would often rely on turning the torso of the avatar to follow the cursor. It is a very distintive animation look were the avatar have a fluid walk cycle, their torso turns randomly, and their hands and head are very stiff.

For a multiplayer game, I would suggest to start with this approach, you can then upgrade if you have the means to. Just using the third person animations for first person view will allow you to prototype faster.

---

Games from this last decade has been able to fluidly animate arms and head to adapt to the direction where the player is pointing. That can be done with a large library of animations※ with parametric adjustments, or with a good inverse kinematic system.

※: keyframe and interpolations, either for rigged skeletons or for morph targets, either recorded from mocap and tweaked, procedurally generated, or designed by animators.

With this approach you can have all the flexibility you want without swapping models depending on whatever or not the character is in first person. However, as you can imagine, it is much more expensive.

It can sound odd given how expensive good inverse kinematic systems can be, however: inverse kinematics is the cheap option. Doing a lot of mocap having distinct and expressive animations for each character is the expensive option... yes, I know you cannot possible record the character aming at every angle, however it is possible to tweak animations in runtime, or, well, if you invested in mocap, you might aswell add inverse kinematics. However, if you only use inverse kinematics then every character will move the same way, with mocap it is possible to do better than that.

About recoil et. al. by using rigged skeletons, the character can always be a physics entity that react to external forces that offset it and springs back to target position dictated by the skeleton. So, you can have actual recoil as an applied force on the body, and your inverse kinematics will solve the rest. Ragdoll also becomes simply disabling those systems instead of switching gears, because the ragdoll is actually always there.

---

By the way, remember to use placeholders. Is is better that development does not have to wait on assets and animations, and often it is not clear how much polish you will be able to get with whatever budged you have. Also, the quiker you can start testing the better.
> 2 votes

---
Tags: first-person-shooter, inverse-kinematics
---


# Question
Title: How can I remove scores or ban users from Google Play leaderboards?
I have included Google Play game services in my Android game. I see lot of users posting fake scores.

Can I ban them or can I delete these scores somehow?

# Answer
You can use the Google REST API gamesManagement.players.hide to hide a player from your applications leaderboard.
> 4 votes

# Answer
For future strugglers as this is not well documented. You can hide players by adding a web application in your Google Play Console and using the OAuth Playground, to execute the REST APIs Scores: list and Players: hide to get player ids and hiding her/him.

For a thorough walkthrough see my article: https://gaute.app/dev-blog/gpgs-hide-player
> 2 votes

# Answer
You can use this tool to hide cheaters:

https://github.com/playgameservices/management-tools
> 0 votes

---
Tags: leaderboards, google-play
---


# Question
Title: Algorithm to detect impossible scenarios
I'm making a simple game where a surface is split up into 4 parts, rows, obstacles spawn in them, and a player tries to dodge them.

Up to 3 obstacles are generated in each row, and this can lead to some impossible scenarios such as:

And

What would be the best way to implement an algorithm to check if it is possible to get through or not?

# Answer
> 1 votes
What we're doing here is called finding connected components of the graph representing your play space.

In this graph, the nodes are the squares of your playfield, and the edges are the allowed transitions between them (ie. pairs of adjacent non-obstacle tiles)

With this frame in mind, we can apply standard graph search algorithms.

You can start a depth-first search from.the bottom row (following only legal moves as defined by the edges described above), and check whether that search ever touches the top row.(Defining a single "start" node adjacent to all cells in the bottom row, and an "end" node adjacent to all cells in the top can help with this)

If you reach the end this way, then the start & end are in the same connected component and the end is reachable.

If the depth first search returns without ever reaching the end row, then there is no viable solution path, and the obstacles cut the graph into at least two disjoint connected components.

# Answer
> 1 votes
A different approach to generating passable challenges which you could use here is to not generate a *challenge* but instead generate a possible *solution* (a sequence of moves the player is supposed to perform) and then randomly add obstacles which do not interfere with the generated solution.

In this case that would mean that you decide which tile on each row is the one the player is supposed to be in or move through. Generate obstacles in all other tiles of that row.

On the next row, randomly decide if the player is supposed to stay, move left or move right (or move left or right by several tiles, if your game allows the player to do that). Those tiles which need to be free in order to perform that move need to be omitted when generating obstacles.

On every subsequent row, assume the player performed the move they were supposed to perform and apply the same rule.

You can tweak the difficulty by changing:

* The probability of obstacles being generated on the columns which are not marked as required for the solution.
* The probability of "move" rows vs. "stay" rows. The more move-rows and the fewer stay-rows you have, the harder the game will be. You can also increase difficulty by forcing the player to switch between moving left, moving right and staying in short intervals.

---
Tags: java, mathematics, algorithm
---


# Question
Title: How can the ball moving like billiard after collision with wall?
I tried ball.velocity = Vector3.forward * speed and also \*=-1 when the collision is occurred(It only works for straight way. But I want the ball movement be liked in photo. How can i do it? Thank you very much!

# Answer
If you have the velocity vector v and the normal vector n (the vector pointing in the direction the wall is pointing too), then it's simply

$$\vec v\_2=\vec v-2 \vec n (\vec n \cdot \vec v)$$

Where v2 is the new direction vector

You could think of this as "sliding" the end of the velocity vector twice as much as it's facing in the wall's direction or by negating one of it's components
> 1 votes

---
Tags: unity, c#, physics, billiards
---


# Question
Title: How can I defy competing games who are forcing their users to write 5 star reviews?
# Background

I've developed an app in a pretty contested category. It's one of the top three games in terms of quality (out of about 200 relevant games in this category; there are no large publishers with this type of game).

# The Problem

While I have the best ratings overall (4.92 of 5 stars; ~1000 reviews), nearly all competing games started to force their users to write 5 star reviews (including a minimum amount of characters). While these apps can't actually verify the rating afaik, most users are fulfilling their demand because of psychological reasons. They even write things like:

> This app is \****, but I have to write this review... 5 stars.
>
> Not that good, but I want to get XYZ, so I have to write this review... 5 stars.

Unfortunately the poor algorithms of Google Play will rank an app higher, the more ratings they have (My app does fine in Apples App Store, since the manual review process seems to punish these fraudulent apps).

But with Google, even if you are below a 4 star average, you'll rank better if you have a ton of reviews. Number of downloads and update frequency doesn't seem to count at all.

# The Consequences

This all started about three years ago and since then my Play Store ranking is on a downward spiral but I refuse to join this unethical train of fake reviews. Not only that it's a huge financial loss, it's highly depressing. From rank 1-3 my app went down to about 30 for the most relevant keywords.

# What I tried

I talked to multiple people from Google, but none of them feels responsible and sends me to the Developer Policy over and over again. Some of them even had the nerve to recommend Adwords to me as a counter measure.

I also reported some of these apps using Google Plays "Report App" feature. Nothing happened.

# What I have already thought about

> Join the train of manipulated reviews

This would work for sure, but as stated above, it's a no-go to me.

> Asking the competitors to stop

This would require massive administrative work and probably wouldn't work out well. Especially since there are many profit-oriented trash developers.

> Making my users aware of this issue

Since my competitors already copied multiple unique features of my game, I know for sure they are constantly checking my app for new updates. So they would quickly notice this whiny cry for help, which could lead to a massive backlash and make things even worse. Also it's nearly as dishonorable as faked reviews.

# The Question

Do you have any advices how I could preserve my game without risking its, and also my personal reputation?

# Answer
Stop relying on store ranking systems to drive users to your game. The google play store is broken in several ways. Use other channels to promote your game and send them directly to your store page. That way they will only see the rating of your game and not the ratings of the "competition".

For more tips on how to promote your game outside of the stores, check out some of the many other questions under the tag.
> 2 votes

# Answer
It's been a while since I've been developing for android, but even a few years ago, it was a violation to offer goods for good (essentially fake) reviews. Unfortunately there are plenty apps that violate rules, and the Play Store does automated checks only, so the only thing you can do for now is report them and wait.

> Join the train of manipulated reviews

I mean, you can do that, but your decision means your responsibility. You'd be in the violation of Google's Developer Policy, so at any point they can ban your account and all earnings you have.

> Asking the competitors to stop

You can try, you can also ask your local pizza place to stop sending leaflets to the neighbourhood, but that doesn't mean they will comply.

> Making my users aware of this issue

If I use an app that says something like "We don't do X, like our competitors" I'd start being suspicious. Imagine downloading an app that says "We don't track you, we don't store your info", sure it could be true, but it would sound suspicious.

The only advice I can give, keep making awesome apps/games that do treat the user well, and do not beg for good reviews. That's your part as a developer. If one day, for example, Google decided that offering money for reviews is allowed, you can't really do anything about it, and would have to accept it. Who knows, maybe one day most of the "malicious" apps out there might get removed.
> 1 votes

---
Tags: google-play, appstore
---


title: Images disappear when camera zooms in

text:
# Question
Title: Images disappear when camera zooms in
there is no problem when the camera is away, but as I zoom in to the game, the images disappear and I can't see the game properly. What is the reason ?

# Answer
> 2 votes
This is most likely caused by the camera's clipping planes.

> The Near and Far Clip Plane properties determine where the Camera’s view begins and ends. The planes are laid out perpendicular to the Camera’s direction and are measured from its position. The Near plane is the closest location that will be rendered, and the Far plane is the furthest. -Unity Manual: Camera

If you need to see objects that are closer to the camera make the near value smaller.

---
Tags: unity, camera
---


title: Walking on a sphere

text:
# Question
Title: Walking on a sphere
I'm working on a game which involves walking your character on the surface of a sphere. Using the answer to Arbitrary Rotation about a Sphere, I've written my code as:

```
if (game.isKeyDown(37)) { // left
    this.quaternion.multiply(new THREE.Quaternion(0, Math.sin(-0.01), 0, Math.cos(-0.01)));
}

if (game.isKeyDown(39)) { // right
    this.quaternion.multiply(new THREE.Quaternion(0, Math.sin(0.01), 0, Math.cos(0.01)));
}

if (game.isKeyDown(38)) { // up
    this.quaternion.multiply(new THREE.Quaternion(Math.sin(-0.01), 0, 0, Math.cos(-0.01)));
}

if (game.isKeyDown(40)) { // down
    this.quaternion.multiply(new THREE.Quaternion(Math.sin(0.01), 0, 0, Math.cos(0.01)));
}

var qx = this.quaternion.x;
var qy = this.quaternion.y;
var qz = this.quaternion.z;
var qw = this.quaternion.w;
this.obj.position.x = 2 * (qy * qw + qz * qx) * radius;
this.obj.position.y = 2 * (qz * qy - qw * qx) * radius;
this.obj.position.z = ((qz * qz + qw * qw) - (qx * qx + qy * qy)) * radius;

```

Which works fine, however I would like to control the character in such a way that pressing up and down is equivelent to walking forwards and backwards (in the direction you are looking), whereas pressing left and right is the same as turning around on the spot.

I understand that I will have to store a forward vector, but I'm not clear on how that relates to the quaternion which allows the character to walk on the surface of the sphere.

Another problem I've got to overcome is making sure the character on the surface of the sphere is actually "looking" the way it is going, at the moment I'm modelling the player as another sphere, but in the futuer it will be a proper model which will need to orientate itself.

# Answer
Store a direction vector as a tangent to the sphere. When you move, you can take this tangent, the normal vector (normalized position on the sphere) and cross them to get a general axis to rotate around. If you're limiting all movement to a single 2D plane (you're just using a single angle), for direction all you need is a sign (+1 or -1) to multiply your movement angle by. You can also use the sign to calculate a facing rotation about the sphere normal vector (or to just flip the character about its local Y axis) to orient your character properly.
> 4 votes

# Answer
The following code solves one of the OP's problem. That of the player turning around himself on a sphere, when pressing left and right (or d and a) buttons

```
                case 68: //D
                    this.quaternion.multiply(new THREE.Quaternion(0, 0, Math.sin(-0.01), Math.cos(-0.01)));
                    break;
                case 65: //A
                    this.quaternion.multiply(new THREE.Quaternion(0, 0, Math.sin(0.01), Math.cos(0.01)));
                    break;

```
> 0 votes

---
Tags: javascript, movement, quaternion, three.js, sphere
---


# Question
Title: How do I stop XNA/Visual Studio from rebuilding my content project every time I build?
My group and I are working on a game in XNA 4.0 with Visual Studio 2010/2012. The main solution has 6 projects: 2 XNA game projects (1 executable/ 1 class library), 1 WPF executable for the level editor, 2 standard class libraries, and a content project. Originally, the editor and engine XNA game projects had a content reference to separate content projects. Recently, I consolidated the content projects into one to simplify asset additions. Since pushing these changes to our git repo, certain members of my group have been experiencing weird build issues. Every time they run the project, they have to re-build all of the assets. This happens regardless of whether any changes were made, even if they just run the project directly after building. I've taken a few steps to figure out why this is happening. Below is the MSBuild output set on Normal verbosity.

The seemingly important part is at 4, with the line
`4> Rebuilding all content because build settings have changed`

```
1>------ Build started: Project: Engine.Core, Configuration: Debug x86 ------
1>Build started 11/29/2012 3:24:24 AM.
1>ResolveAssemblyReferences:
1>  A TargetFramework profile exclusion list will be generated.
1>EmbedXnaFrameworkRuntimeProfile:
1>Skipping target "EmbedXnaFrameworkRuntimeProfile" because all output files are up-to-date with respect to the input files.
1>GenerateTargetFrameworkMonikerAttribute:
1>Skipping target "GenerateTargetFrameworkMonikerAttribute" because all output files are up-to-date with respect to the input files.
1>CoreCompile:
1>Skipping target "CoreCompile" because all output files are up-to-date with respect to the input files.
1>XnaWriteCacheFile:
1>Skipping target "XnaWriteCacheFile" because all output files are up-to-date with respect to the input files.
1>_CopyOutOfDateSourceItemsToOutputDirectoryAlways:
1>  Copying file from "<solution-dir>\src\Engine.Core\DialoguePrototypeTestDB.s3db" to "bin\x86\Debug\DialoguePrototypeTestDB.s3db".
1>_CopyAppConfigFile:
1>Skipping target "_CopyAppConfigFile" because all output files are up-to-date with respect to the input files.
1>CopyFilesToOutputDirectory:
1>  Engine.Core -> <solution-dir>\src\Engine.Core\bin\x86\Debug\TimeSink.Engine.Core.dll
1>
1>Build succeeded.
1>
1>Time Elapsed 00:00:00.13
2>------ Build started: Project: TimeSink.Entities, Configuration: Debug x86 ------
2>Build started 11/29/2012 3:24:25 AM.
2>ResolveAssemblyReferences:
2>  A TargetFramework profile exclusion list will be generated.
2>EmbedXnaFrameworkRuntimeProfile:
2>Skipping target "EmbedXnaFrameworkRuntimeProfile" because all output files are up-to-date with respect to the input files.
2>GenerateTargetFrameworkMonikerAttribute:
2>Skipping target "GenerateTargetFrameworkMonikerAttribute" because all output files are up-to-date with respect to the input files.
2>CoreCompile:
2>Skipping target "CoreCompile" because all output files are up-to-date with respect to the input files.
2>XnaWriteCacheFile:
2>Skipping target "XnaWriteCacheFile" because all output files are up-to-date with respect to the input files.
2>_CopyOutOfDateSourceItemsToOutputDirectoryAlways:
2>  Copying file from "<solution-dir>\src\Engine.Core\DialoguePrototypeTestDB.s3db" to "bin\x86\Debug\DialoguePrototypeTestDB.s3db".
2>CopyFilesToOutputDirectory:
2>  TimeSink.Entities -> <solution-dir>\src\TimeSink.Entities\bin\x86\Debug\TimeSink.Entities.dll
2>
2>Build succeeded.
2>
2>Time Elapsed 00:00:00.11
3>------ Build started: Project: Editor (Editor\Editor), Configuration: Debug x86 ------
4>------ Build started: Project: Engine.Game, Configuration: Debug x86 ------
3>Build started 11/29/2012 3:24:25 AM.
3>CoreCompile:
3>  All content is already up to date
3>ResolveAssemblyReferences:
3>  A TargetFramework profile exclusion list will be generated.
3>EmbedXnaFrameworkRuntimeProfile:
3>Skipping target "EmbedXnaFrameworkRuntimeProfile" because all output files are up-to-date with respect to the input files.
3>GenerateTargetFrameworkMonikerAttribute:
3>Skipping target "GenerateTargetFrameworkMonikerAttribute" because all output files are up-to-date with respect to the input files.
3>CoreCompile:
3>Skipping target "CoreCompile" because all output files are up-to-date with respect to the input files.
3>XnaWriteCacheFile:
3>Skipping target "XnaWriteCacheFile" because all output files are up-to-date with respect to the input files.
3>_CopyOutOfDateSourceItemsToOutputDirectoryAlways:
3>  Copying file from "<solution-dir>\src\Engine.Core\DialoguePrototypeTestDB.s3db" to "bin\x86\Debug\DialoguePrototypeTestDB.s3db".
3>_CopyOutOfDateNestedContentItemsToOutputDirectory:
3>Skipping target "_CopyOutOfDateNestedContentItemsToOutputDirectory" because all output files are up-to-date with respect to the input files.
3>CopyFilesToOutputDirectory:
3>  Editor -> <solution-dir>\src\Editor\Editor\bin\x86\Debug\Editor.dll
3>
3>Build succeeded.
3>
3>Time Elapsed 00:00:00.39
4>Build started 11/29/2012 3:24:25 AM.
4>CoreCompile:
4>  Rebuilding all content because build settings have changed
4>  Building Textures\circle.png -> <solution-dir>\src\Engine.Game\Engine.Game\bin\x86\Debug\Content\Textures\circle.xnb
4>  Importing Textures\circle.png with Microsoft.Xna.Framework.Content.Pipeline.TextureImporter
4>  Processing Textures\circle.png with Microsoft.Xna.Framework.Content.Pipeline.Processors.TextureProcessor
4>  Compiling <solution-dir>\src\Engine.Game\Engine.Game\bin\x86\Debug\Content\Textures\circle.xnb
4>  Building Textures\giroux.png -> <solution-dir>\src\Engine.Game\Engine.Game\bin\x86\Debug\Content\Textures\giroux.xnb
4>  Importing Textures\giroux.png with Microsoft.Xna.Framework.Content.Pipeline.TextureImporter
4>  Processing Textures\giroux.png with Microsoft.Xna.Framework.Content.Pipeline.Processors.TextureProcessor
4>  Compiling <solution-dir>\src\Engine.Game\Engine.Game\bin\x86\Debug\Content\Textures\giroux.xnb
4>  Building Textures\Body_Neutral.png -> <solution-dir>\src\Engine.Game\Engine.Game\bin\x86\Debug\Content\Textures\Body_Neutral.xnb
4>  Importing Textures\Body_Neutral.png with Microsoft.Xna.Framework.Content.Pipeline.TextureImporter
4>  Processing Textures\Body_Neutral.png with Microsoft.Xna.Framework.Content.Pipeline.Processors.TextureProcessor
4>  Compiling <solution-dir>\src\Engine.Game\Engine.Game\bin\x86\Debug\Content\Textures\Body_Neutral.xnb
4>  Building font.spritefont -> <solution-dir>\src\Engine.Game\Engine.Game\bin\x86\Debug\Content\font.xnb
4>  Importing font.spritefont with Microsoft.Xna.Framework.Content.Pipeline.FontDescriptionImporter
4>  Processing font.spritefont with Microsoft.Xna.Framework.Content.Pipeline.Processors.FontDescriptionProcessor
4>  Compiling <solution-dir>\src\Engine.Game\Engine.Game\bin\x86\Debug\Content\font.xnb
4>ResolveAssemblyReferences:
4>  A TargetFramework profile exclusion list will be generated.
4>EmbedXnaFrameworkRuntimeProfile:
4>Skipping target "EmbedXnaFrameworkRuntimeProfile" because all output files are up-to-date with respect to the input files.
4>GenerateTargetFrameworkMonikerAttribute:
4>Skipping target "GenerateTargetFrameworkMonikerAttribute" because all output files are up-to-date with respect to the input files.
4>CoreCompile:
4>Skipping target "CoreCompile" because all output files are up-to-date with respect to the input files.
4>_CopyOutOfDateSourceItemsToOutputDirectoryAlways:
4>  Copying file from "<solution-dir>\src\Engine.Core\DialoguePrototypeTestDB.s3db" to "bin\x86\Debug\DialoguePrototypeTestDB.s3db".
4>_CopyOutOfDateNestedContentItemsToOutputDirectory:
4>Skipping target "_CopyOutOfDateNestedContentItemsToOutputDirectory" because all output files are up-to-date with respect to the input files.
4>_CopyAppConfigFile:
4>Skipping target "_CopyAppConfigFile" because all output files are up-to-date with respect to the input files.
4>CopyFilesToOutputDirectory:
4>  Engine.Game -> <solution-dir>\src\Engine.Game\Engine.Game\bin\x86\Debug\Engine.Game.exe
4>IncrementalClean:
4>  Deleting file "<solution-dir>\src\Engine.Game\Engine.Game\bin\x86\Debug\circle.xnb".
4>  Deleting file "<solution-dir>\src\Engine.Game\Engine.Game\bin\x86\Debug\giroux.xnb".
4>  Deleting file "<solution-dir>\src\Engine.Game\Engine.Game\bin\x86\Debug\Body_Neutral.xnb".
4>  Deleting file "<solution-dir>\src\Engine.Game\Engine.Game\bin\x86\Debug\font.xnb".
4>
4>Build succeeded.
4>
4>Time Elapsed 00:00:01.72
========== Build: 4 succeeded, 0 failed, 1 up-to-date, 0 skipped ==========

```

I can't think of how build settings could change between consecutive executions. Like I said, this only happens for half our group. One member is on a 32-bit Windows 7 Prof bootcamp partition on a Mac. Everyone else, including those who don't have the issue, are running straight 64-bit Windows 7 Prof. Both have tried using VS 2010 and VS 2012.

Any insight would be greatly appreciated. Also, I can post more details upon request if this isn't thorough enough.

**EDIT 1:** Upon further investigation, all the files are going to the right place (Content/Whatever/File), but what's odd is that upon finishing the build, the Content directory is just deleted from the Editor output directory, but not the Game output directory.

**EDIT 2:** I built the Editor project again, which rebuilt all the content to the proper spot in the Editor output directory, but removed it from the Game output directory for some reason.

# Answer
I've had a similar problem recently. What worked for me was creating a separate build configuration for the editor. This config excludes building the main game project. The main game project excludes building the editor.

When I'm working on the editor I switch to that configuration in Visual Studio, and back to the main config when working on the game.

This is easy to do, and keeps the content from rebuilding every time.

Previously, with the editor and game both building, and both referencing the content project, the content would build every time, which was quite annoying.
> 1 votes

# Answer
I'm a relative beginner, but I read something about this recently. You mentioned consolidating content projects--the game and level editor developed over the course of the book *XNA 4.0 Game Development by Example* use two different (but identical) content projects; the author states that the reason for this is that XNA *just won't let you* have two projects reference the same content project unless they're targeting different platforms (PC and 360, etc). The author doesn't even attempt to explain why it doesn't work, unfortunately. This may be the source of your problems.
> 0 votes

# Answer
This is an *ooooold* question, but the problem can still occur with the current (3.6) version of MonoGame where the project content files are rebuilt every time you build the project. So changing a single line of code can result in a long delay when you test the project as all the content gets reimported...

The solution is to select the Content.mcgb file in the Visual Studio solution explorer pane to expose the properties for the pipeline tool. Change the "Build Action" to "None" - now the content will only be built when you manually start this in the pipeline tool.
> 0 votes

---
Tags: xna, xna-4.0, xna-content-pipeline
---


title: How to create bullet impact effects?

text:
# Question
Title: How to create bullet impact effects?
I'm creating a small fps and I don't know how to create a bullet impact effect. I have a muzzle flare and I have recasting set up but I don't know how to make a bullet impact effect. I've already tried working with the particle system prefab 'Flare' but nothing seems to work for me, please can someone help? **Soon Please**

# Answer
You're probably looking for a combination of the following concepts:

1. **Particle system** for the bullet hitting a surface (i.e. sparks on hitting metal, wood splints on hitting wood etc.)
2. **Decals** to allow projectiles to leave hit marks
> 5 votes

---
Tags: first-person-shooter
---


# Question
Title: How can I make a proxy server between a client and a server to analyise my packets
Otherhand how can i manipulate where the game client want to connect? I've built a python proxy server that can handle this proxy server, it is a basic thing that just: bind a server, wait till the client connect, and connect to the server, and send all data that have got from the client via this proxy, and send forward to the main server. And here is the problem that i not able to solve, the client don't want to connect to my proxy server. I modified my etc/hosts before, and i failed as well. Any idea to solve this problem?

# Answer
It seems that the address you are trying to define in your etc/hosts file is not the one that the game is going to connect to.

You should first find out what address the game is trying to connect. Install Wireshark or any other network packet sniffer, while it is running, start the game and then close it. Take a look at the Wireshark traffic and search for "DNS Queries" or filter the traffic using port number 53.

When you found that the exact address, define it in etc/hosts to point to 127.0.0.1, then verify with a ping command and then run the game...
> 0 votes

---
Tags: client-server
---


# Question
Title: Why can't this simple SDL app be closed without task manager or rapid clicking of x button?
I wrote a simple app that generates a window, a raster, and redraws the raster once every 16ms. Right now the calculations are empty, it just draws a solid color. I don't know how, but I have created a very resource hungry app that cannot be easily closed. I generally have to close it via the task manager.

Here is my SDL "wrapper" class. Below this class is what will eventually calculate a ray caster. I initially thought my call to SDL\_RenderDrawPoint for every pixel in the 600x600 window was causing the issue, but I still cannot close the window easily with that code commented out.

SDLWrapper.cpp

```
#include <iostream>
#include <SDL2/SDL.h>
#include <vector>
#include "include/SDLWrapper.h"

using namespace std;

#define TICK_INTERVAL 16

static int next_time;

SDLWrapper::SDLWrapper() {
}

int SDLWrapper::setupSDLRenderer(int WINDOW_WIDTH, vector<vector<RGB>> (*generateRaster)()){
    SDL_Event event;
    SDL_Renderer *renderer;
    SDL_Window *window;

SDL_Init(SDL_INIT_VIDEO);
SDL_CreateWindowAndRenderer(WINDOW_WIDTH, WINDOW_WIDTH, 0, &window, &renderer);
next_time = SDL_GetTicks() + TICK_INTERVAL;
while (1) {
    if (SDL_PollEvent(&event) && event.type == SDL_QUIT)
        break;

    SDL_RenderClear(renderer);

    rasterPixels = (*generateRaster)();
    for (int i = 0; i < rasterPixels.size(); ++i)
    {
        for (int j = 0; j < rasterPixels.at(i).size(); ++j)
        {
            SDL_SetRenderDrawColor(renderer,
            rasterPixels.at(i).at(j).R,
            rasterPixels.at(i).at(j).G,
            rasterPixels.at(i).at(j).B, 255);
            SDL_RenderDrawPoint(renderer, i, j);
        }
    }
    SDL_RenderPresent(renderer);

    SDL_Delay(time_left());
    next_time += TICK_INTERVAL;

}
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
SDL_Quit();
return EXIT_SUCCESS;
}

RGB SDLWrapper::peek(int x, int y){
    return rasterPixels.at(x).at(y);
}

void SDLWrapper::poke(int x, int y, RGB color) {
   rasterPixels[x][y] = ((RGB){color.R, color.G, color.B});
}

int SDLWrapper::time_left(void)
{
Uint32 now;

now = SDL_GetTicks();
if(next_time <= now)
    return 0;
else
    return next_time - now;
}

```

RayCaster1.cpp

```
#include "include/SDLWrapper.h"
#include <iostream>
#include <vector>

#define WINDOW_WIDTH 600

#define mapWidth 24
#define mapHeight 24

vector<vector<RGB>> rasterPixels;

vector<vector<RGB>> generateRaster(){
      RGB greenPixel;
      greenPixel.R = 255;
      greenPixel.G = 255;
      greenPixel.B = 255;

      for(int i = 0; i < WINDOW_WIDTH; i++) {
          vector<RGB> column;

          for(int j = 0; j < WINDOW_WIDTH; j++){
              column.push_back(greenPixel);
          }

          rasterPixels.push_back(column);
      }

  return rasterPixels;
}

int main(int /*argc*/, char */*argv*/[])
{
    double posX = 22, posY = 12;  //x and y start position
    double dirX = -1, dirY = 0; //initial direction vector
    double planeX = 0, planeY = 0.66; //the 2d raycaster version of camera plane

    SDLWrapper sdlWrapper;
    sdlWrapper.setupSDLRenderer(WINDOW_WIDTH, generateRaster);
}

```

# Answer
Your event loop looks ill-formed, as it will only process one event per frame. Here's what it probably should look like:

```
SDL_Event e;
while (SDL_PollEvent(&e)) {
    if (e.type == SDL_QUIT) run = false;
}

```

And then change your mainloop to depend on `run`.
> 5 votes

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


# Question
Title: How can I make an update patch for a Unity game on Windows?
I ran into trouble making a PC game using Unity.

If I try to update my game, I can't a update the C# scripts (because AssetBundles don't include C# scripts)

So I think I'll need to use a server and patch all files.

But I don't know how to do so...

How can I make an update for my Windows game?

# Answer
> 6 votes
Specifically for Unity, you're correct that AssetBundles cannot update script code. You can use bundles for updating *data*, but any actual code changes will require a new version of the main game .exe to be installed. This can be an even bigger problem on non-desktop platforms, as releasing a new executable version on platforms like iOS can take a lot of time waiting for approval and release.

For that reason, it is often *highly* beneficial to make your game as data-driven as possible. The less you have to update code, the better. Prefer configuration in assets that you *can* put into bundles to drive a generic codebase, rather than having to patch the code itself.

The rest of this answer is not Unity-specific but tailored more to the specific ask of auto-updating games on Windows. :)

Auto-updating applications is a relatively non-trivial operation. Dealing with permissions correctly is non-obvious, actually writing all the server infrastructure to distribute updates is tricky, and auto-updating requires some tricks.

Permissions makes it difficult for an updater on Windows to install updates to `C:\Program Files\` without administrator privileges, which your game itself won't have. Some apps thus install to `%LOCALAPPDATA%` instead, or have to rely on an external updater utility that *does* have administrator privileges. Some users will refuse to play your game if it *does* require administrator privileges (even for updates) because they don't trust random game developers to get this stuff right (without opening their systems up to massive security holes).

Auto-updating in Windows is also tricky because you cannot (easily) replace a running binary or DLL. An updater effectively needs to either spawn an installer binary and exit itself (and let the installer do all the Windows update work), or it has to run itself from a temporary location so that it can freely modify its installation location.

A tool like NSIS or InnoSetup can be used to create the installers, and I believe both of those make it easy to create installers that install to a location in `%LOCALAPPDATA%`.

However, if you add in the detection of updates, the download of new installers, verification (to make sure your update CDN isn't being hijacked!), and so on and you've got a lot of work on your hands.

By far, your best bet is to distribute on existing store platform. Windows Store, Steam, GOG, Epic Games Store, or one of the bazillion others (including some popular in non-Western regions of the world; I'm not myself familiar with those markets, though, so I don't know all the offerings).

Using an established store lets all the heavy-lifting of update distribution be handled by someone else. It lets the store handle detecting and installing updates. It absolves you of needing players' trust as the store app is the only software that requires administrator privileges. There's of course also the benefits in terms of exposure, sales, community, and so on, but with the downside of incurring some fiscal cost.

That said, there are some third-party tools that could help out. Squirrel for example is a .NET suite for creating auto-updating application (using Nuget, iirc, though it claims it works for native C++ applications, too), for example. It includes logic for multiple platforms (Windows, Mac, iOS) and includes a server-side component you'll have to host and configure. It may not be the right tool for this job, but it illustrates the necessary code for addressing the technical challenges I outlined above.

TL;DR: avoid requiring code changes as much as you possibly can; use an existing store or distribution channel to handle updates when you must; and be wary of the great complexity of auto-updates if you still want to roll your own.

---
Tags: unity, windows, patching, assetbundle
---


# Question
Title: Why are not the images loaded in Phaser?
I am starting to use phaser to create games and I found a problem that I can not find for more tests that I did. I can not show the images I am uploading. You only see a small square in the center, (I show it in this capture: when you should see the entire background of the canvas in green, which is the image that first charge. In the example I only charge one, so that more if it does not work. I do not see what error I'm committing, because the navigator inspector does not show errors. The server is created with Node.js.

```
const http = require('http')
const fs = require('fs')

const server = http.createServer((req, res) => {
    fs.readFile("./part1.html", (err, data) => {
        if(err){console.error(err); return;}
        res.end(data)
    })
})
console.log('escuchando en el puerto 3000')
server.listen(3000)

```

I show the code for if someone can see the error that I am committing. Thank you.

***I EDIT the question:***

I add the code that I should add first. The project is in a folder called Game. Here is the file server.js and package.json There is also a folder called public where the html code and images are located. I show you the code.

```
<!doctype html>
<html lang="es">

<head>
 <meta charset="UTF-8" />
 <title>Primer juego en Phaser</title>
 <script src="//cdn.jsdelivr.net/npm/phaser@3.11.0/dist/phaser.js"></script>
 <style type="text/css">
  body {
   margin: 0;
  }
 </style>
</head>
<body>
 <script type="text/javascript">

  var config = {
   type: Phaser.AUTO,
   width: 800,
   height: 600,
   scene: {
    preload: preload,
    create: create,
    update: update
   }
  };

  var game = new Phaser.Game(config);

  function preload() {
   this.load.image('sky', 'sky.png')
   this.load.image('sky', 'assets/sky.png');
         this.load.image('ground', 'assets/platform.png');
         this.load.image('star', 'assets/star.png');
         this.load.image('bomb', 'assets/bomb.png');
         this.load.spritesheet('dude', 'assets/dude.png', {         frameWidth: 32, frameHeight: 48 });

  }

  function create() {
   this.add.image(400, 300, 'sky')
  }

  function update() {
  }

 </script>
</body>
</html>
```

# Answer
I tested your Phaser Javascript code and it works fine. So I'm thinking it's a problem with how you've set up your server. Look up Express.js, its an NPM module that makes it really easy to set up Nodejs servers. If you want to continue using the more bare-bones http, then make sure you're using fs and that callback function properly, I don't know enough about it myself.

I will also say you should avoid loading images using the same key, I see you've used the key "sky" two image files.
> 2 votes

---
Tags: javascript, phaser, node.js
---


# Question
Title: How can I make outline shader like "Life is Strange"?
I want to make sketch shader like life strange.

shader has two part:

1.animated dashed line

2.noisy outline

I like to know how can I make noisy outline?

see outline of objects

First I tried to make outline by copying of incoming vertex data and scaled according to normal direction then Cull Back.but I think it's something like Image effect because outline sometimes move inside of object. anyway I will appreciate if someone help me to Implement this shader :)

# What I tried

I used edge detection and animate it by vertex shader but this isn't good like above gifs.

# Answer
> 1 votes
I've done something similar in Unreal Engine 4, so I'm going to explain just the concepts. There are 2 ways you can do that, and they are different gradients of tradeoffs between performance and ease of implementation.

1. First, add a new mesh on top of the main mesh, just a little bigger (just like a physical collider mesh). Then create a transparent material shader for it and enable the shader/show the mesh as the player's view frustum is within x distance units from the entity. This is performance heavy because of the transparency shader, but since you only have a small set of objects highlighted at a certain point, it is easy to implement and feasible.
2. Create a base texture with the hash lines, and displace the texture coordinates according to a pre-determined set of matrices. This creates the illusion of "animated textures"; in the industry, it is also called a dynamic material (there's more to it, but you can read up if you want to). As for the outline, you can find plenty of tutorials on the web. This technique takes significantly more time to implement, since you have to tinker with the displacement matrices and the material update time to get a result similar to the above screenshots, not to mention having to allign the hash lines on angle changes in the base mesh.

If performance is not an issue, go with 1. If every FPS counts, use 2, but expect a lot of issues that take time to solve.

---
Tags: unity, shaders, hlsl
---


# Question
Title: Standard Asset package import in unity 2018.3
I am using iMac, I don't see any for import standard package in unity. My working project need to import standard packages. I use unity version unity 2018.3.0f2. Please guide me from where I get the unity standard asset package.

Thanks.

# Answer
Yet now in a new release of unity for mac, default Standard Asset Package removed. if a user wants to download it will available in Unity Asset Store.
> 1 votes

---
Tags: unity
---


# Question
Title: How to keep consistent between image quality, device range support and final size of the game?
I am developing a game with the LibGdx framework, but I would like to discuss a more theoretical question.

Criteria:

1. I want to support as many devices as possible for my game (phones and tablets)
2. I want to see the same image quality for each device (it is a different topic about scaling or aspect ratio)
3. I want my game to not freeze (support devices with a low amount of RAM).
4. I want to make my game as small as possible.

For example, let's take a look at the Samsung Galaxy Tab S4 10.5. It has a resolution of 2560x1600.

If I take this resolution as standard, and make all other textures dependent on this background resolution, it will make a huge size for images. Also, It won't work on slower and older devices with small resolution. (800x480, etc). So it does not satisfy criteria #1, #2 and #3.

I suppose I can make different quality versions of the same images for different devices. It may affect only the #4 criteria, but it's not as critical as others.

What strategies do you guys use to satisfy the above criteria?

# Answer
There's not perfect answer that cover everything you've asked for. However I have some tips that can help.

* If you are focusing on Android, you can upload images of different sizes for different screen densities. This ensures that images display with **roughly** the same quality/size without any blurriness. This also means that a small-screen phone will load the smaller asset, requiring less memory (RAM). You can read more on Android Developers - Support different screen sizes.
* To support multiple screen sizes, simply make sure that when placing assets on the screen, you don't use absolute pixels. So if you want a button on the right side of the screen, do not set it on pixel `470`, set it on pixel `SCREEN_WIDTH -10` (assuming `10` is the desired padding). This ensures the button will be on the right side of the screen regardless of screen size.
* Unfortunately for android, if you support small screens and bigger screens, you will need separate assets. When the game is installed on a small-screen device, it will also install the assets for the bigger screen. As far as I understand, that's in case you plan to connect your phone on a bigger screen, it will user bigger assets. That means if you decide to support a massive screen (TV?) with 4k quality, and big density, you will need big assets, which contribute to the installation size even on smaller devices.
* If you want to support older android versions, if your app doesn't use any new feature, there is no reason to declare in your manifest that you only support the latest version. For most games, the only thing they do is draw pixels on the screen, which the oldest android versions could do as well. If you want to have optional new features, make sure you check it in the code, something like `if (supports_notifications) { showNotification(); }`. This ensures your game runs on most android versions.
* If you have an asset that has a simple shape, take a look at Android Developers - Add multi-density vector graphics. The idea is basically you describe an asset using vector graphics, and it works on all device sizes/densities. I made a simplistic game in the past using this technique, that was less than 500kb in size. Keep in mind that really complex assets might take longer to load using this method.
* For background, you can't have an image that is exactly the size of the screen. I mean, you can, but you'd need 100+ different assets, each customised for each screen, but that's just very wasteful. There are many techniques to handle that, you can for example make a background image that is big enough, but has an internal "safe zone", that is a rectangle that everything inside it will be shown no matter what. Then when placing the background, make sure you resize it, so that at least one side of the safe zone touches one side of the screen, and the other side is bigger than the screen. This means some pixels of your image will never be shown, but that the whole screen is constantly filled. Alternatively you can fit the image to the background with some black border either on top and bottom or left and right, depending on the screen's aspect ratio. The only link I could find relevant to this is V-Play Engine - How to create mobile games for different screen sizes and resolutions. It explains in details what I mean, in a way that can be used on any project.

Unfortunately you can't have both support for most devices and small game size. But I've followed these tips in the past and made games smaller than 2MB, that are still running on modern versions and support a lot of old android versions.
> 2 votes

---
Tags: libgdx, architecture, image, resolution
---