title: The view matrix finally explained

text:
# Question
Title: The view matrix finally explained
I must say that I am really confused by how a view matrix is constructed and works.

First, there are 3 terms: view matrix, lookat matrix, and camera transformation matrix. Are those 3 the same, or different things. From what I undestand, the camera transformation matrix is basically the model matrix of the camera, and the view matrix is the inverse of that. The lookat matrix is basically for going from world space to view space, and I think I undestand how it works (doing dot products for projecting a point into another coordinate system).

I am also confused by the fact that sometimes, it seems like the view matrix is built by translation and dot products, and some other times, it is built with translation and rotation (with cos and sin).

There are also quaternions. When you convert a quaternion to a matrix, what kind of matrix is this?

Can someone explain to me how it really works, or point me towards a good resource.

Thank you.

# Answer
---

## Spaces and Matrices

First of all, as you know, we use matrices to represent and to do coordinate transformations. They can be any of the affine transformations. That includes translation, scaling, rotation, shear, and reflection transformations.

We (traditionally) have these coordinate systems to work with:

* Model space (Sometimes called "Object space"): The coordinates inside the model.
* World space: The coordinates in the world.
* Camera space: The coordinates respect to the camera.
* Screen space (Sometimes called "Window space" or "Device space"): The coordinates for the screen.

And of course, there are matrices to transform between them:

* Model matrix (Sometimes called “Object matrix”): from Model space to World space. *You use this matrix to place objects in the world.*
* View matrix (Sometimes called “Camera Transformation matrix”): from World space to Camera space.
* Projection Matrix (Sometimes called “Camera Projection matrix”): from Camera space to Clip space.

*Wait, Clip space? Will come back to that.*

---

Of course, as you would know, we can compose matrices by multiplying them. We can also invert them, resulting in a matrix usable to do the transformation in the opposite direction.

To apply a transformation to a vector, you do a matrix-vector multiplication. Which is a matrix multiplication where one of the matrices happens to be a vector. *And yes, the code looks like a bunch of dot products, it is all multiply and add, which is very fast for the computer to do. Also, yes, the values in rotation matrices come from trigonometric operations.*

**Note**: Remember that matrix multiplication is not commutative. The order of the operands matters.

In fact, we use square (4D) matrices instead for augmented 3D matrices. *This ensures that inverse always exists*. So we augment the 3D vectors with a `w` component (usually with value `1`), and then apply the transformation. This leaves a result that has a `w` coordinate which controls translation. Our 3D translation is an affine transformation in 3D, yet it is a linear transformation in 4D.

We usually do not want to have `w` or use it for scaled translations. So we normalize by multiplying the vector by `1/w`, then discard `w`, leaving us a 3D vector. This is effectively a projection from 4D to 3D.

However, if we do not want the transformation to do any translation, we can augment the vector with a `w` component with value `0` instead.

See also Homogeneous Coordinates and Transformation Matrices.

---

So, as you can imagine, the result of transforming to Clip space is 4D. We do the above normalization by `w`, and that gives us a 3D space. This is called Normalized Device space (sometimes called “Normalized Screen space”).

Finally the conversion from Normalized Device space to Screen space is controlled by the view port (and depth range). Finally leaving us with a 2D space in pixels.

---

## Virtual Camera

We also want to model a virtual camera. The simplest perspective virtual cameras have a position in the world, an orientation, a field of view (will get to this one later).

* Position:

We are going to represent the position of the camera is by using a vector in World space.
* Rotation:

Using director (Euler) angles is going to be easier to control for first person games. *In particular for those games where where there is a clear up and down. Which are most of them.*

If we need to compose rotations, interpolate rotations, or we want controls for open space (with no clear up and down), we want quaternions. And yes, you can have the input be director angles and then create a quaternion from those angles. **Note**: Similar to matrices, you also compose quaternions by multiplication. And similar to matrices, the order matters.

If you want a camera that looks at something (for example a third person camera), you can use a Look-at matrix. *You may want to convert it to quaternions for interpolation if need to animate the camera rotating to look at something.*

You build your Look-at matrix with a forward vector which points in the direction towards where the camera is looking at, and an up vector. If you only had the forward vector, the camera rotation still have one degree of freedom (rotating around the forward vector)... The up vector fixes that. Thus, remember that the up vector and forward vector should not be in the same direction. *Ideally they are perpendicular.*

You pick what you use to represent the position and rotation of the camera for convenience. Regardless of what you use. You are going to convert them into matrices, so we can compose them for our render pipeline.

So, we will have a Camera Position matrix and a Camera Rotation matrix. *If you are using a Look-at matrix for the rotation of the camera, that is the Camera Rotation matrix, no need to convert anything.*

We are going to compose the Camera Position matrix and a Camera Rotation matrix into our Camera Transformation matrix (View matrix).

---

We still need to convert from Camera space to Screen Clip space. That is, we still need a Camera Projection matrix. The camera projection matrix is the one that would represent the camera frustum… that is, it is the one that would implement perspective. And it is the one that we create with the field of view of the camera.

*Of course, the camera does not have to be a perspective camera. This is just the common case.*

---

The Vertex shader is the opportunity we have to apply our Model matrix, View matrix and Projection matrix. Which you could pre-compose in a single Model-View-Projection matrix.

If you write your Vertex shader… you could decide to not have Model matrix, View matrix and Projection matrix. You can do thing differently. *For example, for Ray tracing.*

---

## Your questions

> First, there are 3 terms: view matrix, lookat matrix, and camera transformation matrix.

The View matrix converts from World space to Camera space. The Look-at matrix is usually used for the Camera Rotation matrix. And the Camera Transformation matrix is the Camera Position matrix composed with the Camera Rotation matrix.

> I am also confused by the fact that sometimes, it seems like the view matrix is built by translation and dot products, and some other times, it is built with translation and rotation (with cos and sin).

Sometimes the Camera Rotation matrix (Look-at matrix if you are using that) is the identity matrix, resulting in a View matrix with no rotation.

> There are also quaternions. When you convert a quaternion to a matrix, what kind of matrix is this?

At the end you are going to convert to matrices whatever representation of rotation you have, so you can apply the rotation transformation to vectors. However, you may want to do some operations between quaternions. In particular composition of rotations and interpolation of rotations.

What kind of matrix is it? It is a rotation matrix. If it is any of the (transitionally) named matrices depends on how you use it.

---

## Bonus chatter

If you want to do skeleton animation, you would use transformation to moves parts respect to others. That is also done with matrices, quaternions, etc. Perhaps a Look-at matrix can result useful to make a character point its arm in a particular direction. *You may also be interested in inverse kinematics.*

---

## Learning material

You will find a good introduction to modern OpenGL for beginers at OGLdev.

I learned the old fashion way, with the red book. It should serve you well as reference and to clear up concepts.

I also want to recommend Learn OpenGL and opengl-tutorial.

For learning to code shaders, aside from the above, I found useful Shadertoy and Shaderific.

---

By the way, you are going to want a library that handles setting up the view port (window or full-screen) and handling input... many (old) tutorials use `glut`. If you see `glut` (and you are going to) go use `freeglut`, it is a drop-in replacement... why?

> The original GLUT library seems to have been abandoned with the most recent version (3.7) dating back to August 1998. Its license does not allow anyone to distribute modified library code. This would be OK, if not for the fact that GLUT is getting old and really needs improvement. Also, GLUT's license is incompatible with some software distributions (e.g., XFree86).

-- source.

Other alternatives include `glfw` or `sdl`. See GLUT-like Windowing, GUI, and Media Control toolkits. *I'm currently on `glfw` camp.*

---

**Note**: OpenGL code is relatively easy to translate from a language to another. In particular if you are using a portable library to handle the setup of the view port. Do not be afraid of reading a tutorial for a different programming language than the one you are using. In fact, I would argue that learning WebGL is a good idea. Despite it being a different API, it is very close. I recommend the MDN WebGl tutorial.
> 14 votes

---
Tags: opengl, mathematics, graphics
---


title: SceneKit - Creating a sense of scale

text:
# Question
Title: SceneKit - Creating a sense of scale
I'm experimenting with 3D using SceneKit on iOS. I'm trying to create a galaxy but would appreciate some guidance on the following things:

1. I'm having a hard time working out how to make the galaxy seem 'big'. I've created multiple solar system nodes in a spiral, but the distances between them are hard to get right. I want to get a sense of scale, but I'm not sure of the best approach. Do I want to put huge distances between solar systems, and make the objects in the system very large too? In this case I need to set the camera zFar to be massive. I feel like I'm missing something.
2. I've created a cube map for the 'galaxy'. As I zoom in on a solar system, the cube map seems to come in very close, which breaks the illusion of scale. How do I make that better?

Thanks for any guidance!

# Answer
I work on something similar and wondered about that as well. I wanted giant stars and supermassive black holes to be perceived as incredibly huge (which they are). My thought was that any star would "look" and behave the same if you simply stood further away.

Meaning: A star with the diameter of 10 at a distance of 50 will look the same as a star with a diameter of 1000 at a distance of 5000. But there are two things to consider:

1. Giant stars have a very low relative mass! Meaning while their radius is thousands of times larger than that of "normal" stars, their mass is merely a multitude of several hundreds as large. Meaning their gravitational effect is much lower, probably causing planets to revolve around them much closer - relatively. Their lifespan is therefore also much lower, because they effectively burn their mass much quicker than other stars.
2. The speed at which stars pass by as you move in space is essential (especially FTL). If you see that normal stars pass by as visibly small objects around you, but some stars just appear to be almost static even though they are of similar size on the screen - their size is perceived as much higher.
3. Seeing large objects already at a large distance moving much quicker than even larger objects behind them also contributes to the sense of scale. Meaning: Flying past a star and seeing a giant star behind it will cause the star in front to move relatively quickly. This clearly indicates that the giant star is indeed gigantic. This plays together with number 2.

So movement is probably the best way, and the setup of the solar system the other. One scenario I can imagine is that giant stars have plenty of planets revolving around them (their mass is still high) at much closer range. It's possible that this is not scientifically accurate, but from a visual and worldbuilding perspective, it might be feasible solution.
> 1 votes

---
Tags: ios, cubemap, scenekit
---


# Question
Title: What game objects can have a "material"?
In Unity, I created an empty GameObject called "Person". I created some child objects to it, such as "head" (a sphere), "body" (a capsule), "leg" (a box), etc. Then, I wanted to change the person's color, so I created a material. However, I could not drag & drop it on the person - I could only drag and drop it on each child object separately.

My question is: what game objects in Unity are allowed to have a "material" on them? And, is there a way I can put a material on a parent object, and let it affect all its child and descendant objects?

# Answer
There are actually two completely unrelated kinds of materials in Unity: Renderer materials (which define how things are rendered) and physics materials (which define how rigidbodies behave when they bump into each other). But if you are talking about color, you are likely talking about renderer materials.

Generally speaking, you can assign a material to any game object which has a **Renderer** component. There are lots of different kinds of renderers. MeshRenderers for 3d models, SpriteRenderers for sprites and a couple specialized ones like LineRenderer or TrailRenderer. But one thing all renderers have in common is that they all use materials (in some cases more than one, for example when you have a 3d model which uses multiple materials then the MeshRenderer will have a separate material slot for each of them).

It is possible that your "Person" is just a hierarchical object which has no renderer itself but has several children which do. In that case you will have to assign the material to each of the renderers of the children.

If you want to do that from the editor, then you will have to select each of the children and assign the material to their respective renderers.

If you want to do that from a script, you can get an array with all the renderers in all the children using `GetComponentsInChildren<Renderer>()`. It returns an array of `Renderer` interfaces. This interface represents the lowest common denominator of the functionality of all the specialized renderers and only exposes those functionality they all have in common. One of those is `renderer.material`.
> 4 votes

# Answer
Sounds like you have combined multiple surfaces together to create one 'person' (object), and the material is attached to that singular surface. So if you wanted to apply one Material to that person as a whole color then it would need to be a singular surface (to my understanding at least).

Reference: https://docs.unity3d.com/Manual/Shaders.html

In Unreal you could attach that material to the parent object and its sub objects would inherit that surface, but to my knowledge that is still not a feature in unity yet. You would need to do this programatically if you wanted it to iterate through a list of sub-objects (or do it manually) like they did here: https://answers.unity.com/questions/56819/assign-material-to-multiple-objects.html

Hopefully this helps.
> 1 votes

---
Tags: unity, materials
---


# Question
Title: Is it possible to have a script built-in into a custom resource?
Here's a rudimentary custom resource:

```
extends Resource

export(Resource) var scr

```

I can drag a pre-made .gd script into this exported property in Inspector, and it works as intended. I can click on the exported property field and embed a resource (like "New ShaderMaterial"), and it would also work as intended, and I would be able to edit that sub-resource normally. However, if I click on the exported property and select "New GDScript", there doesn't seem to be a way to open the new gdscript for editing. Is it possible to embed a gdscript sub-resource the same way you can embed a different sub-resource?

# Answer
> 3 votes
As far as I can tell, Godot does not provide any GUI for this, but it *is* possible. When you add a `GDScript` to your resource, you will see that it is given a path within the resource file:

If you crack open `new_resource.tres` in a text editor, you'll see the following:

```
[gd_resource type="Resource" load_steps=3 format=2]

[ext_resource path="res://MyResource.gd" type="Script" id=1]

[sub_resource type="GDScript" id=1]

[resource]
script = ExtResource( 1 )
scr = SubResource( 1 )

```

You can write your script under the `GDScript` `sub_resource` like so:

```
[sub_resource type="GDScript" id=1]
script/source = "extends Spatial

func _ready():
    pass # Replace with function body.
"

```

This feels rather hacky, so you might consider submitting a proposal if this workflow is important to you.

---
Tags: godot, gdscript
---


title: Unity Seamless Terrain

text:
# Question
Title: Unity Seamless Terrain
I am programmatically generating terrain using unity's terrain object and assigning height maps to it via the terrainData, the problem is that there are seams even when using the GroupingId(which is used for auto connect). I even tried creating a terrain object in the editor with neighbours, and modified their terrain data via script, seams still there.

I have also tried SetConnectivityDirty after applying terrainData.

Most people who have reported this seemed(lol) to have issues with their normals at the edges, I cant see that being the issue here, but if it is, how do i approach solving it given I am using unity terrains.

If there is no good answer I will have to resort to custom meshes and lose all the nice terrain tool functionality.

Edit: Here is how I'm setting heights.

```
var terrain = GameObject.Find("test").GetComponent<Terrain>();
var terrainData = terrain.terrainData;
var noiseMap = Tool_Generators.GenerateNoiseMap(chunkSize, seed, scale, octaves, persistance, lacunarity, 0f, 0f);
terrainData.SetHeights(0, 0, noiseMap);

```

Then the actual noise generation is just a 2D array of heights, i have been using a simplified version with only 1 pass for testing.

```
  public static float[,] GenerateNoiseMap(int chunkSize, int seed, float scale, int octaves, float persistance, float lacunarity, float offsetX, float offsetY)
  {
    float[,] noiseMap = new float[chunkSize, chunkSize];

    for (int y = 0; y < chunkSize; y++)
    {
        for (int x = 0; x < chunkSize; x++)
        {
            float noiseHeight = 0;

            float sampleX = (x + offsetX) / scale;
            float sampleY = (y + offsetY) / scale;

            noiseHeight = Mathf.PerlinNoise(sampleX, sampleY);
            noiseMap[y, x] = noiseHeight;
        }
    }

    return noiseMap;
  }

```

# Answer
This question is quite old but here's an answer in case someone else is looking for a solution.

You have to stitch terrains together by matching heightmap values on the edges. Below is a code that stithces a terrain with it's left or bottom neightbor. Code assumes that terrain tiles have same size and resolution.

To stitch with top neighbor, you just switch parameters to StitchToBottom(top, terrain) and with right StitchToLeft(right, terrain).

```
    public void StitchToLeft(Terrain terrain, Terrain leftNeighbor)
    {
        TerrainData data = terrain.terrainData;
        int resolution = data.heightmapResolution;

        // Take the last x-column of neighbors heightmap array
        // 1 pixel wide (single x value), resolution pixels tall (all y values)
        float[,] edgeValues = leftNeighbor.terrainData.GetHeights(resolution - 1, 0, 1, resolution);

        // Stitch with other terrain by setting same heightmap values on the edge
        data.SetHeights(0, 0, edgeValues);
    }

    public void StitchToBottom(Terrain terrain, Terrain bottomNeighbor)
    {
        TerrainData data = terrain.terrainData;
        int resolution = data.heightmapResolution;

        // Take the top y-column of neighbors heightmap array
        // resolution pixels wide (all x values), 1 pixel tall (single y value)
        float[,] edgeValues = bottomNeighbor.terrainData.GetHeights(0, resolution - 1, resolution, 1);

        // Stitch with other terrain by setting same heightmap values on the edge
        data.SetHeights(0, 0, edgeValues);
    }

```
> 2 votes

---
Tags: unity, terrain, terrain-rendering, seams
---


title: Error cs1061 Is Showing Up

text:
# Question
Title: Error cs1061 Is Showing Up
I've been looking into this online but can only find similar cases that don't really match mine and because of that I'm having a little trouble finding a clear answer to how to fix this code. Please help and thank you.

# Answer
> 0 votes
The error tells you that Vector3 does not contain a member called c.

If you double-click your error, it will take you to this line:

```
if( transform.position.c < -10 )

```

It looks like you meant to type "x" there, not "c".

Please read your error messages carefully in future so you can solve typos like this more quickly.

---
Tags: unity
---


# Question
Title: How can I blend an animated character with ragdoll physics collisions?
I'm trying to make an effect that a ragdolled character controlled by an animator also affected by the physics collisions. Similar to this game: Crazy Shopping.

The problem is animator controller overrides every change that happens in the Fixed Update or internal physics update (even when the animator update mode set to Animate physics).

I think this can be achieved by some how changing the order of execution of the animator so it can happen before physics update. This way physics can affect the animated object. There are solutions like using a second object which contains the ragdoll and in the LateUpdate you can set the positions and rotations of the animated object which works ok but not the thing in my head.

ActiveRagdoll by MetalCore999 is also a really great work which i would love to learn how it works in behind.

How can i achieve this? i don't even know if my solution would work properly?

Do you have any suggestion or a different way of thinking. I would really appreciate a road map on this.

# Answer
There is an inverse kinematic method for blending animation with physics, it basicly tries to keep the same position and rotation of bone structure of another animated object with the ragdoll, after physics applied to the ragdoll it updates the bones in the late update. Link is here: Active Ragdoll

But I found another way around for this problem its not perfect, but it works for me. The idea is like this: for each ragdoll joint object(nodes with a character joint component) you create an empty parent node at the same position with the joint object and you use this parent object for all of the animations. That way animation does not interfere with the physics system. It should look like this:

After changing all of the joint objects you want to animate, you must use this parent objects in the animation panel.

**Warning**

If you do this you can't use mixamo animations because they use Avatar bone structure.

Maybe you can use blender for changing the armature of model and add animation joint nodes in there and configure avatar bones in the unity, but again i'm not sure if it would work.
> 2 votes

---
Tags: unity, physics, animation, blending
---


# Question
Title: How to not move my character when they collide using Unity and Box Collider?
I'm trying to get my characters near to each other so they can attack the other one, but when the player character or otherwise gets near they are pushed to the other direction when they collide. How to prevent that happen so they won't move when touching each other?

This is the player objects:

The Treant objects:

I what I want is that they collide and can't move through each other and stop moving. But this keep happen: gif of my treant getting pushed away

Can someone help me with this issue?

# Answer
Fixed by removing rigidbody from the Treant and change from kinematics to dynamics in the rigidbody from Player.

There is an explanation of what does the colliders in Unity API
> 1 votes

# Answer
If you don't want collisions to be able to push your objects, you can make them Kinematic (Under Rigidbody 2D -\> Body Type -\> Kinematic)

This tells the Physics engine "I will take responsibility for this object's movement, including dealing with collisions, so you don't have to push this object around to solve penetration"

The trick is that then you actually have to take that responsibility. If you just teleport one object into another one by setting its position, the physics engine won't intervene to stop you or push them apart, because you told it you'd handle that part.

Instead you'll want to use methods like MovePosition to move up to, but not through, the next collision, or use shapecast queries to check how far you can move your character in open space before you actually move them there
> 2 votes

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


# Question
Title: When does a Reference become Copyright Infringement?
I've seen quite a few posts on here similar to my question, but I am still having doubts about my implementation of an Easter Egg.

In the background of my game, There is a bookshelf, purely for cosmetic purposes. Because it's got books in it, I wanted to have names on all the books, as references to either real-world books, or fictional books in media.

Some Examples:

Real World Books:(These ones all have the authors names included on the cover)

```
 I-Robot

 D&D Monster Manual

 Rendevous with Rama

```

Fictional Books:(No Authors, Because they're fictional)

```
 The Necronomicon (From many H.P Lovercraft Stories)

 The Enchiridion (From Adventure Time)

 Gray's Sports Almanac 1950-2000 (Back to the Future)

```

Books Imagined by Me:

```
 Graboid Hunting for Beginers (Graboids are monsters in Tremors, but this book does not exist in the movies)

 Aperature Science Employee Handbook (Aperature Science is the corporation from Portal, but this book does not exist in the games)

```

So, My question is, is it "acceptable" to simply mention names of real-world or fictional works in a background asset such as this? Or is even that going to far? My confusion comes from the fact that i'm not using any of the writing or artwork from the works, simply stating the name of the title.

If someone could please give my some guidance on this, I would greatly appreciate it.

Thanks!

# Answer
> 1 votes
Good article on this subject here: How To Add Easter Eggs To Your Game Legally.

The article states that the following are all legal uses of references to properties within your game / easter egg:

* References to your own work
* Non Parody, indirect reference: For example, hitting a block in a game and a coin pops out of it a la Super Mario Bros. This is an iconic part of Mario games but it isn’t – by itself – a copyrighted property, a trademark name or identifier or a protected character likeness.
* Parody, direct reference: Parody is a form of critique and fair use law may cover this type of reference.

I would say your reference could arguably fall into parody category. Feels like a matter of weighing the odds of getting called out along with your desire to include the easter egg. FYI, I'm not a lawyer. If you are truley concerned then you should probably consult one.

---
Tags: legal
---


title: Can a GameObject be both 2D and 3D?

text:
# Question
Title: Can a GameObject be both 2D and 3D?
In all Unity games I saw so far, every object is either 2D (with RigidBody2D and Collider2D components), or 3D (with RigidBody and Collider components). This makes sense, but I wonder if there is any use to an object that has both (for example, both RigidBody2D and RigidBody, or both Collider2D and Collider)?

Are the worlds of 2D and 3D completely parallel and unrelated, or can they be connected somehow?

# Answer
No, it can't.

Unity won't allow you to add both a Rigidbody and a Rigidbody2D to the same game object:

It also won't allow you to add both a 3d Collider and a 2d Collider:

What you **can** have, though, is objects with 3d colliders and other objects with 2d colliders in the same scene. But those objects won't interact with each other in any way. They will just pass through each other.

The 2d physics engine and the 3d physics engine are basically two parallel universes. The renderer can perceive both of these universes, but the two universes can not perceive each other.

But what you can of course do is communicate between 2d game objects and 3d game objects via scripts. You can use that to create interactions between objects in these two parallel universes. But you have to program those yourself.
> 4 votes

---
Tags: unity, 2d, collision-detection, 3d, rigidbody
---


# Question
Title: What is wrong with my gravity calculation?
Im trying to create a method to calculate the fall time for an object using real formulas. Well I came up with this:

```
    public static double calculate_fall_time(float height) {
        final float GRAVITY = 9.81f;
        float h = (1/2)*GRAVITY*2;
        float h2 = GRAVITY/GRAVITY;
        double t = Math.sqrt(((2*h2)/GRAVITY));

        return t;
    }

```

Well I used to this website to compare the results but it wasn't the same. If I have 370 at the input then my program shows 0.4515 but the website is showing around 8,6 seconds.

Does anybody know how I can fix this problem? Thanks in advance :D

**NOTE:** I know that arcade physics are much more fun but my goal is to create a rather realistic game. Thanks for reading.

# Answer
> 1 votes
I have found a very simple solution to my problem. This is my code: `double t = Math.sqrt(2 * height / GRAVITY);` Thanks a lot! (ᴵᵐ ᵃⁿ ᶦᵈᶦᵒᵗ)

---
Tags: java, physics, physics-engine
---


# Question
Title: How to identify performance issues with large numbers of mods?
My current problem is with RimWorld, but in the past I had the same issue with Minecraft. Basically the game gets more fun with more mods, up until the point where performance becomes unmanageable. Most mods are open source and I am confident that I could fix many of these performance issues if I could only identify where the hotspots are.

So as a modder, how can I figure out where I should try and help out?

* 200+ mods, though obviously I would add more if I could.
* I don't have access to the core game source code.
* I don't have access to a debug version of the core game.
* I probably have source code access to a given mod.
* I'm looking for ways to help the community, not ways to make the game faster for just me (like adding more memory).

# Answer
> 4 votes
The issue is often death of the thousand cuts, each mod has some overhead that you cannot get around from the mod-dev's side. This is not helped by the unofficial \[redacted\] contest of how many mods you are running pushing people into having mods installed that they don't use.

One of the things you can do to alleviate overhead is to consolidate mods into bigger utility mods that replace the smaller 1 block/function mods.

Sometimes mods just don't play well together. Some interaction between them causes them to require more processing than strictly needed. This can be very hard to track down and requires deep knowledge of the mods involved and how the modding architecture is set up. Fixing it will also require cooperation between the affected mod authors.

# Answer
> 0 votes
It looks like for Rimworld specifically there is an ongoing project to create a profiler mod:

https://github.com/Dubwise56/Dubs-Performance-Analyzer

From those diagnostics it looks like the performance issues I am seeing come from garbage collection (and so indirectly memory allocation).

In theory it would also be possible to get profiling info from the mono runtime but I haven't tried to get that to work.

---
Tags: performance, modding
---


# Question
Title: Is it possible to find a seed based on 10,000 generated random numbers?
I'm currently entertaining an idea I've had about procedurally generating a world. I would like the entire world to be procedurally generated on the fly. So when a chunk is loaded, it uses a seeded random number generator to create the terrain and objects. It is seeded to maintain persistence. This is nothing new.

Next, I want the player to be able to come in and manipulate the environment (destroy blocks, place blocks; I'm using a minecraft type recreation right now to test the idea because the blocky environment is simple to work with). If we simply used a seeded random number generator, the player's changes would get overwritten once the chunk is discarded and reloaded. So what if we use the new block locations in the scene to generate a seed for a random number generator that will generate the environment. We know the exact order that it will generate blocks, so each time a number will be generated, we know what that number should be. I've looked around the cybersecurity forums a bit but haven't found a good explanation of retrieving seeds given ordered generated numbers. If this works you could save a large scene in only the seed it takes to generate it.

Please let me know if this idea is stupid and should be thrown away, thanks!

# Answer
> 6 votes
> Please let me know if this idea is stupid and should be thrown away, thanks!

This idea is \[ill-founded\] and should be thrown away.

And we can prove it with a little math!

Let's say your seed is a 64-bit integer. That means it can hold one of \\$2^{64}\\$ values.

That means that you can describe, at most, \\$2^{64}\\$ different worlds by specifying a seed. "At most," because your generator might produce identical outputs for two different values — say if your RNG function has a collision (two internal states that yield the same observable output), or if you round a value somewhere, wrap/truncate it, or use non-uniform probability to give some features a greater chance of occurring.

From this seed you're generating 10 000 blocks. Let's say each one can be specified by a single byte. The number of possible 10K block worlds that can be built in this way is \\$8^{10 000} = 2^{30 000}\\$.

There are vastly more worlds that can be produced by editing block-by-block than can ever be created by your generator acting on your seed.

So there are things your player can do to your worlds that take them outside the expressive range of your generator, and no possible seed could replicate it, even if you had a fast way to check every seed.

---
Tags: procedural-generation, random
---


# Question
Title: Stepping from Point out on Archimedes Spiral for Length along Arc
I wasn’t sure whether to put this question in mathematics or programming?

My question has two parts with the second part dependent on the first. I’m looking to use Archimedes spirals in some game code I’m writing.

I figured that there is possibly a unary Archimedes spiral from which all other achimedes spirals can be derived. (Hopefully the use of ‘unary’ is correct here?) That is a unary Archimedes spiral is one where the spiral spirals one radian outwards for every radian of angle starting at centre.

1. So my first question is: Is that true? Can every Archimedes spiral be derived from a ‘unary Archimedes spiral’ like I’ve described?

By derived I mean by the use of simple multiplication and division to transform from the unary Archimedes spiral to any Achimedes spiral with a different rate of out-spiral.

eg. spiral20RadiansOutPerRadian = unaryspiral * 20

If that is the case then could someone possibly help me also with this second question?

I’m looking to step a measured arc length outwards (and inwards) from a point that is out on a measured Archimedes spiral. So not from the zero or centre point but from somewhere out on the spiral. The begin point out on the spiral is represented by a measured radius from zero (or centre).

I’m looking to find: r' = f(r , arclen)

where r is the initial radius, arclen is the length stepping outwards along the arc (negative to step inwards) and the resultant r' is the new radius at that stepped to point.

My process for deriving from the unit spiral would hopefully then be:

```
Programmer sets a value for delta_radius which is per radian of angle.
Programmer sets a value for start_radius.
Programmer sets a value for step_length which is the length to step around arc.

The unary_step_length is worked out by dividing step_length by delta_radius.
The unary_start_radius is worked out by dividing start_radius by delta_radius.

We call achimedes() function with the two unary values and it returns unary_end_radius.

The actual end_radius is worked out by multiplying unary_end_radius by delta_radius.
The delta_angle is worked by subtracting unary_end_radius from the unary_start_radius.

```
2. My second question is: Could somebody please help me to write this achimedes() function (if the answer to question 1 is yes)?

I’m looking to have function be of the form:

```
unary_end_radius = archimedes(unary_start_radius , unary_step_length)

```

where the unary\_delta\_radius is understood to be 1 radian.

# Answer
> 1 votes
> Can any Archemedean spiral be derived from one common template?

Yes: you can verify this using the parametric equation itself. Let's define the \\$pitch\\$ of a spiral to be the rate at which its radius changes as its angle changes. So your "unary" spiral is the spiral with \\$pitch = 1\\$:

$$Spiral\_1(\theta) = 1 \cdot \theta \begin{bmatrix} \cos \theta \\ \sin \theta\end{bmatrix}$$

And a spiral with any arbitrary pitch can be expressed as...

$$\begin{align} Spiral\_{pitch}(\theta) &= pitch \cdot \theta \begin{bmatrix} \cos \theta \\ \sin \theta\end{bmatrix} \\ &= pitch \cdot Spiral\_1(\theta) \end{align}$$

> How can we compute a point a particular length further along the spiral from a given start point?

First we can differentiate our spiral function to get its rate of change:

$$\begin{align} \frac {d Spiral\_{pitch}} {d \theta}(\theta) &= {pitch} \begin{bmatrix} \cos \theta \\ \sin \theta\end{bmatrix} \+ {pitch} \cdot \theta \begin{bmatrix} -\sin \theta \\ \cos \theta\end{bmatrix}\\ &= {pitch} \begin{bmatrix} \cos \theta -\theta \sin \theta \\ \sin \theta + \theta \cos \theta\end{bmatrix} \end{align}$$

And get its length:

$$\left| \left| \frac {d Spiral\_{pitch}} {d \theta}(\theta)\right| \right| =\sqrt{{pitch}^2 \left( \left( \cos^2 \theta - 2 \theta \cos \theta \sin \theta + \theta^2 \sin^2 \theta \right ) \+ \left( \sin^2 \theta + 2 \theta \cos \theta \sin \theta + \theta^2 \cos^2 \theta \right) \right)} \\ = {pitch} \cdot \sqrt{\theta^2 + 1} $$

Then integrate this from our starting angle to our ending angle (using Wolfram Alpha):

$$ \begin{align} L &= {pitch} \int\_\alpha^\beta \sqrt{\theta^2 + 1}d\theta\\ &= \frac {pitch} 2 \left( \theta \sqrt{\theta^2 + 1} + \ln\left(\sqrt{\theta^2 + 1} + \theta\right) \right) \Biggr| ^ \beta \_\alpha \end{align}$$

Now inverting this beast is a mess, so in the past I've approximated it and then used the Newton-Raphson method a few times to reduce the error to within my needed precision. It's a strictly increasing function whose slope changes very gradually, so it's quite well-behaved for this use, thankfully.

```
// Compute the arc length from the origin to a given angle
// along a spiral with pitch = 1. radical = sqrt(angle*angle + 1)
float UnitSpiralArcLength(float angle, float radical) {
    return 0.5f *(angle * radical + Mathf.Log(angle + radical));
}

// Given a starting angle, compute a new angle that is a particular
// arc length away, along a spiral with a chosen pitch.
float ShiftSpiralAngle(float pitch, float startAngle, float signedLengthShift) {
    // This square root is both the length of the derivative at this angle,
    // and useful in computing the arc length up to that point, so let's cache it.
    float radical = Mathf.Sqrt(startAngle * startAngle + 1f);

    // On a pitch = 1 spiral, how far from 0 do we start?
    float startLength = UnitSpiralArcLength(startAngle, radical);

    // How far from zero do we want to end?
    float targetLength = startLength + signedLengthShift / pitch;

    // Start with a naive estimate of what angle gets us to here.
    // We use derivative at start angle to guess how much angle to add.
    float estimatedAngle = startAngle + (targetLength - startLength) / radical;

    // Refine our estimate using the Newton-Raphson method.
    // You can adjust a fixed iteration count, or use an error threshold.
    for(int i = 0; i < 10; i++) {
        radical = Mathf.Sqrt(estimatedAngle * estimatedAngle + 1f);
        float error = UnitSpiralArcLength(estimatedAngle, radical) - targetLength;
        estimatedAngle -= error / radical;
    }

    return estimatedAngle;
}

```

Here I've found it clearer to use angle as my parameter rather than radius, but of course you can convert between them by multiplying/dividing by your pitch.

---
Tags: algorithm
---


# Question
Title: How to make many perlin noise function match
I am trying to create procedural terrain using Perlin noise here is what I have so far:

* I create "Chunks" of a fixed size using a Perlin noise function, each chunk is a flat mesh (like a plane).
* Different Chunks can have different noise parameters (octaves, amplitude, ...) to make some part more like plains or mountains.
* now because of the noise parameters some chunk borders don't match.

How can I go about this? I have tried to lerp the borders but it makes a flat edge that is kind of ugly.

# Answer
> 3 votes
Do not assign a biome per chunk.

Instead, compute your biome as a function of position. There are a few popular ways to do this...

* Compute the low-frequency levels of your height map first (the underlying tectonics and geology not impacted by the surface biome) and combine this with a procedural moisture map, then use this pair of (elevation, moisture) or a derived (temperature, fertility) to look up into a map of biome types, like in this example from jgallant:

Note that when you look up into this map with a floating point pair of coordinates, you can find out not only which type of biome cell you're in, but also which biome cells you're close to, and how close you are to the border.
* Break your map into Voronoi cells, and assign each cell a biome arbitrarily. Again you can peek at the biomes used in adjacent cells, and compute how far you are from those cells (this time in world space distance, rather than temperature-moisture-space)

Now, when you want to assign a height to a point, you generate a height using the rule for the biome it's in **AND** *each nearby biome*.

This will give you 3-4 heights for that point, differing opinions according to each neighbouring biome.

Form a weighted average of these heights, using a weight that increases as you move into the interior of the biome cell, and decreases toward zero as you move into a neighbouring cell. You can tune the range of this transition zone to keep the feathering subtle.

This gives a better result than generating each chunk with one biome and then lerping the results only at the edges in a few ways:

* Since the low frequencies are shared (the tectonics), you won't have adjacent biomes at vastly different baseline heights, so you don't get a sudden vertical wall at the boundaries.
* Instead of every point near the border of one chunk lerping toward the same value at the nearby edge, each one lerps to a different height chosen for *its own* position, as if the neighbouring biome continued past the edge. This gives you more variation across the transition zone and a more natural-looking blend that reduces visible artifacts.
* Your transition regions aren't strictly straight lines in a regular chunk grid, making them less likely to stand out. You can even add some noise into your weights to break up any visible structure further.

---
Tags: unity, terrain, mesh, perlin-noise, procedural
---


# Question
Title: Why are rotations in 2D game engines often counter-clockwise = positive systems?
I was looking over the API for a game engine a friend was developing in her spare time. She made the decision to make positive angles rotate in a clockwise direction. This immediately struck me as odd. My intuition was that angle should be measured counter-clockwise. I envision the typical unit circle when thinking about 2D rotations:

Her reasoning for picking this convention was that she was using a "positive y" = "down" coordinate system. From a mathematical sense, it makes sense to me that rotations would be clockwise if you're using this orientation. sin(90 degrees) would give me y = +1, which would be in a downward direction on my screen. So shouldn't I be thinking about angles in a clockwise way?

Why have we arrived at the convention that rotations should be counter-clockwise then, even in engines where positive y is down?

# Answer
> Why have we arrived at the convention that rotations should be counter-clockwise then, even in engines where positive y is down?

Have we? Let us try CSS:

```
const box = document.getElementById("box");

function step(timestamp)
{
    let deg = timestamp/10;
    box.style.transform = "rotate(" + deg + "deg)";
    window.requestAnimationFrame(step);
}

window.requestAnimationFrame(step);
```

```
#box
{
  width: 100px;
  height: 100px;
  border: 1px solid black;
}
```

```
<div id="box"></div>
```

Hmm... It look clockwise to me.

Let us try with canvas:

```
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");

canvas.width = 250;
canvas.height = 250;

const cx = canvas.width/2;
const cy = canvas.height/2;

const x = -50;
const y = -50;
const w = 100;
const h = 100;

function step(timestamp)
{
    let deg = timestamp/10;
    let rad = deg * Math.PI/180;

    // erase
    ctx.save();
    ctx.setTransform(1, 0, 0, 1, 0, 0);
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    ctx.restore();

    // draw
    ctx.save();
    ctx.translate(cx, cy); // pivot point
    ctx.rotate(rad); // rotate square in radians
    ctx.fillRect(x, y, w, h);
    ctx.restore();

    window.requestAnimationFrame(step);
}

window.requestAnimationFrame(step);
```

```
<canvas id="canvas"></canvas>
```

Still clockwise.

WebGL?

```
const canvas = document.getElementById("canvas");
const gl = canvas.getContext("webgl");

const vsSource = `
    attribute vec4 aVertexPosition;

    uniform mat4 uModelViewMatrix;
    uniform mat4 uProjectionMatrix;

    void main() {
      gl_Position = uProjectionMatrix * uModelViewMatrix * aVertexPosition;
    }
`;

const fsSource = `
    void main() {
      gl_FragColor = vec4(1.0, 1.0, 1.0, 1.0);
    }
`;

function loadShader(gl, type, source) {
  const shader = gl.createShader(type);
  gl.shaderSource(shader, source);
  gl.compileShader(shader);
  return shader;
}

const vertexShader = loadShader(gl, gl.VERTEX_SHADER, vsSource);
const fragmentShader = loadShader(gl, gl.FRAGMENT_SHADER, fsSource);

const shaderProgram = gl.createProgram();
gl.attachShader(shaderProgram, vertexShader);
gl.attachShader(shaderProgram, fragmentShader);
gl.linkProgram(shaderProgram);

const programInfo = {
  program: shaderProgram,
  attribLocations: {
    vertexPosition: gl.getAttribLocation(shaderProgram, 'aVertexPosition'),
  },
  uniformLocations: {
    projectionMatrix: gl.getUniformLocation(shaderProgram, 'uProjectionMatrix'),
    modelViewMatrix: gl.getUniformLocation(shaderProgram, 'uModelViewMatrix'),
  },
};

// ---

const positionBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);

const positions = [
 -1.0,  1.0,
  1.0,  1.0,
 -1.0, -1.0,
  1.0, -1.0,
];
const numComponents = 2;
const componentType = gl.FLOAT;
const vertexCount = 4;

gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(positions), gl.STATIC_DRAW);

// ---

gl.enable(gl.DEPTH_TEST);
gl.depthFunc(gl.LEQUAL);
gl.clearColor(0.0, 0.0, 0.0, 1.0);
gl.clearDepth(1.0);

// ---

function step(timestamp)
{
    let deg = timestamp/10;
    let rad = deg * Math.PI/180;

    //erase

    gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);

    //draw

    gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
    gl.vertexAttribPointer(
        programInfo.attribLocations.vertexPosition,
        numComponents,
        componentType,
        false,
        0,
        0);
    gl.enableVertexAttribArray(programInfo.attribLocations.vertexPosition);
    gl.useProgram(programInfo.program);
    gl.uniformMatrix4fv(
      programInfo.uniformLocations.projectionMatrix,
      false,
      [1.0, 0.0, 0.0, 0.0,
       0.0, 1.0, 0.0, 0.0,
       0.0, 0.0, 1.0, 0.0,
       0.0, 0.0, 0.0, 1.0]);
    gl.uniformMatrix4fv(
      programInfo.uniformLocations.modelViewMatrix,
      false,
      [Math.cos(rad), -Math.sin(rad), 0.0, 0.0,
       Math.sin(rad),  Math.cos(rad), 0.0, 0.0,
       0.0          , 0.0           , 1.0, 0.0,
       0.0          , 0.0           , 0.0, 1.0]);
    gl.drawArrays(gl.TRIANGLE_STRIP, 0, vertexCount);

    window.requestAnimationFrame(step);
}

window.requestAnimationFrame(step);
```

```
#canvas
{
  width: 250px;
  height: 250px;
}
```

```
<canvas id="canvas"></canvas>
```

Clockwise too. And I believe I have wrote that rotation matrix as per math convention. You can compare with Rotation Matrix at Wolfram MathWorld or Rotation Matrix at Wikipedia.

I would remind you that web technologies *are standard*.

So, if your friend is doing the rotation like this, then it is correct. And you are right, this makes sense with a vertical axis going down. We think of angles going counter-clockwise because we think of the vertical axis going up, which is mathematical convention. However, the vertical axis in screen goes down, because historical reasons.

I could have, of course, flipped the vertical axis in the projection matrix. Then the rotation would be counter-clockwise. In fact, it is more or less common that developers do some axis flipping to make it match their expectations.
> 6 votes

# Answer
Positive angles of rotation follow the “Right Hand Rule.” Place your right hand with palm at origin and fingers along positive x-axis. Curl your fingers toward the positive y-axis. The direction your fingers curl is a positive angle by convention.
> -1 votes

---
Tags: 2d, mathematics, architecture, rotation, trigonometry
---


# Question
Title: Clothing and physics asset collisions not working
I"m making a character in Blender where there's a character mesh and a simple skirt.

The skirt has a different material slot, which allows me to use the Unreal Clothing tool. I created the clothing data, applied it, painted it so the top part isn't moving at all and bottom has 100 "dynamics".

I also created a physics asset, however no matter what settings I try, the skirt will always poke through the thighs like they don't exist. All the colliders are capsules. I also get the feeling that the hip collider actually works. But only that one!

The skirt works perfectly with the wind, which makes it even weirder.

Does anyone know what can cause this?

# Answer
> 1 votes
I managed to find a solution. Turns out there were a couple of things to do:

1. First, proper scaling in Blender - I had a proper scale of the character. But after parenting it to a skeleton, the scale went crazy once again.
2. Second, I used the wrong type of collider.

Solutions:

1. Don't bother scaling the mesh initially. Scale the skeleton (apply scale), parent mesh to the skeleton, then apply scale to the mesh.
2. Only use tapered capsule and not the regular capsule in the Unreal Physics Asset.

One more tip, if the cloth still doesn't work - use "reimport base model".

---
Tags: physics, unreal-4, blender, cloth
---


# Question
Title: Why are the sprites in my AssetBundles ending up as Texture2Ds instead of Sprites?
I packed some sprites into an AssetBundle and uploaded it to my server. The sprites are set to type `Advanced`, so I can check the `read/write enabled` box.

When my game downloads it I want to initialize a sprite:

```
Sprite sprite = (Sprite)Instantiate(bundle.LoadAsset("1.png"));

```

This is not possible because apparently the asset is not a sprite (but it is...) - it seems like, for some reason, the asset is a `Texture2D` object rather than a `Sprite` one (why?). So I have to do something like this:

```
Texture2D tex = ((Texture2D)Instantiate(bundle.LoadAsset("1.png")));
Sprite sprite = Sprite.Create(tex,new Rect(0,0,tex.width,tex.height));

```

And that's fine. But I have the feeling this is not how it's supposed to be: why is my asset a `Texture2D` and not a `Sprite` already? Why do I need to create a brand new `Sprite`?

# Answer
Ancient question, but here's the answer: you need to pass an extra type parameter:

`var sprite = bundle.LoadAsset("1.png", typeof(Sprite));`

I believe that should make sure that any rect / pivot information defined in the sprite asset itself should be retained too.
> 2 votes

---
Tags: unity
---


# Question
Title: Knockback to zone on non-rectangular field
I have a playing field which is divided in 4 zones (as seen on the image below)

The player (blue) is on the second zone while there are 2 enemies (red) on the third zone. When the player throws an object and hits the enemy, the enemy is knockbacked in the next zone (4) but should stay within that zone.

If the enemy was being hit on the edge of the zone, I want him to still be in the zone 4 and not outside of it (if he got knocked back). I'm not sure if the direction of the hit matters in the calculation

Question: How can I find X?

Note that it can be on any shape of playing field (triangular, hexagonal, circular, ...)

# Answer
Looks like a job for the Physics engine. I would give the boundary of your play area a Rigidbody, and when the enemy is hit you apply a force to *their* Rigidbody equivalent to the vector (force) of the projectile (or similar). The physics engine will try to move that enemy away, in the same direction as the projectile, but if they hit the boundary wall they would 'slide' round it.
> 0 votes

---
Tags: unity, mathematics, vector
---


# Question
Title: Can I use music from TheFatRat for my game?
I saw on GitHub, it told me that I can use TheFatRat's music as commercial use. I'm in Vietnam, though, but I like developing games, and I think TheFatRat's music is very appropriate for my game. Am I allowed to use his music? Or is it illegal?

# Answer
It is illegal to use music made by someone else in your game, unless you have their permission. <sub>(unless the artist is dead for over 70 years, but that's unlikely to apply here)</sub>

Some artists give a blanket permission to everyone to use some of their works under specific conditions by adding a permissive license to them. Kevin MacLeod, for example, is an artist who is very well known for that. You might have heard his work in quite a lot of independent games. One example of a well known game which sourced most of its soundtrack from MacLeod is *Kerbal Space Program*.

I only did a superficial search about the artist mentioned in the question and found that they advertise at least some of their work on YouTube as "copyright FREE on YouTube. Please credit the artists and link to this upload". But that is only a public license for one specific use-case (YouTube). It does not mean that the artist gave permission to use their work as a game soundtrack.

When the artist does not give general permission to use their work in a game, then you have to obtain their permission by asking them nicely. When they don't agree to let you use their music (at least not for a price you are willing to pay), then you are not allowed to use it. If you do it anyway, they might take legal actions to prevent you from doing so and/or get you to pay them money.
> 4 votes

# Answer
I tried to see if the artist TheFatRat has released any music under a free license...

He has music on YouTube as "copyright free". However, we can only be confident on that meaning that you can download it without paying.

He has not said his music is public domain, nor any creative commons or any other license.

---

What he has said:

> I just want my music to be completely free I want everybody to be able to use it just to share it upload it download whatever also change they can remix it just because of what people to have fun with my music

-- Video Bet you heard this guys music while gaming – the story of TheFatRat

He saying he wants this, does not mean it is. *Quite the contrary, it suggest that it isn't the case, and he wants it be.*

> I have so much freedom right now, I can release music whenever I want and I can let you guys share it and use it on YouTube

-- Video Who is TheFatRat? Q&A and face reveal (around minute 13)

Yeah, well, that he saying that he can. If we count this, it is only for YouTube.

---

He has "open sourced" some content, for example: https://app.box.com/s/2tt7sdwsu0wbngoqroog and https://app.box.com/s/watfpnesl8wz2sdhx4p9djf4ejrf64ci however, none of these include a license file. He is sharing that content with everybody, does not mean you can use it for any commercial purpose.

I joined his discord and looked around. I didn't find any statement from him saying his music is free. Perhaps somebody asked about a license... A few people did... There was no reply. Some third parties has said that you can do anything with his music. However, as far as I can tell, those third parties do not speak for TheFatRat.

This is the only piece of content I found with what could be considered a license:

> @everyone here's an orchestral layout that I did for Warrior Songs. But it didn't fit into the final concept. Feel free to share, re-upload, remix and do whatever you want with it.
>
> DOTA\_2\_Layout.mp3

-- Published on 2018-10-04 on the channel "announcements" of the TheFatRat discord server.

---

However, I managed to find some legal text on "The Arcadium".

> This site is home to TheFatRat and his label “The Arcadium”. All music here is free to use on YouTube and will not be silenced or monetized by any third parties.
>
> All songs can be downloaded in several different versions depending on your needs. If you for example want to make a trailer or soundtrack a very long video we have prepared versions that should fit your needs better than the original radio edit of the track.
>
> All we ask in return is that you give credit to the artist on your YouTube clip by a pre written text provided to you after you pick a song that you want to use.

-- About in The Arcadium

> The Company, together with the artist professionally known as TheFatRat (“Artist”), have created the Site to enable private individuals to use certain musical recordings with the Artist (“Content”) for creation of user generated content in which the Content is used as a musical background (“UGC”). The Content subject to these Terms will be made available on the Site.
>
> The Content made available on the Site is available for download free of charge. You are urged to post a copyright text with the Artist, the name of the Content along with a Spotify link to the description of your YouTube video to support the Artist.
>
> The UGC may only be made available for non-commercial and promotional use on the YouTube service. All other uses of the Content or the UGC are strictly reserved by the Company and the Artist.
>
> Your right to use the content is non-exclusive and at all times revocable. You may not allow others to use the Content.
>
> The Content made available on the Site for use within UGC on the YouTube service may not be edited, remixed, mixed or otherwise adapted.
>
> (...)

-- Terms and Conditions in The Arcadium

**Note**: The Arcadium site is down at the time of writing. The links above is provided via archive.org.

As you can see, you can use his music for YouTube, as background music, and not remixed.

---

Bottom Line:

**You need to ask TheFatRat permission to use his music in a video game.** *And good luck with that.*
> 2 votes

---
Tags: music
---


title: Möbius effect in Unity

text:
# Question
Title: Möbius effect in Unity
This morning I've seen the following animation on Twitter. It is a kind of Möbius strip effect.

It's cool! Isn't it? So I've decided to build something similar using Unity, just for fun. I want to build the effect using just the cameras, as this way we can use it for any rotating scene. The first step has been to create a circle scene and make it rotate:

Note that the camera uses an ortographic projection so perspective does not deform it. This is important so we can merge different views later.

Then I've replaced the main camera by two different ones, located in opposite positions (horizontal and vertical) and rendering to textures. A simple Canvas with two panels (divided vertically) shows the partial result (one camera texture per panel):

I know this is cool, but not perfect yet, as the center of the rendered output shows clearly where a panel finishes and the other one starts. Look at the center of the rendered output above.

The original inspiration video shows no perspective in the center, and I think that is the trick, but I cannot achieve that with an orthographic camera (or I don't know how).

**Do you know any approach to distort the camera or something similar, so the cameras are perpendicular in the middle of the scene (and only in the middle)? Are you able to think a solution to dissimulate the joint of both camera views?**

As a first approach (dismissed for the moment) I've tried to add another camera, perpendicular to the scene so there is no perspective in that point. Then I render its output in the UI in another panel on top of the previous ones. And it is not too bad, but again the joint is too obvious and now I have two joints instead of one:

# Answer
After some effort, I've found a temporal approach: overlapping the panels and using a shader mask to combine both images in the middle.

Anyway I'm sure there must be a way to make the camera perpendicular in the middle and not on the sides. Hopefully somebody can give us some ideas about how to do it.
> 5 votes

---
Tags: unity, camera, movement, perspective
---


title: Server-side "Fog of War"

text:
# Question
Title: Server-side "Fog of War"
I am working on my custom server for my online game and I was wondering if there is any way to accomplish this in a more performant way.

Basically I will be spawning and despawning objects (such as other players) to clients based on the distance between their positions. Basically, if you are within, say, 500 meters away from another character, the server will send you a "Spawn character" packet to spawn that character on your client. If you move more than 500 meters away from that client, the server will send you a despawn packet.

The only way I can think of doing this on the server is a nested for loop. For every character on the server, check every other character position. That's expensive and obviously as the character count grows, so does the time it takes for process the loops.

Can anyone think of any different approach to this that will be better performant? Most survival games don't do this, and you just have all characters spawned on every client, but this allows for ESP hacks (Extra Sensory Perception which basically is a hack that shows you exactly where everyone is, even if the client isn't rendering them because they are far away) and I don't want that as a possibility.

If you need any other information let me know, thanks.

# Answer
You can tame this in the same way we tame other \\$n^2\\$ interactions in games, like collision detection: use a spatial partition to break it into smaller, more tractable pieces.

Let's say I divide my world into 500 m x 500 m chunks. As players move around the world, the server keeps track of which chunk each player is in. When a player enters a new chunk, they're removed from the list of players in their previous chunk, and added to the list of players in their new chunk.

Now when we want to notify nearby players, we only need to search the lists of players in the same or adjacent chunks - everyone else on the server is too far away to even consider.

So it's still an \\$n^2\\$ problem, but with a much smaller \\$n\\$, proportional to the density of players in a single chunk, rather than the total population of the server.

The more finely you break up the world, the better you can thin down the list of players (or other significant entities) within any given region/radius, but also the more work you need to do to keep everything sorted into their respective buckets. So you'll have some tuning decisions to make based on your typical densities, query ranges, and movement patterns to find the trade-offs that work best for your game's use cases.
> 1 votes

---
Tags: c#, performance, server
---


# Question
Title: How to have coins burst out in random directions after destroying an object in unity?
I want coins to burst out of an obstacle in random directions after I destroy it, kind of like the rings in sonic. I have everything else done: the physics, bouncing, instantiating to coins. I just don't know how to get them to fly out in random directions.

Here's my script:

```
while (counter < 5) {
    counter++;
    Instantiate(token, transform.position, transform.rotation);
}
Destroy (gameObject, 0.4f);

```

# Answer
Unity has a great Random property called `UnityEngine.Random.insideUnitCircle` that will pick a random vector inside the unit circle. It great to assign both position around the spawn point and a random direction they can go in.

An example of a basic trajectory code:

```
void Start()
{
    trajectory = UnityEngine.Random.insideUnitCircle * velocity;
}

void FixedUpdate()
{
    transform.position += trajecotry * Time.deltaTime - 2 * gravity * Time.deltaTime**2
}

```

This probably isn't the best example, but the key is how to assign the random trajectory.
> 5 votes

# Answer
I did this to instantiate multiple coins in random directions :

```
Vector3 trajectory = UnityEngine.Random.insideUnitCircle * 200f;
        for (int i = 0; i <= rdm_amount; i++)
        {
            GameObject coin = Instantiate(coin_GO, transform.position, Quaternion.identity);
            coin.GetComponent<Rigidbody>().AddForce(Random.Range(-600f,600f) + trajectory.x, 600f + trajectory.y, Random.Range(-600f, 600f) + trajectory.z);
        }

```
> 0 votes

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


# Question
Title: Can I use Google Ads on a game published on non-Google platforms?
I just made a game with unity personal. And I want to publish/release it on sites like Getjar, Aptoide, Slideme etc. instead of Play Store.

So I want to know if I can still get revenue from Google ads or if I have to publish it on the play store to get revenue from ads.

# Answer
> 2 votes
Yes, you can earn revenue from Google Mobile Ads on other stores, or even if you just distribute the app yourself by uploading the apk somewhere online.

This is obviously also true in the case of iOS apps.

---
Tags: unity, google-play, monetization, advertisements
---


# Question
Title: Calculating projectile path when fired at an angle, forward
I have a problem to code the path of a projectile from a gun as it moves forward and upward. This needs to be done in p5.js.

Although the Angry Birds method has been tried by me, I am looking for a more physics derived function involving the sine and cosine of angle of the gun.

# Answer
Presumably you started by reading our extensive library of existing Q&A on , and constructing a vector from an angle.

Putting those together, you should have no difficulty deriving:

```
launchVelocity.x = launchSpeed * Math.cos(launchAngle);
launchVelocity.y = launchSpeed * Math.sin(launchAngle);

positionAtTimeT.x = launchPosition.x + t * launchVelocity.x
positionAtTimeT.y = launchPosition.y + t * launchVelocity.y + t * t * gravity/2.0;

```

Where `gravity` is your acceleration due to gravity, eg. \\$-9.81 \frac m {s^2}\\$
> 1 votes

---
Tags: path, projectile
---


# Question
Title: how to make ascii ui like in dwarf fortress
Only one text field, and inside it - different sections, menus, and popups, all in ascii. How to make that?

I mean something like this:

```
╔═════════════════╦══════╗
║                 ║      ║
║                 ║      ║
║                 ║      ║
║                 ║      ║
╚═════════════════╩══════╝

```

I see only the possibility to draw each line, calculating line length and somewhat manually. But maybe there is some kind of a simple way i am not aware of?

# Answer
> 2 votes
I can't think of a pre-made library to do this all directly, and with such a low "resolution", you probably want precise control over how wide each column is etc.

You can basically treat your display like a very low resolution image, (e.g. a `char screen[80][50]`) then write that out each update, or you can just print the chars directly using something like ncurses or platform specific APIs to specify position. Or fake the whole thing displaying it like a tile-array with images that happen to look like ASCII/Extended-ASCII using one of many 2D graphics libraries/APIs.

Starting with some basic things like a single single column, row, etc. You can then build up from there, like you could for other graphics. The borders for a two column layout like that might be:

```
// make BUFFER_WIDTH, BUFFER_HEIGHT variable if want to support any sized console/terminal
int panel_height = BUFFER_HEIGHT - 2 /*pad*/ - 2 /*borders*/;
int border_bottom_y = panel_height + 2;
int right_width = 30;
int left_x = 2;
int left_width = BUFFER_WIDTH - right_width - 2 /*pad*/ - 3 /*outer and inner line*/;
int border_middle_x = left_x + left_width;
int right_x = border_middle_x + 1;
int border_right_x = right_x + right_width;

draw_cell(1, 1, 201); // (x, y, char)
draw_row(left_x, 1, left_width, 205); // (x, y, width, char)
draw_cell(border_middle_x, 1, 203);
draw_row(right_x, 1, right_width, 205);
draw_cell(border_right_x, 1, 187);

draw_col(1, 2, panel_height, 186); // (x, y, height, char)
draw_col(border_middle_x, 2, panel_height, 186);
draw_col(border_right_x, 2, panel_height, 186);

draw_cell(1, border_bottom_y, 200);
draw_row(left_x, border_bottom_y, left_width, 205);
draw_cell(border_middle_x, border_bottom_y, 202);
draw_row(right_x, border_bottom_y, right_width, 205);
draw_cell(border_right_x, border_bottom_y, 188);

```

Which you can then re-factor into a reusable `left_right_panels` function/class, along with functions/properties to get the coordinates and size of the left and right panel for further drawing within them.

As you build up these functions, there will be less individual values you are having to work out manually, potentially just the key ones (like "I want the right panel to be 30 columns, and the left to be everything else").

You can also of course extend the functions to accept colour codes etc. And probably use named constants for the ASCII "graphics" characters.

# Answer
> 2 votes
There's lots of information in the article about *Output libraries* on RogueBasin wiki.

You're likely looking for *curses* or one of the derivatives, like ncurses, PDCurses, etc. Such a style of library lets you render UIs in a text-based console, supporting for example sub-windows, changing text at specific coordinates, and depending on the specific library sometimes even higher-level UI elements like text boxes, checkboxes, or scrollable areas. This is much more efficient than doing it yourself and redrawing the entire screen every frame.

Many such libraries exist with Java bindings.

# Answer
> 1 votes
One approach would be to make your UI regularily and then just run it through an ASCII-Art Library (I found this one with 5 secs googling for example: https://www.baeldung.com/ascii-art-in-java )

However that might not be possible performance-wise on an actual game.

Then you'd probably have to do it yourself. Using a monospace font in all UI elements would be valuable (ones where EVERY letter and symbol has the same pixel width) and from there on simply calculate the necessary values in width/height.

\[Since you mentioned Java as well:\] JavaFX also allows CSS styling afaik so id't be easy to style the chars in a cool manner. It also works pretty smoothly with bigger text boxes

# Answer
> 1 votes
you could use the ASCII Table library. it provides a basic acces to draw tables in java.

Here's an example of an grid layout

> ```
> +--------------------------------------------------------------------------------------------+
> |                                                                                |
> |                                      Top Frame Margin                                      |
> |                                                                                |
> |        ╔════════════════════════╦════════════════════════╦════════════════════════╗        |
> |        ║ row 1 col 1 / cell 1,1 ║ row 1 col 2 / cell 1,2 ║ row 1 col 3 / cell 1,3 ║        |
> |  F  M  ╠════════════════════════╩════════════════════════╬════════════════════════╣  F  M  |
> |  r  a  ║            row 2 col 1&2 / cell 1,1/2           ║ row 2 col 3 / cell 1,3 ║  r  a  |
> |  a  r  ╠════════════════════════╦════════════════════════╩════════════════════════╣  a  r  |
> |  m  g  ║ row 3 col 1 / cell 1,1 ║            row 2 col 2&3 / cell 1,2/3           ║  m  g  |
> |  e  i  ╠════════════════════════╩═════════════════════════════════════════════════╣  e  i  |
> |     n  ║                      row 4 col 1&2&3 / cell 1,1/2/3                      ║     n  |
> |        ╚══════════════════════════════════════════════════════════════════════════╝        |
> |                                                                                |
> |                                     Bottom Frame Margin                                    |
> |                                                                                |
> +--------------------------------------------------------------------------------------------+
>
> ```

this would be an example of an single cell:

> ```
> ╔══════════════════════════════╗
> ║          Top Padding         ║
> ║------------------------------║
> ║ Left    |   cell   |   Right ║
> ║ Padding |   text   | Padding ║
> ║------------------------------║
> ║        Bottom Padding        ║
> ╚══════════════════════════════╝
>
>
> ```

---
Tags: java, gui, ui-design
---


# Question
Title: Unity3D - JsonUtility returns empty string
i have the problem that when I convert an instance of highscores through JsonUtility.ToJson the value of my value of it is always {"highscoreEntryList":\[{},{},{},{},{},{},{},{},{},{},{}\]}...

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

public class HighScoreTable : MonoBehaviour
{
    private Transform entryContainer;
    private Transform entryTemplate;
    private List<HighScoreEntry> highScoreEntries;
    private List<Transform> highScoreEntryTransformList;
    private void Awake()
    {
        entryContainer = transform.Find("HighScoreEntryContainer");
        entryTemplate = entryContainer.Find("HighScoreEntryTemp");

        entryTemplate.gameObject.SetActive(false);

        highScoreEntries = new List<HighScoreEntry>()
        {
            new HighScoreEntry { Score = 9999, Name = "T1"} ,
            new HighScoreEntry { Score = 9282, Name = "T2"} ,
            new HighScoreEntry { Score = 9942, Name = "T3"} ,
            new HighScoreEntry { Score = 2419, Name = "t4"} ,
            new HighScoreEntry { Score = 2390, Name = "t5"} ,
            new HighScoreEntry { Score = 9282, Name = "t7"} ,
            new HighScoreEntry { Score = 2918, Name = "t6"} ,
            new HighScoreEntry { Score = 4921, Name = "t8"} ,
            new HighScoreEntry { Score = 1318, Name = "t9"} ,
            new HighScoreEntry { Score = 8818, Name = "t10"} ,
            new HighScoreEntry { Score = 9231, Name = "t11"} ,
        };

        highScoreEntryTransformList = new List<Transform>();
        highScoreEntries.Sort((first, second) => second.Score.CompareTo(first.Score));

        foreach (var highScoreEntry in highScoreEntries)
            CreateHighScoreEntry(highScoreEntry, entryContainer, highScoreEntryTransformList);

        Highscores highscores = new Highscores {highscoreEntryList = highScoreEntries };
        string json = JsonUtility.ToJson(highscores);
        PlayerPrefs.SetString("highscoreTable", json);
        PlayerPrefs.Save();
        Debug.Log(PlayerPrefs.GetString("highscoreTable"));
    }

    private void CreateHighScoreEntry(HighScoreEntry highScoreEntry, Transform container, List<Transform> transformlist)
    {
        float tempHeight = 40f;
        Transform entryTransform = Instantiate(entryTemplate, container);
        RectTransform entryRectTransform = entryTransform.GetComponent<RectTransform>();
        entryRectTransform.anchoredPosition = new Vector2(0, -tempHeight * transformlist.Count);
        entryTransform.gameObject.SetActive(true);

        entryTransform.Find("posText").GetComponent<Text>().text = "" + (transformlist.Count + 1);
        entryTransform.Find("scoreText").GetComponent<Text>().text = "" + highScoreEntry.Score;
        entryTransform.Find("nameText").GetComponent<Text>().text = "" + highScoreEntry.Name;

        transformlist.Add(entryTransform);

    }

    private class Highscores
    {
        public List<HighScoreEntry> highscoreEntryList;
    }

    [Serializable]
    private class HighScoreEntry
    {
        public int Score { get; set; }
        public string Name { get; set; }
    }
}

```

My List property is public and i also tried to write \[SerializeField\] over it.

# Answer
JSONUtility can serialize *fields*, but it can not serialize *properties*. As the documentation of `[SerializeField]` says:

> The serialization system can do the following:
>
> * CAN serialize public non-static fields (of serializable types)
> * CAN serialize nonpublic non-static fields marked with the SerializeField attribute.
> * CANNOT serialize static fields.
> * **CANNOT serialize properties.**

So how do we solve this problem? The most simple solution would be to get rid of the `{ get; set; }` parts in `class HighScoreEntry`.

```
[Serializable]
private class HighScoreEntry
{
    public int Score;
    public string Name;
}

```

Whether those fields are raw public fields or properties with trivial getters and setters shouldn't really change anything in this *particular* case. But if you really want to use properties in a serializable object for some reason, then you have to use getters and setters which encapsulate private fields marked with the `[SerializeField]` attribute:

```
[Serializable]
private class HighScoreEntry
{
    [SerializeField] private int score;
    public int Score {  get { return this.score; }
                        set { this.score = value; } }

    [SerializeField] private string name;
    public int Name {  get { return this.name; }
                       set { this.name = value; } }
}

```
> 2 votes

---
Tags: unity, c#, serialization, json
---


# Question
Title: Why is my TouchScript gesture event not firing?
I am using TouchScript (v9.0) with Unity (2018.2.14f1) and am struggling with getting the `Flicked` gesture event to fire. I created an empty game object with a few UI elements in it (text and raw images) and added the `Flick Gesture` component to it (didn't change any of the settings on it), along with a custom script I wrote to register the `Flicked` event - this code is mostly from the wiki:

```
public class FlickGestureHandler : MonoBehaviour {
    FlickGesture gesture;

    // Use this for initialization
    void Start () {
        gesture = GetComponent<FlickGesture>();

        if (gesture != null)
        {
            gesture.Flicked += flickedHandler;
        }
        else
        {
            print("Gesture is null...");
        }
    }

    public void flickedHandler(object sender, EventArgs e)
    {
        print("Flick gesture recorded");
    }
}

```

I've also added an empty and added a `Touch Manager` component to it, although I don't know if that does anything by itself, or how to connect it to my draggable game object.

When I run the app, I wait for the gameobject's contents to appear (I am using Keyframe animation and the UI elements do not appear until a few seconds after load), then try to drag the UI elements in any direction and nothing is printed to the console. I am using a touch screen monitor and a touch pen for this. Why is the event not firing? FWIW, I tried creating a simpler example where I just attach the scripts (`Flick Gesture` and my custom script `Flick Gesture Handler`) to an image object and I got the same result.

# Answer
> 0 votes
I had a similar problem

After I created a scene object as parent of a camera it suddenly worked

---
Tags: unity, touch
---


title: String storage in game engine

text:
# Question
Title: String storage in game engine
I've been designing the memory management module for my game engine, including things like custom allocators and when it came to allocating memory for strings I kinda got stuck. What I mean by strings in this context is things like UI text, Items description, dialogues etc, so basically strings themselves are immutable, but they can stop being useful and just get freed.

With the string (and basically any object type with such allocation patterns) allocator I'd like to mostly get rid of the malloc/free invocations and so I'm wondering what kind of allocator is suitable for this jobs. Another thing that worries me is fragmentation, because string have variable length by nature

How do game engines handle strings like this in the first place?

EDIT

Firstly I'd like to address some of the questions that came up.

The strings themselves would be loaded from an asset file.

By 'stop being useful' I mean a situation where player interacts with some kind of item that has a description associated with it and we'd like to show the description on screen.

To do that, the text would get loaded, displayed and freed some time after the player closes the description window (the delay is here because there the player could reopen the window again in a brief second for whatever reason).

Such allocations would occur very often, because we don't need all the resources at all times, just a specific subset of them and my idea was to create an allocator for that purpose. It would `malloc` a large enough block of memory and store the strings (or any resource of such allocation pattern) in it, marking the free spots as the string get freed.

That's when 'what about fragmentation' came up in my mind, because some strings might actually be stored a bit longer than others, leading to fragmentation inside the allocator.

But after reading some of the comments I figured that what I actually need is separate allocators for long-living strings/resources, such as UI elements, and for short-lived elements, like the dialogues and descriptions What I also realized thanks to @Moo-Juice is that I could introduce something like resource-groups, that would hold the group of resources needed at that time, for example when entering some location, we'd load all the things that are contained within that location. Thanks for the insight!

One thing remains a puzzle for me tho. I've looked around Doom 3 source code, where I found a class called `idStrPool` which uses `new`/`delete` to allocate/deallocate strings. Can anybody comment on that? After reading some books and articles I was convinced, that such a thing is pure evil in a game engine, yet here it its. A use case I see for this is like handling input from the player, i.e. when the player types something and we want to capture it. Can anyone comment on that?

Edit 2

Ok, I see that guys from idSoftware have overrided the operators in Heap.h

# Answer
To address your initial concern, unless you are targeting older generation consoles or embedded devices, you probably don't need to worry about fragmentation.

With that said, one way you can address the problem is to have a dedicated memory pool for strings which are then interned.

With string interning in C, you create a hash table where the keys are ids of the hashes of the strings. Whenever you want to use a string you get it from the string intern pool. If the hash of that string isn't in the pool yet, you add it. If it is, you can just return it. This makes it so that you don't pay the cost for duplicated strings.

If your use case contains lots of unique temporary strings, then interning might not be the best solution. And if you have concerns about hashing performance, look up compile time string hashing.
> 2 votes

# Answer
Pombal gives a very good answer, but I'd just like to add a note to it.

Like your textures, sounds, and other game-related data, strings are also a resource. Lots of game engines allow you to load and unload resources in groups... that is, you can have a global group (this stuff is alive for the duration of a play session), and then more specific groups for portions of a game (e.g. specific levels).

Strings are no different, and using the hash-table that Pombal mentions, is a fast way of looking up the string resource you want, and by using the resource allocation methods mentioned above, you are not allocating the strings for your whole game at the start, nor are you doing it on demand - rather you are doing it at the beginning of a level, or some other game-defined event.

I prefer the resource-group method, as it is done at a stage when the player is not actually actively participating (think... global being the game start, and at the beginning of a level or whatever resource group or partition you feel necessary). And believe me, you can load thousands of string resources in a heart beat using this method, and nobody will notice - and they're available.

Think ahead! :)
> 1 votes

---
Tags: c++, architecture, memory
---


title: How to stop a signal from being sent

text:
# Question
Title: How to stop a signal from being sent
Currently i have three buttons that can be toggled with only one being active at once. When one button is selected by the player it sends a signal to the other two buttons to toggle off. Before the recent Godot update this set up worked fine, but now when the player toggeles a button on, the button thats being turned off now sends its toggeled signal thus turning off the very button the player clicked.

So im looking for a way to block a signal in code to prevent this loop.

Code for reference:

Player button:

```
func _on_Ally1_Button_toggled(button_pressed,check):
    print("on ally1 toggeled P")
    self.set_pressed(false)

func _on_Ally2_Button_toggled(button_pressed,check):
    print("on ally2 toggeled P")
    self.set_pressed(false)

```

Ally1 Button:

```
 func _on_Player_Button_toggled(button_pressed,check):
    print("on player toggeled A1")
    self.set_pressed(false)

 func _on_Ally2_Button_toggled(button_pressed,check):
    print("on ally2 toggeled A1")
    self.set_pressed(false)

```

Ally2 Button:

```
 func _on_Player_Button_toggled(button_pressed,check):
    print("on player toggeled A2")
    self.set_pressed(false)

func _on_Ally1_Button_toggled(button_pressed,check):
    print("on ally1 toggeled A2")
    print(check)
    self.set_pressed(false)

```

The check varible being passed in is how i plan stop the loop i just need a way stop signal.

Thank you in advance for the help.

# Answer
> 4 votes
Forget about all these signals, and just use a ButtonGroup. When multiple buttons have the same `ButtonGroup` assigned to their group field, Godot will only allow one to be toggled on at once.

---
Tags: godot
---


title: Game Similarity Legal Consequences

text:
# Question
Title: Game Similarity Legal Consequences
I'm already half a year into planning a Turn Based Strategy (4X) game for mobile phones.

Recently I tried to play Civilization 6 and while playing, totally horrified, I realized that my idea and Civ 6 are very, very similar.

So what should I do? Do you recommend that I should change elements that are too similar, or create game I planned, not looking at similarities to Civ 6?

Could there be any legal consequences due to similarity of those two games?

# Answer
> 2 votes
Making a clone-ish game is a big risk.

Please go read Clone Wars: The Five Most Important Cases Every Game Developer Should Know.

*I'm not a lawyer. This is not legal advice. I’m talking about Game Design.*

---

Everything is a Remix. Or if you prefer, there is nothing new under the sun. It is OK to stand on the shoulders of giants.

It is extremely hard to make a game without mechanic comparable to those in other games. In fact, it is arguably good to use similar mechanics to other games. That makes it easier for players to pick up your game. *You might be interested in the concepts of "skill transference", "affordance" and "conveyance".*

Thus, having mechanics similar to those of another game is not a bad thing per-se.

What you want to avoid is the game (as a whole) being perceived as a clone. And, no, just changing the artwork or a change of setting won't do. You want to have a unique mix of mechanics. If you can add some innovative mechanics, much better.

*Under the assumption that you do not get into any legal trouble. If your game grows in the shadow of a much popular game, its popularity will likely be hindered. Have you heard of "Blue Ocean Strategy"?*

---

Since you are designing a 4X game, *and you have already spoiled yourself with Civ 6...* My suggestion is to study more games on the genre. In particular older titles and how they evolved. Older titles tend to be simpler and closer to the core of the genre.

For Civilization in particular. It suffered accretion up to Civ 4. Civ 5 was a reinvention. Going back to simple terms and breaking some traditions, making it easier to pick up for new players, and getting some old players angry. Civ 6 is a refinement of what Civ 5 did, incorporating what they learned with it. There are decades of design lessons packed in those games, if you can unpack them.

Think about the motivation of the designers to include each mechanic on the game. What would happen if you remove them? What alternative could you use to those mechanics? Is there any mechanics that would work better?

Also, can you incorporate mechanics from other genres?

*In liue of buying all those games. Let's play videos and wiki articles are a cheap substitute. Oh, by the way, see what critics say, perhaps you can provide an alternative that avoids some of the drawbacks of the games you study.*

---

Although I said that adding innovative mechanics is better than simply having a unique mix... There is also an argument for a minimalist approach.

Ideally, each mechanic is fun on its own... or rather I should say, has intrinsic rewards. *In practice that is not the case.*

Sometimes it is possible to remove mechanics in such a way that you find a better core than the original. To do this, you need to forget the lore, the setting, the world building and even the fantasy and the theme of the game. *Do not let the fact that such icon is supposed to mean food prevent you from seeing the underlying mechanic.*

Focus on the mechanics, abstract them. If possible, remove those mechanics that lack intrinsic rewards. Express the mechanics in simpler, minimalist, terms. You can think of a setting, a world, and a lore that fits your mechanics later.

*Mario is a plumber because he goes into pipes. There are pipes because they are a way to connect different parts of the game. It is not the other way around. Mario is not a game about what it is like to be a plumber.*

---

You may also be interested in game aesthetics. If you do not know what mechanics have intrinsic rewards, you need to think about what appeals to the players. In particular, have a look at the Mechanics-Dynamics-Aesthetics framework.

---
Tags: game-design, legal, 4x
---


# Question
Title: How to use a boolean to activate every item with the same tag?
I've been really stuck on this one and need some help.

I've got some accessories for my player, and my goal is to have a collider, with the script attached. When the player walks into the script, the inactive model components on the player, will be set to active.

This is the script I'm using:

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

public class ItemEquip : MonoBehaviour
{
    public GameObject[] Apparel;
    public bool SetActive;

    void Start()
    {
        Apparel = GameObject.FindGameObjectsWithTag("Apparel");
    }

    void OnTriggerEnter(Collider ApparelCollect)
    {
        if (ApparelCollect.CompareTag("Player"))
        {
            GameObject[] clothes = GameObject.FindGameObjectsWithTag("Apparel");
            foreach (GameObject apparel in clothes)
            {
                apparel.SetActive(true);
            }
        }
    }
}

```

I'm really stuck on this. It's something basic but despite trying several tutorials, asking some people I know and experimenting, nothing is getting this script to work.

What I've tried: -Deactivating the individual components -Attaching a script to each component, along with the trigger -Activating the individual components (from inspector) -Activating the script (from inspector) -Double checking that each component I want affected has the Apparel tag -Cry in a corner

I've been going around in a loop for ages trying to get this thing to work, but still nothing.

I'm self taught on game development, working on my first game. I've read the Unity manual (that absolutely did not help) as well as hit up YouTube and multiple forums, all with no luck.

# Answer
> 1 votes
`FindGameObjectsWithTag` only finds already active GameObjects. From the documentation:

> Returns an array of **active GameObjects** tagged `tag`. Returns empty array if no GameObject was found.

So it won’t work to turn on a collection of inactive objects. You’re going to have to figure out a different way to find all the apparel. You might try adding an empty `Apparel` script to each item of apparel and getting all instances of it, eg.

```
void OnTriggerEnter(Collider ApparelCollect)
{
    if (ApparelCollect.CompareTag("Player"))
    {
        Apparel[] clothes = ApparelCollect.gameObject.GetComponentsInChildren<Apparel>(true);
        foreach (Apparel apparel in clothes)
        {
            apparel.gameObject.SetActive(true);
        }
    }
}

```

Note that this assumes that the apparel are all children of the collider that hit the trigger. If that’s not the case, you’ll need a more complex solution.

---
Tags: c#, collider, boolean
---


title: Simple message box in gdscript / godot

text:
# Question
Title: Simple message box in gdscript / godot
I want a single line of code which shows a popup dialog with the words "Hello World!" and an "Ok" button. (I want something simple for now, I know how to make something more complicated but that would be stupid at this point in development).

# Answer
> 10 votes
You can use the OS / platform's `alert` system:

```
OS.alert('This is your message', 'Message Title')

```

You can use `WindowDialog` or subclass on any node like this:

```
func alert(text: String, title: String='Message') -> void:
    var dialog = AcceptDialog.new()
    dialog.dialog_text = text
    dialog.window_title = title
    dialog.connect('modal_closed', dialog, 'queue_free')
    add_child(dialog)
    dialog.popup_centered()

```

You can do the above, but globally:

```
func alert(text: String, title: String='Message') -> void:
    # ... code from above, but instead of `add_child(dialog)` do
    var scene_tree = Engine.get_main_loop()
    scene_tree.current_scene.add_child(dialog)
    dialog.popup_centered()

```

---
Tags: input, godot, gdscript
---