# Question
Title: How to call a function in response to a Button's OnSelect event?
I'm new to Unity and C# and have been struggling to figure out how to solve this. What I'm looking for is a way to make text display whenever a button is selected. (ex. Player selects a difficulty option, and text pops up describing what mechanics the difficulty will affect) I can get this to work with mouse input with no issue, with the following code attached to the button.

```
void Update()    {
        if (this.IsHighlighted() == true)
        {
            gameObject.transform.GetChild(1).gameObject.SetActive(true);
        }
        else
        {
            gameObject.transform.GetChild(1).gameObject.SetActive(false);
        }
}

```

The aforementioned description text is set up as a child to the button, and will appear/disappear depending on whether it's highlighted or not. The problem is that `isHighlighted` only occurs when the mouse is hovered over the button, and does not take effect when selected via directional inputs from a keyboard/controller, which is what I'm looking for. I've done some research and noticed there is an `OnSelect` method, but I can't figure out how to implement it. Any advice would be greatly appreciated.

# Answer
**Edit:** I added the OnSelect version.

Note that selecting and highlighting / hovering are two different things. When you hover over your button with mouse, OnPointerEnter will be triggered (if using Color Tint transition, Highlighted color will be also activated), and when you exit the Button, OnPointerExit will be triggered. But when you click a Button or navigate to it with keyboard, it is selected and when you click elsewhere or navigate away from your Button, it gets deselected.

So I think you might have to think about your highlighting / hovering if you want to make it work for different navigation styles. When using mouse one doesn't expect he/she has to click a button to see a tooltip.

To detect Button select with ISelectHandler (this should work for at least keyboard and mouse):

```
public class ButtonTest : MonoBehaviour, ISelectHandler
{
    public void OnSelect(BaseEventData eventData)
    {
        Debug.Log("selected");
    }
}

```

And seems like you also might need deselect, if that is the case, then you can also implement IDeselectHandler:

```
public class ButtonTest : MonoBehaviour, ISelectHandler, IDeselectHandler
{
    public void OnSelect(BaseEventData eventData)
    {
        Debug.Log("selected");
    }

    public void OnDeselect(BaseEventData eventData)
    {
        Debug.Log("deselected");
    }
}

```

If you want to detect cursor hovering over your Button use IPointerEnterHandler / IPointerExitHandler:

```
public class ButtonTest : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler
{
    public void OnPointerEnter(PointerEventData eventData)
    {
        Debug.Log("pointer enter");
    }

    public void OnPointerExit(PointerEventData eventData)
    {
        Debug.Log("pointer exit");
    }
}

```

You will also have to add a using statement for UnityEngine.EventSystems for these to work.

If you want to detect Button select without using ISelectHandler and IDeselectHandler, you could also do this in your Update:

```
void Update()
{
    if (EventSystem.current.currentSelectedGameObject == this.gameObject)
    {
        Debug.Log("selected");
    }
}

```
> 3 votes

# Answer
On latest 2021+ unity versions this can be achieved easier on the editor by adding a component on the button gameobject called Event trigger, from there you can choose the event you want to trigger. Select, deselect, drag , ... and add the function you want to perform on each event
> 1 votes

---
Tags: unity, c#, events, unity-ui
---


# Question
Title: Mouse Ray Picking: Z-Coordinate of Projected vector (glm::unproject)
I've run into a curious issue when implementing ray picking in my game engine. It seems the Z coordinate of the Projected matrix has to be ever so slightly more than `1.0f`.

I was having some issues when doing ray-triangle picking. When trying to pick an object, the cursor was just a few pixels off from where the ray would end up going. I tried looking for a pattern (if it got more off the further from the center, à la FOV/perspective projection issue) but couldn't find one.

I made sure that all changes to the perspective matrix throughout the code base were the exact same (specifically the near and far planes).

I finally started messing around with the Z coordinate of the projected vector. I had it as `1.0f`, but after trial and error, changed it to `1.00001f` and now everything works great, and the ray-picking is super accurate.

Here is my code for generating the world coordinates (ctx is the renderer context that holds relevant information like the projection matrix, width/height, etc.):

```
glm::vec4 viewport(0.0f, 0.0f, ctx.width, ctx.height);
glm::mat4 projection = ctx.projection;
glm::mat4 model_view = camera.get_view_matrix();
glm::vec3 projected = {
    mouse.x,
    ctx.height - mouse.y,
    1.00001f
};

glm::vec3 unprojected = glm::normalize(glm::unProject(projected, model_view, projection, viewport));

```

When I change the projected vector to:

```
glm::vec3 projected = {
    mouse.x,
    ctx.height - mouse.y,
    1.0f
};

```

everything seems to be slightly off. I'm wondering if there's an explanation as to what could be causing this? Surely it wouldn't just be a floating point rounding error, but I can't seem to find another reason.

# Answer
> 0 votes
I believe I found a solution here. The solution was actually calculating the near plane (where Z = 0) and the far plane (Z = 1...what I'm currently doing) and subtracting them. I was experiencing the same phenomena as the linked thread.

---
Tags: c++, opengl, camera, raycasting, glm
---


# Question
Title: Does OpenGL have any automatic texture interpolation?
An image of a minecraft grass block in gimp:

Loading from a texture atlas in OpenGL, gives a much blurrier image:

I know that the actual image in my glfw window is larger than it is in gimp. (640x640 window, 64x64 image in gimp) Is it possible that OpenGL is seeing this increase in size, and automatically interpolating the image, not keeping the sharpness between "pixels" on the block?

I am a beginner with OpenGL, so any suggestion on how to fix this would be appreciated.

# Answer
# Texture filters

When creating a texture buffer you can set the pixel lookup method via the glTexParameteri call. See link for full details.

Example creates texture handle and set the pixel lookup filter used when reading pixels from the texture.

```
GLint lookup = GL_NEAREST; // gives pixelated render Does not interpolate
                           // or GL_LINEAR for smooth, the default setting
GLuint hdl;
glGenTextures(1, &hdl);
glBindTexture(GL_TEXTURE_2D, hdl);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, lookup);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, lookup);

```
> 1 votes

---
Tags: opengl, textures, texture-atlas, glfw
---


title: Sobotka's AgX in Godot 4?

text:
# Question
Title: Sobotka's AgX in Godot 4?
Is it possible to use a custom OCIO called AgX in Godot 4? Has anyone ever tried something like this and succeeded?

# Answer
> 2 votes
As per this post regard ACES/OCIO on imported textures:

> Godot doesn’t support color management yet (or customizing tonemapping on import for HDR textures). Customizing tonemapping on import may be feasible with a custom script or import plugin.

That's the only hit I found searching the Godot forums for OCIO and searching the official documentation gave zero hits. Godot isn't listed on the game engine list at the Open Color IO homepage. So my assumption is that it's still currently unsupported. Based on this pull request it looks like adding AgX @Calinou options to the Godot Environment is under active development though.

As mentioned in the forum post, it might be may be feasible to do something via a script or plugin. I wasn't able to turn up an example, but that doesn't mean it can't be done or hasn't been tried. You might be able to use the color correction development demo to build something yourself, but based on some on the feedback in the pull request (linked earlier in the answer), it presently seems like the AgX results aren't meeting expectations yet.

---
Tags: godot, godot-4
---


# Question
Title: Why do you use logarithmic curve to fix distortion of texture?
I'm a noob shader learner, and I came across this question about animated shaders in Unity: Animated textures for models; How to write a shader?

After reading the answer, I kind of understood the concept of using polar coordinate to animate circular movement of texture. What I failed to comprehend was how the `log()` function reduces the distortion of texture. So my question, is how does `log` help the image scale up linearly (not sure if it's the right terminology)?

Here's the shader code from the link just in case.

```
fixed4 frag(v2f i) : SV_Target
{
    float2 polar = float2(
           atan2(i.uv.y, i.uv.x) / (2.0f * 3.141592653589f), // angle
           log(dot(i.uv, i.uv)) * 0.5f                       // log-radius
        );

    // Check how much our texture sampling point changes between
    // neighbouring pixels to the sides (ddx) and above/below (ddy)
    float4 gradient = float4(ddx(polar), ddy(polar));

    // If our angle wraps around between adjacent samples,
    // discard one full rotation from its value and keep the fraction.
    gradient.xz = frac(gradient.xz + 1.5f) - 0.5f;

    // Copy the polar coordinates before we scale & shift them,
    // so we can scale & shift the tint texture independently.
    float2 tintUVs = polar * _TintTex_ST.xy;
    tintUVs += _ScrollSpeeds.zw * _Time.x;

    polar *= _MainTex_ST.xy;
    polar += _ScrollSpeeds.xy * _Time.x;

    // Sample with our custom gradients.
    fixed4 col = tex2Dgrad(_MainTex, polar,
                           _MainTex_ST.xy * gradient.xy,
                           _MainTex_ST.xy * gradient.zw
                         );

    // Since our tint texture has its own scale,
    // its gradients also need to be scaled to match.
    col *= tex2Dgrad(_TintTex, tintUVs,
                          _TintTex_ST.xy * gradient.xy,
                          _TintTex_ST.xy * gradient.zw
                         );

    UNITY_APPLY_FOG(i.fogCoord, col);
    return col;
}

```

# Answer
This comes from trying to make each tile of the image maintain the same width:height aspect ratio as we reduce in size toward the center of the funnel.

Let's take a swatch of this endless pattern, and look at one ring of texture repeats where the top of the tiles sits exactly on the unit circle (in yellow):

A single tile in this ring has a width \\$w\\$ along its curved top edge, and a radial height \\$h\\$. Its bottom edge is shorter, because the image tapers in toward the center - let's express it as some fraction of the top width we'll call \\$a\\$.

Now we want to ask, how big is the next tile down the funnel? Well, we know its top width is \\$aw\\$, since its top is the previous tile's bottom. That means, if we want to maintain the same aspect ratio as the original tile, the height has to be \\$ah\\$ (if we multiplied the width by \\$a\\$, we have to do the same to height to keep it in the same proportion).

By the same argument, we can conclude the third tile down in this stack must be \\$a^2w \times a^2h\\$, and the one after that \\$a^3w \times a^3 h\\$

In other words, we have an exponential progression: the height of the \\$i^{th}\\$ tile down from our unit circle row is \\$h\_i = a^i h\\$.

By a similar argument, we can show the radius at which we'll find the \\$i^{th}\\$ row of tiles is also an exponential function of the tile number \\$i\\$.

But in the shader, we want to do the *opposite*: we already know the radius from the center for the pixel being shaded, and we want to figure out which tile that is, to sample the texture at that offset. **So we use the inverse of the exponential function, the logarithm**.

(In the code I showed in my previous answer, I actually take the logarithm of the *square* of the radius, knowing that the logarithm of the square is just twice the logarithm of the original, and halving the answer after the fact is faster than a square root. There are some extra constant factors if you do the full math treatment, but we don't really care about those because they just end up as a scale/shift, and can be subsumed into our texture scaling/scrolling animation anyway)

You'll find this "do the opposite operation" is common when doing texture transformations in a shader, because you're manipulating the function's domain, not its range. So if I want a texture to look twice as big, I halve the uv coordinates. If I want it to be half as big, I double the uv coordinates. If I want the texture to tile exponentially, I adjust the uv coordinates logarithmically.
> 3 votes

---
Tags: unity, shaders, hlsl
---


# Question
Title: How to make an authoritative server assign turn order numbers to players once they join?
I'm having trouble developing and understanding Server code. Currently, I'm trying to have each person that joins the Server be given a single digit ID that can then be used for determining turn order and a number of other things (ex: specify whose card to place where). As it stands, I tried a few versions, but the debug message indicating who should go first doesn't print and couldn't think of a way for it to run DetermineFirstPlayer() after both players join in after the server is already existing.

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

public class ServerManager : NetworkBehaviour
{
    // SyncVars for game state variables
    [SyncVar]
    private List<Player> players = new List<Player>();

    [SyncVar]
    public int playerNum = 0;

    //Reference to the Player
    public Player player;

    // Reference to the TurnManager
    public TurnManager turnManager;

    // Other game state variables
    private List<Card> drawStack = new List<Card>();
    private List<Card>[] playerHands;
    private List<Card>[] playerBoard;
    private List<Card> graveyard = new List<Card>();
    private int currentPlayerIndex = 0;

    //Starts server (Host + Client)
    [Server]
    public override void OnStartServer()
    {
        base.OnStartServer();

        //Tells us that the server is running
        Debug.Log("OnStartServer was activated");
    }

    // Start is called before the first frame update
    void Start()
    {
        // Find a reference to the TurnManager
        turnManager = GameObject.Find("TurnManager").GetComponent<TurnManager>();
    }

    //Runs whens Server stops running
    [Server]
    public override void OnStopServer()
    {
        base.OnStopServer();

        //Tells us that the server is running
        Debug.Log("OnStartServer was deactivated");
    }

    //Starts when client button pressed
    public override void OnStartClient()
    {
        base.OnStartClient();
        //Message to show that client is running; appears in console tab
        Debug.Log("OnStartClient was activated");

    }

    //Runs when Client disconnects or leaves
    public override void OnStopClient()
    {
        base.OnStopClient();
        //Message to show that client is not running; appears in console tab
        Debug.Log("OnStartClient was deactivated");
    }

}

```

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

public class TurnManager : NetworkBehaviour
{
    List<NetworkIdentity> _identities = new List<NetworkIdentity>();
    private int _currentPlayerIndex = 1;
    [SyncVar(hook = nameof(NextTurnEvent))] public uint currentPlayer = 0;
    public UnityEvent<uint> nextPlayer;
    public UnityEvent<NetworkIdentity, int> playerRegisteredEvent;

    // Track the number of players that have joined
    private int playersJoined = 0;

    private void Start()
    {
        gameObject.name = "TurnManager";
        if (isServer) _identities.Add(null);
    }

    [Server]
    public void RegisterPlayer(NetworkConnectionToClient connection)
    {
        //Handle here if reconnects can happen
        Debug.LogFormat("Payer added: {0}", connection.identity);

        _identities.Add(connection.identity);
        playerRegisteredEvent?.Invoke(connection.identity, GetPlayerTurn(connection));

        // Increment the count of players that have joined
        playersJoined++;

        // If all players have joined, print the current number of players and whose turn it is
        if (playersJoined == 2)
        {
            Debug.LogFormat("Both players have joined. Current number of players: {0}", playersJoined);
            Debug.LogFormat("Current turn: {0}", currentPlayer + " player");
        }
    }

    [Server]
    public void NextPlayer()
    {
        _currentPlayerIndex++;
        if (_currentPlayerIndex >= _identities.Count) _currentPlayerIndex = 1;
        currentPlayer = _identities[_currentPlayerIndex].netId;
    }

    [Server]
    public bool IsCurrentTurn(NetworkConnectionToClient connection)
    {
        if (_identities[_currentPlayerIndex] == connection.identity) return true;
        //Sent a message to the client the action is out of turn
        //_errorManager.TargetErrorMessage(connection, "Not your turn");
        return false;
    }

    [Server]
    public int GetCurrentPlayerIndex()
    {
        return _currentPlayerIndex;
    }

    [Server]
    public uint GetPlayerByIndex(int index)
    {
        return _identities[index].netId;
    }

    public int GetPlayerTurn(NetworkConnectionToClient connection)
    {
        return _identities.IndexOf(connection.identity);
    }

    void NextTurnEvent(uint oldPlayer, uint newPlayer)
    {
        nextPlayer?.Invoke(newPlayer);
    }
}
}

```

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

public class Player : NetworkBehaviour
{
    // References to game objects
    public GameObject PlayerCard;
    public TurnManager turnManager;

    public GameObject Hand;
    public GameObject Deck;

    public List<GameObject> DropZones = new List<GameObject>();

    // Variables for game state
    public int Health;
    public int CardsPlayed = 0;
    public bool IsMyTurn = false;

    // Start is called before the first frame update
    void Start()
    {

            // Initialize references to game objects
            Hand = GameObject.Find("AllyHand");
            Deck = GameObject.Find("Deck");

            // Connect drop zones to the list
            DropZones.Add(GameObject.Find("AllyDropZone"));
            DropZones.Add(GameObject.Find("AllyDropZone (1)"));
            DropZones.Add(GameObject.Find("AllyDropZone (2)"));
            DropZones.Add(GameObject.Find("AllyDropZone (3)"));
            DropZones.Add(GameObject.Find("AllyDropZone (4)"));
            DropZones.Add(GameObject.Find("AllyDropZone (5)"));

            // Find a reference to the TurnManager
            turnManager = GameObject.Find("TurnManager").GetComponent<TurnManager>();
    }

    public override void OnStartClient()
    {
        base.OnStartClient();

        CmdRegisterPlayer();
    }

    [Command]
    void CmdRegisterPlayer(NetworkConnectionToClient sender = null)
    {
        turnManager.RegisterPlayer(sender);
    }

}

```

# Answer
> 5 votes
The server needs to know who is playing. The easiest way to do that is let the players report themself. When your game gets bigger, games usually use google, facebook or some custom login for telling who they are. But there is a way easier option for small games/ prototyping. Device Authenticator uses the `SystemInfo.deviceUniqueIdentifier` to identify the client.

This is one of my old Turnmanagers, you can remove the events for direct methods and make your own error manager if you want to inform clients for invalid actions or out of turn commands

```
public class TurnManager: NetworkBehaviour {

    List<NetworkIdentity> _identities = new List<NetworkIdentity>();
    private int _currentPlayerIndex = 1;
    [SyncVar(hook = nameof(NextTurnEvent))] public uint currentPlayer = 0;
    public UnityEvent<uint> nextPlayer;
    public UnityEvent<NetworkIdentity, int> playerRegisteredEvent;

    private void Start() {
        gameObject.name = "TurnManager";
        if (isServer) _identities.Add(null);
    }

    [Server]
    public void RegisterPlayer(NetworkConnectionToClient connection) {
        //Handle here if reconnects can happen
        Debug.LogFormat("Payer added: {0}", connection.identity);
        _identities.Add(connection.identity);
        playerRegisteredEvent?.Invoke(connection.identity, GetPlayerTurn(connection));
    }

    [Server]
    public void NextPlayer() {
        _currentPlayerIndex++;
        if (_currentPlayerIndex >= _identities.Count) _currentPlayerIndex = 1;
        currentPlayer = _identities[_currentPlayerIndex].netId;
    }

    [Server]
    public bool IsCurrentTurn(NetworkConnectionToClient connection) {
        if (_identities[_currentPlayerIndex] == connection.identity) return true;
        //Sent a message to the client the action is out of turn
        //_errorManager.TargetErrorMessage(connection, "Not your turn");
        return false;
    }

    [Server]
    public int GetCurrentPlayerIndex() {
        return _currentPlayerIndex;
    }

    [Server]
    public uint GetPlayerByIndex(int index) {
        return _identities[index].netId;
    }

    public int GetPlayerTurn(NetworkConnectionToClient connection) {
        return _identities.IndexOf(connection.identity);
    }

    void NextTurnEvent(uint oldPlayer, uint newPlayer) {
        nextPlayer?.Invoke(newPlayer);
    }
}

```

The idea is, each player calls something like

```
[Command]
void CmdRegisterPlayer(NetworkConnectionToClient sender = null) {
    _turnManager.RegisterPlayer(sender);
}

```

This should happen once, maybe from the title screen on the Play Game button or search for opponent. Normally this should point to some kind of lobby which we are skipping for simple games.

An example for an user action - end turn - would look this

```
[Command(requiresAuthority = false)]
public void CmdEndTurn(NetworkConnectionToClient connection = null) {
    EndTurn(connection);
}

[Server]
private void EndTurn(NetworkConnectionToClient connection) {
    if (!_turnManager.IsCurrentTurn(connection)) return;
    ...
    //code that handles your turn end
}

```

The client can't end the turn on its own. It just sends the request to the server with his connection. The turnmanager checks, if its the players turn. Only if thats true, continue with the action.

As for your question when to actually start the game, you can use the `RegisterPlayer` method server side to check each time how many people are already registered and once the amount is reached for your game, call the server method of StartGame logic.

---
Tags: unity, c#, client-server, mirror-networking
---


title: How to show your game vision?

text:
# Question
Title: How to show your game vision?
I am developing a game and have a clear vision of how it works, what key features it has and how it should look alike.

But when it comes to introduce the designer I feel a little bit lost. I have no graphics talent so I try to pitch it with mockups and text.

But I guess there are better ways or methods to get it on paper - how would they look like?

# Answer
> 2 votes
Most gaming companies create a Game Design Document (GDD). Its purpose is to contain all aspects of the game before actual development starts. It's mostly text, but it can contain rough sketches (mine have been just boxes with labels representing objects) to help give visual for how the game should play out. A GDD usually includes other parts of development, such as art style, target audience and target platform.

When my friends and I started working on a game project the first thing we did was create an elaborate GDD, and we found it a very good way to organize our thoughts through the design phase. A GDD isn't just for giant studios, it can help Indie developers too, group or single.

There are many online tutorials and examples for writing a GDD, a quick search should give you many resources to reference.

# Answer
> 0 votes
The above answer is really good, but generally look at how you want the gameplay loop to be is what I’ve been doing for a while. Making a flowchart is amazing. if you want your game to be going around slashing monsters apart until you reach the win condition, your flowchart can be like

start—\>go to nearest monster—-\>kill—\>repeat until \[win condition\]

you can even scale it up by drawing it into huge designs. There is a meme known as “flowchart ken” it’s funny but more importantly, it accurately describes gameplay for street fighter. You can make a flowchart for any game. Try making one for your desired game. happy creating!

---
Tags: game-design, graphics-design
---


# Question
Title: How to allow replaying levels in story mode
I'm working on a game that focuses on a campaign/story mode for the majority of the content; the player progresses their character, collecting items/currency/upgrades along the way, and playing levels in a strictly sequential order. For most players, simply having a "Continue" button that throws them into the next level should work just fine, but I want to give players the option to replay an earlier level that they enjoyed before.

However, I'm struggling to come up with a way to conflate this "Level Select" ability with the (persistent) progression of the player character:

* How do I avoid the player accumulating more currency and items by playing old levels (potentially misbalancing the difficulty of later levels)?
* How do I deal with "future" upgrades that the player acquired in later levels that should not be available in the earlier level yet?
* How to "lock in" decisions that the player makes that might affect the story later on in the campaign?

I noticed some games with a campaign structure opt to deal with all this by simply loading an older savestate, essentially going back in time and undoing all progress made in later levels, but this feels overly destructive to the players who might just want to replay a cool boss battle without losing their overall progress.

Another option I thought of would be to run previously completed levels in a "replay" mode that does not save any progress, but this feels a bit inelegant, and might not be what the player expects.

I'm looking for advice on how to approach this in a way that feels right to the player, maybe how other games typically solve this, and (if needed) how to communicate the mechanic to the player.

# Answer
One game that handled savegames in a way I find really elegant is *Papers Please*:

The way the savegame system operates should remind every software developer of how version control systems like git work:

* The game auto-saves after every level (or "day" in the narrative of the game)
* All the previous level autosaves of every run are easily accessible on the "load game" screen.
* When the player continues from a previous level, the savegame history "branches". The savegame history of both branches is preserved separately.

That means the player can easily replay any previous level from the gamestate they had at the start of that level, make different choices, and then either continue the story from there or return to their old savegame branch.
> 7 votes

# Answer
For currency the first question is if the total amount of currency available in a level is fixed or whether it is somewhat random.

If the game is more puzzle like and the amount is fixed, then a replay just gives you another attempt to find more and the bigger value is used. If on the first play through you found 15 out of 20 and in the replay you found 18, then you have 3 more. This should be balanced because people may find all 20 as well. This would encourage replaying because missing too much currency will make later levels too hard.

If the total amount is somewhat random then I think you just have to balance the game in a way that allows for gathering more currency be replaying. If the amount available per level increases sufficiently fast it doesn't disturb the balance much. Carefully consider how many replays you want to encourage the player to do, too many quickly get tedious.

For future upgrades I would recommend to just make it a feature. Using later upgrades you can access places in earlier levels that you couldn't access the first time you played them. It is meant to be that way and allows reusing levels and discovering little secrets.
> 0 votes

# Answer
> However, I'm struggling to come up with a way to conflate this "Level Select" ability with the (persistent) progression of the player character:
>
> * How do I avoid the player accumulating more currency and items by playing old levels (potentially misbalancing the difficulty of later levels)?
> * How do I deal with "future" upgrades that the player acquired in later levels that should not be available in the earlier level yet?
> * How to "lock in" decisions that the player makes that might affect the story later on in the campaign?”

The problem with making story heavy games is that the choices you make should be and are permanent. Unless there is a story explanation for him somehow being able to reenter previous levels.
> 0 votes

---
Tags: game-design, progression
---


# Question
Title: I want to change the direction of my platform from z direction to y direction alternatively
So basically, I want my platform to move first on the z axis from `start` position to `end` position, and then from `end` position to `start` again. Now after reaching `start`, it should change its direction to the y axis, repeat the same motion (`start` to `end` to `start`) and then change direction back to the z axis. But I can't seem to do it.

Can anyone please help me achieve this in UE5?

```
// Sets default values
AMovingPlatform::AMovingPlatform()
{
    // Set this actor to call Tick() every frame.  You can turn this off to improve performance if you don't need it.
    PrimaryActorTick.bCanEverTick = true;
}
// Called when the game starts or when spawned
void AMovingPlatform::BeginPlay()
{
    Super::BeginPlay();
    StartLocation = GetActorLocation();

    UE_LOG(LogTemp, Display, TEXT("Hello"));
}
// Called every frame
void AMovingPlatform::Tick(float DeltaTime)
{
    Super::Tick(DeltaTime);

    MovePlatform(DeltaTime);
    RotatePlatform(DeltaTime);
}
void AMovingPlatform::MovePlatform(float DeltaTime) {
    if (ShouldPlatformReturn()) {

        FVector MoveDirection = PlatformVelocity.GetSafeNormal();
        StartLocation = StartLocation + MoveDirection * MoveDistance;
        SetActorLocation(StartLocation);
        PlatformVelocity = -PlatformVelocity;
    }
    else {
        if (ShouldChangeDirection()) {
            PlatformVelocity = FVector(0, 600, 0); // Change direction
            FVector MoveDirection = PlatformVelocity.GetSafeNormal();
            StartLocation = StartLocation + MoveDirection * MoveDistance;
            SetActorLocation(StartLocation);
            PlatformVelocity = -PlatformVelocity;

        }
        FVector CurrentLocation = GetActorLocation();
        CurrentLocation = CurrentLocation + (PlatformVelocity * DeltaTime);
        SetActorLocation(CurrentLocation);
    }
}
void AMovingPlatform::RotatePlatform(float DeltaTime) {

    AddActorLocalRotation(RotationVelocity * DeltaTime);

}

bool AMovingPlatform::ShouldChangeDirection() const {

    float Epsilon = 10.0f; // Adjust this value to account for floating-point precision
    return GetDistanceMoved() > MoveDistance - Epsilon;
    //return StartLocation == GetActorLocation();
}

bool AMovingPlatform::ShouldPlatformReturn() const {
    return GetDistanceMoved() >= MoveDistance;
}

float AMovingPlatform :: GetDistanceMoved() const {

    return FVector::Dist(StartLocation, GetActorLocation());
}
// Fill out your copyright notice in the Description page of Project Settings.

#pragma once

#include "CoreMinimal.h"
#include "GameFramework/Actor.h"
#include "MovingPlatform.generated.h"

UCLASS()
class FAKEFALLGUYS_API AMovingPlatform : public AActor
{
    GENERATED_BODY()

public:
    // Sets default values for this actor's properties
    AMovingPlatform();

protected:
    // Called when the game starts or when spawned
    virtual void BeginPlay() override;

public:
    // Called every frame
    virtual void Tick(float DeltaTime) override;

    UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="Moving")
    FVector PlatformVelocity = FVector(0,0,500);

    UPROPERTY(EDITANYWHERE, BlueprintReadWrite, Category = "Moving")
    float MoveDistance = 500;
    UPROPERTY(EDITANYWHERE, BlueprintReadWrite, Category = "Rotation")
    FRotator RotationVelocity;
    FVector StartLocation;

    UFUNCTION(BlueprintCallable)
        void MovePlatform(float DeltaTime);

    UFUNCTION(BlueprintCallable)
        void RotatePlatform(float DeltaTime);

    UFUNCTION(BlueprintCallable)
        bool ShouldPlatformReturn() const;

    UFUNCTION(BlueprintCallable)
        float GetDistanceMoved() const;

    UFUNCTION(BlueprintCallable)
        bool ShouldChangeDirection() const;
private:

};

```

# Answer
Use a spline member object and have the platform follow it.

I recommend making the spline member object blueprint editable and viewable, defaulting to None, in order to make life easier during level editing/creation.

How to make a spline: https://www.youtube.com/watch?v=eKIiWa19EMI
> 0 votes

---
Tags: c++, unreal, unreal-5, moving-platforms
---


# Question
Title: How do you effectively induce "berserk" player behaviour?
I have recently been wondering, how can you "induce player behaviour" in a video game

An example of what I am thinking of is when a player uses an ability like "rage" or "berserk" where their character should lose rationality, by using visuals and sound I want to make the player think less about strategy or tactics.

It would be similar to a status effect but it wouldnt be a status effect in the traditional sense. It would be something more psychological which makes the player (ie. the human playing the game) where it induces emotions. The status would not effect the avatar itself, it should change visuals and sound without getting in their way but still inducing a "behaviour" of not thinking through things before doing it.

How should I go about learning something like this and how should it be implemented to a game?

Keep in mind, the idea of "berserk" is simply an example, I intend to apply this to abilities which induce serenity, curiosity and calmness later on.

Is there a better way to define this in terms of game design?

Is there any place I can read about this in effect or something similar?

What are the positive and negative effects on both the game and the player when using this? How can it these effects be avoided or lessened over time?

# Answer
> 4 votes
## Reward and punishment.

If you want the player to behave in a certain way, then the two game design tools that are usually most effective are to reward the behavior you want and punish the behavior you don't want.

So how could you design a reward and punishment mechanic that encourages a particularly aggressive playstyle? You didn't even say what genre your game is in, so I can only guess what options you have in your design space. So I am just going to assume you are developing a game with a 3rd person hack&slash combat system like Dark Souls or God of War.

One thing you could do is reward the player for performing lots of attacks and/or kills in a short amount of time while under the "Berserk" condition. For example by giving them a temporary damage boost for it that grows even more the more they attack and kill, generating a positive feedback loop. Similar you could discourage defensive actions like blocking, dodging or running away by punishing the player for those actions. For example by taking away the damage bonus they accumulated through aggressive behavior.

You also need to make sure that any of the usual punishments you might have in place to discourage too aggressive behavior are mitigated or even removed while in the Berserk state. For example, when the player isn't supposed to dodge or block while in the Berserker state, then they need some other way to mitigate damage. So you might want to consider to grant them some damage reduction and stagger immunity as well while in that state.

If you do all this, then you might notice that the berserker state is indeed pretty overpowered: The player does more damage, takes less damage and doesn't need to concern themselves with damage mitigation. While such a power trip can be very satisfying for a short duration, allowing the player to be in that state permanently would trivialize the game. So you either need to limit the duration the player can spend berserking, or you need to add some incentive for *not* berserking. What incentive? Again, reward and punishment are the keys. Punish the player for spending too much time in the berserker state or reward them for overcoming challenges without using the berserker mode.

# Answer
> 0 votes
I can’t direct you to any studies or academic research but, generally you can look at things like the Persona series where the player loses “some” control of their character/party. When the “Rage” status is put on somebody they attack mindlessly at the person they were attacking. Depending on what genre you are looking for, maybe that’s the key for you.

On how to implement it with sound, music, and visuals depends. Do you want it to be a debuff? Something where you go “oh god how do i unangry” or something like doom where it’s an on command buff where you just remove all recast time(cooldown) on your abilities and just go haywire?

---
Tags: game-design, psychology
---


title: Lower Near Clipping Plane

text:
# Question
Title: Lower Near Clipping Plane
I've searched everywhere and can't really find a good answer... Even with my near clipping plane set to 0.01 the objects are clipping too close.

Tried to get a view where you can see it clipping a little... This camera is supposed to go into this tube, but if i put the camera into the tube, the sides of the cube clip away. I lowered the near clipping plane as much as it lets me, but it's not enough. Only thing i can think of is increasing the size of everything, which would be a pain to work with...

Someone else suggested overlaying a second camera and having a giant tube elsewhere in the scene, but this seems inefficient as it means i would need to have 2 people, 2 cameras, 2 tubes, and everything that happens to one would have to happen to the other...

Thanks in advance.

# Answer
The engine is not designed for scenarios like putting the rendering camera inside an endoscopy tube that is probably less than an inch in diameter. For one thing, the engine relies primarily on single-precision 32-bit floats, so you'd start to get jitter and other issues caused by floating-point precision error with a camera confined into such a tiny space.

Your best bet is indeed increasing the size of everything in the scene. This should not make the scene "a pain to work with"; in fact, it should be easier to work with, because you won't be fighting with the Editor trying to do things at a scale that it isn't designed for.

Rather than manually increasing the size of each object in the scene, you can scale the whole scene at once in the Editor like this:

1. Create an empty GameObject at world position (0,0,0) (let's call it the "container")
2. In the Hierarchy panel, move everything in the scene into that container
3. Increase the scale of the container.
4. If needed, you can then move everything out of the container, and it will keep the size and position that it had inside the container.

Unity assets are normally authored at a scale where 1 Unity unit = 1 meter. If you need to measure things precisely, it's best to increase the scale by 10 (so 1 unit = 10cm) or 100 (so 1 unit = 1cm).

Once you've scaled up your scene, you can simply zoom out the camera in the Scene view (using the mouse wheel) to make it easier to move around. Also keep in mind that you can double-click on any object in the Hierarchy panel to automatically focus the camera on that object; this will zoom the camera in or out as needed to account for the size of the object.
> 0 votes

---
Tags: unity, camera, clipping
---


# Question
Title: How to remove a shader (or material) from a particle system in Unity?
I bought a Unity asset that has a particle system that displays many small cubes flying around. Then, the creator of this particle system add their own shader (or material) at the end of the particle systems to set the colors of these cubes.

How do I remove this shader (or material) from the particle system ?

---

Here is a picture of a shader (or material) added to a particle system:

# Answer
> 1 votes
Unfold the "Renderer" sub-component at the bottom of the list.

Shader materials are used in rendering, so this is where you'll find material settings for the particle system.

Colour modulation can also be accomplished by the Star Color parameter in the top section of the particle system inspector, and Color Over Lifetime sub-component.

---
Tags: unity, shaders, particles
---


# Question
Title: What is the best way to create a location in Blender or Unity?
I am new to this, and the task before me was to create a laboratory location. Here I have a question, what is the best way to implement this? I've heard about Unity ProBuilder, but I've also heard the opinion that locations should be created in Blender. By laboratory building, I mean rooms (walls, floor, ceiling), as, for example, made in Black Mesa.

# Answer
The workflow I would use is:

1. Create the basic blockout (floors, walls, ceilings) in Unity using Pro Builder and/or Polybrush.
2. Place cubes in the blockout as stand-ins for furniture
3. Playtest the level to make sure it does its job from a gameplay perspective, probably making a couple adjustments regarding what to place where and if at all.
4. Create all the more detailed 3d objects (furniture, lab equipment...) in Blender.
5. Import the models into Unity and replace the placeholder cubes with the actual 3d models.
> 0 votes

---
Tags: unity, blender, level-design, 3d-modeling
---


# Question
Title: Tiled Map in Unity is Darker than in Tiled Editor
I have a problem rendering a Tiled Map in Unity (`.tmx` format): the Tiled Map is darker in Unity than in Tiled Editor.

I tried to change properties but got same result over and over. I will share the pictures, may you take a look and tell what exactly the problem is?

# Answer
Thanks to @DMGregory, I found solution !

The solution was changing the Player settings (Color Space -\> Gamma) Important: You need to Reimport Assets and all TMX files
> 1 votes

---
Tags: 2d, tiled2unity
---


# Question
Title: Avoiding string literals to reduce memory allocations
In Unity, should we avoid string literals in frequently executed methods (like `Update()`) to avoid unnecessary memory allocations and instead store string values into fields?

```
class TouchInputManager : MonoBehaviour
{
    // private const string messageVar = "OnFingerMove";
    /* ... */
    private void HandleFingerMove(Finger finger)
    {
        /* ... */
        gameObj.SendMessage("OnFingerMove");
        // vs.
        // gameObj.SendMessage(messageVar);
    }
}

```

I assume that the string literal "OnFingerMove" will allocate new memory on every frame. Will the compiler somehow optimize string literals to reduce garbage? I read some articles that suggest avoiding string concatenation in methods executed on every frame, so I started wondering if string literals would also create garbage in the heap.

# Answer
> 24 votes
A string literal in C# will be compiled to string literals in IL.

Then the IL is compiled to machine (or to C++ and then to machine code if you are using IL2CPP).

On machine code the strings constants should be placed on a data section and referenced where needed. *Note: it is not a requirement of the .NET standard that the string literals will be handled this way, but this is what happens in practice.*

*To be clear: you do not need to intern constants.*

Thus, using a string literal does not cause additional allocations. From a performance standpoint using a named constant or a literal should make no difference.

*It would only make a difference from a maintanability standpoint, if you use the same string literal in multiple places, creating a named constant allows you to change it in a single place (i.e. a single source of truth).*

# Answer
> 5 votes
There is a trick with strings called "interning" Which stores the string in a global pool and lets you get the same string object for the same string contents.

C# is defined to automatically intern all string literals:

> The intern pool conserves string storage. If you assign a literal string constant to several variables, each variable is set to reference the same constant in the intern pool instead of referencing several different instances of String that have identical values.

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


# Question
Title: Reduce processing time of image to shape
I'm making a simple game engine using Java and have found a major issue. To create accurate collision detection I decided to convert a transparent image into a `java.awt.geom.Area` object. However the method I'm doing this might be wrong or unoptimized.

To test it out, I tried loading an almost 200x200 (exactly 195x196) pixels image. I ran the program 5 times and this is the time it took

* 2900ms = 2s
* 2848ms = 2s
* 2999ms = 2s
* 2887ms = 2s
* 2871ms = 2s

**Average time**: 2,901ms
This isn't very good especially considering the size of the image.

Here is the code I am using:

```
public Entity(BufferedImage image) {
    this.image = image;

    entityArea = new Area();
    heightmap = new int[image.getWidth()];

    boolean heightFound = false;

    for (int x = 0; x < image.getWidth(); x++) {

        for (int y = 0; y < image.getHeight(); y++) {

            if((image.getRGB(x, y) & 0xFF000000) != 0) {
                entityArea.add(new Area(new Rectangle(x, y, 1, 1)));

                if(!heightFound) {
                    heightmap[x] = y;
                    heightFound = true;
                }
            }

        }

    }
}

```

`heightmap` is used to refer the top pixels for an entity

# Answer
This answer is based of off bornander's answer.

*"Using the `java.awt` packages will likely be a problem when it comes to performance."* \- The cause of the performance issue was `entityArea.add(new Area(new Rectangle(x, y, 1, 1)))`. Instead of using an `Area` object I used an array to create a transparency map as shown below

```
public Entity(BufferedImage image) {
    this.image = image;

    transmap = new int[image.getWidth()][image.getHeight()];
    heightmap = new int[image.getWidth()];

    boolean heightFound = false;

    for (int x = 0; x < image.getWidth(); x++) {

        for (int y = 0; y < image.getHeight(); y++) {

            if((image.getRGB(x, y) & 0xFF000000) != 0) {

                transmap[x][y] = 1;

                if(!heightFound) {
                    heightmap[x] = y;
                    heightFound = true;
                }
            }
            else
                transmap[x][y] = 0;
        }
    }
}

```

The average time when running the program 5 times changed from 2,901ms to 167ms.
> 0 votes

# Answer
Using the `java.awt` packages will likely be a problem when it comes to performance.

Even if you ignore the reading of the image (which I doubt is the bottleneck here), trying to add 200 * 200 = 40,000 `Area`s into a single `Area` will run slow.

This cut down example with high-light the performance problem (note that no image is used here);

```
    long start = System.currentTimeMillis();
    Area entityArea = new Area();
    for(int y = 0; y < 200; ++y) {
        for (int x = 0; x < 200; ++x) {
            entityArea.add(new Area(new Rectangle(x, y, 1, 1)));
        }
    }
    System.out.println(System.currentTimeMillis() - start);

```

For game-related code you are likely better off moving away from the `java.awt` packages and go for something optimized for gaming.
> 1 votes

# Answer
`.getRGB()` as a per pixel operation is slow. It can be okay if you're only sampling a few pixels, but looping over it for processing all the pixels in an image is significant performance bottleneck.

Instead of working directly on the `BufferedImage`, convert the image to an array and work with that:

```
byte[] pixels = ((DataBufferByte)image.getRaster().getDataBuffer()).getData();

```

Or consider wrapping the conversion in a helper class as shown here:

```
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;

public class FastRGB
{
    private int width;
    private int height;
    private boolean hasAlphaChannel;
    private int pixelLength;
    private byte[] pixels;

    FastRGB(BufferedImage image)
    {
        pixels = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();
        width = image.getWidth();
        height = image.getHeight();
        hasAlphaChannel = image.getAlphaRaster() != null;
        pixelLength = 3;
        if (hasAlphaChannel)
        {
            pixelLength = 4;
        }

    }

    int getRGB(int x, int y)
    {
        int pos = (y * pixelLength * width) + (x * pixelLength);
        int argb = -16777216; // 255 alpha
        if (hasAlphaChannel)
        {
            argb = (((int) pixels[pos++] & 0xff) << 24); // alpha
        }

        argb += ((int) pixels[pos++] & 0xff); // blue
        argb += (((int) pixels[pos++] & 0xff) << 8); // green
        argb += (((int) pixels[pos++] & 0xff) << 16); // red
        return argb;
    }
}

```
> 0 votes

---
Tags: java, collision-detection, optimization
---


# Question
Title: What’s the benefit of breaking code down into other classes?
Sorry if this isn’t the proper spot to ask, but something I struggle to wrap my head around is the benefit of breaking down code into smaller pieces on the surface it seems to make sense I think you get more control and scalability maybe? but then I actually write code and it’s difficult to tell what should and shouldn’t be put into its own class it kind of just seems like more work and things that can fail.

For example I’ve been stumped on managing resources in my engine loading meshes, textures, etc. What’s the difference between having a single manager class that knows how to load and get any asset vs a manager that just delegates the work to loader classes or something like that? Another example I can think of is having an asset class like a mesh that’s just a pod vs knowing how to load itself.

Looking for some clarification or advice on the subject which I guess falls under designing code?

# Answer
> 4 votes
A lot of design decisions come from the needs of your project, and your experience: e.g. "I've been burned before when I used approach X to accomplish Y, I had to re-write a lot of code to get Y in, and I had to write it using approach Z" -- in this situation, you'd use again approach Z when situation Y occurs.

> For example I’ve been stumped on managing resources in my engine loading meshes, textures, etc. What’s the difference between having a single manager class that knows how to load and get any asset vs a manager that just delegates the work to loader classes or something like that?

This is an example case, so I can address that specifically.

* Retrieving yourself within one class -- it may be easier to manager and remember where to look for things in smaller classes than it is in larger classes
* Side effects mitigation -- if you have a monolith class, and you edit the header file, chances are your header file is included in a lot of other files; in comparison, a smaller manager will likely be included in a lesser amount of files; so when you edit the header, the need for recompilation will be less painful. I agree this is not really an issue on smaller projects, but can be very annoying on bigger projects.
* Patterns -- We like patterns. They comfort us and allow us to think less. If you have a monolith manager, you'll likely find yourself with 2-3 patterns within the same class to load 4-5 types of assets. If you take out those functions into smaller managers, you can benefit from using some kind of interfaces and/or parent class that would abstract or take care of recurring patterns.
* Object swap/"dependency injection" -- Say you have to "manage sound", and you have your "sound managing" functions into your Monolith class, it's all fine until your program crashes because the sound device is broken/disabled on your system. You don't want it to crash, so you need to "do nothing about sound" when the device is broken. An easy approach when you use "smaller managers" is to check whether the sound device is operational, and based on that instantiate the correct class between SoundManager and SoundManagerMute, where the SoundManagerMute receives audio requests but does nothing about it.
* Memory/cache access -- In some situations, you'll want a tight management of the memory. It is generally easier to do with smaller scoped classes.
* Ease of team work -- When working with a team, everyone working on the Monolith class may cause headaches when you'll get to merge the code with your teammates'.

> Another example I can think of is having an asset class like a mesh that’s just a pod vs knowing how to load itself.

Again this is very specific. It can depend at first on personal preferences, what you've been taught and what you've learned, then it will be morphed into something based on the project needs and experience. You can use a class at first, then you'll realize that cache misses take a toll on the performances. Then you'll decide to go ahead with an ECS, in which situation we "act on data" and so the pod will naturally come to mind.

# Answer
> 2 votes
Software Architecture is all about creating and using **abstractions** to describe what we want the hardware to do.

For instance, you probably don't even think about the abstraction provided by a simple function call like `playVideo(introVideoAsset);` The `playVideo` function hides away a lot of details about how to decode a video stream, how to render that to the hardware, and so on. But before you even get to that, the compiler is going to choose a register to place `introVideoAsset` where the `playVideo` function is going to read it; it's going to store the memory location to return to once the video finishes playing; and it's going to jump to the correct memory location for the `playVideo` routine.

At the point where you're trying to play the intro video, you don't want to think about any of that, so you keep it all buried under several layers of abstraction.

Breaking code into classes has exactly the same aim: to allow you to express high-level relationships between different parts of your application. For instance, maybe you need to support loading multiple different texture formats, but you also need to support *using* a texture once it's loaded. If all the texture loading code is in its own class, you don't need to think about it when you're just using a texture; and when you *are* changing that class, you can see clearly which parts are "private", and can be changed without impacting other code.

The more code you have inside one function, or one class, the harder it is to reason at a high-level about that function or class. In an ideal world, you can just look at the name, and know immediately what its high-level purpose is. At the other extreme, a class called "Utilities" forces you to look at the list of methods it contains, because the name gives you no clue.

> it’s difficult to tell what should and shouldn’t be put into its own class

Yes, this is fundamentally a difficult problem. **There is no perfect level of abstraction**; deciding how much to break things down, and how to track the relationships, is a skill and an art. Many books have been written about approaches and patterns which people have found helpful, and there are many debates about which one is best in which circumstances.

You *will* find that sometimes you break things down in a way you hope will be helpful, then find it makes your life harder, and have to decide whether to go through the pain of rewriting it, or live with it. Don't be discouraged and think you're doing something fundamentally wrong; just keep learning from those mistakes, and seeking the right balance for your particular situation.

---
Tags: c++, architecture, design-patterns
---


# Question
Title: Blinding flash. Set background color when creating new window
Using GLFW to create the main window

Example c++

```
wS->win->hdl = glfwCreateWindow(wS->win->width, wS->win->height, wS->win->appName, NULL, NULL);

```

The created window for a moment has a white background, until openGL is setup and rendering the correct color (between `glfwCreateWindow` and first call to `glClear`).

In dark mode on a large monitor it is almost painful having a sudden flash of full white.

My current solution is to open the window as small as possible, resizing it when openGL is ready. This is a hack and it would be nice to be able to set the default window background color to match the current display mode of the OS (dark / light modes)

# Answer
> 0 votes
## A better hack?

After some trial and error I found a solution that is still a hack but much better than resizing.

Immediately after creating the window with `wS->win->hdl = glfwCreateWindow((wS->win->width, wS->win->height, wS->win->appName, NULL, NULL);` call `glfwSwapBuffers(wS->win->hdl);`

The default state of the back buffer seams to be black and overwrites the white window content.

---
Tags: c++, opengl, glfw
---


# Question
Title: Compiling Unity to WebGL gives a Node ESM module error
I'm trying to build my multiplayer game to WebGL in Unity (using Mirror). However, when I press "build", it gives me the following *three* errors:

```
Building Builds\Web\index.html failed with output:
(node:78892) ExperimentalWarning: The ESM module loader is experimental.
file:///[unity install dir]/Editor/Data/PlaybackEngines/WebGLSupport/BuildTools/Preprocess.js:91
  return;
  ^^^^^^

SyntaxError: Illegal return statement
    at Loader.moduleStrategy (internal/modules/esm/translators.js:88:18)
    at async link (internal/modules/esm/module_job.js:41:21)

UnityEngine.GUIUtility:ProcessEvent (int,intptr,bool&)

```

```
Building Builds\Web\Build\Web.loader.js failed with output:
(node:80608) ExperimentalWarning: The ESM module loader is experimental.
file:///[unity install dir]/Editor/Data/PlaybackEngines/WebGLSupport/BuildTools/Preprocess.js:91
  return;
  ^^^^^^

SyntaxError: Illegal return statement
    at Loader.moduleStrategy (internal/modules/esm/translators.js:88:18)
    at async link (internal/modules/esm/module_job.js:41:21)

UnityEngine.GUIUtility:ProcessEvent (int,intptr,bool&)

```

```
Building Builds\Web\TemplateData\style.css failed with output:
(node:83572) ExperimentalWarning: The ESM module loader is experimental.
file:///[unity install dir]/Editor/Data/PlaybackEngines/WebGLSupport/BuildTools/Preprocess.js:91
  return;
  ^^^^^^

SyntaxError: Illegal return statement
    at Loader.moduleStrategy (internal/modules/esm/translators.js:88:18)
    at async link (internal/modules/esm/module_job.js:41:21)

UnityEngine.GUIUtility:ProcessEvent (int,intptr,bool&)

```

I've tried Googling it, but I couldn't find anything other than this post which didn't really help me at all.

* OS: Windows 11
* Unity version: `2022.3.4f1`
* Node.JS version (I'm not sure if it really matters): `20.8.1`

**EDIT**: I looked in "Preprocess.js" to see where the error was and it looks like it was here:

```
if (!locals.outputPath) {
  console.log(JSON.stringify(Object.keys(locals.variables)));
  return;
}

```

There's just a return in the global scope... Not sure if this has to do with anything but I thought it might be helpful

**EDIT 2**: I commented out the return statement:

file:///[unity install dir]/Editor/Data/PlaybackEngines/WebGLSupport/BuildTools/Preprocess.js:2
  fs: require("fs"),
      ^

ReferenceError: require is not defined
    at file:///[unity install dir]/Editor/Data/PlaybackEngines/WebGLSupport/BuildTools/Preprocess.js:2:7
    at ModuleJob.run (internal/modules/esm/module_job.js:137:37)
    at async Loader.import (internal/modules/esm/loader.js:179:24)

UnityEngine.GUIUtility:ProcessEvent (int,intptr,bool&)
```

# Answer
I fixed it by removing `"type": "module"` from my home directory's `package.json`. I'm guessing it had something to do with Unity using CommonJS internally and then my NodeJS install not letting it use it because of the `package.json` config.
> 1 votes

---
Tags: unity, node.js, unity-webgl, mirror-networking
---


# Question
Title: Ways to include relativity in multiplayer
Im currently working on a game concept including flying Space Ships in the solar system and maybe beyond. As the ships are using similar engines than in "The Expance" Epstein Drive. relativistic speeds may be possible.

As i dwelled deeper into the topic, i realized that including relativistic speeds may bring some problems, if you want to acknowledge this in any game.

1. First of all time dilation when moving with higher speeds relativ to some other ship means, you can basicly do less things in the same time frame compared to a stationary observer. Including producing goods, shooting and whatever. For the traveler, this does look like everyone else is just faster.
2. Another Problem is the lenght contraction. Basicly distances in the direction of movement shorten. Distance between objects get shorter, the objects themself seem squished, while from a stationary observer, the traveling ship seems longer and stretcht.

In a singleplayer game, all these concept may be doable, as the player is either the one who travels or the one observing. There are some interesting games working with relatitivy in interesting games, like reducing the speed of light to walking speed.

In multiplayer this seems to make problems, as the game has to compensate for these relativitic effects. Yes, i can let the game run asymetricly for different players, that would work for the time dilatation. But then the twin paradox comes along and basicly breaks the concept of continuity. The stationary player needs to have much more time than the traveling one.

My Question is, is there any way to do it right or at least ways to compensate in regards to the time dilation. Are there any games that did have a good implementation of relativistic in multiplayer?

# Answer
The whole idea of simultaneity breaks down when you take into account relativity. Client/server games kind of depend on this concept. So you will definitely have to let the clients run independently. BUT the concept of a client itself is dependent upon the time passing in the computer it's running on, and the time flow for the person using the client. The twin paradox happens because time slows for one of the twins, so your client will have to slow, which will make your player in our universe bored.

I think you've opened a game design can of worms that doesn't have a solution that will result in something fun.
> 2 votes

# Answer
You know, general relativity and networked multiplayer games already have a lot in common. Except, usually, games try to eliminate the effects of relativity. This is not easy. Watch any PUBG desync video (or this one). Observe the Fallout 76 fiasco.

Every player has a version of events that happen. Also, there is a server that has *its* version of events that happen. However, every actor is connected by a network, that takes a non-zero (and differing) amount of time to "sync up". This would be equivalent to each player accelerating towards a very distant mirror at different rates, and then describing what they are seeing everyone doing by looking at that mirror. It's going to get confusing.
> 1 votes

# Answer
I'm kind of surprised that nobody has brought up EVE online, so I will...

Sure, the clock of the clients drift. However, do we really want to have a player with a fast clock right next to another player that has a slow clock? I do not think so. That is not how gravity wells work.

Instead we want areas to have a slower clock, futhermore we want a gradient of time dilation. And this time dilation depends on the ammount of mass in the area.

EVE online does that. In places where there are many ships they slow down simulation on the server (everything is still synchronized) so that the server has to deal with less stuff per tick... Thus, it is a server load solution, and they correctly talk about it in terms of relativity, in fact, players get a display of how much time dilation they are under.

Read about it in their dev blog: INTRODUCING TIME DILATION (TIDI).

---

However, Almo is right on the boring part. Not for the gravity well, but for traveling near the speed of light, which you would need for that twin paradox.

In fact, it is not uncommon for games to have fast travel that is actually faster than light... because the whole point of it is removing the tedious parts.
> 1 votes

# Answer
I don't want to throw a lot of detail at you, but the Twin Paradox isn't really a paradox. The effect will not happen in real life (unless we live on a Torus or something) because returning to your twin requires you to accelerate. Correcting for accelerating frames resolves the paradox. What's more, if I recall correctly, you don't need full GR to do this.
> 0 votes

---
Tags: physics, game-design, multiplayer
---


# Question
Title: How to correctly add animation for a rotating object with Script?
I have the following structure of my Turret:

The Body rotates by Y and Head rotating by X via script to a target, I have created simple Idle animation for turret which rotate Body and Head. The problem when the animation is added to an Animator, tower is stacked in static position, if i make translation to a Idle animation it's playing normally, but don't return back to a default state. I tried to create a buffer State without Idle Motion turret is rotating fine, I tried add conditions with bool value.

The questis is:

1. How to play animation in different rotations? (If object changes his Transform, and then play animation, the animation shout start not from 0,0,0 but from 90,0,0 for example)
2. How to switch default behaviour of targeting Enemies, maybee I should may animation for a Targeting or smth like this?

# Answer
> 0 votes
To solve it, I used parent object to have such structure:

I am rotating Body and Head via script, and create animation for an BodyAnimRotator, I have added reference to a BodyAnimRotator and Animator. When target is out of range I am enabling Animator if no, disabling.

To save current rotation of the body, we are rotating BodyAnimRotator in Animation, so position of the body stays the same.

# Answer
> 0 votes
When one of the animation states of an Animator changes a certain property of an object, then the Animator thinks that it "owns" that property. It will reset it to the default value each frame even when in a state where that property isn't a part of the Action.

However, you can override the results of the animator to implement the `LateUpdate` event. LateUpdate gets executed after the Animator, so you can use it to overwrite its results with something else.

This means that you can have an idle animation defined as an animation, and then when the turret has a target, overwrite the rotations in LateUpdate with your target tracking code.

---
Tags: unity, animation, animator
---


# Question
Title: In Unity, the character's spine position reference changed after I put something into its hand
The situation can be illustrated by a few pictures.

here is a character

After i put a gun under his right hand

As you can see, when I select spine.003, its position is now located at the gun. When I try to rotate the spine, it will use that gun position as a pivot point, which is definitely unintended. And after I delete the gun, the spine's position goes back, and everything is fine again.

Strangely enough, the breast position remains unaffected, while only the spine is affected. Why is this happening?

# Answer
In the Scene view, click the "Toggle Tool Handle Position" dropdown, and select "Pivot".
> 1 votes

---
Tags: unity
---


# Question
Title: Type or namespace name 'Collider' could not be found
I asked Mail.RU how to make a script so that when an object is touched, the game will restart. They sent me this:

```
using UnityEngine.SceneManagement;

public class RestartGameOnTouch : MonoBehaviour
{
    // Attach this script to an object that
    // should restart the game when touched.

    void OnTriggerEnter(Collider other)
    {
        // Check if the player has touched
        // the object with this script.
        if (other.CompareTag("Player"))
        {
            // Restart the game.
            RestartGame();
        }
    }

    void RestartGame()
    {
        // Here you can add any logic that needs
        // to be executed before restarting the
        // game, for example, resetting counters,
        // player position, etc.

        // For simplicity, we'll reload the scene:
        var scene = SceneManager.GetActiveScene();
        SceneManager.LoadScene(scene.buildIndex);
    }
}

```

Then, using other answers from Mail.RU, I changed the restart method to:

```
    void RestartGame()
    {
        var scene = SceneManager.GetActiveScene(1);
        SceneManager.LoadScene(scene.buildIndex);
    }

```

I don't know what the problem is, but I get this error message:

> Assets\Scenes\TOUGT RESTART.cs(5,25): error CS0246: The type or namespace name 'Collider' could not be found (are you missing a using directive or an assembly reference?)

When I try to run my game, it says that first I need to fix all compiler errors.

What do I need to do?

# Answer
This is the compiler saying "I don't know what this `Collider` name is referring to".

`Collider` is a class in the `UnityEngine` namespace.

So you probably accidentally deleted (or forgot to add) the `using UnityEngine;` declaration at the top of the script (before `public class RestartGameOnTouch`).

As Zibelas points out in the comments, you should also generally name your file the same as the main type it defines. So a class called `RestartGameOnTouch` should be in a file named `RestartGameOnTouch.cs` not `TOUGT RESTART.cs`

There's also no overload of `GetActiveScene()` that takes an argument like 1, so your change to the restart method does not make sense. It's unclear what you were trying to do here.
> 1 votes

# Answer
You need to add `using UnityEngine;` to the very beginning of the script because unity does not know what a collider is. As the error suggests:

> are you missing a using directive?

Also you should name the file same as the class, so TOUGT RESTART.cs should be renamed to RestartGameOnTouch.cs

You should also try to avoid spaces whenever you are naming things in unity because unity cannot always handle spaces in names.
> 1 votes

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


# Question
Title: Different Spacing of all Children Grid Layout Group
I am creating a top down 2D game, and I am creating randomized triangles on the ground. Such as this:

This is to enhance the "knowledge" that you are moving.

But it certainly doesn't look right. Making them randomly spaced will make it more satisfying (unless you disagree).

This includes the green background (maybe creating an empty object as the parent separate from the background would be better) as the parent, and the green triangles as children. The parent has a grid layout group.

What I want to do is randomize the spacing for each individual triangle, with a minimum spacing from other triangles and a maximum spacing from other triangles.

I am not manually moving 400 triangles randomly (I could, but if I create a similar project I know exactly what to do). I would much rather hand type a 1000 line script. A script would be preferable as it could be used in other projects, but some other method is also fun. Just any method that can be re-used.

I will try making my own script that clones in a line with looping.

# Answer
> 0 votes
The "simplest" way is to populate a Canvas; so you don't have to worry about "rows and columns". Starting from the "origin" (0,0), you "chunk" your way from top to bottom and left to right; randomizing the position of your triangle into a given chunk (a bounding Rect).

# Answer
> 0 votes
Create the prefab with a few possible positions of the triangle. Then each cell will contain this prefab. Then set the triangle to the random (or defined) space inside the prefab. For example each cell is 3x3 squares you put a triangle in x = 1 y = 3 position the else position is empty. You can define the position of each triangle in each cell.

---
Tags: unity, c#, 2d
---


# Question
Title: How can I securely store Gmail SMTP credentials in a Unity project to comply with security guidelines?
I am currently working on a Unity Asset that involves sending emails using Gmail's SMTP server. As part of the setup, developers using the asset are required to input their email address and the corresponding App Password for authentication.

Recently, I encountered a problem during the submission of my Unity Asset. The rejection reason stated that the email credentials were not stored securely and could potentially be exposed in the built project, violating security guidelines (**Section 1.5.b:** *API key storage non-secure*).

Here's a summary of my situation:

* My Unity Asset requires email credentials for SMTP server usage, specifically the App Password for Gmail.
* The credentials are currently stored directly within the Unity project, leading to security concerns.
* I attempted to reach out to Unity for guidance, but their response suggested exploring alternatives without providing specific solutions tailored to my implementation.
* I am seeking advice and suggestions from the community on how to securely store email credentials, especially considering the sensitivity of the App Password. I want to ensure that the credentials are adequately protected to prevent unauthorized access or exposure in the built project.

Here is my Code that is causing the problem:

```
[Header("Mail Credentials\n")]

//This where Mail credentials is Initilized/store.

[SerializeField] private string ReceiverMail = "ReceiverMail@gmail.com";
[SerializeField] private string SenderMail = "SenderMail@gmail.com";
[SerializeField] private string appPassword = "SenderMailAppPassword(dfkfjjfkjgmnfk)";

private async void SendMail()
{
        //code.....

        mail.From = new MailAddress(SenderMail);

        mail.To.Add(ReceiverMail);

        //code.....

        //This is where Sender Mail credentials is used in entire Code
        smtpServer.Credentials = new System.Net.NetworkCredential(SenderMail, appPassword) as ICredentialsByHost;

        //code.....

}

```

How can I best solve this problem?

# Answer
> 3 votes
Since your goal is to send feedback to yourself, there are others ways instead of storing or even giving the credentials to the asset. As Almo pointed out, giving your credentials to a random asset is giving away your credentials.

* You could have somewhere your own server and do a post request against your endpoint. Not fully an email, but would be close enough.
* You could use a `<a href="mailto:` link to open a local mail provider if the target system allows it.
* You could link to a discord (or other online forum) dedicated to your asset.
* You could link to the Unity Forum for assets (to a thread dedicated to your asset)

There is even a bigger benefit of a forum based solution compared to email. It is easier for others to see, to edit and review a question. People who are taking their time to write good feedback or wanting to reports bugs won't mind usually the extra few minutes. And are usually as well tech savy enough to handle more than an email.

# Answer
> 0 votes
Consider "Isolated Storage".

> Using isolated storage enables partially trusted applications to store data in a manner that is controlled by the computer's security policy.

https://learn.microsoft.com/en-us/dotnet/standard/io/isolated-storage

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


# Question
Title: Performance issues with high-resolution maps in 2D strategy games
I'm currently developing a 2D strategy game, and I've encountered some issues with the game map.

My idea is to use a single 2D image as the strategic map for the game. similar to this (Supremacy 1914) but in a 2D version:

However, I'd like players to be able to zoom in to see the details of the map or zoom out to view the entire map. Therefore, the image might have a high resolution (e.g., 10000x8000).

Now, my concern is that loading the entire image into memory would incur unacceptable memory overhead. One approach I'm considering is to divide this high-resolution image into blocks and only load the blocks within the player's view.

However, there's a drawback to this approach as well. If I need to zoom out to view the entire map, I'd still have to load all the blocks, resulting in excessive memory usage. Alternatively, I could prepare a low-resolution version of the image and load it when viewing the full map, but I'm not sure if this approach is elegant.

Do you have any suggestions? Your help would be greatly appreciated.

# Answer
> 4 votes
You can do something similar to what Google Maps does (at least visually):

Have different quality versions of your map. When zoomed out, your entire map loads on low quality (let's say `1920x1080`), but because you are zoomed out it looks good.

When zooming in, load only that part of the map in high quality. As an example, when you zoom in on the top-left quarter of the map, it will load a new `1920x1080` texture that **only shows the top-left quarter of the map**, so the whole map would be `7920x4320`, but only one quarter of it would be loaded.

You can have different quality levels, so the more the user zooms in, the more quality is revealed. Dividing the map into quarters was just an example, you might need to come up with a way that best works for your project.

This might require to organise the map into a grid, or something similar, depending on your project. Tt's up to you to decide if you want to show this loading process to the users as they zoom in, or attempt to pre-load sections of the map, which might be more complex to do but have smoother results.

Hopefully this gives you at least some idea on how to proceed.

# Answer
> 1 votes
Another trick you can use is to compose this map in a shader from lower-resolution inputs.

You could use a signed distance field texture for the territory lines to get crisp vector-like edges even zoomed in tightly without spending a lot of texture memory or juggling different sets of tile textures at different zooms (we used this for the topographic contours on our planet maps on Starlink: Battle for Atlas).

This also makes it easy to control the line thickness, if you want to keep borders from vanishing into hairlines when zoomed out or looking to chunky zoomed in: you can dynamically re-draw them with your desired thickness for the current view.

Then the paper surface can be filled in by tiling "detail maps" that you layer based on the zoom level, fading in more detailed/higher frequency tiling when you zoom in, and mipping away as you zoom out.

# Answer
> 0 votes
I personally dont think you need to worry, you can split it into smaller images, but the main reason is that even a high res image probably wont take up that much.

From google:

> A standard 32-bit color depth (8 bits per channel for red, green, blue, and alpha) would require approximately 8,100 kilobytes (KB) of VRAM for a 1920x1080 resolution image.

8MB for a 1080p image is really not a lot, if we round 1080 to 1000 and 1920 to 2000, 1000 x 10 = 10000, 2000 x 10 = 20000, and 8 x 10 = 80, that means an image with a size of 20000 x 10000 would only take up about 80MB, not as much as you'd think. If you're still worried splitting them up into chunks and loading/unloading could also help.

The main reason modern games use so much VRAM, is because they are loading loads of textures for all the different parts of the game. Just one high res texture shouldn't effect it much.

# Answer
> 0 votes
(Beware of premature optimizing). My "current" map is only 6000x6000, but I have had no issues (UWP). I used a ScrollViewer to zoom and scroll the map. The map is also "parsed" to create a shadow elevation map (so, 2 maps) and a "mini-map" with every update. The map is loaded async while the splash screen shows. No issues at all in that regard (memory). BTW. Reducing the "number of distinct colors" can reduce the size of the file even thought the width and height of the image don't change (jpg). So, I have a function that can clean my images of "dirt" by flooding from a "good" color.

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


# Question
Title: Automated playtesting in a 2D platformer
For a hard 2D platformer I'm working on, I want to make an automated playtesting system. The goal is to allow every level to be tested in parallel as part of an automated test suite. These tests would both help to catch bugs and determine if a level is still possible to beat after any given change, which could both be huge time savers in a game that could take a few hours to finish.

How do other games approach this?

My initial approach has been to record some inputs I use to finish a level, and then replay those inputs in the test. Specifically, every frame I check if the input state is different from the last recorded input state, and if it is, save it along with a timestamp relative to when the player spawns into the level. Replays simply set the input state according to those timestamps.

This works maybe a quarter of the time. I suspect the issue is that small fluctuations in floating point math add up pretty quickly, and the input recordings make a lot of assumptions as to where the player is at any given frame which may not be true due to those deviations. (I also thought it might have to do with variable frame rate, but I didn't see any improvement from switching to `FixedUpdate`.)

I have a couple ideas for how to fix this, but they all have cons:

1. Implement an AI. A fully autonomous agent is overkill; a more realistic alternative might take the input recordings and make small adjustments in real time, but that would still be a lot of work to make
2. Fudge things. Record the state of every entity, and if it deviates enough during a replay, set it back to the recorded value. This smells bad to me - it feels like in this case, the behavior I'm testing is different enough from actual gameplay that the tests lose a lot of their value
3. Explore deterministic physics. I've found approaches like this, but I'm not sure if they're relevant for my game - I only use Unity's physics for collisions (everything else is hand-rolled to avoid generic gamefeel), and I'm already loading the scene fresh at the start of each test, so I'm not sure what else could be achieved with a reload. I absolutely could be missing something, though

What else haven't I considered?

# Answer
> 1 votes
Automated testing of full levels is a difficult topic. As you've noticed, replaying inputs is tricky. Even if you get the timing right and switch to a deterministic physics engine, a small change in the level or gameplay code can make the replay invalid in various ways and require you to rerecord the level. Depending on how often this happens, you might find that the replay-testing system doesn't save you any time.

A recording also doesn't tell you everything and can even give you a false sense of security. For example, say that you adjust the collider for a platform incorrectly, making it possible to fall through the edge that looks like it should be solid. If you landed squarely on the *middle* of the platform when you recorded a playthrough, replaying the inputs won't help you realize that the collider doesn't line up with the *edge*.

Regarding #1, as an alternative to developing your own AI code from scratch, you can use an ML-driven system such as Unity's ML Agents package. In theory, with sufficient training, you'd end up with an agent that can play through any level if the level is beatable. Would this actually save you any time? That'll depend on you and your project. There are some of the same risks as replays - for example, if you change the player's jump height after training the agent, the agent might break down and need retraining.

Rather than immediately investing a lot of time into an automated testing system, you should start by analyzing your game and your development strategy and weighing the costs and benefits of automated testing.

Try to answer these questions:

* How often am I expecting to make changes that could break some levels?
* What types of changes could break levels? (E.g. adjusting the player's speed or jump height.)
* How significant of an impact would each change have? For example, changing the player's jump height could have a drastic impact on all sections of all levels of a platformer, but changing the damage from an environmental hazard would only require you to retest areas where that hazard exists.
* How many levels are there? How long would it take to re-test each level?

The goal here is to try to get a rough idea of how much time you would expect to spend manually retesting after changes, and determine whether developing an automated testing system would save more time than it costs.

---

## A strategy recommendation

If you are expecting to be spending so much time doing regression testing (going back and testing something that used to work to see if you've broken it) that you really need an automated system, you might be approaching this from the wrong angle. You can save an enormous amount of time by making key decisions early and then building around the decisions that you've made.

For example, in a platformer, the player's speed and jump height should be determined as early as possible and then set in stone. Design levels around mechanics, rather than redesigning mechanics around levels.

Build levels one at a time in the order that they'll appear in the game, and try to get a level to a point where you're very happy with it before moving on to the next level. Then, do your best never to make a change that would break a level that you've already finished. When you introduce a new mechanic such as a new enemy, build a level with that new mechanic and get it to a point that you're happy with. During this process, you might refine the enemy behavior. Once the level is finished, however, you should keep that enemy as-is for all future levels. Again - design levels around mechanics, rather than redesigning mechanics around levels.

Any time you catch yourself wanting to change a mechanic that you've already used in previous levels, stop and really think about whether the change is justified. Were you happy with the mechanic in previous levels? Is the problem something you can solve by tweaking the level, rather than the mechanic? In some cases you can introduce a derivative or variant mechanic - for example, creating a new variant of an enemy rather than modifying the original enemy.

---
Tags: unity, physics, testing, automated-testing
---


# Question
Title: Kinematic "dive bomb" motion toward a moving target
Context: infinite runner, stationary player, obstacles move toward player. I have an asteroid that currently `Vector3.MoveTowards` a *moving* target e.g. a "rubble" object spawns hidden far away from player and moves toward player. At time of spawn, an asteroid spawns well above it and starts moving toward the rubble. When they collide, rubble appears, asteroid disappears, boom, particles, etc.

## TL;DR

I want a kinematic object to track high for awhile and dive bomb at the last minute to crash into a moving target with variable speed (final location unknown.) I also want animation curves to tweak the speed and dive bomb effects.

## The meat

The goal: I'd like the asteroid to track mostly high until some time close to impact and then sort of dive bomb down toward the rubble. I want to control the speed with an animation curve in the inspector. Bonus points if I can control the "dive bomb" intensity with another animation curve. I'd like to keep the motion smooth (I thought of maybe trying to calculate

The problem: The current path of motion is lame. The asteroid just gradually moves down and sort of asymptotically (to the ground) hits the rubble since I'm just using `Vector3.MoveTowards` with a *moving* target. Even if I try to control its speed over time, it's not what I'm looking for. The game speed *also* changes variably, so it would be tricky at best to figure out the actual final destination of the target.

How can I keep the asteroid high-ish until a point, then start dive bombing for a more dramatic crash? I'm thinking somehow the distance and/or time need to be normalized to use the animation curve, but I don't know how to do it when the target moves variably. I've attempted to normalize it, but maybe just can't get the math right. Can time spent traveling be normalized if you don't know how long it will travel?

The current lame code:

```
timeSinceStart += Time.deltaTime;

float baseSpeed = GameManager.gm.speed * gameSpeedMultiplier;

float adjustedSpeed = baseSpeed * speedCurve.Evaluate(timeSinceStart);

float step = adjustedSpeed * Time.deltaTime;

transform.position = Vector3.MoveTowards(transform.position, target.transform.position, step);

transform.Rotate(randomRotation, rotationSpeed * Time.deltaTime);

```

Update: sketched image

* A == asteroid
* R == rubble/target
* P == player

# Answer
> 0 votes
This is how I would do it:

The first thing you would need to do is calculate a vector from the position of the asteroid to the end position.

`Vector 3 direction = (transform.position - endPosition);`

We can then use the equation \\$Speed = Distance / Time\\$ to calculate the speed needed.

For example if we want the asteroid to travel **10 units** in a time of **5 seconds** we can input the values into the equation to calculate how many units per second we need to move:

**(U = Unity Units)**

\\$U/s = 10 / 5\\$

or in other words, **2U/s**.

Here's how we can implement this inside of Unity:

We can create an IEnemerator to do things over time:

```
private IEnumerator DropAsteroid(float duration, AnimationCurve speedCurve)
{
    float elapsed = 0f;
    Vector3 direction = (transform.position - endPosition);
    Vector3 speed = direction / duration;

    while (elapsed < duration)
    {
        Vector3 velo = speed * speedCurve.Evaluate(elapsed / duration);
        m_Rigidbody.velocity = velo;
        elapsed += Time.deltaTime;
    }
}

```

Hope that helps. (also this is untested code so any issues let me know and ill try to help.)

# Answer
> 0 votes
Based on the image, the rubble is moving in the x direction, and the asteroid in x,y. Using 3 DoubleAnimations (StoryBoard) and a common target point (CompositeTransform.TranslateX and Y for asteroid; X for rubble) and common duration, you can accomplish what you want. Use an "easing function" for the y animation of the asteroid to get the "plunge" you want (versus a linear interpolation). A common "target point" (collision point) and same duration is the key.

https://learn.microsoft.com/en-us/dotnet/desktop/wpf/graphics-multimedia/easing-functions?view=netframeworkdesktop-4.8

---
Tags: unity, c#, 3d
---


title: Unity Game Architecture

text:
# Question
Title: Unity Game Architecture
I'm working on a relatively simple game, but even simple games have a lot of moving parts, and I'm running into some architecture issues. Just to be clear, everything works fine, but it feels dirty, and that's usually a sign of a problem.

So, I'm following SOLID principles, which, by my understanding means that I should have many scripts that each do a single thing versus large scripts that do many things. It makes things easier to maintain, but linking things that require references turns into a mess, for me at least.

To get more specific, my game uses a grid. Great, I've got a script that represents a grid and contains methods related to the grid (ex: converting from world to grid position).

I've got another script that instantiates the grid and manages things with the grid in a level, such as populating it. Then I've got a script that handles the merging logic for the items on the grid. (matching game logic)

Then, I've got a score manager that manages the game's score, and then I've got a UI manager that manages the UI.

The thing is that the merge script requires a hard reference to the grid to work, and the score manager requires a reference to the merge script, and the UI manager requires a reference to the score manager, and by the end of it, everything is referencing everything.

For the record, I'm trying to avoid inspector references, and instead referenced the main components using the Singleton pattern. But I don't like it.

Is there a better way?

The only thing I can think of is having a game manager script that references everything and then handles communication between all the other managers.

# Answer
> 0 votes
It seems that you're generally following SOLID principles and utilizing the Singleton pattern, which is a step in the right direction. However, relying heavily on the Singleton pattern can often result in tangled code where components are overly interconnected, as in your case.

As with many architectural challenges, the appropriate solution depends on the specific context of your problem. In this scenario, employing a service locator pattern could offer a more elegant approach to managing dependencies.

Here's how a service locator pattern might be applied:

**Registration:** Essential services, such as the grid or score manager, would register themselves with the service locator, associating each with a unique key or identifier. This registration typically occurs during application startup or initialization.

**Lookup:** Clients of these services can then request an instance by specifying its corresponding key or type. The service locator responds by querying its registry and returning the requested service instance to the client.

**Instantiation:** In some cases, the service locator may need to handle the creation and lifecycle management of services. However, in your scenario, since essential services like the grid are likely already present in the scene, you may be able to skip this instantiation step.

Using the service locator, clients are effectively decoupled from the specific implementations of services. They can simply request services from the locator without needing to be aware of how those services are created or where they originate. This promotes cleaner, more modular code and simplifies the process of integrating and maintaining various components within your game architecture.

# Answer
> 0 votes
*There are a couple ways you could approach this depending on your needs and viewpoints.*

The first method would indeed be to use singleton patterns for each manager. This is the approach I personally use in my game with about 80+ scripts and I've never had a huge problem with it.

**Benefits:**

* Easy to implement
* Accessible by any script (no reference needed)

**Drawbacks:**

* Can be confusing

The other method is to use some sort of "level asset", I also use these in my project however its slightly more complicated.

The idea is you have a Game Object, I usually call mine "*Level*", tagged with some specific tag like "LevelAsset". Then you create some kind of LevelAssetLoader script that can take all the references and place them into reference slots within the specific managers.

**Benefits:**

* Gives a clear place to drag and drop scene references
* Easy to swap/remove/change values

**Drawbacks:**

* You would have duplicates (for example all the references in GameManager would also need to be in LevelAsset which may become confusing and unneccessary)
* More references
* Can be messy

***Both have their pros and cons, so me and my team tend to use both, but it's up to how you like it. I think singletons are much easier, but its personal preference.***

# Answer
> 0 votes
Ultimately, I find that giving classes meaningful names, and using "as many namespaces" as necessary to make sense of it all, is what keeps things sane. The harder a class is to name, the "busier" it probably is; that's where the (static) "one method per class" starts making more sense. I realized I had a "Geometry" namespace, if I just gathered all my "calculators" in one place. That was a reward in itself. (Now I can create a "geometry dll" if I need to).

---
Tags: unity, c#, architecture, design-patterns
---