# Question
Title: Problems with normal recovery from storage as two floats and normal from depth buffer
In my app I’m producing for my deferred shading 4 layers of data to show up occluded parts of the scene during screen space reflection (SSR) pass. I need normal maps with bumpiness of these layers for lighting and I also need for my SSR to produce a normal map for the whole scene from flat mesh surface. So I’m trying to optimize the resources to have only one texture for the two normal maps or rebuild the normal for flat surfaces from the depth buffer.

Storing two normals in one RGBA texture is possible by encoding Nxy only and decode Nxyz in the pixel shader; Several methods are proposed here and I use the Lambert one claimed to work well with the two following functions:

```
float2 N3toN2(float3 N) // encode
{
    float p = sqrt(N.z*8+8);
    return N.xy/p+0.5f;
}

float3 N2toN3(float2 N ) //decode
{
   float2 FE = N*4-2;
   float F = FE.x*FE.x+FE.y*FE.y;
   float t = sqrt(1-F*0.25f);
   return float3(FE*t, 1-F*0.5);
 }

```

I have checked their behaviours by writing these functions on the cpu and they seems to work well including with negative signs. But in my shader the result is darker than the original and in some cases totally black (see picture A). Depending on the POV it can be blue only. So there's apparently a problem with the N.z component.

Regarding normal reconstruction from the depth buffer the method is explained here and uses the “magic” of ddx/ddy functions (how it is working explained here). In the original post they rebuild the position in world space so I suppose the normals they use are in world space. I work in view space so I reconstruct the position PosV in view space and use it to get the flat surface normal SSNormal in view space I guess. From PosV and SSNormal you get the ray direction SSDir in view space like this:

```
   float3 PosV = float3(InvProj.x*(dI.x*4-1), InvProj.y*(1-dI.y*4), 1)/(InvProj.z*D+1);//compact format of the inverse projection matrix
   //with dI = input.texcoord*0.5 because I use only the upper quarter of the texture
   //holding the 4 layers as the final scene to reflect.
   //So dI*4 is used to get PosV instead of usual dI*2
   float3 SSNormal = normalize(cross(ddx(PosV), ddy(PosV)));
   float3 VSDir = normalize(reflect(normalize(PosV),SSNormal));

```

Here I have a bizarre behaviour that seems to depend on the resolution of the texture compared to the final screen size.

I have two methods to generate the layers I need.

If for the 4 layers I need I use a single RTV texture that is twice the size of the screen (e.g. 1920x1080 for the RTV and 960x540 for the screen) I have a nice result (PanelB). If I set the screen to 1920x1080 SSR disappear. Of note the final scene is recomposed during SSR by selecting the appropriate color from the 4 layers based on Zbuffer value. THe problem seems to come from the PosV calcul when the screen size is equal to the texture size. After checking the SSDir.z if mostly negative and I have a test to not do SSR for ray with negative SSdir.z. After some attemps to change this equation I'm still not successful.

In a second method (Panel A) I have one RTV per layers, each RTV having the size of the screen. Here I have unfilled lines that appear in the SSR.

Of course everything works well if I use an extra texture for storing the full flat or bump normal (XYZ) of the scene.

# Answer
A first answer concerns the normals packing At the moment what works best for me is to store Nx and Ny and recover Nz = sqrt(1-dot(Nxy,Nxy)). I manage the problem of the sign with an unused alpha bit elsewhere. That said as far as I have seen with my view space settings the Nz component seems to be always negative. The problems with normals from depth are still to be corrected.
> 0 votes

---
Tags: hlsl, compression, reflection-rendering, normal-generation
---


# Question
Title: Reliably addressing compute buffer when using large numbers of threads
I'm trying to move a 262,144 \[2^18\] points (stars) in a compute shader and am struggling to reliably address the data in a buffer.

I understand that there's a 3-dimensional array `SV_DispatchThreadID` that provides an index for the thread in the thread group.

My hardware can run 65,536 threads per thread group (assuming I've understood the terminology correctly). As my total number of stars exceeds that number (and they're rendered), unity must be making multiple calls under the covers(?)

In any case, I have:

```
[numthreads(64, 64, 16)]
void BuildStars(uint3 id3 : SV_DispatchThreadID, uint id1 : SV_GroupIndex) {
    int id = id3.x
            + id3.y * 64
            + id3.z * 4096;
    ...

```

\[To simplify things, I'm only attempting to use 32,768 stars to begin with, meaning I'm ignoring `id1` for the moment. I'd hoped to be able to add `id += id1 * 65536`, but I haven't got that far yet\]

The movement of the stars is inconsistent. Some move far more rapidly than others, some don't move at all.

As all I'm doing is adding a constant offset every frame, the only explanation I can come up with is that I'm generating the ID incorrectly, wrapping around and effectively updating random stars

```
mapComputeShader.Dispatch(Kernel("MoveStars"), 64, 64, 8);

```

With an eye to calling the following in future

```
mapComputeShader.Dispatch(Kernel("MoveStars"), 64, 64, 64);

```

What's the correct way from within the compute shader to get an id that varies from `0` to `numDispatchedThreads - 1`, where `numDispatchedThreads` exceeds 65,536?

# Answer
> 1 votes
Well first of all, the way GPUs work is each warp or compute block will have to make a product of 1024, so numthreads(1024,1,1) will do, 64 * 64 * 16 or numthreads(64,64,16) isn't valid. Think of the numthreads term as a way of distributing a collection of threads in the GPU. you can have numthreads(4,1,1) which is 4 compute blocks working all at the same time or you can have numthreads(2,2,1) which is the same 4 compute blocks still working at the same time but instead of having an index of X, you have XY. Usually for texture work you see XY style thread groups since that is conceptually what is best for the given task (this can sometimes tell the engine how to structure the memory differently but for the most part it just comes down to the work done to get the index.) Unity can in fact schedule groups of work but the group blocks are a little different in how you call dispatch. if you have a 128x128 image and you queue (32,32,1) then the dispatch terms should be ceil(128/32), ceil(128/32), ceil(128/1) or

```
mapComputeShader.Dispatch(kernel, 4, 4, 1);

```

the documentation on what indexing systems you have at hand and some other useful documentation files are here:

> Also heavy side note, have an if statement at the top of your compute shader to stop the index if it goes past your array, it will keep working past the buffer if you let it,

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


title: Old tv effect in shader graph

text:
# Question
Title: Old tv effect in shader graph
I am trying to use Unity's shader graph to create this old tv effect:

I thought about using a noise node, and somehow randomize the noise's seed.

Can anyone help me?

# Answer
I accidentally managed to make such shader while playing around with nodes. Here's how the whole setup looks:

We're using Gradient Noise node, but to animate it, we're using Rotate node that rotates its UV (rotating the generated noise texture), with Time node connected to Rotation value. However, if you crank up Rotate's Center parameter to 10,10 it doesn't look like it's rotating anymore. Gradient's Scale parameter has to be 90+, but not too much because it looks worse then.
> 4 votes

# Answer
For more contrast, add Remap node and configure out value. In my case, \[-6, 5\] looks good.
> 0 votes

---
Tags: unity, shaders
---


# Question
Title: How to replicate damage between users in a MUD
I'm working on a text-based MUD (Multi-User-Dungeon) in C++, but the most important thing in a MUD is the MU (Multi-User). Is there any easy way to implement these mechanics? I want a player on one client to deal damage to an enemy, and that enemy to lose HP on the other clients. Here's an example of what I'd like to happen.

Client 1:

```
Demon HP: [####################]
You used SWORD on DEMON!
Demon HP: [##################--]

```

Client 2:

```
Demon HP: [####################]
User1 used SWORD on DEMON!
Demon HP: [##################--]

```

I can do that, but the hard part is the underlying bits (as it always is). I need client one to update the demon's HP, and that to register on client two. Sort of like this.

Client 1

```
int DemonHP = 10;
DemonHP = DemonHP - 2;
send(DemonHP)

```

Client 2

```
int DemonHP = 10;
//Client 1 calls send(DemonHP)
//At this point, DemonHP should equal 8

```

This is the basis of a multiplayer experience.

To clarify, I understand that `send(var)` is not proper C++ notation, the question is what the proper notation *would* be.

# Answer
> 3 votes
MUDs are usually client-server applications. That means there are two separate programs, a server and a client. The server program runs on a server in a datacenter (although for testing you can just run it on your local machine). The client program runs on the devices of the players and connects to that server.

The server handles all the game mechanics, while the clients serve as an interface between the player and the game. In the case of classic text-based MUDs, those clients are often just terminal emulators which do nothing but send the text inputs from the player to the server and receive text from the server. They do not contain any logic at all, not even basic syntax checking. All the game logic happens on the server.

If I would build an application like that, I would structure it something like this:

```
          ┌───────────────────────────────────────────────────┐
          │                                                   │
          │Game Logic Implementation                          │
          └────────────▲──────────────────────────┬───────────┘
                       │                          │
                       │              ┌───────────▼───────────┐
                       │              │                       │
Server                 │              │Event Router           │
                       │              │                       │
                       │              └───────────┬───────────┘
                       │                          │
          ┌────────────┴───────────┐  ┌───────────▼───────────┐
          │                        │  │                       │
          │Parser                  │  │Event Translator       │
          │                        │  │                       │
          └────────────▲───────────┘  └───────────┬───────────┘
                       │                          │
───────────────────────┼──────────────────────────┼───────────────────────────
                       │                          │
                       │                          │
Clients                │                          │
          ┌────────────┴────────────┐ ┌───────────▼───────────┐
          │ Client                  │ │Client                 │
          │ Input                   │ │Output                 │
          │                         │ │                       │
          │                         │ │                       │
          └─────────────────────────┘ └───────────────────────┘

```
1. The client sends a text string "Attack DEMON with SWORD" to the server
2. The Parser finds out what that actually means (something like `entity[156].attack([entity[272], entity[156].getItem(6))` and translates it to a command to the game logic implementation.
3. The Game Logic Implementation then processes that command and communicates the results of the action in form of a series of event objects which it then sends to the event router. Note that these events are not yet human-readable strings describing what happens. They are logical message objects in an internal format.
4. The Event Router decides which clients need to know about which event. Some events might go to only the one player it concerns. Some events go to every player in the room. Some events go to every player currently connected to the server.
5. The Event Translator then translates these events into strings. Note that depending on who receives the message, the translation could look different. For example, the message stating that Bob did 2 damage to the demon would be translated as "You hit the demon for 2 damage" for Bob and "Bob hits the demon for 2 damage" for everyone else in the room. This is also where you could do *literal* translation into the preferred language of the end-user if you wanted to.
6. The resulting string gets send to the client, which then gets displayed on their screen.

OK, but how would you implement sending messages from client to server and from server to client? In order to learn that, I would recommend you to look for a basic tutorial on "Socket programming in C++". Note that there are no network sockets in the C++ standard library. So you will have to use a library for networking. One popular choice are POSIX sockets - the original BSD socket library that was ported to pretty much everything by now and became the de-facto standard for low-level C/C++ network programming. But there are other networking libraries which might be worth looking at.

---

**Bonus answer: How would this change for a graphical game?**

In a graphical game, the line of separation between client and server would move up by a level.

The client is usually not nearly as "dumb" as in a MUD. It usually maintains an own copy of the game state (or at least those parts of the game state which are currently relevant for the player) and takes care of presenting that game-state to the player in form of visual output.

The client usually doesn't just send raw inputs to the server. It translates them into machine-readable messages of what the player intends to do (not *does* but *intends to do* \- the server still has the authority to deny any player actions).

And the client doesn't receive pre-rendered output. It receives events in a binary format which it then translates into updates to its local copy of the game-state.

The format specification for the binary messages sent between client and server are usually referred to as the "network protocol" of the game. The program code responsible for creating and interpreting those messages is usually called the "netcode".

---
Tags: c++, multiplayer, mmo, synchronization, mud
---


# Question
Title: Host & Client user input moving both Player prefabs at the same time
I have a player controller attached to the Player prefab - along with the NGO components

Network Object Client Network Transform Network Animator

In the Network Manager I have the Player prefab added so that the host & clients will spawn when joining.

The issue I have is that the user input from client & host is controlling both prefabs on screen at the same time.

On the player controller script I have the line if (!IsOwner) return; at the start of the Update() before any movement is called

The Player Prefab is setup as follows:

* **Player (Has the Network Object & Client Network Transform components)Parent Obj**
* *Controller (Has the PlayerController script attached to it)*
* *Model (Has the Owner Network Animator component with the Animator applied)*

Any help much appreciated.

PlayerController update():

```
void Update()
    {
        if(!IsOwner) return;

        if (!rigidbody || !animator) return;

        currentVelocity = rigidbody.velocity;

        GetAxisHistory();

        GetTargetHeading();

        GetLocomotionState();

        GetTurnSpeed();

        if (currentAnimationStates.HasFlag(AnimationPlayerStates.Pivoting))
        {
            SetTurnParams();
        }
        else if (TurnTriggerIsSet())
        {
            SetVelocityToCurrent();
        }
        else
        {
            TurnCheck();

            SetLocomotionVelocity();
        }
    }

```

I am using the New Input System

See the attached video for the issue

https://youtu.be/udOMW0Fbu14

# Answer
> 0 votes
I'm wondering if the IsOwner check is not working properly because it looks like you might have the PlayerController script attached to something nested under the NetworkObject.

Try moving it up to the Player GameObject.

# Answer
> 0 votes
So it was because I was using 2 instances on the same machine - the input was being read by both. I was able to get the outcome when I played a host & client across 2 different machines using gamepads. Each gamepad controlled their own player

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


# Question
Title: P2P + Authoritative server for Web based game, how to combine?
I'm working on an online Web RPG game (jRPG) with a map, that characters can go around. Also, an important part, is that each player has his own world and each player can invite his friends to play on the map together.

Almost any action can be processed by a dedicated server as well, except for the character's movement/animations, because the server is written over WebSockets, that are using TCP under the hood.

Actually, those actions can be processed with an overhead of package reliability.

But I thought, what If I create a peer for each player and use it in combination with an authoritative server? And then, in a case, if one player invites the second player to play together, then the second payer just connects to the first one using p2p technology.

But at the same time, each action, like setting a new prop on a map or opening a chest with a reward (that can be hidden in the forest) is processed by a dedicated server (through the WebSockets)

So, the purpose of p2p here is to transmit not reliable(or too frequent) data, such as user's movements(position)/animations/etc. Also, my opinion is that will work great for hubs (some locations, where 16-32 random players can meet each other, like in *No Man's sky*)

All looks perfect, except for one thing:

> I want players to be able to move over the map(want to WASD), but not to be able to move through the objects (e.g. wallhack) So, if players enter a dungeon, I want to be sure, that they solve a dungeon, but not finished it by moving through the walls.

> There is another problem similar to prev: Not allowing fast map exploration (e.g. speed hack)

**Is there any way to handle this issue without processing player movements(and other frequent unreliable data) on the main server for each update tick?**

I know that p2p is for players that love to cheat as well, but in that case, I have an additional Authorative server that can approve/reject a lot, I just do not want to make all the stuff laggy on the main server (if there will be a lot of messages per update)

*Btw. positions are only used by the player(dungeons, map exploration) or the group of players that play together, it's NOT an MMO, where thousands of players can see each other. As for me, it's useless to update the player each frame or to make the game a real MMO, so there will be a sense to update all the positions on the main server.*

*P.S. I know, If there will be no WASD, but mouse clicks then the movement path can be built using the main server. In this case, p2p will work as expected. But I really want to use a joystick on mobile devices to move around.*

# Answer
You should really go with an authoritative server in this case. Web sockets do not allow peer-to-peer connections. So you are going to need a relay server anyway. When you need a relay server anyway, you can just as well turn it into an authoritative server.

But if an authoritative server would indeed be too expensive for you, then you could as a compromise use a server which just acts as a relay, but does occasional plausibility checks. Like keeping a journal of player positions with timestamps and verify that they are not further away from each other than it should be physically possible for the player.

If you want to catch cheaters, then it might not even be necessary to verify *every* action. A cheater isn't going to cheat only once. They are going to cheat all the time. So you just need to pick a random sample of actions that get verified by the server. This also doesn't need to delay the execution of those messages. You can just do that on a separate thread while the game continues. When too many actions of the player get flagged as implausible, that player gets banned for cheating. But be aware of false positives. Especially when it comes to movement and pathfinding. Latency and jitter mean that the players and the server never see the *exact* same gameplay state. So it is not uncommon for them to occasionally disagree about what is and isn't possible.
> 0 votes

---
Tags: networking, game-mechanics, client-server, websocket, peer-to-peer
---


# Question
Title: Looking for an advice on how to possibly boost my compute shader
I have 4 rendertargets R10G10B10A2 each being used to store color and normal in a compact double RGB 555 bits format. When I'm doing the lighting pass I'm obliged to have extra rendertargets because if I can read(extract) the normal/color, I can't write back directly the lit color to these surfaces.

So I moved to a compute shader to achieve this goal (DX11 CS5). I have found that I'm limited to R32\_UINT for read/write in DX11 CS5. I have thus adapted my encoding/decoding to have things work fine, although the final colors are a little bit hugly with my encoding.

Unfortunately the final frame rate is lower than the regular pixel shader even if I have to do 4 copyresources from the intermediate rendertargets with my previous method.

I have implemented the CS starting from those found in the legacy DX11 samples. My code is like this:

CPU calls:

```
 //some CSbufferConstant and CSshaderresourceview settings (e.g. shadowmaps, depth textures
 gpDC11->CSSetShader(pCS, 0, 0);
 //I' mworking on 4 UAV at the same time in the CSshader. With only one it is even slower
 gpDC11->CSSetUnorderedAccessViews(0, 4, gSRDeffered.ppUAV, (UINT*)(&gSRDeffered.ppUAV));
 gpDC11->Dispatch(960, 540, 1);//the size of my screen

```

GPU CS shader:

```
[numthreads(1,1,1)]
void CS_PostDeferred( uint3 nGid : SV_GroupID, uint3 nDTid : SV_DispatchThreadID, uint3 nGTid : SV_GroupThreadID )//only nDTid is used in fact here
{
    uint Output;
    float2 Tex = float2(nDTid.x/960.0, nDTid.y/540.0);
    float Depth1 = txDepth1.SampleLevel(samPoint, Tex, 0).r;
    float Depth2 = txDepth2.SampleLevel(samPoint, Tex, 0).r;
    float Depth3 = txDepth3.SampleLevel(samPoint, Tex, 0).r;
    float Depth4 = txDepth4.SampleLevel(samPoint, Tex, 0).r;

    Output = UAVDiffuse0[nDTid.xy];
    if ( Depth1 < 1 ) Output = GetLColorUnPackPack_CS(Depth1, Tex, Output);
    UAVDiffuse0[nDTid.xy]=Output;
    Output = UAVDiffuse1[nDTid.xy];
    if ( Depth2 < 1 ) Output = GetLColorUnPackPack_CS(Depth2, Tex, Output);
    UAVDiffuse1[nDTid.xy]=Output;
    Output = UAVDiffuse2[nDTid.xy];
    if ( Depth3 < 1 ) Output = GetLColorUnPackPack_CS(Depth3, Tex, Output);
    UAVDiffuse2[nDTid.xy]=Output;
    Output = UAVDiffuse3[nDTid.xy];
    if ( Depth4 < 1 ) Output = GetLColorUnPackPack_CS(Depth4, Tex, Output);
    UAVDiffuse3[nDTid.xy]=Output;
}

```

The uint GetLColorUnPackPack\_CS (float Depth, float2 UV, uint Data) is the function extracting the color and normal as 2 float3 from the R32\_UINT Data param, calculating as usual lighting and shadows for the pixel and then recompacting the final color to the R32\_UINT (the normal is not changed). The Depth and UV params are used to recover the position in view space needed for the point lights I'm using.

Any advice welcome

# Answer
When you call `Dispatch(960, 540, 1)` with `[numthreads(1,1,1)]` you are basically asking your GPU to distribute the workload on a single thread per thread group, where each thread group (depending on hardware) has a size of 32 or 64 threads, thus only using 1/32 of or 1/64 of the computational power of the threadgroup, while at the same time requesting 960x540 threadgroups

You should aim to use thread groups with sizes that are multiples of 32 or 64 and as few thread groups in `Dispatch()` as possible:

```
gpDC11->Dispatch(30, 18, 1); // (960, 540) / 32

```

Compute Shader:

```
[numthreads(32,32,1)]
void CS_PostDeferred( uint3 nGid : SV_GroupID, uint3 nDTid :
SV_DispatchThreadID, uint3 nGTid : SV_GroupThreadID )
{
    /*...*/

```

Another thing to note is that texture reads are WAY slower than register operations on modern hardware (a few orders of magnitude). The more data you are able to pack into a single texture, the better:

```
float Depth1 = txDepth1.SampleLevel(samPoint, Tex, 0).r;
float Depth2 = txDepth2.SampleLevel(samPoint, Tex, 0).r;
float Depth3 = txDepth3.SampleLevel(samPoint, Tex, 0).r;
float Depth4 = txDepth4.SampleLevel(samPoint, Tex, 0).r;

```

Can be packed as

```
float4 Depth = txDepth.SampleLevel(samPoint, Tex, 0).rgba;
float Depth1 = Depth.r;
float Depth2 = Depth.g;
float Depth3 = Depth.b;
float Depth4 = Depth.a;

```
> 2 votes

---
Tags: directx11, hlsl, compute-shader
---


# Question
Title: Multiple enemies get hit by arrow instead of one
I am working on my first Tower Defense game and I have a problem where multiple enemies get hit by a projectile instead of one.

Enemy with its collider:

The problem is that when the enemies get close to each other, their colliders overlap and one arrow deals damage to multiple units.

Arrow and Enemy both have trigger colliders 2D.

Code for Arrow.cs component:

```
    private void OnTriggerEnter2D(Collider2D collision) {
    Enemy enemy = collision.GetComponent<Enemy>();

         if (enemy != null) {
             IDamagable damagable = enemy.GetComponent<IDamagable>();
             if (damagable != null) {
                 damagable.ReceiveDamage(DamageType.PHYSICAL, attackType, damage);
             } else {
                 Debug.Log("Unit is missing the IDamagable script");
             }
             Destroy(gameObject);
        }
    }

```

Seems like collision detection and OnTriggerEnter2D is called in the same step and this function runs multiple times even if the game object is destroyed.

# Answer
As I have target set during initialization

```
private GameObject targetEnemy;
private int damage;
private AttackType attackType;

public void Initialize(GameObject targetEnemy, int damage, AttackType attackType) {
    this.targetEnemy = targetEnemy;
    this.damage = damage;
    this.attackType = attackType;
}

```

I just had to add additional check if collision happened for taget enemy, not some enemy that was close to he target.

```
    private void OnTriggerEnter2D(Collider2D collision) {
    Enemy enemy = collision.GetComponent<Enemy>();

    if (enemy != null && targetEnemy == collision.gameObject) {
        ...receive damage
    }
}

```
> 2 votes

# Answer
I disagree with the suggestion to keep track of the target. What you can do instead is have some bookkeeping in the projectile about whether it already hit a target or not (a boolean field should do the job). And if it already has, then you can just short-circuit in the collision code and not apply damage.

So something like this:

```
private bool hasHitAnEnemy = false;

private void OnTriggerEnter2D(Collider2D collision) {
    if(hasHitAnEnemy) {
        return;
    }

    Enemy enemy = collision.GetComponent<Enemy>();

    if (enemy != null) {
         IDamagable damagable = enemy.GetComponent<IDamagable>();
         if (damagable != null) {
             damagable.ReceiveDamage(DamageType.PHYSICAL, attackType, damage);
             hasHitAnEnemy = true;
         } else {
             Debug.Log("Unit is missing the IDamagable script");
         }
         Destroy(gameObject);
    }
}

```
> 1 votes

---
Tags: unity, 2d, collision-detection, collider, projectile
---


# Question
Title: Is there a generic formula to determine the angle of deflection off of a rectangle?
I have a perfect 2D system, with no friction, elasticity, etc. A ball is colliding with a rectangle. I know the angle of the motion of the ball in degrees. I want to figure out how said angle will change upon collision. I determine the angle of collision by averaging angles of a bunch of points in the intersection. What do I do with these two angles? Maybe I also have to determine if the corner is in the intersection as well and handle it differently? Also, the angles con be larger than 360. It doesn't matter for movement, since it's in polar coordinates, but it may hinder calculations?

# Answer
> 5 votes
The edges of your rectangle are just straight lines, so the angle of reflection is equal to the angle of incidence:

Now, if this surface has its own angle, we can factor that in. Call the angle of incidence/reflection θ and the angle of the surface Φ:

So our new angle is θ + Φ. But how do these relate to the angle of the original vector? Let's call that α:

Then we have, from the sum of the interior angles and the supplementary angle of Φ:

α + θ + (π - Φ) = π

α + θ = Φ

and the angle we want is

θ + Φ = 2 Φ - α

where, to reiterate, α is the angle of our incoming object and Φ is the angle of the reflecting surface.

For inside corners, you can consider that as two reflections off of surfaces that are at an angle of π/2 to each other, resulting in a turn of π (back in the direction it came from).

For outside corners, you can consider the plane of reflection as perpendicular to the vector to the point of contact:

This time μ is the angle of the vector drawn from the ball's center to the point of collision. So now

Φ = μ + π/2

and the resulting angle is

2 Φ - α = 2 μ + π - α

where, again, α is the direction of motion and μ is the angle from the center of the ball to the point of contact.

---
Tags: collision-detection, mathematics, collision-resolution, trigonometry
---


# Question
Title: Is there a way to calculate velocity for root motion controlled character in Unreal Engine?
So I see variations of this question all over the place, but no satisfying answers, so here goes.

When using root motion to move your character in Unreal Engine the Velocity property of the Movement Component returns the velocity of the animation/root bone and not the actual velocity of the character. These two things are the same when there are no obstacles, but if the character is blocked by something and just walking in place (i.e facing a wall so he can't move forwards) the Velocity property is still returning the velocity of the animation/root bone as if it was moving through the wall unhindered, even though the actual velocity of the character is now zero.

Is there some (easy and performant) way to calculate the actual velocity of the character?

# Answer
in your case, i think u could use IF for colliding object, If your player (forward arrow) collide with object u could set forward velocity to 0.
> -1 votes

---
Tags: unreal
---


# Question
Title: Best way to dynamically enumerate a list of types, and then route tasks based on those types?
I am programming a Jobs Queue in Unity, so that I can send Tasks/Jobs to a central queue where the tasks will be processed.

First, I defined 3 possible job types inside of a Scriptable Object.

`public enum jobsType {justPlay, playAndWait, justWait}`

Then I defined a class inside of the same Scriptable Object, so that each Jobs could have 3 inputs: a GameObject, a jobs Type, and a float. Here's the whole Scriptable Object.

```
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Audio;
using Unity.VisualScripting;

public enum jobsType {justPlay, playAndWait, justWait}

[CreateAssetMenu(fileName = "New JobsData", menuName = "Jobs Data", order = 51)]

public class JobsData : ScriptableObject {

    [SerializeField]
    public JobsItem thisJobsItem;

    [IncludeInSettings(true)]
    [System.Serializable]
    public class JobsItem {

    [SerializeField]
    public jobsType typeOfJob;

    [SerializeField]
    public GameObject thisGameObject;

    [SerializeField]
    public float jobsNumber;
}
}

```

Then in my code, I use a Switch to route the jobs processing based on the jobs Type enum. This code is working great - so far, so good!

That said, I don't want to have to modify this JobsData Scriptable Object every time I want to add a new jobs Type. I'm trying to honor the Open-Closed Principle: "software entities (classes, modules, methods, etc.) should be open for extension, but closed for modification."

It would be ideal if I could define jobsType to be a separate Scriptable Object... and then use a Switch to route between various jobsTypes.

At first, I was considering doing the following:

1. Create Scriptable Object assets using JobsData, where each asset represents a Jobs Type
2. Create a List of these Scriptable Object assets
3. Use that List to dynamically generate an Enum (not sure if this is possible)
4. Then use that Enum to power a Switch. (also don't see how this is possible).

But as I thought it through, I realized that this might not be the best path forward... since as I understand it, Enums must be specified at compile time. Beyond that, I can't figure out how I would even use any dynamically-generated Enums in my Switch.

Right now my code works because I define my Enums in the class, but not sure how to achieve the same thing with a dynamic Enum (if those are even possible).

I'd love to be able to define my JobsTypes as Scriptable Object assets, and then route jobs based on those assets. Given that:

1. Is there an alternative to a Switch I could use to route JobsTypes to the appropriate processing code?
2. Or alternatively, is there a way I could use dynamically-generated Enums in a Switch?

Or maybe I'm thinking about this all wrong? Open to any and all ideas!

# Answer
As I reread your question, I think you can do this with just plain old inheritance. First we'll declare an abstract base class for all our job types, and expose a `Process()` method. Here I've defined it as an `IEnumerator` on the assumption that you want these to run as coroutines so they can include delays, based on your "wait" names, but you could also make it just a plain `void` method if you don't need that.

```
public abstract class JobType : ScriptableObject {
    public abstract IEnumerator Process(JobData data);
}

```

Then we can implement derived classes for each distinct processing behaviour you need:

```
[CreateAssetMenu(fileName="JustPlayJobType.asset", menuName="Job Type/Just Play")]
public class JustPlayJobType : JobType {
    public override IEnumerator Process(JobData data) {
        // "Play" code goes here.
        yield break;
    }
}

[CreateAssetMenu(fileName="PlayAndWaitJobType.asset", menuName="Job Type/Play and Wait")]
public class PlayAndWaitJobType : JobType {
    public override IEnumerator Process(JobData data) {
        // Play" code goes here.
        yield return new WaitForSeconds(data.jobItem.number);
    }
}

```

Then instead of a switch statement, you can just read the job type scriptable object from your job item and invoke its process method:

```
IEnumerator ProcessJobs(Queue<JobData> jobs) {
    jobsInProgress = true;
    while (jobs.Count > 0) {
        var job = jobs.Dequeue();
        var jobType = job.jobItem.jobType;
        yield return jobType.Process(job);
    }
    jobsInProgress = false;
}

```

You can then run `ProcessJobs` as a coroutine and it will run the jobs sequentially, including waits as specified by the respective job types in the collection.
> 2 votes

---
Tags: scriptable-object
---


# Question
Title: How do I make Inno Setup quit if the system does not meet minimum requirements?
We are developing a game using Inno Setup and require a feature where the installer detects system specs (CPU, GPU, RAM, Disk Space) and automatically quits or prompts to quit if the requirements are not met.

How can we do this with Inno Setup?

# Answer
According to their FAQ entry for conditional installs:

> Can Inno Setup do a conditional installation - for example, proceed only if a certain registry key or file exists?
>
> Yes, through the Pascal Scripting feature.
> 0 votes

---
Tags: installer, requirements
---


title: Changes to in-game object affect prefab

text:
# Question
Title: Changes to in-game object affect prefab
I've created a prefab of a stick object, the stick scales as in a mobile game stick hero, the thing is I want to instantiate the prefab, but the already instantiated stick somehow affects the prefab and sets its scale to the one of the previous stick, as well as deleting user input from the object. I think it's the problem with the prefab itself, as the code worked somewhat okay before making a prefab. Main code that invokes such behaviour is GameLogic script:

```
public class GameLogic : MonoBehaviour, IGameLogic
{
    [SerializeField] private CollisionDetection _collisionDetection; //collision point of a child gameobject with 2D collider attached
    [SerializeField] private UnityEvent _onLevelPassed;
    [SerializeField] private UnityEvent _onLevelFailed;//currently unused event
    private void Awake()
    {

    }
    public void Fail()
    {
        _onLevelFailed?.Invoke(); //display Fail UI
    }
    public void Pass()
    {
        _collisionDetection.Reset();//resets collision detection script for the next pillar
        _onLevelPassed?.Invoke();//instantiates the stick at collision point
    }
    public void Determine() // calls the functions based on whether or not the stick collided with the pillar
    {
        IEnumerator GameLoop()
        {
            yield return new WaitForSeconds(.1f);
            if (_collisionDetection._collided)
                Pass();
            else
                Fail();
        }
        StartCoroutine(GameLoop());
    }
}

```

When the level is passed, I remove input from the stick, as well as move it to the point of collision and then I instantiate it, however the new stick gameobject seems to be a modified version of the previous stick even though I set it up to be a Transform of the stick with the needed scale and input. InputRemover script:

```
public class InputRemover : MonoBehaviour, IRemoveInput
{
    private InputHandler _inputHandler;
    private void Start()
    {
        _inputHandler = transform.GetComponent<InputHandler>();
    }
    public void RemoveInput()
    {
        Destroy(_inputHandler);
    }

}

```

The Scale script:

```
public class StickGrower : MonoBehaviour, IStickGrower
{
    [SerializeField] private float _speed;
    public void Grow()
    {
        var scale = transform.localScale;
        scale.y += _speed * Time.deltaTime;
        transform.localScale = scale;
    }

}

```

And the Instantiator script

```
public class StickInstantiator : MonoBehaviour, IStickInstantiator
{
    [SerializeField] private Transform _stickPrefab;
    [SerializeField] private UnityEvent _onStickInstantiated;
    private Vector2 _instantiationPosition;
    public void Instantiate()
    {
        Instantiate(_stickPrefab, _instantiationPosition, Quaternion.identity);
        _onStickInstantiated?.Invoke();
    }
}

```

InputRemover removes input when the stick has rotated, while the StickScale script scales the object on key down.

# Answer
> 0 votes
It looks like you're not capturing a reference to the new *instance* of the prefab you spawned. So when you invoke your events, you're invoking them on the original prefab, not the spawned instance.

You probably want to do something a bit more like this:

```
public class StickInstantiator : MonoBehaviour, IStickInstantiator
{
    [SerializeField] private UnityEvent _onStickInstantiated;
    private Vector2 _instantiationPosition;
    public void Instantiate()
    {
        // Instantiate a copy, and hold a reference to that copy.
        StickInstantiator instance = Instantiate(this, _instantiationPosition, Quaternion.identity);

        // Invoke the event on the copy, not on the original.
        instance._onStickInstantiated?.Invoke();
    }
}

```

But you have not shown us the full configuration of the Stick prefab, including the `StickInstantiator` component in the inspector, so it's still difficult to say for sure. This is why I asked you to share a Minimal **Complete** verifiable example. A good question leaves *nothing* undefined that we'd need to ask you follow-up questions to clarify.

---
Tags: unity, prefabs
---


# Question
Title: Does an average professional game development project have a higher rate of bug occurrence than other fields?
Does game development's iterative, interactive, and multi-area nature make it more susceptible to the occurrence of bugs, compared to other fields such as desktop, web, and mobile software development?

Provide statistics of your project if possible.

I am currently working on a game project where 50% of development cards are bugs, and I intend to discover how it compares to other projects.

# Answer
> 3 votes
There is no answer to your question.

First you need to define what is a bug.

Say I write a feature. I'm done with the code, and I start testing it. I find something that is not quite what I expected. So it *could* be considered a bug. I fix it, test again, and the code I wrote seems to work fine.

Now if I ship this feature to the test department, and they find something they think is not quite what they expect; now if the testing of feature is part of the normal development process, and it's expected that they find such kind of issue, is it a *bug* or just something that needs fixing (in which case it will be part of the "feature" card)? If the test department is the last step before shipping, and they find something, it'll likely a *bug* and you'll likely get a *bug card*.

And once the product is in the hands of the client, and they report something, you'll likely also get a bug card.

So here we have four "issues" that could be considered *bugs*. Which of those your team considers actual bugs?

Then you need to consider how your team handles those bugs.

"Bug management" differs from team to team. Some teams *stop everything they do* when a bug gets on their JIRA board, some will accumulate them and wait until they can fill up a full sprint only with bugs to fix, some teams will send the bugs to fix to their junior devs/new hires.

It will even differ within the same team during development. An increased attention to bugs may be given once the project gets close to the shipping date, while focus may be on broad development during the earlier days.

Finally, you need to consider the nature of those "bugs". A spelling mistake in an obscure part of the user manual *is* a bug, but it will be much less of an issue for a game where you get a solid tutorial than when the software is about the actual language.

For these reasons, since every team is different, there is no one metric that you can use to compare your own team to other teams/other fields.

---

> I am currently working on a game project where 50% of development cards are bugs and I intend to discover how it compares to other projects.

I bet you're asking this because you find you have a lot of bugs on your JIRA tasks list, and a colleague just said that it was because game development was a bug-prone domain.

As it's been commented by thedemons on this version of the question on SO:

> game development tends to require a lot of maths, and needs to be able to handle a lot of edge cases because the players/users usually have more freedom interacting with the application compared to other fields. Therefore, it is more prone to error.

Being *error prone* does not relate to the proportion of bugs on a JIRA board.

The amount of bug cards you have on your JIRA board only relates to how *your team* works. If you think the ratio of bugs/not-bug cards is too high, it may be time to try and convince your team to think about how you work and what/how you prioritize: make sure no bugs stay there for more than one sprint? Make sure the definition of "done" requires that the feature is tested and *ready to ship*? Empower your devs and allow peer testing?

That's for you and your team to decide.

---
Tags: project-management
---


title: This script keeps crashing

text:
# Question
Title: This script keeps crashing
I'm using the arcade library, and this script keeps crashing. I think it's my function but idk. Definitely the script, I've run it from two IDEs and the file explorer and every time it shows a black screen and then after a second says "not responding". Full script below.

```
import os
SCREEN_WIDTH = 1000
SCREEN_HEIGHT = 2000
arcade.open_window(SCREEN_WIDTH, SCREEN_HEIGHT, "Asteroids.py.gg.bozo.gitgud")
arcade.set_background_color(arcade.color.BLACK)
arcade.start_render()
def loadKraft(x, y):
    arcade.draw_line(x, y + 25, x - 14, y - 18, arcade.color.RED, 6)
    arcade.draw_line(x, y + 25, x + 14, y - 18, arcade.color.RED, 6)
    arcade.draw_line(x - 14, y - 18, x, y - 12, arcade.color.RED, 6)
    arcade.draw_line(x + 14, y - 18, x, y - 12, arcade.color.RED, 6)
loadKraft(0, -59)
arcade.finish_render()
arcade.pause(60)

```

# Answer
> 1 votes
> keeps crashing

Technically, nope.

> every time it shows a black screen and then after a second says "not responding"

Your script is technically *freezing* or *stalling*.

> it shows a black scree

In this piece of code

```
def loadKraft(x, y):
    arcade.draw_line(x, y + 25, x - 14, y - 18, arcade.color.RED, 6)
    arcade.draw_line(x, y + 25, x + 14, y - 18, arcade.color.RED, 6)
    arcade.draw_line(x - 14, y - 18, x, y - 12, arcade.color.RED, 6)
    arcade.draw_line(x + 14, y - 18, x, y - 12, arcade.color.RED, 6)

```

try to replace x and y with the values you supply here:

```
loadKraft(0, -59)

```

You'll realize that the `y` coordinates you supply are always negative. This likely means that you try to draw outside your viewport and so, well, you don't see it.

To fix this, try to draw everything using positive coordinates.

> `arcade.pause(60)`

This will pause your game for 60 *seconds*. I don't know what is the intention here, but if you started your script and did not wait those 60 seconds, it likely means that you ask your game to *freeze* during this period of time until it finishes.

So to fix this issue, try to make it pause for a smaller amount of time.

> Any way I can get the script to keep displaying the render without making it seem unresponsive?

I think what you're missing, from looking at examples (I haven't tried it myself), is to call this

```
arcade.run()

```

instead of

```
arcade.pause(60)

```

---
Tags: 2d, python, arcade
---


# Question
Title: How were/ are integer angles calculated in regards of sin/cosine?
Older Games (PSX hardware, but also N64) used 16 bit integers for their angles.

I grasp that 0 = 0rad and 65535 = Pi\*2rad.
But how would someone generate directions out of it, since the range from sine/cosine are \[-1,1\]

# Answer
> 2 votes
First of all, games of that generation did not calculate sine and cosine values in real-time. The hardware back then was too slow at trigonometric functions to do that. Instead they used sine tables. They had precomputed arrays of angles and their sines in memory and then just did lookups (We don't do that anymore today because on modern CPUs and GPUs, calculating a sine is actually cheaper than looking up the value in memory).

But those sine tables still had integers. So how do you represent the value of 0.7071 in it?

One option is to multiply it by a fixed factor like 1000. So sin\[45\] = 707. If you then want to turn a direction and an angle into a vector, you would calculate `vector.x = (dist * sin[angle]) / 1000`.

But divisions are also rather expensive. But do you know what is actually a really fast operation? Bit-shifts! The bit-shift operation means to move all the bits in a value left or right by a certain number of places. Many programming languages use the operators `<<` and `>>` for left-shift and right-shift respectively. This is an operation which is lightning-fast on many CPUs. What do you need that for? If you multiply or divide by a pwer of 2, then you can substitute this by a bit-shifting. It's basically the binary equivalent of multiplying or dividing by powers of 10 by adding or removing zeros.

So you don't fill your sine table by the values multiplied by 1000 but by some power of 2. For example 2^10 which is 1024. So sin\[45\] is 0.7071 * 1024 or 724. Then you can substitute the division by a much faster bit-shift of 10 places: `vector.x = (dist * sin[angle]) >> 10`.

# Answer
> 0 votes
Use fixed-point arithmetic, which means putting an implicit binary (or decimal, or some other base) point somewhere in the number.

For instance, in a 16 bit number, you could decide to have 8 bits before the binary point, and 8 bits after, which would give you a range of 0 to 255.99609375 (or -128 to 127.99609375 if treating it as signed), with a precision of 1/256.

For this particular example, 2 bits before the binary point and 14 after would give the best precision (it gets you numbers from -2 to 1.99993896484375 with a precision of 1/16384), which may or may not be suitable depending what you wanted to do with the numbers afterwards.

This has applications on very old or low end hardware that doesn't support floating point, and also cases where you want determinism that floating point rounding might get in the way of.

As an aside, trigonometry is expensive (which can be of extra importance on old and low end hardware), and it may be better to avoid the trigonometry altogether where possible, by for instance transforming a problem to use vector geometry (e.g. with dot products) instead.

---
Tags: mathematics
---


# Question
Title: Unity button highlight not working properly after spawn
I am instantiating a UI button. After it spawns if I hover on the button it highlights properly.

The problem is if I spawn the button and the mouse position is already on top of the instantiated button, then the hover event does not trigger. If I move the mouse away from the button and then back in, then the highlight works.

# Answer
> 0 votes
I sort of solved it, but in a really hacky way.

Since I couldn't refresh the button hover events, I just moved the mouse away from the button for a millisecond and then put it back on top of the button. Which does work, but its not very elegant solution. Here is the code if anyone has the same problem in the future.

```
using System.Runtime.InteropServices;

```

...

```
int x_Pos, y_Pos;

[DllImport("user32.dll")]
static extern bool GetCursorPos(out int X, out int Y);

[DllImport("user32.dll")]
static extern bool SetCursorPos(int X, int Y);

public IEnumerator Mouse_Shuffle() {
    GetCursorPos(out x_Pos, out y_Pos);

    Cursor.visible = false;
    SetCursorPos(0, 0);

    yield return new WaitForSeconds(0.00000000000001f);

    SetCursorPos(x_Pos, y_Pos);
    Cursor.visible = true;
}

```

---
Tags: unity, unity-ui
---


# Question
Title: How to set up server architecture using C++
I'm trying to make a Multi User Dungeon (MUD) game, and obviously a pre-requisite to that is a server.

I've seen stuff like this:

```
          ┌───────────────────────────────────────────────────┐
          │                                                   │
          │Game Logic Implementation                          │
          └────────────▲──────────────────────────┬───────────┘
                       │                          │
                       │              ┌───────────▼───────────┐
                       │              │                       │
Server                 │              │Event Router           │
                       │              │                       │
                       │              └───────────┬───────────┘
                       │                          │
          ┌────────────┴───────────┐  ┌───────────▼───────────┐
          │                        │  │                       │
          │Parser                  │  │Event Translator       │
          │                        │  │                       │
          └────────────▲───────────┘  └───────────┬───────────┘
                       │                          │
───────────────────────┼──────────────────────────┼───────────────────────────
                       │                          │
                       │                          │
Clients                │                          │
          ┌────────────┴────────────┐ ┌───────────▼───────────┐
          │ Client                  │ │Client                 │
          │ Input                   │ │Output                 │
          │                         │ │                       │
          │                         │ │                       │
          └─────────────────────────┘ └───────────────────────┘

```

(Credit to stack exchange user Phillip on the Gamedev Stack Exchange)

But that's relatively advanced. Is there some way to structure my project more like this?

```
          ┌───────────────────────────────────────────────────┐
          │                                                   │
          │Game Logic Implementation                          │
Server    └────────────▲──────────────────────────┬───────────┘
          ┌────────────┴──────────────────────────▼───────────┐
          │                                                   │
          │Function                    or Library             │
          │                                                   │
          └────────────▲──────────────────────────┬───────────┘
                       │                          │
───────────────────────┼──────────────────────────┼───────────────────────────
                       │                          │
                       │                          │
Clients                │                          │
          ┌────────────┴──────────────────────────▼───────────┐
          │ Client                     Client                 │
          │ Input                      Output                 │
          │                                                   │
          │                                                   │
          └───────────────────────────────────────────────────┘

```

To put that more complex stuff under the hood? That way I can focus on developing the game and not setting up a complex server system that basically carries two variables from the client to the server and two variables from the server to the client.

I've tried tutorials, pre-built (public domain) code, and even books but I still can't seem to make it work from scratch.

# Answer
# That sort of middleware is a Game Engine

From your diagram, it looks like you only want to write game logic and maybe a little bit of presentation/UI, and are looking for a piece of middleware to handle the rest.

The purpose of a game engine is to allow designers to focus on writing the unique game logic of their game, and the engine takes care of the rest. Therefore, the thing that is most likely to solve your problem here is a game engine.

## But game engines take control over the program flow away!

Any middleware that solves your problem here will *have to* take control of the program flow. You will not be able to write a program that starts with `int main(void)` and which uses networks unless you write your own netcode.

The reason for this is that netcode for a MUD imposes a bunch of requirements on the program's flow, and adhering to those requirements is *exactly what makes netcode hard*.

### Net-code is always multi-threaded

A MUD server needs to be able to receive new log-in requests at any time, and maintain the state of each connection. It also needs to receive input from already connected players, and actively maintain the connections with players who are not currently sending input (to detect when they get disconnected ungracefully).

Every implementation of this that I've seen or worked on has used threads. One thread listens for new connections, each already active connection gets a thread, and the game logic runs on yet another thread.

### Net-code is a mess of tricky edge cases, all different

A lot of things can happen when you try to receive data on a socket. Maybe you get the data you expected. Maybe you get data you didn't expect (like a hacker testing your defenses by sending malformed packets). Maybe you don't get data at all because the connection is gone. If you write your own netcode, you have to decide how to handle each of these cases. If you use an engine, you'll have out-of-the-box solutions that just work, based on industry standard practices.

### You will probably need to persist character/account data

Your players will probably disconnect and reconnect. Sometimes this will be for network-related reasons, but quite often because humans need to sleep. Handling accounts and authentication yourself will take a lot longer than you think it will.

## Are there engines that don't restrict my game logic?

Yes, lots. At a quick search, I found TinyMud-Server which seems pretty close to what you're looking for - but it's a complete program that you add your code to, not just a piece of middleware that you can link with.

If that doesn't meet your needs, there's dozens of other engines out there. A google search for `mud server engine c++` will turn up a few hits.

## What if I really do want to write my own?

If you're really looking to write your own server, I'd recommend the following:

* **Allocate enough time to learn.** Going from "what is a socket?" to "writing a MUD from scratch" will take more than a week, and probably more than a couple months. (It took me two years, but I wrote a couple of other games in between.)
* **Write a TCP echo server.** Follow a tutorial for creating a simple one-connection-at-a-time TCP echo server and client. There's lots of such tutorials out there: search for "TCP echo server tutorial C++" to get started.
* **Expand that server to multiple connections.** Once you've created a one-connection-at-a-time server, the next step is to handle multiple clients. `listen` on one thread, `receive` on one thread per client, and whenever a message comes in, post it to a queue where another thread will see it and `send` it back to each client.
* **Turn it into a chat server with accounts and sign-in.** Add a sign-in process to your initial connection and prepend each message that gets re-sent with the account name.
* **Convert the `send` thread into your game logic.** Once you have the above all finished, it should be straightforward to turn it into a MUD by replacing the main "send message" thread.
> 5 votes

---
Tags: c++, client-server, text-based, mud
---


# Question
Title: Using atan2 vs dot product to get an angle in 2D games
I have some confusion that I need to be cleared up about the `atan2` function.

I am making a game in Godot where a 2D ship rotates to face some object in space by using `atan2` and it is working good. `Atan2` finds angle between that object and the ship, right?

If so, what is with dot product then, since dot product also finds angle? I have a feeling it's very simple but I'm confused about the difference between these functions.

# Answer
> 0 votes
`atan2(v.y, v.x)` gives you the *bearing* angle of a *single* vector. That is, the signed angle of rotation measured counter-clockwise from the positive x axis to that vector. Vectors with a negative y component will give you a negative (clockwise) angle. So this gives you an absolute reference coordinate system to rotate to exactly this direction.

The dot product of *two* vectors gives you the cosine of the angle *between* them, multiplied by the length of each vector. If we normalize the vectors first so they both have length 1, then this simplifies to just the cosine, and we can take the arc cosine of that value to get an angle:

`angle = acos(dot(normalize(a), normalize(b)))`

This tells you this *magnitude* of the angular gap between them, but unlike `atan2` it does not tell you the direction of rotation - you will only ever get positive angles this way. In the diagram below, both `acos(dot(a, b))` and `acos(dot(c, b))` will give you the same angle:

So this is no longer an absolute angular coordinate but a relative measure. That means the dot product is good for measuring how parallel two vectors are to each other (1 = 0° = parallel, 0 = 90° = perpendicular, -1 = 180° = anti-parallel), but not good for determining which direction to rotate to get from one to the other.

To get that, you'd need to construct a perpendicular to one of the vectors (which in 2D is as easy as interchanging its x & y components and negating one of them), then take the dot product between the other vector and this perpendicular. Positive means rotation toward your chosen perpendicular, negative means rotation away.

---
Tags: mathematics, vector, linear-algebra, angles, trigonometry
---


# Question
Title: What are normal, tangent and binormal vectors and how are they used?
I would like to find out the following information:

* What are they?
* Example usage in game development (the area they are used in)

About the following vector types:

* `Normal`
* `Tangent`
* `Binormal`

A simple game development centric explanation would suffice.

# Answer
> 64 votes
Generally speaking, a Normal vector represents the direction pointing directly "out" from a surface, meaning it is orthogonal (at 90 degree angles to) any vector which is coplanar with (in the case of a flat surface) or tangent to (in the case of a non-flat surface) the surface at a given point.

A Tangent vector is typically regarded as one vector that exists within the surface's plane (for a flat surface) or which lies tangent to a reference point on a curved surface (ie. if a flat plane were constructed with the same normal from the reference point, the tangent vector would be coplanar with that plane).

The concept of a Binormal vector is a bit more complex; in computer graphics, it generally refers to a Bitangent vector (reference here), which is effectively the "other" tangent vector for the surface, which is orthogonal to both the Normal vector and the chosen Tangent vector.

With regards to how they are computed, this varies depending on the complexity of the surface and how precise you want the normal to be (in some cases, such as with smooth shaders, it is more desirable to calculate a normal for an approximated surface, when the actual information for a surface is not present), but there are several generalized formulas given here.

In terms of where they occur, the answer is **EVERYWHERE**. Normal vectors are used to position cameras and objects in 3D space, to determine trajectories, reflections, and angles in physics calculations, to map skins and textures to 3D models, to determine aim trajectory offsets in AI programming, to give hints to shaders about how to light, shade, and color points on a surface relative to lights, the camera, and other objects, and so on. They are possibly one of the most useful pieces of information to have in a 3D environment, and they even come in extremely handy in 2D as well.

Tangents and binormal vectors are used to determine things like torque and angular velocity, deflections of light or physical objects, and so forth. They are generally used in combination with the normal vector to give an angular 3-dimensional frame of reference to more complicated collisions, physics calculations, light deflections, and so forth; they're the additional information needed to ensure that angular momentum is preserved along the correct system of axes.

# Answer
> 21 votes
Normal vectors are typically used for lighting calculations. It is a vector that is supposed to be perpendicular to the surface that is approximated by the vertices of a mesh. Normals are defined at each vertice position but can be calculated differently depending on how you want light to refect at that vertice or what you want to do with your light calculations in the shader.

Tangent and Binormal vectors are vectors that are perpendicular to each other and the normal vector which essentially describe the direction of the u,v texture coordinates with respect to the surface that you are trying to render. Typically they can be used alongside normal maps which allow you to create sub surface lighting detail to your model(bumpiness).

There are obviously other ways to utilize these vectors and I have just described the average use of them. For more technical information I would suggest you pick up a book on computer graphics or explore some articles on the internet. There is plenty of information out there about this.

# Answer
> 10 votes
The difference between the tangent and the binormal is less immediately clear on surfaces, but that shouldn't be too surprising - the binormal was originally defined not for surfaces but for *curves*, where the concept makes a lot more sense (and where it really lives as a 'normal' in that it's orthogonal to the direction of movement, thus the name). To be more specific, given a space curve of the form p = V(t) = (Vx(t), Vy(t), Vz(t)), then the tangent - which is a vector pointing in the direction of motion - is given by Tu = dp/dt = (dVx/dt, dVz/dt, dVz/dt). (I'm using the subscript here to distinguish 'unnormalized' since I don't have my MathJax here.) Then the (instantaneous) speed along the curve is just s = |Tu|, the length of the tangent vector, and the 'normalized' tangent vector is simply T = Tu/s.

Then the normal vector to the curve is the derivative of the normalized tangent vector over time, Nu=dT/dt; the reason that the normalized tangent is used here is to keep the speed along the curve from skewing the normal vector - you can show that with this definition, we always have T.Nu = 0. Note that Nu isn't necessarily a unit vector, any more than Tu is; in fact, its magnitude k = |Nu| is the (instantaneous) *curvature* of the curve at the given point, and the point p+Nu is the center of the so-called *osculating circle* (at the given point). The normalized normal is then just N=Nu/k, and the bitangent B is the cross product B=TxN; since T and N are both unit vectors and they're orthogonal to each other, then B is also a unit vector, and (T, N, B) is an orthogonal frame.

Note that by this definition the 'binormal' to a curve is closer to what we think of as the normal to a surface (it's the normal to the 'local' plane of the curve), and the normal to a curve is closer to what we think of as the bitangent to a surface.

(This image, sadly, doesn't really do the concept justice, but it's the best I could find on the web and I can't readily build my own...)

# Answer
> 9 votes
I know this is old but i would like to add a little practical information. As stated by others but more specifically related to graphical programming.

1. A **Normal** aka (a surface normal) is orthogonal to a flat plane our triangles surface. (it sticks out from it)
2. A **Tangent** can be considered to be a normal that lies along or on that plane (its co-planar) typically this is chosen from a quad on a mesh, (so a side of two triangles that form a square), is typically applied to two triangles to be the tangent for two or all of the vertices of the quad depending on how precise it needs to be.
3. The **Bi-tangent** or called a **bi-normal** or called a **co-tangent**. A vector on plane may give the notion of direction however, a complete matrix is comprised of 3 unit length vectors to describe a orientation so this is that. The BiTangent is computed via the **Cross Product** as it has the property of being orthonormal or perpendicular (at 90 degrees) to both the normal and the tangent. (*actually each of these are perpendicular to the others proper and so knowing any two gives the other with a cross product*)
4. All these vectors, the normal, the tangent and the bi-tangent, are typically **unit length** to say they are **normalized** when used in graphical programming.
5. Care must be taken when performing a crossproduct on these vectors to ensure that the desired **Winding Order** is understood, be it if you are defining it or adhering to someone else's mesh or model winding order (their intent). To say Cross(A,B) is the opposite of Cross(B,A) thus the direction would opposite. (*this can lead to, if placed into a matrix, to what amounts to a transposed matrix and or improperly defined matrix in the axis of the mistake*)
6. The bi-tangent maybe calculated typically on the gpu or stored via pre-computation in the vertices data for a mesh or model.

*Practical Relation to a 4x4 matrix.*

Typically as you may be aware a commonly used right handed 4x4 matrix has 3 vectors denoting the **forward** the **up** and the **right**. These three unit length vectors together placed in a matrix equates to a complete orientation matrix. (For example the matrix may relate to these vectors like so, though this is not standardized as far as i know, m.Forward = normal, m.Up = tangent, m.Right = bi-tangent).

This forms a Orientation to say it forms a Orthogonal matrix were each vector is perpendicular to the others and one vector for each dimension x y z.

When another matrix typically a rotation matrix is applied to it (*the surface being triangles in the graphical case*), the orientation describing the surface will be ... rotated properly.

So then traversal across a triangle on screen in the 2d case.

```
x = x + 1;

```

Might translate so that we move across our surface in 3d directly equivalently. (Though simplified you can see that the premise of the below formula even if the matrix m is rotated will hold)

```
x = x + m.Right;

```

*Practical usage.*

When complex rotations are applied to a surface that is for instance texture mapped if you have all three of these values you will always have it's forward its up and right no matter what orientation the surface is rotated into. The texture uv positions can be found from this or if you like its tangent and bi-tangent vectors on the surface of the triangles can be moved along from one of a triangles vertices. As easily in a 3 dimensional space as a 2d space. With this information you can map from 3d to 2d screen space or vice versa positionally when or if you need to for a variety of possible needs.

*Concrete Application.*

This is most often illustrated with the graphical technique of **Normal mapping** or Bump mapping which makes a flat surface appear to have depth which you can look up that term for more information.

# Answer
> 1 votes
As for the usage tangent and binormal (bitangent) are mostly used for normal (aka bump) mapping and related techniques. The tangent, bitangent, and normal define a rotation from tangent space (aligned with surface) to object space. When you calculate lighting, they are used to rotate a normal vector (sampled from texture map, and defined in tangent space) into object space (and then either camera or world space) for final lighting calculations. The tangents are usually calculated from the vertex normals and texture coordinates using the MikkTspace algorithm.

---
Tags: graphics, vector, vertex
---


# Question
Title: Removing duplicates/ignoring them from a 2 dimensional Array
I have a bool\[,\] Array for keeping track of Nations that are either at war(true) or neutral(false).

The problem Im having is that when going over the matrix, to display al wars in UI elements, it will actually shwo duplicates of all wars, this is ofcourse obvious because: Nation 1 is at war with Nation 2. Nation 2 is at war with Nation 1. So it will ofcourse display both, but I just want one.

So how do I remove/ignore the duplicates?

Heres my code for generating the matrix:

It wont let me post images or code.

```

    public static void Init(Nation[] nationsArray)
    {
        nations = new List<Nation>(nationsArray);
        int numNations = nations.Count;

        enemyMatrix = new bool[numNations - 1, numNations - 1];

        for (int i = 0; i < numNations - 1; i++)
            nations[i].ID = i;
    }

    public static bool AreNationsEnemies(Nation nation1, Nation nation2)
    {
        return enemyMatrix[nation1.ID, nation2.ID];
    }

    public static void SetAsEnemies(Nation nation1, Nation nation2)
    {
        enemyMatrix[nation1.ID, nation2.ID] = true;
        enemyMatrix[nation2.ID, nation1.ID] = true;

        numberOfActiveWars++;
    }
    public static void SetAsNeutral(Nation nation1, Nation nation2)
    {
        enemyMatrix[nation1.ID, nation2.ID] = false;
        enemyMatrix[nation2.ID, nation1.ID] = false;

        numberOfActiveWars--;
    }
    }

```

So thats the problem, it displays the wars doubly so!

I appreciate any help, thanks in advance!

# Answer
Consider only one half of the matrix. You can do it with

```
// Reading out the nations having war by eliminating the duplicates
for (int x = 0; x < numNations; x++) {
    for (int y = 0; y < x; y++) {
        // Here y is always < x, so we get e.g. x = 5, y = 3 but never x = 3, y = 5
        if (enemyMatrix[x, y]) {
             TODO: add nations nations[x], nations[y]
        }
    }
}

```

or, if you want `y` to be greater than `x`

```
   for (int y = x + 1; y < numNations; y++) {

```

---

Btw. the declaration of the matrix should be

```
enemyMatrix = new bool[numNations, numNations]; // Without the -1

```

Because in C# you specify the size of the matrix dimensions and not the upper bounds as in VB.

---

The matrix is automatically created with all the positions set to `false`. So, `SetAsNeutral` might not be necessary, unless you must change the values later.
> 0 votes

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


# Question
Title: Draw a player in an isometric tilemap in the right order
I'm trying to create an isometric tilemap world in Godot 4 beta 4. The world is made of blocks on top of each other where for every Y level (thinking the world like if its in 3D coords) there is a different layer of tilemap.

My player is like 1.5 blocks tall and I want to put it in the world, but I can't understand how to draw the player in the right order with the tilemap to prevent the player going over or under every layer of the tilemap.

Right now every layer except the terrain one is drawn on top of the player like in this image:

Expected result:

Another example of an expected result:

I also tried making the same thing with threejs before doing it in godot where I can define the order of every object before rendering every frame, so I divided my tilemap by distance from the camera and put the player in the right spot in the rendering order based on its distance from the camera (its like zindex but without changing the actual Z of the sprites, just calculating it from the X and Y coords of the world).

But I don't think there is a way to do this in godot and I have no idea where to start.

The question is, how do I manipulate the rendering order of the tilemap to make the player fit in the right spot? If this is not possible, is there any way to archieve the expected results?

# Answer
> 0 votes
# Customizing Draw Order

According to this issue, there is currently no support in Godot for customizing the draw order how you want, but there are some workarounds:

1. Manually sort your tiles. "TileMaps currently break ties by rendering the oldest tiles first" so you can change the draw order by creating tiles in your intended order.
2. "changing the second value in the TileMap's cell\_custom\_transform to a very small number like 0.01 so tiles are rendered from left to right."

> This is because the tiles on the left have an indiscernibly smaller y value. This could be changed to -0.01 to render from right to left.

> This does mean that your tiles won't be perfectly horizontally aligned, and will drift by a pixel every 100 tiles. But, this small amount of drift may be preferable to the blinking of the xsort() function I provided.

# Controlling tall item draw order

Looks like changing the node hierarchy to allow y sorting to sort individual nodes as described in this answer might help for properly sorting your character (who is taller than a single tile).

Essentially, make sure your character is at the same level in the hierarchy as all of the other tilemap nodes (instead of putting all your doors/torches/etc under one node).

Also, make sure the character's root position is at their feet so when their feet are in front of a wall, their whole body is also considered in front of the wall.

> then the walls tilemap should sort the wall tiles, the character, and all the torch nodes based on their Y position. Although, I can see a small issue where the Y position of the wall tile matches the wall tile, causing the wall to be on top (maybe). This should be fixable by moving the torch down a little (by 1px or even less).

---
Tags: 2d, tilemap, isometric, draw-order, godot-4
---


# Question
Title: Is it possible to draw billboards from point data held in a compute buffer?
I'm currently trying to show a galaxy and have developed a compute shader that places/moves "stars".

Another vertex/fragment shader reads the buffer and currently places a point at each location.

I'm achieving this by getting a reference to the shader, binding the same compute buffer and then calling `Graphics.DrawProceduralNow()`

```
    private void InitialiseShaders() {
        int itemSize = Marshal.SizeOf(typeof(MapShaderStarDetail));
        starLocations = new ComputeBuffer(
            numStars,
            itemSize);

        //....Blah....
        mapComputeShader.SetBuffer(Kernel("BuildStars"), "starBuffer", starLocations);
        Shader.SetGlobalBuffer(Shader.PropertyToID("starBuffer"), starLocations);

        mapMaterial = new Material(mapRenderShader);
        mapMaterial.SetBuffer("starBuffer", starLocations);
        //....Blah....
    }

    private void Update() {
        mapComputeShader.Dispatch(Kernel("MoveStars"), threadDimensions.x, threadDimensions.y, threadDimensions.z);
    }

    public void OnPostRender() {
        mapMaterial.SetFloat("maxRadius", maxRadius);
        mapMaterial.SetPass(0);
        Graphics.DrawProceduralNow(MeshTopology.Points, numStars, 1);
    }

```

This works as expected...

However, I need to use an obscenely large number of stars to get the visual density I'm looking for.

Ideally, instead of rending a point at each location, I'd render an instanced billboard with a circular sprite, then significantly reduce the number of stars.

This would also allow me to add dust clouds and similar for added visual complexity.

I've tried swapping `MeshTopology.Points` to `MeshTopology.Quads` but I've hit two issues:

* The fragment shader only returns one point for each buffer item, so it effectively picks 4 random stars to form a quad, rather than 4 quads per star.
* I don't see any obvious way to keep the billboard angled towards the camera.

I'd prefer to keep the existing data structure (entry per point, rather than entry per billboard corner) if possible, to avoid needless duplicating other properties.

Is this possible?

# Answer
I think you might want to use DrawMeshInstancedIndirect (or another function in that family, like DrawMeshInstancedProcedural). That way, you can specify the mesh that you want to draw (in this case, a quad) at each of the points, and you get to write a vertex shader in which to do the billboarding.
> 0 votes

---
Tags: unity, shaders, rendering, fragment-shader, compute-shader
---


# Question
Title: Give the Volume of a Sound a Character is currently making
I'm looking to have a sound file drive the location of a bone or morph target, to create a basic form of lip syncing. Specifically, I'm looking for help getting the volume of the sound file as a float.

An example of what I mean can be seen in Half Life 1. The scientist has an audio file, and the volume of the audio causes the mouth to open depending on how loud the volume is.

https://youtu.be/JoV9o6b91Sc?t=466

https://i.makeagif.com/media/3-19-2021/JmU6Gx.gif

This seems very simple but I havn't really found anything on doing this in Unreal.

# Answer
By use of 'Audio Synesthesia' I managed to do this. I followed This Tutorial to do it, plugging the value into a Morph target that moves the mouth.

Thanks to @Adam to the guidence
> 0 votes

---
Tags: audio, character, unreal-5
---


# Question
Title: Why there are two different games with the same title?
I have found 2 games that have similar title called City Racing and City Racing 3D. Why this game have a same title? A Russian developer EA Group creating this game before the Chinese developers does. 3DGames and Feamber are a Chinese developers, they creating a game that similar title called City Racing 3D.

Logos:

Gameplays:

What is the difference between City Racing and City Racing 3D?

# Answer
> 3 votes
The other answer is incorrect. It's not actually required to register a trademark in order to enforce it. You can legally enforce an unregistered trademark as soon as you start "using the name in commerce", or in other words the moment you start to sell your game. Registering a trademark serves as a way to secure a trademark before you release your game and can make certain legal proceedings a bit easier, but it is certainly not required. Whenever you see a company use the ™ symbol instead of the ® symbol after a product or company name, they decided to save the money for a trademark registration and purely rely on the automatic protection of the name through use in commerce. And no, it's not required either that you wrote the name of your game with a ™ every time you mention it. The ™ is just a warning for others that you consider this your trademark.

For more information on trademarks I recommend the video "Practical IP Law for Indie Developers 301: Plain Scary Edition" from GDC 2018. The section on trademarks begins at 12:35.

So whoever released their game first should now theoretically be able to sue the other for trademark infringement.

Why doesn't that happen?

Well, trademark lawsuits are voluntary. You *can* sue people who use your trademark, but you are not forced to. It is very well possible that they are not aware of the other game, or if they are they don't consider it worth their time and their money to take legal actions. Or perhaps they did write them and they came to an agreement that the second game may use the trademark.

Also, such lawsuits can be rather expensive, especially when you are suing someone in a different country. And on top of that, you mentioned that one company appears to be in China and the other in Russia. Both are countries with civil court systems with a reputation for a very strong national bias. They very rarely decide in favor of a foreign company suing a domestic one. So it is possible that their lawyers advised them that taking legal actions will probably not be worth it in this case.

---
Tags: legal, racing
---


# Question
Title: Can I build & run Unity games on PS5 without registering?
So, I have a question on building/running (B&R) Unity games for/on PS5. Specifically, this is only for educational/testing reasons with no intention to sell the games.

Question: **Is it legal to B&R unity games on PS5, without registering or reporting this activity, assuming that I keep these games to myself?**

# Answer
The full article about this can be found at https://support.unity.com/hc/en-us/articles/212064606-How-do-I-develop-to-PlayStation-platforms-

Considering the passages (emphasis mine)

> If you would like to use Unity to `develop` for PS5 or other PlayStation® hardware, you need to be a certified PlayStation® developer and have a valid Unity Pro serial key.

and

> To `register` as a PlayStation® Partner, get access to the DevNet developer network, and receive your Unity Pro serial key, you first need to register on the PlayStation® Partners website.

and

> If you `attempt to build` to a PlayStation platform, you will be faced with the following (or similar) message if you do not have a PlayStation license activated: `“Your license does not cover PS4 publishing"`.

This implies to me: No. You are not allowed to B&R even if it is for yourself without registering and you will encounter the problem that without registering, you won't even be able to build the game for just your own PlayStation. Trying to circumvent that is against the Eula and might bring you legal trouble.
> 2 votes

---
Tags: unity, legal, playstation5
---


title: Godot distorting pixels

text:
# Question
Title: Godot distorting pixels
As the title says, Godot is stretching/distorting pixel art. It seems to be dependent on where on the screen the pixel is located.

I've already double-checked my project settings and searched several queries, to no avail. It looks okay in the preview and editor, but this happens when running. It doesn't matter whether it's debug or release, regular resolution or full screen, it still happens. Based on other people's posts, I think it's due to resolution issues, but I'm not sure.

If it's relevant, my screen has a resolution of 2560 × 1600.

# Answer
> 1 votes
The issue, which @Theraot helped me figure out, was that the camera was zoomed at a factor of 0.7, which caused issues since it didn't divide evenly. Changing to 0.5 fixed the problem.

---
Tags: 2d, godot, resolution, pixel, pixel-art
---


title: OpenGL 4 hidden line removal

text:
# Question
Title: OpenGL 4 hidden line removal
I'm having trouble with hidden line removal in OpenGL 4. I use a vertex/geometry/fragment shader to draw the lines. I call

```
glDepthRange(0.01, 1.0);

```

before I draw the lines, and it works, sort of. Attached is a screenshot. Is there a better method? I tried other methods, but they all suffer from the limitation that lines are stuck at 1 pixel wide.

What happens is that I draw the filled triangles, then I draw over top of that with lines (3 lines per triangle, one per edge). These edges show up when the view angle is almost parallel to the surface.

I don't want the black lines showing up.

Please let me know if you wish for more code.

# Answer
> 0 votes
It is heuristically derived that one must call glDepthRange(0.1, 1.0) before drawing the game board, and glDepthRange(0.01, 1.0) before drawing the character. Thanks to DMGregory for guidance.

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


title: Quadtree UV mapping texture

text:
# Question
Title: Quadtree UV mapping texture
I need help coming up with dynamic uv values (general formula) so that my texture looks continuous through all levels of my quadtree. level 0-1 works perfectly, level 1 subdivision looks great. but continuing to level 2 and onwards is where I realized my current method isn’t going to work. I need to come up with UV values unique to each quad at different levels.

here is a working example of my code: https://codepen.io/miguel007/pen/KKeMxQY?editors=0011

line 233 in the createLodChildQuads function is where I’m doing the UV modification.

Move the red player to activate Quadtree levels. Control the red player (W,A,S,E,R,F)

level 0

level 1

level 2

# Answer
> 0 votes
so I figured out the answer to this problem 4 days ago.

pseudo code

//this allows for the correct scaling of each mesh uv for any level.
var scaling = currentMeshDimensions/rootMeshDimensions
var u_ = u * scaling
var v_ = v * scaling

// function to normalize input 0-1
function norm(val, max, min) { return (val - min) / (max - min); }

var wp = currentMesh.getWorldPosition()
var xn = norm(wp.x,rootMeshDimensions/2,-rootMeshDimensions/2)
var yn = norm(wp.y,rootMeshDimensions/2,-rootMeshDimensions/2)

var n = scaling/2

u = u_ + (xn-n)
v = v_ + (yn-n)

```

---
Tags: uv-mapping, heightmap, level-of-detail, quadtree, planet
---


# Question
Title: Is there a good reason I shouldn't use a java applet for a game?
I want to make a multiplayer browser-based game. The nice thing about using an applet is that I can make the client and the server in the same language (java/closure/scala/etc). I know there's html5 and javascript, but server side javascript isn't as mature as the jvm platform and browser support is still kind of flaky.

Applets don't seem to be widely used (except for Runescape), but is there a reason they're unsuitable or is it just because of the bad reputation they developed in their infancy?

# Answer
> 9 votes
They are obviously not unsuited for it, as demonstrated by RuneScape and Minecraft and other smaller Java applet games. There are also libraries for hardware-accelerated 3D graphics (LWJGL, JOGL). It's just not a popular language in the game development community.

You do have to consider your supported platforms though. Windows and Linux have great Java plugins, Mac has a decent one (only works at full speed in Safari in my experience), but obviously platforms such as the iPad and Google's Chrome OS would be completely missed because they do not, and probably will not ever, have the Java VM on them.

# Answer
> 6 votes
I use Java to write games and I've used C++ to write games and have found Java to be fine so long as you remain mindful of what Java's strengths and weaknesses are. The big two advantages for me, programming in Java are speed of development and deployability/portability. Compile times are much faster than in VC++ (can't speak for XCode or Clang yet) which means I can iron out problems much quicker. Also, as Eclipse is compiling constantly, I make fewer typo type errors. I've never written a piece of C++ code that 'just works' on another system or compiler. In Java, this is the norm.

On the other hand, Java has some major draw backs. Efficiency is often sited as a reason not to use Java but I've found that as long as you code in a certain way, Java can perform quite well. The trouble is, the certain way you have to code goes against what a lot of Java folk would consider good design.
At Java's heart is the 'garbage collector', it's memory management system. When writing efficient code, you want to avoid making dynamic allocations every frame in any language and this is particularly true of Java. If you set the garbage collector off due to sloppy new'ing then you can kiss smooth frame rates good bye. Secondly (and most annoyingly) Java does not support 1st class user data types. Every user data type in Java is instantiated essentially as a pointer to a class, allocated on the heap. This is awful for cache concurrency that you can't have things like an array of Vector3 objects and have those concurrent in memory - you can have an array of Vector3 pointers but that's not the same thing at all. Generally you have to use offsets into large arrays of primitive types instead.

# Answer
> 4 votes
Times have changed. To state the obvious, and because there is currently no "correct" answer to this question: you should not use a Java applet to build your game because modern web browsers no longer support Java applets. Support for Java applets was removed because of security reasons.

* Chrome removed their support around 2014.
* Safari support for it was removed around 2018 and 2020.
* Microsoft Edge has never supported Java.
* Firefox dropped the support for it around 2016.
* Other browsers use are marginal according to this (screen shot when this was checked), so you wouldn't want to support only one of those.
* The `<applet>` HTML tag used to insert an applet on a page is deprecated in HTML5 and no longer supported by most recent browsers.

You can still use Java to build games: AFAIK, there are multiple mature game development frameworks/libraries/engines available; however the way you'll distribute your game will be different than using an applet. If you wish to distribute your game through a web browser, the way to go nowadays is typically by using JavaScript.

# Answer
> 3 votes
Nothing wrong with Java applets for a web game. I wrote an open source roguelike game (Tyrant) in Java and it works very well as an applet.

Some big plus points of Java in my experience:

* Portability is excellent - given the complexity of Tyrant, it was pretty impressive that I managed to get exactly the same compiled code to run well on Windows, Mac and Linux.
* You don't have to worry about browser quirks.
* With a bit of cleverness, you can make the same code run both as an applet or as a standalone desktop application
* Performance is great assuming a modern JVM.
* All the usual plus points of Java in terms of great array of open source libraries/APIs etc.

Just be aware of the following:

* You'll need to sign your applet / get privileged permissions if you want to do things like store data on the local filesystem or access native libraries. This can be a barrier to some users.
* Startup time tends to be a bit slower than Flash or JavaScript. On the other hand, performance is better once the JVM is up and running......
* Java is a garbage collected language, so it does have very slight GC pauses on occasion. Not really a problem for casual / roleplaying / strategy games, but might be an issue for high performance 3D FPS titles where you're trying to maintain a constant jitter-free 120 FPs framerate......

# Answer
> 1 votes
If you're planning for the game to be freeware or are prepared to handle making money from it all by yourself, Java's fine. However, it doesn't have an established, wide-spread game sponsorship model like Flash does, so making cash would be a bit harder.

---
Tags: java, web
---