title: Getting Position of a Player in a grid

text:
# Question
Title: Getting Position of a Player in a grid
So I am making a pacman-like game. the game has tiles/grid. I keep the node data in a struct:

```
struct Node

{
    std::pair <int, int> node; // position of the node <x,y>
    float f = 0,
          h = 0,
          g = 0;
    std::pair <int, int> previous;
    bool iswall = false;
    sf::Vector2f rectCenter = sf::Vector2f(0, 0);
    sf::Vector2f position;

};

```

i use the struct to calculate a path, check if the cell is an obstacle (or not) etc.

now in the main I use the arrays and a for loop to draw the grid:

```
for (int i = 0; i<col; i++)
        for (int j = 0; j < row; j++)
        {
            /*default color is black*/
            box[i][j].setFillColor(sf::Color::Black);
            box[i][j].setOutlineColor(sf::Color::Yellow);
            box[i][j].setOutlineThickness(-1);
            box[i][j].setSize(sf::Vector2f(w, h));
            box[i][j].setPosition(sf::Vector2f(i*w, j*h));
            sf::FloatRect fbox = box[i][j].getGlobalBounds();
        }

```

\[

I also use the strcut to create specific nodes (current position, start node, end node)

and i draw it in the man like this:

```
        //displays the start node as green
        if (i == crntNodex && j == crntNodey)
        {
            box[i][j].setFillColor(sf::Color::Green);
                }

```

now the problem that I'm facing is making a function that can get the current node that the player (blue square on the green cell) is. My attempt for this was checking if the cell contained the player

```
std::pair<int, int> AIEnemy::getNodePosition(sf::RectangleShape * grid, int i, int j)
{

    if (box.contains(rect.getPosition().x, rect.getPosition().y))
    {
         return std::pair<int, int>(i,j);
    }
}

```

but It is not efficient (and also doesn't update). is there a way I can get game objects coord on a grid?

# Answer
If your player is at (x, y) where both coordinates are in pixels, and you know that the width pf a tile is `w` pixels, then you can get the position by simply doing

```
posX = floor(x / w)
posY = floor(y / w)

```
> 2 votes

---
Tags: c++, sfml, grid, visual-studio
---


# Question
Title: Downloading image to apply as a Texture fails
In my app I need to download some images and apply them as Textures.

If I use following code to get image from my local pc hard disk, it works.

But it does not work if I use a url like (http://www.something.com/image.jpg). In that case, the texture appears as the image below.

More specifically:

1. The image I'm downloading is not the one I've attached.
2. The image/url exists and is accessible
3. The image is a JPG
4. Loading the same image stored on my local pc works ( file:// instead of http:// )

```
Texture2D tex;
tex = new Texture2D(4, 4, TextureFormat.DXT1, false);
if (url.Substring(0, 4).ToLower() != "http")
    url = "file://" + url;
using (WWW www = new WWW(url))
{
    www.LoadImageIntoTexture(tex);

    while (!www.isDone) { }
    if (www.error==null)
    {

        MyObject.GetComponent<Renderer>().material.mainTexture = (Texture)tex;
    }

}

```

# Answer
> 3 votes
It looks like you're trying to load the downloaded data into your texture before you've waited for it to download:

```
using (WWW www = new WWW(url))
{
    // We've only just sent the request, and maybe haven't received a reply yet.
    // So here the downloaded data might still be empty or incomplete.
    www.LoadImageIntoTexture(tex);

    // Now we're finally giving the download a chance to finish and guarding against errors.
    while (!www.isDone) { }

    if (www.error==null)
    {
        MyObject.GetComponent<Renderer>().material.mainTexture = (Texture)tex;
    }
}

```

On your local file system, this may be so fast and error-free that the data is already reliably available then. On the web, where everything takes longer, you might have longer to wait before the data is ready.

Have you tried moving the `www.LoadImageIntoTexture(tex);` line down, so it's the first thing inside the `if (www.error == null) {...` block? This will delay the texture load until you're actually sure the download has finished without errors.

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


title: Integrate Stripe with Unity

text:
# Question
Title: Integrate Stripe with Unity
I'm trying to install the Stripe API Library through NuGet Manager in Visual Studio but it installs it inside packages folder of the Project (I.E. before Project's Assets folder) doing this I cannot use the library:

```
Using UnityEngine;
Using Stripe; //Doesn't recognise this

```

Then I:

* Moved those installed files from packages to Assets folder
* Uninstalled Stripe from NuGet (as I could now access them in my script by using Stripe)

Now these are the main errors that I'm getting:

```
PrecompiledAssemblyException: Multiple precompiled assemblies with the same name Newtonsoft.Json.dll included for the current platform. Only one assembly with the same name is allowed per platform. Assembly path: {0}
Assembly 'Assets/Temp/lib/netstandard2.0/Stripe.net.dll' will not be loaded due to errors:
Unable to resolve reference 'System.Collections.Immutable'. Is the assembly missing or incompatible with the current platform?

Assembly 'Assets/Temp/lib/netstandard1.2/Stripe.net.dll' will not be loaded due to errors:
Unable to resolve reference 'System.Collections.Immutable'. Is the assembly missing or incompatible with the current platform?

```

# Answer
It looks like stripe is / is using a precompiled c# dll. Whenever you have a precompiled dll in unity it should be located in a folder called Plugins. When you click on the dll file you can set the platform that it's built for. You need to compile the dll for each platform you plan to release on, then set the unity settings on the dll to tell unity that. The error you have above shows that there are already multiple dlls, but you haven't set them to their correct platform settings. I'm not familiar with stripe's nuget package, but I do recognize that unity error, and I've worked with stripe in other languages.
> 2 votes

---
Tags: unity, visual-studio
---


# Question
Title: How to handle a Google Play game's privacy policy
I am trying to release a mobile game (*insert obligatory sellout statement for Chunk of Space*) on Google Play, and I'm worried about their privacy policy system. Basically, if you mark your game as "directed primarily towards children," you need to include a privacy policy (mostly to adhere to COPPA regulations). Now, my game isn't primarily for children, but because it's made to appeal to all ages, it's likely that I might have children playing it (or, I might have nobody play it. Hooray for insecurity). The question is, do I need to make the app say that it is "Designed for Families," or can I leave that option unchecked? Will the game not be marketed/available to children if I do not do so? And if I do need to set that option, how might I go about creating the privacy policy? I know there are several privacy policy generators online, so if you've used one or more in the past, could you recommend it to me? And how would I need to modify the policy to allow children to use it?

As for information the app uses, here's a short list:

* Anything needed for Unity analytics, IAP, and ads
* Anything needed for Google play IAP and ads

That's all that I know it uses, although there might be some additional information that each uses, along with any hidden Google Play and Unity stuff.

# Answer
Before you read this, I'm not a lawyer.

As far as I understand, the "Designed for Children" refers to apps that primarily target children, like educational apps, or cartoon-games. They do not affect apps that target a wider audience that includes them.

Having a wider audience that includes children is handled when you get a rating for your app, in which case, based on the amount of violence, and other adult-specific subjects that your app includes, it will be given a rating, something like 12+ or 3+. (They are different for each country)

From my experience with Google, marking your app as "Designed for Children" is not a requirement. That means if you do make an app made for children, you don't have to mark it as such. The benefit you get when you do though is that Google might use it in "Child-friendly" areas of the Play-Store, so it will get better visibility to its target audience.
> 4 votes

---
Tags: legal, mobile, marketing, google-play, advertisements
---


# Question
Title: JOGL KeyListener not functioning properly
I have been having a problem with the JOGL KeyListener where if I hold down a key, it would register the key as pressed for around 1 second, then it would start quickly switching back and forth between pressed and unpressed. However, if I hold more than one key at once, sometimes the key listener "forgets" about one of the keys and keeps it held down (like it should) while releasing the other one (when it shouldn't).

Here is the relevant code in the class:

```
import com.jogamp.newt.event.KeyEvent;
import com.jogamp.newt.event.KeyListener;

import java.util.HashSet;
import java.util.Set;

public class KeyInput implements KeyListener {
    private static Set<Short> key=new HashSet<Short>();
    public void keyPressed(KeyEvent keyEvent) {
        key.add(keyEvent.getKeyCode());
        System.out.println("added " +keyEvent.getKeyChar());
    }

    public void keyReleased(KeyEvent keyEvent) {
        key.remove(keyEvent.getKeyCode());
        System.out.println("removed " +keyEvent.getKeyChar());
    }

    public static boolean getKey(short k){
        return key.contains(k);
    }
}

```

I tried using other methods of storing the keys to no avail. How should I fix it so that it properly registers and remembers held down keys? I tried a different program with Swing and it worked fine. It has the exact same code as shown here.

# Answer
> 1 votes
Just figured out my problem. It turns out that OpenGL had auto-repeat enabled (which is the default on Windows), which was giving me the rapid on-off values. If anyone else has this problem, the solution is to add this code snippet before removing a key from an index:

```
if(keyEvent.isAutoRepeat()){
     return;
}

```

This would go in the `keyReleased` method.

---
Tags: opengl, java, jogl
---


# Question
Title: Rotate on one axis, but visibly keep the other axes stable and editable
It's been a long two weeks. Quaternions are freaking complicated. I've managed to make a few baby steps towards finishing my project, but I've hit a brick wall and could use a few of your beautiful minds to help me past it.

I'm making an asset for Unity that will automatically rotate/shift objects to make them appear 2.5D. What I'm having trouble with is the rotation part. I go through a trigonometric process to get a calculation of how much, between 0 and 180 degrees (typically), that the object should rotate on its x-axis.

The rotation of this object should be locked between 0 and 180 degrees. Think of it this way: my trigonometric calculation is telling me whether the object should be flipped right-side-up or upside-down

So, we've got the angle it should rotate. Just plop it in a `Quaternion.Euler(MyNewXValue, prevEulerY, prevEulerZ)` and we should be good, right? WRONG.

There are a number of things wrong with this.

1. The previous eulers can come back a bit wonky since they can correspond to multiple values in the -360 to +360 degree range, so we have to "normalize" them a bit.
2. Due to the rotation order, it ends up "swirling" in 3D space and altering the other two rotations instead of maintaining a stable x-axis rotation change.

With that said, here is my code:

```
// C#

if (current_euler.z < 180f)
{
   rot = Quaternion.Euler(rotation_angle.x, current_euler.y, current_euler.z);
} else
{
   rot = Quaternion.Euler(rotation_angle.x, current_euler.y-180, current_euler.z-180);
}
```

Ignore the (if \< 180). That's just so I can get this test running and working. I'll find a proper way to normalize it later.

Anyway, this snippet works, but has one problem: It twirls in 3D space and doesn't remain locked on its x-axis. I've tried numerous other solutions, but they either spin out of control or... they all spun out of control.

My question: Is there a way to *set* the rotation by rotating on one axis, while allowing the other rotations to change at the user's command without it "swirling" in 3D space?

**EDIT: SOLUTION**

For my use case I was able to use transform.localScale and modify it's Y-scale as a solution to my issue. It has the exact effect as I was looking for, and is definitely more stable. I accepted @Lunin's answer, however, as it seems to be another possible solution, and is written on this forum :).

To clarify, my wish was to rotate a 2D object on its x-axis, which would cause it to rotate vertically. At the same time, I wanted to allow the other axes to be editable at any given time. I can mimic a vertical rotation by changing the y-scale of the 2D object. +1 y-scale is normal, -1 y-scale is flipped upside down. Since I only needed that one axis to change, this workaround worked perfectly.

# Answer
> 1 votes
I'm not sure I entirely grok what you're going for, however if you're looking to set one axis explicitly a good choice is **Quaternion.LookRotation**

This will set the forward axis to pointing at whatever you want, while spinning the rest around that axis in such a way as to keep the up axis pointing as "Up" as possible. The nice thing is, "Up" is another parameter you can put in, so you can use this function to allow a 2D direction around said rotation. You may find the axes being changed are not what you want, but it's not too bad to either do it to a container object where the "forward" is actually the direction you want to change or to rotate the resulting Quaternion afterwards into the orientation you want.

Just remember that with this method, the "Forward" angle gets priority, and the "Up" gets as close as it can given the "Forward", so you can decide based on your logic which angle should most get its way based on the gameplay you're going for :)

# Answer
> 1 votes
For my use case I was able to use transform.localScale and modify it's Y-scale as a solution to my issue. I simply got a proportion of my trigonometric calculation's result and turned it into a value between -1 and +1. It has the exact effect as I was looking for, and is definitely more stable.

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


# Question
Title: Unity Networked gaming 2019... What happened to NetworkBehaviour, OnServerStart() etc
After a long break, I am now trying to learn some basics in networked gaming in Unity. I've installed the latest beta client (because I want to ultimately make a network multiplayer game but it will be many months of learning and building barebone prototypes to ensure I can get game objects spawning correctly and be controllable by the correct client etc etc

I have some experience in Unet, by extending the NetworkBehaviour class. I don't remember exactly but there were things such as \[Client RPC\] and \[Command\] and also OnServerStart() methods etc.

But I am aware Unet is being removed. And I tried to extend my class from NetworkBehaviour (I also tried NetworkBehavior lol) and it doesn't recognise it anymore.

So what replaces OnServerStart() method and \[ClientRpc\] instruction? Ideally I want to use a Dedicated Server solution (which I will run on my own computer in order to play small tests online of my game). The game im trying to make to start off with is extremely simple. The 'player' is just a capsule which can shoot small cubes and give damage to other players. Also the player object 'you' are controlling will appear blue, but all the other players will be grey.

Using Unet I was able to make the above small game idea work. But now I am unable to.

# Answer
As of right now, there is no production ready replacement for UNET. UNET is currently deprecated. UNET has four main components, HLAPI, LLAPI, relay server, and legacy matchmaking. The HLAPI will be last shipped with 2018.4 LTS and supported until early 2021. The LLAPI will be last shipped with the 2019.4 LTS and have support until Spring 2022.

Therefore, unless you’re using a beta, UNET is currently deprecated but in the engine as of writing this post (2018.3.8 is the current official release). If you’re having problems, make sure you import the correct namespaces.

The new networking system is currently in alpha. You can can read about it here and see the source here.

Here is the transition timeframe:

Currently, the official advice is:

> **What should I use if I am making a multiplayer game today or have already shipped a multiplayer game?**
>
> Already launched: If your game has shipped and uses our Relay service, it will continue to run as expected until at least Spring 2022. By that time, we will either extend the Relay service or provide a clear transition plan to new technologies.
>
> To be shipped in the next 0-6 months: If you’ve already completed most of the work on your multiplayer game using the LLAPI or HLAPI, it is okay to ship it using the 2018.4 (LTS) or prior versions of Unity. However, P2P architectures of all forms struggle with scalability, inconsistent connection quality, and hackable clients, so we recommend most games move to a dedicated server model if possible.
>
> To be shipped in 6+ months: You should immediately consider moving to dedicated servers to determine what it will take to create a server-authoritative version of your game. Stay tuned for more details soon about the upcoming Preview packages to build your game with the new networking, dedicated servers, and matchmaker.

From here.

Additionally, there are other networking alternatives such as Mirror which strives to mirror UNET while providing fixes and improvements.
> 2 votes

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


# Question
Title: How do I wait till an animation is finished?
I am currently working on a Warfare 1917 like game. Right now I am trying to get the combat system working. I have made animations for a running and shooting soldier. It takes exactly 0.5 seconds till the animation lets the soldier shoot.
I have taken out the animations, hud etc. because I put much effort in them and I don't want someone to steal them just now. :) It currently looks like this:

Obviously they are killing each other too fast. How can I let them wait till the animation is at the point where they can calculate if they die or not?
This is my code. First it checks if two "soldiers" are in each others vicinity and then I calculate who of those two will die. `german.stop(true); britain.stop(true);`In the class where I handle the spawning and the animations of my soldiers I have a simple `if else` statement. Whenever `stop = true` then the soldier will stay at his current position and does his shooting animation. That this soldier continues to run after killing the other soldier is also a problem, but that's something for a later time.

```
ArrayList<britain> britainToRemove = new ArrayList<britain>();

ArrayList<germans> germansToRemove = new ArrayList<germans>();

    for (int i = german_array.size() - 1; i >= 0; i--) {
        germans german = german_array.get(i);
        for (int j = britain_array.size() - 1; j >= 0; j--) {
            britain britain = britain_array.get(j);
            if (german.getBounds().overlaps(britain.getBounds())) {
                //handle collision
                german.stop(true);
                britain.stop(true);
                int german_hit = random.nextInt(100) + 0;
                int britain_hit = random.nextInt(100) + 0;
                message = "Red: " + german_hit + "Blue: " + britain_hit;
                if (german_hit > britain_hit) {

                    britainToRemove.add(britain);

                } else {

                    germansToRemove.add(german);

                }
            }
        }
    }
    britain_array.removeAll(britainToRemove);
    german_array.removeAll(germansToRemove);

```

# Answer
> 1 votes
Assuming you are using LibGDX `Animation` class, you can use `isAnimationFinished()` method to check if animation has finished or not.

When you start your animation, you need to store starting time and subtract current time from it. Obviously, this needs to run as a separate loop with objects waiting for their animation to finish. You could use `britainToRemove` and `germansToRemove` for that. Iterate through these lists and remove elements from `britain_array` and `german_array` only when their animation finishes (don't forget to remove them from the list you are iterating through).

Note: My suggestion would make the two `*toRemove` lists state objects.

EDIT: If you care about performance, you should use `PriorityQueue` instead of iterating through the whole list.

---
Tags: java, libgdx, game-mechanics
---


# Question
Title: How would I move something around inside of a sphere without it going outside of the sphere?
I want to be able to do this, but not go outside of the 4.4 meter limit, the radius is 4.4 meters, and it has zero gravity and no friction. I have a hard time explaining this, but imagine holding a hollow sphere with a little ball inside, when you shake it around the ball goes around the inside, I need something like that, but with zero gravity and no friction. I wasn't really sure how to do this, but I tried:

```
void Slide() {
if (slide) {
    for (uint32_t deviceIndex = 0; deviceIndex < vr::k_unMaxTrackedDeviceCount; deviceIndex++) {
        glm::vec3 position = devicePos[deviceIndex].xyz();
        if (sqrt(pow(position.x - 0.35, 2) + pow(position.y + 1.75, 2) + pow(position.z + 0.85, 2)) >= 4.4) {
            if (abs(position.x) > abs(position.y) && abs(position.x) > abs(position.z)) {
                if (position.x > 0) {
                    velocity.x = ((abs(velocity.y)) + (abs(velocity.z))) / 2;
                }
                else {
                    velocity.x = ((abs(velocity.y) * -1) + (abs(velocity.z) * -1)) / 2;
                }

            }
            if (abs(position.y) > abs(position.x) && abs(position.y) > abs(position.z)) {
                if (position.y > 0) {
                    velocity.y = ((abs(velocity.x)) + (abs(velocity.z))) / 2;
                }
                else {
                    velocity.y = ((abs(velocity.x) * -1) + (abs(velocity.z) * -1)) / 2;
                }

            }
            if (abs(position.z) > abs(position.x) && abs(position.z) > abs(position.y)) {
                if (position.z > 0) {
                    velocity.z = ((abs(velocity.x)) + (abs(velocity.y))) / 2;
                }
                else {
                    velocity.z = ((abs(velocity.x) * -1) + (abs(velocity.y) * -1)) / 2;
                }
            }
        }
    }
}

```

}

# Answer
> 1 votes
I think the easiest way would be to create a "reverse" sphere object. One that is hollow inside, and has colliders on the edges. If you can do that, it would surely be the fastest way.

If you want to do it programatically, it will be harder to answer since you gave no language / engine info. However, I will try:

You need to somehow check whether the inside ball touched the outside sphere. Since they are both spheres, you can do that with simple maths:

```
if((center_of_the_ball - center_of_the_sphere) + radius_of_the_ball > radius_of_the_sphere)

```

then we have a collision.

In that case you should change the direction of the ball. You could achieve that by rotating the current movement vector of the ball around the normal at the collision point. If I'm correct, you could use the vector between the center of ball and center of sphere as that.

---
Tags: collision-detection, physics, movement, visual-studio, sphere
---


# Question
Title: Unity Rendering (Bug): Objects rendered as multiple instances after repositioning
**Context:** I am currently making the menu for my game demo. It involoves "Raindrop"-Gameobjects (Sprites) being repositoned and recolored after a random amount of time. I do this by instantiating a predefined amount of Raindrops and manipulate them after said amount of time.

I am using *Unity 2018.1.6f* and, if possible, want to avoid switching to another version. If it is of relevance and requested, I can also post my sprite import settings.

**Problem:** Upon repositioning a sprite, it keeps being rendered at its old position AND the new position, making it appear as if a new instance was created

(this isn't the case as 1. the objects in the hierarchy view remain the same, and 2. the unwanted "multiple renderings" aren't shown in the scene view either, only in game view)

As seen below, there are 5 Raindrop objects in the hierarchy as well as in the scene view. In the game view however, there a lot more than 5 Raindrops are being rendered. The amount of rendered Raindrops increases each time a single one is repositioned.

**Further notice:** I had a fairly similar problem once where a bug in my code caused it tho delete all objects at once. The objects were deleted but kept on being rendered and even functioning as if nothing happened, save for the difference that all moving objects would be rendered like the cards in solitaire once the game is over (I do not know of a different way of describing it). None of the code above, except for the Exit() function of MenuEnvironment destroys any object. As you can see, the rainbow objects are only instantiated once, upon Setup(GameObject, GameObject) and being continuously manipulated in Unity's Update Loop.

# Answer
> 0 votes
As user DMGregory Pointed out, the camera settings are what cause this problem to occur. The camera's clear flags option was set to "don't clear":

Setting this option to "solid color" (or whatever else is appropiate in your case) fixed the problem:

---
Tags: unity, c#, sprites, bug
---


title: Line of Sight Check Theta* Algorithm

text:
# Question
Title: Line of Sight Check Theta* Algorithm
I am looking at implementing the Theta\* algorithm in a 2D NavMesh. I have A\* working, and I need to add a line of sight check to turn it into Theta\*, this seems relatively easy in a uniform grid but a bit trickier in a NavMesh. There is excellent documentation on the funnel algorithm here, however this seems better suited to A\* post smoothing.

Is there an method that would be better suited to Theta\* line of sight checks in a Navmesh, or would I just need to use a modified version of the funnel algorithm?

# Answer
> 0 votes
Conceptually you want to follow the line from `s1` to `s2`, determining which edges get crossed. The details depend on your representation of the NavMesh, but let's suppose it consists of triangles and allows the following operations:

```
# Returns the three vertices of the given triangle in CCW order
GetVertices(t)
# Returns the three triangles adjacent to this one.
# Ordered so that GetAdjacentTriangles(t)[i] shares entries i and i+1 of GetVertices(t).
# An entry may be None if the edge is on the boundary of the navmesh.
GetAdjacentTriangles(t)

```

Suppose we already know the triangles `t1`, `t2` containing `s1` and `s2`. Then the following ~~Python~~ pseudocode determines whether there is a line of sight:

```
def LineOfSight(s1,t1,s2,t2):
  d = s2 - s1 # Direction from s1 to s2
  n = (-d.y, d.x) # Normal to line s1-s2.
  ns = Dot(n, s1)
  while t1 != t2:
    dp = [Dot(n, v) for v in navmesh.GetVertices(t1)]
    for i in xrange(3):
      if dp[i] < 0 and dp[(i+1)%3] >= 0: break
    # We should cross the edge between vertices i and i+1.
    t1 = navmesh.GetAdjacentTriangles(t1)[i]
    if t1 is None: return False # We stepped off the NavMesh
  return True

```

This can probably be improved; it computes the same dot product multiple times, and probably mishandles the case where the line from `s1` to `s2` coincides with an edge in the NavMesh.

---
Tags: path-finding, navmesh, graph
---


# Question
Title: How can I draw a rectangle with a color gradient?
I'm trying to implement the below picture in my code but doesn't work. It only shows red color on all sides. I'm using line renderer and color gradient. Kindly check my code.

```
void Start()
{
lineGeneratorPrefab = new GameObject();

DrawLine();
}

private void DrawLine()
{
GameObject myLine = new GameObject();
myLine.transform.position = start;
myLine.AddComponent<LineRenderer>();
lr = myLine.GetComponent<LineRenderer>();
lr.material = new Material(Shader.Find("Sprites/Default"));
lr.positionCount = 4;
lr.SetPosition(0, new Vector3(-2, 0, 0));
lr.SetPosition(1, new Vector3(2, 0, 0));
lr.SetPosition(2, new Vector3(2, -2, 0));
lr.SetPosition(3, new Vector3(-2, -2, 0));
lr.loop = true;

Gradient gradient = new Gradient();
gradient.SetKeys(
    new GradientColorKey[]
    {
        new GradientColorKey(Color.red, 0.25f),
        new GradientColorKey(Color.blue, 0.25f),
        new GradientColorKey(Color.green, 0.25f),
        new GradientColorKey(Color.yellow, 0.25f)
    },
        new GradientAlphaKey[] { new GradientAlphaKey(1.0f, 0.0f) }
    );
lr.colorGradient = gradient;

}

```

# Answer
> 2 votes
The problem is that you have set the time parameter of all four of you `GradientColorKey` to .25f so it will only apply the first color.

Just change it to something like this

```
gradient.SetKeys(
            new GradientColorKey[]
            {
                new GradientColorKey(Color.red, 0.25f),
                new GradientColorKey(Color.blue, 0.5f),
                new GradientColorKey(Color.green, 0.75f),
                new GradientColorKey(Color.yellow, 1f)
            },
                new GradientAlphaKey[] { new GradientAlphaKey(1.0f, 0.0f) }
            );

```

Here the red color is going to apply at the first 25%, then blue from 26% to 50%, and so on.

And you will get result similar to this

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


title: Make half of the sprite transparent

text:
# Question
Title: Make half of the sprite transparent
Guys if I have two sprites placed on the same spot. How can I show the half of each Sprite instead of the one on top? The sprites are basic circles

All sprites have basic colors, no textures.

# Answer
> 1 votes
If each circle is a separate GameObject and SpriteRenderer then the solution is to use a sprite mask. If you only need to work when they are exactly overlapped, then just check if their positions are sufficiently close. If so, clip them together, and enable a sprite mask on each. The sprite mask should take a white square as it's mask sprite. Position the white square so it IS covering the half you want to HIDE, and NOT covering the half you want to SHOW. I would recommend putting these objects on their own layer, or moving them to a layer that the sprite mask affects, to avoid affecting other objects. You can always move them back to default when done.

If you're looking to blend smoothly in any positions that overlap, you probably need to write a shader, that has a custom blend function. However that's a bit involved for me to get into on this answer, so I would recommend learning some shading skills in unity, which is a process in it's own right.

---
Tags: unity
---


# Question
Title: Why do my NPC's fall through the world when I select them as triggers?
I'm making a game in Unity where when the player comes into contact with an NPC it will switch scenes. I have the code for it and made sure all NPC's have rigidbody as well as using gravity and convex. They do not fall through the world but as soon as I click the trigger box on the mesh collider they start falling straight through the world. The switching scenes code works fine - I tested it and it does switch the scene.

# Answer
When you set the `isTrigger` property of a `Collider`, it no longer registers collisions with incoming rigidbodies/colliders. As a result, your NPC falls through the floor.

If you want the scene transition to occur immediately upon contact with the NPC, you could simply uncheck `isTrigger` and put your scene transition code inside of `OnCollisionEnter()` instead of `OnTriggerEnter()`.
> 1 votes

---
Tags: unity, collision-detection, collider, meshcollider
---


# Question
Title: What are some gameplay cases where knowing the Z as a result of the raycasting is useful in a 2D setting?
The context is an 3D engine with a 2.5D level format. Like a roller coaster tycoon level, with some other level features added, and layers removed. For example the tile functions have the following interface.

```
markTile([3, 5]);

```

This statement places a mark on the tile located at 3x5. This tile can be on top of a mountain or a cave, but different tiles on the same height can't exist, so the Z axis isn't needed. Internally everything is in 3D, but it isn't exposed to the interfaces since there can't be more than one tile at the same X, Y position.

Because the tile functions are 2D, units also store their positions in 2D.

```
markTile(unit.position); // place a mark where the unit is

```

There are also cases where knowing the Z of an unit is useful, but it is almost never about the tile or the placement position. For example it is useful to create a sprite or an exclamation mark on top of an unit, but that is done by using the Z from the tile and the height of the unit. That interface also uses an unit as the parameter, not a position, because multiple units can be on the same position unlike a tile.

```
placeExclamationMarkOnUnit(unitId);

```

Now, I am wondering, is there a need for the raycaster to even return the Z data in this setting? I can't think of a gameplay case. I can think of cases where the unit height is important, but none that would need to know the Z from the ray. I can also think of cases where I could want to place an effect on an exact position on the unit, but that can be done by just X and Y(floats, not ints) as well.

Thanks.

# Answer
One example is overlapping objects, where you want to sort them by z value and act on them one at a time. Consider a system where pressing x over a trigger causes the player to perform some kin of interaction. If many of these are overlapping, and there's no priority set, you likely want the top most one. But what if some are disabled in terms of interaction, but not in terms of GameObject.SetActive(). Now you want the list of overlapping triggers (which unity doesn't guarentee is sorted by z value) then you want to sort them via z value (from front to back) and get the first one that is capable of interaction, or passes some set of conditions.
> 2 votes

---
Tags: game-design, architecture, raycasting, level-design
---


# Question
Title: Unity Proximity Warning System Trigger issues
I'm trying to set up a proximity warning system but I'm having some trouble.

To simplify things as much as possible:

I have two game objects in a scene (Object1 and Object2). Object1 has a large child object (twice as large as Object1 or Object2) which has no mesh renderer, but has a box collider (with the Is Trigger box ticked). Object 2 has a rigidbody component.

When Object1 gets close enough that it's child's Box Collider overlaps with Object2's rigidbody, a script on Object1 should Debug.Log the name of the object it's close to once a frame until Object1 moves away.

My code is as follows:

```
public Collider objectCollidedWith;

void OnTriggerStay(Collider other)
{
objectCollidedWith = other.transform.GetComponent<Collider>();
}

void Update()
{
Debug.Log(objectCollidedWith);
}

```

Unfortunately, something about my setup isn't working. The console just shows "null" once a frame and the objects getting close doesn't change this.

Can you tell me what I'm doing wrong?

Many thanks for your time.

# Answer
> 1 votes
If the script is ON object1, and the trigger is on the CHILD, then it will not bubble up to the script, unless you put a rigidbody on object1. A collider without a rigidbody, only broadcasts the collision messages to the gameObject the collider is on. A collider with a rigidbody anywhere in its parents, will broadcast the message to the gameobject that the rigidbody is on.

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


# Question
Title: Is there a reliable and fast way of getting a list of all installed games on a Windows PC?
Note: This was the best fitting stack I could find for this. Apparently this site doesn't specify in the scope whether this is allowed. I originally asked in Meta, and they told me to create the question so the community could decide using a concrete question.

Like other people with large gaming libraries, I've often been faced with uncertainty about what game to play. There are websites that can check your Steam library and suggest you a game based on things like Metascore, user ratings, genre preferences,... but there are 3 major issues with these:

1. They require an internet connection;
2. They check all your games, which also means games you've yet to download or which you got through a bundle deal with no intention of ever playing;
3. They only check Steam games, not games from other clients or even just classic disc-based games.

During my spare time, I had been working on a small C# program trying to fix this. It worked using a very brute-force way: you entered a folder name, it would get ALL files from that folder, then filter out everything that wasn't a .exe file and the stuff that didn't look like it was a game executable. It kinda worked, but it had 3 main issues:

1. SLOOOOOOW! it took 15 minutes to get all the files, if it didn't crash due to memory issues.
2. it included things that weren't games, like uninstallers, C redists and utilities;
3. I wrote it as an UWP program, which meant it wasn't portable to Windows 7 and 8 and was lacking proper libraries for things like mocking.

I'm taking another stab at it soon, but this time, I don't want to do it brute-force. I'm hoping to leverage the power of the platform and use readily available methods to find what I need.

My question is:

* Does Windows have something that can give me a list of installed games?
* If Windows can't do it, do the major digital distribution clients (meaning Steam, Origin and UPlay) have a way to provide a list of installed games? I don't mind if it means parsing files and then looking things up.

# Answer
> 4 votes
There's no API from Windows to specifically get installed games. However you *can* programmatically grab the currently installed programs:

```
string registry_key = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall";
using(Microsoft.Win32.RegistryKey key = Registry.LocalMachine.OpenSubKey(registry_key))
{
    foreach(string subkey_name in key.GetSubKeyNames())
    {
        using(RegistryKey subkey = key.OpenSubKey(subkey_name))
        {
            Console.WriteLine(subkey.GetValue("DisplayName"));
        }
    }
}

```

Source

You will also want to do this for the key:

`HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall`

Then, from there, you will need to grab a list from any potential game store front.

For Steam, you want to check for a `SteamPath` key in: `HKEY_CURRENT_USER\Software\Valve\Steam`

This will give you the path to the Steam install directory. From here, you are looking for `Config\config.vdf`. This file can contain several keys in the format `BaseInstallFolder_#`, which are the individual Steam Library paths. These paths will be where all of Steam's games are stored, although it won't help with 3rd-party games added into Steam manually. Please consult this helpful wiki article for parsing the .vdf file.

# Answer
> 1 votes
Check the registry paths `HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Uninstall` and `HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Uninstall`. They have a sub-key for every piece of software which was installed through a common installation wizard. It doesn't separate games from other software, but when you are building a game recommendation engine then identifying the games should be within your area of expertise.

This also includes most (but not all) steam games. However, it won't list any games which are not installed through a conventional installer. This is uncommon, but not unheard of.

By the way, you might notice that while browsing to these paths you will stumble upon a list of almost all programs which were ever installed on the system, including those which were uninstalled long ago. That might or might not be interesting information for your application.

# Answer
> 1 votes
> Does Windows have something that can give me a list of installed games?

Nope. The closest you can get are various ways to get all *executables* on the machine... these include techniques like searching for `*.exe` in the whole filesystem (your 15 minute timeframe, by the way, suggests to me you did something very inefficient) or trawling the registry as suggested by others.

There was a Games shell folder in Windows 7, but it seems to have vanished in modern Windows, and would not pick up all games accurately anyhow.

> If Windows can't do it, do the major digital distribution clients (meaning Steam, Origin and UPlay) have a way to provide a list of installed games? I don't mind if it means parsing files and then looking things up.

Steam has an API you could use for this. Origin does not, as far as I can tell (and at least as of 2013 didn't). Neither does UPlay.

# Answer
> 1 votes
Probably a completely dead topic but one I referred to when I was trying to accomplish the same.

I ended up searching registry as mentioned above, and it wasn't too bad, until I came across battle.net launcher... no consistent identifying factor, so I hardcoded those games.

I've put below how I found them all

(Note, I'm not a professional developer, it's a learning project, but if you want to give it a test feel free) https://github.com/pekempy/Breeze/blob/master/Models/ExeSearch.cs

---
Tags: steam, distribution
---


# Question
Title: How to set ortho projection / model view matrix without a camera?
I'm trying to create the correct projection and model view matrix for rendering without a camera.

`_orthoCamera` is a camera I set up in the scene view. Using the `_orthoCamera` projection matrix and `modelView` matrix works but I don't know exactly how to recreate these. My attempt is the commented code.

```
    //not correct
    //var projection = Matrix4x4.Ortho(-512, 512, -512, 512, 0.3f, 1000);
    //var modelView = Matrix4x4.LookAt(new Vector3(512, 512, -5), new Vector3(512, 512, 0), Vector3.up); //inverse?

    //correct result
    var projection = _orthoCamera.projectionMatrix;
    var modelView = _orthoCamera.worldToCameraMatrix;

    GL.LoadProjectionMatrix(projection);
    GL.modelview = (modelView);

```

This is how I set the camera up in the scene.

# Answer
> 1 votes
Ended up going with this. Based on this documentation.

```
var orthoSize = 512f;
var projection = Matrix4x4.Ortho(-orthoSize, orthoSize, -orthoSize, orthoSize, 0.3f, 1000);
var offset = new Vector3(512, 512, -5);
var modelView = Matrix4x4.TRS(new Vector3(-offset.x, -offset.y, offset.z), Quaternion.identity, new Vector3(1,1,-1));

```

---
Tags: unity, camera, matrix, projection-matrix
---


# Question
Title: How do I prevent inappropriate ads from appearing in my game?
My game implements Unity ads, and is designed with a universal audience in mind. As such, I would prefer not to have 18+ ads (or even 13+ ads depending on the circumstances) appearing in it, especially since it would appeal to younger audiences as well. My question is then, how do I prevent age-inappropriate ads from appearing? Is there a way to simply set the age limit or content restrictions on Unity ads? The only setting along those lines that I can find is the COPPA toggle, and that would cause other issues (not to mention that it wouldn't do anything to the ads). I've looked in the dashboard for a while, and I've tried to research it beforehand, but the fact that they've shifted to a centralized services page, redirected all the old links (breaking them in the process), reorganized the settings in the dashboard, and 404d their FAQ post on the topic doesn't help either. Blocking ads based on a rating would work too, as I would have to get one because I am publishing to Google Play.

Edit: The second link only 404s some of the time. I just happened to get it every time before asking this question. Bad luck, I guess.

# Answer
Unity ads can't contain adult material:

https://unity3d.com/legal/advertising-content-policy

> Advertising containing, linking or relating to content, goods or services in any of the following categories are prohibited by Unity Ads and may not be disseminated in any form via the Unity Ads Platform. \[...\]
>
> ## Adult
>
> Content that is sexually suggestive or that depicts, contains or provides access to pornography, nudity or other adult or risqué material, including content promoting adult-themed products.
>
> \[...\]
>
> ## Excessive violence
>
> Content that depicts or contains excessive violence or mutilation or that glorifies human suffering, death, self-harm or violence against animals.
>
> ## Gambling
>
> Content promoting any form of gambling or lottery to users where it is illegal or where any related required government license is not in place.
>
> \[...\]
>
> ## Tobacco/Vaping
>
> Content that promotes any form of tobacco or nicotine-related products, including vaping and electronic cigarettes.

These categories are what are usually seen as 13+, but for a full list, visit the site
> 28 votes

---
Tags: unity, advertisements, content-rating, unity-ads
---


title: Select Unity Prefab from enum choice

text:
# Question
Title: Select Unity Prefab from enum choice
After a couple tries, I still haven't found any solution to this problem of mine.

Currently, I have a script inheriting from MonoBehavior which creates a map with Perlin Noise. Let's call it `mapGenerator`. It instantiates a `HexTile` object from another script, which does not inherit from MonoBehaviour, that contains a refere to my terrain prefab and an enum value which says its type (so `water`, `grass`, `wood`, etc.). There is an array declared at the beginning of the script that I manually change as I'm adding terrains.

Everything works fine except when tweaking the map generation, If I want to change some values for perlin intervals, I might have to add another value to my `HexTile[]` and then drag my terrain prefab and set the enum value.

What I want is to know if there is a way to make the script select a prefab depending on the value the enum was set to.

Here is the code (simplified):

```
public class ProceduralTerrainGenerator : MonoBehaviour
{
public bool regenerateMap = true;

public Hextile[] hexTiles;

void Update()
{
    CreateMap();
}

private void CreateMap()
{
    // Some code for Perlin Noise generation inside perlinMap[,]
    for (int i = 0; i < mapLength; i++)
    {
        for (int j = 0; j < mapHeight; j++)
        {
            // Setting up position from i and j index
            foreach (HexTile hexTile in hexTiles)
            {
                if (ValueInRange(perlinMap[i,j], hexTile.LowLimit, hexTile.HighLimit)
                {
                    Instantiate<HexTile>(hexTile.tile, position, Quaternion.Euler(0f, 0f, 0f), this.transform);
                }
            }
        }
    }
}
}

```

and my other script

```
[System.Serializable]
public class HexTile
{
    public GameObject tile;
    public HexMetrics.HexType hexType;
    public float perlinNoiseLowLimit;
    public float perlinNoiseHighLimit;
}

```

**=========== EDIT 1 ===========**

I tried simplifing my problem, because I'm more interested in the concept, but here are more details.

I have a class named HexSettings, which contains the hex prefab (`HexTile`) named `tile`, its HexType, and the perlin noise bundaries.

```
[System.Serializable]
public class HexSettings
{
    public HexTile tile;
    public HexMetrics.HexType hexType;
    public float perlinNoiseLowLimit;
    public float perlinNoiseHighLimit;
}

```

Here is the HexType enum contained inside HexMetrics

```
public class HexMetrics
{
    // Hex metrics data for placement in grid data

    public enum HexType
    {
        GRASS,
        FOREST,
        WATER,
        SNOW,
        DESERT,
        LAKE
    }
}

```

What I would like is to have some soprt of dictionnary that contains the correct prefab according to the selected HexType.

As you can see in the image below, I can set my HexType to my terrain types, but I also have to set the HexTile object manually, **where it could be set automatically according to the HexType value set.** That is what I'm looking for.

I tried adding it in a dictionnary (something like `Dictionnary<Hextype, HexTile>`), looking for prefabs in my folder prefab with `Resources.LoadAll<HexTile>("prefab");`, no success, prefabs couldn't be loaded in HexSettings.

# Answer
> 3 votes
Try a ScriptableObject containing everything you need.

```
using UnityEngine;
using System;

[CreateAssetMenu]
public class HexTileCollection : ScriptableObject {
    [Serializable]
    public class HexPrefab {
        public GameObject prefab;
        public HexMetrics.HexType hexType;
    }
    private Dictionary<HexMetrics.HexType, GameObject> dict;
    public HexPrefab[] AllPrefabs;
    public GameObject this[HexMetrics.HexType type] {
        get {
            Init();
            return dict[type];
        }
    }

    private void Init() {
        if (dict != null)
            return;
        dict = new Dictionary<HexMetrics.HexType, GameObject>();
        foreach (var tile in AllPrefabs) {
            dict[tile.hexType] = tile.prefab;
        }
    }
}

```

Create an instance of this class in the project view by right clicking and choosing create Hex Tile Collection. Select this object, then set up your associations between hex types and prefabs once. It will look similar to your existing generator's hexTiles, except without Perlin noise ranges.

Your generator will change to use this newly created object:

```
class ProceduralTerrainGenerator : MonoBehaviour {
    [System.Serializable]
    public class HexTile
    {
        public HexMetrics.HexType hexType;
        public float perlinNoiseLowLimit;
        public float perlinNoiseHighLimit;
    }

    public HexTileCollection prefabs;
    public HexTile[] hexTiles;

    private void CreateMap()
    {
        // Some code for Perlin Noise generation inside perlinMap[,]
        for (int i = 0; i < mapLength; i++)
        {
            for (int j = 0; j < mapHeight; j++)
            {
                // Setting up position from i and j index
                foreach (HexTile hexTile in hexTiles)
                {
                    if (ValueInRange(perlinMap[i,j], hexTile.LowLimit, hexTile.HighLimit)
                    {
                        Instantiate(prefabs[hexTile.hexType], position, Quaternion.Identity, this.transform);
                        break;
                    }
                }
            }
        }
    }
}

```

Assign the HexTileCollection you created earlier into this component's `prefabs` field in the inspector. The hexTiles field now lists hex type and Perlin noise ranges but no prefab. That instead is fetched from the HexTileCollection. I'm not sure if this is what you're looking for, but it's what came to mind for me.

Note that at least one reason your attempt (`Resources.LoadAll<HexTile>("prefab");`) did not work is because HexTile would need to be a MonoBehavior or ScriptableObject to be able to be loaded. More generally, Resources.Load\* works only on Unity Object assets, not on simple serialized objects.

# Answer
> 1 votes
This question boils down to "how can I access prefabs dynamically without inspector references".

You can absolutely can `.Load()` prefabs dynamically. Just make sure they're in the `/Resources` folder. As long as the `string` values of each `enum` entry match the names of those prefabs (or can be converted to them) , you should have no problems doing what you intend.

Call `.Load` in `Awake()` or in your own custom `Initialise()` after `Instantiate`() / `Awake()`.

It's also possible to key them in the dictionary using the `Type` (from `typeof`) or type name (`string`) rather than an `enum` value, if you so prefer.

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


title: Smoothen line on linerender

text:
# Question
Title: Smoothen line on linerender
I've created a square using linerenderer but my problem now is that the line is not smooth. see below picture. I've tried enabling anti-aliasing and setting lr.numCapVertices to no avail.

```
 private void DrawLine()
{
GameObject myLine = new GameObject();
myLine.transform.position = start;
myLine.AddComponent<LineRenderer>();
lr = myLine.GetComponent<LineRenderer>();
lr.material = new Material(Shader.Find("Sprites/Default"));
lr.positionCount = 4;
lr.startWidth = .1f;
lr.endWidth = .1f;

lr.SetPosition(0, new Vector3(1, 0, 0));
lr.SetPosition(1, new Vector3(2, 0, 0));
lr.SetPosition(2, new Vector3(2, -1, 0));
lr.SetPosition(3, new Vector3(1, -1, 0));
lr.loop = true;

Gradient gradient = new Gradient();
gradient.SetKeys(
    new GradientColorKey[]
    {
        new GradientColorKey(Color.red, 0.25f),
        new GradientColorKey(Color.green, 0.50f),
        new GradientColorKey(Color.blue, 0.75f),
        new GradientColorKey(Color.yellow, 1f),
    },
        new GradientAlphaKey[] { new GradientAlphaKey(1f, 0.0f)

    }
    );
lr.colorGradient = gradient;

```

}

# Answer
> 1 votes
Well I don't exactly know the cause of the problem but when i try to manipulate the values of linerenderer's positions, I find that when gap between the point is less then the value of 1 (-1 or 1) then we will get this weird behaviour.

however, when I increase the gap between the points then the line became crispy smooth.

Here are the some test results.

Now I understand completely that it is not a solution to the problem, And I am glad to know the explaination myself from anyone who know the reason that why is this happening but for now just change the position of your linerenderers points with distance greater than 1 unit.

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


# Question
Title: Unity - Play animation based on horizontal drag position
What I want to do is somewhat complicated, but I'll try to explain it to the best of my ability. I am using Unity's EventSystems events to detect a drag. When the user drags the object horizontally, I want to play the animation relative to the position of the object.

For example: If the user drags object to position 0.5, I want the animation to only play to time 0.5, and if the user drags back to 0.2, I want the animation to play back to time 0.2

Currently, I do not have any code because I do not know where to begin.

# Answer
> 2 votes
Due to the luck of more detailed information I’ll have to do some assumptions. I’m not sure to understand exactly what you mean by “only play to time 0.X”, so I’ll assume you mean that you have one animation clip and you want to set the frame based on the position. Since you did not specify the direction I’ll assume you mean to do it in a 2d space along the X axis. I will consider as if you’ll be using C#.

An animation clip goes from 0 (start) to 1 (end) so you need to normalize the position of your `gameObject` in order to set the value of animation. Say your object can only be moved between `-5 < X < 7` than you would need to normalize this space like so:

```
float normalizedPosX = (yourObj.position.x + 5) / 12;

```

Now that you have your position returned as a value between 0 and 1 than you can set your clip to play at the given time. You can do this in different ways depending on the way you’re animating the object, I’ll assume you are using an Animator and will do that by using the following method:

```
animator.Play(“animationName”, 0, normalizedPosX);

```

It’s important to set the animation speed to 0 to avoid issues.

Refer: https://docs.unity3d.com/ScriptReference/Animator.Play.html

I hope this can be of help

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


title: Problems generating procedural mesh

text:
# Question
Title: Problems generating procedural mesh
I have this code below that I found on catlikecoding that generates a procedural grid that I want to apply noise to, however once I go over a certain value it does expand vertically. Can anyone see why it wouldn't?

For example, 100x100:

However, 500x500 is clearly wrong:

Code used:

```
using UnityEngine;

[RequireComponent(typeof(MeshFilter), typeof(MeshRenderer))]
public class Island : MonoBehaviour {

public int xSize, ySize;

    private Mesh mesh;
    private Vector3[] vertices;

    private void Awake () {
        Generate();
    }

    private void Generate () {
        GetComponent<MeshFilter>().mesh = mesh = new Mesh();
        mesh.name = "Procedural Island";

        vertices = new Vector3[(xSize + 1) * (ySize + 1)];
        Vector2[] uv = new Vector2[vertices.Length];

        for (int i = 0, y = 0; y <= ySize; y++) {
            for (int x = 0; x <= xSize; x++, i++) {
                vertices[i] = new Vector3(x, y);
                uv[i] = new Vector2((float)x / xSize, (float)y / ySize);
            }
        }

        mesh.vertices = vertices;
        mesh.uv = uv;

        int[] triangles = new int[xSize * ySize * 6];
        for (int ti = 0, vi = 0, y = 0; y < ySize; y++, vi++) {
            for (int x = 0; x < xSize; x++, ti += 6, vi++) {
                triangles[ti] = vi;
                triangles[ti + 3] = triangles[ti + 2] = vi + 1;
                triangles[ti + 4] = triangles[ti + 1] = vi + xSize + 1;
                triangles[ti + 5] = vi + xSize + 2;
            }
        }

        mesh.triangles = triangles;
        mesh.RecalculateNormals();
    }
}

```

# Answer
Been there, done that. I followed that series and encountered the exact same problem. I wrote directly to the author on facebook and he was kind enough to answer me that the problem lies in https://docs.unity3d.com/ScriptReference/Mesh-indexFormat.html

In this case the default IndexFormat.UInt16 is used, so the max vertices number you can have is 65536 (= 256x256) - thats why a 500x500 verticies list gives you a badly generated mesh. This can be solved simply by changing the mesh's index format to UInt32 (then you have max 4294967296 vertices )

Another alternative solution is spliting the mesh into smaller pieces as Bálint has suggested.
> 2 votes

# Answer
Unity meshes can only contain 65536 indices (=triangles array). Since 100x100 has 10000 squares and each needs 6 indices, that's just barely below 65536.

To solve this you can split it into multiple pieces, which would also allow you to implement LODs and view distance.
> 0 votes

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


# Question
Title: Is there performance difference between OnCollisionEnter and OnTriggerEnter?
Is there performance difference between OnCollisionEnter and OnTriggerEnter? I have around 12 objects all calling OnCollisionEnter when in fact OnTriggerEnter could work as well. So I wonder if the are is any difference PERFORMANCE WISE between the two

# Answer
Calling the methods themselves should not really matter. The physics system figures out there is a rigidbody collision / trigger collision and after that it figures out if the objects in question implement the respective handler methods. Yes, the OnCollision\* methods receive a `Collision` object which contains far more information about the collision event than you have in the OnTrigger\* methods, and that object must get constructed, no matter if you actually need all that information or not. But it's all information which is available anyway from detecting the collision, so we are talking about just a hand full of CPU cycles here.

But it's the detection itself which might matter. OnCollisionEnter only triggers for rigidbodies. Managing a rigidbody require far more physics calculations than managing a simple trigger collider. So you might want to reconsider if all the objects which got rigidbodies in your scene actually need them or if a simple trigger would also do the job (or if you at least can make the rigidbody kinematic to absolve the engine from calculating forces you don't actually want anyway). Generally speaking, you can use a trigger when you have an object which doesn't interact physically. For example, if you would create a modern clone of Super Mario Bros, then:

* Mario would have a rigidbody, because you want to be able to detect collisions between Mario and triggers and between Mario and other rigidbodies.
* The Goombas would have rigidbodies, because when Mario jumps on them, he bumps off a little. This can be easily implemented as a physics collision with a bouncy physics material. The data from the `Collision` object passed to `OnCollisionEnter` would also be useful for deciding whether Mario collided with the Goomba from above or from the side.
* The coins would have trigger colliders instead of rigidbodies, because Mario's movement isn't affected when they are collected.
* Regular blocks would have rigidbodies marked as kinematic, because although they do not move themselves, they do block the movement of other rigidbodies like Goombas or Mario.
> 6 votes

---
Tags: unity
---


# Question
Title: How to rotate a parent object while rotating a child object to a certain angle using coroutines
I have a semicircle like game object which I made by putting two arcs in an empty game object (SCircle) and rotating the 15° (for left arc) and -15° (for right arc) as seen below.

`SCircle` has an `Orientation` enum with two values`Left` (rotates SCircle to 45°) and `Right` (rotates `SCircle` to -45°) as seen in the image below.

I use the following coroutine to move `SCircle` between orientations.

```
IEnumerator RotateLeftOrRight(Vector3 byAngles, float inTime)
{
    Quaternion fromAngle = gameObject.transform.rotation ;
    Quaternion toAngle = Quaternion.Euler (transform.eulerAngles);

    if (circOrientation == Orientation.Left) {
        toAngle = Quaternion.Euler (gameObject.transform.eulerAngles - byAngles);
        circOrientation = Orientation.Right;

    }
    else if (circOrientation == Orientation.Right) {

        toAngle = Quaternion.Euler (gameObject.transform.eulerAngles + byAngles);
        circOrientation = Orientation.Left;
    }

    for(float t = 0f ; t <= 1f ; t += Time.deltaTime/inTime)
    {
        gameObject.transform.rotation = Quaternion.Lerp(fromAngle, toAngle, t) ;
        yield return null ;

        gameObject.transform.rotation = Quaternion.Lerp(fromAngle, toAngle, 1);
    }

}

```

I also used a very similar coroutine to move the individual arcs by 30° (in opposite directions) from say, Orientation `Left`, as seen below:

Since `SCircle` Coroutine is activated by a mouse click, I have the case where the individual arcs coroutine is run and before it is complete the parent `SCircle` coroutine is also run. In this case the arcs end up moving from `Left` to A, which is not the behavior I need. I would want the behavior of them ending up at B when moving from the `Left`. Likewise, from B, when the `SCircle` coroutine is run while the arcs coroutine is in progress the orientation will return to the `Left`.

Please note that the blue arrow represents the movement of the left Arc, the red represents the right Arc and the black represents movement of `SCircle` \- the parent object.

How can I achieve the behavior from Left to B and from B back to Left?

# Answer
> 0 votes
Your approach SHOULD work if you keep your local rotations straight. Essentially you have two rotations you want to act independent, and somehow they're coupling. The following scenario SHOULD work, and if not you may not have set it up correctly. Try attaching a script like this to each object you wish to rotate independently:

```
public class TransformOffsetRotatable : MonoBehaviour
{
    public float rotationSpeed;

    private Quaternion targetRotation;
    private Quaternion startingRotation;

    private void Awake()
    {
        startingRotation = transform.localRotation;
        targetRotation = startingRotation;
    }

    private void OnEnable()
    {
        StartCoroutine(RotateToTargetCoroutine());
    }

    public void SetRotationOffset(float deg)
    {
        targetRotation = startingRotation * Quaternion.Euler(0, 0, deg); // Assuming standard 2D axis
    }

    // This coroutine is simple and handles changing of rotation value
    // mid execution. If you don't want it running all the time, you can
    // end the coroutine after completing rotation, and restart when needed.
    private IEnumerator RotateToTargetCoroutine()
    {
        while (true)
        {
            yield return new WaitForFixedUpdate(); // Should probably rotate on fixed update
            // maxDeg = speed * time
            transform.localRotation = Quaternion.RotateTowards(transform.localRotation, targetRotation, Time.fixedDeltaTime * rotationSpeed);
        }
    }
}

```

This solution has the bonus that it can be attached to any game object. You can have your existing classes simply use a reference to this script. It's plug and play!

---
Tags: unity
---


# Question
Title: Are delayed abilities bad in turn-based strategy games?
In my PvP turn-based strategy, one of the balancing mechanisms for separating stronger from weaker abilities is their "delay", which is the number of turns it will take to actually execute that ability, from when it was commanded. For example, if you cast an ability with delay = 1, that unit won't use it until the start of your next turn. Most abilities have delay = 0, meaning it's used right when the command is given. It is clear when a unit is "casting" a delayed ability; they have an ongoing casting animation, there are tick marks above their head to count how many turns left for casting, and when you click on them, you see which tiles are targeted.

It's similar to "casting time" in Final Fantasy Tactics.

It serves several purposes in my game. For one thing, I need to balance stronger vs weaker abilities somehow, and there's already a lot of other resources to keep track of (action points, gold, etc). I don't want to clutter the game with more resources, such as mana on individual units. Units can have "cooldown" (number of turns where they can't be used) after being used, so moving units into enemy territory with cooldown can be dangerous, because they're vulnerable to the more powerful "delay" abilities. Finally, some of them can just be used as a deterrent, such as casting a large AoE delayed ability to say "don't come into this territory".

However, I read this article about Final Fantasy Tactics. It's an interview with a developer of a new indie game inspired by FFT, who was also a dev in FFT. Basically he says that casting time won't be in the new game, and was only in FFT because of technical limitations (the game needed time to load the graphics of certain spells). Also, I notice that it hasn't appeared in any of the later Tactics games by Square, nor in many other tactical games that are self-confessed "clones" of FFT (Fell Seal, for example). I basically haven't seen delayed abilities in any tactical turn-based game since FFT.

I also noticed, when playing the prototype of my game with some friends, that they were annoyed that some abilities didn't execute right away, even though it was advertised in their details that they have delay.

These things make me wonder if delay is an inherently bad mechanic, and that there's a good reason developers have been avoiding it since FFT. Perhaps it just feels bad or clunky on the side of the user, and reduces their overall gaming experience.

I have a few alternatives in mind. But my question is, **are delayed abilities in turn-based strategies generally a bad mechanic?**

# Answer
> 4 votes
My stance is there aren't inherently bad mechanics. Different mechanics appeal to different people. However, it sounds like that particular set of play testing *might* have found a disconnect between this particular mechanic & your particular game.

Here are some options:

**The play testers are not the intended audience.** The good news is this lets you keep your game as is. The bad news is it leads to new questions like:

* Who is the intend audience?
* How do you find them & connect with them?

These questions aren't necessarily easier to deal with & will need to be addressed if you want to have a viable product. (If you're not making your game as a product, the intended audience is probably yourself).

**The mechanic is not a good fit.** In this case to take it out, and see how it does. then check to see if it play tests well & if as a designer you are still evoking the experience you want. If it only sort of works, you may need to add in something else to add friction, evoke emotion, etc. Figuring this out can be one of the most difficult parts of design.

**The mechanic needs to be re-framed.** Sometimes the problem is context. If the mechanic is critical to your vision & you genuinely believe you're testing with the correct groups, look for ways to present the same thing in a different context. For instance, you mentioned cool downs. In a way, a cool down is a "first one free, delay on next". Not exactly the same, but it may be similar enough to keep your vision & simultaneously more appealing to your audience.

Along those lines, some other ideas might be:

* Offer both delayed & undelayed versions of an ability & tune to reflect risk / reward
* Instead of targeting units with a delayed ability, target terrain. This is akin to laying a trap & might 'feel' better to the players.

**The play testers are just reacting to push back.** It's not uncommon for players to want more than they have. Sometimes you want "just one more move" or to equip more than one trinket or to buy both of two mutually exclusive skills. Just because something is annoying doesn't mean the mechanic that caused it is un-fun. Again, it comes down to testing & designer expertise. Consider adding something that under certain circumstances, allows players to break the delay effect rule. If that addition is seen as a necessity, there's probably a problem. If it's just seen as great to have if you can get it, then things are probably okay.

Final comment on casting time not being included in the inspiration game: games often make choices to deal with constraints that might not be present to other developers at a later point in time &/or on a different platform. That doesn't mean the choices themselves were bad. Pixel graphics, permadeath, abstract logic games - these (and many more) were born out of necessity, but they still have value today.

# Answer
> 2 votes
There are a few problems which can arise from abilities which require a preparation time.

* They unnecessarily draw out combats which are already decided. Let's say the player has a completely overpowered level 999 wizard who has that ability which single-handedly defeats the whole enemy army with one use, but it takes three rounds to cast. The player uses it in the beginning of the first round.

The battle is decided now. There is nothing the enemy can do about it. Yes, the opponent *could* try to take out the wizard, but the AI isn't smart enough to realize that and the player is smart enough to make it impossible through clever positioning of their tanks. So there is no reason to continue that combat. Yet the player has to play through 3 pointless rounds of combat until the ability triggers and all enemies die.

Never waste the player's time!
* It reduces the numbers of meaningful choices the player can make. When most of their army can't do anything on their turns because they are all preparing attacks, the player feels like they don't have anything to do. The player might even feel helpless because they should do something important to counter an enemy move, but they can't because all their units who could do it are caught up in casting.
* Attack with long delay might be too easy to counter, even accidentally. The intended target might move out of range. The target might get killed by some other ability. The caster might die. The target might get affected by a defense-enhancement buff which negates the damage. A better target might show up. These are all very frustrating and anti-climatic for the player. They anticipated to see something really cool, and when the time finally arrives, it falls flat.

# Answer
> 0 votes
There are no good or bad styles.

It is the execution that matters. Often unique play styles are received badly (initially, due to prebuilt mindsets) but gain good traction later on.

But, if you think that player base (your friends) do not like delay based abilities, then you can definitely try other alternative and check which has better response.

Cheers..

---
Tags: game-mechanics, turn-based, turn-based-strategy
---


title: Changing the camera in Unity

text:
# Question
Title: Changing the camera in Unity
I am trying to make a game like Mario Party in Unity. I want the camera to automatically change between players after each turn.

I don't have a lot of experience in C#, and I totally would learn about it myself and figure out to solve it through my own acquired knowledge (which is what I'm going to spend my summer vacation doing), but I have to deliver a prototype before May.

I have followed some tutorials on how to make a game and tried to solve the problem on my own. I tried to solve it by copying some code and editing it with what I've learned, but it didn't work.

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

// Attached to Main Camera
public class CameraController : MonoBehaviour {
// Set manually in inspector
public GameObject[] players;
public float movementSpeed = 1.0f;
public float rotationSpeed = 1.0f;

StateManager theStateManager;
bool isAnimating = false;

private int currentPlayer;
private float startTime;
private float distanceToPlayer;
private Vector3 startPosition;
private Quaternion startOrientation;

//Use this for initialization
void start()
{
    theStateManager = GameObject.FindObjectOfType<StateManager> ();
    currentPlayer = 0;
    ResetCamera ();
}

//Update is called once per frame
void Update()
{
    float distanceCovered;
    float rotationCovered;
    float fractionTraveled;

    if (isAnimating == false)
    {
        return;
    }

    // switch to previous
    if (isAnimating == true)
    {
        if (currentPlayer == 0)
            currentPlayer = players.Length - 1;
        else
            currentPlayer++;
        ResetCamera ();
    }

    // Keep moving camera
    if (transform.position != players [currentPlayer].transform.position) {
        distanceCovered = (Time.time - startTime) * movementSpeed;
        fractionTraveled = distanceCovered / distanceToPlayer;
        rotationCovered = (Time.time - startTime) * rotationSpeed;
        // Lerp to players position
        transform.position = Vector3.Lerp (
            startPosition, players [currentPlayer].transform.position, rotationCovered);
        // Stop moving camera
    }
    else
    {
        // Match orientation
        if (transform.rotation != players[currentPlayer].transform.rotation)
            transform.rotation = players[currentPlayer].transform.rotation;

        // Set parent transform to current player
        transform.parent = players[currentPlayer].transform;
    }

    if (theStateManager.IsDoneAnimating == true)
    {
        isAnimating = false;
        return;
    }

    if (theStateManager.IsDoneAnimating == false)
    {
        isAnimating = true;
    }

    isAnimating = false;
}
void ResetCamera()
{
    transform.parent = null;
    startTime = Time.time;
    startPosition = transform.position;
    startOrientation = transform.rotation;
    distanceToPlayer = Vector3.Distance (transform.position, players[currentPlayer].transform.position);
  }
}

```

The `StateManager` is a piece of code that switches the players' turns. The gameplay works thus far.

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

public class StateManager : MonoBehaviour {

// Use this for initialization
void Start () {

}

public int NumberofPlayers = 4;
public int CurrentPlayerId = 0;

public int Dicetotal;

public bool IsDoneRolling = false;
public bool IsDoneClicking = false;
public bool IsDoneAnimating = false;

public GameObject NoLegalMovesPopup;

public void Newturn () {
    // This is the start of a player's turn.
    // We don have roll for them yet.
    IsDoneRolling = false;
    IsDoneClicking = false;
    IsDoneAnimating = false;

    CurrentPlayerId = (CurrentPlayerId + 1) % NumberofPlayers;
}

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

    // Is the turn done?
    if (IsDoneRolling && IsDoneClicking && IsDoneAnimating)
    {
        Debug.Log ("Turn is done!");
        Newturn ();
    }

}

public void CheckLegalMoves()
{
    // If we rolled a zero, then we clearly have no legal moves.
    if (Dicetotal == 0)
    {
        StartCoroutine ( NoLegalMoveCoroutine() );
        return;
    }

    // Loop through all of a player's stones.
    // Now I know everyone only has one stone, but just to be sure that
    // I don miss a part of the code. Besides, being extra secure never hurt anyone
    PlayerStone[] pss = GameObject.FindObjectsOfType<PlayerStone> ();
    bool hasLegalMove = false;
    foreach (PlayerStone ps in pss)
    {
        if (ps.PlayerId == CurrentPlayerId)
        {

            if (ps.CanLegallyMoveAhead (Dicetotal))
            {
                // TODO: Highlight tiles that are legal move spaces
                hasLegalMove = true;
            }
        }
    }

    // If no legal moves are possible, wait a sec then move to next player (and give a message)
    if(hasLegalMove == false)
    {
        StartCoroutine ( NoLegalMoveCoroutine() );
        return;
    }
}

IEnumerator NoLegalMoveCoroutine()
{
    // Display message
    NoLegalMovesPopup.SetActive (true);
    // Wait 1 second
    yield return new  WaitForSeconds(1f);

    NoLegalMovesPopup.SetActive (false);

    Newturn ();
}

}

```

# Answer
Looks like you already store the players `GameObjects` in your `CameraController`, so you could quite easily get their position and set the camera's position to that.

I wouldn't be setting the camera's transform to be a child of your current player though. Just have the camera position update every time the state changes to the currently selected player position, with a preferred offset, perhaps in your `NewTurn()` method?
> 2 votes

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


# Question
Title: How can I rotate my character so that he is facing the mouse?
I just want to preface this by saying I am very new to pygame.

At the moment I have calculated the angle that I need to apply to my character so he can rotate but I am unsure how to actually make him rotate (I understand the principle of it but not how to code it). I have tried to watch videos and look at other questions on here but I have only seen lots of different solutions that I can't implement into my own code.

I want to make it so that my character faces wherever my mouse is moving.

```
import pygame
import math
from random import randint

pygame.init()

screen = pygame.display.set_mode((600, 600))
screen_width = 600
screen_height = 600
pygame.display.set_caption("Mousey")
char = pygame.image.load('76011.png')
background = pygame.image.load('pygameback.png')
clock = pygame.time.Clock()

class Player:
    def __init__(self, x, y, width, height):
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.velocity = 12.5
        self.original = pygame.image.load('76011.png')
        self.rotated = self.original
        self.rect = self.rotated.get_rect()
        self.angle = 0

    def draw(self, win):
        screen.blit(char, (self.x, self.y))

class Enemy(Player):
    def __init__(self, x, y, width, height):
        Player.__init__(self, x, y, width, height)

    def draw(self, win):
        pygame.draw.rect(win, (0, 255, 0), (jeff.x, jeff.y, jeff.width, jeff.height))

def drawWindow():
    screen.blit(background, (0, 0))
    mag.draw(screen)
    jeff.draw(screen)
    pygame.display.update()

def XOR(a, b):
    if bool(a) != bool(b):
        return True
    return False

mag = Player(300, 300, 60, 60)
jeff = Enemy(180, 180, 60, 60)
run = True
while run:
    clock.tick(40)

    keys = pygame.key.get_pressed()

    for e in pygame.event.get():
        if e.type == pygame.QUIT:
            run = False
        if e.type == pygame.MOUSEBUTTONDOWN:
            mouse_x, mouse_y = pygame.mouse.get_pos()

        if e.type == pygame.MOUSEMOTION:
            mouse_x, mouse_y = pygame.mouse.get_pos()
            rel_x, rel_y = mouse_x - mag.x, mouse_y - mag.y
            angle = math.atan2(rel_y, rel_x)

    if XOR(keys[pygame.K_a], keys[pygame.K_LEFT]) and mag.x > mag.velocity:
        mag.x -= mag.velocity
        right = False
        left = True
    elif XOR(keys[pygame.K_d], keys[pygame.K_RIGHT]) and mag.x < screen_height - mag.width - mag.velocity:
        mag.x += mag.velocity
        right = True
        left = False
    elif XOR(keys[pygame.K_w], keys[pygame.K_UP]) and mag.y > mag.velocity:
        mag.y -= mag.velocity
        right = False
        left = False
    elif XOR(keys[pygame.K_s], keys[pygame.K_DOWN]) and mag.y < screen_height - mag.height - mag.velocity:
        mag.y += mag.velocity
        right = False
        left = False

    drawWindow()

```

I was also confused about where I need to make the character rotate. By this I mean, do I make a method inside the class that calculates the angle and makes the character rotate **OR** do I do all the calculations down where they are now?

# Answer
Take a look at the pygame.transform.rotate method. It allows you to transform the drawing surface temporarily (don't forget to transform it by the inverse rotation afterwards) so that anything you draw will be rotated.

Now, as far as calculating the angle to transform by, the pygame.transform.rotate method, unlike most rotate methods in libraries like this, requires that the argument supplied be in degrees, as opposed to radians. To calculate the angle needed to make your character face the mouse, first, make sure the image of your player is already facing the origin of PyGame's radial origin (usually, to the right), and then calculate the angle using the formula:

```
math.atan2((mouse.y - player.y), (mouse.x - player.x))

```

This will give you the angle in radians, which can then be converted to degrees using the following formula:

```
degs = radians * (180 / math.pi)

```

Note, if you're using Python 2.x, make sure to include the following import at the top of the module including this code:

```
from __future__ import division

```

This is so Python will use proper division instead of defaulting to integer division.

From there, just supply the degree value to the function like so:

```
pygame.transform.rotate(degs)
surface.draw(player)
pygame.transform.rotate(-degs)

```

You would do this wherever you do the rest of your rendering.

Hope that helps. Let me know if you need more help.
> 2 votes

---
Tags: 2d, rotation, python, pygame
---


# Question
Title: What is the difference between D3D12 structures/functions with terminal 1 in the name and without?
I could not figure out the difference between for instance CD3DX12\_DESCRIPTOR\_RANGE and CD3DX12\_DESCRIPTOR\_RANGE1.

Why do both exist? Which should I use? Is there a general rule of behavior/usage/recommendation for all structures and functions with both naming?

# Answer
> 2 votes
Looking at the documentation the `D3D12_DESCRIPTOR_RANGE1` structure has one extra member `D3D12_DESCRIPTOR_RANGE_FLAGS Flags;` to

> Specifies the D3D12\_DESCRIPTOR\_RANGE\_FLAGS that determine descriptor and data volatility.

So they are not the same, one has more information.

They are used by / available in **Root Signature Version 1.1** rather than Version 1.0

So the 1-suffixed versions are a newer version of the API. Most likely you want to use this unless you're targeting old incompatible hardware/drivers.

---
Tags: directx, directx12
---


# Question
Title: Why is my client's body drifting even after using data from the server, and how do I fix it?
I am trying to use Box2d on nodejs server with libGDX client. What I am trying to apply is authoritative server model so clients are just sending input data to server, server is running simulation and returning data to clients.

Client sends right key pressed input data to server, server calculates applyForce vector, applies force to server side body.

Server is sending world's body data to clients such as linearVelocity, position angular velocity etc with `sendWorldData()` function. After geting data, clients equalize this data to client side bodies.

Right now I just equalize linear velocity data, if I use `setTransform` on body for same position, it breaks the simulation and game crashes. I guess just linear velocity is way to go for now.

**The problem is: even though I return the same linearvelocity from server to client, bodies end up on slightly different `x,y` positions.**

```
client is
(6.8612046,7.3647866)
server is
(7.260152142360204,7.807573379341183)

```

I read a lot about this problem and started by trying to fix timestep on server and client. Client timestep:

```
private var fixedTimestepAccumulator = 0f
    private var MAX_ACCUMULATED_TIME = 1.0f
    val TIMESTEP = 1 / 60f
  fun update(delta:Float){
        fixedTimestepAccumulator += delta;
        if(fixedTimestepAccumulator > MAX_ACCUMULATED_TIME)
            fixedTimestepAccumulator = MAX_ACCUMULATED_TIME;

        while (fixedTimestepAccumulator >= TIMESTEP) {

            world.step(TIMESTEP, 6, 2);

            fixedTimestepAccumulator -= TIMESTEP;
        }

        inputUpdate(delta)
        cameraUpdate(delta)
        tmr.setView(camera)
        batch.projectionMatrix.set(camera.combined)

    }

```

Server update method:

```
var lastUpdate = Date.now()/1000;
var fixedTimestepAccumulator = 0;
var MAX_ACCUMULATED_TIME = 1;
var TIMESTEP = 1/60;

function physics_hanlder() {

    var now = Date.now() / 1000;
    var delta = now - lastUpdate;
    lastUpdate = now;
    fixedTimestepAccumulator = fixedTimestepAccumulator+delta;
    if(fixedTimestepAccumulator > MAX_ACCUMULATED_TIME)
        fixedTimestepAccumulator = MAX_ACCUMULATED_TIME;

    while (fixedTimestepAccumulator >= TIMESTEP) {
        world.step(TIMESTEP,6,2);
        sendWorldData() // sends servers body data to clients
        fixedTimestepAccumulator -= TIMESTEP;
    }

}

setInterval(physics_hanlder, 1000/60);

```

# Answer
Let's say that the communication delay between the server and the client is 50ms, not really unusual, but still noticeable.

If for instance we're dealing with the player who's going upwards but suddenly starts going to the right, this information takes around 50ms to reach the server. Since that timeframe contains multiple updates probably, the player character on the server will drift a little.

This is the main reason people don't use extrapolation that much nowadays. Instead they generally go with interpolation.

Instead of knowing the current state of the game and guessing the states after it, you take the last and current state and interpolate the object between them. This introduces a couple of problems for fast paced games (e.g. in shooters you need to go back a bit to see what the players were shooting at), but this is easier to solve, than lowering latency. If you don't do some kind of calculation, you'll get the PUBG experience of having to shoot 5 feet in front of someone, to hit them.

However, if the game isn't fast paced and the exact position of the players doesn't matter that much, you could just send the positions to the clients instead of velocities.
> 1 votes

---
Tags: libgdx, javascript, box2d, client-server, synchronization
---


title: 2D Circular Distribution Overlap

text:
# Question
Title: 2D Circular Distribution Overlap
I'm working with the C# wrapper for SDL and am stumped at how to handle this issue. Right now I have a simple Actor that spawns N number of bullets from himself and fires them circularly outward. The problem is that the last bullet renders on top of everything and looks awful.

Below is a picture with the last bullet painted blue with the shooting actor in the center (also blue).

I was hoping to try and figure out how to get it above the 2nd to last bullet while the bottom half is under the first. The closest thing I could find on this subject was this CSS article. The problem though is that it is solving the issue with 3D and I am working in pure 2D. Here's a picture from the article of what I am trying to achieve.

I can't tell if this is something easy or really hard to achieve, but it appears I definitely don't know what to search for because even that one article I found, I just happened to stumble upon it by looking at Google Images.

So I guess my question is, what is the proper term for this and what are the tricks to trying to solve this in a 2D space?

# Answer
> 2 votes
This can be done by using SDL\_SetClipRect. This'll basically only allow you to render inside the provided rectangle.

First draw the first 3/4 of the circles. If you started at the circle farthest to the right, this would leave you with a circle, where the top right quarter is missing.

Place the rectangle so that the left side of it lines up with the left side of the window, the top side lines up with the top, the right with the right and the bottom with the top of the second circle (y is the center of the second circle minus radius).

Draw the rest of the circles and to make sure everything lines up, draw the first one again. Since the clipping rectangle stops the circles from touching the second circle, they won't get above it.

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