# Question
Title: How can I use offset to make the camera rotate around the player, but keep the distance from player?
The script is attached to the Main Camera.

At the top :

```
[Header("Camera Orbit")]
public bool orbitCamera = false;
public float rotationSpeed;
public Vector3 offset;

```

Then in the Start()

```
private void Start()
{
    offset = new Vector3(player.position.x, player.position.y, player.position.z);
}

```

And in the Update()

```
private void Update()
{
    if (orbitCamera)
    {
        transform.eulerAngles += rotationSpeed * new Vector3(-Input.GetAxis("Mouse Y"), Input.GetAxis("Mouse X"), 0);

        offset = Quaternion.AngleAxis(Input.GetAxis("Mouse X") * rotationSpeed, Vector3.up) * offset;
            transform.position = player.position + offset;
    }
 }

```

The problem is the offset or something e else position the camera too far in a big radius from the player. I can rotate the camera around the player with the mouse and also move the camera up down left right all around with the mouse the something with the part that rotates the camera around the player make the camera position to be very far from the player.

How can I make that it will not change the distance between the camera and the player? Not that the camera will be on the player but if I start the game and the distance between the camera and the player is 4 then keep this distance and use the mouse to rotate around the player at a 4 distance radius.

Now the distance radius is very very far.

This is a screenshot showing the camera and the player distance when running the game :

but then when it's getting to the offset part in the Update this part :

```
offset = Quaternion.AngleAxis(Input.GetAxis("Mouse X") * rotationSpeed, Vector3.up) * offset;
transform.position = player.position + offset;

```

Then this happens :

I marked with red circle the player to show how fat the camera is from the player.

What I'm trying to do the main goal is to be able to use the mouse to rotate the camera up down left right and also to rotate the camera around the player.

Technically it's working but I don't want the camera to be too far from the player with the offset part I want to keep the distance from the camera as it is before running the game.

The full script :

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

public class CameraController : MonoBehaviour
{
    [Header("Camera Transitions")]
    public bool startTransitions = false;
    public bool waitBeforeStart = false;
    public float transitionTimeToWait;
    public Transform transitionTarget;
    public float movementSpeed;

    [Header("Follow/Look AT")]
    public Transform follow;
    public Transform lookAt;

    [Header("Camera Orbit")]
    public bool orbitCamera = false;
    public float rotationSpeed;

    [Header("Player")]
    public Transform player;
    public Vector3 offset;

    private void Start()
    {
        offset = new Vector3(player.position.x, player.position.y, player.position.z);

        if (waitBeforeStart)
        {
            startTransitions = false;

            StartCoroutine(TimeToStartTransition());
        }
    }

    private void Update()
    {
        if (orbitCamera)
        {
            transform.eulerAngles += rotationSpeed * new Vector3(-Input.GetAxis("Mouse Y"), Input.GetAxis("Mouse X"), 0);

            offset = Quaternion.AngleAxis(Input.GetAxis("Mouse X") * rotationSpeed, Vector3.up) * offset;
            transform.position = player.position + offset;
        }

        if (startTransitions && transitionTarget != null)
        {
            transform.position = Vector3.MoveTowards(transform.position, transitionTarget.position, movementSpeed * Time.deltaTime);

            if (transform.position == transitionTarget.position)
            {
                transform.gameObject.SetActive(false);
                transitionTarget.gameObject.SetActive(true);
            }
        }
    }

    IEnumerator TimeToStartTransition()
    {
        yield return new WaitForSeconds(transitionTimeToWait);

        startTransitions = true;
    }
}

```

# Answer
> 0 votes
Yeah, this line

```
offset = Quaternion.AngleAxis(Input.GetAxis("Mouse X") * rotationSpeed, Vector3.up) * offset;

```

is the problem. And, honestly, I don't understand what you expected it to do and why you used it, because to me the line just makes no sense in this use case.

I'll give 2 approaches I would use for the 3rd person camera:

1st approach:
Adjusting the offset depending on the current camera position and rotation. In this approach you need to use the `player.position` as the base point, and then add some offset using the camera transform's directional vectors : `transform.forward`, `transform.right`.
For example, to get a point that is 4 units behind the camera, i. e. 4 units back along the current camera `forward` direction you do this:

```
Vector3 point = transform.forward * -4f;

```

To get a point that is 4 units back and 2 units up relative to the current camera position and orientation and also take into account the player's position:

```
Vector3 point = player.position + transform.forward * -4f + transform.up * 2f;

```

Or, using the `offset` vector:

```
Vector3 offset = new Vector3(0, 2, -4);

void Update()
{
    Vector3 point = player.position + transform.forward * offset.z + transform.up * offset.y;
    transform.position = point;
}

```

2nd approch:
Construct the camera object from 2 game objects and let Unity do the translations automatically. In this method you create a root empty game object and attach a new object to it as a child. The camera component should be on the child. Then you set the offset for the child that will represent the local position of the child relative to the root (parent). You then move and rotate the root object to follow the player, rotate with mouse, and the child object will keep standing at the predefined offset from the root object no matter what. The camera controller script could be on any of the objects, you just need to provide references to the root and child game objects. For example:

```
/*
| Root game object -> this script
    ^
    | Child game object -> Camera component
*/

Transform child;
Vector3 offset = new Vector3(0, 2, 4);

void Start()
{
    // Assuming the script is attached to the root object and the child object name is "Child"
    child = transform.Find("Child");
    child.localPosition = offset;
}

void Update()
{
    // Make the root object follow the player:
    transform.position = player.position;
    // Do your camera rotation code.
    // The child holding the Camera will stay at (0, 2, 4) offset from the root object relative to the camera current orientation automagically.
}

```

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


title: Creating walls for a racing game?

text:
# Question
Title: Creating walls for a racing game?
I have the following kind of race track:

As you can see some walls are talls but some aren't...

**Question:**

How can one create invisible walls so that cars stays in track?

More exactly, how to model walls for complex shapes in a relatively easy way?

# Answer
> 4 votes
I ended up creating my own editor tool/window combo:

The general idea is the following:

Click a quad vertex, add a wall point, upper point is just `Vector3.up`.

And allow to remove any point as well.

Along necessary data/logic, etc.

Though manually paint, any vertex can form a collider thus I'll get vertex perfect colliders.

**EDIT:**

I now leverage the following:

* store data directly in game objects
* a global editor tool + a custom window in scene view
* scriptable singleton for tool data

---
Tags: unity, collision-detection, racing
---


# Question
Title: How to enable anti-aliasing when camera zoom in libgdx
I develop a game where I draw some textures on the screen and want to zoom in and out the scene. I am using `OrthographicCamera` and when I zoom in, the textures become very pixelated. Is it possible to enable anti-aliasing or is there another way to get zoomed textures without crisp edges?

My code is the following

```
public class DesktopLauncher {
    public static void main (String[] arg) {
        LwjglApplicationConfiguration config = new LwjglApplicationConfiguration();
        config.title = "Anti-aliasing";
        config.width = 600;
        config.height = 480;
        new LwjglApplication(new MyGdxGame(), config);
    }
}

class MyGdxGame extends ApplicationAdapter {
    SpriteBatch batch;
    Texture img;
    OrthographicCamera camera;

    @Override
    public void create () {
        batch = new SpriteBatch();
        img = new Texture("badlogic.jpg");
        camera = new OrthographicCamera(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
        camera.setToOrtho(false);

        camera.zoom = 0.1f; // this makes it all to look pixelated
    }

    @Override
    public void render () {
        ScreenUtils.clear(0.1f, 0.2f, 0.3f, 0.1f);
        camera.update();
        batch.setProjectionMatrix(camera.combined);
        batch.begin();
        batch.draw(img, 100, 100);
        batch.end();
    }

    @Override
    public void dispose () {
        batch.dispose();
        img.dispose();
    }
}

```

# Answer
> 0 votes
Thanks to @DMGregory, the solution was to add a texture filter after creation of the texture, e.g. `Texture.TextureFilter.Linear` which does bilinear interpolation.

I modified the code of `create` method as follows

```
public void create () {
    batch = new SpriteBatch();
    img = new Texture("badlogic.jpg");
    // adding bilinear filter
    img.setFilter(Texture.TextureFilter.Linear, Texture.TextureFilter.Linear);

    camera = new OrthographicCamera(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
    camera.setToOrtho(false);

    camera.zoom = 0.1f;
}

```

Now the image from the question looks like this

---
Tags: libgdx, camera, antialiasing
---


# Question
Title: Any way to guarantee the order of objects returned by FindObjectsOfType?
I wanted to create my spawn points for NPC's and also the player inside my 3D modelling software. So when I import each level, it has its own set of spawn points already built in.

This seems to work fine for me so far. But I had intended to use the FindObjectsOfType function. The problem is its important that I set the points in order (ie. spawn1 at bottom ... spawn 4 at top).

My problem is that the first element in the array is not my 'spawn\_1', in my case here it is actually spawn2 first.

This is my hierarchy:

beer\_tap\_stand 1-4 are the spawn points in question at the moment, as you can see they are in order.

Then i have this code trying to spawn the player at 'beer\_tap 1' :

```
public class GameManager : MonoBehaviour
{
    public static GameManager instance;

    Customer_SpawnPoint[] customer_spawns;
    Beer_Tap_Standpoint[] beertap_standpoints;

    Player playerPrefab;
    Player player;

    private void Start()
    {
        if (instance == null)
            instance = this;
        else
            Destroy(this);

        customer_spawns = FindObjectsOfType<Customer_SpawnPoint>();
        beertap_standpoints = FindObjectsOfType<Beer_Tap_Standpoint>();
        playerPrefab = Resources.Load<Player>("Player");
        player = Instantiate(playerPrefab, beertap_standpoints[0].transform.position, Quaternion.identity);

    }
}

```

I need a way to guarantee the order, but I can't just drag them to the script as I have multiple levels.

# Answer
**You want a hierarchical sort using `Comparer<Transform>` with `GetSiblingIndex`:**

```
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using JetBrains.Annotations;
using UnityEngine;

namespace xyz
{
    /// <summary>
    ///     Hierarchical comparisons utility.
    /// </summary>
    public static class HierarchyComparer
    {
        /// <summary>
        ///     Gets an instance that compares a hierarchy of <see cref="UnityEngine.Component" />.
        /// </summary>
        [PublicAPI]
        public static System.Collections.Generic.Comparer<Component> Component { get; } = new Comparer<Component>(Compare);

        /// <summary>
        ///     Gets an instance that compares a hierarchy of <see cref="UnityEngine.GameObject" />.
        /// </summary>
        [PublicAPI]
        public static System.Collections.Generic.Comparer<GameObject> GameObject { get; } = new Comparer<GameObject>(Compare);

        /// <summary>
        ///     Gets an instance that compares a hierarchy of <see cref="UnityEngine.Transform" />.
        /// </summary>
        [PublicAPI]
        public static System.Collections.Generic.Comparer<Transform> Transform { get; } = new Comparer<Transform>(Compare);

        private static int Compare([CanBeNull] Component x, [CanBeNull] Component y)
        {
#pragma warning disable IDE0031 // Null check can be simplified
            return Compare(x != null ? x.transform : null, y != null ? y.transform : null);
#pragma warning restore IDE0031
        }

        private static int Compare([CanBeNull] GameObject x, [CanBeNull] GameObject y)
        {
#pragma warning disable IDE0031 // Null check can be simplified
            return Compare(x != null ? x.transform : null, y != null ? y.transform : null);
#pragma warning restore IDE0031
        }

        private static int Compare([CanBeNull] Transform x, [CanBeNull] Transform y)
        {
            if (x == null && y == null)
                return 0;

            if (x == null)
                return -1;

            if (y == null)
                return +1;

            var hierarchy1 = GetHierarchy(x);
            var hierarchy2 = GetHierarchy(y);

            while (true)
            {
                if (!hierarchy1.Any())
                    return -1;

                var pop1 = hierarchy1.Pop();

                if (!hierarchy2.Any())
                    return +1;

                var pop2 = hierarchy2.Pop();

                var index1 = pop1.Index;
                var index2 = pop2.Index;

                if (index1 == index2)
                    continue;

                var compare = index1.CompareTo(index2);

                return compare;
            }
        }

        private static Stack<Hierarchy> GetHierarchy([NotNull] Transform transform)
        {
            if (transform == null)
                throw new ArgumentNullException(nameof(transform));

            var stack = new Stack<Hierarchy>();

            var current = transform;

            while (current != null)
            {
                var index = current.GetSiblingIndex();

                stack.Push(new Hierarchy(index, current));

                current = current.parent;
            }

            return stack;
        }

        /// <summary>
        ///     Hierarchically sort an array of components.
        /// </summary>
        /// <param name="components"></param>
        /// <returns></returns>
        [PublicAPI]
        public static Component[] HierarchicalSort([NotNull] this Component[] components)
        {
            if (components == null)
                throw new ArgumentNullException(nameof(components));

            Array.Sort(components, Component);

            return components;
        }

        /// <summary>
        ///     Hierarchically sort an array of game objects.
        /// </summary>
        /// <param name="gameObjects"></param>
        /// <returns></returns>
        [PublicAPI]
        public static GameObject[] HierarchicalSort([NotNull] this GameObject[] gameObjects)
        {
            if (gameObjects == null)
                throw new ArgumentNullException(nameof(gameObjects));

            Array.Sort(gameObjects, GameObject);

            return gameObjects;
        }

        /// <summary>
        ///     Hierarchically sort an array of transforms.
        /// </summary>
        /// <param name="transforms"></param>
        /// <returns></returns>
        [PublicAPI]
        public static Transform[] HierarchicalSort([NotNull] this Transform[] transforms)
        {
            if (transforms == null)
                throw new ArgumentNullException(nameof(transforms));

            Array.Sort(transforms, Transform);

            return transforms;
        }

        #region Nested type: Comparer

        private sealed class Comparer<T> : System.Collections.Generic.Comparer<T>
        {
            public Comparer([NotNull] Func<T, T, int> func)
            {
                Func = func ?? throw new ArgumentNullException(nameof(func));
            }

            private Func<T, T, int> Func { get; }

            public override int Compare(T x, T y)
            {
                return Func(x, y);
            }
        }

        #endregion

        #region Nested type: Hierarchy

        private struct Hierarchy
        {
            public int Index { get; }

            [SuppressMessage("ReSharper", "MemberCanBePrivate.Local", Justification = "debugging")]
            public Transform Target { get; }

            public Hierarchy(int index, [NotNull] Transform transform)
            {
                if (index < 0)
                    throw new ArgumentOutOfRangeException(nameof(index));

#pragma warning disable IDE0016 // Null check can be simplified
                if (transform == null)
                    throw new ArgumentNullException(nameof(transform));
#pragma warning restore IDE0016

                Index = index;
                Target = transform;
            }

            public override string ToString()
            {
                return $"{nameof(Index)}: {Index}, {nameof(Target)}: {Target}";
            }
        }

        #endregion
    }
}

```

Throw that to an array of transforms, they will always be sorted in hierarchy order.

**Edit:**

Refined version, minor adjustments, supports any `Component`, less code but functionally identical:

```
using System;
using System.Collections.Generic;
using System.Linq;
using JetBrains.Annotations;
using UnityEngine;

namespace xyz
{
    public static class HierarchicalSorting
    {
        private static int Compare([CanBeNull] Component x, [CanBeNull] Component y)
        {
            return Compare(x != null ? x.transform : null, y != null ? y.transform : null);
        }

        private static int Compare([CanBeNull] GameObject x, [CanBeNull] GameObject y)
        {
            return Compare(x != null ? x.transform : null, y != null ? y.transform : null);
        }

        private static int Compare([CanBeNull] Transform x, [CanBeNull] Transform y)
        {
            if (x == null && y == null)
                return 0;

            if (x == null)
                return -1;

            if (y == null)
                return +1;

            var hierarchy1 = GetHierarchy(x);
            var hierarchy2 = GetHierarchy(y);

            while (true)
            {
                if (!hierarchy1.Any())
                    return -1;

                var pop1 = hierarchy1.Pop();

                if (!hierarchy2.Any())
                    return +1;

                var pop2 = hierarchy2.Pop();

                var compare = pop1.CompareTo(pop2);

                if (compare == 0)
                    continue;

                return compare;
            }
        }

        [NotNull]
        private static Stack<int> GetHierarchy([NotNull] Transform transform)
        {
            if (transform == null)
                throw new ArgumentNullException(nameof(transform));

            var stack = new Stack<int>();

            var current = transform;

            while (current != null)
            {
                var index = current.GetSiblingIndex();

                stack.Push(index);

                current = current.parent;
            }

            return stack;
        }

        [PublicAPI]
        [NotNull]
        [ItemNotNull]
        public static T[] Sort<T>([NotNull] [ItemNotNull] T[] components) where T : Component
        {
            if (components == null)
                throw new ArgumentNullException(nameof(components));

            Array.Sort(components, new RelayComparer<T>(Compare));

            return components;
        }

        [PublicAPI]
        [NotNull]
        [ItemNotNull]
        public static GameObject[] Sort([NotNull] [ItemNotNull] GameObject[] gameObjects)
        {
            if (gameObjects == null)
                throw new ArgumentNullException(nameof(gameObjects));

            Array.Sort(gameObjects, new RelayComparer<GameObject>(Compare));

            return gameObjects;
        }

        [PublicAPI]
        [NotNull]
        [ItemNotNull]
        public static Transform[] Sort([NotNull] [ItemNotNull] Transform[] transforms)
        {
            if (transforms == null)
                throw new ArgumentNullException(nameof(transforms));

            Array.Sort(transforms, new RelayComparer<Transform>(Compare));

            return transforms;
        }

        private sealed class RelayComparer<T> : Comparer<T>
        {
            public RelayComparer([NotNull] Func<T, T, int> func)
            {
                Func = func ?? throw new ArgumentNullException(nameof(func));
            }

            [NotNull]
            private Func<T, T, int> Func { get; }

            public override int Compare(T x, T y)
            {
                return Func(x, y);
            }
        }
    }
}

```
> 2 votes

# Answer
You can create a `LevelManager` script. That script should have an array in the inspector where you can drag the spawnpoints specific to that level. Add the `LevelManager` to all of your levels.

```
public class LevelManager : MonoBehaviour
{
    public Customer_SpawnPoint[] customer_spawns;
    public Beer_Tap_Standpoint[] beertap_standpoints;
}

```

Then in your `GameManager` script, you can find that level's `LevelManager` with `var myLevelManager = FindObjectOfType<LevelManager>();`. Now you can use the spawnpoints with `myLevelManager.customer_spawns`, and they will be in the same order as you dragged them in the inspector.
> 2 votes

# Answer
> I have seen the detailed answer from Aybe, but just checking there isnt some magic one-line solution.

```
var objects = FindObjectsOfType<SomeType>();
System.Array.Sort(objects, (a, b) => a.name.CompareTo(b.name));

```

> I'm still trying to learn about Lambda functions, they confuse the heck outta me! But is this one of those times I need it to use in the Array.Sort() function?

No, you can do it without a lambda. Just define an ordinary named function that takes two components as parameters and returns an integer representing their relative sort order. (You can exchange a & b or negate the return value if you want to sort in the opposite order)

```
static int CompareComponentNames(Component a, Component b) {
    return a.name.CompareTo(b.name);
}

// ...later, when you have an array you want to sort:

System.Array.Sort(objects, CompareComponentNames);

```
> 1 votes

---
Tags: unity, c#, level-design
---


# Question
Title: How do I solve a problem where sometimes recursion is untenably vast and sometimes it is not?
I am writing a programming language of my own. (I've done two Turing complete ones in the past, but this time I'm trying to actually be useful.)

Now, one thing that should be especially easy with this is interactive fiction.

```
"Three criminals approach you and accuse you of being a detective (which of course you are).  What do you do?"

Choice A (pull your weapon)
Choice B (accuse someone else)
Chioce C (flee)

```

Right now, I'm just executing choices that the player makes. However, I was thinking of translating my script to Java so you can play this on a website. My approach was going to be recursion.. just execute A, execute all the choices after that until you run out of choices and go to B. Essentially generate a tree. For this kind of a problem, this looks like it would work great. You are just transcribing the problem into

However, this exposes the language to certain ways of solving problems that might lead to more recursion than could have been computed since the start of the known universe. Easily. For example, chess.

I have a subroutine `askMultiple(...)` that would offer the player a series of choices. This is where the recursion would take place; every time a choice leads to more choices, just go down the tree.

Now, this would be an unwieldy way to ask for choices on a chess board (its a long list of moves.) But it would be quite logically possible, and maybe less unwieldy than you might think since the language supports custom output modules.

Now if I use the same approach to this problem I would on the detective game, my program would puke. There are 10^120 chess games. Countless lifetimes would be long over by the time your incomprehensibly vast javascript page was done.

It's easy to handle infinite numbers of input in a finite space (`what is your name?`). For example

```
Hi, detective Ashley,
Hi, detective Morris...

```

but I know that this approach might generate problems.

How can I avoid this?

# Answer
> 0 votes
Why do you need recursion for a dialog tree?

In the dialog system of my current project, each dialog tree is an array of nodes. I then have an integer which represents the index of the currently active dialog node.

When the player picks a choice, I just do `currentNodeId = nodes[currentNodeId].choices[pickedChoiceIndex].nextId` and that's it. No recursion whatsoever.

Need to remember a choice later? That's what variables are for. Nodes can change the value of variables. Those variables can later be used to hide or show conditional choices or create invisible branches between two or more nodes. That gives me a Turing-complete system without requiring any stack-based recursion whatsoever. Oh, and I also have a syntax which allows to embed conditional text within text nodes which is `{character.loyalty>=50|shown|hidden}` depending on the value of a variable. A useful shortcut for small details which don't warrant a whole branch.

If I wanted to implement a turn-based game like Chess to be played through this system, then I would also use variables for that. I would not create a separate node for each possible state of the game board. I would encode the state of the game using variables and then present that state and the choices the player has by using those variables. Although I would likely hard-code the actual mechanics of that game (it would be theoretically possible due to the Turing-completeness of this system, but I am not a masochist).

The only situation where I have recursion is when I am working with sub-trees (dialog nodes which are implemented as complete separate dialog trees - usually used to make them reusable or to break up very large trees into multiple ones for easier editing). But I see no reason why I would ever go deeper than a hand full of levels of recursion with this.

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


# Question
Title: How can I solve interactions between game environment and Entities like player or NPC on the code level?
I want to figure out how objects in a game environment like these:

* A reward Chest
* A mana depleting/replenishing zone
* sudden stormy winds in a certain direction

should affect other entities' (player's) properties like:

* Inventory
* Health/mana values
* add a force on the entity in a certain direction.

When the above such interactions occur, I'm thinking of using an event bus as follows:

* The player interacts with a script on the chest and an event is raised containing the chest content via the environment manager. The player Manager (entity manager) should subscribe to this event and update accordingly.
* In the case of mana zones, these zones can communicate the interaction to the environment manager which can raise the event which is already subscribed by the player manager.
* similarly, force magnitude and direction can be communicated.

Some important points I'm keeping in mind:

* These event types can be reused in most cases, e.g., all health-related interactions can be communicated via a single event type, all physics (rigid body) related interactions can be another type. This will probably keep the number of events type low.
* The environment entities can choose to raise or player entities can choose to respond to an event.
* This would be a local event bus that is open to the Core game system only. Trying to keep these events away from other systems.

I wanted to know what is generally used for this purpose in the game industry. Will this be overkill? Is there a better approach that handles all such interactions keeping the code entities decoupled from each other?

# Answer
> 2 votes
**The approach and some evolutions / pitfalls**

Fairly standard. To give your approach a handle of sorts: you want to centralise most or all interactions to go through some high level (if not top level) controller, say `Environment`, which reduces coupling. We'll call it something like "top level interactions mediator / intermediary / proxy". See associated design patterns.

The problem comes in when that top level, generalised controller `Environment` becomes too cluttered, which will usually happen quickly in such a general class. This is where you begin factoring `Environment` into new subsystems, delegating its responsibilities further down the control tree or hierarchy.

For example, if trading is a possiblity, then `Environment`, which may receive a message from a player requesting to trade, may delegate these messages down to a `TradingSystem` which acts as intermediary for the exchange of items between the two entities in question, which could be actual trading, looting a corpse, or pickpocketing, depending on the parameters in that message; this would probably be reflected in a similar UI between the three styles of interaction. `TradingSystem` may fire a message when that UI closes, indicating that the interaction is complete, which is picked up by `Environment` so that it can, for example, ensure that corpse can't be looted again, or even remove the body altogether once looted. `TradingSystem` can delegate control down, even further.

What we typically don't want is `TradingSystem` having a reference back up to its controller `Environment`. This increases coupling, and can make it difficult to trace what is controlling what, since subordinate controllers can (via method call) directly cause a parent controller to react, rather than *requesting* an action on part of a parent by notifying them via event / message / signal - you suggested `choose to raise or player entities can choose to respond to an event` \- especially true for higher level controllers which should never *have to* listen to subordinates.

*EDIT re question about messaging coupling* The Observer Pattern, AKA pub-sub, loosens coupling in the following way: `Publisher` will have a list of `Subscriber`s to be notified. These references are "loose" because they refer to type `Subscriber` which comes from a generic list of `Subscribers` which the `Publisher` holds. `Publisher` thus has no idea what the actual, concrete types (such as `TradingSystem` or `Environment`) these objects are, so it cannot call public methods on them, meddle with their public members, etc. And because the `Publisher`-`Subscriber` is intrinsically limited in functionality, it should remain the same throughout development. So no need to worry about these `Subscriber`s changing and breaking `Publisher` code.

**Will this be overkill?**

Not really, but...

I'd always take the simplest approach *for now*, until that starts to get in the way of efficient development. Then I'd start formulating a plan as to how to solve the problem, systematically. As this plan is crystallising in my mind, and assuming the project is not on a schedule e.g. for a client where other tasks take priority, I'd tie up loose ends on current tasks, merge into the base branch, create a new branch off this base, and implement the planned solution in full.

I would not try to preempt what those problems *might* be as that is nearly always a waste of time and effort. It may be better to get started on making your game and do the simplest thing that works (for example, direct method calls or a modifying a globally-accessible array of message slots you can read and write as and when), for the time being.

**Conclusion**

It's good to stay on top of things, and working in "difficult" code can be tedious, but sometimes it is worth the wait to see all the potential ways in which you *have* problems with a given (sub)system, and the ways in which you could solve them all at once, so that when you finally *do* fix them, you do so as effectively and universally as possible for the current stage of development.

In the meantime, do the simplest thing that works.

---
Tags: unity, c#, architecture, game-mechanics
---


title: MagicaVoxel export world in 1 model

text:
# Question
Title: MagicaVoxel export world in 1 model
So I'm currently working in MagicaVoxel and I have 2 objects in my world. When I export it as .obj it exports as seperate 2 obj models with 2 seperate textures and materials. Is there any way that I can export whole MagicaVoxel world to single object. If there is a way this would really made my work easier because I will add more objects to world.

Thank you for answers.

# Answer
I'm not aware of a way to do this directly within the current version of MagicaVoxel (0.99.4 \[5/29/2019\]).

It's not uncommon for special purpose apps to lack the full functionality of more general purpose main stream software. To get around these limitations, you may need to chain together more than one piece of software to accomplish your goal.

In this case, I recommend opening the `.obj` file exported from MagicaVoxel in a general 3d modelling app such as Blender, Maya, 3ds Max, etc. I know that Blender in particular has support for taking multiple objects/meshes and combining such that they are represented as one object.

After combining the objects, simply save the file and use it as desired.

As a final note, if you have a significant number of files to process, you should consider automating the task if possible. Most modeling software that I'm familiar with has a scripting language for automating repetitive tasks.
> 2 votes

# Answer
This is how I do it:

1. Switch to a Objects View \[Tab\]
2. Select all objects \[Ctrl+a\] and Press "Union"
3. Export .obj (which now should export the project as a single object)
4. Undo the Union operation \[Ctrl-z\]
> 2 votes

---
Tags: obj, export, magicavoxel
---


# Question
Title: How to synchronize reads and writes to a StructuredBuffer across warps in HLSL?
I'm currently trying to implement smooth voxel terrain (using dual contouring) with mesh generation happening on the GPU and I'm struggeling with chunked level of detail creation. My approach is as follows:

1. Always create each chunk's vertices at the highest level of detail.
2. Merge the vertices of higher level of detail (using averaging) to create a level of detail which is one level lower than the original level of detail (similarly to merging leaves in an octree).
3. Repeat until the desired level of detail is reached.

For this purpose I wrote the following kernel, which should do exactly that:

```
uint cellStride;

RWStructuredBuffer<Vertex> generatedVertices;
RWStructuredBuffer<uint> generatedVertexIndicesLookupTable;

[numthreads(4, 4, 4)]
void DecrementLevelOfDetail(uint3 id : SV_DispatchThreadID)
{
    uint3 cellID = id * cellStride + 1;

    uint numberOfChildVertices = 0;
    uint parentVertexIndex = NULL_VERTEX_INDEX;
    Vertex parentVertex = Vertex::Create();

    for (uint cornerIndex = 0; cornerIndex < numberOfCellCorners; cornerIndex++)
    {
        uint3 coordinate = cellID + cellStride / 2 * cellCorners[cornerIndex];
        uint childVertexIndex = generatedVertexIndicesLookupTable[CalculateGeneratedVertexIndicesLookupTableIndex(coordinate, cellStride / 2)];

        if (childVertexIndex != NULL_VERTEX_INDEX)
        {
            Vertex childVertex = generatedVertices[childVertexIndex];
            parentVertex.position += childVertex.position;
            parentVertex.normal += childVertex.normal;
            numberOfChildVertices++;
        }
    }

    // I need a sync point here.

    if (any(cellID > numberOfVoxels - 3))
    {
        return;
    }

    if (numberOfChildVertices > 0)
    {
       parentVertexIndex = generatedVertices.IncrementCounter();
       parentVertex.position /= numberOfChildVertices;
       parentVertex.normal = normalize(parentVertex.normal);
       generatedVertices[parentVertexIndex] = parentVertex;
    }
    generatedVertexIndicesLookupTable[CalculateGeneratedVertexIndicesLookupTableIndex(cellID, cellStride)] = parentVertexIndex;
}

```

The `generatedVertices` buffer contains the vertices to be merged and the `generatedVertexIndicesLookupTable` buffer acts as a lookup table that - given a `cellID` \- returns the associated index of the vertex in the `generatedVertices` buffer. Both these buffers were populated by another kernel previously.

To populate these buffers the kernel goes over all cells of a chunks voxel volume and generates a vertex if necessary. If a vertex is created I will do something along these lines to store it:

```
[numthreads(4, 4, 4)]
void GenerateVertices(uint3 cellID: SV_DispatchThreadID)
{
    Vertex vertex;

    // vertex is being created...

    uint vertexIndex = generatedVertices.IncrementCounter();
    generatedVertexIndicesLookupTable[CalculateIndex(cellID)] = vertexIndex;
    generatedVertices[vertexIndex] = vertex;

```

I dispatch the `DecrementLevelOfDetail` kernel recursively as follows:

```
for (int cellStride = 2; cellStride <= (1 << lod); cellStride <<= 1)
{
    m_generatedVerticesBuffer.SetCounterValue(0);
    m_parent.m_voxelConfigs.DualContouringConfig.Compute.SetInt(ComputeShaderProperties.CellStride, cellStride);
    m_parent.m_voxelConfigs.DualContouringConfig.Compute.Dispatch(1, m_parent.m_voxelConfigs.VoxelVolumeConfig.NumberOfCells / cellStride);
}

```

In order for this to work I need all threads of all warps associated with a specific dispatch call to the `DecrementLevelOfDetail` kernel to read from the `generatedVertices` buffer before writing to it at the end of the kernel. Is there a way to achieve that?

# Answer
> 0 votes
I don't think creating a sync point as explained in the question is possible so I eventually settled on having two vertex buffers, one acting as the input for the kernel and one acting as the output. After each successive kernel invocation to lower the level of detail I simply swap the two buffers around so during the next invocation the new input buffer will be the last invocations output buffer.

**Note:** I initially wanted to avoid using two buffers because of the added memory space required for another buffer.

---
Tags: unity, hlsl, compute-shader
---


# Question
Title: Can I replace the source image of slices by script?
I have a Unity2D prefab that uses several slices from a single PNG. (in it sprite renderer, and in its animation clips). If I replace that PNG in the Finder, all slices taken from that PNG are automatically updated, which is great.

But I want to do this by script: just replace the PNG where all slices are taken from, with another PNG. This is so that each of my prefabs instances can all use a different spritesheet PNG source for its slices.

Is this possible in Unity?

# Answer
If you want to replace the sprite of a SpriteRenderer, you can do this:

```
var spriteRenderer = gameObject.GetComponent<SpriteRenderer>();
spriteRenderer.sprite = newBackgroundSprite;

```

The newBackgroundSprite could be added in the inspector (by adding a Sprite to your Script). You can also load resources at runtime; see Loading Resources at Runtime.
> 0 votes

# Answer
Basically, you need to put the sprite inside Resources Folder (or make an asset bundle/ addressable) and then you can simply use an array to load all the sliced sprites incorporated with that image(Sprite). The code to load sprites inside an array is.

```
Sprite[] sprites = Resources.LoadAll<Sprite>("Character");

```

Hope that helps
> 0 votes

# Answer
In more recent versions of Unity, you can use the sprite swapping functionality of the 2D Animation package.

First you create a Sprite Library Asset. This lets you define a collection of categories, each describing a category of sprites (like "head", "chest", etc.) and within each logical sprite category you can define several variants, each defined by a label name and the sprite to use.

Then you can add a Sprite Library component to your root game object, referencing this asset, and Sprite Resolver components to the Sprite Renderers you want to swap. Set the category and label on each to point to your original/base sprite for that role.

Now by changing the label field on these components, you can swap to the corresponding sprite for that category.

This makes it possible to swap these sprites at runtime - as characters equip different gear for example. And the sprites don't all have to be from the same PNG or even the same size/shape/layout in the image file (though if using skinned animation, they do need to have identical bones).
> 0 votes

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


# Question
Title: Calculate coordinates of boundaries containing group of objects
I would like to understand how to calculate coordinates of boundaries group of objects as a parallelepiped in 3D game?

Let's say for simplicity we have spheres randomly slowly moving in 3d space some of them cross each other from time to time and forming groups from 2 or more object locating very close to each other. Now I need to create dynamic parallelepiped surrounding this formed group as long as this group still formed because spheres moving constantly and such groups may appear and disappear chaotically.

So how to calculate coordinates of this parallelepiped faster? The naive approach I was thinking is just calculate distance of each object from each other individually to know to which group each sphere belongs which is slow O(n^2) time complexity. Is there more efficient solution to solve this problem?

Sorry if already similar question answered. I couldn't find answer to my question so far.

# Answer
> 2 votes
This is a broad question, so a broad answer is required. You can follow up individual implementations / algorithms yourself, and post separate questions if you need to.

**The basic approach for games**

Create some sort of grid in space. This grid can be either:

* flat (literally, a 2D grid or 3D grid)
* hierarchical (2D: quadtree or bounding box hierarchy, 3D: octree or bounding volume hierarchy)

These are implemented as an array of containers. Hierarchical grids are arrays of containers *of* arrays of containers, *ad nauseam*, down the tree.

For now let us focus on flat structures, as these are easier to conceptualise.

Each grid cell or "bucket" groups a set of bodies. This approach is simple and generally works well enough in most cases, and I would recommend it as a starting point for beginners. We determine (naively) whether a body is within a cell as follows:

```
for each body
    get xmin and xmax for this body
    xcentre = xmin + (xmax - xmin) / 2
    find the cell which holds this body:
    xcell = xcentre / numcols //integer division, round down (in this case, numcols=4)

    repeat for y (and if in 3D, also for z).

```

So in the case of our bottom-most point in the image above, `cx == 1` and `cy == 3` (remember this is zero-based, so cols and rows each run `0-3`).

Thus the boxes or volumes that we use to contain bodies, are defined by a fixed, repeating grid. Note also that the size of the cells are directly influenced by the size of the bodies they can contain. Too small, and you will not create good-sized clusters; too large, and you may not get enough reduction in the number of body-body checks.

**Problems, and more advanced approaches**

A problem arises in pathological cases like this:

...This will be less than optimal since we'd ideally have liked the four red bodies, and maybe even the orange one, grouped together. This way we'd have only had to process one bucket instead of four, which would have reduced processing costs.

This can also happen in a quadtree, which is also defined by a fixed grid structure (quadtrees are otherwise *much* more performant for large numbers of bodies, than flat grids):

Where such pathological cases are of crucial importance, e.g. they are a performance bottleneck, we prefer something that clusters more dynamically. A graph connectivity approach such as Kruskal's Spanning Tree Algorithm which DMGregory mentioned, or any other which creates a dynamic, connected clustering. If a maximum edge distance is used, long edges are eliminated, dividing output into localised subgraphs / clusters:

Or we can use an iterative classification method such as K-means clustering, which again creates dynamic groupings with no regard to rigid boundaries:

(K-means animation attributed to Chire under Creative Commons)

Once we have clustered using e.g. K-means or Kruskal's, we can use these clusterings to determine bounding box or volume limits. We could also use this as an input to a flexible bounding volume hierarchy (actually area, not volume, in 2D). There are countless ways to subdivide the space, but only a few that cluster efficiently, it all depends on the use case. This shows a space-filling bounds structure vs a sparse structure:

---
Tags: 3d, algorithm, objects, efficiency
---


# Question
Title: Unreal gives error when line tracing collision
I am currently using Unreal Engine 4.26. I have been following this tutorial to make a parkour game in Unreal.

I followed the tutorial exactly, and made a walk/jump/double jump game.

However, when I made the wall climbing system, Unreal started giving an error.

The wall climbing still works, but it shows this error when it ends:

```
Blueprint Runtime Error: "Accessed None trying to read property CallFunc_BreakHitResult_HitActor". Blueprint:  Parkour_BP_Char Function:  Execute Ubergraph Parkour BP Char Graph:  EventGraph Node:  Branch

```

It has hundreds of copies of that error in the message log.

I would provide my unreal file, but I don't know how.

Here is the double jump blueprint setup; Image 1 Image 2 Image 3

(Sorry about 3 images, it's a large setup.)

Does anyone know how I can solve the error?

Will edit question with more info if needed.

# Answer
> 2 votes
The error is caused because your linetrace isn't hitting anything but is still trying to run the rest of the code.

To prevent this, there is a node called "Is Valid"

Actually, there's two of them. One of them is an executable and handles what happens if the node is valid and isn't, the other ends with a Boolean and you need a branch. Plug the Hit Hit Actor into the node to check if it is valid.

If you use one of these between your hit result and the branch that your "Actor Has Tag" is going in to, this should fix the error.

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


title: Putting a material on a fractured model

text:
# Question
Title: Putting a material on a fractured model
I have a square model that has been fractured using blender's cell fracture. I also have a material that I want to apply onto the broken pieces.

The only problem is that the material needs to be organized in a certain way so it looks right when I replace it with the broken model.

Scripting-wise i'm using Brackey's tutorial for destruction

**How can I make the material look the same on both the fractured and the unfractured model?**

I also left a picture if it helps.

The one on the left, is the unbroken model with the material. The one on the right is the broken model with all the cells having the same material.

# Answer
did you unwrap the model before the cell fracture? if so you should do it after everything else. because normally the cell fracture add-on keeps the original uv's as seen here:

maybe its also a fbx export issue. personally i use these settings to get the desired result in unity:
> 1 votes

---
Tags: unity, blender, materials
---


# Question
Title: Control does not work if motion is set in FixedUpdate
I made touch controls, but when I set forward movement, the control stops working.

```
[SerializeField]
Rigidbody _rigidbody;

float? _lastX = null;

void FixedUpdate()
{
    // Vector3.right = new Vector(1f, 0f, 0f)
    // the control does not work because of this line
    _rigidbody.MovePosition(_rigidbody.position + Vector3.right * 3f * Time.fixedDeltaTime);
}

void Update()
{
    if (Input.GetMouseButtonDown(0))
    {
        _lastX = Input.mousePosition.x;
    }
    else if (_lastX != null && Input.GetMouseButton(0))
    {
        var pos = _rigidbody.position;
        var x = Input.mousePosition.x;
        pos.z += -((x - (float)_lastX) / Screen.width * 12f);
        pos.z = Mathf.Clamp(pos.z, -2.6f, 2.6f);
        _rigidbody.MovePosition(pos);
        _lastX = x;
    }
    else if (Input.GetMouseButtonUp(0))
    {
        _lastX = null;
    }
}

```

How can you solve this?

thanks for help

# Answer
> 0 votes
```
[SerializeField]
Rigidbody _rigidbody;

float? _lastX = null;

float _p = 0f;

void FixedUpdate()
{
    var pos = _rigidbody.position;
    pos.x += 3f * Time.fixedDeltaTime;
    pos.z = _p;
    _rigidbody.MovePosition(pos);
}

void Update()
{
    if (Input.GetMouseButtonDown(0))
    {
        _lastX = Input.mousePosition.x;
    }
    else if (_lastX != null && Input.GetMouseButton(0))
    {
        var pos = _rigidbody.position.z;
        var x = Input.mousePosition.x;
        pos += -((x - (float)_lastX) / Screen.width * 160f * Time.deltaTime);
        pos = Mathf.Clamp(pos, -2f, 2f);
        //_rigidbody.MovePosition(pos);
        _p = pos;
        _lastX = x;
    }
    else if (Input.GetMouseButtonUp(0))
    {
        _lastX = null;
    }
}

```

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


# Question
Title: How can I improve the performance of my game that plays a video?
I have a level where I have embedded 5 short videos and the levels lags a little compared to the other levels, so it seems that adding videos in a Unity made game is expensive on its performance and memory.

Is there a better way to do this unity, maybe using GIFs or something?

# Answer
Ok so I tried a few different methods, turns out instead of using .mp4 I can use .ogv, this results in a little bit of quality loss, but it made it extremely small in size, so the issues with the memory are fixed.

Also i now don't feel any frame drops at all in-engine, things should work even better outside.
> 0 votes

---
Tags: unity, performance, optimization, video
---


# Question
Title: How to make a GameObject occasionally change direction in Unity?
I'm trying to create a periodic timer in Unity, so that I can create a GameObject that randomly moves around. Unfortunately, with my current code, the GameObject goes in a constant direction and doesn't ever update to change the direction. I believe that it might not be changing because the coroutine might only be called once, but I'm not exactly sure how to create a timer that can do this. I've been searching for a while online, but I haven't found anything yet. Here's the main code that has been causing the issue:

```
   public float speed;
   public float wanderDegrees;

    void Update()
    {

        if (gameObject.name == "Enemy_R")
        {
            StartCoroutine("RandomMovements");
        }
    }

    IEnumerator RandomMovements()
    {
            float angle = Mathf.PerlinNoise(-wanderDegrees, wanderDegrees) * Mathf.Deg2Rad;
            Vector2 direction = new Vector2(Mathf.Sin(angle), -Mathf.Cos(angle));
            yield return new WaitForSeconds(1f);
            Vector2 velocity = direction * speed;
            transform.Translate(velocity * Time.deltaTime);
    }

```

# Answer
```
public float speed = 1f;
public float wanderDegrees = 45f;

Vector2 _velocity;

void Start() {
    // Don't check the game object's name here. Just put this component
    // on ONLY the enemy that's supposed to use it, and not on the others.
    // if (gameObject.name == "Enemy_R")

    // Don't look up your coroutine by its name - that's unnecessarily slow.
    StartCoroutine(ChooseRandomDirectionsPeriodically());
}

// You want to move every frame, not just when you pick a new direction,
// so put that in Update.
void Update() {
    transform.Translate(_velocity * Time.deltaTime);
}

IEnumerator ChooseRandomDirectionsPeriodically()
{
    // Use a while loop to repeat this behaviour over and over again at intervals.
    while (true) {
        // The way you were using noise here was nonsensical.
        // Let's use a random die roll instead.
        float angle = Random.Range(-wanderDegrees, wanderDegrees) * Mathf.Deg2Rad;
        Vector2 direction = new Vector2(Mathf.Sin(angle), -Mathf.Cos(angle));
        // Cache the velocity in a member variable to be used in Update.
        _velocity = direction * speed;

        // Wait at the end of the loop, after we've done all our work.
        yield return new WaitForSeconds(1f);
    }
}

```
> 3 votes

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


# Question
Title: Something goes wrong when using System.Diagnostics.Process.Start to open a Monogame project
I am trying to develop a menu application for a homemade arcade. However, when I use `Process.Start(path)` to open my monogame projects' `.exe` files something weird occurs. If I try to open the .exe file manually it all works fine. When the menu opens one specific game all the effects disappear and in another the game crashes.

Other games on platforms such as Steam work just fine. From the beginning I thought that the Monogame projects somehow couldn't run at the same time. However, that is not the case as I tested running a MonoGame project from a basic terminal application. It had the same result as my menu.

Does anyone know why this could be occuring? Is there any equivalent to Process that does not have this issue?

# Answer
> 1 votes
In order to solve the problem you have to set a so called `working directory`. This has to be the path to the folder in which the .exe is in.

My code:

```
ProcessStartInfo info = new ProcessStartInfo(path);

int index = path.LastIndexOf("\\") + 1;

string dirPath = path.Remove(index - 1);

info.WorkingDirectory = dirPath;
process = Process.Start(info);

```

Huge thanks to @Tyyppi\_77 for pointing me in the right direction!

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


# Question
Title: Timing User Inputs for Inventory on 60UPS game loop
I'm making an inventory system for my pure Java game right now. Currently, the game runs at a 60UPS, and inputs are checked each update.

I have inputs set up using arrays of the current update and last update's key presses:

```
private final int NUM_KEYS = 256;

    private boolean[] pressedKeys;
    private boolean[] pressedKeysLast;

    // yes, those are initialized in the actual code :)

    @Override
    public void keyPressed(KeyEvent e) {

        if (e.getKeyCode() <= NUM_KEYS) {
            // Presses the key if it is valid.
            pressedKeys[e.getKeyCode()] = true;
        }

    }

    /**
     * Handles the keyReleased event.
     */

    @Override
    public void keyReleased(KeyEvent e) {

        if (e.getKeyCode() <= NUM_KEYS) {
            // Releases the key if it is valid.
            pressedKeys[e.getKeyCode()] = false;
        }
    }

    /**
     * Updates the input class and updates the input arrays.
     */

    public void update() {

        /*
         * Sets the values of last frame's pressed keys
         * to this frame's pressed keys.
         */
        for (int index = 0; index < NUM_KEYS; index++) {
            pressedKeysLast[index] = pressedKeys[index];
        }
    }

    /**
     * Determines if a specific key has just been pressed.
     * @param keyCode The key to be checked.
     * @return True if the key is pressed, false if it is not.
     */

    public boolean isKeyDown(int keyCode) {
        /*
         * This will return true if the key has been pressed in
         * this frame, but not in the last frame.
         */
        return pressedKeys[keyCode] && !pressedKeysLast[keyCode];
    }

```

This works fine, but for logging quick keypresses, such quickly pressing and releasing "E" to open the player's inventory, this system is too fast.

I have seen that every time that I try to quickly press and release a key to see if I can open the inventory using `isKeyDown(KeyEvent.VK_E)`, the `update()` method is called approximately 3 times, and since the arrays reset each frame, I only have a 0.05 seccond window to achieve the result I want, which is to get when the key is pressed and released quickly.

I am looking for suggestions to my problem so the`input.isKeyDown(int keycode)` method be able to determine when keycodes are quickly pressed, regardless if the duration of the press is 0.05s or 1.5s.

# Answer
To keep track of when keys are down and when a key has been pressed (down and up) you need to track some additional data and states.

## Key states

You will need a frame counter that counts up for each call to `update` and 3 arrays to hold the key states.

* `downKeys` boolean array true when key is down
* `wasPressedKeys` boolean array true after a key has been pressed
* `keyHeldTime` int array holds when key went down, in frames, if the key is down.

When the key is up it holds how long the key was down for in frames.

The key event methods flag when keys are down, and sets the frame time or held length for each key (see example `keyPressed` and `keyReleased`)

## Query key states

Then to query the keyboard state we have two methods

* `int wasKeyDown(int keyCode)` that returns how long the key was down for in frames.

If the key is currently down it returns 0.
* `int isKeyDown(int keyCode)` Return number of frames the key is down for.

If the key is up then it returns 0

To ensure we react only once to key events an additional method is used to clear was pressed state

* `void clearPressedKey(int keyCode)`

## Using key states

We can now react to both keys held, and key pressed. If a key has both a fast action and a hold action, the hold action must be delayed (or reversible) until the key has been held for longer than the fast action time.

In the example the key 13 if pressed for less than 4 frames will call the method `doActionShort()`. it will also reset the `wasPressedKeys` flag by calling `clearPressedKey(13)` to ensure we don't repeat the action.

If the key is held nothing will happen until it has been held for more than 3 frames. After being held for over 3 frames it will call the method `doActionHold()` as long as the key is held down.

**Note** that the first thing the update function does is increment the `frameCounter` so that you can track when and how long keys have been down for.

**Note** that you do not need to count frames, you can use time rather than frames.

## Example code snippets

/* Keyboard State */
private boolean[] downKeys;
private boolean[] wasPressedKeys;
private int[] keyHeldTimes;
private int frameCounter = 0;

/* Keyboard events */
@Override
public void keyPressed(KeyEvent e) {
    int keyCode = e.getKeyCode();
    downKeys[keyCode] = true;
    wasPressedKeys[keyCode] = false;
    keyHeldTime[keyCode] = frameCounter;

}
@Override
public void keyReleased(KeyEvent e) {
    int keyCode = e.getKeyCode();
    downKeys[keyCode] = false;
    wasPressedKeys[keyCode] = true;
    keyHeldTime[keyCode] = frameCounter - keyHeldTime[keyCode];
}

/* Keyboard state queries */
public int isKeyDown(int keyCode) {
    if (downKeys[keyCode] && !wasPressedKeys[e.keyCode]) {
        return keyHeldTime[keyCode] - frameCounter;
    }
    return 0;
}
public int wasKeyDown(int keyCode) {
    if (!downKeys[keyCode] && wasPressedKeys[e.keyCode]) {
        return keyHeldTime[keyCode];
    }
    return 0;
}

/* Keyboard state utility */
public void clearPressedKey(int keyCode) {
    wasPressedKeys[keyCode] = false;
}

/* Update loop ? 60FPS */
public void update() {
    frameCounter += 1; // count current frame

    int wasDownFor = wasKeyDown(13);        // was key down and for how long
    if (wasDownFor > 0 && wasDownFor < 4) { // key was down for less than 4 frames
        clearPressedKey(13);                // reset the key
        doActionShort();                    // do short action
    }

    if (isKeyDown(13) > 3) { // key is down for more than 3 frames
        doActionHold();      // while key is held do hold action
    }
}

```

> 1 votes

---
Tags: java, input, inventory
---


# Question
Title: How do I split an anim into separate takes?
I can split the animations of an FBX file into individual takes by script.

However, I have not found a way to do that with .anim files.

Is it not possible to split .anim files into individual takes?

ps: This is the script that I use to split an FBX files into individual takes. However, I can't use the same script for anim files because there is no model importer for an anim file:

```
ModelImporter nModelImporter = (ModelImporter)AssetImporter.GetAtPath(sPathOfFBXFileInAssetFolder);

nModelImporter.clipAnimations = (ModelImporterClipAnimation[])nList.ToArray(typeof(ModelImporterClipAnimation));

```

# Answer
> 2 votes
The reason you can "split" animations in an fbx is because the format itself keeps the different tracks separated, so you technically aren't splitting them, they are already different animations. Your own code should make it pretty clear as you're casting a list of animations into an array of the same type.

You cannot split .anim files as they don't store multiple animation clips, they ARE animation clips.

The only possible way of splitting a single clip into multiple ones that comes to my mind would be to:

1. Know at what frames to split up the animation
2. Copy each section you want to be separated and insert it into a new clip which you would then create as an asset file inside of Unity through some Editor Utilities

Here's a link where you can take a look at an example of creating an animation clip through code: https://answers.unity.com/questions/784855/how-to-create-animations-via-script.html

Not sure if my answer satisfies your question, but I hope it can help you towards your goal.

---
Tags: unity
---


# Question
Title: How to change the transparency of an object in using code?
I have laser-object in my scene, which I want to be seen only when I press the 'E' button on the key board(just an example of a key). I have seen many ways to change the transparency , however, none of them worked. one of them was -

```
gameObject.renderer.material.color.a = 0.0f ;

```

I get an Error - UnityEngine.renderer does not contain color and material sub-functions.

I don't know how to do it, and I tried many ways. Does someone have an easy way to make an object transparent and visible in C# script ? Thank you

# Answer
Making an object 'transparent' so it cannot be seen is not the most efficient way to do things. What you rather want to do is make the renderer inactive when you don't want to see it, and active when you do.

If you click on your gameObject in the editor, there should be a Mesh Renderer as one of the components.

To set it to inactive from a script attached to this same gameObject, you can do this...

```
gameObject.GetComponent<Renderer> ().enabled = false;

```

If you really want to use transparency, you can do this...

```
gameObject.GetComponent<Renderer> ().material.color.a = 0;

```

Although if you are setting transparency, you need to make sure the shader the material is using supports transparency. I would suggest using the Legacy Shaders/Transparent Diffuse shader.
> 4 votes

# Answer
In **recent Unity version**,

## this code is invalid

**gameObject.renderer.material.color.a = 0.0f ;** instead first you have to get materail from rendere like this

```
 private Material currentMat;

    // Start is called before the first frame update
    void Start()
    {
        currentMat = gameObject.GetComponent<Renderer>().material;

    }

```

Then, use this method to change alpha value

```
void ChangeAlpha(float alphaVal)
    {
        Color oldColor = currentMat .color;
        Color newColor = new Color(oldColor.r, oldColor.g, oldColor.b, alphaVal);
        currentMat .SetColor("_Color", newColor);

    }

```

For more explanation, you see this **video link**.
> 3 votes

# Answer
## Disable Objects || Set Objects Transparent

Ok, so I'm by no means an expert but let me take a crack at this.

If you want an object disabled entirely, you would say:

```
public bool isInvisible;
private void Update()
{
    if (Input.GetKeyDown(KeyCode.E))
    {
        if (!isInvisible)
            gameObject.SetActive(false);
            isInvisible = !isInvisible;
        else
            gameObject.SetActive(true);
            isInvisible = !isInvisible;
    }
}

```

In the Unity editor, within the Inspector window, next to the name of each GameObject there's a little boolean check box. This sets the GameObject to either active or not active, the corresponding line of code in C# being the one listed above within the if statement. This will keep the object instantiated, but render it disabled and all of its components will be disabled as well.

Now if you wanted to stick with changing the alpha, and simply making it transparent, you could try something like this:

```
public bool isInvisible;
private void Update()
{
    if (Input.GetKeyDown(KeyCode.E))
    {
        Color curColor = gameObject.GetComponent<Renderer>().material.color;
        if (!isInvisible)
            gameObject.GetComponent<Renderer>().material.color = new Color(curColor.r, curColor.g, curColor.b, 0);
            isInvisible = !isInvisible;
        else
            gameObject.GetComponent<Renderer>().material.color = new Color(curColor.r, curColor.g, curColor.b, 1);
            isInvisible = !isInvisible;
    }
}

```

This will set the Renderer's current color's alpha to 0, then to 1 respectively as you press "e".
> 0 votes

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


title: Palette Swapping in Allegro 5

text:
# Question
Title: Palette Swapping in Allegro 5
I am trying to do a palette swap in Allegro 5. I have not found any way to do this from my research. So what I've thought of doing is to do it myself by setting individual pixels. I also haven't found a way to do this but Allegro 5 does allow for getting pixels. Is there some way to set a pixel in Allegro 5?

# Answer
I'm not familiar with Allegro, but a scan through the documentation turns up the following:

al\_draw\_pixel
`void al_draw_pixel(float x, float y, ALLEGRO_COLOR color)`

> Draws a single pixel at x, y.

al\_put\_pixel
`void al_put_pixel(int x, int y, ALLEGRO_COLOR color)`

> Draw a single pixel on the target bitmap.

If you look at the source code linked from the documentation of either, you will notice that both make a call to `al_get_target_bitmap`, which is used to get the target bitmap of the calling thread. That function has a setter companion: `al_set_target_bitmap` which is used to select the bitmap to which all subsequent drawing operations in the calling thread will draw (docs for the latter).

For performance reasons, you might also want to look into locking the bitmap with `al_lock_bitmap` when manipulating the pixels.

There also appears to be some example code with some manual palette manipulation.
> 1 votes

---
Tags: pixel, allegro, palette
---


# Question
Title: How do I make the game appear in the window?
```
#include<SFML/Graphics.hpp>
#include<iostream>
#include <SFML/Graphics/Font.hpp>
#include <SFML/Audio.hpp>
#include "menu1.h"
//#include "menuNames.h"
using namespace std;
using namespace sf;

/*
    class menu2play
    in main function:
        check event if event keboard enter
            check mainMenuPressed == 0:
            window menu2play
*/

int  page_number;
sf::Event event;
bool check(int x, int y, int& value);

int boarddata1[9][9] = {
    {0, 0, 0, 2, 6, 0, 7, 0, 1},
    {6, 8, 0, 0, 7, 0, 0, 9, 0},
    {1, 9, 0, 0, 0, 4, 5, 0, 0},
    {8, 2, 0, 1, 0, 0, 0, 4, 0},
    {0, 0, 4, 6, 0, 2, 9, 0, 0},
    {0, 5, 0, 0, 0, 3, 0, 2, 8},
    {0, 0, 9, 3, 0, 0, 0, 7, 4},
    {0, 4, 0, 0, 5, 0, 0, 3, 6},
    {7, 0, 3, 0, 1, 8, 0, 0, 0}
};

int answer1[9][9] = {
  {4, 3, 5, 2, 6, 9, 7, 8, 1},
  {6, 8, 2, 5, 7, 1, 4, 9, 3},
  {1, 9, 7, 8, 3, 4, 5, 6, 2},
  {8, 2, 6, 1, 9, 5, 3, 4, 7},
  {3, 7, 4, 6, 8, 2, 9, 1, 5},
  {9, 5, 1, 7, 4, 3, 6, 2, 8},
  {5, 1, 9, 3, 2, 6, 8, 7, 4},
  {2, 4, 8, 9, 5, 7, 1, 3, 6},
  {7, 6, 3, 4, 1, 8, 2, 5, 9}
};

int boardData2[9][9] = {

    {2, 0, 0, 0, 0, 1, 0, 0, 7},
    {0, 0, 0, 8, 0, 9, 4, 2, 0},
    {0, 0, 3, 6, 0, 0, 0, 0, 0},
    {0, 7, 2, 0, 3, 0, 0, 0, 0},
    {9, 3, 0, 0, 0, 2, 1, 5, 0},
    {8, 6, 0, 0, 9, 0, 7, 0, 0},
    {5, 0, 0, 9, 0, 0, 0, 0, 0},
    {0, 1, 0, 2, 0, 3, 6, 0, 8},
    {0, 8, 0, 0, 6, 7, 2, 0, 0}
};

int answer2[9][9] = {

{2, 9, 8, 3, 4, 1, 5, 6, 7},
{6, 5, 1, 8, 7, 9, 4, 2, 3},
{7, 4, 3, 6, 2, 5, 9, 8, 1},
{1, 7, 2, 5, 3, 6, 8, 4, 9},
{9, 3, 4, 7, 8, 2, 1, 5, 6},
{8, 6, 5, 1, 9, 4, 7, 3, 2},
{5, 2, 6, 9, 1, 8, 3, 7, 4},
{4, 1, 7, 2, 5, 3, 6, 9, 8},
{3, 8, 9, 4, 6, 7, 2, 1, 5}
};

int boardData3[9][9] = {
{8, 0, 1, 0, 0, 0, 0, 0, 4},
{4, 5, 0, 3, 0, 2, 6, 0, 7},
{3, 0, 0, 0, 0, 0, 5, 9, 1},
{0, 3, 0, 0, 0, 0, 0, 0, 8},
{6, 1, 2, 9, 8, 0, 0, 0, 0},
{0, 0, 5, 1, 6, 0, 0, 2, 3},
{0, 4, 0, 5, 0, 0, 8, 7, 0},
{0, 6, 0, 2, 4, 0, 0, 5, 0},
{0, 9, 0, 8, 0, 0, 0, 1, 2}
};

int answer3[9][9] = {

{8, 7, 1, 6, 5, 9, 2, 3, 4},
{4, 5, 9, 3, 1, 2, 6, 8, 7},
{3, 2, 6, 4, 7, 8, 5, 9, 1},
{9, 3, 4, 7, 2, 5, 1, 6, 8},
{6, 1, 2, 9, 8, 3, 7, 4, 5},
{7, 8, 5, 1, 6, 4, 9, 2, 3},
{2, 4, 3, 5, 9, 1, 8, 7, 6},
{1, 6, 8, 2, 4, 7, 3, 5, 9},
{5, 9, 7, 8, 3, 6, 4, 1, 2}
};
int usedarray[9][9];
int answer[9][9];

bool lock[9][9];

int X, Y;
int counter = 0;
int variable = 0;
sf::Text boardtext[9][9];
sf::RenderWindow window1(sf::VideoMode(1067, 715), "Sudoku!");
sf::SoundBuffer wrongAnswer;
sf::Sound explosionWrong;
sf::SoundBuffer youWin;
sf::Sound explosionWin;

int raw, column;

int main()
{
    RenderWindow window(sf::VideoMode(600, 600), "suduko");

    menu1 Menu(500, 500);
    //menu1 menuPlay(500, 500);
    /*menuNames  menu(string);
    menuNames m;*/
    while (window.isOpen())
    {
        sf::Event event;
        while (window.pollEvent(event))
        {
            if (event.type == sf::Event::Closed)
                window.close();
            if (event.type == sf::Event::KeyReleased)
            {
                if (event.key.code == sf::Keyboard::Up)
                {
                    Menu.moveUp();
                    break;
                }
                if (event.key.code == sf::Keyboard::Down)
                {
                    Menu.moveDown();
                    break;

                }
                //choose page
                if (event.key.code == sf::Keyboard::Return) //enter
                {

                    if (Menu.mainMenuPressed() == 0)
                    {
                        window.close();
                        page_number = 0;
                    }
                    if (Menu.mainMenuPressed() == 1)
                    {
                        window.close();
                        page_number = 1;
                    }
                    if (Menu.mainMenuPressed() == 2)
                    {
                        window.close();
                        page_number = 2;
                    }
                }

            }

        }

        window.clear();
        Menu.draw(window);
        window.display();
    }
        if (page_number == 0)
        {
            srand(time(0));
            int randomnumber = rand() % 3 + 1;

            for (int i = 0; i < 9; i++) {
                for (int j = 0; j < 9; j++) {

                    if (randomnumber == 1)
                    {

                        usedarray[i][j] = boarddata1[i][j];
                        answer[i][j] = answer1[i][j];

                    }
                    else if (randomnumber == 2)
                    {
                        usedarray[i][j] = boardData2[i][j];
                        answer[i][j] = answer2[i][j];
                    }
                    else
                    {
                        usedarray[i][j] = boardData3[i][j];
                        answer[i][j] = answer3[i][j];

                    }

                }
            }

            for (int i = 0; i < 9; i++)
            {
                for (int j = 0; j < 9; j++)
                {
                    if (usedarray[i][j] != 0)

                        lock[i][j] = 1;
                    else
                        counter++;
                }
            }

            sf::Texture texture;
            texture.loadFromFile("sudoku-test.png");
            sf::Sprite background(texture);
            background.setScale(1, 1);

            sf::Font font;
            if (!font.loadFromFile("arial.ttf"))
                throw("couldn't open font");

            window1.clear();

            window1.display();

            sf::Text space;
            space.setString(" ");

            if (wrongAnswer.loadFromFile("wrong answer.wav") == 0)
            {
                return 1;
            }
            if (youWin.loadFromFile("clapping.wav") == 0)
            {
                return 1;
            }

            for (int i = 0; i < 9; i++)
            {
                for (int j = 0; j < 9; j++)
                {
                    boardtext[i][j] = sf::Text();
                    boardtext[i][j].setCharacterSize(30);
                    boardtext[i][j].setFont(font);
                    boardtext[i][j].setFillColor(sf::Color::Blue);
                    boardtext[i][j].setString(std::to_string(usedarray[i][j]));
                    boardtext[i][j].setPosition(sf::Vector2f((window1.getSize().x - 337) / 9 * i + 35, window1.getSize().y / 9 * j + 25));
                }
            }

        //mouse event
        if (sf::Mouse::isButtonPressed(sf::Mouse::Left)) {
            sf::Vector2i position = sf::Mouse::getPosition();
            sf::Mouse::setPosition(sf::Vector2i(100, 200), window1);
        }

        //play
        sf::RenderWindow window1(VideoMode(1067, 715), "play", sf::Style::Close);
        while (window1.isOpen())
            //background.jpeg

            while (window1.pollEvent(event))
            {

                if (event.type == sf::Event::Closed)
                    window1.close();

                switch (event.type)
                {
                case sf::Event::MouseButtonPressed:
                    X = sf::Mouse::getPosition(window1).x;
                    Y = sf::Mouse::getPosition(window1).y;

                    raw = X / 80;
                    column = Y / 80;
                    cout << "i" << raw << " j " << column << endl;
                    if ((X < 861) && (X > 758))
                    {
                        if ((Y > 529) && (Y < 587)) {
                            variable = 0;
                        }
                    }
                    if (X > 720)
                    {
                        if ((Y > 160) && (Y <= 260)) {
                            variable = (((X - 780) / 74) + 1);
                        }
                        else if ((Y > 260) && (Y <= 369)) {
                            variable = (((X - 780) / 74) + 4);
                        }
                        else if ((Y > 369) && (Y <= 478)) {
                            variable = (((X - 780) / 74) + 7);
                        }
                        std::cout << "number is" << variable << endl;
                    }
                    if (X < 720) check(raw, column, variable);

                    break;
                }

            }
        window1.clear();

        window1.draw(background);

        window1.display();
        for (int i = 0; i < 9; i++)
        {
            for (int j = 0; j < 9; j++)
            {
                if (usedarray[i][j] == 0)
                    window1.draw(space);
                else
                    window1.draw(boardtext[i][j]);

            }
        }

    /*  window1.clear();

        window1.display();*/

    }

}

    //if (page_number == 1)
    //{
    //  //About
    //  sf::RenderWindow window_play(VideoMode(300, 300), "About", sf::Style::Close);
    //  while (window_play.isOpen())
    //  {
    //      while (window_play.pollEvent(event))
    //      {
    //          if (event.type == sf::Event::Closed)
    //              window_play.close();

    //          cout << "Tesser Redaa";
    //          cout << "Smaa Salah";
    //          cout << "Doaa Mohamed";
    //          cout << "Salwa Ahmed";
    //          cout << "Menna Shaaban";
    //          cout << "Rana Ahmed";
    //          cout << "ranneem Loaa";

    //      }
    //      window_play.clear();
    //      window_play.display();
    //  }
    //}

    //if (page_number == 2)
    //{
    //  //play
    //  sf::RenderWindow window_play(VideoMode(300, 300), "Exit", sf::Style::Close);
    //  while (window_play.isOpen())
    //  {
    //      while (window_play.pollEvent(event))
    //      {
    //          if (event.type == sf::Event::Closed)
    //              window_play.close();
    //          break;

    //      }
    //      window_play.clear();

    //      window_play.display();
    //  }
    //}

    //if (page_number == 2)
    //{
    //  //exit
    //  break;
    //}

    /*return 0;

}*/

bool check(int i, int j, int& value)
{
    if (lock[i][j] == 0)
    {
        i = raw;
        j = column;
        cout << "correct answer is" << answer[i][j] << endl;
        if (value == answer[i][j])
        {
            usedarray[i][j] = value;
            lock[i][j] = 1;
            counter--;
            boardtext[i][j].setFillColor(sf::Color::Green);
            cout << usedarray[i][j] << " correct\n";
            boardtext[i][j].setString(std::to_string(usedarray[i][j]));

            if (counter == 0)
            {
                cout << "you winned !!!!!";

                explosionWin.setBuffer(youWin);
                explosionWin.setVolume(1000);

                explosionWin.play();
            }

            return 1;
        }
        else
        {
            usedarray[i][j] = value;
            boardtext[i][j].setFillColor(sf::Color::Red);
            cout << boarddata1[i][j] << " wrong\n";
            boardtext[i][j].setString(std::to_string(usedarray[i][j]));

            explosionWrong.setBuffer(wrongAnswer);
            explosionWrong.setVolume(1000);

            explosionWrong.play();

            return 0;

        }
    }

}

```

# Answer
> 1 votes
Just like what's been said in the comment section of your question, you typically create one (1) window, with a lifetime of game startup to game shutdown, and then you have a so-called state machine, which controls what state the game is/should be in.

What I usually do is that I have a base class, which serves as a single state in my game and other sub classes inherits from that class. When I say sub classes, I mean each individual state in my game, like menu state, game state, quit state etc.

When I have that structure set up, I usually also have a state machine class, which only purpose is to keep track of the states that exist in the game, handling switching from one state to another and finally also to update- and render the state the game is currently in.

Let's see how we can structure the code to make this happen:

First we have the state class, which every state in the game should inherit from.

```
class IState
{
public:

             IState         (void) {}
    virtual ~IState         (void) {}

    virtual bool Create     (CApplication* pApplication, CStateMachine* pStateMachine)  = 0;
    virtual void Destroy    (void)                                                      = 0;
    virtual void OnCreate   (void)                                                      = 0;
    virtual void OnDestroy  (void)                                                      = 0;
    virtual void OnEnter    (void)                                                      = 0;
    virtual void OnExit     (void)                                                      = 0;
    virtual void Update     (const float DeltaTime)                                     = 0;
    virtual void Render     (void)                                                      = 0;

protected:

    CApplication*   m_pApplication;

    CStateMachine*  m_pStateMachine;

};

```

As you can see, it's an abstract class with only virtual functions, which will be called by the state machine later.

Next we have each state in the game and I will show an example of a menu state.

```
/**
* h file:
**/

class CStateMenu : public IState
{
public:

     CStateMenu     (void);
    ~CStateMenu     (void);

    bool Create     (CApplication* pApplication, CStateMachine* pStateMachine) override;
    void Destroy    (void) override;
    void OnCreate   (void) override;
    void OnDestroy  (void) override;
    void OnEnter    (void) override;
    void OnExit     (void) override;
    void Update     (const float DeltaTime) override;
    void Render     (void) override;

private:

};

//////////////////////////////////////////////////////////////////////////

/**
* cpp file:
**/

#include "CStateMenu.h"

#include "CApplication.h"
#include "CStateMachine.h"

#include <SFML/Window.hpp>

CStateMenu::CStateMenu(void)
{
    m_pApplication  = nullptr;
    m_pStateMachine = nullptr;
}

CStateMenu::~CStateMenu(void)
{

}

bool CStateMenu::Create(CApplication* pApplication, CStateMachine* pStateMachine)
{
    // Stuff that needs to be created/set at application startup, and not on each state change, and needs to last during the lifetime of the state

    m_pApplication  = pApplication;
    m_pStateMachine = pStateMachine;

    return true;
}

void CStateMenu::Destroy(void)
{
    // Stuff that needs to be destroyed/unset at application shutdown, and not on each state change

    m_pStateMachine = nullptr;
    m_pApplication  = nullptr;
}

void CStateMenu::OnCreate(void)
{
    // Create the menu objects, load font file(s), load menu music file(s) etc

    /*
    Example:

    ButtonStartGame.Create();
    ButtonQuit.Create();
    Music->Load("Menu music.mp3");
    */
}

void CStateMenu::OnDestroy(void)
{
    // Destroy the menu objects, unload font file(s), unload menu music file(s) etc

    /*
    Example:

    Music->Unload();
    ButtonQuit.Destroy();
    ButtonStartGame.Destroy();
    */
}

void CStateMenu::OnEnter(void)
{
    // Start the menu music etc

    /*
    Example:

    Music->Play();
    */
}

void CStateMenu::OnExit(void)
{
    // Stop the menu music etc

    /*
    Example:

    Music->Stop();
    */
}

void CStateMenu::Update(const float DeltaTime)
{
    // Update the menu, handle input from the keyboard and/or mouse etc

    if(sf::Keyboard::isKeyPressed(sf::Keyboard::Return))
        m_pStateMachine->SetState(m_pStateMachine->GetStateGame());

    /*
    Example for mouse usage:

    if(ButtonStartGame.Pressed())
        m_pStateMachine->SetState(m_pStateMachine->GetStateGame());
    */
}

void CStateMenu::Render(void)
{
    // Render the menu buttons etc

    /*
    Example:

    ButtonGameStart.Render();
    ButtonQuit.Render();
    */
}

```

Note how the menu state class is inheriting from the state class and overrides its virtual functions. If you have, say, a class called StateGame, and you want to use it as a game state as well, that class should inherit from the state and override its functions too, just like the menu state class does.

In the menu state class above, I'm showing an example on how to use it, how to render stuff and also how to change from the menu state into the game state, which happens when the return key on the keyboard is pressed. The same usage can be used when you want to switch back to the menu state from the game state etc.

Next we have the state machine class, which, again, will handle the different states the game can/should be in, handling switching from one state to another and finally also to update- and render the current state the game is in.

```
/**
* h file:
**/

class CStateMachine
{
public:

     CStateMachine              (void);
    ~CStateMachine              (void);

    bool        Create          (CApplication* pApplication);
    void        Destroy         (void);

    void        Update          (const float DeltaTime);
    void        Render          (void);

    void        SetState        (IState* pNewState);

public:

    CStateMenu* GetStateMenu    (void)  const   {return m_pStateMenu;}
    CStateGame* GetStateGame    (void)  const   {return m_pStateGame;}

private:

    void SwitchState(void);

private:

    IState*     m_pCurrentState;
    IState*     m_pNextState;

    CStateMenu* m_pStateMenu;
    CStateGame* m_pStateGame;

};

//////////////////////////////////////////////////////////////////////////

/**
* cpp file:
**/

#include "CStateMachine.h"

CStateMachine::CStateMachine(void)
: m_pCurrentState(nullptr)
, m_pNextState(nullptr)
, m_pStateMenu(nullptr)
, m_pStateGame(nullptr)
{

}

CStateMachine::~CStateMachine(void)
{

}

bool CStateMachine::Create(CApplication* pApplication)
{
    m_pStateMenu = new CStateMenu;
    if(!m_pStateMenu->Create(pApplication, this))
        return false;

    m_pStateGame = new CStateGame;
    if(!m_pStateGame->Create(pApplication, this))
        return false;

    // Set the start state
    m_pCurrentState = m_pStateMenu;
    m_pCurrentState->OnCreate();
    m_pCurrentState->OnEnter();

    return true;
}

void CStateMachine::Destroy(void)
{
    m_pCurrentState = nullptr;
    m_pNextState    = nullptr;

    m_pStateGame->Destroy();
    delete m_pStateGame;
    m_pStateGame = nullptr;

    m_pStateMenu->Destroy();
    delete m_pStateMenu;
    m_pStateMenu = nullptr;
}

void CStateMachine::Update(const float DeltaTime)
{
    m_pCurrentState->Update(DeltaTime);

    if(m_pNextState)
        SwitchState();
}

void CStateMachine::Render(void)
{
    m_pCurrentState->Render();
}

void CStateMachine::SetState(IState* pNewState)
{
    // Queue a state change, which will occur when the current state's update function is finished
    m_pNextState = pNewState;
}

void CStateMachine::SwitchState(void)
{
    /*
    I have separated the state creation/preparation into two functions since you
    might wanna execute 'OnCreate' / 'OnDestroy' in a loading thread to load assets etc,
    while having the main thread showing a loading screen
    */

    m_pCurrentState->OnExit();
    m_pCurrentState->OnDestroy();

    m_pCurrentState = m_pNextState;
    m_pCurrentState->OnCreate();
    m_pCurrentState->OnEnter();

    m_pNextState = nullptr;
}

```

The class itself is very simple, with only a few functions, and using this class is very simple as well.

I always try to make the main function as short/minimal as possible, so I usually end up creating an application class, which creates my window and other needed objects for my game, while also keeping track of their lifetime etc. Let's see how a simple application class can look like:

```
/**
* h file:
**/

class CApplication
{
public:

     CApplication                   (void);
    ~CApplication                   (void);

    bool                Create      (void);
    void                Destroy     (void);

    void                Run         (void);

    void                Update      (void);
    void                Render      (void);

    void                Quit        (void);

public:

    sf::RenderWindow&   GetWindow   (void)  {return m_Window;}

private:

    sf::RenderWindow    m_Window;

    sf::Clock           m_Clock;

    sf::Event           m_Event;

    CStateMachine*      m_pStateMachine;

    bool                m_Running;

};

//////////////////////////////////////////////////////////////////////////

/**
* cpp file:
**/

#include "CApplication.h"

CApplication::CApplication(void)
: m_Window()
, m_Clock()
, m_Event()
, m_pStateMachine(nullptr)
, m_Running(true)
{
    m_Clock.restart();
}

CApplication::~CApplication(void)
{

}

bool CApplication::Create(void)
{
    m_Window.create(sf::VideoMode(1280, 720), "SFML state machine");

    m_pStateMachine = new CStateMachine;
    if(!m_pStateMachine->Create(this))
        return false;

    return true;
}

void CApplication::Destroy(void)
{
    m_pStateMachine->Destroy();
    delete m_pStateMachine;
    m_pStateMachine = nullptr;

    m_Window.close();
}

void CApplication::Run(void)
{
    while(m_Running)
    {
        Update();
        Render();
    }
}

void CApplication::Update(void)
{
    while(m_Window.pollEvent(m_Event))
    {
        switch(m_Event.type)
        {
            case sf::Event::Closed:
            {
                Quit();

                break;
            }
        }
    }

    m_pStateMachine->Update(m_Clock.restart().asSeconds());
}

void CApplication::Render(void)
{
    m_Window.clear();

    m_pStateMachine->Render();

    m_Window.display();
}

void CApplication::Quit(void)
{
    m_Running = false;
}

```

As you can see, the application class creates the SFML window and the state machine, which creates each individual state.

Finally, the main function/entry point would then look something like this:

```
int main()
{
    CApplication* pApplication = new CApplication;

    if(!pApplication->Create())
        return 0;

    pApplication->Run();

    pApplication->Destroy();
    delete pApplication;
    pApplication = nullptr;

    return 0;
}

```

Hope this helps a bit.

Let me know if you have any questions and/or need me to explain something better.

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


# Question
Title: What are the most important accessibility features for games?
We're currently developing a 2D Platformer and we decided to take some time to implement Accessibility Features. But we couldn't find good information about Accessibility Features, muss less how to implenent them. With Accessibility Features we mean things like to reduce risk of seizure (Photosensitive Epilepsy). There will be a Accessibility Menu to manually activate these.

So does anybody have some Ideas what Features we could implement and some helpful tips about how to implement them?

# Answer
The most relevant accessibility concerns for game developers are:

* Color blindness. The most frequent one is red-green blindness which affects 9% of all genetically male people (it's quite rare for genetically female people, but not unheard of either). But there are also other forms of color blindness which might be worth accomodating. See this question for more details.
* Other visual impairments. There are many people who have bad eyesight. These players can be accomodated by having large and easy to read UI elements and fonts. Designing a game which can be played by completely blind people is a very difficult challenge which greatly restricts your game design. It hurts me to write this, but blind gamers are a very niche demographic, and the concessions you have to make to accommodate them are next to impossible in most game genres. So it simply does not make much economic sense to develop a "blind mode" for most games. But if you manage to pull this off, then I am pretty sure that you will get some media interest in your game. I would certainly want to check out your game to see hear and feel how you did this.
* Deafness. Your game should not rely too much on audio cues. Make sure that any information communicated via audio is also communicated visually. This is actually a great example for how accessibility features can improve your game for everyone, not just people with disability. Even players who can hear just fine might want to switch off sound for a variety of reasons. Maybe they like to listen to their own music while playing. Or maybe they need to listen to what happens in their real-world environment. Or perhaps they are in a voice chat with other players. Those are situations where it is very useful when a game is playable with sound off.
* Speaking of voice chat: This is of course also a problem for deaf gamers and players with speech impairments. But there are also a lot of players who can't or don't want to engage in voice chat for a variety of other reasons. Perhaps they don't want to disturb other people in their real-world environment. Or perhaps they are afraid of racist, ageist or sexist discrimination from other players. Or perhaps they are just shy. So if your game is multiplayer, do not assume that every player will be able and willing to engage in voice chat.

But on the other hand, voice chat can offer a way to communicate for those who can not type very fast. So it's still something you might want to have as an optional communication medium in your game.

I don't think I have ever seen a game which does automatic real-time transcription of voice chat. But the technology exists and got a lot better in the past years. So IMO it's something worth considering to break through the communication barrier between those who don't type and those who don't have sound.
* Motor disabilities. There are gamers who don't have two hands with 5 fingers each or can not move them as well as most people can. Measures to make your game playable for these gamers are:

+ Very customizable input configuration.
    + Support for a wide variety of input devices. You should also make sure that the game is fully playable with any single one of the input devices (mouse-only, keyboard-only or gamepad-only) or with a combination of multiple input devices (for example, distributing controls for one player over two or more gamepads). And, of course, support for adaptive controllers.
    + An ultra-low difficulty setting to accomodate players who are unable to make inputs fast enough.
    + Settings which remove mechanics which can be impossible for people with impaired motor-skills. Removing the need for button-mashing inputs is a typical example, and usually very easy to implement. Another example which is difficult for some players are inputs which require to make many inputs simultaneously. But those might require a bit more creativity.

Some resources for further reading:
> 8 votes

# Answer
Phillip has the more comprehensive answer to this question but since you asked about seizures, here's some information.

For the subject of seizures, one resource you can use is the Photosensitive Epilepsy Analysis Tool (PEAT). PEAT is a free, downloadable resource for developers to identify seizure risks in their web content and software. The evaluation used is based on an analysis engine developed specifically for web and computer applications.

PEAT can help authors determine whether animations or video in their content are likely to cause seizures. Not all content needs to be evaluated by PEAT, but content that contains video or animation should be evaluated, especially if that content contains flashing or rapid transitions between light and dark background colors.

The site contains additional information and resources that will ramp you up on this subject.
> 4 votes

---
Tags: accessibility
---