# Question
Title: Unity 5.6 - Compilation Error with UWP using Facebook SDK for Windows
I built my unity game for UWP and I added winsdkfb to authenticate user with facebook ID. When I build my project in visual studio 2017, it throws an error which is:

> Severity Code Description Project File Line Suppression State Error The command ""C:\Users\saada\Documents\Tap n Jump\Build\W10\Unity\Tools\AssemblyConverter.exe" -platform=uap -lock="C:\Users\saada\Documents\Tap n Jump\Build\W10\Kukku Free\project.lock.json" -bits=32 -configuration=Master -removeDebuggableAttribute=True -uwpsdk=10.0.15063.0 -path="." -path="D:\Unity5.6\Editor\Data\PlaybackEngines\MetroSupport\Players\UAP\dotnet\x86\Master" "C:\Users\saada\Documents\Tap n Jump\Build\W10\Kukku Free\Assembly-CSharp.dll" "C:\Users\saada\Documents\Tap n Jump\Build\W10\Kukku Free\Assembly-CSharp-firstpass.dll" "C:\Users\saada\Documents\Tap n Jump\Build\W10\Kukku Free\UnityEngine.dll" "C:\Users\saada\Documents\Tap n Jump\Build\W10\Kukku Free\Facebook.Unity.Settings.dll" "C:\Users\saada\Documents\Tap n Jump\Build\W10\Kukku Free\nunit.framework.dll" "C:\Users\saada\Documents\Tap n Jump\Build\W10\Kukku Free\GameSparks.dll" "C:\Users\saada\Documents\Tap n Jump\Build\W10\Kukku Free\UnityEngine.UI.dll" "C:\Users\saada\Documents\Tap n Jump\Build\W10\Kukku Free\GameSparks.Api.dll" "C:\Users\saada\Documents\Tap n Jump\Build\W10\Kukku Free\UnityEngine.Networking.dll" "C:\Users\saada\Documents\Tap n Jump\Build\W10\Kukku Free\Facebook.Unity.dll" "C:\Users\saada\Documents\Tap n Jump\Build\W10\Kukku Free\GameSparksRT.dll"" exited with code 1. Kukku Free C:\Users\saada\Documents\Tap n Jump\Build\W10\Kukku Free\Kukku Free.csproj 321

When I remove my code which involves facebook authentication, it builds and runs fine. I googled it but didn't find any solution. Any help would be appreciated.

# Answer
Hey this post I assume is quite old but this bug had me for a while so I figured I would pay it forward.

You are getting an exception because Unity is using Mono.Cecil to try to weave all your compiled assemblies. It every one in the error above and also every assembly it references. If it can't find one of these assemblies you get this exception. The issue is the winsdkfb project is not going to be found.

Fix: Copy the output of the compiled winsdkfb into the folder `[Generated Project Path]\[project name]\[Project Name]\`. You will know it's the correct folder because you will see all the dlls mentioned in the error above.

Cheers,
> 1 votes

---
Tags: unity, c#, windows, facebook
---


# Question
Title: How to balance GPU compute usage against render usage?
The GPU's primary purpose, obviously, is to render the scene.

However, if we use compute capabilities on the very same GPU, how do we partitition and control these calls such that they do not interfere with render throughput, i.e. manage load balancing? Is there standard practice in this regard?

# Answer
I will have a stab at answering part of this, but like all devs. There are many aspects and considerations and its all opinion.

In short, there is no one answer. But I can give you only my tips based upon my experience and there are some wonderful GPU profiling tools out there, even VS 2017 community edition allows you to at least see how your GPU is performing under load. But I digress.

One of the main goals for your pipeline is to keep your GPU fed, now this in itself is fraught with danger. Because an occupied GPU does not necessarily mean a efficiently used GPU. To address your question on how to partition, it might not necessarily be best to try and control this tightly, submitting your jobs in a timely manner is one thing, submitting at exactly the right time every frame may be impossible.

When I mentioned before profiling, one of the most important this it will reveal is when your GPU is not being used. This should allow you to consider how to either utilise that down time or restructure your renderer to use that time.

I will be honest here, you will get varying levels of success based upon various things such as technical know how, rendering goals, complexity and load and blah blah blah (tech term for numerous other considerations). If your question is more about the best general strategy to approach, then I could go no further than recommending one of the numerous job queue type rendering architectures to get the best utilisation of what hardware you are rendering to.

Personally in all my work with GPUs, have I come across a specific practices around load balancing between rendering and compute. This also due to different compute characteristics of AMD and Nvidia (Even threading settings are different on compute and subject to huge performance differences).

All this is my experience and opinion. So you can take it with a grain of salt, no offence taken. But my final thought would be, find a technique you feel comfortable with and grow with it. Experience is your best tool. GPU architecture is continually changing, and I feel alot of stuff is going to be flipped upside down when Ray casting comes to hardware also.
> 1 votes

---
Tags: optimization, gpu, gpgpu
---


# Question
Title: System.Windows.Form.Control.FromHandle returns null for current window
I was following the book "XNA 4.0 Game Development By Example" and in the eighth chapter, the author adds windows form to an XNA game. I was following the book for a MonoGame project, but I get null reference exception on the line "gameForm.visibleChanged += new EventHandler(gameForm\_visibleChanged)" and I cannot comprehend what's going on. When trying to use Console.WriteLine(gameForm), nothing is returned. this.Window.Handle returns a value, System.Windows.Forms.Control.FromHandle(this.Window.Handle) does not.

Here is the Game1.cs file :

```
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using TileEngine;

namespace LevelEditor
{
    /// <summary>
   /// This is the main type for your game
   /// </summary>
  public class Game1 : Game
{
    GraphicsDeviceManager graphics;
    SpriteBatch spriteBatch;
    IntPtr drawSurface;
    System.Windows.Forms.Form parentForm;
    System.Windows.Forms.PictureBox pictureBox;
    System.Windows.Forms.Control gameForm;

    public int DrawLayer = 0;
    public int DrawTile = 0;
    public bool EditingCode = false;
    public string CurrentCodeValue = "";
    public string HoverCodeValue = "";

    public MouseState lastMouseState;
    System.Windows.Forms.VScrollBar vscroll;
    System.Windows.Forms.HScrollBar hscroll;

    public Game1(IntPtr drawSurface,
                System.Windows.Forms.Form parentForm,
                System.Windows.Forms.PictureBox surfacePictureBox)
    {
        graphics = new GraphicsDeviceManager(this);
        Content.RootDirectory = "Content";

        this.drawSurface = drawSurface;
        this.parentForm = parentForm;
        this.pictureBox = surfacePictureBox;

        graphics.PreparingDeviceSettings +=
            new EventHandler<PreparingDeviceSettingsEventArgs>(
            graphics_PreparingDeviceSettings);

        Mouse.WindowHandle = drawSurface;

        gameForm = System.Windows.Forms.Control.FromHandle(this.Window.Handle);

        gameForm.VisibleChanged += new EventHandler(gameForm_VisibleChanged);

        pictureBox.SizeChanged += new EventHandler(pictureBox_SizeChanged);

        vscroll =
            (System.Windows.Forms.VScrollBar)parentForm.Controls["vScrollBar1"];
        hscroll =
            (System.Windows.Forms.HScrollBar)parentForm.Controls["hScrollBar1"];

        IsMouseVisible = true;
    }

    void graphics_PreparingDeviceSettings(object sender,
        PreparingDeviceSettingsEventArgs e)
    {

        e.GraphicsDeviceInformation.PresentationParameters.DeviceWindowHandle = drawSurface;

    }

    private void gameForm_VisibleChanged(object sender, EventArgs e)
    {
        if (gameForm.Visible == true)
            gameForm.Visible = false;
    }

    void pictureBox_SizeChanged(object sender, EventArgs e)
    {
        if (parentForm.WindowState !=
            System.Windows.Forms.FormWindowState.Minimized)
        {
            graphics.PreferredBackBufferWidth = pictureBox.Width;
            graphics.PreferredBackBufferHeight = pictureBox.Height;
            Camera.ViewPortWidth = pictureBox.Width;
            Camera.ViewPortHeight = pictureBox.Height;
            graphics.ApplyChanges();
        }
    }

    /// <summary>
    /// Allows the game to perform any initialization it needs to before starting to run.
    /// This is where it can query for any required services and load any non-graphic
    /// related content.  Calling base.Initialize will enumerate through any components
    /// and initialize them as well.
    /// </summary>
    protected override void Initialize()
    {
        // TODO: Add your initialization logic here

        base.Initialize();
    }

    /// <summary>
    /// LoadContent will be called once per game and is the place to load
    /// all of your content.
    /// </summary>
    protected override void LoadContent()
    {
        spriteBatch = new SpriteBatch(GraphicsDevice);

        Camera.ViewPortWidth = pictureBox.Width;
        Camera.ViewPortHeight = pictureBox.Height;
        Camera.WorldRectangle =
            new Rectangle(
                0,
                0,
                TileMap.TileWidth * TileMap.MapWidth,
                TileMap.TileHeight * TileMap.MapHeight
            );

        TileMap.Initialize(
            Content.Load<Texture2D>(@"Textures\MarioTiles"));

        TileMap.spriteFont =
            Content.Load<SpriteFont>(@"Fonts\Pericles8");

        lastMouseState = Mouse.GetState();

        pictureBox_SizeChanged(null, null);
    }

    /// <summary>
    /// UnloadContent will be called once per game and is the place to unload
    /// all content.
    /// </summary>
    protected override void UnloadContent()
    {
        // TODO: Unload any non ContentManager content here
    }

    /// <summary>
    /// Allows the game to run logic such as updating the world,
    /// checking for collisions, gathering input, and playing audio.
    /// </summary>
    /// <param name="gameTime">Provides a snapshot of timing values.</param>
    protected override void Update(GameTime gameTime)
    {
        Camera.Position = new Vector2(hscroll.Value, vscroll.Value);

        MouseState ms = Mouse.GetState();

        if ((ms.X > 0) && (ms.Y > 0) &&
            (ms.X < Camera.ViewPortWidth) &&
            (ms.Y < Camera.ViewPortHeight))
        {
            Vector2 mouseLoc = Camera.ScreenToWorld(
                new Vector2(ms.X, ms.Y));

            if (Camera.WorldRectangle.Contains(
                (int)mouseLoc.X, (int)mouseLoc.Y))
            {
                if (ms.LeftButton == ButtonState.Pressed)
                {
                    TileMap.SetTileAtCell(
                      TileMap.GetCellByPixelX((int)mouseLoc.X),
                      TileMap.GetCellByPixelY((int)mouseLoc.Y),
                      DrawLayer,
                      DrawTile);
                }

                if ((ms.RightButton == ButtonState.Pressed) &&
                    (lastMouseState.RightButton == ButtonState.Released))
                {
                    if (EditingCode)
                    {
                        TileMap.GetMapSquareAtCell(
                          TileMap.GetCellByPixelX((int)mouseLoc.X),
                          TileMap.GetCellByPixelY((int)mouseLoc.Y)
                        ).CodeValue = CurrentCodeValue;
                    }
                    else
                    {
                        TileMap.GetMapSquareAtCell(
                          TileMap.GetCellByPixelX((int)mouseLoc.X),
                          TileMap.GetCellByPixelY((int)mouseLoc.Y)
                        ).TogglePassable();
                    }
                }

                HoverCodeValue =
                        TileMap.GetMapSquareAtCell(
                            TileMap.GetCellByPixelX(
                                (int)mouseLoc.X),
                            TileMap.GetCellByPixelY(
                                (int)mouseLoc.Y)).CodeValue;
            }
        }

        lastMouseState = ms;

        base.Update(gameTime);
    }

    /// <summary>
    /// This is called when the game should draw itself.
    /// </summary>
    /// <param name="gameTime">Provides a snapshot of timing values.</param>
    protected override void Draw(GameTime gameTime)
    {
        GraphicsDevice.Clear(Color.Black);

        spriteBatch.Begin(
            SpriteSortMode.BackToFront,
            BlendState.AlphaBlend);
        TileMap.Draw(spriteBatch);
        spriteBatch.End();

        base.Draw(gameTime);
    }
  }
}

```

Thanks!

# Answer
> 1 votes
I have ran into the same trouble with that same book and I believe it is because that book is using true XNA while you are using the modern non-microsoft supported MonoGame. I think winForms has changed in some regard since the release of this book.

The only fix I could figure out was to change this

```
public Game1(IntPtr drawSurface,
        System.Windows.Forms.Form parentForm,
        System.Windows.Forms.PictureBox surfacePictureBox)
{
    graphics = new GraphicsDeviceManager(this);
    Content.RootDirectory = "Content";

    this.drawSurface = drawSurface;
    this.parentForm = parentForm;
    this.pictureBox = surfacePictureBox;

    graphics.PreparingDeviceSettings +=
    new EventHandler<PreparingDeviceSettingsEventArgs>(
    graphics_PreparingDeviceSettings);

    Mouse.WindowHandle = drawSurface;

    gameForm =
    System.Windows.Forms.Control.FromHandle(this.Window.Handle);

    gameForm.VisibleChanged += new EventHandler(gameForm_VisibleChanged);

    pictureBox.SizeChanged += new EventHandler(pictureBox_SizeChanged);

    vscroll =
    (System.Windows.Forms.VScrollBar)parentForm.Controls["vScrollBar1"];
    hscroll =
    (System.Windows.Forms.HScrollBar)parentForm.Controls["hScrollBar1"];

    IsMouseVisible = true;
}

```

to something like

Unfortunately, this will not solve your problem but will only make it so your game is on a seperate window than the forms control... so you will have two windows.

An approach I've seen is to somehow make your xna drawing window into a forms control, and then use that control like any other forms tool. This can be easily implemented by using something like this MonoGame.Forms. MonoGame.Forms does all that for you and I have personally found useful for making editor environments for XNA, and will most likely solve your problem.

---
Tags: c#, xna, monogame, windows, windows-forms
---


title: Monogame Drawing Text

text:
# Question
Title: Monogame Drawing Text
I'm really new at XNA. I've been following some tutorials at gameprogrammingadventures.org but when it comes to conversations I don't really like how the author does it so I've been trying to understand how to create a rectangle over the game and writing text inside it. This is done very poorly but I just wanted to understand how to do the basics first and perfect it later. This is what I have so far:

```
public void CheckConversation(GameTime gameTime)
    {
        if(Xin.CheckKeyReleased(Keys.Space) || Xin.CheckKeyReleased(Keys.Enter))
        {
            foreach (string s in map.Characters.Keys)
            {
                ICharacter c = CharacterManager.Instance.GetCharacter(s);
                float distance = Vector2.Distance(player.Sprite.Center, c.Sprite.Center);

                if (Math.Abs(distance) < 72f)
                {
                    DialogueBox dialogue = new DialogueBox(gameRef, "Text here");
                    dialogue.Draw();
                }
            }
        }
    }

```

The "game" itself runs on a GamePlayState class. And this is some code for the DialogueBox class:

```
public DialogueBox(Game1 game, string text)
    {
        TextBox = new Rectangle(1, 1, 300, 200);
        Text = text;
        gameRef = game;
        background = gameRef.Content.Load<Texture2D>(@"Scenes\scenebackground");
        font = gameRef.Content.Load<SpriteFont>(@"Fonts\scenefont");
    }
public void Draw()
    {
        SpriteBatch spriteBatch =gameRef.SpriteBatch;
        spriteBatch.Begin(
            SpriteSortMode.Deferred,
            BlendState.AlphaBlend,
            SamplerState.PointClamp,
            null, null, null,
            null);
        spriteBatch.Draw(background, TextBox, Color.White);
        spriteBatch.DrawString(font, text, new Vector2(1, 1), Color.White);
        spriteBatch.End();
    }

```

But I can't get it to draw anything on screen. I know for sure the dialogue.Draw call is executed (game crashes if I load a non-existing texture) and I'm going crazy. Like I said, this is probably some stupidly easy question but I can't really figure it out. Thanks for any help!

# Answer
Are you positive that the dialogue.Draw() method is really being called?

Like you said here

> I know for sure the dialogue.Draw call is executed (game crashes if I load a non-existing texture)

You claim that it crashes if you load a non-existent texture but that isn't proof at all that Draw is getting called. That is just proof that your constructor is getting called because you load your textures in the constructor and that type of thing would fail at load, not when they are first run. A more proper way of testing if you are running the draw function is to use a Console.Write() or something like that.

I would also check if the problem is that you might never be closing this distance that you check for before calling Draw().

```
 if (Math.Abs(distance) < 72f)
            {
                DialogueBox dialogue = new DialogueBox(gameRef, "Text here");
                dialogue.Draw();
            }

```

I would test this out by simply removing the if statement here and seeing if it runs now.
> 1 votes

# Answer
I do not know if this makes any difference but the second argument of the DrawString method is supposed to be a type string, not a type text. But I do not know if they make any difference.
> 0 votes

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


# Question
Title: Appropriate Cache Friendly Associative Container For An Entity Component System
The intro to this problem is a bit of a long one so my apologies in advance. In short I am asking for suggestion as to what type of collection I should use to store data for a particular part of my system.

I have an entity component system in place where a static EntityManager creates and stores components within vectors of their own type, and creates Entities storing them in either a vector for dynamic entities or a vector for static entities. Something like this:

```
#define COMPONENTS X(MeshComponent) X(CameraComponent) X(PointLightComponent) X(DirectionLightComponent)
#define X(ARG) std::vector<ARG>,
using ComponentTuple = std::tuple<COMPONENTS Empty>;
#undef X

class EntityManager {
    static ComponentTuple components;

    vector<Entity>& getDynamicEntities() {
        static vector<Entity> entities;
        return entities;
    }

    vector<Entity>& getStaticEntities() {
        static vector<Entity> entities;
        return entities;
    }
}

```

Without getting into too much detail each Entity has an id (stored as a `short` which determines its dynamic or static status and its index within the respective vector).

Each Component has its own id (an `unsigned short` referring to its index in its respective vector) and an Entity id, referring to the entity it is "attached" to.

At this point all the Entity object is, is an ID and useful functions. To make it more useful I decided to let the Entity object store a collection of id's (unsigned shorts) of its own components (to make searching for the entities specific components faster). My initial plan was to use an `unordered_map` data structure it like so:

```
class Entity {
    friend class EntityManager;
private:
    short id = SHRT_MAX;
    std::unordered_map<std::type_index, vector<unsigned short>> components;
}

```

Thinking on it though, this introduces at least two (from what I can see) levels of indirection. One to the hash table produced by the unordered map and another to the vector storing the actual id's. With this in mind I was wondering if anyone else would be able to suggest a more cache friendly data structure. If not a simple reassurance that my choice was a correct one will also suffice (as right now I can't help but feel that there is a better way).

Some of the things that I would like the collection to do:

1) I would like to be able to search the collection by ComponentType (because components may share the same ID but be stored in different vectors)

2) I would like the collection to be expansive (not all entities will have the same components and it just seems wasteful to have an array for all potential Component Types when the entity may only have one)

3) I would like the potential to have multiple Components of the same Component Type in the collection (in the example given above maybe some Components have two `PointLightComponent`s)

Any suggestions or comments would be greatly appreciated as I've been wracking my brain on this one for some time now. Thanks in advance.

# Answer
Do the simplest thing that works, *especially* early on.

If you've ever seen videos of triple-A titles in alpha, you'll know how slow / buggy they are. This is normal; in fact, it's *desirable*. And it's often because they used the *naive* solution to problems.

Agile development philosophy states Refactor Mercilessly; I couldn't agree more, from experience. Expect to refactor in phases, every few days. It is a far safer approach than spending countless hours fussing over the fine details, never realising they will never even come to fruition as you usually end up choosing a different approach. Software dev works in phases like this: for now, use the simplest thing that works. It's how the big companies work, too.

The most important thing is to write code that does *something*, otherwise you don't even know what you ultimately have to optimise. Making progress means glossing over fine performance details.

What this means in your case is: don't expect a one-size-fits-all data structure. What I suggest is you start with the *essential needs* data structure (for which I think `unordered_map` will do fine), and either

1. use more optimal data structures "alongside" (can be fraught with peril, as you must keep various data structures in sync) or
2. sort / search that primary data structure in non-optimal ways, and maintain just that one. (This means for example doing `O(n)` searches over your `map`)

It is far more productive to code this way and aim for lower thresholds e.g. in unit count, number of AI updates per minute, and so on, than to try to aim high from the start. Then you have the basic principle and can focus later on the finer implementation details once the concept has crystallised.

If you're struggling with the idea of gutting your game, my view is you need to spend more time practicing refactoring, as it is an unavoidable necessity in our field. Write code to throw it away.

**Closing tip** When you find yourself wanting to access the same data structure in a variety of different ways (even worse, *potentially*), there is problem in your conceptualisation of the problem. I got this a lot as a younger programmer. That's the point at which, in order to get meaningful work done, you need to decide what is the primary thing you need, start coding that up in the simplest way possible, and go from there. You'll usually find along the way that you didn't need all the rest!
> 5 votes

# Answer
ArcaneEngineer's advice is good, particularly for early development (to an extent - once you configure your engine to work a particular way, it can be significantly hard to rework it later).

For best performance, look into slot maps (also known as slot arrays, packed arrays) and colony.

A slot map has the advantage of already having the map (id) functionality built in, and the unordered iterative performance of an array. A colony has the advantage of stable pointers to elements regardless of insertion/erasure, and a faster insertion/erasure mechanism than slot maps. It has slightly lower iteration speed. I would not recommend unordered\_map, as it has well-known and significant performance issues due to way it was conceived in the standard preventing better cache-friendly implementations.

A couple of slot\_x implementations:

SG14 slot\_map

Masstronaut slot\_array
> 2 votes

---
Tags: c++, component-based, data-structure, entity-component, data-oriented
---


# Question
Title: How to pick up a powerup by clicking or tapping on it
I have a powerup that randomly drops from enemies. Right now I have it set up using `onTriggerEnter2D` and am checking for the `player` collider tag for the pickup to take effect.

```
    public class FireRatePowerUpScript : MonoBehaviour
{

    public float incrementRate = 1.3f;
    private Animator anim;

    private Weapon weapon;

    // Use this for initialization
    void Start()
    {
        anim = gameObject.GetComponent<Animator>();
    }

    // Update is called once per frame
    void Update()
    {

    }

    private void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.tag == "Player")
        {
            weapon = collision.gameObject.GetComponentInChildren<Weapon>();
            weapon.fireRate *= incrementRate;
            anim.SetTrigger("goPoof");
            Destroy(gameObject, 1f);
        }
    }
}

```

How do I change it so that instead of the player character bumping into it I have the player click or tap on it to activate/register?

Thanks

# Answer
Have you tried the `OnMouseDown` method? It's a message called on `MonoBehaviour`.

```
private void OnMouseDown()
{
     weapon = GameObject.FindWithTag("Player").GetComponentInChildren<Weapon>();
     weapon.fireRate *= incrementRate;
     anim.SetTrigger("goPoof");
     Destroy(gameObject, 1f);
}

```

See the Unity documentation on this method here
> 2 votes

---
Tags: unity
---


# Question
Title: What harm would be done if a user were able to play the client side of a multiplayer game without logging in?
I am currently developing a multiplayer game for a university project. The purpose of the assignment is to learn about the use of a cluster architecture, but I have a question concerning security.

The multiplayer role-playing game that I'm developing for class utilizes a client-server architecture. The client holds all of the game assets and a 2D game engine. The server provides authentication to log into a user account, provides access to characters and their progression, etc. The server also provides the positions of non-player characters and other players on the same server, and also provides their actions and movements.

My question is whether a tech savvy user that modified the source code of the client could "play the game" without authenticating, forcing a kind of single player version of my game? I am imagining a user sending the client his/her own custom information about where to spawn enemies and whatnot. Maybe he/she would simply want to move around the game world freely.

1) Does this scenario seem possible?

2) Most importantly, what harm could this cause to a multiplayer game? Perhaps I have content that I don't want someone to be able to access without properly purchasing the game, or if they have been banned for some reason.

3) If this is a problem I should try to mitigate, how could I go about preventing this kind of thing from happening?

# Answer
1.) This scenario seems possible, as there also exist private servers of some MMOs.

2.) I don't think that this could cause much harm. The important data for your game are on the Server. So they won't affect anything in the Online experience of other Players. Datamining will probably always exist in games. To prevent story leaks you could stream Texts from your Server. (Thanks Bálint for the idea)

Acessing areas they are not meant to go is a interesting point. For the MMO Guild wars 2 exists http://www.tyria3d.com/ There you can see the wohle World of the Game in your browser. If something like this would be a Problem you are not allowed to Store the Map on the Client. (that could be difficult)

You can't keep bannes players from playing offline, or on private Servers. So just ignore them.

3.) I don't think this is a Problem and i also don't think that you can avoid something like this as long as the Players have a local Client.
> 1 votes

# Answer
When you have a multiplayer game, then any calculations which happen on the client can be controlled by the client in order to cheat. So you should think carefully about which game mechanics should be client-sided and which mechanics should be server-sided.

> I am imagining a user sending the client his/her own custom information about where to spawn enemies and whatnot.

Enemy spawns should definitly be something which is server-controlled. If you let clients control mob spawns, players can cause all kinds of shenanigans. Like spawning a few hundred instances the rare one-every-day mob which drops the Ultrarare Unobtainium Sword of Awesomeness and farm it.

Also, when it is a multiplayer game, you certainly want mobs to be synchronized across clients. That will be a lot easier to accomplish when they are server-controlled.

When you move any mechanics worth manipulating to the server, then there aren't many fun things left the player could do without being connected to the server. Exploring the world on their own without being bothered by other players is one thing which would be quite easy to do. But any form of progression (gain exp, earn items and money...) should be impossible unless the client is connected to a server acknowledges that the player did something which makes them entitled to that progression.

---

But considering that this is an academic project and you have very likely drastically underestimated the amount of effort it takes to create an MMO (everyone does), I would recommend you to just pick the easy route and not worry about cheaters at all.
> 1 votes

# Answer
A notorious example would be the 2016 (?) Sim City. It was multiplayer only, which definitely made the game less accessible (due to server issues and EA being EA). Someone hacked the game to have a single player (offline) mode.

The harm there wasn't huge, the same content was accessible, but without having to be connected to the server.

If you have content you want to keep secret, you should stream it to the player instead of bundling with the game. That way you also stop any attempt at data mining and also people trying to crack it.
> 0 votes

---
Tags: mmo, client-server, security, pc, authentication
---


# Question
Title: Should competitive multiplayer games be pusposefully inbalanced so they don't get boring?
I've had a discussion on the internet about game balancement. Actually, this was a Pokemon fansite, and the discussion started from a simple observation that some pokemon are OP while others are outright bad.

Now I know that Pokemon is a peculiar game... Still, I believe, this topic can be easily generalized to almost any competitve multiplayer game.

Namely, most people were making the argument that while Pokemon gameplay is very inbalanced, it is a **good thing**, because a perfectly balanced gameplay is inherently boring and dull.

Let me try to quote some of their arguments, (redacting them so that they become more readable outside of chat):

> It'd just turn into a game of "lets use my favourite pokemon yayayay". The only thing that would matter than would be type matchups. Or, if the tank/glass cannon diversity was retained, then a team full of tanks would always win.
>
> Pokemon is inherently unbalanced and that's what makes it interesting IMO.
>
> "Optimal" gameplay, for anything, always becomes boring. What's fun to see is to see niche pokemon and gimmicks. There will always be something better that what you say is the best.
>
> You could just make every pokemon 100 across the board and identical everything. Of course, that loses the point of the game.
>
> Being able to use a "bad" mon well is one of the coolest things. There's an *optimal* team that wins a lot but cteaming exists and you can't really make it un-exist. It's always more fun to win with a stall team than a real shoot em up team.
>
> Perfect games becomes boring, not optimal gameplay. If everyone plays well, there's nothing wrong with that; but if everyone has a perfect team, then what?

That goes right in the face of what I always believed about game balancement. In short, I believed that, regardless of the game's genre: If we have a mon, or unit, or champion, or whatever, which is known to have little to no place in any competetively viable strategy (the Pokemon case) or, if we have a "meta", that is, a strategy that is, in general, the only competetively viable strategy (the League of Legends case), then **this** is what makes gameplay dull and boring, since it clearly, almost by definition, **greatly reduces** the pool of viable picks and strategies; and that game designers ought to avoid these pitfalls. Thus, a "perfect" game should have many viable picks, each different than another but none clearly useless, (that is, we should avoid the situation that if one wants to pick A, picking B instead will always be a better idea - some picks may and should be niche and/or situational though), that can be mixed in a plethora of ways to make a plethora of different, but viable teams, thus creating a plethora of different, but viable strategies (this doesn't mean that each team is equivalent or that a team assembled randomly is viable; teams can still be good or bad, but we should avoid the situation that there is only one viable prescription for a good team).

However, what I was being told seems to boil down to something opposite. The people I quoted seemed to think that good balancement of a game can only be achieved at the cost of making all possible picks equivalent, to the point of making it matterless what to pick. They also seemed to think that therefore, in such a scenario, an obvious winning strategy would inevitably emerge, making the game trivial.

Is it really true that a game can only be well balanced if it sacrifices all of its diversity? Is it really true that getting rid of useless picks can only be achieved at the cost of introducing a trivial winning strategy??

# Answer
This is a misunderstanding of the concept of game balance.

Game balance does not mean uniformity among the tools used by players; it means that no one tool (or set of tools) sits far above the rest in terms of efficacy.

At its perfection, game balance pursues a situation where it is not the tool that matters (be it a pokemon, a weapon, a character or an ability set etc.) but the player's familiarity, understanding and skill with use of the tool to achieve success: the tools work differently, play differently, require their own unique pursuit of mastery, but have no outstanding fundamental "better"ness above the others.

This does not, however, mean they must all be identical or even remotely similar in utility and performance! There are several techniques that aim to balance a game while making each tool unique:

* Making a tool powerful in many circumstances but with a fatal, exploitable flaw
    + Different skill ceilings for different tools - a seemingly weak tool, with practice, exceeds others
    + "Rock paper scissors" - no one tool is better than all the others, it is strong against some but countered by others
    + A more powerful tool may have limited resources, requiring the player to manage their use of it

Pokemon makes use of a few of these, the obvious one being its "Rock paper scissors" style use of elemental types with strengths and weaknesses (going down two levels for further complexity).

---

Pokemon is an interesting example because it is arguably not strictly a competitive game - its initial iterations were very poorly balanced, in fact, but as you said it relies to some degree on emotional connection to the team you catch and train. However it does have a significant competitive scene which has gone to long lengths to "round off" some of the edges to make things fairer - such as bans on some of the explicitly more powerful pokemon (legendaries etc.) and limitations on some moves to prevent overt exploitation.

In the end I'd actually argue against your perception of it as an "Imbalanced game" - balance is a sliding scale and I would wager a game any more complicated than pong or tetris is near impossible to balance perfectly. Even games that *do* have identical rules for both players are imbalanced to some degree - see first move advantage in Chess, where white wins slightly over 50% of the time!!

Game balance is like philosophy: it is not the achievement of the perfect answer that counts, but the pursuit of one. To bring up some good examples, Starcraft is known for constant tweaking of its mere three races to come as close as possible to that perfect 1:1 ratio, while League of Legends similarly has to battle with introducing new content while updating the old to keep them in line.

---

Another thing to consider which is missed when considering tools purely at the mathematical level... it misses the human element:

If I pick the rubber-chicken-on-a-wheel against a skilled swordsman you might think it a foregone conclusion... but being a master of poultry I might trick him into underestimating my ability; I might confuse him into exposing his weakness; I might anger him into making a fatal mistake; I might even just humiliate him into forfeiting the match!

All games are psychological games: if you can beat your opponent's mind, whatever tool you pick becomes irrelevant...
> 8 votes

---
Tags: balance
---


# Question
Title: How can I avoid assets reload if an Android activity is re-created?
I've put my libGDX view inside a bigger Android layout. When the user rotates the screen, a new layout specific for the orientation is drawn, for this reason, the activity is rebuilt from scratch forcing the libGDX view to reload all assets.

I tried to store these assets in a static variable, but on the second time I create the libGDX view, they are not rendered correctly (it looks like textures are not loaded and everything is transparent).

How can I avoid reloading heavy assets (models and textures)?

# Answer
i haven't seen much that implementation, usually you have to create your assets every time you enter a new level, and dispose all of them if you change of level/screen, when libgdx reload all assets at the same time is freeing memory of other assets, to implement what you want is more an issue of game design, i mean, if you know there will be the same background in several levels, then you have to load that asset once and have in memory or not to dispose it under specific circunstances.
> 0 votes

---
Tags: libgdx, asset-management
---


# Question
Title: Why do I keep getting an exception about "an element with the same key already exists" in this code?
I'm trying to follow this tutorial about object pooling in Unity

I got to minute 17:22. But when I run the game I get this exception:

```
ArgumentException: An element with the same key already exists in the dictionary.

System.Collections.Generic.Dictionary`2[System.String,System.Collections.Generic.Queue`1[UnityEngine.GameObject]].Add (System.String key, System.Collections.Generic.Queue`1 value) (at /Users/builduser/buildslave/mono/build/mcs/class/corlib/System.Collections.Generic/Dictionary.cs:404)
ObjectPooler.Start () (at Assets/Scripts/ObjectPooler.cs:31)

```

This script is attached to a new empty GameObject:

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

public class ObjectPooler : MonoBehaviour
{
    [System.Serializable]
    public class Pool
    {
        public string tag;
        public GameObject prefab;
        public int size;
    }

    public List<Pool> pools;
    public Dictionary<string, Queue<GameObject>> poolDictionary;

    private void Start()
    {
        poolDictionary = new Dictionary<string, Queue<GameObject>>();

        foreach(Pool pool in pools)
        {
            Queue<GameObject> objectPool = new Queue<GameObject>();

            for (int i = 0; i < pool.size; i++)
            {
                GameObject obj = Instantiate(pool.prefab);
                obj.SetActive(false);
                objectPool.Enqueue(obj);

                poolDictionary.Add(pool.tag, objectPool);
            }
        }
    }
}

```

Like in the tutorial I'm making size of 1 of the Pools in the Inspector then giving as tag name: Cube then drag a cube prefab to the Prefab then set the size to 150.

But I'm getting this exception when running the game.

# Answer
> 1 votes
In the innermost loop of `Start()`, you're trying to add `objectPool` to the `poolDictionary` using `pool.tag` as the key. This innermost loop executes once for every slot in the pool, and `pool.tag` is the same for each invocation, thus the exception. It also doesn't seem to make that much sense, placed there.

It looks to me like what you *want* is to add `objectPool` to `poolDictionary` outside the `for` loop, and add each new game object to `objectPool` inside the `for` loop. Something like this:

```
foreach(Pool pool in pools) {
  Queue<GameObject> objectPool = new Queue<GameObject>();

  // Insert into poolDictionary here, not in the loop below.
  poolDictionary.Add(pool.tag, objectPool);

  for (int i = 0; i < pool.size; i++) {
    GameObject obj = Instantiate(pool.prefab);
    obj.SetActive(false);
    objectPool.Enqueue(obj);
  }
}

```

Provided every `pool` has a unique `tag` value, this should work the way you expect.

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


# Question
Title: How can I make a custom editor that creates/deletes game object clones around a given point
I have been manually creating and deleting clones of my game objects that I arrange in a circle around a given point. Each of the objects is rotated making each object the same angle apart from the others as seen in the image below.

My objects range from 2 to 10. Doing this manually is very cumbersome, especially when changes have to made. How can I create a unity custom editor that allows me to specify a number of game object clones I want to create around a specified anchor point? Additionally, adjusting the number of clones should dynamically create/delete clones and reposition/rerotate them.

# Answer
Make an object and position at the center of your circle. If you already have an object with a custom script there, make an Inspector for it. If you don't have anything, make a script. It doesn't have to do anything. It might just hold data. A custom inspector just needs an script. Let's call them `CircleSpawn` and `CircleSpawnEditor`. CircleSpawn gets attached to the object at the center of the circle. It might look like this:

```
public class CircleSpawn : MonoBehaviour {
    public float radius;
    public int numOfItems;
    public GameObject clonedObject;
    public List<GameObject> spawnedObjects;
}

```

CircleSpawnEditor needs to be saved to a folder called `Editor` and looks something like this:

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

[CustomEditor(typeof(CircleSpawn))]
public class CircleSpawnEditor : Editor
{

    public override void OnInspectorGUI()
    {
        var tar = (CircleSpawn)target;

        //set its values
        tar.radius = EditorGUILayout.FloatField("Radius:", tar.radius);
        tar.numOfItems = EditorGUILayout.IntField("Number of Items:", tar.numOfItems);
        tar.clonedObject = (GameObject)EditorGUILayout.ObjectField(tar.clonedObject,
                       typeof(GameObject), true);

        //Inspector button for creating the objects in the Editor
        if (GUILayout.Button("Create"))
        {

            //clean up old objects
            if (tar.spawnedObjects != null)
            {
                foreach (var ob in tar.spawnedObjects)
                {
                    DestroyImmediate(ob);
                }
            }
            tar.spawnedObjects = new List<GameObject>();

            float angleBetween = 360.0f / tar.numOfItems;
            float angle = 0;
            for (int i = 0; i <= tar.numOfItems; i++)
            {
                //for each object, find a rotation and position
                var rot = Quaternion.Euler(0, angle, 0);
                var localPos = rot * Vector3.forward * tar.radius;
                tar.spawnedObjects.Add(Instantiate(tar.clonedObject,
                    tar.transform.position + localPos, rot));
                angle += angleBetween;
            }
        }
    }
}

```

I tested it and the result looks like this:
> 1 votes

---
Tags: unity
---


title: How do I get extents in my mesh

text:
# Question
Title: How do I get extents in my mesh
I am creating a AABB for collision detection. I need to calculate the extents for my model and also update them when my model moves. I calculate my min and max when I create my mesh and I use my position to reference the center.

Could someone please show me how to get the extents either with my min and max vectors or with an array of vertices.

Actually for more clarification I tried this

```
public Vector3f getMin() {
    return Vector3f.sub(pos, extents, null);
}

public Vector3f getMax() {
    return Vector3f.add(pos, extents, null);
}

```

The problem is that everything seems to be centered around the origin(0,0,0). The position is the position of the entity the AABB represents.

# Answer
> 0 votes
The size of the box that covers the whole mesh is simply the difference between the max and the min position: `vec3 size = max - min;`.

Now from that you can get the extents simply by halfing the size: `vec3 extents = size * 0.5f;`

---
Tags: mesh, aabb
---


# Question
Title: Can all DirectX11 games be deployed to Xbox One?
If I program a game with DirectX 11 and C++ and make my own implementation can I deploy it on an Xbox one to test it? Otherwise, what do I need to do so?

# Answer
Short answer is: **yes, you can**.

As stated on the ID@Xbox webpage for independent game developers:

> **Can I use my retail Xbox One as a developer kit?**
>
> Yes, you can. Once you download the preview version of the Xbox Dev Mode Activation app, you can unlock dev mode on your Xbox One and experiment with creating games for a "10 foot" living room experience. You don't need to be part of ID@Xbox to get started, but we're here to help if you want to ship a UWP game on Windows 10, or ship a game on Xbox One.

That means you can use a commercial console and turn it into a testing environment for your games. That's all if you are working on your own, at least: if you are developing a game using an engine like Unity you are required to register.

By the way registration is free, as stated on the site:

> **What will it cost me?**
>
> There are no fees to apply to ID@Xbox, to submit a game to certification, publish, or update your games. There is a very modest one-time cost associated with development for the Universal Windows Platform.

You are paying only if you want your game to include UWP features, such as gamertags, achievements, dedicated multiplayer services, and so on.

To use developer mode, you need to download the Dev Mode app on your console from the store that lets you switch between *retail mode* and *developer mode*. There are several guides and how-to's, on the Windows Dev Center page there's a deep explanation of *developer mode* as well as other steps; also take a look to these articles on Polygon and Windows Central, Polygon's is clear about differences between free and paid preview of dev mode as well as their limitations. Check the FAQs if in doubt.

Finally, if you want to set up your development environment and try to make a simple Hello World app, you can follow this guide found in the Microsoft Developers documentation.
> 4 votes

---
Tags: c++, xbox
---


title: How to design phases of a single turn

text:
# Question
Title: How to design phases of a single turn
Battles in my game run fully automatically and return a combat log afterwards. My main game loop looks like this:

```
public BattleResult run() throws BattleException {
    BattleResult result = null;
    while((result = this.determineWinners()) == null) {
        // TODO: execute the turn an move on to the next character
        this.history.add(new BattleLog(this.currentState.copy()));
    }
    return result;
}

```

Basically, as long as the game isn't over `determineWinners` will return null and the main loop continues. Once a win condition is reached (usually all characters of either one or both teams have died), the method wraps the battle history together with the winners and returns them, causing the loop to break.

The important part is handling each individual turn, which right now consists of several phases:

* turn start: set `state.currentCharacter` to `state.nextCharacter` and `state.playedCard` to null. If the current character is stunned, skip to the last phase
* draw card: instruct the current characters deck to return the next card and store it in `state.playedCard`. If the deck is empty, null is returned, causing the character to die and skip to the last phase
* play card: Retrieve the card from state and resolve its effects
* (not implemented yet) apply on-turn-end effects
* set `state.nextCharacter` to the next character in order or leave it as-is, if the current character gets to take another turn. Dead characters are skipped over

Right now, i'm implementing my turns like this:

```
public BattleResult run() throws BattleException {
    BattleResult result = null;
    while((result = this.determineWinners()) == null) {
        Phase phase = this.startingPhase;
        while(phase != null) {
            phase = phase.execute(this.currentState, this.effectFactory);
        }
        this.history.add(new BattleLog(this.currentState.copy()));
    }
    return result;
}

```

```
@FunctionalInterface
public interface Phase {
    public Phase execute(BattleState state, EffectFactory factory) throws BattleException;
}

```

```
public final class DefaultPhases {
    public static final Phase TURN_START = new TurnStart();
    public static final Phase DRAW_CARD = new DrawCard();
    public static final Phase PLAY_CARD = new PlayCard();
    // ...
    public static final Phase SET_NEXT = new SetNext();
}

```

```
public class TurnStart implements Phase {

    @Override
    public Phase execute(BattleState state, EffectFactory factory) throws BattleException {
        state.advanceCharacter();
        state.setPlayedCard(null);
        return DefaultPhases.DRAW_CARD;
    }
}

```

```
public class DrawCard implements Phase {

    @Override
    public Phase execute(BattleState state, EffectFactory factory) throws BattleException {
        CharacterState character = state.getCurrentCharacter();
        Card card = character.drawCard();
        if(card == null) {
            character.setLife(0);
            return DefaultPhases.SET_NEXT;
        }
        state.setPlayedCard(card);
        return DefaultPhases.PLAY_CARD;
    }
}

```

```
public class PlayCard implements Phase {

    @Override
    public Phase execute(BattleState state, EffectFactory factory) throws BattleException {
        factory.getEffect(state.getPlayedCard().getId()).resolve(state);
        return DefaultPhases.SET_NEXT;
    }
}

```

```
public class SetNext implements Phase {

    @Override
    public Phase execute(BattleState state, EffectFactory factory) throws BattleException {
        // some logic to determine the next character
        return null;
    }
}

```

So, every phase executes its logic (setting up the turn, drawing a card, playing it, etc) and returns the next one. Once a phase returns null, the turn ends, the current state is saved into history and the next turn begins (unless the game is over).

In general i like this system, as it allows me to dynamically skip or add phases, depending on whatever i need and i can also completely change the rules of a battle by setting `startingPhase` to something else than `DefaultPhases.TURN_START`.

But, since this is my first time designing a system like this, i would like to get some feedback about my design or if i should better use something different.

# Answer
> -1 votes
i think you may read a little about "finite state machine" and how to implement that in a game, with that in mind i think you can make a better desing not only for what you want, but for others users as well.

---
Tags: java, state, turn-based
---


# Question
Title: Can I output a text file on build with build details in it?
We have an issue with organizing our builds. They get copied around and moved so much that it's hard to keep track of what is the newest.

I would like to output a simple text file to the build root (same level as exe) that contains info like the build date and time, platform, etc.

Is this possible from within Unity? Right now we have no automated build process (CI/CD).

edit: I found `onPreprocessBuild()` but unfortunately one of our main projects still uses Unity 5.3.6f1, so this will not work. Is there an alternative?

# Answer
> 2 votes
In Unity 5.3, there is the `PostProcessBuildAttribute`. "Add this attribute to a method to get a notification just after building the player." (Source: UnityEditor.Callbacks.PostProcessBuildAttribute documentation.)

Using that attribute, you should be able to set up something like:

```
[PostProcessBuild]
public static void OnPostprocessBuild(BuildTarget target, string pathToBuiltProject)
{
    CreateBuildTimestampFile(pathToBuiltProject);
}

private static void CreateBuildTimestampFile(string pathToBuiltProject)
{
    string directory = Path.GetDirectoryName(pathToBuiltProject);

    string timestampFile = Path.Combine(directory, "timestamp.txt");

    if (File.Exists(timestampFile))
    {
        File.Delete(timestampFile);
    }

    using (var streamWriter = File.CreateText(timestampFile))
    {
        var timestamp = System.DateTime.UtcNow.ToString(CultureInfo.InvariantCulture);
        streamWriter.WriteLine(timestamp);
    }
}

```

As a side note, you may find the Unity 5.3 Build Player Pipeline documentation page useful as well.

---
Tags: unity, build-process
---


title: How much "real life" immersion is good?

text:
# Question
Title: How much "real life" immersion is good?
I've been making a visual novel game where the Player Character can get hungry, thirsty, has energy and also needs to go to the toilet, has sanity, has cleanliness, has life, has money, has a reputation in the school he visits, has a "Love-Meter" with his relationship partner (for now), strength, intelligence and the list goes on and on.....

But now I think too much of those things would rather "bother" the player than add fun.

But then I also think a lot of survival games have those things and it's a lot of fun to keep those numbers up and survive or get punished.

Now I'm struggling with the balance between making "too much" and "too few".

So maybe one experienced Game Designer here has a good answer for this problem. How much "real life" immersion is good?

# Answer
> 91 votes
Realism is generally not a good guide to game design. When someone asks you "What is your game design reason for having the player tell their character when to go to the toilet?" and your only answer is "realism", then you are doing something wrong. People play video games to *escape* reality. When the player wants a 100% realistic experience, they would stop playing video games and go outside.

Games are primarily about two things:

* Challenge the player's skills
* Let the player live out a fantasy they can't live out in real life

I *could* imagine a game concept where your character's bladder capacity is an important resource to manage and it actually makes the game more interesting to play. *The Sims* certainly pulled this off successfully. But the idea of *The Sims* is a very unique game concept. Taking care of the basic everyday functions of a human being was the main fantasy of the game. And even though it is not a particularly extraordinary fantasy, the series and its countless expansions still sold over a hundred million copies, making it one of the best selling game series of all times.

When you consider to add a bladder management mechanic to your game, you should ask yourself:

* **Does it contribute to the fantasy you want the player to live out?** If you want the player to live out the fantasy of being an action hero, emperor, criminal, business owner or casanova, then the mechanic might not actually add anything to that fantasy. So it should not have a place in your game.
* **Does it make the game more interesting?** Does it lead to hard decisions to make? Does it lead to interesting optimization challenges? Does anything interesting happen on the toilet? Does it have interesting interactions with other game mechanics? If it does - fine. If it is just something you need to take care of by clicking "use toilet" whenever the "pee" bar is full, it's just an annoyance which distracts from the parts of the game which are actually interesting.

# Answer
> 37 votes
---

## Believability instead of realism

I would argue that realism is not bad per-se. However, realism should not be your objective, and it is not good excuse - by itself - for introducing game mechanics. *Instead the place of realism in video games is as a particular esthetic, which you may want or not, but that is another topic.*

Instead, you should aim for immersion. And believability is your main tool for that. It means that you should not aim to create something that matches our reality, but something that players can believe about your fictional world.

*This is also a good principle when creating animations or character designs. Your world can have crazy creatures that cannot exist in reality, and nobody cares. But if their physicality is wrong, they lose believability, most people will know it does not look right.*

Often times excluding things helps believability, because once you portray something, players can ponder if that makes sense. Meanwhile, if the soldier at war does not have the need to go to the bathroom, it will not break immersion because everything else keeps the player engaged.

Your base line for believability is popcorn/fridge logic:

> You know. You’ve just come home from a movie, you had a great time, you go to the refrigerator to get a beer, you open the door, and you say, ‘Wait a minute …’

-- Jonathan Demme

However, sometimes you include things because it helps believability.

---

## Toilets and complexity

The Sims is certainly the main example, up to the point of being nicknamed "The Toiled Game" within Maxis. The Sims has toilets, because if the game did not have them, you would notice (you build the house, after all). If it had them but sims did NOT use them, it will not make sense. Thus, The Sims needs toilets.

They also covered what happens if the sim can't go the toilet (accidents that needs cleaning). They added on top that toilets get dirty, and that they could break and flood the place.

*I also want to point out that The Sims added sobrenatural elements.*

However, I want to talk about a game that uses toilets much better: Prison Architect.

* Players would notice if there were not toilets to put in the cells.
* Why would players place toilets in the cells? Prisoners need to use the toilet.
* If they do not have access to a toilet, not only you will get accidents, that needs cleaning... but also it increases the chances of prisoners to riot.
* Furthermore, a toilet needs an active water pipe connection to work, meaning that you need to ensure that there is enough water supply and connected (the pipes can be destroyed).
* If they break a toilet, while still connected to water, it will flood the place.
* Furthermore, prisoners may hide tools, drugs and weapons in the toilet (which they can be smuggled by other means). Which they will use in their riots, gang fights and attempts to escape. Do not forget to search the prisoner’s cells.
* Oh, but prisoners will take advantage of your toilets to dig tunnels to escape. Search for tunnels regularly, put guard patrols and outer walls when you can.

The developers has gone up and beyond asking the questions about their world. Furthermore, they have managed to create interesting game mechanics around the answers to those questions. Moreover, the game – or at least that aspect of the game - is more engaging thanks to that.

As you can see, sometimes you need to add things for believability. And that building complex systems on top of that can be engaging, even with toilets.

It is, in fact, a good idea to turn this kind of problems (test players ask why there are not toilets) into fuel for creativity. If you have to include toilets, what interesting mechanical implication that might have for the game?

For instance, the sims can die. This is a possible out come of neglecting their needs. How can they make death mechanically interesting? They become ghosts, and go on scaring other sims, of course. Realistic? No.

Is it ok to aspire to create something like that? If that is your vision, sure.

However…

---

## Find a minimum viable product

Let me tell you about software engineering. We know that the complexity of the software increases exponentially with the number of requirements. We also know that the number of possible bugs increases with the complexity of the software.

I will refer you to “What We Actually Know About Software Development, and Why We Believe It’s True” by Greg Wilson.

This means that if you can remove requirements, not only you create a software in less time and with less bugs, but also the improvement will be super linear.

This is a good argument to take your design and start removing things. File them for version 2.0 or whatever. Another argument is that you will be able to find the core of your design: the minimum viable product. Ship this first.

*Oh, and any bugs you leave alive build up your technical debt, they charge interests (the longer you take to fix a bug, the more expensive, and that is exponential).*

I am not telling you that you should not go for a crazy design; I am telling you that you need to start small. Plan how you will add stuff on top, and grow over time.

Back to The Sims, they called it “The Toilet Game” because it required doing unappealing tasks such as going to the toilet and cleaning it. In addition, executives initially rejected the project. However, the developers kept working on it until they created something that executives approved. It required years to archive it, of course, but look the success that The Sims has.

---

## Growth and design, by examples

I have told you to find a minimum viable product, and to make that product grow. You can plan how to extend it ahead of time, which will save you a lot of trouble. However, once you do, you will have effectively coupled those systems to your core design, and that can bring trouble.

Examples:

* The Sims. They had many expansions, which means many systems for which they had to plan. That is a form of Accretion (look it up). That kept the evolution of their core mechanics in check. The Sims 4 was a return to rework the core of the game, and that is a good thing to do.
* Civilization. Again, it had accretion, and people were used to - and enjoyed - the complexity of all the interlocked systems. However, that complexity meant a high entry point for new players that had to learn a lot to be competent in the game. Again, the developers did a return to the core mechanics, and Civilization V shipped with an overhaul of the core principles of the games (down to the grid and movement), there was some backslash from veteran players, but it served as entry point for many new players who were not following the franchise from the start. Then they went to improve it and add some of the complexity back in Civilization VI.
* Windows. Microsoft sells licenses and support to companies. Companies that has business critical software running on Windows. If the developers of that software used deprecated API functions, or relied on undocumented behavior, and as a result did not work in the new version of Windows… who do the company blame? Microsoft, because Windows was the thing that changed. They call support – that they are paying for – and Microsoft has to solve the problem. As a result, Microsoft developed a strong tradition of backward compatibility, Windows core grew in complexity, and the system started to become slower in each iteration. Until you got Windows Vista. Windows 7 was them going back to rework how they organized things. *Windows 8 was them going too far, and trying to appleal to the mobile market at the same time.*
* English. The spelling make little sense. Look at why the letter “e” sounds different “here” than “there”, and countless more examples. The abstract is because of “historical reasons”. As English takes words from different roots, and as those words evolve their pronunciation change. Then either you change the way you write it to match the pronunciation (breaking backwards compatibility with old documents that will no longer make sense to people learning with the new version of the word) or you let the spelling and pronunciation diverge. Furthermore, people has been finding ways to shorthand writing since the time of monk scribes. Nuthin new m8. Sometimes people did try to standardize. We have to thank the printed press for pushing the process. Yet, that is just spelling, "the structure of language grows, as a reef of dead metaphors" -- The Unfolding of Language by Guy Deutscher.

I am telling you that systems evolve, and that accretion happens. Yes, aim small. Yes, create a simple and elegant minimum viable product. However, plan and design the system in such way that it can grow, preferably avoiding strong coupling. Yet, every decision you do, cuts some path you didn't taken. If eventually you need to go back and rework, be ready.

# Answer
> 14 votes
No-one has exact answers to questions like these, especially not for a game they've never seen and one which presumably exists mostly (or only) inside your own mind.

The only answer is: Every designer has these questions, but the only way to resolve them is to build a simple prototype (or two, or three, or a hundred) and test, test, test until you find the kind of gameplay you desire. That is how most products are developed in industry, not just games.

You don't need fancy graphics, and you don't need complex rules, but what you do need to do is to *find the fun factor*. In this endeavour, it really is wise to follow RAD principles and make the simplest thing that allows you to test those game dynamics you mention, individually and together.

# Answer
> 5 votes
I think the answer is in your very first sentence actually. You are creating a 'visual novel' which is not the same as a survival game. Realism in descriptive text isnt the same as a game mechanic. That is where you are already diverting strongly from what you declared your product to be. A novel guides a user/player through a given story line (and sometimes splits into several possible story lines by giving choices).

Realism as a game mechanic is part of simulated environment which can be found in several types of games - survival games is just one of them.

Extending a novel into a life simulator is obviously an option but you are faced with the problem that you mix 2 completely opposite types of entertainment. Realism of environment as a mechanic caters to players who want to micromanage those type of events. Its the main mean of being entertained for them.

A novel on the other hand caters to the exact opposite of players. They want to be guided through a well written story, want to immerse in a given universe.

# Answer
> 3 votes
In game design, **Realism is a tool**, not a goal.

Realism serves multiple purposes:

* Intuitive design. E.g. No need to explain that: drink more -\> more going to the toilet
* Humor. Reality sets expectations, which can be exploited for humor. E.g. break the 4th wall.
* Advertisement. Many players are excited by the idea of simulating something. E.g. Kerbal.
* Educational, similar to the above. Some players and many parents/teachers are excited by games that promise to teach something. E.g. Kerbal.

---

If I have to mention just one thing about realism that players don't respond well to, it is excessive negative repercussions for events/actions outside of the player's control.

---
Tags: game-design, visual-novel
---


# Question
Title: Would it be good idea to use blender to create sprite and animating rather than using a 2d software to create sprites and animating them in 2d
I'm making this 2d side scroller game. I had been working on 3d games(modelling and animation) for 2 years, thus my experience with 2d sprites is none to zero.

So I've been struggling with asset creation in 2d especially thinking about animation is kind of stressing me out. There will be a lot of fighting animation in the game and may be that I'm new to 2d it just feels impossible to create a character and animating it do lots of combos.

An idea poped into my mind, using blender to create animation and rendering the animation as png to create spritesheet. I'm not sure if that's already a thing, I've did some research and there are people who do recommend and there are those who don't. It just felt a bit vague.

So my question is, would using blender to create 2d sprites and their animations be easier, since I'm exprienced with it. Or should I try to handle sprites in completely 2d? side note: every character is gonna be plain black(like shadow)

# Answer
> 2 votes
There are several famous games which used 2d assets pre-rendered from 3d models. It was quite popular in the late 90s when 3d rendering was still too slow to render decent-looking characters in real-time but was already mature enough to generate good looking pre-rendered sprites. A popular title which pioneered this technique was Donkey Kong Country. It became a common technique for real-time strategy games before 3d hardware became capable of real-time rendering hundreds of units with decent level of detail at once. The technique is still used today from time to time. One recent title which comes to mind is Factorio. The developers posted an article about their workflow on their development blog which might be interesting to you.

It is mostly a question of the kind of aesthetic you want to go for. Hand-pixeled sprites just have a different style to them. I don't want to say better or worse, just different. The different aesthetic might or might not fit your game, but it might be worth a try.

---
Tags: 2d, animation, sprites
---


# Question
Title: How To Get Current Selected Tiles and Neighbour
I've 2D array that store each planes that instantiate using code.

```
Tile[][] map;

```

Then in `Update()`function, I try to `Raycast` and i can get the tile from `RaycastHit` game object.

How to get which Tile in my 2D array `map` is hovered base from `RaycastHit` without loop each tiles in array and check it ?

# Answer
If your grid has uniform spacing, you can get this without raycasting, just using a bit of math.

Let's say `map[0][0]` has its center positioned at a worldspace point called `origin`, and `map[0][1]` is `spacing` units away from `origin` along the positive x-axis, and `map[1][0]` is `spacing` units away from `origin` along the positive y-axis.

Then...

```
var cursor = ConvertScreenCoordinatesToWorldCoordinates(mousePosition);

fromOrigin = cursor - origin;

int x = roundToInt(fromOrigin.x/spacing);
int y = roundToInt(fromOrigin.y/spacign);

```

Then you can get your neighbouring tiles by incrementing/decrementing `x` & `y` (and bounds checking to make sure you don'y try to walk off the edge of the map when starting from a tile right on the edge)
> 0 votes

---
Tags: c#, maps
---


# Question
Title: How can I set the radius the object will rotate around the target?
```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TargetBehaviour : MonoBehaviour
{
    // Add this script to Cube(2)
    [Header("Add your turret")]
    public GameObject Turret;//to get the position in worldspace to which this gameObject will rotate around.

    [Header("The axis by which it will rotate around")]
    public Vector3 axis;//by which axis it will rotate. x,y or z.

    [Header("Angle covered per update")]
    public float angle; //or the speed of rotation.

    public float upperLimit, lowerLimit, delay;// upperLimit & lowerLimit: heighest & lowest height;
    private float height, prevHeight, time;//height:height it is trying to reach(randomly generated); prevHeight:stores last value of height;delay in radomness;

    // Update is called once per frame
    void Update()
    {
        //Gets the position of your 'Turret' and rotates this gameObject around it by the 'axis' provided at speed 'angle' in degrees per update
        transform.RotateAround(Turret.transform.position, axis.normalized, angle);
        time += Time.deltaTime;
        //Sets value of 'height' randomly within 'upperLimit' & 'lowerLimit' after delay
        if (time > delay)
        {
            prevHeight = height;
            height = Random.Range(lowerLimit, upperLimit);
            time = 0;
        }
        //Mathf.Lerp changes height from 'prevHeight' to 'height' gradually (smooth transition)
        transform.position = new Vector3(transform.position.x, Mathf.Lerp(prevHeight, height, time), transform.position.z);
    }
}

```

Now it's rotating in a constant radius. I set the variable axis to 0,1,0

But if I want the object to rotate around the turret very close to it or very far ? I want to add a radius variable so I can change and set the radius.

# Answer
This line: transform.RotateAround(Turret.transform.position, axis.normalized, angle); is saying rotate the cube around the turret. So if you want to rotate farther away you need to move the cube farther away. To do this first we find the current vector representing the current radius which would simply be position of the cube minus the position of the turret. This gives us the radius from the turret. Then let us say you want a radius of 40, this is the current radius normalized (the same vector but of length 1) multiplied by 40. So this will be the new radius from the turret. Should look something like this:

```
public float radius = 40;

void Start()
 {
        if (radius > 0)
        {
             var newPos = (transform.position -Turret.transform.position).normalized * radius;
                newPos += Turret.transform.position;
                transform.position = newPos;
        }
 }

```
> 2 votes

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


# Question
Title: How can I attach a script to a GameObject prefab at runtime?
I've got a script that manages a scene browser within my application where I'm hoping to generate a new button instance for each scene found. I've put together a button that I've made into a prefab and everything works up until I try to attach click behavior to the button. So far I am unable to capture or attach anything to the "onClick()" piece of the button component no matter what I try.

Code is as follows:

```
MySceneBrowser.cs
   foreach(string sceneName in sceneList){
     GameObject sceneButton = Instantiate(SceneButton) as GameObject;
     // Attach the scene name to the nested text UI object of the button
     sceneButton.GetComponentInChildren<Text>().text = sceneName;
  /* Where I hope to attach script and method with parameter, method is within
   * this class and called LoadSelectedScene(string sceneName)
   */
     sceneButton.transform.SetParent(SceneListPanel, false);
     }

```

Where in the inspector SceneButton is assigned to the prefab I've created, SceneListPanel is set to a content panel, and the scene list is generated in another method.

Any attempt I make to get the button component and allow me to set the onclick() fails, it just doesn't seem to exist through the script editor.

Setting any of these items through the inspector works, but I can't assign my controller class to the prefab before RunTime. I tried attaching a script directly to the prefab, but in this case only MonoBehavior functions were present through the inspector and I was unable to find any other method.

Once I attach the script I also need to be able to add the sceneName as the parameter.

\[Edit\] DMGregory pointed out I didn't elaborate on what I've tried so far, at this time I've tried the following (likely very wrong, still new to Unity) attempts to attach the desired script method:

* sceneButton.AddComponent\< SceneBrowserController \>().LoadSelectedScene(sceneName);
* Button b = sceneButton.GetComponent\< Button \>(); b.OnClick()...\<--- Script can't find onClick, doesn't exist, doesn't show it as an option in code completion, etc.
* sceneButton.AddComponent\< SceneBrowserController \>.LoadSelectedScene(sceneName); \<-- obviously doesn't add it to the onClick listener, just attaches the script
* SceneButton.AddComponent\< UIEventListener \>()....
* UIEventListener.Get(sceneButton).onClick().....

This is in general the attempts I've made so far, with some variation. I don't have all my old attempts saved unfortunately. I'm sure I'm making a newbie assumption/mistake somewhere.

While playing with the prefab through my script I went ahead and tried this out:

```
if(sceneButton.GetComponent< Button >()){
Debug.Log("This object is here");
}

```

and it returns false on the if, if I change the if to (!sceneButton.GetComponent()) it does show the log message. To my understanding this indicates the button game object is not found, yet it is a component on the top level of the prefab.

Also, can anyone explain why this doesn't work to attach the onclick listener?

```
sceneButton.GetComponentInChildren<Button>().OnClick.AddListener(() => LoadSelectedScene(scene));

```

Gives the following compiler error:

```
Assets/.../.../.../SceneBrowser.cs(347,68): error CS1061: Type `Button' does not contain a definition for `OnClick' and no extension method `OnClick' of type `Button' could be found (are you missing a using directive or an assembly reference?)

```

As close to showing my full code as possible:

```
using UnityEngine;
using UnityEngine.UI;
using System;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using System.Text.RegularExpressions;

public class MyFileBrowser : MonoBehaviour
{
 Public GameObject SceneButton; // This is assigned to the prefab in inspector, they render properly.
 [...]

 public void LoadSelectedScene(string sceneName){
  // This is the method I'm hoping to reference in the onClick listener, while passing it the scene name
 }

[...]

private void DisplaySceneList(string[] scenesOutput){

   foreach(string sceneName in sceneList){
     GameObject sceneButton = Instantiate(SceneButton) as GameObject;
     // Attach the scene name to the nested text UI object of the button
     sceneButton.GetComponentInChildren<Text>().text = sceneName;
  /* Where I hope to attach script and method with parameter, method is within
   * this class and called LoadSelectedScene(string sceneName)
   */
     // Current attempt:
     sceneButton.GetComponent<Button>().onClick.AddListener(() => LoadSelectedScene(sceneName));
    // The onClick.AddListener[...] is all red in MonoDevelop, hover message says "'Button' does not contain a definition for 'onClick'

     sceneButton.transform.SetParent(SceneListPanel, false);
     }

}

```

This is with a prefab with the following structure:

* SceneBrowser\_SceneSelectButton (Image Component, Button Component, Layout Element Component)
    + Scene Image (Image component w/ sprite)
    + Scene Label (Text component)

I can access the Scene label no trouble with "GetComponentInChildren\< Text \>.text \[...\]" but cannot get "GetComponent\< Button \> on the sceneButton object created from this prefab. Oddly, "GetComponent\< Image \> does capture the image component off the top level object just fine.

# Answer
we can't able to assign onclick() function on run time. so use event system to declare your function. This ll shows you how to use event listener for a button

**Edit 1:** Declare the header for scene management

```
using UnityEngine.SceneManagement;

```

initialise the scene

```
Scene m_Scene;

```

Remove this line

```
sceneButton.GetComponentInChildren<Text>().text = sceneName;

```

Replace as

```
m_Scene = SceneManager.GetActiveScene();

```

`sceneButton.GetComponentInChildren<Text>().text = m_Scene.name;`

Then remove this line

```
sceneButton.GetComponent<Button>().onClick.AddListener(() => LoadSelectedScene(sceneName));

```

Replace as

```
sceneButton.GetComponent<Button>().onClick.AddListener(() => LoadSelectedScene(m_Scene.name));

```
> 1 votes

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


# Question
Title: Object is not rotating from right direction
im beginner to unity so im using this code to rotate object with mouse with max rotation of 35 degrees,it is working but it's only possible to rotate object if mouse is under of that object. here is my code:

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

public class rotObj : MonoBehaviour {
    //private float baseAngle = 0.0f;
    private float maxRotaion = 35f;
    void Update () {
        var dir = Camera.main.ScreenToWorldPoint (Input.mousePosition) - transform.position;
        var angle = Mathf.Atan2 (dir.y, dir.x) * Mathf.Rad2Deg;
        if (angle >= -maxRotaion && angle <= maxRotaion)
            transform.localRotation = Quaternion.AngleAxis (angle, Vector3.forward);
    }
}

```

as i think, localrotation is making that problem? how can i fix this without removing maximum rotation angle and will be able to rotate object not just from mouse under object, but from any position? my english grammar is very bad but i hope you will understand

# Answer
> 0 votes
The standard mathematical convention for the angles returned by `atan2(y, x)` is that they're measured counter-clockwise from the positive x-axis.

If I understand your problem correctly, you want to measure them from the positive y-axis instead, which you can do by rotating your coordinates 90 degrees clockwise (exchanging x & y and negating x):

```
var dir = Camera.main.ScreenToWorldPoint (Input.mousePosition) - transform.position;
var angle = Mathf.Atan2 (-dir.x, dir.y) * Mathf.Rad2Deg;

```

Or, for more flexibility, you could capture the direction your object is pointing at startup, and measure your angles from that direction. Then you can rotate your turret to any arbitrary angle and it will work, without needing different `atan` math for every combination:

```
Quaternion initialOrientation;

private void Start() {
    initialOrientation = transform.rotation;
}

void Update() {
    var dir = Camera.main.ScreenToWorldPoint(Input.mousePosition + Vector3.forward) - transform.position;
    // Rotate the direction into our initial reference frame.
    dir = Quaternion.Inverse(initialOrientation) * dir;

    var angle = Mathf.Atan2(-dir.x, dir.y) * Mathf.Rad2Deg;
    angle = Mathf.Clamp(angle, -maxRotaion, maxRotaion);

    // Rotate the result back into worldspace.
    transform.rotation = initialOrientation * Quaternion.AngleAxis(angle, Vector3.forward);
}

```

---
Tags: unity, c#, rotation, quaternion, angles
---


# Question
Title: Are we supposed to be creating player prefab?
This may seem like a dumb question, but I want a single player object for the entirety of my game. However when I load multiple levels obviously I need to reload the player so I would create a player prefab and instantiate him. However, it seems counterintuitive as prefabs are for objects you want to create multiple instances of easily, correct? Also, I need values to be carried over accross levels for my player object therefore I guess I would need a static global singleton to store the player objects.

Hence the dilemna and confusion! Can anyone help me out here?

# Answer
> 5 votes
Games really aren't about "supposed to" - they're about what works and what doesn't.

If creating a player prefab makes it easier for you to spawn the player avatar in any scene you need them in, and that works for your needs, then it's a good solution.

No Unity police will knock on your door and say "I heard you used a prefab for an object that's only spawned once. That'll be a bajillion dollar fine" - the tools exist for you to get your work done, so use them the way that makes sense to you.

> Also, I need values to be carried over accross levels for my player object therefore I guess I would need a static global singleton to store the player objects.

Not necessarily. You could also use `DontDestroyOnLoad` or additive scene loading to persist one instance of an object throughout your game, rather than unloading & respawning it every time you change to a new level.

---
Tags: unity, game-design
---


# Question
Title: How to implement circle clipping in SDL2?
In SDL2 there's a function to set a rectangular clip mask:

```
int SDL_RenderSetClipRect(SDL_Renderer* Renderer, SDL_Rect* clip);

```

If i call this function, copied textures will be displayed in this clip rect but not outside of it. What I'm wondering is if it's possible to set a circle as a clip?

For example, in Material Design:

There are some buttons with the shape of a circle and when you click on them, it appears a small circle from the cursor and this becomes bigger. This small circle is not display outside the button but only inside. And so, i want to do this. I want to renderer a texture that is clipped with a circle.

I don't think `SDL_RenderSetClipCircle` exists, so how could I emulate this?

# Answer
Yeah, just as you thought there is no function to use a clip rectangle. However, if your use case is limited enough, you should be able to simulate this with render targets & blend-modes. Here's how you could do that:

1. Create a render texture that is transparent and can fit your circle in it.
2. Render your circle to the render texture.
3. Change the blend mode to `SDL_BLENDMODE_ADD`.\*
4. Render whatever you want to render on top of the circle in the render texture.
5. When done, just render the render texture to the default target (window).

\*If you don't want additive blending, you could take a look at `SDL_ComposeCustomBlendMode`. I haven't used that myself but it looks like you might be able to implement a blend mode that takes the source color but keeps the destination alpha.

Incase you're unable to figure out the custom blend mode on your own, here's something to get you started:

```
 SDL_ComposeCustomBlendMode(SDL_BLENDFACTOR_ONE, SDL_BLENDFACTOR_ZERO, SDL_BLENDOPERATION_ADD, SDL_BLENDFACTOR_ZERO, SDL_BLENDFACTOR_ONE, SDL_BLENDOPERATION_ADD);

```

Do note that I haven't tried this out myself, but here's how I built that blend mode: First, we wanted to keep the source color, and not let the destination color affect that. So, we simply keep the source color as what it is (so multiply by `SDL_BLENDFACTOR_ONE`) and zero out the destination color (`SDL_BLENDFACTOR_ZERO`). Those can then simply be added together to get the source color as a result. Similarly, for alpha, we wanted to keep the destination alpha, so we zero out the source alpha but keep destination alpha as what it is. These can be added together.
> 1 votes

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


# Question
Title: Packet/Event-Based Entity-Component-System
I know what one of the big commonalities I see in ECS projects is that there is a main game loop that iterates through systems and calls their respective update methods (for example, RenderSystem).

I'm a bit stumped on how this applies to an event-based game where the client sends packets of information and you update from there. For example:

**MovementPacket**

1. Read incoming movement packet and send to appropriate packet handler, which makes changes to appropriate components regarding entity through systems.
2. Packets are then sent back through the systems (which work with components to access the data needed to write these packets).

Now, I'm not sure where a game loop really comes in here, since everything seems to be event-based. I'm scared that most of the work I'm doing ultimately for ECS just isn't being done right. My systems are typically becoming "containers that do logic and stuff, but don't operate within a game loop."

In fact, the game itself doesn't have a game loop, since we haven't really found an area to insert it in.

Is the approach just **wrong**? Is my approach towards interweaving ECS with this packet-based game for the most part incorrect?

# Answer
> 1 votes
You dont quite seem to understand, what events are really there for.

First of all, the game loop has an intentional order. Imagine you would first do the movement, then the physics in one frame, but in the next frame you do it the other way round. Maybe your character could suddenly move through walls or similar strange behavior.

As you describe it, your events are basically just callbacks from one system to another. One system does something, the other system has to react to it, so the first system calls it and sends its data to change. That would imply, that every system knows each other, so it can call it with an appropriate callback-function. This would mean, that you couldn't guaranty the order the systems are called, let alone how often a system is called each frame. Or if the other system even cares if it should react to an event.

Events are like messages in a message board. Back to your example:

1. Your MovementSystem registeres the player presses the button for moving right, so it set the value in the direction component and creates an event marked for the PhysicsSystem(to calculate the real position change) and the GraphicsSystem (to maybe start an animation loop).
2. The next System is the GameplaySystem. Its update function is called and sees that the character is in a trap, so it posts an event only ment to the physicsSystem saying not to move. It also posts another event but with a 5 second timer, to accept movement again.
3. Next in line is your PhysicsSystem, so it does it regular update and calculates every frame stuff (like gravity, etc.) and then checks the EventBoard for events ment for the PhysicsSystem. Now the interesting part: it finds the MovementEvent, so it changes its velocity component to the right value, then reads the Trap event and changes the value back to zero. Then still in the update function, it sets its position of the character depending on the velocity, which is now zero. Since it read both events, it checks that it had read them. so the trap event disappears. The other event with the timer is not yet due, so it won't be read.
4. The GraphisSystem calls it update and checks for events, where the movement Event is still on the board. It doesn't care, that the position hasn't changed, so it starts the movement animation. Your character is now Moonwalking in the trap (if that is intentional). Then it draws the players view.

To cut short, your events can be handled asynchronous, delayed and by different systems at the same time/frame, without dependency of knowledge with system exists. And just to make it clear, it is important to call some systems every frame, like physics, graphic and AI.

---
Tags: entity-system
---


# Question
Title: Unknown variable direction in object.direction | Game Maker
This is my first question on a forum so please forgive any mistakes I may have made.

I am trying to make a game similar to the classic "Asteroids". I am trying to split the asteroids in two when a laser hits them. The following code is in an event in the asteroid object that is triggered when the laser collides with the asteroid.

```
inst1 = instance_create(x, y, medium1)
with (inst1) {
    speed = random_range(5,8)
    direction = laser.direction + random_range(0, 90)
}

inst2 = instance_create(x, y, medium1)
with (inst2) {
    speed = random_range(5,8)
    direction = laser.direction - random_range(0 ,90)
}

```

My issue occurs seemingly randomly. The game loads normally and the asteroids will split several times (sometimes 3-4, sometimes I can almost go through an entire game without encountering it) as I want them to, then this error pops up.

> ERROR in
> action number 1
> of Collision Event with object laser
> for object big1:
>
> Error in code at line 4:
> direction = laser.direction + random\_range(0, 90)
> ^
> at position 26: Unknown variable direction

Any suggestions on how to fix this issue? Thank you very much in advance!

# Answer
You are using the `with` statement, which makes code be executed by a given instance but you must be aware of instance reference variables: at line 4 the `direction` variable is `inst1`'s, but the reference `laser` is not the laser object it collided with, but the reference to *all* `laser` instances. It means, if there's at least one `laser` instance, its direction will be referenced correctly, otherwise the script is trying to read an unexisting variable (since there are no `laser`s).

You can easily fix your code by using the special keyword `other`:

```
// Create asteroid fragments
inst1 = instance_create(x, y, medium1);
inst2 = instance_create(x, y, medium1);

// Update fragment variables
inst1.speed = random_range(5,8);
inst1.direction = other.direction + random_range(0, 90);

inst2.speed = random_range(5,8);
inst2.direction = other.direction - random_range(0, 90);

```

Since we are executing code inside the *Collision Event*, the special keyword `other` lets us reference the *other* instance that our *current* instance has collided with. So, `other.direction` is not any laser's direction, but the very laser that hit our asteroid.

The reason I'm not using the `with` construction is because the keyword `other` can be used there too, but with a different meaning:

```
with (inst1) {
    speed = random_range(5,8);
    direction = other.direction + random_range(0, 90);
}

```

Here, `other` references to the asteroid instance, because it is the one invoking the `with` construction. If we want to reference the `laser` we are colliding with, we must write `other.other`, so its direction will be `other.other.direction`, but that's quite confusing (and maybe wrong too).
> 1 votes

---
Tags: collision-detection, game-maker
---


# Question
Title: Unity FP Character Can't Look Vertically
I have a FP Character and well, it can't look vertically. Its happened about 3 times now, each time I just replaced it with the standard assets prefab, first few times it worked fine, but then after a little while, I suddenly couldn't look vertically. I have checked and double check the vertical clamping on the prefab and they haven't been touched. I really need my player to be able to look vertically as soon as possible, could someone show me how to fix this?

Thanks in advance!

# Answer
> 0 votes
The Fix:

> With Unity 5, they change the setup of FPController Scripts so theres no more MouseLook script. The old MouseLook Script is called SimpleMouseRotator. With Referencing the SimpleMouseRotator, it got the vertical axis back for him and disabling the camera from the First Person Character.

Do you have any error or warning on console like audio listeners that needs to be deactivated?

Also try placing 2 mouselook script but deactivate one of them. Then when you lose vertical look, deactivate the current and enable the second one. See if that worked in getting vertical look back?

Are you changing anything from the FP prefab by any chance like height or width of character?

# Answer
> 1 votes
I just found exact problem as you did, so what you need to look for are some extra cameras that you don't remember putting in your game, when you found the camera that somehow added itself in, delete it. If that didn't work press Ctrl+Z to reverse the action you have just done and find a different camera to remove.

Hopefully I solved the problem but your post was made 4 months ago, so I think you already have made new game/scene.

# Answer
> 0 votes
**This is the easy solution, if your FPS Controller stops looking up and down**, after you import a new big asset package, like the Post Processing Stack:

**1. Go to Assets \> Reimport All**

**2. Select your default "Main Camera", in the Inspector change it's Tag to "Untagged".**

That's it. The Main Camera thing, it's because the FPS Controller child, FirstPersonCharacter, has it's own Camera component tagged "Main Camera". And there can be only one.

# Answer
> -1 votes
I just duplicate fsp and delete old one usually works but i think it is a bug. Delete all the main cameras that's what its. So much time duplicating and attracting stuff. DELETE MAIN CAMERAS.

---
Tags: unity, c#, character, first-person-shooter
---


# Question
Title: Unity: Why does playModeStateChanged get called after Start?
I have this:

```
[InitializeOnLoad]
public class MyClass
{
    static MyClass()
    {
        EditorApplication.playModeStateChanged += x => { PlaymodeStateChanged(); };
    }

    private static void PlaymodeStateChanged()
    {
        Debug.Log("Play mode changed");
    }
}

```

and another class with a `Debug.Log("Start()");` in the Start method. When I hit play I see on the log output:
`Start()`
`Play mode changed`

Shouldn't `playModeStateChanged` get called *before* `Start` is called on all objects? Any way to go around this? I need this so I can initialize an object before other objects that need to reference this one run Start.

Thanks in advance!

# Answer
> 1 votes
My best guess based on the docs:

> **EditorApplication.playModeStateChanged**
>
> Add an event handler to this event to receive a notification that the play mode state *has changed*

Note the use of past tense - this event promises to notify you only *after* the state has changed. It's not a `playModeStateWillChange` event.

But clearly your static constructor is getting called earlier, thanks to the `[InitializeOnLoad]` attribute:

> Note that static constructors with this attribute are called when Unity starts and *when Run is pressed*. In this second case the Unity runtime is intialised and this is treated as a Load.

So it looks like, rather than registering to handle the event after the editor finishes starting playmode (which apparently includes calling `Start()` for all `MonoBehaviours` in the open scenes), you could act immediately in the static constructor.

Since this constructor also fires when the editor loads, you might need to check:

> **EditorApplication.isPlayingOrWillChangePlaymode**
>
> Is editor either currently in play mode, or about to switch to it? (Read Only)
>
> This will return true when editor will switch to play mode after finishing some tasks (e.g. after scripts will be recompiled).

to verify whether this initialization is due to the editor loading or a play mode switch.

Give that a shot, and let us know if that helps you get your needed actions in before `Start()` happens.

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