# Question
Title: Invert parent transform (doesn't work for combination of rotation and scale)
### My problem

I'm working with Qt3D and my problem is almost exactly like this one:

https://stackoverflow.com/q/60995155/3405291

### Suggested solution

A solution is suggested here:

https://stackoverflow.com/a/61315454/3405291

### Understanding the solution

I have a problem understanding the suggested solution. Specifically:

> The problem is that the `QTransform` node does not store the transformation as a general `4x4` matrix. Rather is decomposes the matrix into a `3` transformations that are applied in fixed order:

> S - a diagonal scaling matrix
>
> R - the rotation matrix
>
> T - translation
>
> and then applies it in the order `T * R * S * X` to a point `X`.

> So when the transformation on the parent is `M = T * R * S`, then the inverse on the child will be `M^-1 = S^-1 * R^-1 * T^-1`. Setting the inverse on the child `QTransform` will attempt to decompose it in the same way:

> `M^-1 = T_i * R_i * S_i = S^-1 * R^-1 * T^-1`

> That doesn't work, because particularly `S` and `R` don't commute like this.

I'm looking for the phenomenon happening here and why it happens. Does it happen in other 3D engines? How is it resolved in other 3D engines?

# Answer
> 3 votes
A 4x4 homogeneous matrix can represent any affine transformation. That is, any combination of:

* Translation by any offset
* Rotation around any axis by any angle
* Scale along multiple arbitrary axes by any scale factor
* Shearing in any plane by any factor

Including any arbitrary composition of the above, in any order - like rotating then scaling then rotating and scaling again.

But there are good reasons why we don't want to use a 4x4 matrix as the "source of truth" for the transformations of objects in our game scene.

* Repeated transformations of a matrix can allow rounding errors to creep in and distort our objects, or even flatten them to a plane/line/point!
* Decomposing a matrix, like if we wanted to isolate and read or change just the rotation component, is somewhat expensive.

It's also *ambiguous*: we can't tell the difference between an object that's been rotated 180 degrees, versus one that's been scaled by a factor of -1 on two axes: the net transformed result is the same. So we lose some information when we compose transformations into a matrix.

For this reason, game engines often store the "source of truth" for an object's transformation as separate components, and generate the corresponding matrix on demand from that source. Frequently these source components will be:

* Translation vector
* Rotation quaternion or Euler angle triplet
* Scale factors along the object's 3 local coordinate axes

(Note that this is also just 9-10 floats, a little lighter than the full 16 needed for a 4x4 matrix)

When we need to update the matrix for rendering, we can build it by applying these three components in order from right to left:

$$M = T \times R \times S$$

Applying this matrix to a vector \\$\vec v\\$ is the same as first multiplying that vector's x, y, and z components by the axis-aligned scale factors, then rotating the result around the origin, then adding the translation vector to that rotated result.

$$M \times \vec v = T \times R \times S \times \vec v$$

(See this answer that goes into more depth about constructing and using matrices like this)

This covers the set of transformations we most frequently use in 3D games, but it's not as expressive as a 4x4 matrix. We can't use a single set of the components above to represent shearing transformations, or scaling along a diagonal axis.

That means *we cannot make every matrix* \\$ M\\$ in this way.

In environments like this, the object's transformation matrix will either be read-only (like in Unity), or if you're allowed to "set" it, what you're really doing is *requesting* a transformation *as close as possible to* the value you provide. The framework will then try to find some combination of translation, rotation, and axis-aligned scale that comes closest to matching the matrix you provided, maybe using an algorithm like this one.

That latter seems to be what Qt3D is doing, according to the answer you linked. So when you set a matrix, what you're really doing is asking the framework to calculate the best matching \\$T\\$ \\$R\\$ and \\$S\\$, and then assign the matrix \\$M = T \times R \times S\\$, even if that \\$M\\$ doesn't exactly match the matrix you provided.

In particular, if you have a parent object with a non-uniform scale applied, and a child object that is rotated diagonally to that parent, then the net effect of that transformation is a shear, or a scale along a diagonal axis of the child.

As we saw above, we can't represent a diagonal scale/shear in TRS form. So if you make an inverse matrix that cancels out the diagonal scale, and try to assign it to the child, the framework has no valid choice of \\$S\\$ that exactly matches the diagonal scale you're trying to apply. It has to compromise and pick the closest axis-aligned scale instead.

The best fix for this is to **avoid applying non-uniform scales to parent objects**. Consider making an invisible parent with only uniform scale, then give it two children: one with non-uniform scale representing the original parent's visual, and the second representing the original child. By keeping non-uniform scale out of the parent chain, you ensure you don't get these shear transforms that we cannot correct by applying the inverse to child objects.

---
Tags: rotation, matrix, transformation, linear-algebra, scale
---


# Question
Title: Why are vertices coordinates are always between -1 and 1 in 3D Models
I'm writing my very first 3D rendering engine in C++ using SDL2, and I've been following this book that has multiple code examples that has 3D models with vertices that all have coordinates between -1 and 1. The problem is I can't wrap my head why is that exactly. I tried creating a cube on my engine with vertex coordinates positioned according to where I want the object to be ex: v1 is (300, 100, 10) but then when rotating the cube it goes all out the place. Can someone explain why this is happening

# Answer
In graphics programming, we have the concept of multiple coordinate systems. Models that we create are typically made in model space (or local space if you prefer). When you make a model in e.g. blender, there is a coordinate system with an origin that all of the model's vertices are relative to. When we want to use those models in a game, we typically want to be able to move them, rotate them, and scale them so they appear in the correct location.

We accomplish this with translation, rotation, and scale matrices. Typically, we apply the scale, then the rotation, and then the translation. Together, these are called a world matrix. Multiplying a vertex in model space by its world matrix will move it into world space. From there, your view and projection matrices will convert it into screen space. This matrix multiplication is done in the shader typically.

In short, there shouldn't be an arbitrary limit on the coordinates of your models. Create your models around their own model origin and then position the model origin wherever you want in space.

The reason why your cube is going wacky is likely because the vertices are defined relative to the world origin and not to their own model origin. Your matrix is rotating the vertices around the world origin.
> 0 votes

---
Tags: c++, graphics-programming, sdl2
---


# Question
Title: Cannot create EAttachmentRule variable in a Blueprint struct
I'm trying to add a EAttachmentRule variable in a struct but the enum doesn't appear in the list of available types

I managed to create a variable in a BP by dragging the pin from an AttachActorToComponent node and promoting it to a variable. But I can't do the same thing to create a variable in a struct

# Answer
It does look like that is not possible. The easiest way around it would be to create an Enum with the same options (KeepRelative, KeepWorld, SnapToTarget) as the EAttachmentRule Enum and use that instead.
> 1 votes

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


title: Unity Export Package Taking Too Long

text:
# Question
Title: Unity Export Package Taking Too Long
I'm trying to export a Unity Package and it's taking far too long (it just keeps counting, and doesn't end). I'm not sure why it continues to count in the `PackageImporter.Tick` but I'm wondering if others have noticed performance issues.

Unity Version: 2020.2.3f1 OS: Windows 10

# Answer
> 1 votes
Following this thread from Unity Forums I came to a conclusion to update, I no longer have the issue I was facing with the `ImportPackage.Tick()` hanging the editor

---
Tags: unity
---


# Question
Title: Wall Jump doesn't push character away from wall
I followed a tutorial about implementing a wall jump but one thing that doesn't work is getting the character pushed on the opposite side of the wall when pressing the jump button. As it is, character is only jumping on the y axis upwards on the wall. I read a possible solution that my move code in the FixedUpdate is overriding my wall jumping code. I tried to set a condition to run the move code only if isWallJumping bool is false but to no avail. I have no idea what to try next.

Here is my code:

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

public class PlayerController : MonoBehaviour {

public Animator animator;

public Rigidbody2D rb;
public float speed;
private float moveInput;
public float jumpForce;
public float maxFallVelocity = -20;

private bool isGrounded;
public Transform feetPos;
public float checkRadius;
public LayerMask whatIsGround;

private float jumpTimeCounter;
public float jumpTime;
private bool isJumping;

IEnumerator dashCoroutine;
bool isDashing;
bool canDash = true;
float normalGravity;

bool isTouchingFront;
public Transform frontCheck;
bool wallSliding;
public float wallSlidingSpeed;
public bool wallJumping;
public float xWallForce;
public float yWallForce;
public float wallJumpTime;

private bool facingRight = true;

void Start()
{
    rb = GetComponent<Rigidbody2D>();
    normalGravity = rb.gravityScale;
}

void Update()
{
    Debug.Log("The velocity in the Y-axis is: " + rb.velocity.y);

        isGrounded = Physics2D.OverlapCircle(feetPos.position, .2f, whatIsGround);

        //Flipping

        if (moveInput > 0 && facingRight == false)
        {
            Flipper();
        }
        else if (moveInput < 0 && facingRight == true)
        {
            Flipper();
        }

        //////////////////////////////////////////////////////////
        //Animation
        /////////////////////////////////////////////////////////
        if (Input.GetButtonDown("Jump") && rb.velocity.y == 0)
            rb.AddForce(Vector2.up * 700f);

        if (Mathf.Abs(moveInput) > 0 && rb.velocity.y == 0)
            animator.SetBool("Running", true);
        else
            animator.SetBool("Running", false);

        if (rb.velocity.y == 0)
        {
            animator.SetBool("Jumping", false);
            animator.SetBool("Falling", false);
        }

        if (rb.velocity.y > 0.2)
        {
            animator.SetBool("Jumping", true);
        }

        if (rb.velocity.y < 0)
        {
            animator.SetBool("Jumping", false);
            animator.SetBool("Falling", true);
        }

        if (isDashing && moveInput > 0)
        {
            animator.SetBool("Dashing", true);
        }
        else if (isDashing && moveInput < 0)
        {
            animator.SetBool("Dashing", true);
        }
        else
        {
            animator.SetBool("Dashing", false);
        }
        ///////////////////////////////////////////////////////
        // Jumping
        //////////////////////////////////////////////////////

        if (isGrounded == true && Input.GetButtonDown("Jump"))
        {
            isJumping = true;

            jumpTimeCounter = jumpTime;
            rb.velocity = Vector2.up * jumpForce;
        }
        if (Input.GetButton("Jump") && isJumping == true)
        {
            if (jumpTimeCounter > 0)
            {
                rb.velocity = Vector2.up * jumpForce;
                jumpTimeCounter -= Time.deltaTime;
            }
            else
            {
                isJumping = false;
            }
        }

        if (Input.GetButtonUp("Jump") && rb.velocity.y > 0)
        {
            isJumping = false;
            rb.velocity = new Vector2(rb.velocity.x, 0f);

        }

        /////////////////////////////////////////////////////////
        // DASHING
        if (Input.GetButtonDown("Dash") && canDash == true)
        {
            if (dashCoroutine != null)
            {
                StopCoroutine(dashCoroutine);
            }
            dashCoroutine = Dash(.4f, .5f);
            StartCoroutine(dashCoroutine);
        }

        ////////////////////////////////////////////////////////
        // Wall Jumping

        isTouchingFront = Physics2D.OverlapCircle(frontCheck.position, .2f, whatIsGround);

        if (isTouchingFront == true && isGrounded == false && moveInput != 0)
        {
            wallSliding = true;
        }
        else
        {
            wallSliding = false;
        }
        if (wallSliding)
        {
            rb.velocity = new Vector2(rb.velocity.x, Mathf.Clamp(rb.velocity.y, -wallSlidingSpeed, float.MaxValue));
        }

        if (Input.GetButtonDown("Jump") && wallSliding == true)
        {
            wallJumping = true;
            Invoke("SetWallJumpingToFalse", wallJumpTime);
        }

        if (wallJumping == true)
        {
            rb.velocity = new Vector2(xWallForce * -moveInput, yWallForce);
        }
}

private void FixedUpdate()
{
        if (wallJumping != true)
    {
        moveInput = Input.GetAxisRaw("Horizontal");
        rb.velocity = new Vector2(moveInput * speed, rb.velocity.y);
    }
    ///////////////////////////////////////////////////////////////////////
    ///DASHING
    //////////////////////////////////////////////////////////////////////
    if (isDashing && moveInput > 0)
    {
        rb.AddForce(new Vector2(1f * 130, 0), ForceMode2D.Impulse);
    }
    if (isDashing && moveInput < 0)
    {
        rb.AddForce(new Vector2(1f * -130, 0), ForceMode2D.Impulse);
    }

}
//DASHING SCIENCE FICTION
IEnumerator Dash(float dashDuration, float dashCooldown)
{
    Vector2 originalVelocity = rb.velocity;
    isDashing = true;
    canDash = false;
    rb.gravityScale = 0;
    rb.velocity = new Vector2(originalVelocity.x, 0);
    yield return new WaitForSeconds(dashDuration);
    isDashing = false;
    rb.gravityScale = normalGravity;
    rb.velocity = new Vector2(originalVelocity.x, 0);
    yield return new WaitForSeconds(dashCooldown);
    canDash = true;
}

void Flipper()
{
    transform.localScale = new Vector3(-transform.localScale.x, transform.localScale.y, transform.localScale.z);
    facingRight = !facingRight;
}

void SetWallJumpingToFalse()
{
    wallJumping = false;
}

```

}

# Answer
> 0 votes
You should use `Debug.Log()` to better understand what your code is doing:

```
//...
    if (Input.GetButtonDown("Jump") && wallSliding == true)
    {
        Debug.Log("Started wall jumping. Will stop in " + wallJumpTime);
        wallJumping = true;
        Invoke("SetWallJumpingToFalse", wallJumpTime);
    }
//...

void SetWallJumpingToFalse()
{
    Debug.Log("Setting wallJumping to false");
    wallJumping = false;
}

```

My first guess would be that you forgot to set a value for `wallJumpTime` in the Inspector. Since you didn't specify a default value in your code, the value will be 0 if you don't set it in the Inspector.

---

A few other issues with your code:

* Always specify default values for primitive numbers (ints, floats) so the code will still work even if you forget to set something in the Inspector
* Never use `Invoke()`; it refers to functions by name using a string, which is bad for many reasons (IDE doesn't detect the reference, code will break if you rename function, etc). Use coroutines instead.
* Never put public variables into your scripts. Use `[SerializeField] private` or `[SerializeField] protected` if you want it to show in the Inspector
* `if (wallJumping != true)` can be shortened to `if (!wallJumping)`
* Your `Update()` function is way too long. The engine doesn't care, but it's messy and makes the code harder to read. Since that function is already divided into sections, you should split the sections off into their own functions, e.g.

```
void Update() {
    isGrounded = Physics2D.OverlapCircle(feetPos.position, .2f, whatIsGround);
    CheckFlipping();
    Animate();
    CheckJumping();
    CheckDashing();
    CheckWallJumping();
}

```

# Answer
> 0 votes
The character can jump now without using horizontal move input, since i removed the move input requirement in order to wall jump. line 161:

```
if (isTouchingFront == true && isGrounded == false && moveInput != 0)

```

to

```
if (isTouchingFront == true && isGrounded == false)

```

---
Tags: unity, platformer
---


# Question
Title: Do game testers have to live locally to be considered?
I've been told by a few former game testers that you must live in their city because game testing has few educational requirements so it's easier to hire someone local. Some descriptions say "you must live in or near (insert city)". Some won't tell you this until you get on the phone with them.

# Answer
It depends entirely on the situation.

There are a number of factors that favor hiring locally:

* You have the option of person to person interviews.
* Hiring across state lines can require additional considerations with respect to things like taxes, withholding and worker's compensation insurance.
* It's easier to secure your game from various leaks. In person testers can talk about your game, but it's much harder for them to leak footage or files.
* Some testing include observing the testers as the play and it's much easier to do this if they are physically present.
* Typically, the number of applicants exceeds the number of positions; hiring locally restricts the number of applicants that need to be reviewed.

Some situation favor or possibly even require hiring remotely:

* Assessing network performance under conditions that more closely resemble expected post-release play.
* Testing the game with demographics that aren't present or under represented locally.

Ultimately a smart company is going to tune their hiring process based on their needs and resources.
> 1 votes

---
Tags: testing, career, jobs
---


# Question
Title: How to manage in-game factions, alliances, federations, etc
So this question is code or engine agnostic but, I’m looking for ideas on how a game can keep track of a pre-determined number of factions or alliances. For example, say I made a space game that has 2 major and 3 minor federations of planets. A planet may join or leave a federation, but the federation itself may have an alliance or be at war with another (actually, to keep it simpler, I think all these changes will solely be reliant on the player’s actions).

However, I would also like to keep track of such diplomatic endeavours on the ‘individual’ level as well. Say the player has joined one federation that is at war with another. If the player should encounter another ship of the opposing federation, that ship becomes hostile. On the other side, two ships have an alliance, they might help one another.

What is the best way to keep track of all this?

One way I was thinking was creating a manager that holds all the Federation classes (which hold the status it holds with all other federations — say less than 0 and the federations are at war; more than x-amount, there’s an alliance). Meanwhile, each player/ship holds similar data in its class, along with its current alliance to whatever federation. Is my thinking logical in this or are there better ways of managing such things? Many thanks.

# Answer
> 0 votes
I don't know what the best way is, but if you are just interested in the current relationship between entities you could go with a manager. Decide how entities are connected, then save the individual relationships and check them hierarchically.

Federation A is at war with Federation B Ship A belonging to Federation A is allied with Ship B belonging to Federation B -\> When Ship A meets Ship B they are allies, but any other ship from Federation B would be considered an enemy.

If you also need to keep track of which things happened in the past you could look into implementing a block chain. That way you have the current state of things and can trace every change back to the beginning of the game.

---
Tags: software-engineering, data
---


# Question
Title: Is it possible to clone a game, and make modifiactions to it?
I basically want to know whether or not it is possible to copy a mobile game and make it into a new game by modifying it . I want to be able to access , moderation tools and basically alter, things like characters, events, in ap purchases etc. Alter it to make it different enough from the original and make it available to other users. The game I want to copy is no longer in the play stores and I want to change that.

# Answer
Is it *technically* possible? Perhaps. You could disassemble the APK, but when it relies on any server-sided components, you would have to clone those yourself. But taking a game executable made by someone else, doing modifications to it and then releasing it yourself is a copyright violation. It does not matter if the game is still being maintained or even if it's still available on the market. Copyright expires decades after the death of the author. It also doesn't matter if you changed a bit of stuff to make it more original. If there is just a tiny bit that remains from the original, you are violating the copyright on that.

"But what about all the other people who are doing that and their ripped games stay up?"

There can be a variety of reasons why the copyright owner did not take actions yet:

* They are not yet aware of the violation
* They lack the legal awareness of their rights and how to enforce them
* They don't have the time or money to deal with it
* The violator and/or the platform they release on are in some country where the copyright owner can not reach them
* They don't care

But whatever the reason might be, you can not count on the same reason to apply to you.

So when you like a game and would like to create your own version of it, then you have to start from scratch. You can not reuse any assets or code from the original. You have to recreate them yourself. For more information about how closely you can stick to the original without getting into legal hot waters, check out the question "How closely can a game legally resemble another?".
> 2 votes

---
Tags: mobile, copyright
---


# Question
Title: How to map gamepad inputs for my platformer?
With keyboard+mouse controls, we seem to have an unspoken control mapping standard, with keys be like WSAD for moving, E for use, mouse button for attacks or interactions, spacebar for jumping, and so on. But I'm unsure what conventions apply to gamepads.

I'm doing the typical platformer game, so my input would be:

* movement
* sprinting
* jumping
* attack
* interacting
* accessing main menu
* accessing inventory menu.

How can I map these actions to a gamepad's buttons/sticks in a way that will be intuitive for my players?

# Answer
> 6 votes
**Most importantly**: plan for remappable controls from the start.

Different games use different conventions, and different players have different preferences. This is also important for accessibility - not everyone plays with the same hardware - electrically or biologically speaking - and the ability to remap controls can turn an impossible game into a favourite game. The last thing you want to do is alienate a player who would otherwise love your game, but who can't comfortably use the default control scheme you chose.

That said, there are some common conventions for several of the controls in your list:

* **Movement**: Left analog stick (optionally with the D-Pad as a synonymous option, especially in retro-style pixel platformers)
* **Accessing Main Menu**: (by this, I assume you mean the in-game pause menu, not the front-end menu you reach when the game first boots up)

The button formerly known as "Start". Now different controllers call it different things...

+ Xbox One, Series S & X: "Menu" (the hamburger button "≡")
    + PlayStation 4: "Options" / PS5: "≡"
    + Nintendo Switch: "+"
* **Jump**: In western games, this is almost always the "South" face button (Xbox: A, PlayStation: Cross, Switch: B)

It often matches the control used to "Accept" a selection in a menu. Just note that this convention is different in Japanese games, which use the "East" face button (Xbox: B, PlayStation: Circle, Switch: A) for this. So games will often flip these two face buttons for localized releases. Games on the Switch sometimes carry this Japanese convention into their western releases too, since "A = Accept" is so ingrained)

Some of the other actions have less strong conventions:

* **Attack**: Sometimes the "Cancel" button counterpart to the Jump action's "Accept", ie. the "East" face button (Xbox: B / PlayStation: Circle / Switch: A), or flipped if jump has been swapped as described above.

In some games where attacking frequently needs to be done in conjunction with other face buttons like jumping, blocking, or dodging, it might be moved to a the right shoulder button or trigger - especially if you want to distinguish a "primary/light" (shoulder) attack versus an "alt fire/secondary/heavy" (trigger) attack.
* **Sprinting**: If this is a one-off action like a dash, it will often be on a face button in easy reach not already used by another action. So based on the breakdowns above, the "West" face button would be a good option (Xbox: X, PlayStation: Square, Switch: Y)

If this is a movement state that you need to toggle or hold, then it's more common to be on a shoulder or trigger button - particularly the left shoulder button to match the side of the controller used for movement.

I'd recommend against using the "stick click" button for this, as it's harder for players to discover, easy to trigger accidentally when trying to move the left stick urgently, and can be difficult, uncomfortable, or even painful for some players to execute. I try to put only optional actions on this control, and provide settings to remap/disable it in case it causes frustration.
* **Accessing Inventory Menu**: If this is a paused menu state, it will often be offered as a button or tab within the game's pause menu.

+ If accessing the inventory needs to be done frequently / on the fly with minimal gameplay interruption, then it may instead be implemented as a selection wheel accessed eg. by holding a shoulder button, or as a carousel widget on the HUD where the player presses D-Pad directions to cycle through the items.
    + Some games (particularly older Japanese titles) would put an in-game menu like this on the "North" face button (Xbox: Y, Playstation: Triangle, Switch: X)
    + Secondary menu shortcuts are often available via the button formerly known as "Select" (Xbox One, Series S & X: "View" - the two overlapping rectangles, PlayStation: touchpad click, Switch: "-"). But this is more frequently the map, rather than inventory.
* **Interacting**: This can mean different things in different games. Since these actions are often less frequent, and can be prompted with an on-screen control when available, you can use basically anything. If you're not using the "North" button above, then it could be a good choice.

If you're out of face buttons to assign, some games will make it a contextual action that takes over from one of your normal abilities (like attack or dash) when you're in range of an interactable object. Though you'd usually only do this if interactions are well-separated from combat areas to avoid accidentally triggering the wrong action. If you need to share a face button without interfering with combat/navigation, you can hold the button to interact but tap to execute the other ability, showing a progress bar filling on the interaction prompt to communicate this.

To sort out what to do in these more ambiguous cases, where multiple conventions exist, a good strategy is to play some popular games that are similar to yours, ie. ones that your players are likely also familiar with. Then you can match your conventions to what your players are already likely to know from these examples.

And of course, *playtest*. A control scheme can tick all the boxes above, following all standard conventions and looking great on paper, and still not be well liked be real flesh-and-blood players. So get hands-on feedback from players in your target audience, both early and often throughout development (using new players each time to avoid bias from their memory of how the game played previously). This will help you spot cases where your specific circumstances might demand a different approach.

# Answer
> 3 votes
There are a couple setups that have become ubiquitous. Here are some common uses (non-exhaustive list):

* Left stick for Player movement
    + Top-down shooters:
        - Movement direction
    + Clicking:
        - Ducks
* Right Stick for Camera movement
    + Top-down shooters:
        - Shooting direction
    + Clicking:
        - Cycles zoom levels
        - Centers the camera on the player
* Dpad:
    + Player movement
    + Side-scrollers:
        - Down: Duck
        - Eight-directional aiming
* Right Trigger for Primary shooting weapons
* Left Trigger for Secondary shooting weapons
* Right Shoulder button:
    + Next page navigation
* Left Shoulder button
    + Previous page navigation
* For four face-button controllers:
    + The "bottom" button for the most common action the player will perform:
        - Jumping
        - Interaction
        - Thrust-based forward movement (or gas pedal for cars)
        - Confirm dialog/menus
    + The "right" button for the next-most common action:
        - Attacking
        - Braking/Reversing
        - Cancel dialog/menus
    + The "left" button for less-common but useful actions:
        - Open the map
        - Use sub-weapons
    + The "top" button for auxiliary actions:
        - Open a submenu
        - Open the map (interchangeable with left button)

The ability to re-map the controls is proportionally related to the number of buttons/controls in use. Re-mapping on an Atari controller is an exercise in futility. Remapping on a NES controller will lead to confusion. Remapping on a three-button Genesis controller or some thing more complex (6-button/SNES/Xbox/PS) is almost required.

---
Tags: input, platformer, gamepad
---


# Question
Title: Why is Random.Range(0,3) generating only 0, 1 or 2 when 3 is supposed to be inclusive?
I'm currently having trouble getting my head around how *Random.Range()* and *Array\[\].Length* are working in the script below.

```
public class SpawnManager : MonoBehaviour
{
    public GameObject[] animalPrefabs;

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyUp(KeyCode.S))
        {
            int animalIndex = Random.Range(0, animalPrefabs.Length);
            Instantiate(animalPrefabs[animalIndex], new Vector3(0, 0, 20), animalPrefabs[animalIndex].transform.rotation);
        }
    }
}

```

Here, *animalIndex* is being assigned by *Random.Range()* a random number between 0 and the *animalPrefabs\[\]* array's length, which is 3. According to the documentation (both Visual Studio's and Unity's), both the minimum and maximum *Random.Range()* numbers are **inclusive**, which means *Random.Range()*'s possible outputs would amount to 4 numbers (0, 1, 2 and 3). However only 3 animalPrefabs\[\] (0, 1 and 2) are defined, as shown in the picture above.

Testing the script, however (printing *Random.Range()*'s outputs to the console), *Random.Range()* seems to be generating numbers from 0 to 2 only.

Is the documentation simply wrong? Otherwise, what's going on?

# Answer
You are using the `public static int Range(int min, int max);`  overload, which as per the documentation is inclusive for the lower boundary, and exclusive for the upper boundary. The documentation you see in Visual Studio is for the version accepting floating point parameters. The overload accepting integers is documented below the floating point version on Unity's documentation page.
> 4 votes

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


# Question
Title: How to write shaders that can be compiled for DirectX, OpenGL, and Vulkan
I recently finished writing the **DirectX** renderer for my game engine. Now I have an **OpenGL**, **DirectX** as well as a not yet finished **Vulkan** renderer.

Well, the majority of the renderers work perfectly now but I have a problem: I need a **shader programming language**.

The problem is that **OpenGL** and **Vulkan** use *GLSL* but **DirectX** uses *HLSL* (and Apple's **Metal** API uses *MSL*). So I searched for a High Level Shader Language and found only **C for graphics** from NVIDIA. But since this project was deprecated I looked for something else: Without success.

It's a bit annoying to write for 3 shader programming languages at the same time, so I'm looking for a language that can be translated into the native language immediately when the game starts (or is simply compatible with a lot of rendering APIs)

After several weeks of finding nothing, I decided to write my own language for it. But before I invest too much time I want to know if there is another solution to this problem.

# Answer
> 4 votes
This problem is often solved through the use of a **transpiler**, a program that can translate a shader written in one language into another.

HLSL2GLSL is one such example that was used in Unity up until 2016. Shaders could be authored in a standard HLSL syntax, then transpiled at build time into corresponding GLSL code.

SPIRV-Cross is another transpiler maintained by the Unity team that can serve as a bridge between HLSL, GLSL, MSL, and Vulkan.

Using an existing shader language as your source helps you avoid the overhead of designing a brand new one from scratch, and you can leverage a lot of work shared by other teams via projects like the ones linked above.

There are some extra considerations though, as outlined in the SPIRV-Cross Readme:

> ## Implementation notes
>
> When using SPIR-V and SPIRV-Cross as an intermediate step for cross-compiling between high level languages there are some considerations to take into account, as not all features used by one high-level language are necessarily supported natively by the target shader language. SPIRV-Cross aims to provide the tools needed to handle these scenarios in a clean and robust way, but some manual action is required to maintain compatibility.

The areas they call out include:

* HLSL source to GLSL
    + HLSL entry points
    + Vertex/Fragment interface linking
* HLSL source to legacy GLSL/ESSL
    + Separate image samplers (HLSL/Vulkan) for backends which do not support it (GLSL)
    + Descriptor sets (Vulkan GLSL) for backends which do not support them (HLSL/GLSL/Metal)
    + Linking by name for targets which do not support explicit locations (legacy GLSL/ESSL)
    + Clip-space conventions
    + Reserved identifiers

See the linked document for all the gory details of how to handle these situations.

---
Tags: shaders, glsl, hlsl, cg
---


title: Question on parallelizing ECS Systems

text:
# Question
Title: Question on parallelizing ECS Systems
Learning & Implementing an ECS system for my game, I'm wondering how I am supposed to parallelize the systems on multiple threads. Different systems can't run at the same time (unless they operate on completely different set of components), so I guess the most common option is to run each system sequentially and parallelize the iteration they do on components, in a parallel\_for fashion. The problem with this is that parallel\_for assumes each iteration is self contained, which is not always true. In case an entity needs to access the component of another entity, and maybe modify it (very common in gameplay programming), we cannot really run a parallel\_for as often we don't know what entities will want to access (through the system) what other entities.

How is this handled in ECS?

# Answer
> 3 votes
**Pipelines**

The simplest implementation of ECS will run systems sequentially one after the other. Perhaps you are familiar with the idea of fixing your timestep. Simply running systems sequentially in a predefined order blows past that concept.

The solution is to have pipelines. Then you can have a pipeline for physics, one pipeline for rendering, and another for input, for example. Or as many as you would want. Each pipeline has a different configuration. The first criteria is, of course, how often to run the pipeline.

My suggestion is have pipelines run sequentially, one after the other. Then you can run the systems in the current pipeline concurrently. That way you know that only the systems of the current pipeline are running. For instance, the systems in the rendering pipeline know that the systems in the physics pipeline will not move entities (update their position components) because that is a different pipeline, and pipelines run sequentially.

With that said, if you need to, for example, split the physics pipeline in two, to make sure one stage is completed before running the other, that is ok. Furthermore if a pipeline ends up having only one system, that is ok too. Use this to ensure that you will not have systems stepping on each other.

---

**Read-Write Locks**

You can use pipelines to have control over which systems can run concurrently, which allows you to prevent running in parallel systems that may step on each other. However, that can be error prone, as it requires to design you pipelines carefully. There is, of course, another way to ensure this: locks.

As you might know, having system declare what kinds of component they need on initialization is a good idea. It allows some optimizations. For example, if a system wants entities that have two kinds of component, we have a couple options:

* We can go over every entity and checking if they have the components, every time the system runs.
* We can keep a list of the entities that match the criteria, and every time one of those components is added or removed we can update that list.

The latter is only possible if the system declares the kinds of components it wants before hand. *Plus, multiple systems that want the same set of component kinds can share list. You might also be interested in the concept of Archetypes. Although I prefer to think about these as queries.*

Ok, extend that idea to include not only which kinds of components the system will read, but also which kinds of components the system will write (we can assume that write access implies read access). And now you can consider read-write locks on kinds of components:

* If a system that wants to write a kind of component is running, you cannot run any systems that want to read or write that same kind of component at the same time.
* Otherwise, multiple systems that want to read (but not write) the same kind of component can run at the same time. Any system that wants to write that kind of component must wait.

---

**On running a system for multiple entities in parallel**

A system runs over the components sequentially. One of the talking points of ECS is that they store components contiguously in memory, and to really take advantage of that you want to run over them orderly.

However, that does not mean that running a system in parallel is imposible. Yet, in order to do so we need to consider whether or not that introduces race conditions. A solution is to have a flag indicating if a system should run in parallel or sequentially.

---
Tags: multithreading, entity-component-system
---


# Question
Title: Exported FBX to Monogame doesn't translate all meshes
I'm taking a crack at a minecraft clone in Monogame, and I am trying to get my model to render as it's shown in Blender 2.9.1. When I look at the model in Blender, it looks great. When displaying in Monogame, the head is distinct but the body, arms, and legs are all mashed together. When I inspect the `ParentBone` for each `ModelMesh`, all except for the head have the same `ModelTransform` and `Transform` (but ModelTransform != Transform).

This is what I made in Blender:

But this is how it renders in Monogame:

I then tried creating an armature and adding bones, but did not seem to change anything other than the model in Monogame had a lot more bones in it. I thought it had something to do with how I exported, but I tried both FBX All and Local All for scaling with no change. I've also tried exporting as DAE instead of FBX (still need to use the FBX Importer for this to work) and no change there either.

Where I am missing a step that is causing what looks to be a translation issue? Minimally reproduceable code is below. I did find something on this site about storing the transforms for the bones, but when I tried to use that all I could see was the top of the head and couldn't rotate it? Or maybe I'm holding it wrong, I left it the code below commented out.

```
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;

namespace test
{
    public class Game1 : Game
    {
        private GraphicsDeviceManager _graphics;
        private Model model;
        private Texture2D texture;
        private Vector3 position;
        private Matrix world = Matrix.CreateTranslation(new Vector3(0, 0, 0));
        private Matrix view = Matrix.CreateLookAt(new Vector3(0, 0, 10), new Vector3(0, 0, 0), Vector3.UnitY);
        private Matrix projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.ToRadians(45), 800/480f, 0.1f, 100f);

        public Game1()
        {
            _graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
            IsMouseVisible = true;
        }

        protected override void Initialize()
        {
            // TODO: Add your initialization logic here
            base.Initialize();
        }

        protected override void LoadContent()
        {
            model = Content.Load<Model>("human");
            texture = Content.Load<Texture2D>("human_texture");;
            position = new Vector3(0, 0, 0);
            world = Matrix.CreateRotationX(-0.5f) * Matrix.CreateRotationY(0.5f) * Matrix.CreateRotationZ(0.1f)  * Matrix.CreateTranslation(position);

            // TODO: use this.Content to load your game content here
        }

        protected override void Update(GameTime gameTime)
        {
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
                Exit();
                world = Matrix.CreateRotationX(-0.5f) * Matrix.CreateRotationY(0.5f) * Matrix.CreateRotationZ(0.1f)  * Matrix.CreateTranslation(position);
            base.Update(gameTime);
        }

        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.CornflowerBlue);
            // pixelate textures
            GraphicsDevice.SamplerStates[0] = SamplerState.PointWrap;

            // lifted this from somewhere on the internet, but all I see is the top of the head and can't rotate when I use it?
            Matrix[] transforms = new Matrix[model.Bones.Count];
            model.CopyAbsoluteBoneTransformsTo(transforms);

            foreach (ModelMesh mesh in model.Meshes)
            {
                foreach (BasicEffect effect in mesh.Effects)
                {
                    effect.World = world;//transforms[mesh.ParentBone.Index];
                    effect.View = view;
                    effect.Projection = projection;
                    effect.Texture = texture;
                }
                mesh.Draw();
            }

            base.Draw(gameTime);
        }
    }
}

```

I've also uploaded my full .blend file, the generated FBX, and the texture here.

# Answer
Ah, I forgot to update this with the answer I found. I was still able to keep the current blender version, but I needed to do this:

```
effect.World = transforms[mesh.ParentBone.Index] * world; // (don’t forget - order is important)

```

The answer source is from the monogame forums here: https://community.monogame.net/t/exported-fbx-to-monogame-doesnt-translate-all-meshes/14887

(AlienScribble, if you're on here post your answer and I'll mark yours as accepted)
> 0 votes

# Answer
I’m not an expert. I only just recently got into modding using Blender.

I had a similar issue with a custom model I imported into MonoGame using FXB format. What fixed it for me was downgrading to Blender 2.79b. In 2.8, Blender stopped supporting the FXB 7.4 binary export format, which also had something to do with how the program handles bounding boxes.

I’d start there and see if it fixes your issue. Be warned, you will have to relearn/rebind a lot of controls and it will be frustrating.
> 3 votes

---
Tags: monogame, blender, 3d-meshes, fbx
---


# Question
Title: Component-based ability system for turn-based rpg
I am trying to make a component-based ability system for my new turn based game that I am working on. I not sure with the architecture and the approach I am following.

So here my idea:

Every Ability is a Prefab.
Four Ability Prefabs will be attached to every Character, those are their abilities.

An Ability consists of an `AbilityController.cs`. This will have the name and some basic data for the ability. Then I will attach one or more `AbilityTargetMode.cs`. Here I can pick a target mode (enemySingle, enemyAll, enemyRandom, AllySelf, ...) and attach one or more `AbilityComponent.cs` to every `AbilityTargetMode`. `AbilityComponents` are things like "Do Damage", "Apply Poison", and so on.

The idea behind this is that I can build complex abilities:

***Do** damage to a random enemy and poison him, **then** heal self, **then** apply buff to all allies.*

The structure for an ability would be:

```
-- Controller
---- TargetMode: EnemySingle
------ Component 1: Damage
------ Component 2: Poison
---- TargetMode: Self
------ Component 1: Heal
---- TargetMode: AlliesAll
------ Component 1 : Buff

```

And so on..

But I'm not sure about the whole system. Is it something that sounds right? Should I overthink something?

And another problem that I have is that I do not know how to attach my Components and my target mode to my Controller/Prefab. Is it better to use scriptable objects? What are your thoughts on the system?

**######EDIT######**

So yesterday i got my system working. At least a prototype for it. Here is a picture what i can do with it in the inspector:

Cool thing about it is, that i can make Components like "DoDamage" or "ApplyPoison". Then chain them and compose my custom abilitys. One ability can have more effects. Like a chain of effects. Damage one Enemy \> heal one ally \> buff all other allys

Its not optimal. I really would like to have something like this with scriptabla objects, but i was not able to pull it off. Is this system okay how i did it?

My game is turn based. The game is based around the combat and around a lot of characters. thats why i want an easy ability composer.

I have 3 codes:

1. AbilityController

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

public class AbilityController : MonoBehaviour
{
    public string abilityName;
    public AbilityTargetMode[] targetModes;

    private void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            for(int i = 0; i < targetModes.Length; i++)
            {
                targetModes[i].Execute();
            }
        }
    }

}

```
2. AbilityTargetMode

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

public enum TargetMode { EnemySingle, EnemyAll, EnemyRandom, AllySingle, AllySingleOther, AllyAll, AllyAllOther, AllyRandom, AllyRandomOther, AllySelf}

[System.Serializable]
public class AbilityTargetMode
{
    public TargetMode targetMode;

    public AbilityComponent[] abilityComponents;

    private Character[] targets;

    public void Execute()
    {
        CastAbilityComponentsOnTarget();
    }

    private void CastAbilityComponentsOnTarget()
    {
        for (int i = 0; i < abilityComponents.Length; i++)
        {
            abilityComponents[i].CastAbilityComponent(targets);
        }
    }

    private void SelectTargets()
    {
        switch (targetMode)
        {
            case TargetMode.EnemySingle:
                break;
            case TargetMode.EnemyAll:
                break;
            case TargetMode.EnemyRandom:
                break;
            case TargetMode.AllySingle:
                break;
            case TargetMode.AllySingleOther:
                break;
            case TargetMode.AllyAll:
                break;
            case TargetMode.AllyAllOther:
                break;
            case TargetMode.AllyRandom:
                break;
            case TargetMode.AllyRandomOther:
                break;
            case TargetMode.AllySelf:
                break;

        }
    }

}

```
3. AbilityComponent

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

[System.Serializable]
public class AbilityComponent : MonoBehaviour
{
    public virtual void CastAbilityComponent(Character[] _targets)
    {
        //do stuff
    }
}

```

# Answer
**Problems with this implementation:**

1. The first most obvious problem with your implementation is with `AbilityTargetMode`. You will run into a problem that one class implements a lot of logic and will become bloated, hard to manage. Basically it doesn't follow the Single Responsibility principle. The main culprit is `switch` statement. Not only there is this problem, but the issue with adding new types of targets, while game is in development it's really hard to predict what kind of types you are going to need in the future, thus making you add more and more code to this class.
2. It is limited in aspect of conditions. (Imagine you have a water spirit in your party, it neglects any water based damage, how would you define here if it takes this damage or not? This can of course be handled by passing damage information when actually doing damage to a target. But what if there are other conditions that do not depend on what character knows? Like "Swamp Blessing"\[if you are in swamp location - restore 20hp to all allies\], how would you handle such a case? It is not a passive skill of a character, nor this is something you want to have in your ability code - because again it will become a mess once you have a few hundred conditions.) Casting of a single `AbilityComponent` should be able to be under conditions.
3. It uses prefabs which will work fine, but it could be harder to manage if ability is complicated. The main issue with referencing, it would be hard to tell if you are referencing the correct component, as well as assigning them would be quite tedious. ScriptableObjects are a much better fit.

**Possible solution:**

I understand that this is link a based answer, but there are 11 scripts and fitting them here would make this answer quite long. If that is necessary to copy them here, let me know, I will do that. But this link will be up as long as this account here exists anyway.

Component-based ability system for turn-based rpg

There is a scene with an example, so I recommend downloading and playing with it because it may look complicated, but it's pretty easy in essence.

\[TEST Ability\] has a button.

And I apologise in advance for my over modular design, but it's intended to be scalable solution for different types of games. Also, some of the stuff can be used for other systems.

**Future possible improvements:**

1. Maybe, condition per action instead or both?
2. Selection of target providers can be improved by writing a custom inspector that will find them all and show you options to choose from, or using Addressables, though, I would not suggest going with this if you are not fully comfortable in Unity yet, it's a complicated beast and it serves a different purpose, having it for editor stuff is probably an overkill.
3. `FunctionalConditionsGroup` is definitely not the best way to handle this, but it's an ok way. A better solution is possible I think, but I would need to work with it to see what works and what not.
> 0 votes

---
Tags: unity, architecture, rpg, component-based, combat
---


# Question
Title: Why are transform values in inspector different from animation tab?
I’m trying to make animation in timeline. But transform values in animation tab and inspector are different from each other. It causes problem when ı try to rotate player. It doesn’t rotate the way I want.

# Answer
Let me say first that Unity inaccuracies on the scale of, i.e. 0.00001 is completely normal.

In your case, it's far off from that. The reason to that could have different reasons.

If it rotates back to it's original position for example it might be because of "Apply Root Motion" being unchecked.

However, in your case, it seems to be a general problem. The warning message at the bottom could be the reason why this problem occurs. Setting an inital offset on rotation can mess up transform values. So make sure that your rotation is set to 0, 0, 0 prior to recording.

If there are more Unity warning messages, please share them so we can help out further.
> 1 votes

---
Tags: unity
---


# Question
Title: Unity Mirror client scene.local player.connection to client.client owned object not working in client
U hmm I'm new to mirror networking I just wanna find objects that the local player has authority, but it doesn't work on client, is there a solution to this? Well I could make an object tracking script but that will complicate things. This question might look like I haven't research anything, truth is I've searched everywhere there is just no documentation for this

# Answer
To check if a client has authority or not, as long as the script is from `NetworkBehaviour` you can just use hasAuthority

```
void Start() {
    if (hasAuthority)
    {
        //only execute on client with Authority
    }
}

```

By default almost all objects have server authority. The player prefab assigned in the Networkmanager is the exception. To give a client authority, you need to assign it.

```
GameObject go = Instantiate(prefab);
NetworkServer.Spawn(go, connectionToClient);

```

or if it is already spawned

```
identity.AssignClientAuthority(conn);

```

If you need to find out who owns an object, you can find out on the server with the identity.connectionToClient property. If it is null then the server has authority.

If you do not need authority over an object, you can add the ignore flag in the command. docu

```
[Command(ignoreAuthority = true)]
public void CmdRideVehicle() {
    if (player.hasKeys()) {
    //transfer ownership to player
    }
}

```

You can find it in the documentation under authority
> 0 votes

---
Tags: unity, mirror-networking
---


# Question
Title: LIBGDX: Shoot a bullet using mouse position
I want to shoot a bullet towards my mouse position but I think that my math is probably wrong since the position the bullets travel to isn't the right one. Here's my code

```
Vector2 bulletDirection = new Vector2(screenX - player.getX(), Gdx.graphics.getHeight() - (player.getY() - screenY)).nor();
bullet.setPosiion(player.getX(), player.getY());
bullet.translate(bulletDirection.x * flightSpeed, bulletDirection.y * flightSpeed);

```

Can you tell me what I'm doing wrong? The "bullet" object is my current bullet sprite

# Answer
> 1 votes
You are probably using `Gdx.graphics.getHeight()` to change orientation of vertical axis from recieved click. If this is the case following code should work correctly:

```
Vector2 bulletDirection = new Vector2(screenX - player.getX(), (Gdx.graphics.getHeight() - screenY) - player.getY()).nor();

```

Also there is better way using `unproject` described here as it will later solve problems with zooming and moving camera:

```
Vector3 touchPos = new Vector3(screenX, screenY, 0);
Vector3 unprojectedPos = camera.unproject(touchPos);
Vector2 bulletDirection = new Vector2(unprojectedPos.x - player.getX(), unprojectedPos.y - player.getY()).nor();

```

---
Tags: java, libgdx
---


# Question
Title: How to give and remove authority of an object between multiple clients (Or how to let the client controller push a rigidbody)
I'm doing a cooperation FPS game in which players can push big rigidbody cubes with their rigidbody characters (the one from the standard assets).

The problem is that the player hosting the game has authority on these cubes positions and so when the client tries to push them, he really struggles and the result is 100% disappointing.

So i'm searching a way to pass authority from the server to client and vice versa when the cube is touched by a player.

I'm using Unity 2018.2

Have a nice day.

# Answer
> 2 votes
And so here's the script I used to solve this problem. However, if both client and host are sending commands through the object, you'll have a problem when the client has authority. I'll try to solve this later.

```
public class CubeAuthority : NetworkBehaviour {

private void OnCollisionEnter(Collision collision)
{

    if (collision.transform.tag == "Player" && isServer)
    {
        CmdAssignNetworkAuthority(GetComponent<NetworkIdentity>(), collision.transform.GetComponent<NetworkIdentity>());
    }
}

[Command]
public void CmdAssignNetworkAuthority(NetworkIdentity cubeId, NetworkIdentity clientId)
{
    //If -> cube has a owner && owner isn't the actual owner
    if (cubeId.clientAuthorityOwner != null && cubeId.clientAuthorityOwner != clientId.connectionToClient)
    {
        // Remove authority
        cubeId.RemoveClientAuthority(cubeId.clientAuthorityOwner);
    }

    //If -> cube has no owner
    if (cubeId.clientAuthorityOwner == null)
    {
        // Add client as owner
        cubeId.AssignClientAuthority(clientId.connectionToClient);
    }
}
}

```

# Answer
> 0 votes
Probably this helps. Here's code I made, though I made it for a different purpose (changing owner of vehicle key in game) the key is clientauthority.

The player selects which vehicle's key to give away with selectkey() and transfers it with transferkey() which then invoke a method on raycastselect to get the key receiver player and transfers it to the givekey script.

```
    public class keyselector : NetworkBehaviour
    {
        public raycastselect rayselect;
        public Text keyname;
        int ind;
        NetworkIdentity currentkey;

        public void selectkey()
        {
            NetworkIdentity x = ClientScene.localPlayer;
            Cmdselectkey(x);
        }
        [Command]
        public void Cmdselectkey(NetworkIdentity x)
        {
            var y = new NetworkIdentity[x.connectionToClient.clientOwnedObjects.Count];
            (x.connectionToClient.clientOwnedObjects).CopyTo(y);
            Targetselectvehicle(y);
        }
        [TargetRpc]
        public void Targetselectvehicle(NetworkIdentity[] y)
        {
            ind += 1;
            if(ind >= y.Length)
            {
                ind = 0;
            }
            currentkey = y[ind];
            if(y.Length > 1)
            {
                if (y[ind] != ClientScene.localPlayer)
                {
                    keyname.text = y[ind].gameObject.name;
                }
                else
                {
                    keyname.text = "SELECT\nKEY";
                }
            }
            else
            {
                keyname.text = "U HAVE\nNO KEY";
            }
        }
        public void transferkey()
        {
            if(currentkey != null && currentkey != ClientScene.localPlayer)
            {
                rayselect.givekey(currentkey);
            }
        }
    }

```

```
    public class raycastselect : MonoBehaviour
    {
        public GameObject rider;
        public GameObject ramper;
        public GameObject key;
        public Text toride;
        public void go()
        {
            RaycastHit trump;
            if (Physics.Raycast(transform.position, transform.forward, out trump))
            {
                enterexit stalin = trump.transform.GetComponent<enterexit>();
                if(stalin.player == null)
                {
                    stalin.player = transform.parent.gameObject;
                }
                if (trump.transform.GetComponent<crash>() && trump.transform.GetComponent<crash>().putin == null)
                {
                    trump.transform.GetComponent<crash>().putin = transform.parent.gameObject;
                }
                stalin.enter();
            }
        }
        public void givekey(NetworkIdentity vehicle)
        {
            RaycastHit trump;
            if (Physics.Raycast(transform.position, transform.forward, out trump))
            {
                GetComponentInParent<givekey>().Cmdchangeowner(vehicle, trump.transform.GetComponent<NetworkIdentity>());
            }
        }
        public void ramp()
        {
            RaycastHit trump;
            if (Physics.Raycast(transform.position, transform.forward, out trump))
            {
                ramp stalin = trump.transform.GetComponentInChildren<ramp>();
                stalin.door();
            }
        }
        private void Update()
        {
            RaycastHit trump;
            if (Physics.Raycast(transform.position, transform.forward, out trump))
            {
                if (trump.transform.GetComponentInChildren<enterexit>())
                {
                    rider.SetActive(true);
                    toride.text = trump.transform.gameObject.name;
                }
                else
                {
                    rider.SetActive(false);
                }
                if (trump.transform.GetComponentInChildren<ramp>())
                {
                    ramper.SetActive(true);
                }
                else
                {
                    ramper.SetActive(false);
                }
                if (trump.transform.GetComponentInChildren<raycastselect>())
                {
                    key.SetActive(true);
                }
                else
                {
                    key.SetActive(false);
                }
            }
            else
            {
                rider.SetActive(false);
                ramper.SetActive(false);
                key.SetActive(false);
            }
        }
    }

```

```
    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    using Mirror;
    public class givekey : NetworkBehaviour
    {
        [Command]
        public void Cmdchangeowner(NetworkIdentity vehicle, NetworkIdentity player)
        {
            vehicle.RemoveClientAuthority();
            vehicle.AssignClientAuthority(player.connectionToClient);
        }
    }

```

---
Tags: unity, networking, unity-networking, rigidbody
---


# Question
Title: What is the right approach for using foot ik for characters in slopes(Specially when in walk or run)?
i use unity but this question applies for any third person controller or enemy controller.

i need to use foot ik on slopes(any condition and any kind of slope) to place foot on right places. as i considered some important third person games, it seems they only use ik when character is idle and not moving otherwise no ik is applying and leg animations run purely.

i use the same approach and result looks good enough but im looking for applying when character is walking or running.

as i looked, some people disable ik when leg is going up and enable it when its coming down. some other do a raycast from foot bone to the ground to check foot need ik on little distance to ground. but all of these are prototypes and has flaws. can you give me a good approach that works best in all conditions?

# Answer
When I implemented a foot IK system, I used a raycast each frame to determine the position of the ground in front of the foot. I used the raycast for all types of movement and it worked fine for my purposes. Performance shouldn't be an issue if you don't have too many units doing the raycast at once ("too many" depends on your target platform and how hard your game pushes the physics engine). If there might be hundreds of units all simultaneously walking around with IK, you might enable/disable the raycast foot placement based on the distance from the camera (in other words, if the unit is too far away for the player to be able to tell whether their foot IK is accurate, you don't need to perform the raycast).

Obviously, you should use layer masks to ensure the IK raycast only checks your terrain layer (or any other layers containing walkable surfaces)

I found it necessary to start the raycast a little bit above the foot. If you start the raycast right at the foot, but the foot has clipped through the terrain, the raycast won't detect the terrain because it's starting below the terrain. If you start the raycast above the foot, that's not an issue. How far above the foot depends on your specific leg animations and how your terrain is shaped, but a good starting point is the distance from knee to foot. For example, if the character's leg is .5 meters inches from heel to knee, you might start the raycast .5 meters above the foot.

The free "Fast IK" asset on the Unity Asset Store includes an example of combining IK with Mecanim animation. I used a different solution but found it helpful for reference: https://assetstore.unity.com/packages/tools/animation/fast-ik-139972

Unity has a built-in "foot IK" option for humanoid Mecanim animations but they don't really describe it in their documentation and I haven't used it before. If you haven't already looked into it, you should see if it meets your needs.
> 2 votes

---
Tags: unity, animation, animation-controller
---


title: Rotate a Polygon node in Shader Graph

text:
# Question
Title: Rotate a Polygon node in Shader Graph
I have a hexagon in the Polygon node I would like to rotate so the pointy side is upwards. Applying the rotation nodes, however, simply changes the color of the hexagon from white to a color in the rainbow.

What does the `Vector1` of the Polygon output represent and is there a way I can rotate it as if it were a texture?

# Answer
> 0 votes
> What does the Vector1 of the Polygon output represent

It represents whether the current pixel being shaded is inside (1) or outside (0) the polygon.

> and is there a way I can rotate it as if it were a texture?

Just like with a texture, you don't rotate the colour value coming *out* of the node. You have to rotate the sample coordinates going *into* the node.

Here's one way to do it, putting a Rotate node between UV0 and the Polygon node:

Or you can just swap the X and Y axes of your input coordinate:

---
Tags: unity, shaders, unity-shader-graph
---


# Question
Title: How to get all tiles along a straight vector path?
Let's say I have a 100x100 map of tiles where each tile is 16x16 pixels.

How would I get all tiles along a path? For example, let's say I wanted to get a list of all tiles along the shortest direct path between `x: 50, y: 100` and `x: 225, y: 200`

To convert a coordinate to tile space, you simply divide the coordinate by the tile size and then floor it.

So with this example, the world coordinates would be converted to the following tile coordinates:

```
let tileStartX = Math.floor(50 / 16); // 3
let tileStartY = Math.floor(100 / 16); // 6

let tileEndX = Math.floor(225 / 16); // 14
let tileEndY = Math.floor(200 / 16); // 12

```

So, we'd be looking for all tiles between `x: 3, y: 6` and `x: 14, y: 12` like in this example image (`0, 0` is top left here):

It's easy enough to convert world coordinates to tile coordinates, but what I'm having trouble with how to get all the intermediate tiles along the diagonal.

Also, I think I may have messed up the drawing slightly because I didn't fill in some white squares where the units have to briefly walk through.

# Answer
> 1 votes
This is known as a line-drawing algorithm. That link has multiple algorithms to solve this problem - for your case you'll want to ignore the algorithms which anti-alias. The simplest solution is the naive algorithm:

```
dx = x2 − x1
dy = y2 − y1

for x from x1 to x2 do
    y = y1 + dy × (x − x1) / dx
    plot(x, y)

```

*(pseudocode copied from wikipedia)*

A more complex but slightly faster version is Bresenham's algorithm.

---
Tags: mathematics, javascript, algorithm, path-finding, vector
---


# Question
Title: How to apply Time.timeScale only to certain scripts?
I have a need to pause my game and the simplest and most clean way that I know of (other than completely designing my own time system) is by using `Time.timeScale = 0;`

However, this also makes my CameraController script stop working, because it relies on `LateUpdate()` and `FixedUpdate()` to update the camera position.

How would I change the timescale for other things that rely on it, but leave the part of it that the CameraController works with intact?

My first thought was adding a variable `int isPaused;` to parts of code that need to be stopped, and then instead of actually setting the timeScale to 0, I'd just change that isPaused variable to zero, and then multiply it with Time.deltaTime as usual, which would result in that object not moving, while still keeping my CameraController working. However, I'm not sure if this is the cleanest and simplest way to achieve something like this. Perhaps designing my own time system would be more beneficial in the long run?

Here's the CameraController code incase it is needed: https://hatebin.com/fqtybcuwht

# Answer
Nothing wrong with what you've suggested. I would use another `float` value - just like `Time.timeScale` itself - which is set to either `0.0f` or `1.0f`, to multiply by in all scripts except your `CameraController`. It becomes `0.0f` when you pause, `1.0f` otherwise.

This way, you also avoid conditionals - multiplication is cheaper than checking `if (someFlag) ...`
> 1 votes

---
Tags: unity, 2d, camera, time, deltatime
---


# Question
Title: How can I accommodate custom pronouns in voice acting?
I am currently developing an RPG in which, during character creation, players may choose their pronouns as he/him/his, she/her/hers, or a custom entry based on their own text input. Whenever characters refer to them in dialogue, they will use the pronouns listed as they were typed into the character creation.

To head off some objections that have been raised in comments: this game isn't a hardline historical fiction, it's a video game RPG. My setting is what I write it to be, and in my game I want people to be able to make the character they want.

The trouble I've arrived at is that I will eventually be getting dialogue voice acted, and I am not sure how to account for these voice lines. Say for example a character set their name as Pete and pronouns as he/him/his, the dialogue might appear on screen as:

> Hey! This is my friend \[Pete\]! \[He\] is new in town, want to help me show \[him\] around?

Under normal circumstances with a male/female only option, I could simply record two lines which omit the name, such that the line sounds like this in voice:

> Hey! This is my friend! He is new in town, want to help me show him around?

Pronouns, however, cannot simply be omitted from speech.

What ways can I account for this in the voice acting of my game? Do there exist examples of voice acted games with custom pronouns that get around this issue?

Solutions I have come up with thus far:

* Write the story such a way that pronouns simply aren't used in dialogue, only e.g. in UI

This is doable from a writing perspective but doesn't feel right because it makes the pronoun selection feel completely meaningless. I would like players to feel like the gender represented by their pronouns, so a completely pronoun-neutral dialogue would feel weak to me.

* In voice acting, use a generic "they/them/their" pronouns and display the custom pronouns in text

Players will notice this, and it will feel out of place. Playing as a "he/him/his" or "she/her/hers" will probably seem confusing when they hear their "common" pronoun replaced with a neutral variant. Also, some consider "they/them/theirs" to be grammatically incorrect.

* In voice acting, record three lines: "he/him/his", "she/her/hers", and "they/them/theirs" used for any custom pronouns

This is the solution I'm currently leaning towards, but it still feels dirty. Like I'm offering token representation but then reducing it to an "other".

# Answer
## 3x Version

> * In voice acting, record three lines: "he/him/his", "she/her/hers", and "they/them/theirs" used for any custom pronouns
>
> This is the solution I'm currently leaning towards, but it still feels dirty. Like I'm offering token representation but then reducing it to an "other".

While not as powerful as 100% open pronoun selection, I think this is still a valuable direction to explore. There are a lot of players who use they/them pronouns who never even get that third option, so this would be extremely meaningful to them.

Also, from my experience as a queer person in 2SLGBTTIQQA+ community spaces, I've found folks who use other pronouns like ze/fae/etc. will often offer two sets of pronouns, including a more familiar back-up like they/them. It might not be the person's first choice, but ze knows not everyone is ready to pick up a new pronoun on the spot, and it's strictly preferable to being misgendered as he or she.

Just be sure that, if you allow the player to enter custom pronouns beyond the three you've recorded, let them select the spoken pronouns on that same menu/screen. That way the player still has agency over how they'll be referred to, and it doesn't come as an unwelcome surprise later when the audio doesn't match their provided text.

Although this 3x recording approach isn't perfect, it already shows a level of consideration and inclusivity above and beyond what most games offer, and I think that's likely to be appreciated by your audience, rather than perceived as token support.

Increasing your voice acting costs by 50% is not a paltry gesture - that's a serious commitment that I think is praiseworthy.

That said, there is another strategy I've seen used to good effect:

## Excerpts

In this approach, the spoken line is not the entire displayed text verbatim, but a shorter version that captures the main idea and emotional tone.

So a displayed line like...

> Hey! This is my friend Pete! He is new in town, want to help me show him around?

Might be accompanied by a short bark like...

> Hey! This is my friend!

Not only does this help save voice acting budget, it can also help the pacing of the game if it's text-heavy. Players often read faster than they can listen, and narrative game players in particular often re-play several times to try different paths through the story. Using shorter clips means the player doesn't have to cut off the dialogue to play through at their own pace, or feel stuck waiting for a long monologue to finish after they've already read it.

This gives you the ability to incorporate any pronouns you want into the text, so no set of pronouns is relegated to "other". It lets you keep the fidelity and emotional expression of real human voice acting, without limiting the player's choices. And it works as a deliberate stylistic choice - that other games have made for reasons unrelated to gender or other text substitution - so it's not likely to be perceived as a kludge or awkward workaround.

For accessibility, you would still want to consider text-to-speech or screen reader support, to ensure the non-spoken parts of the text can still be understood by all players. But in that context it's somewhat more acceptable if the text-to-speech system doesn't always pronounce everything perfectly or have the right voice/emphasis/emotional tone, since it's not carrying the whole weight of the voice acted narrative on its own.

---

One quick addendum before I wrap this up. You mention:

> Also, some consider "they/them/theirs" to be grammatically incorrect.

Use of "they" as a singular pronoun has a part of the English language since the 1300s. Comparatively speaking, using "you" as a singular is the new-fangled fad, which we only picked up around the 1600s. Before that, "you" was always plural and we used "thou" for singular.

So, myself, I would not consider this objection valid. We've long used "they" as a singular when referring to a hypothetical person, or someone whose gender is unknown or irrelevant to the message. Using it to refer to a specific person in accordance with their gender isn't violating any grammatical rules.
> 57 votes

# Answer
I personally prefer **eliminating all mention of player gender from the entire game**. This approach is not workable for every game, but I think it can be applied to many.

Don't offer the player a gender or pronoun. Let them customize their appearance however they want, without categorizing options by gender (e.g. the player should not have to click on a "female" icon to view dresses). Then use clever writing to avoid mentioning the player's gender identity in the dialog.

RPGs which offer romantic relationship options tend to limit your relationship choices based on your gender. E.g. if you create a female character, you can only develop a romantic relationship with a male character (or the token lesbian, if any). Throw out that idea entirely. Since our player's gender is never specified at all, let the player pursue romantic involvement with any character they are interested in. The character does not care about, or comment on, the player's gender identity. See footnote\** for more rationale on this.

This approach simplifies the software side of things, since your code never needs to check the player's gender or make any decisions based on gender.

> Pronouns, however, cannot simply be omitted from speech.

Sure they can, it's just tricky.

* "Hey! This is my friend Pete! He is new in town, want to help me show him around?"

becomes

* "Hey! My friend here is new in town! You want to help me give the grand tour?"

There are a few tricks to make this easier:

* Give the player character a specific gender-neutral name (e.g. "Alex", "Blake", "Taylor") or a gender-neutral title ("commander", "wanderer", "chosen one") and use this when possible.
* Use the term "person" when possible, e.g. "you're the nicest person I've ever met"
* Lump the player in with a group and refer to the group rather than using a gender pronoun

Where writers tend to get hung up is when several other characters are discussing the player.

* **Original:** "She says that she wants to fight the dragon, and you agree with her? Maybe she's got a death wish, but I'm not about to throw my life away just to suit her notion of honor. She can get herself killed."
* **Bad rewrite:** "The Commander says that the Commander wants to fight the dragon, and you agree with the Commander? Maybe the Commander has a death wish, but I'm not about to throw my life away just to suit the Commander's notion of honor. The Commander can get themself killed."
* **Good rewrite:** "The Commander says that we should fight the dragon, and you agree? Maybe the two of you have a death wish, but I'm not about to throw my life away just to suit some arbitrary notion of honor. You can get yourselves killed."

These types of rewrites can be difficult at first, but like anything else they get easier with practice. After a few hours you'll probably find you're able to write genderless dialog without even having to think about it.

---

\**The RPG *Knights of the Old Republic* has a character, Juhani, who was intended to be a lesbian. However, due to a bug in the code, at release time both male and female player characters could pursue relationships with Juhani. Because Juhani never overtly discusses her sexual preferences, players did not realize this was a bug, and thought she was supposed to be bisexual.

In that case, I would argue that Juhani's sexuality was not an essential part of her character identity, but rather an arbitrary distinction applied by the developers. Maybe the writer intended her to be a lesbian, but this didn't come through in the dialog. If a character can have the "wrong" sexuality due to a bug and nobody can tell that it's a bug, should it really matter whether the player is male, female, or other?
> 23 votes

# Answer
I don't think there is a silver bullet for this. Here are some alternatives you didn't mention…

---

## No Voice Acting

You can convey speech patterns in the speed of the text (don't make it appear all at once, on that note, don't make text too small). You can convey timber with text color. You can use animation for emphasis. Oh, and show me emotion in characters (either on their model or in character portraits accompanying the text on screen).

*I'd suggest to do all of the above even if you have voice acting.*

For audio you can use grunts, beeps, or similar.

This has the advantage of being cheaper. And does not require to go back to the recording booth if you want to change or add dialog (e.g. for DLC).

---

## Gliberish

You can take The Sims route with Simlish (Warframe Greener speech too).

The voice actors did improvise most of the lines for The Sims. If you want voice acting because it is engaging, with gliberish you get that. Plus gliberish can help convey emotion.

Furthermore, gliberish does not have to be random. In The Sims (and in Warframe too) there are translations for everything they said. They gave the text to the voice actors. For The Sims, the actors improvised the language which resulted in some patterns that you might recognize, in fact there are dictionaries of Simlish (For Warframe, the developers have a tool that mingles English and they gave that to the Voice Actors).

If your game is Sci-Fi or Fantasy, you work the language into the world building.

---

## Custom text to speech

There are solution that will allow you to create custom voice to speech for a premium. If you have the money to throw at it, you may create some from your voice actors, and use it to pronounce the pronouns.

Alternatively, if the custom pronouns are restricted to be uni-syllabic, you might as well have the actors record a syllabary and then pick the closer one to what the user chose. People could write unpronounceable things anyway.

In fact, recording syllables is often part of the process of making a custom voice, and if it is only for single syllable words… You can consider skipping the rest of the process. Although, be aware that you may need a lot of testing to make sure the combination of recordings is not jarring.

This has the advantage of being more accesible. And it is easier to make the game engaging with (good) voice acting.
> 10 votes

# Answer
## Write around pronouns in voiced dialog.

Pronouns are a linguistic shortcut which is entirely optional. Whenever you use a pronoun, you can substitute it by a proper noun describing the person being referred to.

Most voice-acted games avoid pronouncing the player's name, by giving them some nickname or title and refer to them by that. ""Dragonborn", "Chosen One", "Commander", "Lone Survivor", "Traveler"... whatever makes sense in the context of the game. But that title can also be used in place of pronouns.

Example:

> This is Frodo, the Ringbearer. He must travel to Mount Doom and cast his ring into the fire.

Becomes:

> This is The Ringbearer. The Ringbearer must travel to Mount Doom, where The Ringbearer's Ring must be cast into the fire.

Now this example does of course sounds a bit stilted. But by structuring your text differently you can move mentions of the player-character further apart so using the proper noun each time seems more natural.
> 5 votes

# Answer
If you're willing to settle for artfully avoiding the problem, the other answers have you covered. But if you absolutely *must* have custom pronouns that are voice acted, I can only think of one way it could maybe, possibly be done: *(WARNING: what follows is an R&D project, not a prepackaged solution)*

Give players the option of replacing the default pronouns with their own audio clips. This is the only way to guarantee correct pronunciation of pronouns that the player invented (which may not follow the conventions of any known language).

Include a recording function on the character creation screen, and/or a way to upload clips. The player will have to provide reasonably good quality recordings if they want good results, but you may be able to apply filters to help decrease static and background noise, etc.

The real challenge is going to be using one set of audio clips-- which probably won't sound like any of your voice actors-- to replace the pronouns spoken by all of the various NPCs. The solution might look something like this:

Step 1: Use voice changing software (e.g. MorphVox, Voicemod, Voxal, etc.) to create a set of custom voices that sound like your actors. Those voices can then be applied to the player's audio clips. If you can't make the custom voices sound enough like the actors, then just create a good set of voices and use them on both the actors and the player.

Step 2: For every replaceable word in the original dialog, create a profile of the relevant audio data (e.g. pitch, volume, duration, etc.). You'll probably want to have a professional sound designer on hand for this step (or for any of this, really).

Step 3: Replace the original pronouns with the players' clips, adjusting them based on the data from Step 2. Use cross-fading and whatever other techniques your sound designer has up their sleeve to blend the clips with the surrounding audio.

Unfortunately, I can't cite any examples of this approach having been implemented successfully. Professional sound designers have had the ability to seamlessly replace individual words in spoken dialog for decades, so I have little doubt that it's possible. Your challenge will be to automate it.

This answer may be a long shot, but it would be really cool if it worked. And it wouldn't be limited to just pronouns. You could also use it for the player's name, and probably other things too. And I'm sure some people would misuse it to hilarious effect.
> 1 votes

# Answer
## **Summary**

Take a hybrid approach. Or limit voices.

This is a problem many developers face: the more freedom you give to the player, to more constraints you place on yourself. Some choose to make the character only one gender, and other do multiple things to work around this. I've done both, so here are my two cent.

**Write out pronouns/use other pronouns**
Like many others have said, write out pronouns as much as necessary. This will mean rewriting some lines to avoid awkward wording. You can also use nicknames, titles, and other words to replace pronouns.

> Hey! This is my friend Pete! He is new in town, want to help me show him around?
>
> Hey! My friend \[Pete\] here is new to town, so want to help me give a tour?
> OR
> Hey! This is my friend \[Pete\]! My buddy's new in town; how about you show "us" around?

**But you can leave in a few line were it counts**
That is not to say you have to completely eliminate pronouns. If you do have room to record a few more lines, you can use it in cases where you absolutely cannot avoid using a pronoun, or in special events.

## **Alternatives**

By limiting the amount of VO, you can potentially avoid this problem, or at least make it easy enough for you to handle. However, if you were planning the game to be fully-voiced, this will be quite a downgrade.

**Excerpts**
I like your excerpts idea, but I feel like having half the line feels like a bug. the way I've used it in my games is to make the lines generic, there only to convey the feeling of the speaker.

> Hey! This is my friend Pete! He is new in town, want to help me show him around?

would now be accompanied with a voice file like:

> "Hey!" (a greeting line)
> OR
> \*friendly laughter\* (to show the speaker is in an good mood).

I prefer this because:

1. The voices are reusable.
2. It's nice on the wallet.
3. You can completely avoid the pronoun dilemma.
4. It's future-proof. You can make changes to the script later an not have to rerecord.

**Partially voicing the game**
By only voicing the main events in the game, you can limit the amount of reworking you'll need to do to only the ones that really count, and you'll be able to freely use pronoun variables in non-voiced sections. You can combine that with excerpts to give the game a more voiced feel to it if you want, too.
> -1 votes

---
Tags: voice, user-generated-content
---


# Question
Title: Generating Realistic Looking Wire in Unity
I'm designing a game that involves the simulation of a breadboard. I would like some advice on the best way to simulate jumper wires used to connect various places on the breadboard together. I have provided a picture below for those unfamiliar with electronics.

These are the wires I would like to simulate. I would like them to dynamically adjust in length based on the distance of the connection points, and with some randomness (so hopefully wihout a perfect curve from point A to B). To be clear, the wires to not need to move dynamically, they just need to generate once.

If realistic randomness is not possible, what would be the best way to achieve even something like a smooth curve of wire from point A to B?

# Answer
*Assuming* only breadboard connection points which go straight down into the board (and at no other angle, such as connectors off to the side of the breadboard), there is a simple solution. Note that here I am talking only about the points needed to create the core of the wire path, not the renderable geometry itself.

First, consider the board top down and draw straight lines between the connection points. This step enables you to determine potential wire crossings. Add any unique crossed pairs to a list, for checking against one another, later.

Now, viewed side-on, you want to avoid crossings AND have a more wirelike (curved) profile, such that the connection curves from point A on the board, up, over and down to point B.

So what we do is to take that line and turn it into a semi-circle. (Formulae for getting points on a circle at various incremental radii can be found all over the internet.)

Great. Since most pairs of connections will not have the same length (in 2D), then even if these intersect on the top-down drawing, they usually (!) will not intersect side-on, because the different lengths lead to different radii which lead to different wire curvature.

**If intersections of wires matter to you...**

However, in some cases you may have an intersection. Though these will be rare (and rarer the thinner the final wire geometry is), if this does matter to you, you will need to check all cylindrical segments of each pair stored above, against one another, and determine if there are intersections - this could be costly, but it sounds like you are building your wires once-off. What you need to do here is scale the set of semi-circular vertices such that is is more elliptic. This perturbation needs to occur until they no longer intersect. To check whether two wires intersect, consider the diagram from top-down again: if the height of the two arcs is the same where the two 2D / overhead lines intersect, then you need to shift one or the other arc, accordingly.

**Final cosmetic effects**

Note that making these curves more elliptic may also be something you do just to get every wire looking a bit different, so it's not all too uniform. As a bonus step, you could also, instead of just using a semi-circle across the distance, use two rounded corners going down into the breadboard, and a straight section between.

Beyond this, with linear segments, perturbations etc. are yours to make as you wish, for example if you wanted a wire to look like it had been fiddled with by hand.
> 2 votes

---
Tags: unity, procedural-generation, simulations
---


# Question
Title: How to correctly implement custom tick system?
I am making a custom tick system to suit my needs (calling normal ticks every 0.2 seconds, medium ticks every 5 seconds etc...)

I followed the tutorial in this video: CodeMonkey tick system tutorial

In his tutorial, he implements the tick counting as shown:

```
    private const float tickTimerMax = 0.2f;

    private void Update()
    {
        tickTimer += Time.deltaTime;

        if (tickTimer >= tickTimerMax)
        {
            tickTimer -= tickTimerMax;
            Tick++;

            // Happens every 0.2 seconds.
            OnTick?.Invoke(this, new OnTickEventArgs {Tick = Tick});
        }
    }

```

However, in other sources I have seen that instead of subtracting `tickTimerMax` from `tickTimer`, we just straight up set the `tickTimer` to 0, as shown:

```
if (tickTimer >= tickTimerMax)
    {
        tickTimer = 0;
        Tick++;
    }

```

It's hard to say if there's a big difference between these two methods, because at first glance they seem to do the same thing, but clearly they have their differences. So I'm wondering, which one I should use?

# Answer
> 13 votes
The second solution will perform slightly less ticks than expected over time, because when `tickTimer` is slightly larger than `tickTimerMax` (which is almost always going to happen due to floating point inaccuracies), then the remaining time gets discarded. Those differences accumulate. So when your game runs for a minute and you check how many 0.2 second ticks were processed, you might notice that they were in fact less than 300.

The first solution is more accurate, because any time left will be credited to the next interval. But of course you don't always need accuracy. The inaccuracies get larger with worse framerate. So when the system you are triggering here is computationally expensive but not actually that important, then one could argue that dropping it more frequently when the framerate is already bad might be a feature and not a bug.

By the way, there is another option which I often use. Replace the `if` with a `while`:

```
private void Update()
{
    tickTimer += Time.deltaTime;
    while (tickTimer >= tickTimerMax)
    {
        tickTimer -= tickTimerMax;
        Tick++;
        OnTick?.Invoke(this, new OnTickEventArgs {Tick = Tick});
    }
}

```

This covers the edge-case that a lag-spike resulted in a frame taking longer to render than multiple intervals. In that case the while-loop results in multiple ticks being performed in a loop in order to make the simulation catch up with the lost time. This solution is preferable when you really want to avoid the simulation from lagging behind.

A word of warning, though: When `tickTimerMax` is 0 or negative, then the script will be caught in an infinite loop. That usually means you need to kill Unity and restart it, which might result in losing unsaved work.

---
Tags: unity, events, time
---


# Question
Title: Understanding this terrain intersection algorithm
I was looking for a fast way to get a ray intersection point of a terrain defined by a heightmap and I stumbled upon this: https://publications.lib.chalmers.se/records/fulltext/250170/250170.pdf

At part 3.2, I don't quite understand why we would get an intersection point in the beginning of the while loop, since it starts with the first quadtree node which is basically the whole map. Thus, there shouldn't be an intersection point with the ray (except if the ray starts out of AABB, higher than the max height of the terrain but that is never the case for me).

# Answer
> There shouldn't be an intersection point with the ray (except if the ray starts out of AABB, higher than the max height of the terrain but that is never the case for me).

It sounds like you're using "intersection point" here to mean "a point where the ray *enters* the AABB from *outside* the AABB volume".

But the paper uses a different definition of intersection, described on page 4:

> ...efficient ray-AABB intersection is possible by utilizing the slab method. With this method, the AABB is conceptually surrounded by pairs of parallel planes and the ray is clipped against each pair (see Figure 2.3). If any portion of the ray still exists after clipping, the ray intersected the AABB.

So here they're really talking about an "intersection *span*" - a *segment* of the ray that is contained inside the AABB volume.

A ray that starts inside the AABB enclosing your whole terrain will always have a span intersecting the volume in this way, even if it lacks an entry point, because the span from its origin to its exit point will remain after the clipping operation described above.

A ray with no span intersecting the AABB is one that misses the AABB entirely - in these cases it is safe to not subdivide the node to check for intersections with its children, because we know there will be none.

So, this means we continue iterating the loop and splitting nodes as long as there is a potential intersection to find, and stop only when further intersections with the terrain are impossible, because the ray has no overlap at all with the other bounding boxes.
> 0 votes

---
Tags: algorithm, terrain, intersection, quadtree
---