# Question
Title: Approximating off-screen action efficiently in a simulation game?
I have a character building constructs all over a pretty large map. My game blends elements of RTS and fast paced action in a room-based environment where players can only see one room at a time.

I would like to be able to do physics simulation, projectiles and high frame rates in the room the player is in, while also maintaining a significant number of AIs (a few thousand, maybe) wrecking all the buildings that the player has created in other rooms. I want their behavior to be approximately consistent with what they'd do in front of the player.

I have a few ideas I could use feedback on, but I'm mostly wondering what creative approaches are out there and where I can read about this kind of architectural problem (must be common for complicated RTS games)

My ideas:

* Avoid particles, projectiles, turn off anything that's un-needed for non-visual simulation
* Switch all offscreen objects to "offscreenSim" versions of expensive components or somehow switch from running their `Update()` methods to running a `SlowUpdate()` method
* `SlowUpdate` would run in another thread and do the same thing as `Update`, except it would be called less often with much longer deltaTimes. Maybe some semaphore would throttle them to share a fixed total pool of worktime allowance per second.
    + i.e. the more objects in the simulation, the longer between SlowUpdates.
    + They'd also probably need to use path-intersection based triggers instead of collisions, since they'd be at risk of skipping through normal sized colliders.
* Or.... Maybe I could recreate a completely simplified graph representation of rooms and their inhabitants and just say "there's a path for enemies to go between A-\>B-\>C, there's a turret in B, here's a formula for enemy damage/turret and turret damage/enemy."
    + This approach seems like it could save a lot of performance, but making two simulations deterministically consistent, plus translating between both representations sounds like a major headache (though maybe players wouldn't notice inconsistency)
* Separate the world into clusters of rooms and leave clusters the player isn't in totally inactive. When a player goes between rooms, run the entire simulation of the cluster they're entering up to that moment in time at 10x speed while showing them a loading screen (I'd worry about keeping them on a loading screen for too long)

# Answer
> 0 votes
What @DMGeorgory said shows that your first three ideas are in fact the *complete* way. now in case you were also looking for a *time-affordable* way, you could record every important variable, make a simple graph with maybe length of 4 ( or less ) , then create the next value in a way that makes sense to the record. if for example the array `val_rec[]` is the record for `float val`, you can get the next value for `val` like below:

```
float maxRand = 4+3+2+1; // because record is length of 4
float rand = Random(0, maxRand);
float next;
if(rand < 4)
{
    rand -= 4;
    next = Random(-val_rec[3]/10, val_rec[3]); // the [3] means 4th element, considering that is the latest record, so it has more chance than other records
}
else if(rand < 3)
{
    rand -= 3;
    next = Random(-val_rec[2]/10, val_rec[2]); // the second latest record
}
else if(rand < 2)
{
    rand -= 2;
    next = Random(-val_rec[1]/10, val_rec[1]); // the third latest record
}
else
{
    next = Random(-val_rec[0]/10, val_rec[0]); // the eldest recodrd. least worthy
}
val = next;

```

and of course you could check different values for your own system and see what works best :D

cheers.

---
Tags: ai, performance, simulations, rts
---


title: A way to test different DPI's in Unity?

text:
# Question
Title: A way to test different DPI's in Unity?
Is there a way to force a Unity canvas set to "Constant Physical Size" to scale based on an arbitrary DPI value for testing purposes? It seems to only respond to the meta-data from the display, if it has any.

Quite annoying because I'd have to use an actual device simulator to see how it will look on displays with different dpi's.

Thanks

# Answer
> 2 votes
Never mind! I have since discovered the built in device simulator.

On 2020 onward you can install it through the package manager, but you have to enable "preview packages" in project settings -\> package manager. After which it will be available as a toggle in the top left of the game window, or as a separate window.

On 2021 onward I believe it comes installed as standard.

---
Tags: unity, unity-ui
---


# Question
Title: Does setting the alpha of a UI canvas group to 0 stop Unity from wasting resources rendering it? Is this a valid optimization for off screen UI?
I am trying to improve the efficiency of a big UI Scroll View in my Unity app. These Scroll Views tend to be inefficient and can be prone to jittery/stuttering motion if they are taxed.

I came across the following thread on Scroll Rect efficiency: https://stackoverflow.com/questions/53005040/what-i-have-learned-about-unity-scrollrect-scrollview-optimization-performan

One suggestion they make to put a canvas group on all elements within the scroll view and use a script to manipulate their opacity to make them transparent if they are not visible. I presume you would run on all elements every time the scroll content shifts (the window scrolls):

```
using UnityEngine;
using UnityEngine.UI;

public class ScrollHider : MonoBehaviour {
    static public float contentTop;
    static public float contentBottom;

    static public bool HideObject(GameObject givenObject, CanvasGroup canvasGroup, float givenPosition, float givenHeight) {
        if ((Mathf.Abs(givenPosition) + givenHeight > contentTop && Mathf.Abs(givenPosition) + givenHeight < contentBottom) || (Mathf.Abs(givenPosition) > contentTop && Mathf.Abs(givenPosition) < contentBottom)) {
            if (canvasGroup.alpha != 1) {
                canvasGroup.alpha = 1;
            }
            return true;
        } else {
            if (canvasGroup.alpha != 0) {
                canvasGroup.alpha = 0;
            }
            return false;
        }
    }

    static public void Setup(Scroll givenScroll) {
        contentTop = (1 - givenScroll.verticalNormalizedPosition) * (givenScroll.content.rect.height - givenScroll.viewport.rect.height);
        contentBottom = contentTop + givenScroll.viewport.rect.height;
    }
}

```

What's strange to me is a few things:

1. Does setting the canvas group opacity to zero stop it from being rendered, or is it still rendered transparently and thus there is no actual benefit to this?
2. Let's say your scroll view is for a SMS style chat window and you have 50-100 bubbles in it. Would running this script on every bubble every single time the content window scrolls a pixel be any more or less expensive than just leaving the bubbles there to render even if "off screen"?

I am curious if this is truly a viable optimization. Does it do anything at all? And even if it does, are you just trading one cost for another?

Thanks.

# Answer
There are other things going on in a canvas/UI other than rendering, such as re-organizing layouts and so on. So especially if things keep changing and happening in the UI, you may want to disable it altogether rather than setting the alpha to 0.
> 1 votes

---
Tags: unity, optimization, efficiency, user-interface
---


# Question
Title: How to program different types of monsters
I'm working with a group of programmers and I'm trying to program different types of monsters in Unity. I want to make it so that all the monsters have values like attack power, attack speed, moving speed, etc, and basic functions like attack or walk.

Normally, if I wanted to do this in Java, I would just create one class called Monster and make child classes for each of the different types, but I'm not sure how to do this in Unity, since Unity c# uses Monobehavior and you have to attach scripts to a game object.

To go into more detail, I want to instantiate different monster types at random. I would have prefabs like slime, skeleton, etc with their corresponding scripts, and instantiate them randomly. And for each of these instantiated monsters, I want them to immediately move and attack according to its type's (slime, skeleton, ...) attack speed, attack power, etc.

How could I achieve this? As in, how would professional game developers organize their code in this situation? I'm looking for basic directions like: create this class, attach this script to this prefab, etc; I could look up the details on my own, and I just need simple guidelines.

# Answer
This is how I would do it:

* All the parameters are configured in a data file (JSON, XML) or ScriptableObject if you prefer. This data file will have a list of all enemies, and for each enemy parameters like - prefab name, damage, health, speed, etc.
* A single animator that has the state machine that fits all enemies, then an AnimatorOverrideController for each specific enemy prefab, that assigns the enemy's specific animations.
* A base enemy script that all enemies use. If for some reason you need a specific script for specific enemies (in most cases I don't think this should be necessary, see below), they can inherit from the base enemy script and add to it.
* The code then instantiates prefabs based on the parameters configured in the data files, and activates animations using the same variables for all enemies (since they share a state machine, only the actual animations are overridden).
* The data file can configure additional stuff like - what types of behavior the enemy has, and then the script can check that configuration and decide what actions to perform. If some enemies are missing actions (say static enemies that can't move), they can still use the same infrastructure and script as all other enemies, but will not execute the move commands.
* If you have significantly different AI for each enemy and you want them in separate scripts, you can simply add different scripts to the prefab (all inheriting from a base AI class). Alternatively you can add the AI script in real-time using reflection, if you specify which AI each enemy has in the data file. The latter is preferred by me because it lets you control enemy behavior directly from the data file without having to open prefabs.
> 1 votes

# Answer
## Prefab management

Unity can do inheritance of game objects by using prefab variants. A prefab variant inherits all the components and sub-objects from its original. When you change the original, then all the variants get changed too. But you can add additional components and sub-objects to the variants and you can override individual properties from the parent by changing them in the variant.

That means you can create on generic "Enemy" prefab which has everything all enemies have in common, and then create multiple variant prefabs inheriting from it which represent more specialized enemies. When you now do a change to the generic enemy, then that change gets automatically applied to all the enemies (unless that enemy overrides that specific property).

## Spawning

When you have spawners which are supposed to spawn enemies randomly, then you can give it a `public GameObject[] enemyPrefabs` (or `[SerializeField] private GameObject[] enemyPrefabs` if you want to be thorough). You can then maintain the palette of enemies in the editor. At runtime, the spawner would then pick from that palette of prefabs.

You might perhaps want some enemies to spawn more frequently than others. You can do that with multiple spawners with different settings. For example, when you want more zombies than skeletons, you can have one spawner which spawns skeletons and zombies, and another which spawns only zombies. Or you can do that using the techniques from the question "How do I create a weighted collection and then pick a random element from it?".

## Code architecture

On the script side, Unity's software architecture is based on the principle of Composition over Inheritance. Which means that instead of having one abstract base class "Enemy" with other more specialized inheriting classes, you usually have multiple classes which each implement one mechanic and which can be mixed and matched to create new enemies with very little effort.

For example, when you have enemies which move, enemies which attack and enemies which do both, then you create two MonoBehaviours "Attacker" and "Mover". Each enemy might have the first, the second or both behaviours. Enemy-specific details (How fast does it move? How strong does it hit?) can then be configured via serialized fields on those behaviours.

If you want to add some unique enemy-specific programming to control *where* these enemies moves and *when* they attack, then you can add a separate controller script to each prefab which makes high-level decisions, but references the "Attacker" and "Mover" components on the same game object (via `GetComponent<T>()`) and delegates the low level execution of those decisions to them by calling public methods.

One great advantage of this architecture is that it allows you to experiment in the editor. You can add and remove components and experiment with values without having to switch back to the IDE. For example, you can see how enemy A works if you give it the controller script of enemy B. Or if it is still challenging if you take away its Mover component, turning it into a stationary enemy. You can in many cases even perform such experiments while the game is running in the editor.
> 0 votes

---
Tags: unity, c#, software-engineering
---


# Question
Title: How can i rotate gameobjects back from mirror?
For some reason when i create the gameobjects they are places like mirror. And i'm not sure how to rotate them back.

```
for (int i = 0; i < pointsList.Count; i++)
        {
            GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
            cube.transform.parent = transform;
            cube.transform.position = new Vector3(pointsList[i].Y, 0, pointsList[i].X);
        }

```

pointsList is a List For example in index 4 X = 3 Y = 17

But i'm not sure why it's creating the objects mirrored. And how to rotate it back.

In the screenshot it should be written Hello World but it looks mirror. The empty GameObject rotation is 0,0,0 and each child Cube rotation also 0,0,0

# Answer
> 1 votes
It's probably your camera which is wrong.

You probably have your camera placed in a positive z-position pointing in the direction of the negative z-axis. So every new object you place is viewed "from behind". The solution would be to place your camera at a negative z-position and having it face parallel to the z-axis of the scene.

However, if you have a really good reason to composition your scene like this and changing it now would be inconvenient, then I would recommend you to create a prefab "Text" and create all other texts in your game either as instances of that prefab or as prefab-variants of that prefab. That way any change you do to the master "Text" prefab will be applied to all the texts in the game, including changing the rotation. This method also has another great advantage: If you want to try different text styles (font, color, size, etc) you just need to change the basic text prefab and it will automatically be applied to all the texts in the game.

When I design UIs then I usually do that with all the basic UI elements. It makes it a lot easier to retroactively experiment with the visual theme of the game after the UI is already built. Want to try a different design for the buttons? Just change the sprite of the master "Button" prefab and all the buttons in the game now look like that.

# Answer
> 0 votes
Solution: Either to change each cube position by adding minus to the X the Z axis: `cube.transform.position = new Vector3(pointsList[i].Y, 0, -pointsList[i].X);` or to rotate the parent GameObject by -180 like this `transform.Rotate(0, 0, -180);`

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


# Question
Title: Editor-only MonoBehaviour (not GameObject)
I'm well aware of the `EditorOnly` tag on game objects. However, my question is slightly different:

I have a large number of game objects in my scene that only mark a spot; i.e. I only care about their transform (position). I use a simple `OnDrawGizmos` script on them simply to have them visible in the editor.

I would like that script to not be exported into the build. It does nothing I need in the build, it is only useful for the editor.

My current workaround is to have it on a child game object that is set to `EditorOnly`, but that's kind of a hack and forces more workarounds in other parts of the code (that assign children to those marker points in-game, etc.)

Is there a way to mark a **script** as "editor-only" in Unity?

# Answer
You can wrap your whole class in an `#if UNITY_EDITOR` preprocessor directive so that in a build it compiles to an empty file, like this:

```
#if UNITY_EDITOR
using UnityEngine;

public class EditorMarker : MonoBehaviour
{
    private void OnDrawGizmos() {
        Gizmos.DrawWireSphere(transform.position, 1);
    }
}
#endif

```

This will still attach a component to the object at runtime, but it will be a `null` component with no stored data, no behaviours, no message hooks.

---

Though for the specific use case of making invisible objects visible in-editor, another alternative you may want to consider is doing away with your `OnDrawGizmos` script entirely, and using Unity's built-in icon system:

By clicking on the icon to the left of a game object's name, you can select a label or icon style to use for that object, including a selection of built-in options, or you can assign a custom sprite of your own creation.

These icons are visible in the Scene view, but are not shown in the built executable, so you don't need to make a custom script that excludes itself from builds.

You can also assign these icons through script, if you want to avoid manual setup steps or creating prefabs for each kind of marker object.
> 3 votes

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


# Question
Title: Each time a new platform spawns, rotate it 90 degrees from the previous
All I want is when the platform changes its position on the x or the z axis, then rotate the whole platform by 90 degrees.

When I try to do this with the following code, I don't see any change - the new platform always has the same rotation, no matter which of the two rotation methods below I use.

```
public GameObject platform;
public Transform lastPlatform;
Vector3 lastPosition;
Vector3 newPos;
bool stop;

private Quaternion rotationQuaternion;

void Start()
{
    lastPosition = lastPlatform.position;
    StartCoroutine(SpawnPlatforms());

    rotationQuaternion = transform.rotation;
}

IEnumerator SpawnPlatforms()
{
    while (!stop)
    {
        GeneratePosition();

        Instantiate(platform, newPos, rotationQuaternion * Quaternion.identity);

        lastPosition = newPos;

        yield return new WaitForSeconds(0.1f);
    }
}

void GeneratePosition()
{
    newPos = lastPosition;

    int rand = Random.Range(0, 2);

    if (rand > 0)
    {
        newPos.x += 1.5f;
        // One way I tried - no visible effect.
        transform.rotation = rotationQuaternion * Quaternion.Euler(0, 90, 0);
    }
    else
    {
        newPos.z += 1.5f;
        // Another way I tried - also no visible effect.
        platform.transform.Rotate(0, 90, 0);
    }
}

```

I appreciate all the help!

# Answer
> 0 votes
Myself, I'd be inclined to bundle up information and behaviour for your "spawning cursor" into its own type, something like this:

```
[System.Serializable]
public struct SpawnPoint {
    public Vector3 position;
    public Quaternion orientation;

    public void Step(float distance) {
        if (Random.value < 0.5) {
            position.x += distance;
        } else {
            position.z += distance;
        }

        orientation = Quaternion.Euler(0, 90, 0) * orientation;
    }
}

```

Then you can set aside a single member variable to hold that cursor's state:

```
SpawnPoint _spawn;

```

Initialize it at startup:

```
void Start() {
    _spawn.position = lastPlatform.position;
    _spawn.orientation = transform.rotation;
}

```

Then, when you want to spawn a platform, step your cursor, and spawn at the cursor:

```
IEnumerator SpawnPlatforms()
{
    while (!stop)
    {
        _spawn.Step(1.5f);

        var newPlatform = Instantiate(platform, _spawn.position, _spawn.orientation);

        yield return new WaitForSeconds(0.1f);
    }
}

```

The reason your approach wasn't working before was because you were always passing the same rotation to `Instantiate` method:

```
Instantiate(platform, newPos, rotationQuaternion * Quaternion.identity);

```

`rotationQuaternion` is only ever assigned once, in the `Start()` method, so for every subsequent execution of this line, it will always have the same value - no matter how you've changed `transform.rotation` or `platform.rotation` in the meantime.

This would be very easy to see if you used a `Debug.Log(rotationQuaternion)` or set a breakpoint to examine the value of the variable during execution, so be sure not to skip those steps when debugging your code!

---
Tags: unity, c#, rotation, transformation
---


# Question
Title: How would you structure a CSV file to load level data for a Match3 puzzle game
Am facing a bit of a problem regarding the structure of a CSV file that will be used to generate levels in a match3 game, my in-engine data structure is the following:

```
  LevelGoal(LevelGoalType type, int colorIndex, int target)

```

so that is a **single goal** in a level, and a level is composed of **multiple goals**, and the number of goals in a single level is not fixed, so some levels can have 3 goals, and other can have 4 (see image below). Am wondering if there is a "common way" to setup the CSV file so it supports this feature, currently the only solution i could think of is to actually include the LevelIndex in the CSV and use that to create the data in game, but maybe there is a better "standarized" way since people have been making Match3 games for ages.

Thanks!

**Edit:**

another solution am thinking of is to have all the goals no matter what, but if the target is 0 then the game won't show that that goal:

**EDIT2:**

I marked @DMGregory answer as the solution because it ended up being the closest one to what the client and my puzzle-expert friend told me, check the image below to see the final version of the table, it turns out that the main priority for game designers is to have **1 row per level**, ideally the "GoalType" could've been a string and we can add rules to the spreadsheet so that the string can never have a typo, their initial suggestion was exactly what @DMGregory suggested, but after talking with the designer we chose this solution instead, plus parsing wise, it's easier for me to have one column per "object", with that said, they also told me that this kind of workflow is only used in prototypes, if the game get the greenlight then the devs will end up creating a Level editor, and will probably never deal with CSV again and save it all as JSON (or binary if your boss is insane)

Thank you all!

# Answer
> 1 votes
If you don't like multiple rows per level, you could structure your data like this...

| Level | Goal 1 Type | Goal 1 Colour | Goal 1 Target | Goal 2 Type | Goal 2 Colour | Goal 2 Target | Goal 3... |
| --- | --- | --- | --- | --- | --- | --- | --- |
| 1 | 0 | 1 | 10 | 0 | 2 | 6 | 0 |
| 2 | 0 | 1 | 5 | 0 | 2 | 8 | 1 |
| 3 | 0 | 3 | 7 |  |  |  |  |

Note that your rows don't all need the same number of cells. A parser can then read triplets of cells to form each goal, until it hits the end of the line and moves on to the next level, something like this:

(Though you'd likely want to include more error checking and helpful debug messages than what I've shown here)

```
var rows = csv.text.Split("\n");
foreach (var row in rows) {
    var cells = row.Split(",");
    int level = int.Parse(cells[0]);

    var goals = new List<Goal>();

    for (int i = 1; i < cells.Length; i+=3) {
        Goal goal = default;
        goal.type = goalTypes[int.Parse(cells[i])];
        goal.colour = colours[int.Parse(cells[i+1])];
        goal.target = int.Parse(cells[i+2]);
        goals.Add(goal);
    }

    levelGoals[level] = goals;
}

```

The downside of this is that now similar data about your goals is spread across many columns. So if you were authoring this data in a spreadsheet tool like Excel or Google Sheets, and you wanted to answer questions like "How well balanced are our goals across the different colours?" you'd have to aggregate data from multiple columns to do that.

If that's a use case you care about, then I'd suggest your existing data format is actually superior to this one, even with its redundancy.

You could slightly reduce the redundancy by omitting the level number when it's the same as the row above, though it doesn't save any significant amount, and I'd argue the types of balancing calculations you might want to do are easier if the data is there, redundant or no.

# Answer
> 0 votes
The CSV format does not support hierarchical data very well. When your data format requires more complexity than a simple table, then you might want to switch to a more advanced markup language which supports nested objects and arrays. Like JSON, for example.

```
levels: [
    { index: 1,
      goals: [
          { type: 0, color: 1, target: 10 },
          { type: 0, color: 3, target: 7 }
      ]
    },
    { index: 2,
      goals: [
          { type: 0, color: 1, target: 8 },
          { type: 1, color: 2, target: 9 },
          { type: 1, color: 3, target: 10 },
          { type: 0, color: 4, target: 10 }
      ]
    }
]

```

You might now wonder "How the heck am I supposed to parse that?". Don't worry, there are plenty of libraries available for parsing JSON and converting it to internal object representations. There is very likely also one available for your programming language of choice.

---
Tags: data-structure, puzzle
---


# Question
Title: LookRotation function for Z-up, right handed system
I am rendering graphics myself using OpenGL, therefore I need to implement math library myself. I am looking for function `Quaternion::LookRotation(forward, up)`, given a forward and up vector, it shall create a quaternion rotating in this direction.

I've found this answer http://answers.unity3d.com/questions/467614/what-is-the-source-code-of-quaternionlookrotation.html for LookRotation and it works well providing we are using Unity's coordinate system (left handed): Forward: `(0, 0, 1)`, Up: `(0, 1, 0)`, Right `(1, 0, 0)`.

In this coordinate system the function works as expected:

```
var dir = new Vector3(1, 0, 1).normalized;
var quaternion = Quaternion.LookRotation(dir, Vector3.Up); // Up == (0, 1, 0)
var backToDirection = quaternion * Vector3.Forward; // Forward == (0, 0, 1)
// backToDirection equals to dir

```

However, in my "engine", I am using **right handed, Z-up** coordinate system: Forward: `(1, 0, 0)`, Up: `(0, 0, 1)`, Right: `(0, -1, 0)`.

Unless I am wrong, the very same code (with corrected LookRotation) should still work:

```
var dir = new Vector3(1, 0, 1).normalized;
var quaternion = Quaternion.LookRotation(dir, Vector3.Up); // new Up == (0, 0, 1)
var backToDirection = quaternion * Vector3.Forward; // new Forward == (1, 0, 0)
// backToDirection should be equal to dir, but obviously `LookRotation` needs to be changed

```

However, for this to work, `LookRotation` needs to be adjusted accordingly. The source code for `LookRotation` posted at answers.unity3d doesn't explain *why*, neither I could find a good explanation *how to do it*. Could anyone give me a hint what needs to be changed there in order to make it work in a different coordinate system?

# Answer
> 3 votes
First, we can transform your coordinates into Unity's coordinates:

```
Quaternion LookRotation(Vector3 myForward, Vector3 myUp) {

    var uForward = new Vector3(-myForward.y, myForward.z, myForward.x);
    var uUp      = new Vector3(-     myUp.y,      myUp.z,      myUp.x);

```

...then we can invoke the Unity code, unchanged:

```
    var uQuaternion = UnityLookRotation(uForward, uUp);

```

...then transform the resulting quaternion back into your coordinate system. That means remapping the axes to match yours, and negating the angle since we're now rotating in a right-handed instead of left-handed scheme.

Since the xyz components are just a unit vector along the axis of rotation times the sine of half the angle, and the w component is the cosine of half the angle, that gives us:

```
    var myQuaternion = new Quaternion(
        -uQuaternion.z, // Our +x is Unity's +z, and we negate the angle
         uQuaternion.x, // Our +y is Unity's -x, and we negate the angle
        -uQuaternion.y, // Our +z is Unity's +y, and we negate the angle
         uQuaternion.w  // cosine(angle) = cosine(-angle), so w remains
    );

    return myQuaternion;
}

```

This should work out of the box, and we can leave it for the compiler to inline and optimize it for us. Or, you can go through the steps of propagating the subscript and sign changes through the Unity method so that it bakes-in the effect of these transformations for you.

---
Tags: rotation, quaternion, coordinates
---


# Question
Title: How can I discourage camping while still supporting a "sniper" style of play?
I am trying to add features into a third person shooter that suit a sniper style of play, in addition to the current rush/deathmatch style it was designed for. The current gameplay is similar in style to Gears of War and Battlefield, perhaps similar to Call of Duty in terms of combat ranges but a little slower paced. The levels are similar in size to large COD maps, or medium Battlefield maps.

Two things which I was planning to add includes some long sight lines and also some "sniper nests". I am concerned though because these two features can open the door to a lot of camping. Sniping and camping are not the same things in my opinion, but it can be easy for campers to abuse such features for easy gain, when they were intended to promote tactical sniper use. That said, I don't believe in blaming the flaws of a game on a player's choice of play style.

**Sniper**: Uses long range rifles, may stay in a specific spot that is tactically advantageous at the time, but knows how to move to other locations good for sniping. Provides spotting and suppression for more offensive/rush style team members.

**Camper**: May use any weapon, always stays in the one spot and waits for players to pass by, leading to easy low risk kills. Follows the same strategy regardless of what is happening in the game/match. Is more focussed on own performance as opposed to supporting team members.

So, I am trying to think of some ways in which to try to discourage camping while still allowing legitimate sniper play and preserving the original rush gameplay.

# Answer
> 31 votes
## How games I've played do this

I've played about 300+ hours of Counter Strike: Global Offensive and find the sniper in it to be quite balanced. There are a variety of ways this game helps counter snipers (AWP).

1. The map has little clutter with a lot of entrances to points of interest.
2. You can go to the other bomb site if there are campers in a strong camping spot.
3. You can use a different entrance to a bomb site to kill snipers that are camping, from a place they are not looking.
4. You can use a flash bang to blind the sniper and assault them.
5. The AWP is a one shot kill so if you know where they are camping you can one shot them, before they do you.
6. The AWP makes you move slower, so it's harder to get into cover. When scoped you move a lot slower.
7. The AWP reduces your FOV and so you can't see people entering from other places.
8. The AWP has both a long chambering duration and reload time, that makes you extremely vulnerable.
9. The AWP is very loud, so everyone can tell where it is from.

If you want to know possibly more tactics then I mention around how the sniper in CS:GO is balanced you could look at the AWP page, there are two other snipers, but they aren't used as much as the AWP.

---

I remember in a few Quake games some friends and I played there were two maps with sniper positions:

One allowed you to be shot from near enough anywhere on the map, and there was a button to kill everyone in that spot.

On the other map the spot was so far away it was hard to be accurate with the sniper.

---

Both Halo and Call Of Duty use smoke trails to show where the sniper was.

## General mechanics you can implement

* Have a sparse map: Less cover, easier to see the sniper.
* Have lots of entrances to the sniper nest: Harder for the sniper to protect themselves.
* Don't allow the sniper nest to have more that 50% cover of the player: Only hide their legs, this reduces their 'camouflage' one of the most important things for them.
* Have a built in way to blow up the sniper nest: If you shoot it with an RPG for example and you destroy it with everyone in it, it will discourage everyone going there.
* Allow opponents to be able to pre-camp the sniper nest: This allows for an easy counter to what could be an OP spot.

Say it takes player 1 5 seconds to get into position to kill the player in the sniper nest. And it takes player 2 either:

+ 10 seconds to get into the sniper nest, peek and be shot.
    + 4 seconds to get into position to snipe player 1.
* Give the sniper a long reload time: The opponent can now just stand there and shoot them.
* Make it very inaccurate if not resting: This makes sniping good. But if you're in close quarter combat the gun will be luck based.
* Give it a small amount of ammunition: It'll make the sniper happy when they die. And will encourage the player to not waste shots.
* Give it a smoke trail to show everyone where it's come from.
* Give it a loud, global audio, and distinct sound.
* Make it only fatal on head shots: This makes it harder to use, and makes small accuracy changes become massive gameplay changes.
* Make the economic benefit of getting kills with it worse than other weapons: Say you get points in your game, get like 5 points for a sniper kill and 10 for a pistol kill.
* Reduce the FOV: Makes the sniper more vulnerable to back/side attacks.

# Answer
> 54 votes
Force players to visit an area not suitable to sniping, to continue playing, for example **limited ammunition**. Or advantages instead of disadvantages - buffs that only last a while that you cant get in the sniper tower, or distant lights that you need to activate to actually see the targets when in the tower (or any other mechanism that could interfere with sniping if not in the correct state).

Another dynamic Ive experienced, is **shift the enemy/friendly territories over time**, such that no point on the map is always under control of one team. This means that eventually what used to be a friendly tower, is now an enemy tower, and sooner or later an enemy will come and kill you with ease. To make this more effective, make it difficult to know when this territory transition happens without knowing whats happening outside the sniping position (so staying longer increases risk).

# Answer
> 52 votes
## Ensure that the positions are not defensible, but just hidden

One way to get snipers to be mobile is to mirror real life military tactics that generally prescribe snipers to immediately vacate their position after executing a shot or two (either moving to a nearby alternate firing spot or retreating) - the 'defensibility' of sniper nests come from camouflage, and as soon as you fire and give your position away, the position should be totally vulnerable, thus discouraging camping.

One way to do that is to give players access to powerful indirect fire weapons - e.g. request mortar fire to a specific spot; an explosive hit with a delay of, say, five seconds (and a much longer cooldown) that will kill anyone nearby with splash damage. This mirrors reality and obviously makes camping in a single spot a losing tactic, since if people know or think that you're exactly there, they can kill you without even seeing you.

# Answer
> 28 votes
*"Fool me once, shame on you. Fool me twice, shame on me!"*

The "problem" of camping is vastly over-stated. That someone might get an easy kill by means of an **ambush** — which is what most sore losers define as "camping" — is not an issue. That is a valid tactic. If the hapless victim then goes back the same way, in the same manner, and gets themselves killed again, well then another maxim becomes relevant:

*"Madness: doing the same thing over and over, and expecting a different result"*

Camping becomes a problem if the spot chosen is impenetrable. If the attacker cannot remove a camper (or ignore/evade them) without considerable luck or high cost (such as dying several times), **then** you have designed the map/game wrong, and only **then** do you need to do something about it.

The solution is that no spot can be made impenetrable. One ambush, sure, that is quite alright. But after that the victim must be given a fair chance to combat or avoid the threat. Anyone that after that walks into the same ambush over and over without heeding the immortal words of Gunnery Sergeant Highway...

*"Improvise. Adapt. Overcome."*

...are the architects of their own humiliation, and you as the game designer are in no way obligated to accommodate such players.

I personally - as a player - despise when people try to force my round playing style into a square hole. It is a **bad idea** to shame people for how they choose to play, or to twist their arm into playing in a particular manner.

The only thing you should be concerned with is to **give everyone a fair chance**. One ambush kill is not unfair, if you give the "offended" party the possibility to get their revenge.

Oh, and for the record: I **never** camp, ever, because that is not my style of play. I am always mobile, relying on stealth and being unpredictable. If a fellow player chooses to give up those things for a couple of easy kills, I have no problem granting them that...

...because I **will** be hunting their leaden arse with a vengeance since they are kind enough to remain in the spot I last saw them at. Sow the wind, you reap the whirlwind. :D

EDIT: Example from my own experience. I play Ghost In the Shell: First Assault. Snipers there love to take up position in the few spots that allow them a long line of sight up a very narrow field of view, and wait for people to run into their cross-hairs for a few one-shot kills.

My response? Find a place of my own that is within grenade throwing range of the sniper spot and is in cover, then "Frag out!" indirect fire style, I.E. lobbing the grenade high to get it to drop in from above.

The ironic part about this is that the snipers themselves are usually just as thick and stubborn as those that — after getting shot for the umpteenth time in the exact same manner — cry "Camper!!!". They keep coming back for more! All I need to do is say "thank you" and reap the easy kills.

# Answer
> 20 votes
You mentioned having wanting to add sight lines and sniper nests. These provide a tactical advantage to one side, but require a certain kind of skill (the ability to aim over a long distance quickly and accurately). You can balance this by providing an appropriate disadvantage at the same time (one that requires a different skill), such as making the sniper nests fairly dangerous places to sit for a while.

The *perfect* sniper's nest would allow lots of great sight lines, be hard to spot from outside, and difficult to get into so it's very easy to defend. Don't make those kinds of nests, that will just encourage people to sit there forever. Instead, consider making your nests fairly accessible, so foes could come from any direction, including in some cases from the opposite team's side of the map.

This will permit players to take advantage of the sight lines, but discourage them from sticking around long after taking a shot (or if they don't get a shot after a few minutes), because they are so exposed. They could be approached easily while focused on what's on the other side of their scope, and having multiple paths to the nest makes it impractical to guard the area with a bunch of mines or whatever.

# Answer
> 10 votes
You could represent the floor of the map as a heatmap that tracks where recent activity occurred. Of course that would look very unusual / abstract, but if balanced game mechanics are your primary goal, then by all means. Maybe have a toggle on-off button for that?

And what about temporarily closing off areas that are frequently used as camping spots? You might need to compartmentalise the map a lot (many doors which perhaps only the map's own omnipotent AI can control) but that should also help if you fit it in alongside existing dynamics.

# Answer
> 8 votes
A lot of great answers have been posted here.

I'd just like to add that it's worth considering whether you want to *discourage* camping behavior, or *encourage* non-camping behavior.

For example, an easy way to discourage camping behavior would be to give players access to area-denial weapons, and make sniping without giving away your position very difficult. If the sniper briefly shows up on the minimap or his rifle leaves a long-lasting tracer trail, and the player has an easy to obtain albeit slow-moving area-effect rocket, then it becomes very hard to camp in position for more than a short amount of time.

However, you have to consider the effect this has on players who lead towards camping behavior - it does nothing except frustrates them, and frustrating your players into doing something is the worst possible way to make them do that something. When trying to balance a game, the best option is always the least frustrating option for your players, unless you have a particularly masochistic player base. Adding, for example, a long windup time to the beret in Soldat was the end of me using that weapon. It was simply too irritating. Adding a minimum range to the rifle-using class in World of Warcraft was frustrating enough that I didn't even continue my free trial.

A better way to go about this would be to give the camper some kind of incentive to break cover. For example, felled enemies could drop dog tags or some other kind of reward or powerup when killed. Perhaps the kill only counts as 'confirmed' if you can bring back their tags, or perhaps they simply gain a bonus for doing so. Additionally, you can "kill steal" or "bonus steal" by taking tags that have been left on the ground for more than a certain amount of time.

Camping would then become a risk-reward strategy. The camper would balance camping for kills with not wanting to leave his trophies open for too long and risk losing them. Additionally, with the right amount of sticky friction, picking up dog tags could be very satisfying for the player, which actually trains them to enjoy moving around over camping.

# Answer
> 5 votes
My definition of camping involves killing players as they spawn with little to no time for the respawning players to react. One example of this is Halo's grifball gametype. As for how to keep snipers from camping in this fashion, the following list is made of methods I've seen other games using.

* Have a spawn point that is inaccessible to the enemy where the enemy cannot even see into. Team Fortress 2 is a good example of this.
* Have moving elements that will block sniping lanes between the tower/nest and the spawn points. This can be something that pops out from the wall/floor to block line of sight or even a conveyor-belt style where the enemy can follow behind a moving object and end up next to the sniper. Halo has a few maps like this.
* Offer multiple spawn points. Whether the game chooses from a list of spawns or the player can choose between some different bases to start by, this makes it harder to simply watch one point and pick off players as they respawn. Halo has choose-from-list style. Section 8 had a system where you choose any point on the map and jump down from orbit.
* Grant temporary immunity. If players take no damage for a few seconds after respawning, they have time to get to cover. Mario Kart's battle mode has something like this.
* Have ammo spawns away from the sniper nest. Most FPS that have ammo can be examples here, but if your game has something that can be dynamically placed and refresh ammo (like the Dispenser in TF2) then this may not be as viable an option.

If players have a hard time figuring out where the snipers are hiding, you can add kill-cams that show the sniper or trails that show the path the bullet took.

# Answer
> 5 votes
Blacklight: Retribution solves this by literally giving everyone wallhacks. Not all the time of course, they have a "battery" and you cannot shoot while using it. There is also a enable/disable delay where you're vulnerable.

Other options are Battlefield-like scope glint, which is basically a reflex on the scope lens that is triggered when someone else has the camper on their peripheral vision, if the sniper is aiming.

Depending on the gameplay style, the ambient could leave tracks of a camper: birds flying away when he shoots, moving grass when people go through it or similar indirect feedback.

# Answer
> 2 votes
Make the snipers more visible when they shoot, and perhaps add a period of time they can't fire. If they can't fire for a second after, and they are very visible, it might help others to find them. Make sure there's a reasonable way to sneak up on the sniper if they are found as well.

# Answer
> 2 votes
I agree with Josh's comment that it's hard to provide an accurate reply with the details you've given us, but I'll try anyway.

There are actually several different approaches you can consider here.

## Mechanic Design

Shootmania had a really unique way of dealing with the situation you're describing - unique at least to me - in that one of the game modes there, Royal, had a tornado that would close in around the map, forcing all players to the middle. From the wiki entry:

> Royal is the survival, free-for-all mode where the goal is to be the last player alive at the end of the round. There are three ways to score points during a round:
>
> 1. Staying alive as long as possible
> 2. Capturing the the pole at the center of the map
> 3. Eliminating the others players
>
> Capturing the pool at the center of the map activates the Off-zone, a storm like environmental effect that will eliminate players on contact. This forces all players towards the middle of the map until only one player remains and the round ends.

The reason this was good is because you could choose to risk running to the pole, with the possible reward of capturing it for more points, or sitting back and waiting for someone else, or the timer, to activate it instead. The interesting thing about it is that if you were near the pole when the tornado started to close in, you would have opportunities to kill players coming towards you as they try to avoid the tornado. That meant you had to know when to hang back to snipe a bit more, and when to move towards the centre of the map.

## Enemy Player Detection

Arcane Engineer's answer covers this, but you could actually go a few steps further. As an example, you could have a (rare) item which detects heat signatures that spawns somewhere on a map - either in a fixed position, or as part of a random event on a map - which a player could equip to detect heat signatures, particularly after rounds have been fired. That means two things:

1. Players have to risk moving around to get the reward of enemy detection.
2. Better players will learn to move around more after they fire, as it won't necessarily be apparent when someone is able to detect them.

## Resource Gathering and Load-outs

For games where combat is the primary focus, resource gathering isn't as popular as it once was, with those games seemingly preferring the idea of 'load-outs' instead, in which players predetermine the type of gear they start with. This forces players to loot the corpses of other players, or items, if your game supports it, to get extra ammunition.

This requires a fair bit of testing to come up with an ammunition level that's suitable. If you set it too high, players can camp, but, if you set it too low, players don't get to snipe. I think it's best used in combination with overall mechanic design, rather than the map design, but that's my own personal preference.

The other way to look at it would be from the standpoint of resources that are needed for survival: food, water, medical supplies. If people are also having to manage their survival, camping can only go on so long before they have to move.

# Answer
> 2 votes
Further to @Waterlimon's excellent answer, consider dynamic sniper spots to force snipers to move from spot to spot to find a place worth sniping from. Some examples:

A pillbox with windows or shutters that are opened/closed elsewhere, or @Waterlimon's point about lights which can be turned off/on elsewhere. Equally useful would be searchlights on your sniping tower which require repairs (poss requiring an engineer or other non-sniper-class?) if shot out.

Most obviously, moving ones. A train roof which gives an excellent vantage point of different streets as it moves around the area, until it runs into the tunnel, killing whoever hasn't jumped off beforehand... and if you leave jumping off too late, you leap into the lake and must slowly swim out, making you an easy target.

A low wall facing a road, which is only really great for sniping when all lights are red on all the cross roads; otherwise traffic gets in the way.

Consider also periodic hazards. The back of a parked trash truck, has excellent vantage and defense, but occasionally starts crushing and gives the snipers within only moments to escape, (perhaps on a timer, or randomly, or when foes run up and hit the button).

Just about any scenery element which moves can be used to make a sniping place good or bad, by regularly getting in the way of the sniper's fire, sight, or both; by regularly exposing or hiding the sniper from view; or by regularly killing or evicting the sniper. You can change the quality of the sniping spot simply by changing the speed or direction of movement: a cart which runs smooth and straight along a road is far easier to fire from than one which zigs and zags randomly.

Most maps seem to have multiple approaches to the good camping spots, many of which are hidden from the camper, so you can get the jump on them. The major disadvantage of a sniper is that people can very easily sneak up behind them. Of course, this isn't a fix for a teamed pair, one sniping from the vantage point and one bagging those sneaking up behind.

# Answer
> 2 votes
## Introduce an anti-camping character

Take a look at the Team Fortress 2 Spy (gameplay) for a good example of an anti-camping character.

* Uses invisibility and disguises to infiltrate into enemy territory.
* Kills instantly when stabbing their victim from behind.

The spy balances the game by allowing the enemy team to fight back. It is now dangerous to camp, and becomes more dangerous the longer you stay in one spot.

# Answer
> 2 votes
Since there's not too many answers here, I'll add one more!

What about having mosquitos / fireflies swarm near players that stay in one spot too long (because they detect the heat / smell if you need a reason). A simple collection of particles should do.

Or have birds fly overhead of campers. It would just a subtle indication when you see multiple birds circle or flyover an area to take notice.

# Answer
> 2 votes
Have a radar mini-map show players that are not moving. Games often show players that are in motion, but flip the fiction, stationary players are easier for radar to lock-on to. snipers and campers will light up the map.

# Answer
> 1 votes
### How to encourage snipers

The benefits for sniping are obvious.

But perhaps provide a mechanism for other players on a team to mark/highlight likely sniper positions to their sniper team mate. It will give that sniper teammate a bunch of options to use depending upon the needs of the battle.

### How to discourage camping

A simple mechanic that you could add is a sort of situational awareness. The more shots coming from a sniper position, the more likely you will know the source of that incoming fire.

A real human would be using all senses (especially sight & sound) to locate the sniper. FPS don't provide that sort of situational awareness, so add it in. Every time a sniper shoots, give the opposing team a chance to "locate" the source of the incoming fire. If the opposing team "locates" it, highlight it on the minimap.

If the opposing team is smart, they'll set up an "antibattery" type sniper position to take out the enemy sniper or perhaps "rush" the position.

Proper use of this mechanic might cause each team to set up an SOP of "you get five shots" and then scoot to the next sniper position highlighted on your map.

# Answer
> 1 votes
In the real world snipers have two main vulnerabilities. The first is that the need to reach their objective undetected and so have to avoid patrols and whatever sensors or surveillance may be deployed against them. This is made more difficult by the fact that their military role tends to include intelligence gathering as much as offensive action so they may often have to move through enemy held territory.

The other issue is that once even the general location of a sniper is known to the enemy they are very vulnerable to crew served weapons such as mortars, heavy machine guns and artillery. These can either kill them outright or suppress them, allowing them to be flanked and assaulted by infantry.

The long range of sniper weapons compared to infantry assault rifles effectively give them the opportunity to evade detection and escape before they can be effectively targeted but if they stay put and allow enemy infantry to close range they are highly likely to be overwhelmed as soon as they can close the range and put down a weight of fire that a sniper cannot possibly match.

This also leads on to the concept of suppressive fire and' winning the firefight', something which is crucial in real warfare but hard to represent in a video game. Conversely setting up an accurate shot from a properly concealed position takes time and preparation and in games which often have greatly condensed ranges and scales of maps what is called 'sniping' is often just sensible infantry tactics where maps are a few hundred metres across rather than 10s of km.

Having said that one practical approach would be to have clear differences in the mechanics of sniping and assault weapons.

* Give sniper weapons great accuracy at long range but at a cost eg include settings for range and windage which need to be set by the player to get accuracy at long range. This could be approximated by having a long settling time for the targeting reticule or even force a short blur on the sight when taking an aimed shot, making them ineffective for close combat.
* Only allow players with a sniper rifle to take a short range pistol as their secondary weapon.
* Nerf accuracy of sniper rifle from a standing position.
* Give players access to mortar fire support with high lethality and large area of effect but with maybe a minute or so delay as a means to take out a sniper who camps for too long.
* Careful design of maps with a mix of cover and open ground to make sniper hides more obvious.
* Force snipers to sling/unsling weapon (takes a few seconds) between running and firing.
* Aimed shots with a sniper rifle only possible at full health

The above nefts to a sniper's agility could be balanced by much greater weapon range and power.

Its also worth considering that if you really want proper sniping some sort of stealth mechanic would be good. A simple solution would just be an invisibility mechanic which switches off when the sniper runs or fires a shot and resets after a certain period of inaction.

In summary an overall realistic approach to allowing snipers but not making the dominant would be to force players who take the sniping option to be careful and deliberate in their shots and movement and make sniping capable weapons all but useless at close quarters.

# Answer
> 1 votes
I've been playing so many FPSs of all sorts and I found a simple game called Ace of Spades and I quite like it, it has HUGE maps and it lets you build your own bunker, it's awesome, anyway, I've been working on an FPS too with HUGE maps, and I've been watching a lot of military documentaries talking about urban warfare and jungle warfare and it's quite interesting, when in urban scenarios with civilians the army snipes the insurgents and then breach and clear the whole area which is dangerous because *campers* and IEDs, whereas in jungles they form a line made of wedges and as they move they use snipers to watch the area for counter-snipers and moving troops, but it's less likely to have people camping, but still boobie traps all over the place.

That said keep three things in mind about a balanced map:

* The maps can neither be small nor large (about 1.8 miles squared)
* Avoid making urban maps because they offer a lot of spots for campers and they are not worth it for snipers
* Create two identical bases for both teams and a gap in between them so players will get exposed when trying to camp on the enemy's base

Try to balance all weapons in game:

* Never make it so slow to reload
* Make the scope-only rifles inaccurate when moving/strafing and shooting
* Add bullet drop to all guns
* Add weight to the guns
* Make it less accurate to shoot after sprinting

Of course, this is just my two cents, if you're going to create sniper nests, which I discourage, you should isolate them from the other buildings so when inside one you have to watch for people coming from basically all directions, the main thing is to avoid creating 90° angle hiding spots like corners behind obstacles or something of that sort and your game won't have that many campers

# Answer
> 1 votes
There are several tremendously good answers to this question, and I hope my personal experience will at least add weight to some of the other answers.

I used to play an *lot* of Team Fortress Classic. Some weeks I probably played 40 hours.

If you're at all familiar with TFC, you'll know that they had class-based play, and one of the classes was a sniper. You'll also know that probably the most common map (pretty sure it was the default map if you started a server) was 2 Fort. It looked like this:

Each base was a mirror image. Between the bases you have a long bridge over a moat. Beneath the battlements are two doorways with very little lighting. In the middle of the battlements you also have a sort of bunker with poor lighting. In a typical game involving snipers, you would find them hiding in the darkness in the doorways (though less often, as these were fairly high-traffic areas, and the sniper was pretty poor in man-to-man combat), or more usually sneaking out from the top battlements to take a shot.

While the snipers did have one-hit kill abilities, the game was still balanced, due to the following:

* one-hit kill shots required both time and precision. The sniper had to 'charge' their rifle by holding down the trigger button. Then they had to hit the enemy in the head.
* The sniper rifle had a "laser" sight, i.e. a red dot that appeared wherever they were aiming. Skilled snipers would do their best to hide the dot until the last possible moment. If you were on the receiving end, typically you'd only know there was a sniper waiting for you when your vision turned red the moment before you instagibbed.
* When charging the rifle the sniper movement was *very* slow. This made them fairly easy prey for splash damage weapons.
* If you could move quickly, it was pretty easy to dodge the hit. Or if they shot your friend in the face, you could take them out while they were re-charging their weapon.
* There were multiple avenues of entrance to the base. Sure the main courtyard was wide open, but there was a water tunnel that came up under the bridge. If you wanted to enter the enemy base unseen that was a reasonable option. You could then come up behind the snipers either in the bottom of the battlements or up through the main ramp room, past the spawn point, and out into the battlements. Or you could do an assisted jump up the grate and come out by the spawn point and through to the battlements.
* Pyros had fire weapons, and when lit on fire your vision would be obscured. This made it difficult for snipers to see where they were aiming.
* Medics and scouts were fast, and if they used a concussion grenade to propel themselves they could easily move faster than most snipers could track. Of course you did get the lucky "skeet" shots. Concussion grenades would also disorient the snipers.
* Spies could disguise themselves as the enemy. Even your crosshairs would take on the name of one of your own teammates with that same class.

Snipers had certain strategies that they would employ, but there was always some way that you could deal with them - even without becoming a sniper yourself.

TFC also had a nice way of preventing camping - you typically had multiple respawn points (2fort had 3 spawn rooms, two of which had two entrances. One came out the right side of your own battlements, and the other let you drop down in the middle of your own base. The third was near your flag in the basement. But you could go up the elevator or the spiral to get into the rest of the base) and these spawn points had built-in turrets that were extremely powerful. All you had to do to stop someone camping in front of your spawn point was open the door. You might die once, but the camper would be pretty dead right after that.

I think the most appropriate anti-camping lesson you can take from TFC is one about *balance*. Each class, each position had some sort of Achilles' heel that required teamwork. The best story that I have about this comes from the map called Well. The Well felt like a much larger map than 2fort - again it was symmetrical, with two large bases facing each other over a large courtyard. At the top of each base there was a catwalk that was only accessible via ladder from the outside of the base, but offered a commanding view of the central field, and some camouflage. Below that was a sniper deck, accessible from within the base, and then the main door. The main feature of the central field was a tunnel across the center of the field that served as a sort of wall. However, in that tunnel was access to the sewers, which (if someone destroyed the grate) allowed you access to the flag room of the opposing team.

The most relevant feature of Well for my story though, is that there were only two spawn rooms. They were across the ramp room from each other, and on exit you had two choices - go into the ramp room and left to go into your flag room (large, with a silo), or up the ramps, across the sniper deck, and up into the attic (which also led into the flag room on the other side). The attic had a singularly interesting feature - a large oblong hole in the floor. If you were an engineer, you could place a sentry gun here. At level 3 it would protect well against all but the most coordinated assault. And with multiple supply packs spawning in the attic, a lone engineer could protect their base... as long as their grate was intact.

In my case, however, it was an *enemy* engineer who set up his sentry gun in our attic.

At that point, my go-to class was a soldier. Slower, but with more armor and firepower that suited me just fine. The team I was on was getting *destroyed* by the enemy. They were on a cap(ture) run - as soon as our flag was captured, they already had a man waiting to pick it up when it was returned to our flag room. So I walked out of the spawn room, ready to do some damage, when to my surprise I was turned into ground beef by a sentry gun inside my base. Next spawn I tried sneaking out, only to have my leg blown clean off. I even tried throwing a nail grenade up into the attic on a suicide mission, but if the engineer is hiding behind his gun repairing it that doesn't work. And it didn't.

Next I tried a heavy weapons guy. His minigun and massive amounts of armor make him quite powerful. Unfortunately for me, his slow speed also makes him a sitting duck. Or shredded duck, in my case.

Finally I had the right thought - an engineer with an EMP grenade. An EMP grenade will usually take out a sentry gun, and the more armor and ammo you're carrying the bigger an explosion *you* make. Enemy engineers make very large explosions. Priming the grenade, I ran out of our spawn room and launched it into the attic. The fireworks were spectacular. I destroyed the sentry gun and the enemy engineer (alas, I died also, but you know - respawn), and then went and put up my *own* sentry gun. I was able to put a halt to their cap run, and even capture their own flag a few times myself.

It was one of my most memorable TFC games. Under most conditions, an engineer would never have made it to that point of the base and had the time to setup a sentry gun. But the players on the team I joined were a little overwhelmed (out of balance). They just needed the scales to not be tipped quite so far in the favor of the opposition.

Balance is what makes a game fun, and is a great way to prevent camping. If your maps are well balanced, and your weapons are balanced, and your teams are balanced, your game will be fun.

If you want to encourage sniping, but you want to prevent the snipers from just setting up shop and not moving, give them a reason to move.

* Make it dangerous to stay in one place for long, either because the enemy can sneak up behind them, or as others have mentioned, call in an airstrike or mortar or make it possible for them to get hit with a rocket.
* Make it pointless to stay in one place for long: maybe the battle moves back and forth along the map. Either the sniper has to advance because there's nothing for them to do, or they have to retreat because they're going to die.

# Answer
> 1 votes
Here's a different approach: Change your game fiction. Make your sniper nest occasionally sway in the wind. If the sniper's team is getting too far ahead, increase the rate and magnitude of the swaying. If you want to shake things up even further..... make your buildings move. This might be more aligned with sci-fi and fantasy genres, but whos to say that all the towers are built on the backs of giant turtles swimming through the galactic rivers of the cosmos?? :)

Campers? Everywhere is sloooow quick-sand. You've got to move every 30 seconds or you'll die from drowning.

Just adding creative answers because we all need thought experiments from time to time.

# Answer
> 0 votes
Verdun is a WWI video game that is predominantly one hit kill bolt action rifles in trench-filled map that really empowers the defence.

The maps themselves use a (way too fast) player-killing mechanic that forces players to assault other trench lines or to defend their own line when getting attacked, lest the game just auto-kill you after 10-30 seconds for being outside of the current field of play. Major (and pointless) bonus points are offered for following your corporals commands, and attacking / defending alongside him. Squad play helps to encourage momentum and attacking.

The attacking a defending swapping happens so fast that it doesn't really offer the feeling of being 'entrenched' but it does encourage an otherwise sniper-dominant game to instead be fast and hard hitting with people driving over hills toward the enemy under sniper and artillery fire every minute.

# Answer
> 0 votes
As a veteran FPS player, here is my suggestion: make the sniper rifles very precise weapons, but lacking in refire rate compared to more standard weapons. What this does is it makes them potentially very vulnerable to being rushed, but if they can keep their enemy at a distance, then they have a dramatic advantage. This discourages camping because sooner or later, someone is going to come looking you and you will need to relocate (example: original Call of Duty). The main thing that is likely to cause problems with this plan is if the game has a strong tendency to form relatively static lines of battle (this can be seen in Planetside 2 for example, where snipers camp all the time, but there, the fact that bullet velocity is modelled keeps sniping from getting overly frustrating to play against).

# Answer
> 0 votes
Add concentration and fatigue associated with staying in one place. In other words, the precision (or damage amount if you support concept of partial damage) of the shot goes up drastically for a period of time and then steadily declines. You can use the impulse-response curve as your reference if you want both partial concentration to come back after a slow decline. The steady-state value of the curve would have to be lower than the value of the curve at time 0 (to make sure that staying in the same place for a long time is a disadvantage).

# Answer
> 0 votes
Personally I think I'd just go for a class divide on mechanics.

If you play as anything else but the Sniper Class, then you get penalized for staying still for too long. However there needs to be a balanced downside to being a sniper like sniper preparation time, slower running or something else similar.

# Answer
> 0 votes
As previous answers have stated, in the real world, snipers become more obvious/vulnerable the more shots they take from a single position. So make them easier to hit or spot or both.

Easier to hit could be in the form of increased bullet accuracy based on how many shots they've taken * how long they've been in one spot, or if you prefer awareness, highlight them for longer on the minimap (if you have one) the more shots they take from their position.

# Answer
> 0 votes
If you are familiar with the game World of Tanks, the SPG (artillery) class was implemented mostly due to complaints about camping. You could implement a similar anti-camp method using mortars and overhead targeting.

Also, spg's in WoT spawn in a different part of the map, so you might even have some players who become dedicated "anti-campers" using long range artillery from an area that is separate from the main fight zones.

# Answer
> 0 votes
A lot of great answers already.

I would like to add this list I came up with to avoid camping (indirectly, for directly avoiding camping see the other answers):

* Add a concept of teritory;
    + Add activatable spawn beacons (Flags for example).
    + If one team enters a key area, the other teams spawn point gets moved back.
    + Work with 'lanes' and 'stations' (Key locations);
        - If all stations on a lane are taken, then the lane is taken;
        - Stations connect multiple lanes.
        - Stations are easy to defend from the connected lanes, but hard to defend from the lane it is on.
        - Stations contain new equipment (Extra ammunition, Extra health, Extra armor, etc.)
        - Stations contain stationary equipment (Rocket launchers, Tanks, Turrets, etc.) (TF2 has a great playstyle where you can place down your own equipment)
        - To avoid deadlock (A state where both teams can easily defend their stations, making it disadvantageous to attack), make the number of stations slightly larger than is possible to defend. About one station for every 2 players I would say. Also keep the number of lanes small (7 lanes at most, 3-5 when \<32 players)
        - Avoid interactions between lanes at places other than stations. (One or two 'sneaky entrances' at most)
        - At the start of the game, teams get only part of a lane. (Giving both teams a full lane from the start might be interesting aswell)
        - The number of lanes should be *uneven* or at least in some way *balanced* (Yes, people mess this up).
        - Lanes and stations are easier to defend near the middle of the lane.
        - There should be a 'middle' lane, which is:
        - defendable (Defend-Defend playstyle; If you take the lane, you can keep it), or
        - attackable (Attack-Defend playstyle; If you leave the lane open, you lose it).
        - Either way, both teams should have to put pressure on this lane.
        - Important: *lanes*, not *trenches*!!!
* Slow down the pace of the game.
    + Slow down the players movement.
    + Make players more vulnerable when moving fast.
    + Increase capture times.
    + Increase the distance between cover ('Minitrenches')
* Group players together
    + Add medics.
    + Add objectives.
    + Add lanes.
    + Add 'overpowered equipment' (Tanks, turrets, miniguns, whatever, not actually overpowered, but hard to take out without teamwork, a 'engineer' or 'heavy' class usually prevents these things from being overpowered).
    + Give players extra points for sticking together.
* Remove hiding spots.
    + Remove unnecessairy cover. (Anywhere you don't need to go in order to complete the objective. As a rule of thumb, remove cover near the edges of a objective and add cover in the middle.)
    + Remove small, tight corners (of ~90 degrees) wherever possible. (Unless it is to slow down attackers)
    + Remove three-way junctions. (You can't look two ways)
    + Avoid tight coridors. (You can't defend yourself if you can't take cover)
* Don't make players *too* vulnerable while moving. (Don't force players to jump into a vulnerable position if they can't shoot while jumping for example (Yes, this happens too))
* And of course, in general, make camping disadvantageous (See the other answers for this)

# Answer
> 0 votes
Here's a unique approach: add an "inactivity-induced fatigue" penalty that makes weapons dramatically less powerful when the player fails to move around on the map. The penalty would be inversely proportional to the average distance travelled by the player over time.

What I like about this approach is that if the campers run from camping location to location, in order to avoid the penalty, they offer themselves the opportunity to be killed by other players.

Snipers, of course, would have to strategically choose where and how long to snipe.

# Answer
> 0 votes
I develop games as well and in the past, this is what occurred to me as a way to keep people from camping.

Track how long they have been in a certain region. If they stay in one general area too long, start emitting bright, noticeable particles (like pink smoke) from their position. This is similar to the 'make the gun put off a lot of smoke and flash' suggestion others have made, except the sniper doesn't necessarily get the benefit of that first shot.

# Answer
> 0 votes
I agree with points given in posted answer and would like to add that you can create NPC airplanes, tanks, mortars, bombards, cannons for each side of the game like the Scourge and the Sentinel in DoTA, leage of legion games. You add algorithms for the following.

Chances that you get hit by one bullet of the mass-bullets (reducing health point by 15-25% your call) and die by (% to be on radar) a rocket, (% to be hit) grenade, randomly by bomb or other explosive arms, if you stand still for quite a while. The game-play may be more interactive when there is a continuous fighting of (NPC) allied forces. The number of NPC units is totally up to you. You may want to have a considerably small number to prevent your game from becoming an AoS, DotA type.

Also like others have said, you can add fuzzy effect to affect the camping snipers if they become slack and don't bother moving around to find the targets. Fuzziness and drowsiness here I mean is to reducing damage and destruction caused by them.

A combined solution may work well for your effort.

cheers

Pristine,

---
Tags: game-design, game-mechanics, shooter
---


# Question
Title: Disable input and score count in pause menu?
I need some sort of an if statement, which allows me to **disable any input and increment score while I'm in the pause menu**.

The problem is that I don't really understand this kind of pausing code, I'm "used to" the regular boolean one. So, I show all the code.

First script:

```
public enum GameState
{
    Gameplay,
    Paused
}

```

Second script:

```
public class GameStateManager
{
    private static GameStateManager _instance;

    public static GameStateManager Instance
    {
        get
        {
            if (_instance == null)
                _instance = new GameStateManager();

            return _instance;
        }
    }

    public GameState CurrentGameState { get; private set; }

    public delegate void GameStateChangeHandler(GameState newGameState);
    public event GameStateChangeHandler OnGameStateChanged;

    private GameStateManager()
    {

    }

    public void SetState (GameState newGameState)
    {
        if (newGameState == CurrentGameState)
            return;

        CurrentGameState = newGameState;
        OnGameStateChanged?.Invoke(newGameState);
    }
}

```

Third script:

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

public class PauseController : MonoBehaviour
{
    public void PauseGame()
    {
        GameState currentGameState = GameStateManager.Instance.CurrentGameState;
        GameState newGameState = currentGameState == GameState.Gameplay
            ? GameState.Paused
            : GameState.Gameplay;

        GameStateManager.Instance.SetState(newGameState);
    }
}

```

And as of last, here is what I've done in my character movement script:

```
void Start()
{
    GameStateManager.Instance.OnGameStateChanged +=
    OnGameStateChanged;
}

private void OnDestroy()
{
        GameStateManager.Instance.OnGameStateChanged -= OnGameStateChanged;
}

private void OnGameStateChanged (GameState newGameState)
{
    enabled = newGameState == GameState.Gameplay;
}

```

This is all the code. Where and how am I supposed to write the input and score increment "blocking"? I am so sorry for this being so long and I am grateful if you read all this! :)

EDIT: the missing states, which should be disabled. Score:

```
if (Input.GetMouseButtonDown(0))
{
    if (EventSystem.current.IsPointerOverGameObject())
        return;
    if (ShootOnClick.onGround == false) // this is for disabling input when the player is colliding with the ground
    {
        //functions
    }
    else
    {
        score++;
        scoreText.text = score.ToString();
        moneyText.text = money.ToString();
    }
}

```

Input:

```
void CheckInput()
{
    //if first input then ignore
    if (firstInput)
    {
        firstInput = false;
        return;
    }

    if (Input.GetMouseButtonDown(0))
    {
        ChangeDirection();
    }
}

```

# Answer
> The problem is that I don't really understand this kind of pausing code, I'm "used to" the regular boolean one.

You can grab your boolean using your GameState:

```
bool paused = GameStateManager.Instance.CurrentGameState == GameState.Paused;

```

Then with this, you can use a regular boolean:

```
if(GameStateManager.Instance.CurrentGameState == GameState.Paused)
{
    return;
}
if (Input.GetMouseButtonDown(0))
{
    if (EventSystem.current.IsPointerOverGameObject())
        return;
    if (ShootOnClick.onGround == false) // this is for disabling input when the player is colliding with the ground
    {
        //functions
    }
    else
    {
        score++;
        scoreText.text = score.ToString();
        moneyText.text = money.ToString();
    }
}

```

There are 100 different ways to architect this, but this solution should be relatively simple.
> 1 votes

# Answer
So because I can't see how your StateMachine is running, I've made up a simple example that hopefully demonstrates *what* the purpose of the Statemachine is in the first place.

In your scenario described (and in the enum) you have two possible states your GameManager can be in, one is in GamePlay, which I imagine processes input and updates the score.

The other is the Paused state which I imagine, sets the timeScale to 0 effectively pausing everything.

So you have already defined yourself how you want these two states to behave, you want GamePlay to work as it should and when you are paused you want the input to not even be checked.

In that case your code might look something like this, if you drag this onto a GameObject and press play you will the see debug logs when you press the right mouse button down, if you press P and toggle the state, you will see your input goes from being "noticed" to being completely disregarded, not even checked.

This seems to be the best way with what you already have to achieve your desired behaviour.

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

public class TestFSM : MonoBehaviour
{
    //Define our current state with an enum
    private GamePlayState CurrentState = GamePlayState.Gameplay;

    public void SetState(GamePlayState newState)
    {
        CurrentState = newState;
        Debug.Log("Switching to State" + newState.ToString());
    }

    private void Update()
    {
        //this is basically a fancier-ish if statement, we are checking what the CurrentState value is, if its Currently GamePlayState.Gameplay then we run the "DoGamePlay" method, if its pause we run the "DoPausedState" method.
        switch (CurrentState)
        {
            case GamePlayState.Gameplay:
                DoGamePlayState();
            break;
            case GamePlayState.Paused:
                DoPausedState();
            break;
        }

        //when P is pressed, if we are paused, unpause if we aren't paused then pause it.
        //not really nessacry you might have your own way of pausing already
        if (Input.GetKeyDown(KeyCode.P))
        {
            switch (CurrentState)
            {
                case GamePlayState.Gameplay:
                    SetState(GamePlayState.Paused);
                break;
                case GamePlayState.Paused:
                    SetState(GamePlayState.Gameplay);
                break;
            }
        }
    }

    private void DoGamePlayState()
    {
        Debug.Log("In Gameplay state");

        if (Input.GetMouseButtonDown(1))
        {
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            if (Physics.Raycast(ray, out RaycastHit hit, 1000f))
            {
                Debug.Log("Hit " + hit.transform.name);
            }

        }
    }
    private void DoPausedState()
    {
        //and in here we are doing literally nothing since you want nothing to happen while paused! notice the key check to toggle the state is outside statemachine states, as we want this to work in either state.
        Debug.Log("In Paused state");
    }

    public enum GamePlayState
    {
        Gameplay,
        Paused
    }
}

```

And in this way we can define behaviour per state, which seems to be how your current code is set up, I hope this helps you apply this to your own code base, feel free to ask any questions.

So lets take your code and try apply it to this simple state machine, what do we get? Bear in mind, I have no real idea how your games supposed to work im just making a guess based on your code :)

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

public class testFSM : MonoBehaviour
{
    //Define our current state with an enum
    public GamePlayState CurrentState = GamePlayState.Gameplay;
    public LayerMask RayCastLayerMask;
    public void SetState(GamePlayState newState)
    {
        CurrentState = newState;
        Debug.Log("Switching to State" + newState.ToString());
    }

    private void Update()
    {
        switch (CurrentState)
        {
            case GamePlayState.Gameplay:
                DoGamePlayState();
                break;
            case GamePlayState.Paused:
                DoPausedState();
                break;
        }

        //when P is pressed, if we are paused, unpause if we aren't paused then pause it.
        //not really nessacry you might have your own way of pausing already
        if (Input.GetKeyDown(KeyCode.P))
        {
            switch (CurrentState)
            {
                case GamePlayState.Gameplay:
                    SetState(GamePlayState.Paused);
                    break;
                case GamePlayState.Paused:
                    SetState(GamePlayState.Gameplay);
                    break;
            }
        }
    }

    private void DoGamePlayState()
    {
        Debug.Log("In Gameplay state");

        if (Input.GetMouseButtonDown(0))
        {
            //if the mouse is over a UI GameObject return from this function
            if (EventSystem.current.IsPointerOverGameObject())
                return;

            //create a ray going from the camera to the mouse position in world space
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);

            //fire this ray and check if we hit anything on the "RayCastLayerMask" layer you can change this to whatever layer you need in the editor
            if (Physics.Raycast(ray, out RaycastHit hit, 1000f, RayCastLayerMask))
            {
                //you hit an enemy, so update your score, update the UI component for it too
                score++;
                scoreText.text = score.ToString();
                moneyText.text = money.ToString();
                Debug.Log("Hit An Enemy " + hit.transform.name);
            }

        }
    }
    private void DoPausedState()
    {
        //and in here we are doing literally nothing since you want nothing to happen while paused! notice the key check to toggle the state is outside statemachine states, as we want this to work in either state.
        Debug.Log("In Paused state");
    }

    public enum GamePlayState
    {
        Gameplay,
        Paused
    }
}

```
> 1 votes

---
Tags: unity, c#, android, input, game-state
---


# Question
Title: Initializing a global variable array once for a shader without using CPU code to populate the array
I know I can initialize arrays via code written in C++, etc. to set arrays in a shader. What I want to know is if I can initialize the array in HLSL code instead.

For example:

```
float3 myArray[64] = InitializeFunction();

```

Is this possible?

I've tried calling this type of function in my vertex shader to set values on the array, but I get unrolling errors...

Is there a concept of a function that only runs once per frame for a shader?

# Answer
No, there is no such concept. You must use CPU code to initialize your variables.
> 0 votes

---
Tags: hlsl
---


# Question
Title: How do I fix this assembly not found (UnityLinker.deps.json) error while building to WebGL?
I'm building a project and this error appeared; it's the first time I'm building it to WebGL from unity. Any help is appreciated.

```
Error:
  An assembly specified in the application dependencies manifest (UnityLinker.deps.json) was not found:
    package: 'runtimepack.Microsoft.NETCore.App.Runtime.win-x64', version: '3.1.7'
    path: 'System.Private.CoreLib.dll'

```

# Answer
As @DMGregory said it was something wrong with my unity installation, I reinstalled the unity editor and it worked fine. Thanks for the help!
> 0 votes

---
Tags: unity-webgl
---


# Question
Title: High-resolution bump map displays bad in Godot
I made a model in Blender, with a normal map. There it renders good.

Now I imported that model to Godot 3.4 stable, and in the far distance, it looks ugly. If camera is close enough "steps" disappears. Looks like, there is no antialiasing or something like this.

Also, the problem is 100% in normal map texture, because if I switch it off, only rendering Albedo texture, all displays fine.

What should I do?

Blender:

(height texture is just black and white version of original texture)

Godot:

# Answer
> 1 votes
Your issue may be due to your texture's import settings.

When you select a texture from the FileSystem tab, its import settings can be accessed via the Import tab, next to the Scene tab:

According to the Godot Docs, you can mark any texture as 3D use if the engine didn't detect it itself (2D texture is the default). You can enable mipmaps for both the albedo and normal map textures so that they look smoothed when moving the camera around. Anisotropic filtering can also help prevent visual artefacts.

About normal maps, Godot requires the texture to use the **X+**, **Y-**, **Z+** coordinates; inverted normal direction along the Y-axis occurs otherwise. If this is your problem, you can fix it in Blender itself when exporting. You can invert the value of one channel using Nodes, as described in this answer from Blender SE (same goes for previous Blender versions, as seen in this answer).

---

#### EDIT

If you're using grayscale heightmaps for bump/displacement mapping, with values between 0 (min elevation) and 1 (max elevation), then you shouldn't use the Normal map slot of the Spatial Material properties in the Inspector.

Instead, you can assign your bump texture to the Depth slot in the Inspector. This data is one-dimensional, and a single-channel image, such as a grayscale one, will do (normal maps use two colour channels OTOH).

Alternatively, you can work in Blender and bake & export an actual normal map instead of a bump map, so that you can use it in Godot as expected.

---

#### EDIT 2

Since your issues derive from plain exporting from Blender to Godot, I can suggest another solution to your texture problem.

When exporting a 3D model, you can choose to export either the full model (mesh + normals + UVs + materials + ...) or only a subset of such features. While geometry data is resolved via 3D file format, material data differs in that the same material might be rendered differently by different engines, due to custom modifiers that are available on one platform but aren't on another.

When importing 3D models from Blender, Godot uses the source geometry but first attempts to apply its own materials because they'd work best. If no corresponding materials exist (which you shall create), Blender's exported will be used instead. Blender materials are simply *mapped* to Godot equivalents as long as they both have shared properties; if Blender uses custom modifiers unavailable to Godot, such features may be lost and only an approximated material is rendered.

This is why Godot suggests how to export Blender materials in order to get the best match possible. To do so, you can use the "Better" Collada exporter, or install this native add-on for Blender.

Of course, this applies if you *don't* want to spend time creating Godot materials from scratch. If this solution doesn't work either, you can still import your model in Godot and override its materials.

---
Tags: godot, bump-map
---


title: Telling steam my game is 64 bit

text:
# Question
Title: Telling steam my game is 64 bit
I'm finally done making my game and am almost done putting it on steam (just need to wait for the build to approve). But I've noticed that on the store it says "Notice: This product is not compatible with macOS 10.15 Catalina or above."

I believe this is because steam thinks that the game is a 32bit game. But I'm on Catalina 10.15.5 and I can play the game. So is there a way to tell steam that the game *is* 64bit?

Or is my game somehow *not* 64bit. How do I know?

EDIT: One other thing I just realized is that the store gave this notice BEFORE I even uploaded a build. So it must have just decided based on something else.

It's just a small pixel art game that's 24mbs and I made it on Unity building for PC, Mac, and linux standalone. Here are my build settings:

# Answer
I suspect this isn't a problem on the development side, but rather a problem with the Steam client failing to correctly identify your OS.

Taken from a Steamworks announcement regarding configuring Steam client to detect 64 bit MacOS:

> If your Mac application already supports 64-bit, please login to Steamworks and select the macOS -\> 64 Bit Binaries Included check box in the Supported Operating Systems section for your application. This will ensure that your macOS app will appear as compatible for users who are running Steam on macOS 10.15.
> 3 votes

---
Tags: unity, steam, macos, build-process, deployment
---


# Question
Title: Create list of objects with a for loop pygame/python
Hi everyone I am trying to make a Mahjong Solitaire game using pygame.

I want to create a list of objects (the tiles of the game) using a for loop, but I can't manage to set a different type (the picture on the tile) for every tile.

I manage to draw them correctly on the screen but by the time the for loop ends all of the tiles are set (overwritten) with the last type and coordinates. I use a click to select the tiles.

Can you explain to me what I am doing wrong?

```
import pygame
import random

pygame.init()
pygame.display.set_caption("Mahjong")
# icon_img = pygame.image.load("mahjong.png")
# pygame.display.set_icon(icon_img)
WIDTH = 800
HEIGHT = 600
WIN = pygame.display.set_mode((WIDTH, HEIGHT))
# start_screen = pygame.image.load("startscreen.jpg")
# start_screen = pygame.transform.scale(start_screen, (WIDTH, HEIGHT))
start_game_font = pygame.font.SysFont("Corbel", 70, bold=True)
game_font = pygame.font.SysFont("Corbel", 30, bold=True)

state = "game"
# Different pictures of the tiles
tile1 = pygame.image.load("tile 1.png").convert_alpha()
tile2 = pygame.image.load("tile 2.png").convert_alpha()
tile3 = pygame.image.load("tile 3.png").convert_alpha()
tile4 = pygame.image.load("tile 4.png").convert_alpha()
tile5 = pygame.image.load("tile 5.png").convert_alpha()
tile6 = pygame.image.load("tile 6.png").convert_alpha()
tile_type = [tile1, tile2, tile3, tile4, tile5, tile6]

class Tile(pygame.sprite.Sprite):
    def __init__(self, x, y, type):
        super().__init__()
        self.image = tile_type[type]
        self.image = pygame.transform.scale(self.image, (60, 100))
        self.rect = self.image.get_rect()
        self.pos = pygame.mouse.get_pos()
        self.rect.x = x
        self.rect.y = y
        self.type = type

# start screen, disabled for debug
# def intro():
#     start_text = start_game_font.render("Start", True, (0, 0, 0))
#     WIN.blit(start_screen, (0, 0))
#     WIN.blit(start_text, (WIDTH / 2 - 100, HEIGHT / 2))

def game():
    WIN.fill((0, 150, 0))
    newgame_text = game_font.render("New Game", True, (0, 0, 0))
    WIN.blit(newgame_text, (WIDTH - 150, 20))
    all_tiles.draw(WIN)

# Create a list of 48 pieces, in pairs
pieces = 48
count = 0
type = 0  # picture on the tile, range 0-5

# Create a set of tile, in pairs and store them to a list
tiles = []
for x in range(pieces):
    count += 1
    if count == 2:
        count = 0
        type += 1
    if type == 6:
        type = 0
    tiles.append(type)

random.shuffle(tiles)
all_tiles = pygame.sprite.Group()
x_pos = 40
y_pos = 100
count = 0

# Use the value on tiles to create a sprite group, arrange them on the screen
# The issue is probably here
for value in tiles:
    tile = Tile(x_pos, y_pos, value)
    print(value, x_pos, y_pos)
    x_pos += 60
    count += 1
    if count % 12 == 0:  # makes new row
        y_pos += 100
        x_pos = 40
    all_tiles.add(tile)

clock = pygame.time.Clock()
running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        if state == "intro":
            intro()
        if state == "game":
            game()
        if event.type == pygame.MOUSEBUTTONDOWN:
            if state == "intro" and WIDTH/2 <= mouse[0] >= 300 or WIDTH/2 <= 460 and HEIGHT/2 <= mouse[1] <= HEIGHT/2+40:
                state = "game"
            # Identify which tile has been clicked
            if tile.pos:
                print(tile.type, tile.rect.x, tile.rect.y)

    mouse = pygame.mouse.get_pos()
    pygame.display.update()
    clock.tick(60)

pygame.quit()

```

# Answer
> 0 votes
I had to change a few line in the main loop, MOUSEBUTTONDOWN event as follows:

```
        # Identify which tile has been clicked
        pos = pygame.mouse.get_pos()
        clicked = []
        for s in all_tiles:
            if s.rect.collidepoint(pos):
                print(s.type)

```

---
Tags: sprites, python, pygame, objects
---


title: Unity Android build crashes randomly

text:
# Question
Title: Unity Android build crashes randomly
I have an Android game, and everything works perfectly in the Editor, but when I run it on my Android device, it crashes sometimes.

This is how it goes: I'll be playing my game, and randomly, or because of a reason that I don't know, the game will quickly drop in FPS, it starts to go slower and slower until it's frozen at 1 FPS. Changing scenes when it starts to slow down, is possible, but it ends up crashing anyway.

It's not a device issue since it has happened on multiple devices.

It's also not a scene-specific crash. It's happened on my menu scene, game scene, and level creator scene.

It happens very rarely, today it took me about an hour of playing until I could replicate this bug, it eventually happened, and this time I had the profiler attached:

As you can see, VSync goes up to 5000+ms, the function causing the problem seems to be:

PlayerLoop -\> PostLateUpdate.FinishFrameRendering -\> Gfx.WaitForPresentOnGfxThread -\> WaitForTargetFPS -\> Semaphore.WaitForSignal

But I haven't found out exactly what this is or how to solve it.

Does anyone know how to fix this?

# Answer
After digging really deep, I found that some people fix this by disabling Optimized Frame Pacing In PlayerSettings\>ResolutionAndPresentation\>Optimized Frame Pacing.

I'm going to try that and tell you if it worked, if you try it, please let me know if it fixed it for you.

Here is where I found this information:

https://forum.unity.com/threads/and...h-playerloop-in-profiler-at-60-000-ms.863143/

https://forum.unity.com/threads/uni...ication-after-migrate-to-unity-2019-3.907628/

https://forum.unity.com/threads/whats-the-optimized-frame-pacing-feature.636847/
> 1 votes

---
Tags: unity, android, profiler
---