title: Network limitation in multiplayer game

text:
# Question
Title: Network limitation in multiplayer game
I have a multiplayer cooperative game (PVE) in where there can be up to 200 enemies at a time (somewhere around that) and I was wondering how devs generally synchronize these? I already have packets being sent every 0.2 seconds or so to players telling other player's position, health points and things like that, and I have no idea how much of the network I can actually use (in a P2P UDP connection).

I really don't wanna leave the clients to sync the enemies positions themselves, as myself as a player have played games like these and its so annoying to have you shooting an enemy in one corner of the map and your friend shooting the same enemy on the other corner. But I have no idea if sending every 0.3 seconds or so updates from 200 enemies and their position is reasonable.

**TL;DR: How would devs synchronize a high number of entities for multiple players and what is the limitation of a UDP connection? Is there a number of packets per second that you would work towards?**

# Answer
Your problem reminds me of this article about AoE: https://www.gamasutra.com/view/feature/131503/1500\_archers\_on\_a\_288\_network\_.php

The articles solution for AoE's large number of units on screen is for every client to simulate the game on their own. The clients only process the commands other players send out but otherwise the entire simulation is client side.

In your game for example, every player could send an event when they use a weapon, an ability, or fire a projectile. Every client simulates the effects of that action and simulates the change to the enemies or environment. That would reduce your networking traffic pretty heavily I'd imagine.

Since your game is PvE and P2P I feel like you could get away with a simulation trick like this rather than full replicating every enemy character in your game.

There are some caveats to consider. Most publicly available large scale game engines don't guarantee that a physics simulation will be identical on two machines. A late join player would require a special case for one of the players sending the entire state of the game to them and probably freezing any command execution during that time. Any packet loss could be catastrophic to the simulation so you have to guarantee that every command has been received and processed.
> 1 votes

---
Tags: networking, multiplayer, synchronization, udp, entity
---


# Question
Title: Unity font API behaves differently in built game
Specifically it's Font.CreateDynamicFontFromOSFont(), use this script attached to an empty GameObject in the scene.

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

public class TestFontTexture : MonoBehaviour {

    void Start ()
    {
        var font = Font.CreateDynamicFontFromOSFont("Consolas", 12);
        font.RequestCharactersInTexture("HelloWorld", 20);
        SaveTexture2PNG("./fontTexture.png", (Texture2D)font.material.mainTexture);
    }

    void Update ()
    {

    }

    void SaveTexture2PNG(string path, Texture2D tex)
    {
        byte[] bytes = tex.EncodeToPNG();
        System.IO.File.WriteAllBytes(path, bytes);
    }
}

```

After click play it should create a fontTexture.png file containing character glyphs in the Assets folder, but only in editor though. In the built game it just created a completely black image.

Since it's OS concerned, I'm using Windows 7 with font Consolas installed and Unity 5.6.5f.

How to make it work in a built game?

# Answer
> 1 votes
Just solved, it's about the readability of `font.material.mainTexture`.

In the editor there's no warning or error, and it's readable, but not in the built game.

Try to create the font by `Resources.Load()` instead of procedurally creating it from script, it'll pop up error when accessing `font.material.mainTexture` saying it's unreadable.

Using the script from https://support.unity3d.com/hc/en-us/articles/206486626-How-can-I-get-pixels-from-unreadable-textures-

and it works fine.

---
Tags: unity, fonts
---


title: How to solve the ground check problem?

text:
# Question
Title: How to solve the ground check problem?
I noticed a problem in Unity's third person controller's ground check.

The ground check should detect whether or not the player is standing on the ground. It does so by sending out a ray beneath the player.

However, if the player stands on top and in middle of two boxes and there is a space between these boxes, then the ray shoots into the gap and the player thinks he is not in contact with the ground, which looks like this:

I am unable to move. You can clearly see that the ray is in the gap and thus the player animator airborne blend tree is active.

What is the best way to solve this problem?

I was thinking of shooting multiple rays, from the same origin but with different angles. And `OnGround` should only be true, if X% of these rays hit the "ground". Or is there a better way?

# Answer
> 18 votes
Multiple rays works just fine in most cases, as described in the other answer.

You can also use a wider check — like a spherecast or boxcast. These use the same concept as a raycast, but with a geometric primitive that has some volume, so it can't slip into narrower cracks than your character could fall through. It also catches the case Shadows In Rain mentions, where your character is standing on a narrow pipe that might get missed by a raycast on each side of it.

A trigger collider that protrudes just a tiny bit below the bottom of your character's collider can accomplish a similar task. Like the sphere of box cast it has some width to detect ground on either side of a gap. Here you'd use OnTriggerEnter to detect when this ground sensor has come into contact with the ground.

# Answer
> 14 votes
I honestly think that the "multiple rays" approach is quite a good idea. I would not shoot them at angle though, instead i would kind of offset the rays, something like this:

The player is the blue stickman; The green arrows rapresent the additional rays, and the the orange points (RaycastHits) are the points where the two rays hit the boxes.

Ideally the two green rays should be positioned right under the feet of the player, in order to get the most precision to check if the player is grounded or not ;)

# Answer
> 1 votes
I think I solved it by changing `Physics.Raycast` to `Physics.SphereCast` in the script `ThirdPersonCharacter.cs`. But it still needs testing.

```
bool condition = Physics.SphereCast(
    m_Capsule.transform.position + m_Capsule.center + (Vector3.up * 0.1f),
    m_Capsule.height / 2,
    Vector3.down,
    out hitInfo,
    m_GroundCheckDistance
);

```

I also had to comment out this line which was changing the `m_GroundCheckDistance` value, otherwise there was some weird sliding at some models:

```
    void HandleAirborneMovement()
    {
        // apply extra gravity from multiplier:
        Vector3 extraGravityForce = (Physics.gravity * m_GravityMultiplier) - Physics.gravity;
        m_Rigidbody.AddForce(extraGravityForce);

        //m_GroundCheckDistance = m_Rigidbody.velocity.y < 0 ? m_OrigGroundCheckDistance : 0.01f;
    }

```

And I changed `m_GroundCheckDistance = 0.1f;` to `m_GroundCheckDistance = m_OrigGroundCheckDistance;`:

```
    void HandleGroundedMovement(bool crouch, bool jump)
    {
        // check whether conditions are right to allow a jump:
        if (jump && !crouch && m_Animator.GetCurrentAnimatorStateInfo(0).IsName("Grounded"))
        {
            // jump!
            m_Rigidbody.velocity = new Vector3(m_Rigidbody.velocity.x, m_JumpPower, m_Rigidbody.velocity.z);
            m_IsGrounded = false;
            m_Animator.applyRootMotion = false;
            m_GroundCheckDistance = m_OrigGroundCheckDistance;
        }
    }

```

**Whole Script:**

```
using UnityEngine;

namespace UnityStandardAssets.Characters.ThirdPerson
{
    [RequireComponent(typeof(Rigidbody))]
    [RequireComponent(typeof(CapsuleCollider))]
    [RequireComponent(typeof(Animator))]
    public class ThirdPersonCharacter : MonoBehaviour
    {
        [SerializeField] float m_MovingTurnSpeed = 360;
        [SerializeField] float m_StationaryTurnSpeed = 180;
        [SerializeField] float m_JumpPower = 12f;
        [Range(1f, 4f)][SerializeField] float m_GravityMultiplier = 2f;
        [SerializeField] float m_RunCycleLegOffset = 0.2f; //specific to the character in sample assets, will need to be modified to work with others
        [SerializeField] float m_MoveSpeedMultiplier = 1f;
        [SerializeField] float m_AnimSpeedMultiplier = 1f;
        [SerializeField] float m_GroundCheckDistance = 0.1f;

        Rigidbody m_Rigidbody;
        Animator m_Animator;
        bool m_IsGrounded;
        float m_OrigGroundCheckDistance;
        const float k_Half = 0.5f;
        float m_TurnAmount;
        float m_ForwardAmount;
        Vector3 m_GroundNormal;
        float m_CapsuleHeight;
        Vector3 m_CapsuleCenter;
        CapsuleCollider m_Capsule;
        bool m_Crouching;

        void Start()
        {
            m_Animator = GetComponent<Animator>();
            m_Rigidbody = GetComponent<Rigidbody>();
            m_Capsule = GetComponent<CapsuleCollider>();
            m_CapsuleHeight = m_Capsule.height;
            m_CapsuleCenter = m_Capsule.center;

            m_Rigidbody.constraints = RigidbodyConstraints.FreezeRotationX | RigidbodyConstraints.FreezeRotationY | RigidbodyConstraints.FreezeRotationZ;
            m_OrigGroundCheckDistance = m_GroundCheckDistance;
        }

        public void Move(Vector3 move, bool crouch, bool jump)
        {

            // convert the world relative moveInput vector into a local-relative
            // turn amount and forward amount required to head in the desired
            // direction.
            if (move.magnitude > 1f) move.Normalize();

            move = transform.InverseTransformDirection(move);
            CheckGroundStatus();
            move = Vector3.ProjectOnPlane(move, m_GroundNormal);
            m_TurnAmount = Mathf.Atan2(move.x, move.z);
            m_ForwardAmount = move.z;

            ApplyExtraTurnRotation();

            // control and velocity handling is different when grounded and airborne:
            if (m_IsGrounded) {
                HandleGroundedMovement(crouch, jump);
            } else {
                HandleAirborneMovement();
            }

            ScaleCapsuleForCrouching(crouch);
            PreventStandingInLowHeadroom();

            // send input and other state parameters to the animator
            UpdateAnimator(move);

        }

        void ScaleCapsuleForCrouching(bool crouch)
        {
            if (m_IsGrounded && crouch)
            {
                if (m_Crouching) return;
                m_Capsule.height = m_Capsule.height / 2f;
                m_Capsule.center = m_Capsule.center / 2f;
                m_Crouching = true;
            }
            else
            {
                Ray crouchRay = new Ray(m_Rigidbody.position + Vector3.up * m_Capsule.radius * k_Half, Vector3.up);
                float crouchRayLength = m_CapsuleHeight - m_Capsule.radius * k_Half;
                if (Physics.SphereCast(crouchRay, m_Capsule.radius * k_Half, crouchRayLength, Physics.AllLayers, QueryTriggerInteraction.Ignore))
                {
                    m_Crouching = true;
                    return;
                }
                m_Capsule.height = m_CapsuleHeight;
                m_Capsule.center = m_CapsuleCenter;
                m_Crouching = false;
            }
        }

        void PreventStandingInLowHeadroom()
        {
            // prevent standing up in crouch-only zones
            if (!m_Crouching)
            {
                Ray crouchRay = new Ray(m_Rigidbody.position + Vector3.up * m_Capsule.radius * k_Half, Vector3.up);
                float crouchRayLength = m_CapsuleHeight - m_Capsule.radius * k_Half;
                if (Physics.SphereCast(crouchRay, m_Capsule.radius * k_Half, crouchRayLength, Physics.AllLayers, QueryTriggerInteraction.Ignore))
                {
                    m_Crouching = true;
                }
            }
        }

        void UpdateAnimator(Vector3 move)
        {
            // update the animator parameters
            m_Animator.SetFloat("Forward", m_ForwardAmount, 0.1f, Time.deltaTime);
            m_Animator.SetFloat("Turn", m_TurnAmount, 0.1f, Time.deltaTime);
            m_Animator.SetBool("Crouch", m_Crouching);
            m_Animator.SetBool("OnGround", m_IsGrounded);
            if (!m_IsGrounded) {
                m_Animator.SetFloat("Jump", m_Rigidbody.velocity.y);
            }

            // calculate which leg is behind, so as to leave that leg trailing in the jump animation
            // (This code is reliant on the specific run cycle offset in our animations,
            // and assumes one leg passes the other at the normalized clip times of 0.0 and 0.5)
            float runCycle =
                Mathf.Repeat(m_Animator.GetCurrentAnimatorStateInfo(0).normalizedTime + m_RunCycleLegOffset, 1);

            float jumpLeg = (runCycle < k_Half ? 1 : -1) * m_ForwardAmount;
            if (m_IsGrounded) {
                m_Animator.SetFloat("JumpLeg", jumpLeg);
            }

            // the anim speed multiplier allows the overall speed of walking/running to be tweaked in the inspector,
            // which affects the movement speed because of the root motion.
            if (m_IsGrounded && move.magnitude > 0) {
                m_Animator.speed = m_AnimSpeedMultiplier;
            } else {
                // don't use that while airborne
                m_Animator.speed = 1;
            }
        }

        void HandleAirborneMovement()
        {
            // apply extra gravity from multiplier:
            Vector3 extraGravityForce = (Physics.gravity * m_GravityMultiplier) - Physics.gravity;
            m_Rigidbody.AddForce(extraGravityForce);

            //m_GroundCheckDistance = m_Rigidbody.velocity.y < 0 ? m_OrigGroundCheckDistance : 0.01f;
        }

        void HandleGroundedMovement(bool crouch, bool jump)
        {
            // check whether conditions are right to allow a jump:
            if (jump && !crouch && m_Animator.GetCurrentAnimatorStateInfo(0).IsName("Grounded"))
            {
                // jump!
                m_Rigidbody.velocity = new Vector3(m_Rigidbody.velocity.x, m_JumpPower, m_Rigidbody.velocity.z);
                m_IsGrounded = false;
                m_Animator.applyRootMotion = false;
                //m_GroundCheckDistance = 0.1f;
            }
        }

        void ApplyExtraTurnRotation()
        {
            // help the character turn faster (this is in addition to root rotation in the animation)
            float turnSpeed = Mathf.Lerp(m_StationaryTurnSpeed, m_MovingTurnSpeed, m_ForwardAmount);
            transform.Rotate(0, m_TurnAmount * turnSpeed * Time.deltaTime, 0);
        }

        public void OnAnimatorMove()
        {
            // we implement this function to override the default root motion.
            // this allows us to modify the positional speed before it's applied.
            if (m_IsGrounded && Time.deltaTime > 0)
            {
                Vector3 v = (m_Animator.deltaPosition * m_MoveSpeedMultiplier) / Time.deltaTime;

                // we preserve the existing y part of the current velocity.
                v.y = m_Rigidbody.velocity.y;
                m_Rigidbody.velocity = v;
            }
        }

        void CheckGroundStatus()
        {
            RaycastHit hitInfo;

#if UNITY_EDITOR
            // helper to visualise the ground check ray in the scene view

            Debug.DrawLine(
                m_Capsule.transform.position + m_Capsule.center + (Vector3.up * 0.1f),
                m_Capsule.transform.position + (Vector3.down * m_GroundCheckDistance),
                Color.red
            );

#endif
            // 0.1f is a small offset to start the ray from inside the character
            // it is also good to note that the transform position in the sample assets is at the base of the character
            bool condition = Physics.SphereCast(
                m_Capsule.transform.position + m_Capsule.center + (Vector3.up * 0.1f),
                m_Capsule.height / 2,
                Vector3.down,
                out hitInfo,
                m_GroundCheckDistance
            );

            if (condition) {
                m_IsGrounded = true;
                m_GroundNormal = hitInfo.normal;
                m_Animator.applyRootMotion = true;

            } else {
                m_IsGrounded = false;
                m_GroundNormal = Vector3.up;
                m_Animator.applyRootMotion = false;
            }
        }
    }
}

```

# Answer
> 1 votes
Why don't use Unity's OnCollisionStay function?

Pros:

* You don't have to create raycast.
* It's more accurate than raycast: Raycast is a shoot-to-check method, if your raycast shooting is not enough coverage, then it leads to bug which is the reason why you asked this question. `OnCollisionStay` method literally checks if something is touching - it perfectly fit for the purpose checking if the player is touching the ground (or anything that the player can land on).

For code and demo, check this answer: http://answers.unity.com/answers/1547919/view.html

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


# Question
Title: Getting dynamic objects to match baked lighting on nearby static objects
Here's how the hallway in my game looks now:

You might notice the dark section near the centre of the screen; This is, in fact, a pair of cupboard doors which are not set to static and so don't get included in the baked lighting.

The problem is, since all of my house lights are baked only, it looks like the only light these doors are getting is the ambient light - so quite dark.

Is there an alternative, best practise to ensure non-static objects get lit sufficiently when lighting is baked?

# Answer
> 1 votes
Basically Dynamic object doesn't include when baking lights. To solve this, Unity provides Light Probe Group, capture the light information passing through the empty space, will use to nearest dynamic objects.

---
Tags: unity, lighting
---


title: Walking around a sphere in Lumberyard

text:
# Question
Title: Walking around a sphere in Lumberyard
I am trying to create a simple game using Amazon Lumberyard and my goal is to have levels/stages where the player will be able to walk around a mini planet.

I have seen a lot of tutorials about this for Unity, but I find it hard to try to translate this into Lua.

My problem is trying to make the "Feet" of the character point towards the planet. Any help would be appreciated.

the script I got for unity is below,

Planet

```
public class PlanetScript : MonoBehaviour {

public float gravity = -12;

public void Attract(Transform playerTransform)
{
    Vector3 gravityUp = (playerTransform.position - transform.position).normalized;
    Vector3 localUp = playerTransform.up;

    playerTransform.GetComponent<Rigidbody>().AddForce(gravityUp * gravity);

    Quaternion targetRotation = Quaternion.FromToRotation(localUp, gravityUp) * playerTransform.rotation;
    playerTransform.rotation = Quaternion.Slerp(playerTransform.rotation, targetRotation, 50f * Time.deltaTime);
    }
}

```

and the player has

```
void FixedUpdate()
{
    if (attractorPlanet)
    {
        attractorPlanet.Attract(playerTransform);
    }
}

```

# Answer
> 0 votes
My Lua is pretty rusty but functionally there are several ways to do this. The easiest may be to set your characters rotation (Quaternion or Vector). If you create a new vector which is the result of playerPosition - planetPosition, you want to make this your players new Up Vector (I would normalize this vector).

You can either a) get the rotation of this vector and then set your players rotation vector. Or b) convert this vector to a quaternion and then setting your players rotation quaternion.

Quaternions are the best!

---
Tags: lua, lumberyard-engine
---


# Question
Title: Why game loop should be running on a separate thread?
I am struggling to fully understand the responsiveness argument suggesting to run the game loop on a separate thread other than main thread.

When OS sends a user event (touch, mouse move, etc.) it will be handled within the main thread. Then you would have to forward this event into a game loop thread where this event usually is placed into a queue. The OS may think that event was processed instantly, but user will still have to wait until event is actually processed.

In this case there is an inevitable latency before the event gets processed.

It is exactly the same latency when event is processed in the main thread, but in this case OS can detect the latency.

Is it this latency that separate thread game loop is trying to avoid, or is there anything else?

# Answer
> 3 votes
One important point - when you're using eg. DirectX, you really, really don't care about the main thread. Let it be as free as possible, it doesn't do anything. All the inputs and outputs are processed separately from the UI thread, so why tie them to it? That's only going your window to stop responding if your rendering / updating is too busy. Also, yes, multithreading is complicated. But that's not the case here - you don't want your threads to interact, so everything is fine - they don't access each other's resources, and they don't need to communicate save for a quit message :)

Let's explore Windows + DirectX more:

You usually want a fairly predictable update (/frame) rate. But at the same time, you want to process windows messages (that's the things like "move the window", "resize the window", "press Alt-F4"). Now, you want to process an incoming windows message as soon as possible. Why? Because they contain important things, like `WM_QUIT`. And Windows will report your application as "not responding" if you, well, don't respond to the windows messages.

Another important thing is that when you use `SendMessage` to send a windows message, you're blocking the sender, until you actually read the message. If you have WM processing tied to your game loop, this can mean many issues (since the update loop will usually take a lot of time to go through, say 16ms for a 60 FPS game, while WM processing is usually very much under-ms). If someone eg. sends key presses to your application (like some macro program), there's a big difference between receiving 100 WM\_CHAR messages in a row and taking 16 ms to process each one.

All that said, this is incredibly platform dependent. On Windows with DirectX, I'd advise to really separate the WM processing from the game itself. The only cases where you actually want them to be tied are those like "I want to resize the game window". Different platforms have different best behaviours and different constraints.

# Answer
> 1 votes
Main thread, (aka Render thread, UI thread) is actually actuator thread, which task is to take some situation and display it to user. In simple fulscreen\realtime\embedded cases (when you run game close to hardware - when you have linux kms or android) its just that. In more complicated cases like windows or xorg it also processes some window-related events, such as resize window\viewport or move it. Also frame rendering time relies on graphics\shader computational heaviness - more triangles in view and complex shaders results in frame rate drop and its variability. So its output, or consumer thread.

On other hand, when running game loop (aka physics loop, logic loop) you want to stick it to some precise fixed time marks, running at fixed rate to get predictable physics integration (ODE solver with fixed dt) and event sampling. It typically processes events like mouse/keyboard/network input, and timer input, and when timer events occurs it calculates next frame, predicts positions and velocities, and updates situation, which is then presented to renderer thread and sent over network. So it is "input and processing" or producer thread. Offloading and separating input from processing is usually hard to achieve task, resulting in greater latencies.

Generally, you want to run your logic thread at faster rates and fixed rates than render thread which may be slower and have variable jitter. Then you may easily apply lockless producer-consumer interthread synchronisation schemes, using triple buffering. Personally i recommend 120+ fixed fps logic thread (usb poll rate is 125 hz, and windows sheduler works best with 64 or 128 fps timers), and render thread can be 40+ fps for comfortable playing experiences and very low input lag.

---
Tags: architecture, game-loop, multithreading, events
---


title: Collision and changing the scene. C#

text:
# Question
Title: Collision and changing the scene. C#
I'm running into a problem where I want to create some code that such that if an object (Cube) is destroyed, it to changes to another scene.

Here is my code:

```
public class Move : MonoBehaviour {

    void playerWalk()
    {
        var x = Input.GetAxis("Horizontal") * Time.deltaTime * 150.0f;
        var z = Input.GetAxis("Vertical") * Time.deltaTime * 3.0f;

        transform.Rotate(0, x, 0);
        transform.Translate(0, 0, z);
    }

    void OnCollisionEnter(Collision col)
    {
        if (col.gameObject.name == "Cube")
            Destroy(col.gameObject);
    }

    void Update ()
    {
        playerWalk();
        if (Input.GetKeyDown(KeyCode.B))
            print("hello");
    }
}

```

What do do I need to do?

# Answer
You use `using UnityEngine.SceneManagement;` and the after the `Destroy(col.gameObject);` just put below `SceneManager.LoadScene("SceneName");`

```
if (col.gameObject.name == "Cube")
{
        Destroy(col.gameObject);
}
if(col.gameObject == null)
{
        SceneManager.LoadScene("SceneName");
}

```
> 1 votes

# Answer
Unity has a special set of methods for using *triggers* as an event to handle logic like this. You are 99% there, but instead of `OnCollisionEnter` use `OnTriggerEnter`, though in your collider on the object set the `IsTrigger` to true.

```
import Unity.SceneManagement;

public class Move : MonoBehaviour {

    void playerWalk()
    {
        var x = Input.GetAxis("Horizontal") * Time.deltaTime * 150.0f;
        var z = Input.GetAxis("Vertical") * Time.deltaTime * 3.0f;

        transform.Rotate(0, x, 0);
        transform.Translate(0, 0, z);
    }

    void OnTriggerEnter(Collider col)
    {
        if (col.gameObject.name == "Cube") {
            Destroy(col.gameObject);
            SceneManagemer.LoadScene("YourSceneName");
         }
    }

    void Update ()
    {
        playerWalk();
        if (Input.GetKeyDown(KeyCode.B))
            print("hello");
    }
}

```
> 1 votes

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


# Question
Title: Which fixed framerate should i choose for physics thread?
I am writing first-person shooter game with fast motion. I have a fixed high-frequency physics loop thread, which is separated from variable-frequency rendering thread. I need to choose the physics frequency, but I'm unsure which value to choose. I have 3 options with the following properties:

* 120 Hz:

+ Monitor support: 1:1 or 1:2 mapping to rendering thread refresh rate
    + Is divided by mains frequency in US, may be good for older CRTs there
* 125 Hz:

+ 8ms integer frame delta (if time is expressed in integer ms, in a games like Quake3)
    + Default USB poll rate for most consumer mices (why the hell is it so?!..)
* 128 Hz:

---

Which rate should i choose?

PS: Feel free to run my test code. If you are lucky Linux user, please share your port and your results, it may be interesting. On Windows: see how worse is 125hz jitter, compared to 128hz:

```
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>

#include <cstdint>
#include <vector>
#include <algorithm>
#include <numeric>
#include <iostream>

uint64_t qpf() {
    uint64_t hpF = 0;
    ::QueryPerformanceFrequency(reinterpret_cast<LARGE_INTEGER*>(&hpF));
    return hpF;
}

uint64_t qpc() {
    uint64_t hpC = 0;
    ::QueryPerformanceCounter(reinterpret_cast<LARGE_INTEGER*>(&hpC));
    return hpC;
}

// very precise (~1000x times), but would consume 100% cpu in absense of active threads.
void yield_active() {
    SwitchToThread();
}

// default precision is 15.625ms, but 1ms +-0.3ms if NtSetTimerResolution() was called
void yield_passive() {
    SleepEx(1, false);
}

// import ntdll stuff, this is the heart of Sleep()/SleepEx():
static int(__stdcall *NtDelayExecution)(BOOL Alertable, PLARGE_INTEGER DelayInterval) = (int(__stdcall*)(BOOL, PLARGE_INTEGER)) GetProcAddress(GetModuleHandleW(L"ntdll.dll"), "NtDelayExecution");

// 0.5ms +-0.3ms, 5000 us value is hardcoded into ntoskrnl, which is hard to change; i tried, attempt failed:
// https://superuser.com/questions/1326252/changing-windows-thread-sheduler-timeslice
// https://reverseengineering.stackexchange.com/questions/18384/ntoskrnl-checksum-mismatch/18387
void yield_passive_hp(const int64_t& delayInterval) {
    //delay.QuadPart = (milliseconds > 1) ? -10000LL * (milliseconds - 1) : -1LL;
    ::NtDelayExecution(false, (PLARGE_INTEGER)(&delayInterval));
}

// ensure that some moment defined by target timespamp had occured
uint64_t wait_stamp(uint64_t targetStamp) {
    uint64_t currentStamp;
    while ((currentStamp = qpc()) < targetStamp)
        //yield_active();
        yield_passive_hp(-1000); // yield_passive_hp(-1000); asking to wait for 100us or 0.1ms, implementation would wait for at least 0.5ms
        //yield_passive();
    return currentStamp;
}

template< typename T >
T series_mean(const std::vector< T >& vSeries) {
    auto lagSum = std::accumulate(vSeries.begin(), vSeries.end(), T(0));
    return lagSum / vSeries.size();
}

template< typename T >
T std_deviation(const std::vector< T >& vSeries, const T& lagMean = 0) {
    std::vector<T> vSqrDiff(vSeries.size());
    std::transform(vSeries.begin(), vSeries.end(), vSqrDiff.begin(), [lagMean](const T& x) { return x - lagMean; });
    double varianceSum = std::inner_product(vSqrDiff.begin(), vSqrDiff.end(), vSqrDiff.begin(), T(0));
    return std::sqrt(varianceSum / vSeries.size());
}

int main() {
    double benchmarkTime = 1.0; // run game loop for 1.0 second
    double fixedFPS = 128.0; // try to stick as close as possible to 1/128th timeslices
    auto hpF = qpf();
    auto fixedDelta = 1.0 / fixedFPS;
    auto numTicks = static_cast< uint64_t >( benchmarkTime * fixedFPS );
    std::vector< double > vLags;
    vLags.reserve(numTicks);
    auto startStamp = qpc();
    uint64_t frameNumber = 0;
    do {
        auto stampDelta = static_cast<uint64_t>(static_cast<double>(hpF * frameNumber++) * fixedDelta);
        auto targetStamp = startStamp + stampDelta;
        auto actualStamp = wait_stamp(targetStamp);
        auto lastDelta = static_cast<double>(actualStamp - targetStamp) / hpF;
        vLags.emplace_back(lastDelta);
    } while (frameNumber < numTicks);

    auto lagMean = series_mean(vLags);
    auto lagDeviation = std_deviation(vLags, lagMean);
    std::cout << "lagMean=" << lagMean * 1000 << " ms; lagDeviation=" << lagDeviation * 1000 << " ms;\n";
    return 0;
}

```

# Answer
I recommend 240Hz or 480Hz for physics.

It seems a bit much, but modern processors, even on mobile, are fast enough to run simple physics at this rate.

Using a timestep this small has the advantage of not having to interpolate frames to match your display rate. You can just just the nearest integer number of steps, and ignore the remainder.

Alternatively, you can follow Gaffer-on-Games approach and do that interpolation, but it requires a lot of book keeping, as you need to keep the state from old frames around, leading to overly complex code.
> 1 votes

# Answer
After playing a bit, i have figured out that **best platform** for implementing unified low-latency event loop for games **is Linux**. That is because it have `nanosleep` or `timerfd` mechanisms to do precise blocking wait, while still be able to perfectly produce up to 10000 fps loops. Windows OS is usually limited to 500-1000 fps loops with worse precision. Using at least one `nanosleep()` call the precision starts to getting worse after 8-10k fps mark, but still remains good(by heavily increasing cpu usage) with timerfd mechanism. So, its 8-10 times more precise than Windows version.

Using `timerfd` with `epoll_wait()` is great, because it also could multiplex network and evdev descriptor events in one event loop, unifying it and taking it much closer to soft realtime, than any other general-purpose OS.

Answering framerate question, I think that 128 or 256 fps would be best guess for almost any game, allowing for fast lockless inter-thread producer-consumer syncronization between *event&physics* loop and *render* loop, using triple buffering scheme. Producer have to run faster than consumer for best effects.

PS: Game loop lag&jitter benchmarking code, that i come to:

```
// LINUX
#include <sys/epoll.h>
#include <sys/timerfd.h>
#include <unistd.h>

#include <cstdint>
#include <cstring>
#include <cmath>
#include <vector>
#include <algorithm>
#include <numeric>
#include <iostream>
#include <stdexcept>

template< typename T >
T series_mean(const std::vector< T >& vSeries) {
    auto lagSum = std::accumulate(vSeries.begin(), vSeries.end(), T(0));
    return lagSum / vSeries.size();
}

template< typename T >
T std_deviation(const std::vector< T >& vSeries, const T& lagMean = 0) {
    std::vector<T> vSqrDiff(vSeries.size());
    std::transform(vSeries.begin(), vSeries.end(), vSqrDiff.begin(), [lagMean](const T& x) { return x - lagMean; });
    double varianceSum = std::inner_product(vSqrDiff.begin(), vSqrDiff.end(), vSqrDiff.begin(), T(0));
    return std::sqrt(varianceSum / vSeries.size());
}

uint64_t qpf() {
    return 1000000000ULL;
}

uint64_t qpc() {
    struct timespec currts;
    clock_gettime(CLOCK_MONOTONIC, &currts);
    return static_cast< uint64_t >(currts.tv_sec) * qpf() + static_cast< uint64_t >(currts.tv_nsec);
}

void s2ts(struct timespec& destTS, uint64_t srcStamp) {
    destTS.tv_sec = srcStamp / qpf();
    destTS.tv_nsec = srcStamp % qpf();
}

int main() {
    int tfd, epfd = 0;
    try {

        struct itimerspec ts;
        tfd = timerfd_create(CLOCK_MONOTONIC, 0);
        if (tfd == -1)
            throw std::runtime_error("timerfd_create()");
        epfd = epoll_create(1);
        if (epfd == -1)
            throw std::runtime_error("epoll_create()");
        struct epoll_event ev;
        memset(&ev, 0, sizeof(ev));
        ev.events = EPOLLIN;
        if (epoll_ctl(epfd, EPOLL_CTL_ADD, tfd, &ev) == -1)
            throw std::runtime_error("epoll_ctl(EPOLL_CTL_ADD)");

        double benchmarkTime = 1.0; // run game loop for 1.0 second
        double fixedFPS = 256.0; // try to stick as close as possible to timeslices
        auto fixedDelta = 1.0 / fixedFPS;
        auto numTicks = static_cast< uint64_t >( benchmarkTime * fixedFPS );
        std::vector< double > vLags;
        vLags.reserve(numTicks);

        uint64_t frameNumber = 0;
        auto hpF = qpf();
        auto startStamp = qpc();
        do {
                auto stampDelta = static_cast<uint64_t>(static_cast<double>(hpF * frameNumber++) * fixedDelta);
                auto targetStamp = startStamp + stampDelta;

            struct itimerspec ts;
            ts.it_interval.tv_sec = 0;
            ts.it_interval.tv_nsec = 0;
            s2ts(ts.it_value, targetStamp);

            auto ret = timerfd_settime(tfd, TFD_TIMER_ABSTIME, &ts, NULL);
            if(ret < 0 )
                throw std::runtime_error("timerfd_settime()");
            memset(&ev, 0, sizeof(ev));
            ret = epoll_wait(epfd, &ev, 1, 500); // wait up to 500ms for timer
            if (ret < 0)
                throw std::runtime_error("epoll_wait()");
            uint64_t res = 0;
            ret = read(tfd, &res, sizeof(res)); // reads number of expirations
                auto actualStamp = qpc(); //wait_stamp(targetStamp);
                auto lastDelta = static_cast<double>(actualStamp - targetStamp) / hpF;
                vLags.emplace_back(lastDelta);
        } while (frameNumber < numTicks);
        auto endStamp = qpc();
        auto testDelta = static_cast<double>(endStamp - startStamp) / hpF;
        std::cout << "test time is" << testDelta << "s\n";
        auto lagMean = series_mean(vLags);
        auto lagDeviation = std_deviation(vLags, lagMean);
        std::cout << "lagMean=" << lagMean * 1000 << " ms; lagDeviation=" << lagDeviation * 1000 << " ms;\n";
        return 0;

    }
    catch(const std::exception& eWhat) {
        std::cout << eWhat.what() << " exception: errno=" << errno;
        close(epfd);
        close(tfd);
        return EXIT_FAILURE;
    }
    return 0;
}

```

PPS. If you are interested, as for drawing thread, i've found excellent kmscube example and libevdev, that shows how to get rid of unwanted X.Org stuff, which can be useful when implementing lowest-latency and highest performance gaming engine in the world :-)
> 0 votes

---
Tags: physics, architecture, first-person-shooter
---


# Question
Title: Are there any branching dialogue editors (preferably for Mac)?
I'm currently looking for a branching dialogue editor that allows me to prepare all the dialogue, export it into an XML format that then can be parsed by Unity 3D.

The only editor I found until now is Chat Mapper, which is Win only. Is there something similar for Mac?

Even if there is nothing for the Mac – what would be other alternatives to Chat Mapper, if any?

# Answer
Have you considered using a mind mapping utility to help you flesh out your conversation branches? There are plenty of free and paid ones for mac

Most conversation builders seem to be tightly coupled to a specific game development engine, and there doesn't seem to be (m)any free standing alternatives.

Since you're looking at using Unity, look for existing Unity conversation makers, such as ConversationMaker and Conversation Engine.
> 2 votes

# Answer
You can try inky by inkle studios, creators of 80 days around the world. It is very simple but let’s you build complex branching conversations.

There is Unity integration as well.
> 1 votes

---
Tags: editors, macos
---


# Question
Title: How do I prevent repeated interactions between two game objects?
I am making a game where a player will jump into another object called land and everytime the player lands or collides with it, a score will be given, now my problems is that my method has a loophole since for every collision a score will be given therefore if a player jumps on the same land everytime score would be added up. What are the ways of assigning attributes to the object in order to prevent the loophole from happening? Can *ScriptableObject* be used to solve this issue?

This is my code for spawning object

```
foreach (var currobj in currentObject) {
         float objectYpos = -7.14f;
         Vector3 objectPos = currobj.transform.position;
         newObjPos.y = objectYpos;
         newObjPos.x = currobj.transform.position.x;

         objectPos = Vector3.Lerp(objectPos, newObjPos, 6f * Time.deltaTime);
         currobj.transform.position = objectPos;

         if (currobj.transform.position.x < playerLocation.x - objectoffsetX) {
             rmbObjects.Add(currobj);
         }
     }
     foreach (var rmv in rmbObjects) {
         currentObject.Remove(rmv);
         Destroy(rmv);
     }
 }

 private void ObjectSpawn() {
     playerLocation = playerObject.transform.position;
     spawnLocX = Random.Range(playerLocation.x + offsetSpawnX, playerLocation.x + maxdistance);
     GameObject spawned = (GameObject)Instantiate(objectList[indexLevel]);
     spawned.transform.position = new Vector2(spawnLocX, 9); //spawn object in out of view
     currentObject.Add(spawned);
 }

```

My code for adding score

```
 private void OnCollisionEnter2D(Collision2D collision)
 {

    if (collision.gameObject.tag == "land" && !onGround)
    {
        scoreManager.AddScore(2);
    }
 }

```

# Answer
> 1 votes
The ScriptableObject is likely not what you are looking for here. You usually use it when you need a custom type of asset for your game which live in your project folder and which can be assigned to variables of game objects.

You could add a MonoBehaviour to your Land game object which handles the land collision mechanic and simply removes itself from the game object after the player collided with it.

```
public class Land : MonoBehaviour {

    void OnCollisionEnter(Collision collision) {
         if (collision.gameObject.CompareTag("Player")) {
                 // do what needs to be done
                 scoreManager.AddScore(2);
                 // remove this script from the game object
                 Destroy(this);
         }
    }
}

```

This would make sure every land can only award points once, unless you re-add the Land behaviour with AddComponent.

Note that OnCollisionEnter will only get triggered when both the Land and the Player have a Rigidbody (which you want to set to "is Kinematic" if you don't want lands to be affected by physical forces) or if the Land is set to static and the player has a Rigidbody. See the Unity collision matrix for details.

---
Tags: unity, gameobject
---


# Question
Title: Networked projectiles in an authoritative server
I'm working on a multiplayer game, and I've implemented a simple enough player prediction (according to this great article) - which works well enough.

What isn't discussed there, and my question here; is how do I handle non-raycast projectiles (like missiles for example)?

There is RTT between the player pressing fire to the time he receives back the server's "confirmation", and then all other players add their latency to the mix.

And of course there is the issue of actually rendering hits; what if I see my missile hit someone in my simulation while he wasn't even there on the server and the missile missed him completely?

So my question is, what is the best way to hide latency for all players in (relatively) slow moving projectiles in an authoritative server?

# Answer
> 6 votes
This is what we ended up doing:

## Client side

1. Detect player clicks button to shot missile
2. Immediatley simulate rocket visuals on client
3. In parallel, send command to server
4. Once predict hit something, destroy missile (no explosion)

## Server Side

1. Receive fire command
2. Save client ping data on missile
3. Fire missile, each frame accelerating the missile until we've caught up with the lag delta (but without rewind replay)
4. On explosion, send both explosion FX + damage result

It works very well most of the time (around 99.9% of the time)

---
Tags: networking, multiplayer, client-server, first-person-shooter
---


# Question
Title: How to make an expanding radial search in Unity?
I am currently working on a City Builder Game and I often come across the problem of having to decide wich location to use.

Examples:

* *The citizen has a job and needs a home. There are several buildings with open slots.*
* *The citizen is at a positon and is hungry. There are several restaurants on the map.*

How can I choose the right building to go to? I don't really wan't to check the distance for each, because there could potentially be hundreds of buildings and that decision problem occurs quite often.

I also don't care for the optimal solution, any nearby result is fine.

Currently all buildings register them self in a LinkedList. When searching for something I'd start at the beginning and the first occurrence that was 'good enough' would be returned. Citizen now drive across the map for something that was right next to them if the one far away was built earlier in the game.

Any suggestions?

# Answer
> 1 votes
The comments suggesting spatial partitioning are a decent choice, but the easiest solution would be to put different building types in different collision layers. Then just incrementally use something like `Physics.OverlapSphere(...)` or grow a spherical trigger.

You can the sort the results, or just choose the first one within an acceptable distance threshold

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


# Question
Title: Why does my OnTriggerStay method throw a NullPointerException when I access the collider's attachedRigidbody?
I set the trigger

```
 void OnTriggerStay(Collider other)
{

    other.attachedRigidbody.AddForce(Vector3.up * 100, ForceMode.Impulse);

}

```

But when player walks on, I got console warning

```
    NullReferenceException: Object reference not set to an instance of an object

```

I have set Rigidbody on the player.

How to make player be affected by trigger ?

# Answer
> 0 votes
Note that `OnTriggerStay` triggers when *any* game object with a collider (on one of the physics layers which collide with that of this object) collides with the object. You might be registering a collision with something other than the player. So you should check if the object you are colliding with is actually the player. A good way to do this is to set the tag of your player object to "Player" and then check for that tag in the collision method:

```
void OnTriggerStay(Collider other)
{
    if (other.gameObject.tag == "Player")
    {
        other.attachedRigidbody.AddForce(Vector3.up * 100, ForceMode.Impulse);
    }
}

```

When you still get that error instead of the expected results, then the most likely explanation is that you think you added a rigidbody to your player, but you actually didn't. In that case please edit the question with some screenshots which show how your player object looks in the inspector.

---
Tags: unity, physics, rigidbody
---


# Question
Title: How do I get the GUI to draw above the kinematic bodies when their z_index is changed?
Currently the Labels in the GUI are below the player and other objects, so the player appears above them. How can this be fixed?

```
extends Node
var load_1 = true

    onready var level = preload("res://scenes/levels/Level.tscn")

    var Level = null

    func _ready():
        Level = level.instance()

        add_child(Level)
        move_child(Level, 0)
        VisualServer.canvas_item_set_z_index($GUI/Label3, 4000)
        print("I'm here")

    func _process(delta):
        getallnodes(self)
        pass

    func set_z_index(node):
        for N in node.get_children():
            if N.get_class() == "KinematicBody2D":
                N.z_index = N.position.y

    func getallnodes(node):
        for N in node.get_children():
            if N.get_child_count() > 0 and N.get_class() != "RigidBody2D" and N.get_class() != "KinematicBody2D" and N.get_class() != "StaticBody2D":
                getallnodes(N)
            else:

                if N.get_class() == "KinematicBody2D" or N.get_class() == "RigidBody2D":
                    setZOrder_kine(N)
                    print("- "+N.get_name())
                if N.get_class() == "StaticBody2D":
                    setZOrder_kine(N)
                    print("- "+N.get_name())
                elif N.get_class() == "Sprite":
                    setZOrder(N)
                    print("- "+N.get_name())

    func setZOrder_kine(node):
        for N in node.get_children():
            if N.get_class() == "Sprite":
                var myPos = N.get_global_transform().get_origin()
                var mySize = N.get_texture().get_height()
                var bottomOfSprite = (mySize*N.get_scale().y * N.get_parent().get_scale().y)/(2 * N.vframes)
                N.get_parent().z_index = (myPos.y+bottomOfSprite)

    func setZOrder(N):
        var myPos = N.get_global_transform().get_origin()
        var mySize = N.get_texture().get_height()
        var bottomOfSprite = (mySize*N.get_scale().y)/(2 * N.vframes)
        N.z_index = (myPos.y+bottomOfSprite)

    func _physics_process(delta):

        if(Level.get_node("Player")):

            $GUI/Label.text = "Velocity: " + str(Level.get_node("Player").velocity.length()) + ", " + str(Level.get_node("Player").velocity.x) + ", " + str( Level.get_node("Player").velocity.y)
            $GUI/Label2.text = "Position: " + str(Level.get_node("Player").position.x) + ", " + str(Level.get_node("Player").position.y) + ", " + str(Level.get_node("Player").z_index)
            $GUI/Label3.text = "Sword: " + "rotation " + str(Level.get_node("Player").rotation)
            $GUI/Label4.text = "stamina" + str(Level.get_node("Player").stam.current) + "attack_charge: " + str(Level.get_node("Player").stab.charge.current) + "countdown: " + str(Level.get_node("Player").stab_countdown[0]) + "cooldown: " + str(Level.get_node("Player").stab_cooldown[0])

```

# Answer
> 4 votes
Godot has Canvas Layers to solve this kind of problem.

They can provide high level control by keeping game elements on separate layers and managing which layers will be drawn in which order. Then within each individual canvas layer by node order or z-index can be managed as usual.

There is a handy tutorial in the official documentation that uses the following example:

* Parallax background
* Level foreground
* Heads Up Display

# Answer
> 1 votes
Well I've got an answer, create a node2d child node set its z index higher than all of the level's objects then make the GUI a child of the node2d. This well set it higher than the level objects.

---
Tags: godot
---


# Question
Title: How to represent a modular FSM for AI using ECS?
I am considering to implement AI using ECS which actually contradicts working with naive FSMs. My current idea is to have multiple components which represent the particular state an Entity that has a `AIControllerComponent` is currently in.

Let's say an enemy starts out with the mentioned `AIControllerComponent` as well as a `EnemyIdleComponent`. Now an `EnemyIdleSystem` would handle all those idle enemies and if it happens that a player comes too close it'd replace the `EnemyIdleComponent` with an `EnemyChasePlayerComponent` leaving the handling of this to `EnemyChasePlayerSystem`.

This approach is rather generic and I would basically end up with a bunch of enemies that have the very same behaviour. I was curious to know how I should combine this approach with some more modular states. At first I thought about adding an enum variable to `AIControllerComponent` which holds the type of the enemy but I can't really think of a decent solution to call different implementations inside of the `EnemyFooSystem`s based on that particular enum value. Do you have any suggestions?

// EDIT: I am using pure ECS patterns and Jobs, as such `MonoBehaviour`s and non-blittable types inside of `IComponentData` are not usable.

# Answer
I recommend you the chapter on State-Driven Agent Design in **Programming AI by Example, By Matt Buckland**, since a general approach of Finite State Machines is shown there. It proposes a singleton generic FiniteStateMachine System, which handles the state updating and transitions of all the agents. The states, by the way they are designed (generally and in the book) are also of the kind of singleton classes, but you could make it Component-wise, so they have their reference to their own agents, so you can handle each agent separately (not applied on my example, but it would be just a matter to add a reference to their Agents, and delete the agent parameter on their methods).

Here is a very generic example, the ECS would be separated by Agents (Entitites), States (Components) and a Finite State Machine per Agent Type (System):

```
/// Entity
public abstract class FSMAgent<T> : MonoBehaviour where T : MonoBehaviour
{
    public StateComponent<T> currentState, previousState;

    private void Update()
    {
        FiniteStateMachine<T>.UpdateState(this);
    }
}

/// Component
public abstract class StateComponent<T> where T : FSMAgent<T>
{
    /// I put it virtual, since maybe there'd be transition actions that you'd like to avoid in certain states.
    public virtual void Exit(T agent) { /*...*/ }
    public virtual void Enter(T agent) { /*...*/ }
    public virtual void Execute(T agent) { /*...*/ }
}

/// System
public class FiniteStateMachine<T> where T : FSMAgent<T>
{
    public static void ChangeState(T agent, StateComponent<T> state)
    {
        /// Store and execute exit of actual state. Execute new state's entrance.
        if(agent.currentState != null)
        {
            agent.previousState = agent.currentState;
            agent.previousState.Exit(agent);
        }
        agent.currentState = state;
        agent.currentState.Enter(agent);
    }

    public static void UpdateState(T agent)
    {
        /// Execute state and check for conditions and transitions...
        if(agent.currentState != null) agent.currentState.Execute(agent);
    }
}

```

So you just have to define classes that inherit from the base, I'll take the example with Halo's Agents, since I read "Brutes" on another answer:

```
public class Grunt : FSMAgent<Grunt> { /*...*/ }
public class Elite: FSMAgent<Elite> { /*...*/ }
public class Jackal : FSMAgent<Jackal> { /*...*/ }

public class GruntIdle : StateComponent<Grunt> { /*...*/ }
public class EliteIdle : StateComponent<Elite> { /*...*/ }
public class JackalIdle : StateComponent<Jackal> { /*...*/ }

/// And so on...

```

And they just would call the static reference of the Finite State Machine of their own kind.

Hope it helps.
> 1 votes

# Answer
I dont really understand, why you would want several components with their own system. You basically just need one `BehaviourComponent`, whice either has only data (System works on Components) or also has functions (System calls Components functions), depending on your liking.

Just to make it clear, i got no idea of unity. And in my following explanation i assume you only use components with data.

Lets assume you have 3 types of enemies with equivalent equipment:

* Brutes that charge and attack your Character in Close Combat. They wont block or retreat
* Balanced enemies that approach you carefully, block and attack you mostly the same time. if Hurt, they may retreat
* anxious enemies that wont approach you, mostly block and may flee if a friend gets hurt or even dies

There three enemy types are basicly the same except for their behavior.

Now, for the sake of it, lets assume they each have three states in their fsm: idle, aware and hurt. On creating an enemy, you set the `BehaviourComponent`with behavior pattern. In Idle, the brute may actively search for an enemy, called `Search`, when he found an enemy, he is `Attacking`and when hurt he is still `Attacking`. Each of these Actions you implement as Enums.

```
enum Action {Search, Attack}

```

Now every state needs to know, when to transition to another state. You could do something like simple events.

enum Event {FoundCharacter, GotHurt}

So. how to implement this? For every state you have you could implement a struct (if you are using something like c#).

```
public struct State{
    public Action
    public Event
}

```

This would be the most simple case. On initiating your `BehaviourComponent` you create to states `Idle` and `Aware`. For `Idle` set `Action` to `Search` and `Event` to `FoundEnemy`, for `Aware` set `Action` to `Attack` and leave `Event` just empty, as he fights to the death. Your `BehaviourComponent` would then have a starting state, e.g. `Idle` and the information to go from one state to another.

Your `BehaviourSystem` then iterates over the `BehaviourComponent`, checks if an event occures and in case switches the state, then if follows the set `Action`.

To make it a bit more difficult, our balanced enemy tries to attack and block when in `State` of `Aware`. For that you could set several actions, like in an array or another struct to give them probabilities.

Your anxious guard may also have several states. When switching from `Idle` he might go to `Aware` or directly to `Run` or something else. This would be the same like several different actions.

The best with this approach is, your `BehaviourSystem` only needs to know what to do on different Actions, as the switch of states is 'sort of' implemented in the `BehaviourComponent`.

If you want it even more complex, you would need something like a script language, to load the 'BehaviourComponents' for each enemy type and maybe even for every `Action`, so you dont even have to implement them in the system. This could be loaded at runtime every time you would need it.
> 0 votes

---
Tags: unity, ai, entity-system, state
---


# Question
Title: (Unity) what happens if i get a transform.position of a nested object
Okay so here is the example

You have a plane at position `0,0,0` with a scale `15,1,15` (for demonstration)

Now you have a parent object for the sake of simplicity lets call it `parentObject` this parent object has the following position: `7,25,26` The parent **DOES NOT** have a mesh and is thereby an empty `gameobject`

The parent has a `child` `gameobject` **Here the issue starts** the `child` has a transform position at `5,-25,30` however this objects `transform.position` is relative to the parent

last take our `agent` i know set him to go to `childObject.transform.position` will he then move correctly to the object or will he, in fact, move to the position that is relative to the `parent` object?

I know this might seem a bit messy but the general question is if i tell an agent to go to a gameobject that is a child of another object using `transform.position` will he go to the place we would expect?

# Answer
> 1 votes
`transform.position` returns the position of an object in world-space coordinates, as in, where the object is in relation to the centre of the world. So basically, it "adds up" all transformations (including position) from all of its parents, to find out its final position.

`transform.localPosition` gives the local position of the object, as in, where the object is in relation to its parent (The value you see in the inspector).

So if `my_obj.position` returns `(0, 0, 0)` that means `my_obj` is located at the centre of the world. If `my_obj.localPosition` returns `(0, 0, 0)`, then `my_obj` is located on the exact same location of its parent.

When moving objects around, if you use `transform.position` would give expected results, `NavMeshAgent`s in Unity expect world-space coordinates, unless otherwise specified in the documentation.

---
Tags: unity, navmesh
---


# Question
Title: AABB test does not consistently detect edge-to-edge contact when bounds are very different in size
My function compares two AABBs for collision detection, and when they are around the same size it works fine, but I noticed that if I greatly decreased the size of one of them (or augmented the size of the other), then the collision wouldn't be detected correctly; I would have to have them intersect for a collision to be registered, rather than having it register when they are at least in direct contact, which is the intended behavior.

Below is my code:

```
local function DetectCollision(a, b) -- AABB to AABB
  local collisionX = (a.Position.X + a.Size.X) >= b.Position.X and (b.Position.X + b.Size.X) >= a.Position.X
  local collisionY = (a.Position.Y + a.Size.Y) >= b.Position.Y and (b.Position.Y + b.Size.Y) >= a.Position.Y
  local collisionZ = (a.Position.Z + a.Size.Z) >= b.Position.Z and (b.Position.Z + b.Size.Z) >= a.Position.Z
  return collisionX and collisionY and collisionZ
end

```

---

To be more specific, the issues start to occur when I cut the size of one of the AABBs in half. For instance, if I had two cubes where one's size is 12 on all axes and the other is 6 on all axes, then the collision will not register. Upon debugging, I noticed that only one of the collision bools will become false. This seems to depend on what axis the smaller bounding box moves from in relation to the bigger one, so if I moved the smaller AABB away from the bigger one on the y-axis, then collisionY will be false.

# Answer
This sounds like floating point precision error when testing for exact equality.

Let's model this in decimal to make it easier to read. Let's say we're using a decimal floating point format with room for 4 digits.

We place our cube B so its left edge is at -9.008.

Next we place our cube A, 10 units in size, so that its right edge just touches B, meaning its left edge is at -19.008. This takes 5 significant digits to represent though, so our number format will round it to the closest value representable with 4 digits, -19.01.

Now when we try to do our collision test:

```
positionA + sizeA >= positionB ?
-19.01 + 10 = -9.010 < -9.008

```

We fail the \>= test, because the rounded sum is less than what we'd have gotten if we could store the position with perfect precision throughout.

Note that this is actually the correct result if we take the positions stored in the variables to be the "ground truth" — it's true that a size-10 cube at -19.01 doesn't collide with one at -9.008, so the floating point math & collision check is giving us the right answer, it's just that we asked it about a different position than we meant to.

By arranging the math this way, we effectively said that the position is accurate and un-rounded, and can be trusted to have full precision as-is. But that's not the general case — most places our objects end up will not be exactly representable as floating point numbers, and we'll be rounding all the time. So we can build some awareness of rounding into the way we structure our test.

One way we can tame floating point rounding is to avoid summing wildly different values (like repeatedly adding a tiny frame delta time to a large total time counter).

Here, position and size measure very different things, and I could have a size-1 cube located at position 10000, or a size-100 cube located at 0.00001, huge gulfs in magnitude. So their sum or difference won't necessarily reflect the precision of either.

But two objects that collide will usually be close-ish together, so we can trust their positions to be in similar ranges of magnitude, and the difference between them will tell us something about the precision we have in that neighborhood. By subtracting one position from the other, we get an offset that more accurately represents the position precision we actually have available in the numeric range where our collision is occurring.

So we can rearrange our test like so:

```
 offset = b.Position - a.Position

 if( offset.x <= a.sizeX and offset.x >= -b.sizeX)
 ...(etc)

```

Using this form, our comparison looks like:

```
 offset = -9.008 - (-19.01)
 offset = 10.002
 (rounds to)
 offset = 10

 offset <= size
 10  <= 10
 passes the test!

```

This version of the collision test gets a little extra tolerance zone for rounding as we move further from the origin, to account for the fact that exact kissing contacts might not be representable numbers in those ranges.

Of course, we don't want to push this so far that this extra "collision skin thickness" becomes visible to the player, so you'll usually want to keep your physics happening no more than a few thousand units from the origin of your physics world, and re-position that origin as needed to avoid truly huge offsets that sacrifice too much precision for magnitude.
> 2 votes

---
Tags: collision-detection, mathematics, lua, aabb
---


# Question
Title: Trigger the button's onclick after checking that the cursor has been on it for some time
I would like to have the mouse hover/click the button for a fixed amount of time (5 seconds) before triggering the `onclick` method, it can click only after they have hovered for a certain amount of time on one button. I'm using it with the leap motion UI and EventSystem to prevent clicking a button by accident when passing the hand over it. I tried using the highlight animation and then triggering the event after it but i can't check if the hand has passed through another button and then got back to the previous one.

# Answer
> 1 votes
Use an IPointerEnterHandler/IPointerExitHandler component.

I wasn’t sure from your question if you wanted it to automatically perform the click action after hovering, or only allow them to click after they have hovered for certain amount of time. This example automatically performs the button click action after five seconds of hovering.

```
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

public class HoverClick : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler
{
    public float ClickDelay = 5;
    //Detect if the Cursor starts to pass over the GameObject
    public void OnPointerEnter(PointerEventData pointerEventData)
    {
        Invoke("doClick", ClickDelay)(
    }

    //Detect when Cursor leaves the GameObject
    public void OnPointerExit(PointerEventData pointerEventData)
    {
        CancelInvoke("doClick");
    }

    public void doClick() {
        GetComponent<Button>().onClick.Invoke();
    }
}

```

---
Tags: unity, gui
---


# Question
Title: How can I detect that the mouse is over a button so that I can display some UI text?
I have a scene, where a panel containing 24 buttons. I need to show some piece of text when hover a mouse cursor over the button. For example, for detecting clicks, I'm using onClick event trigger, but I can't find anything related to something like a onHover event. I have Googled and read the docs, but could not find anything. Can anybody help me with that?

Code:

```
var button = panel.GetChild(0).GetComponent<Button>();

```

# Answer
> 1 votes
> For example, for detecting clicks, I'm using onClick event trigger, but I can't find anything related to something like a onHover event

Due to that piece of your question, I assume that what you want to find out is how to detect mouse hovering over UI Buttons in Unity (version above 4.6). To do that, you do the following:

1. Select the desired UI Button
2. Scroll down the inspector and click the "Add Component" button
3. In the list of components that will appear, select "Event" and then "Event Trigger"
4. You will notice that a new "Event Trigger" area appears in the inspector for the button
5. There, click on the "Add new even type" button
6. A list of even types will pop-up. Choose "PointerEnter"
7. Next, on the "PointerEnter" sub-area that will appear within the "Event Trigger" area in the inspector (when your button is selected, of course), click on '+' to add a new item to the list of events
8. from here on, you just do the same as if you were playing with OnClick events in the inspector, i.e. you just select the object containing the function you want to run when the button is hovered. Then, you select that function.

If you have a lot of buttons and want to automate the process, you can achieve that via script: for each of your buttons you do something like the following (I have not been able to test this myself, unfortunately):

```
    EventTrigger.Entry eventtype = new EventTrigger.Entry();
    eventtype.eventID = EventTriggerType.PointerEnter;
    eventtype.callback.AddListener((eventData) => { YourDesiredFunction(); });

    GameObject newbutton;
    newbutton.AddComponent<Button>();
    newbutton.AddComponent<EventTrigger>();
    newbutton.GetComponent<EventTrigger>().triggers.Add(eventtype);

```

# Answer
> 1 votes
You can also use `IPointerEnterHandler` and `IPointerExitHandler` to detect when the mouse cursor is hovering over a button.

Below is some sample code from the Unity documentation for `IPointerEnterHandler`

```
//Attach this script to the GameObject you would like to have mouse hovering detected on
//This script outputs a message to the Console when the mouse pointer is currently detected hovering over the GameObject and also when the pointer leaves.

using UnityEngine;
using UnityEngine.EventSystems;

public class Example : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler
{
    //Detect if the Cursor starts to pass over the GameObject
    public void OnPointerEnter(PointerEventData pointerEventData)
    {
        //Output to console the GameObject's name and the following message
        Debug.Log("Cursor Entering " + name + " GameObject");
    }

    //Detect when Cursor leaves the GameObject
    public void OnPointerExit(PointerEventData pointerEventData)
    {
        //Output the following message with the GameObject's name
        Debug.Log("Cursor Exiting " + name + " GameObject");
    }
}

```

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


# Question
Title: How can I add acceleration to the movement of an object in a game
Below is the code that I'm using to move an object:

```
let XX = 0
let YY = 0
let maxSpeed = 100;

if(keyDown.w) {
    XX += Math.sin(angle*Math.PI/180)*moveSpeed;
    YY += -Math.cos(angle*Math.PI/180)*moveSpeed;
}

```

I'm trying to implement acceleration in moving. How can I do that?

# Answer
Acceleration is a change in speed over time, so you can implement it by incrementing your movespeed over time.

```
movespeed += acceleration_constant;

```

If you want to limit speed, then you can clamp it like this:

```
movespeed += acceleration_constant;
movespeed = (movespeed < maxSpeed) ? movespeed : maxSpeed;
movespeed = (movespeed > minSpeed) ? movespeed : minSpeed;

```
> 0 votes

---
Tags: mathematics, javascript, linear-algebra, kinematic
---


title: Unity scenemanagement freezes

text:
# Question
Title: Unity scenemanagement freezes
I am very new to Unity, and coding in general. Anyways, I'm trying to load another scene on click, but when I try to do so in the editor, Unity freezes. Also, it, by chance it seems, worked twice when I newly added the script. Not always when I newly add the script, but twice.

```
using UnityEngine;
using System.Collections;
using UnityEngine.SceneManagement;

public class GameMenu : MonoBehaviour {

    // Use this for initialization
    void Start () {

    }

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

        if (Input.GetMouseButtonDown(0))
        {
            SceneManager.LoadSceneAsync(sceneName: "Wisp1");
        }

    }
}

```

Can somebody help?

# Answer
all you need is the string name of the scene so if your scene was named Wisp1

```
void Update()
{
    if (Input.GetMouseButtonDown(0))
    {
        SceneManager.LoadSceneAsync("Wisp1");
    }
}

```

using a coroutine may be much smoother and is how the docs show loading async.

```
if (Input.GetMouseButtonDown(0))
{
    StartCoroutine(LoadYourAsyncScene());
}

IEnumerator LoadYourAsyncScene()
{
     AsyncOperation asyncLoad = SceneManager.LoadSceneAsync("Wisp1");

    // Wait until the asynchronous scene fully loads
    while (!asyncLoad.isDone)
    {
        yield return null;
    }

}

```

double check build settings to make sure the scene is present.
> 1 votes

# Answer
'LoadSceneAsync' takes a third param which is the mode. It's 'Single' by default which means it will unload current scene. I'm pretty sure this is the reason for the hang. Try using additive mode
> 0 votes

---
Tags: unity, scenemanager
---


# Question
Title: How to avoid "completely" dark shadow using directional light (as Sun) ?
Look at my scene:

Sun is rising and as you can see the scene is realistic; I mean, that what is in shadow is almost completely dark. This is correct, but i would like something less "dark", like an HDR.

These are some parameters i'm using:

This is my unique Light in scene (Sun):

I'm using also a Post-Processing profile with "Eye Adaption" unflagged.

Can you suggest me what i've to change to make my object affected by shadow less.. dark ?

Thanks

# Answer
> 1 votes
I've solved adding a "minimum" environment light :

Now, i haven't too dark shadow !

# Answer
> 7 votes
You said you were using an "Eye Adaption" Plug-in. Disable that first to make sure the issue is not caused by that.

At last you have several knobs to tweak the outcome. I recommend you use a balance of each depending on the settings.

Reducing Shadow strength to 80% simply reduces light intensity by 80% where the shadows are supposed to be. Simple, however when you have indoor levels it might give poor results inside the buildings.

These are the key. More information on environment lightning: https://docs.unity3d.com/Manual/GlobalIllumination.html#Environment

I personally use different light settings for indoor and outdoor levels. I don't change anything when the Player is entering a small building, but when the Level changes from an outdoor environment to a large bunker or a cave I have a set of triggers in the map that set different Environment Lightning values when you pass through them. Lerp between two triggers to make a slow transition.

Here is what it should look like.

All mentioned settings turned off:

Only Environment reflections:

Environment reflections and Environment lightning (Skybox):

Sun shadow strength 80% indoors (Nonsense):

A nice balance of all settings (Outdoors):

You also have the possibility to use additional lights with shadows disabled and bake them to tweak the lightning to your needs but going over that would be too much for this answer.

---
Tags: unity, lighting
---


title: Is Domain Driven Design good for games?

text:
# Question
Title: Is Domain Driven Design good for games?
I've just read about Domain models and it enlightened me since I've been developing a game that has a class which only holds data (few behaviors/methods). I assigned the job of handling these classes to the managers...and now my manager seems to look like a God object. My game object that supposed to be handling the logic is just an anemic domain model.

My current design pattern is in Singleton and I want to do some recoding to get this stuff out. I've never seen a DDD on games (as of now) but is this a good approach? I'm just a novice programmer (inclined to game dev't) so I want to learn more about good architecture before the game gets too bloated for redesigning.

# Answer
I'd never heard of domain driven design before your post. A quick look at a couple of references - here and here \- seem to suggest that it's just a fancy name for the traditional 90s method of object-oriented programming that I was taught in university, where you try and write classes for each noun that appears in the situation you're trying to model with software, so that the structure of the software seems to follow the structure of the real-world concept.

As such, my answer to this is that it's not "good". It's usually a reasonable starting point but proves to be inadequate as you go along. You rarely have a single domain but several different domains within one piece of software - for example, you may have the domain of the game (the world, the characters, the items), the domain of the renderer (the shaders, the meshes, the materials), the domain of input (the filesystem, the network, the keyboard and mouse), and the problems come in where the domains overlap and influence each other. Often in the course of joining 2 domains together, you realise that there is actually a dependency there that requires a change, meaning one of your representations becomes more of a burden than a help.

A vague example might be a mathematics library on a console and your in-game characters. Your maths library will like to have a large list of data and then 1 instruction to perform on that list, to run efficiently. Your in-game characters will each have their own set of vertex data for rendering and animation etc. Now, how do you get a long list of all the vertex data from each of your characters to be able to handle it in one go? You could perform a slow copying operation, or instead you could refactor your characters so that their data is more amenable to being processed by the mathematics library - but then one of your domains is breaking down to favour another one.

Personally I am very wary of any label that resembles "Whatever-Driven-Design". Software is both too wide-ranging and too complex for there to be a one-size-fits-all approach to creating it. Instead, when trying to write the best software I can, I try and fall back on the SOLID principles. These give you a good idea of how good your code is, without promising a panacea of a method that you can follow and magically arrive at good code. Unfortunately, without such an attached methodology, it takes a lot of experience before you learn how to conform to these guidelines, which is probably why so many people like the methodologies.

Regarding your issue of having anaemic classes and manager objects, this is usually something that is covered in introductory object orientation lessons and doesn't really require you adhere to any special methodology to 'fix' it. (You might want to pick up a book on object oriented programming if you're just starting out.) A class is a coupling of state and behaviour, where the behaviour modifies that state, and this is called encapsulation. Generally you try and encapsulate as much as possible, which means that the state should be manipulated by the object itself (and only that object). Only for behaviour that cannot be modelled within the class would you delegate to an external class, such as a manager, which is why the existence of manager classes is often considered a sign of poorly-written object-oriented code.

> My current design pattern is in Singleton and I want to do some recoding to get this stuff out.

I don't know what you mean by that line. A design pattern is a well-known way of writing a small part of your program. You wouldn't have a 'current' design pattern, nor would it shape the rest of your program. For beginners, these patterns are useful for getting you on the right track, whereas for experts they're more of a way to communicate about common code situations. One thing is important however: singletons are almost always a bad idea, and you should avoid them whenever possible. You can find many opinions about singletons on this site and over on Stack Overflow, but here is one practical question with answers that help you avoid needing them.
> 13 votes

# Answer
## Paradigm

As of the time that this answer was written, the other posted answers here are all wrong.

Instead of asking whether or not Domain-Driven Design is good for games. You should ask whether or not "Domain Modeling" is good for games.

## Is domain modeling good for games?

The answer is: sometime it's absolutely fabulous. However, if you're creating a real-time game such as a platformer or FPS or whatever (MANY MANY kinds of games) then no. It's not necessarily well suited for those systems. However, there may be systems within that those games in which implementing the domain model pattern is effective.

As others have mentioned here, component-entity frameworks tend to be very popular, and for good reason. However, in game-development culture there seems to be a distinct lack of layered architectures. Again, this is for good reason as most games that people are going to develop just mutate state on entities and let the emergent consequences be the game.

ALL SOFTWARE IS NOT THE SOFTWARE THAT YOU ARE WRITING. Some are quite different from others.

Some examples of domains in which domain modeling works well are card games, board games, and other types of systems that are event-driven.

Games that run at X frame rate with movement etc determined by time deltas as core domain concepts are probably not a great fit. In this case, our "domain" is often so simple that there's no need for domain modeling. Collision detection, spawning of new entities, influence of forces on existing entities etc tend to cover most gameplay.

However, as things become complex you do start to see developers implementing domain models within their entities to handle certain types of behavior and calculation.

## Domain model pattern in game architectures

Your game engine (for example, Unity3D) is often component-entity oriented. In a platformer, you may have an entity for your character and its state is constantly mutated to update position etc.

However, in a more event-driven game, it's more likely that the component-entity framework's role is more to just exist as the User Interface. You end up with a layered architecture.

UI renders game state to the user. User interacts with the UI, triggering commands in the service layer. Service layer interacts with domain objects. Domain objects raised domain events. Event listeners hear the events and trigger changes in the UI.

UI \> Service Layer \> Domain Model

In short, end up with model-view-controller with a service layer implementation.

Using this architecture, you have a completely unit-testable game core (A rarity in game development culture, and it shows) with an event-driven interface.

## Ok now, what is DDD?

Domain-Driven Design specifically is a culture / movement of emphasis on analytic patterns which are used to learn about the domain, so that you're actually building the right thing, and then implementation patterns that empower you to implement a model layer that represents the concepts in the domain model using your language's idiom. DDD comes out of a community that works with complicated domains and is always seeking for ways to manage high complexity in their applications by focusing on domain modeling.

DDD doesn't do so well if your goal is to just start coding, play around with the system and then figure out what you want to build later, etc. It assumes that there's more or less a domain in existence. So, if you have no idea what your game is going to be.. Then, it's not going to work.
> 11 votes

# Answer
No, I don't think DDD, or any other "buzzword" architecture is really good for games. With the possible exception of "component system", which seems really popular here.

When I hear questions and discussions like this, I'm reminded of this site. Pondering various architecture buzzwords will usually do you less good than actually designing and coding your own application.
> 3 votes

# Answer
Yes, but you should adapted.

When using DDD you will get modularity and single responsibility of each domain. But anything else just make things complex.

See my answer here
> -1 votes

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


# Question
Title: Unable to add asset/sprite, not sure why
I'm using Unity and have a 2D project. I'm trying to add a background image to my project/scene, but I'm unable to.

Adding smaller .png files to the project work fine, by simply dragging them onto the Hierarchy tab. My background image, and larger images, do not work though. Below is the image in question:

It's a 66kb png. Nothing weird about it.

How should I be adding it as a background if I'm unable to add it as a sprite?

Below is the assets settings under Import Settings:

# Answer
> 2 votes
At the top of the Inspector, change the "Texture Type" to "Sprite (2D and UI)"

Sprites support dragging them straight into the hierarchy, which automatically generates an object with a SpriteRenderer to display them. Other textures need to be sampled by a material assigned to a renderer, so they're not quite as quick to add to a scene.

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


# Question
Title: InputListener not working on a custom Actor
Right now I am working on a UI for my game. I'm adding my own UI elements to a group and adding that to a stage. But the listeners I'm adding to the actors are not firing off at all. I have looked on some StackExchange posts for answers but I couldn't find a good answer to my problem.

Right now the logic flow is `Stage <-- Group <-- Custom Actors(FurnaceUI & FurnaceRecipeUI)`.

This is the HUD class (hastebin since it wouldnt paste right): https://hastebin.com/zelibejopa.java

FurnaceUI:

```
public class FurnaceUI extends Actor {

private final Texture uiBackground;

public FurnaceUI(Group group, float x, float y, float width, float height){
    group.addActor(this);
    this.setX(x);
    this.setY(y);
    this.setWidth(width);
    this.setHeight(height);
    this.uiBackground = new Texture(Gdx.files.internal("ui/furnaceui.png"));
    for(FurnaceRecipe recipe : FurnaceRecipeRegistry.getRecipes()){
        group.addActor(new FurnaceRecipeUI(recipe, this.getX() + 10, this.getY() + 490, 280, 100));
    }

    setBounds(x,y, width, height);
    setTouchable(Touchable.enabled);

    addListener(new InputListener(){
        @Override
        public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
            System.out.println("usjkmd");
            return super.touchDown(event, x, y, pointer, button);
        }
    });

}

@Override
public void draw(Batch batch, float parentAlpha) {
    super.draw(batch, parentAlpha);
    batch.draw(uiBackground, this.getX(), this.getY(), this.getWidth(), this.getHeight());
}

```

FurnaceRecipeUI:

```
public class FurnaceRecipeUI extends Actor {

private final FurnaceRecipe recipe;
private final static Texture texture = new Texture(Gdx.files.internal("ui/furnace_recipe_ui.png"));
private final static Texture arrowTexture = new Texture(Gdx.files.internal("ui/ui_arrow.png"));
int i = 0;

public FurnaceRecipeUI(FurnaceRecipe recipe, float x, float y, float width, float height){
    this.recipe = recipe;

    this.setX(x);
    this.setY(y);
    this.setWidth(width);
    this.setHeight(height);

    setBounds(x,y, width, height);
    setTouchable(Touchable.enabled);
    addListener(new InputListener(){
        @Override
        public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
            System.out.println("aight");
            return super.touchDown(event, x, y, pointer, button);
        }

        @Override
        public boolean keyDown(InputEvent event, int keycode) {
            System.out.println(keycode);
            return true;
        }
    });
}

@Override
public void draw(Batch batch, float parentAlpha) {
    super.draw(batch, parentAlpha);
    batch.draw(texture, this.getX(), this.getY(), this.getWidth(), this.getHeight());

    for(Map.Entry<Item, Integer> result :  recipe.getIngredients().entrySet()){
        batch.draw(result.getKey().getTexture(), this.getX() + 10 + (i * 58), this.getY() + 20, 64, 64);
        i++;
    }
    i = 0;

    batch.draw(arrowTexture, this.getX() + 110, this.getY() + 40, 64, 32);
    batch.draw(recipe.getOutput().getTexture(), this.getX() + 200, this.getY() + 20, 64, 64);
}}

```

Then here is the main class of my game with the input multiplexer: https://hastebin.com/donosavoru.java

# Answer
I found the answer. I was using the same event somewhere else and was always returning true. Which makes the event not fire on any other event listeners that are in the inputMultiplexer.

```
    @Override
public boolean touchDown(int screenX, int screenY, int pointer, int button) {
    if (button == 0) {
        PlayerComponent component = player.getComponent(PlayerComponent.class);
        if (component.getPlayMode() == PlayerComponent.PlayMode.BUILD) {
            BuildingManager.getInstance().place(player);
        }
    } else if (button == 1) {
        PlayerComponent component = player.getComponent(PlayerComponent.class);
        if (component.getPlayMode() == PlayerComponent.PlayMode.BUILD) {
            component.setPlayMode();
        }
    }
    return true;
}

```

You see it always returns true. Now if I have another event listener in the same multiplexer returning true will tell it that it does not need to handle the event with other listeners.
> 0 votes

---
Tags: java, libgdx, input, events
---


title: Unable to add button in Unity

text:
# Question
Title: Unable to add button in Unity
I am wanting to add a button to my scene in order to mute/unmute music. I can add the button to my scene, but it's not appearing on the UI. I can't see it anywhere, not on the scene nor the game when running.

Below is a screenshot of the editor. You can see the button in front of the camera and in front of the scene itself, but it doesn't appear. I can't actually see a button, just a 'move' control'.

Things I have tried:

* Changing the 'Layer' of the button to default
* Adjusting the z-axis (I've tried 0, +1-5, -1-5)
* Giving the `Image (Script)` a material inside the Inspector

The button has text, which isn't visible either.

I could create a sprite and do a raycast, but that seems like overkill just to do a simple click action.

Any ideas?

# Answer
> 2 votes
You need to make the `Button` a child of a `Canvas`.

---
Tags: unity, 2d, gui, gameobject
---


# Question
Title: The SFML equivalent of polling to see if a key has been released?
I'm testing out SFML by trying to make a square move with lerp velocity. The desired result was that when, let's say, D was pushed, the square would accelerate smoothly from `velocity.x = 0` to `velocity.x = maxVel (20)`. When the D key is let go, it decelerates back to 0. The problem is, I can't get it to decelerate! When I let go of D, it keeps on going!

Player.cpp (only relevant code shown):

```
#include "Player.h"

void Player::input() {
    using Key = sf::Keyboard::Key;
    auto keyDown = [](sf::Keyboard::Key k) {
        return sf::Keyboard::isKeyPressed(k);
        };

    if (keyDown(Key::A)) {

        velocityGoal.x -= 3;
    }
    else if (keyDown(Key::D)) {
        velocityGoal.x += 3;
    }
    if(keyDown(Key::A) != true){
        velocity.x = 0;
    }
    else if (keyDown(Key::D) != true) {
        velocity.x = 0;
    }
    if (keyDown(Key::F)) {
        velocity = velocity; //just a breakpoint cue. Move along.
    }
}
void Player::update(float dt) {

    //interpolating velocity
    velocity.x = Math::interpolate(velocityGoal.x, velocity.x, dt);
    velocity.y = Math::interpolate(velocityGoal.y, velocity.y, dt);

        //capping out speeeeed
    if (velocityGoal.x > maxVel) {
        velocityGoal.x = maxVel;
    }
    if (velocityGoal.x < -maxVel) {
        velocityGoal.x = -maxVel;
    }

    //adding velocity to the player's position
    newPos += velocity;
    rect.setPosition(newPos);
}

void Player::draw(sf::RenderTarget& target) {
    target.draw(rect);
}

```

My interpolation function:

```
float Math::interpolate(float goal, float current, float deltaTime){
float diff = goal - current;
if (diff > deltaTime) {
    return current + deltaTime;
}
else if (diff < -deltaTime) {
    return current - deltaTime;
}

return goal;
}

```

It appears to be a problem with the if statements that set `velocity.x` to 0. SFML doesn't have anything like `keyJustPressed` or `keyUp`, so I just polled to see if `keyDown(D)` was not true. This evidently is not the right thing to do in this situation.

Does anyone know the right way to do this, or if there is some way I can track a key being released?

# Answer
If I understand your question correctly, you want to differentiate between a keyboard press and a keyboard release.

What you want to do is keeping track of the keyboard's state in the current frame and the previous frame. By then comparing the two states, you can figure out if a key was either pressed, released or even held.

Below I've added a code example on how that can be made. I've added all the code in one file but you can of course move all the keyboard checking code to an input handler class etc. The same kind of code can also be used for mouse buttons, joystick buttons etc.

```
#include <SFML/Graphics.hpp>

// The keyboard's state in the current- and the previous frame
bool CurrentKeyState[sf::Keyboard::KeyCount];
bool PreviousKeyState[sf::Keyboard::KeyCount];

// See function bodies below
bool KeyPressed     (sf::Keyboard::Key Key);
bool KeyReleased    (sf::Keyboard::Key Key);
bool KeyHeld        (sf::Keyboard::Key Key);

int main()
{
    sf::RenderWindow Window(sf::VideoMode(800, 600), "SFML keyboard test");

    sf::Event Event;

    memset(CurrentKeyState,     false, sizeof(CurrentKeyState));
    memset(PreviousKeyState,    false, sizeof(PreviousKeyState));

    while(Window.isOpen())
    {
        while(Window.pollEvent(Event))
        {
            if(Event.type == sf::Event::Closed)
                Window.close();
        }

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

        // Save the state of each keyboard key (must be done before any Key* function is executed)
        for(unsigned int i = 0; i < sf::Keyboard::KeyCount; ++i)
        {
            // Save the keyboard's state from the previous frame
            PreviousKeyState[i] = CurrentKeyState[i];

            // And save the keyboard's state in the current frame
            CurrentKeyState[i] = sf::Keyboard::isKeyPressed((sf::Keyboard::Key)i);
        }

        if(KeyPressed(sf::Keyboard::Escape))
            Window.close();

             // Not possible (and also doesn't make much sense) to use KeyHeld and KeyPressed together
        //   if(KeyHeld(sf::Keyboard::A))       printf("Key A is held\n");
             if(KeyPressed(sf::Keyboard::A))    printf("Key A has been pressed\n");
        else if(KeyReleased(sf::Keyboard::A))   printf("Key A has been released\n");

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

        Window.clear(sf::Color::White);

        // Render stuff

        Window.display();
    }

    return 0;
}

bool KeyPressed(sf::Keyboard::Key Key)
{
    return (CurrentKeyState[Key] && !PreviousKeyState[Key]);
}

bool KeyReleased(sf::Keyboard::Key Key)
{
    return (!CurrentKeyState[Key] && PreviousKeyState[Key]);
}

bool KeyHeld(sf::Keyboard::Key Key)
{
    return CurrentKeyState[Key];
}

```
> 1 votes

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


# Question
Title: How do I allocate to a C# dictionary having a string key and an integer 2D array or transform for value?
I'm working in C# on a Unity 2D game that spawns a shape that has only one correct landing place. There are 7 basic shapes but the component 4 squares of each shape are unique, with each bearing, say, a unique number. There are many more than 7 unique shapes because any component square is unique to the shape set. So the shapes have squares bearing a unique number (1,2,3,4 on a square; 5,6,7,8 on another square; 9,10,11,12 in a line (I-shape), 13,14,15,16 in another line (I-shape), etc. each of these shapes must be moved (by dragging, dropping or rotating) to its particular place in the grid.

I need to swiftly (1) indicate whether a shape has landed correctly and, if not, (2) move the misplaced (and possibly mis-rotated) shape to its proper location so that remaining falling pieces are not blocked from attaining their correct placements.

For (1), I'm using a dictionary with a string for the key that identifies the square component of the shape and an integer 2D array for the grid location values. Here is the declaration:

```
Dictionary<string, int[,]> dictOfProperLocations = new Dictionary<string, int[,]>();

```

Visual Studio is OK with that. But I am unable so far to allocate key-value pairs to the dictionary. I've tried the following and variants to indicate that a straight shape (an I-shape) bearing the numbers 1-4 belongs at the origin at its left end and stretches straight to the right:

```
dictOfProperLocations.Add("1", [0,0]);
dictOfProperLocations.Add("2", [1,0]);
dictOfProperLocations.Add("3", [2,0]);
dictOfProperLocations.Add("4", [3,0]);

```

But Visual Studio objects to that. I find many examples for C# dictionaries with string-keys and 1D-array-values, but no examples for this case with 2D-array-values.

Or might this be better handled with a 2D Transform\[,\] for the values representing the proper grid locations? Thank you.

# Answer
> 2 votes
First, you need to understand that just because you need two elements in your array does not make it a two-dimensional array.

We can define a one-dimensional array with two elements like this:

```
int[] myArray = new int[]{1, 2};

```

This array is one-dimensional: you need only one index input to select either `myArray[0] == 1` or `myArray[1] == 2`

A two-dimensional array is an array that needs two indices to select an element. eg..

```
int[,] myMatrix = new int[,]{
 {0, 1, 2},
 {3, 4, 5},
 {6, 7, 8}
};

```

When we want to index this array, we need to specify both the row and the column we want to address: `myMatrix[1, 0] == 3`

But if you know in advance that you just need a pair of coordinates, an array is overkill. We can store our coordinates more efficiently like this:

in `Int2.cs`:

```
public struct Int2 {
    public int x;
    public int y;
    public Int2(int x, int y) {
        this.x = x;
        this.y = y;
    }
}

```

At the top of your `Board` class, where you define member variables:

```
public Dictionary<int, Int2> dictionaryOfProperLocations = new Dictionary<int, Int2>();

```

When you want to define a new location mapping inside that type:

```
dictionaryOfProperLocations.Add(0, new Int2(0, 0));

```

This way you have fewer heap allocations, array bounds checks, etc. Using an integer as a key instead of a string containing an integer makes the hashing work of the Dictionary a little easier too.

I'm not sure if using a dictionary in this way is necessarily the best way to implement the gameplay you're describing, but for now I'll just address the syntax. If you want advice on algorithms & data structures for doing spatial queries about tetrominos, that might be a separate question we could help you with.

---
Tags: unity, c#, transformation, data-structure, visual-studio
---


# Question
Title: Maya - Single Model with different animation
I am newbie in Maya and would like to clarify some implementations in Animation. I know how to create simple animations in Maya. These animations are exported to Unity3D (as `.fbx` with `controllers`) to use in my application.

I want to know whether it's possible to attach different animations to one model. For example, let's say, I have an arrow mark model and I want to show different animations for the model like moving left, moving right, moving up, moving down, etc. So that, when I export, I'll get one model - `Arrow.fbx` and different controllers - `LeftAnimController`, `RightAnimController`, etc.

Is that achievable? Or I need to create different Arrow mark model with it's own controllers.

Any help will be appreciated. Thank you.

# Answer
Yes this is possible!

First, animation controllers are not imported, but created inside of Unity. They tell Unity which animation clip to play on the model. When you import an FBX file, you are importing one of three things:

1. Just a model
2. Just an animation
3. Both a model and an animation

You can choose what your FBX should include under 'Filetype Specific Options \> Include' inside of Maya when you export. So it's possible to export one FBX file for the model, and then export other FBX files that just contain animations and put them together with an animation controller inside of Unity.

If you want it all in one FBX file, a common technique is to have each animation play one after the other in the timeline. For example, have your idle animation on frames 1-30 and your running animation on frames 31-70 and your shooting animation on frames 71-112, etc. When you import the FBX into Unity, you can split it into multiple animation clips based on frame #'s in the import settings.
> 0 votes

---
Tags: unity, maya
---