# Question
Title: Java application chokes - when using MySQL
If I use localhost - XAMPP, my application runs without problems. Once I try to use real MySQL databases: db4free.net, freedb.tech. Applications begins to choke and freezing, resulting it is nearly impossible to use.

If I choose to use paid MySQL database, will it solve problem?

```
public static void scanningPlayers ()
{
    updatePlayers.setNode( GameGroups.finalRoot); // does'nt matter node.
    updatePlayers.setDuration(Duration.millis(1000));
    updatePlayers.play();
    updatePlayers.setOnFinished(evt ->
    {
        GameGroups.rootPlayers.getChildren().clear();

        try
        {
            Statement stmt      = Credentials.conn.createStatement();
            ResultSet users     = stmt.executeQuery("select id, name, avatar, Xpos, Ypos from users");

            while ( users.next() )
            {
                Label playerName            = Default.Label17Light  ( "" + users.getString("name"), users.getInt("Xpos"), users.getInt("Ypos") - 25 );
                ImageView hero;

                hero            = Default.ImageView( Dir.adventure + users.getString("avatar") + ".png", users.getInt("Xpos"), users.getInt("Ypos") );

                GameGroups.rootPlayers.getChildren().addAll ( playerName, hero );

                if ( users.getInt("id") == Variables.id )
                { //identify mysel, used for centering n door.
                    Variables.Xpos = users.getInt("Xpos");
                    Variables.Ypos = users.getInt("Ypos");
                    Variables.myAvatar = hero;

                    GameGroups.rootUniverse.setTranslateX ( -Variables.Xpos  + 550);
                    GameGroups.rootUniverse.setTranslateY ( -Variables.Ypos  + 362);
                }
            }
        } catch (SQLException e) {e.printStackTrace(); }

        updatePlayers.play();
    });
}

```

# Answer
Accessing the database is a very slow operation. In order to access a database, the following things need to happen:

1. Build an SQL query string in memory
2. Put that SQL query into a TCP/IP packet
3. Pass that packet to the network driver of the operating system
4. Send the packet to the network hardware
5. Put the packet into an ethernet frame
6. Route that ethernet frame through the network to the database server, potentially through kilometers of cable and several routers.
7. Unpack that ethernet frame into a TCP/IP packet
8. Forward that packet to the server socket of the MySQL database
9. Parse and validate the SQL string
10. Put it into the buffer of unprocessed SQL queries
11. Fetch the query from the buffer
12. Run the query on the database table(s) and assemble the result set
13. Format the result set into an SQL response string
14. Put that response into a TCP/IP packet
15. Pass that packet to the network driver of the operating system
16. Send the packet to the network hardware
17. Put the packet into an ethernet frame
18. Route that ethernet frame through the network back to the host the game runs on, potentially through kilometers of cable and several routers.
19. Unpack that ethernet frame into a TCP/IP packet
20. Forward that packet to the client socket of the gameserver
21. During all that time, the thread scheduler of your operating system will likely have put your idling game process to sleep, so you have to wait until the thread scheduler wakes it up again.
22. Parse the SQL response
23. Continue with program execution

All this stuff takes much, much longer than just reading a value from memory. Getting the best database server money can buy will only accelerate the steps 7-17. The network roundtrip alone will break your performance. So no, this is not a problem you can solve by throwing money at it.

So what should you do instead?

Do not do any database requests in your inner loop. Request data from the database once, and then keep it in memory. Only write data to the database when you need to persist it permanently.

When you do database requests, don't do them on the main thread. Do them on a background thread, so your application keeps running while it waits for a response from the database. For more information about how to do that, check out this Stackoverflow question: "Is asynchronous jdbc call possible?"
> 1 votes

---
Tags: java, mysql
---


title: Object turns white

text:
# Question
Title: Object turns white
Any idea why this character turns white in Game window with Play button on and off? The character is fine when the animations are not present but the file with the animations shows the character as white and the animation doesn't start even though the animator animation bar looks as though the animation should be running.

I've uploaded the character file at the link below, basically if this character is dragged in a new project the Game tab will show it as all white.

https://easyupload.io/5xzvm7

# Answer
Your FBX file has a pile of point lights in it. These bathe the model in bright light from all sides, over-exposing it until it shines pure white.

Right-click on your prefab instance in the scene and select "Prefab-\>Unpack", then select the seven child objects named "Point" through "Point.006" and delete them.

Now you can rename the root "Xenomorph-noLights", and drag it into your Project window to create a new prefab with all the mesh and animation information, but without the unwanted lights.
> 1 votes

---
Tags: unity, animation, materials
---


title: Added tiles not loading in run time

text:
# Question
Title: Added tiles not loading in run time
So I have a game object MapGenerator and 2 attached scripts: MapGenerator.cs and Lexicon.cs.

I need to be able to access a couple variables in Lexicon.cs from MapGenerator.cs, so I imported it with:

```
void Awake()
{
    GameObject gameObject = new GameObject("Lexicon");
    lexicon = gameObject.AddComponent<Lexicon>();
}

```

Now, this allows me to pull variables from Lexicon, and I am able to do that successfully for the most part. However, the public fields that are being set from Unity (tiles/sprites) are not being pulled in. They just show up as null.

Example scenario:

```
public class Lexicon : MonoBehaviour
{
public Tile thiccTile;
public Tile thiccTile2;
public Tile thiccTile3;
private string fact = "Yummy porchop";
private string favoritefact;
private Tile favoritetile;

 public Lexicon() {
  favoritetile = thiccTile2; //this guy is public and set in unity under components.
  favoritefact = fact;
 }

public Tile Favoritetile { get { return favoritetile; } set { favoritetile= value; } }
public string Favoritefact { get { return favoritefact; } set { favoritefact= value; } }

```

}

```
Start() {
UnityEngine.Debug.Log(lexicon.Favoritefact); //"Yummy porchop"
UnityEngine.Debug.Log(lexicon.Favoritetile); // null
}

```

My first thought was it was because I never explicitly call Lexicon(). However, since favoritefact works, im guessing the gameobject stuff is enough? Anyway, how can I fix this?

EDIT: This is where I set the values (Different variable names but you get the idea)

# Answer
It looks like this is a misunderstanding of how instances of MonoBehaviour scripts work in Unity.

A MonoBehaviour script is a (non-static) class, which means it's a template for a *kind* of object you can have in your project - not a unique or global repository. When you add a MonoBehaviour component to a Game Object, what you have created is one *instance* of that script.

Your project could contain zero instances of the script, or one, or hundreds. Each individual instance gets to have its own set of values stored in its member variables. So setting the variables in the Inspector on one instance does not automatically change the values held in a different instance, or in instances you create in the future.

If I understand correctly what you are doing, in the editor you've added a Lexicon component to a game object, and populated *that one instance* with the variables you want.

Then at runtime, you have another script that creates a *new*, empty game object called "Lexicon" (no relation to the object you set your variables on previously), and attaches to that game object a *new* instance of the Lexicon component. Since this component is new, all of its variable have the default values from the code file. Nothing here tells Unity it should fetch the variables you set in the inspector on that particular other Lexicon component at edit time.

This is a bit like writing a letter, and putting it in an envelope. Then the next day, taking a blank sheet of paper, folding it into an envelope, and opening it - being surprised that this new envelope doesn't contain your letter. Well of course it doesn't, it's *not the same envelope* you put your letter into!

Your attempt to use `GameObject.Find("Lexicon")` will work if the component you set up in the Inspector was on a game object that currently exists *in the same scene* your script Awake script is running in, and named exactly "Lexicon". This method searches only the current scene, and won't find objects you configured in other, unloaded scenes, or in prefabs in your Assets folder. It's also extremely picky about the name. So if you have a "Lexicon" prefab that you spawn at runtime to make an instance in your scene called "Lexicon (Clone)", the `Find` method won't find that one.

Sometimes folks use the singleton pattern to make one globally-accessible instance of a MonoBehaviour script, but singletons have their own complications, and I think we can do better for your use case.

If you just want a data container other scripts can reference, what you might want instead is a **ScriptableObject**. This is a type like a MonoBehaviour that lets you edit data in the Inspector window, but it doesn't attach to a game object in your scene. Instead, it can exist as a standalone asset in your Assets folder. This makes it useful for authoring shared data that you might want to reference from many scripts or many scenes.

Here's what that might look like:

```
// This attribute lets us create an instance of this asset via the menus.
[CreateAssetMenu(fileName="Lexicon.Asset", menuName = "Data/Lexicon")]
public class Lexicon : ScriptableObject
{
    public Tile thiccTile;
    public Tile thiccTile2;
    public Tile thiccTile3;
    private string fact = "Yummy porchop";

    private string favoritefact;
    private Tile favoritetile;

    // Generally for Unity types we avoid using constructors,
    // since object properties are set during deserialization.
    // OnEnable or Awake are good substitutes for ScriptableObjects.
    void OnEnable() {
      favoritetile = thiccTile2;
      favoritefact = fact;
    }

    // It looks like you could implement these as auto-properties for less typing...
    public Tile Favoritetile { get { return favoritetile; } set { favoritetile= value; } }
    public string Favoritefact { get { return favoritefact; } set { favoritefact= value; } }

```

The attribute at the top lets us create an instance of this asset type via the Assets-\> Create menu or the right-click context menu in the Project window:

Then we get a new asset we can configure in the Inspector:

Note how this data is standalone, not attached to a game object or prefab, and not bound to any scene.

Now any script can hold a reference to this Lexicon by declaring a public variable:

```
public Lexicon lexicon;

```

And you can assign it in the Inspector to reference this asset:

This reference will work from any scene, any prefab, etc., and keeps your data centralized in a single asset file rather than duplicated among multiple scenes.
> 1 votes

# Answer
Both favoritetile and favoritefact will get assigned when the object is instantiated. Favoritefact will get assigned "yummy porchop", no ifs/ands/or buts about it, since it is a string literal within the script.

IF thiccTile2 has an assigned a value in the inspector (Unity UI as you call it), then that value will get assigned to favoriteTile. This is where the problem is. If favorite tile is null after instantiation, its because thiccTile2 does not have a value. You might *think* you have assigned it value (but actually have not), for a couple possible reasons:

1. You have a gameobject in your scene with a Lexicon component attached, and you have assigned the value to the component in that gameobject. In this scenario, that Lexicon component is an instance of the Lexicon class. Any values you assign in the inspector will only be assigned to that instance of the class. When you Instantiate a new Lexicon (in your Awake() method), it has no knowledge of the existing Lexicon that is already attached to the gameobject in the scene, and so thiccTile2 is null. You can fix this by updating your Awake() method to get a reference to the existing Lexicon where you have assigned your values in the inspector (using GameObject.Find().GetComponent()). I believe this is the problem. If you actually want a new instance of Lexicon on your game object, you will have to either copy the values from the existing instance, or create a prefab with the Lexicon component, assign your values to the component of the prefab, and then instantiate that prefab.
2. A second scenario is that you have assigned your values and references correctly, but done so in play mode. Nearly all changes done in play mode will be discarded / reverted after exiting to edit mode and restarting play mode. Since your debug happens in Awake(), I can imagine a scenario where you enter play mode with bad references \> see the null debug \> fix your references \> realize you need to restart your game to see the new debugs \> exit play mode (and unknowingly discard your fixed references) \> start play mode and see the same error, and think your changes didnt fix anything. This seems like the unlikely culprit, given the snippets of code you have provided.

The real bottom line is when you instantiate Lexicon using new Lexicon(), thiccTile2 is null, so favoriteTile is null. You need to either pass it in as a constructor variable, or look it up from a reference to a prefab/existing gameobject component or something.
> 0 votes

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


# Question
Title: Unity ScrollView not scrolling with Clamped or Elastic
I have a ScrollView object in my project. It is set to Clamped.

Inside the ViewPort, I have Content and what I actually want to scroll, a TextViewMesh. The Content has a Content Size Fitter, with its Vertical fit set to Preferred Size.

The problem is, when I run it, and try to scroll, it does not scroll at all, in ScrollView to the current setting. If I set the ScrollView mode to Unrestricted, it scrolls to the infinity. What I am doing wrong? How can I set my ScrollView to scroll the text (which can vary in lenght)?

# Answer
> 3 votes
Your screenshot shows that Viewport has two children, *Content* and *Description*. You stated that *Content* has a `ContentSizeFitter` component. If your text is on the *Description* object, the `ContentSizeFitter` is not going to adjust its size for the text because *Description* is not a child of *Content*.

You may need to move *Description* to be a child of *Content*, and add a `VerticalLayoutGroup` component to *Content*.

---
Tags: unity, scrolling, user-interface
---


# Question
Title: Why the OnCollisionEnter is not working?
This script is attached to the wall(3D Cube) with a box collider :

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

public class LockedRoomTrigger : MonoBehaviour
{
    private void OnCollisionEnter(Collision collision)
    {
        Debug.Log(collision.transform.name);
    }
}

```

But when the player is moving and hit the cube it's not getting to the Debug.Log I used a break point on the Debug.Log line.

A screenshot of the cube wall with the box collider component and the script attached to it. The problem is not with the player since if I'm moving with the player near doors they open so the player does trigger things and also not walking through walls.

This is a screenshot of NAVI. NAVI is a bit in front of the player and moving with the player and part of the player in the game like a friend helper.

NAVI is the one that collide and hit stuff if doors walls not the player since the NAVI is a bit in front of the player.

NAVI have only a box collider :

And this is the Inspector screenshots of the player. I will add two screenshots since it's not getting inside in one screenshot :

The player is a first person view :

# Answer
The `OnCollision*` events are for Rigidbody-Rigidbody collisions. They get called when two solid rigidbodies "bump" into each other.

When you want a "non-corporeal" trigger area, like an invisible zone which opens a door when the player enters it, then mark the "Is Trigger?" checkbox in that collider and implement the `OnTrigger*` events in its script (Like `OnTriggerEnter`). Keep in mind that the signature of the OnTrigger methods is different than of the OnCollision methods. While the OnCollision methods receive a `Collision` object with more information about how the collision occured, the OnTrigger methods only receive the `Collider` component which triggered it.

Further, take note of the collision action matrix in the documentation. Trigger events are only generated when at least one of the objects involved in the collision has a Rigidbody and the other is either marked as Static or also has a Rigidbody. Usual practice is to add no rigidbodies to trigger areas but rigidbodies to the objects which are supposed to trigger them.

tl;dr:

* Mark the "Locked Room Trigger" game object as "Static" or give it a Rigidbody component
* Mark the "Is Trigger?" checkbox of the collider of the Locked Room Trigger
* Make sure the object which is supposed to trigger the Locked Room Trigger has a Rigidbody component
* Use OnTriggerEnter instead of OnCollisionEnter:

```
public class LockedRoomTrigger : MonoBehaviour
{
    private void OnTriggerEnter(Collider other)
    {
        Debug.Log(other.name + " entered the trigger " + name);
    }
}

```
> 1 votes

# Answer
Is the Locked Room Trigger object supposed to be a trigger or a collider? From your question, it sounds like you intend it to be a trigger so you need to check "Is Trigger" on its box collider and use OnTriggerEnter instead of OnColliderEnter.
> 0 votes

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


# Question
Title: Why Post-Processing v1 not works in WebGL build?
In my WebGL browser app, i've tried to add Post Processing (first version) stack.

I'm using Unity 2018.4.6f1 (i started 1 years ago to develop this app).

I've added Post Processing Behaviour to my Camera, and this is what i've enabled:

When i run my scene on Chrome or Firefox, Camera appears all black but UI is correctly rendered.

Are there any incompatibility issue using Post Processing and WebGL ?

Thanks

# Answer
> 1 votes
PPS is not supported on WebGL 1. You should have Webgl2 capable browser and GPU required to run WEBGL 2. You can test here or this for WEBGL2 support on your browser. Fore more read this post.

---
Tags: unity, webgl
---


# Question
Title: Creating texture and palette modification
I need to create a texture from a surface with indexed color palette and alter the colors. However, after I set new colors, the rendered texture gets blank.

```
int main(int argc, char** argv)
{
    init();

    gSurface = TTF_RenderText_Solid(gFont, "text", fg1);

    // text is rendered properly, without following line
    SDL_SetPaletteColors(gSurface->format->palette, &fg2, 1, 1);

    gTexture = SDL_CreateTextureFromSurface(gRenderer, gSurface);

    SDL_SetRenderDrawColor(gRenderer, 255, 255, 255, 255);
    SDL_RenderClear(gRenderer);

    SDL_RenderCopy(gRenderer, gTexture, NULL, NULL);
    SDL_RenderPresent(gRenderer);

    SDL_Delay(1000);

    quit();
}

```

I tested this code with software rendering using window surface instead of renderer and pallete changing worked.
Could someone explain me why does it happed and how to fix it?

# Answer
> 0 votes
I think your problem is the fact that SDL\_SetPaletteColors wants an array of `SDL_Color`s as an argument instead of pointer to a single color. I cannot guarantee that this is the problem as you didn't post the code where you initialize the code, and you haven't told if `SDL_GetError()` returns an error message.

Otherwise, make sure to always check what `SDL_GetError()` returns on a SDL function you think might be the cause of the problem.

# Answer
> 0 votes
Some days ago I have encountered a similar issue with a short example SDL2 app. There were no mainloop as in your sample code. After mainloop added the image began to display.

Quick fix for your code seems to be: Put `SDL_Delay(10);` or `SDL_Delay(100);` between `SDL_RenderCopy` and `SDL_RenderPresent`. Just like that

```
SDL_SetRenderDrawColor(gRenderer, 255, 255, 255, 255);
SDL_RenderClear(gRenderer);

SDL_RenderCopy(gRenderer, gTexture, NULL, NULL);
SDL_Delay(10);
SDL_RenderPresent(gRenderer);

SDL_Delay(1000);

```

---
Tags: sdl2
---


# Question
Title: How to switch career to game engine/graphics programming
My whole background is related to enterprise applications but I've been thinking of switching my career path from enterprise/business to something that I feel is more challenging and interesting. One of the main fields I've checked is game programming and more specifically *engine* or *graphics* programming. One of the requirements I've set is that the new domain requires at least some math/computer science knowledge and have interesting problems to research and solve (hopefully even read some white papers). Graphics programming especially seems to have lot's of that in addition to being interesting in general. I've already started studying the related mathematical background via this book and I believe my general experience in developing and releasing quality software (5+ years) will quickly translate, with the right mentorship, putting me at a level of usefulness of a mid-level game programmer at least.

How should I go about proving this to potential employers? I don't feel like creating small sample games really amounts to anything. Familiarizing myself with an engine like Unity or Unreal seems like a good approach but I'm not sure how to go about it in an engine focused way. I'd potentially like to *avoid* *Gameplay* development which is why creating games seems redundant.

I *don't* want to enter subfields such as server programming or any field that is web-appy but under the umbrella of a game company. I'm also looking to transition relatively quickly which is why I don't want to invest in a game company as a web app developer only to hope to be put into game domain later.

TL;DR: I'm looking for ways to enter the "sciency" side of game programming (graphics/engine programming) with a background in enterprise web apps.

# Answer
> 1 votes
This is a bit of a Catch-22, unfortunately.

It's mainly the larger studios who need dedicated engine and graphics programmers, building out, porting, and optimizing custom engine features or rendering pipelines.

The ready availability of flexible, full-featured, off-the-shelf engines like Unreal and Unity means that many small studios are able to get the engine support they need out of the box, or with a much less specialized path of Asset Store plug-ins or modifier scripts. They'll usually have technical artists or general programmers with engine experience, but they don't necessarily need a large staff of full-time engine or rendering programmers.

The large studios, meanwhile, are largely looking for folks with experience shipping (large) games. Especially so for engine/graphics programmers, who have a specialized and often fairly senior role. So hopping straight into a position like that could be very challenging, unless you've already been in such a position, hence the Catch-22.

Even if non-engine code is not your passion, I'd suggest that it can be an easier route into the industry. Studios of all sizes tend to need more gameplay and UI programmers, and as you've found, it's an easier skill to demo in your portfolio to give the studio confidence they're hiring the right person.

Once you're in, you can start looking for advancement paths within the organization into more specialized roles. In the meantime, you'll be building up a portfolio of finished games you've shipped with that team, which can open up doors for you elsewhere, even if advancement in your current team is limited.

This also gives you a way to start earning income in your chosen field while you continue to hone the specialized skills your dream job needs - maybe even benefiting from company-paid training and conferences - instead of having to build all those skills on your own before you can make your move.

# Answer
> -2 votes
You need to know what game design is. There are many different type of games...and when you know what type of game what type of audience, and many game design related topics you will have no problem with choosing the right engine...and graphics. Ex: I want to make a 2d game... I want to apeal to darksouls audience... I want networking inthe game... I want to be able to scale the game (size graphic updates etc) Mybe godot can do that? Ok I will check godot then unity

---
Tags: graphics-programming, physics-engine, career, webapp
---


# Question
Title: Why do we have to use a fractional numbers in the graphic engines (2D/3D)? Why integers are not enough?
Maybe it'll be a super beginner question but can someone explain me why do we have to use a fractional numbers (`floats`, `doubles`) in the graphic engines (2D/3D)? Couldn't be all the calculation results just rounded up to an integers values or even such constructed not to use fractions at all?

# Answer
Vaillancourt's answer covers why we need to provide floats to work with our graphics acceleration APIs, but I think we can go a bit deeper into why do our graphics acceleration APIs expect floats in the first place.

So why do we even have graphics acceleration APIs?

It's important to remember that one of the big reasons hardware graphics acceleration came about was to support 3D rendering and 3D games. If all you want is pixel-perfect 2D sprites, you can already get a very long way with the CPU alone, working all in integers or any other data type you like. Even back in the days when 3D accelerators were still new and CPUs were far less powerful than today, we had beautiful and fast 2D games.

But 3D brings with it an order of magnitude more complexity, and several aspects that require or benefit from fine-grained fractional representation, including...

* Perspective projection: the closer something is to my camera in 3D, the bigger it looks on my screen. That means even if I choose a suitable integer position grid based on a particular viewing distance, any time objects get closer to my camera than that, I'm going to start to see rounding errors, because those gaps between integer positions are now bigger than a screen pixel.

You can see this in old PS1 games, where meshes often had a noticeable distortion or vibration, as vertices snapped to representable positions in the fixed-point coordinate system the console used.

Floating point has an additional advantage over integer/fixed point solutions here, in that while it also has rounding, the rounding error is proportional to the magnitude of the value. So vertices close to the camera, where errors would be most noticeable, have the highest precision available and experience the least rounding error. Further away, the rounding error can eventually get worse than an integer-based system, but at that distance the errors end up smaller than a pixel on-screen if we've done our work right.
* Texture mapping: computing which pixel of a texture to draw on a skewed polygon in a perspective-correct way requires dividing by the depth from the camera. If that depth is measured as an integer, many possible output ratios won't be representable as an integer, making the texture appear to crawl or slosh across the surface rather than track it perfectly.
* 3D animation: if I have a character built out of connected bones, snapping in the allowable positions and rotations of a parent bone cascades down to its children and their children. Allowing fractional values in the orientation lets even long bone chains play and blend-together smooth animations without visibly snapping from pose to pose.

All of these features include at their heart being able to divide something into small parts, and even though floating point division is slower than addition/multiplication/subtraction, integer division is often even slower. So floats fill this role pretty well.

So, there are very good reasons to make a fast floating point path in 3D graphics acceleration hardware, to handle these common use cases where CPU rendering just wasn't enough.

And once you have a fast float path, you might as well make that the only path: a 32-bit float can represent all the integer values from negative to positive 16 million - plenty of range to uniquely address every pixel on your screen if all you need is pixel-perfect 2D with integer snapping. So there's not a big demand to complicate the hardware or the graphics APIs with a separate all-integer solution.
> 3 votes

# Answer
Your graphics API expects this. I'll quote a site that will explain it better that I would (emphasis mine):

> OpenGL expects all the vertices, that we want to become visible, to be in normalized device coordinates after each vertex shader run. That is, the x, y and z **coordinates of each vertex should be between -1.0 and 1.0**; coordinates outside this range will not be visible. <sup>(Source)</sup>
> -1 votes

---
Tags: c++, architecture, software-engineering
---


# Question
Title: How to get a random Vector 2 within a range
I'm working on a game and I need the objects that get spawned to launch within a range of angles, so like in the horrible 2 second paint image seen below, I need to grab a random vector within that range of arrows, and then the ball will go off in that direction. I'm just not sure how to get a vector within a range like that. This is in C# and Unity, the game is 2D. Any ideas?

# Answer
I would write a function that uses a random rotation value and converts it into a Vector2 using sin/cos.

The following function takes the angle range (in radians) for how big you want the range of values to be in, and a starting angle if you want it offset.

C#

```
public Vector2 RandomVector2(float angle, float angleMin){
    float random = Random.value * angle + angleMin;
    return new Vector2(Mathf.Cos(random), Mathf.Sin(random));
}

```

JavaScript

```
function RandomVector2(angle, angleMin){
    var random = Math.random()*angle+angleMin;
    return [Math.cos(random), Math.sin(random)];
}

```

Sample use

```
RandomVector2(3.1415, 0.0); // random angle between 0-180 degrees
RandomVector2(3.1415, 3.1415); // random angle between 180-360degrees

```
> 7 votes

# Answer
The other answer's here work fine. If you want a "vector only" approach you could use a Lerp function. Basically, generate a new vector that blends between two others based on a random value.

It's quick, intuitive, and you get reliable results. Also you're just using a built in vector math call, so you don't have to worry about implementation issues.

```
Vector2 RandomV2(Vector2 min, Vector2 max){
    return Vector2.Lerp(min,max, Random.value).normalized;
}

```
> 2 votes

# Answer
Personally I find the following approach more intuitive:

1. Generate the random angle as a float like

```
float angle = Random.Range(minAngle, maxAngle);
```
2. Then use a function like

```
// https://answers.unity.com/questions/823090/equivalent-of-degree-to-vector2-in-unity.html
public static Vector2 DegreeToVector2(float degree)
{
    return RadianToVector2(degree * Mathf.Deg2Rad);
}
public static Vector2 RadianToVector2(float radian)
{
    return new Vector2(Mathf.Cos(radian), Mathf.Sin(radian));
}
```

to convert it into a Vector2.
> 2 votes

# Answer
Randomize first the X values.

```
offsetLeft = -3;
offsetRight = 3;
ballposX = gameobject.transform.position
int randomX = Random.Range(ballposX.x-offsetLeft,ballposX.x+offsetRight

```

Then after that you could probably use a velocity function `rb.velocity = new Vector3(randomX, gameobject.trasform.position.y + 3, 0);` I havent really tried this code but maybe that will maybe give an idea
> -1 votes

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


# Question
Title: Reversing plane projection texture mapping algorithm
I found this algorithm in some old codebase, it takes two triangles from a mesh ABC and PMN, where ABC is the triangle that will be rendered and PMN is an extra triangle that is only used to generate the UV coordinate for ABC and is not rendered.

I am trying to create a reverse algorithm to calculate the PMN triangle positions based on UV coordinates of a triangle and ABC positions of the same triangle.

```
Vector3f A = /* stored in mesh data */;
Vector3f B = /* stored in mesh data */;
Vector3f C = /* stored in mesh data */;

Vector3f P = /* stored in mesh data */;
Vector3f M = /* stored in mesh data */;
Vector3f N = /* stored in mesh data */;

Vector3f PM = M.sub(P, new Vector3f());
Vector3f PN = N.sub(P, new Vector3f());
Vector3f PA = A.sub(P, new Vector3f());
Vector3f PB = B.sub(P, new Vector3f());
Vector3f PC = C.sub(P, new Vector3f());

Vector3f PMxPN = PM.cross(PN, new Vector3f());

// Calculate the U coordinates
Vector3f U = PN.cross(PMxPN, new Vector3f());
float Mu = 1.0F / U.dot(PM);
float Ua = U.dot(PA) * Mu; /* 1st U coordinate (for vertex A) */
float Ub = U.dot(PB) * Mu; /* 2nd U coordinate (for vertex B) */
float Uc = U.dot(PC) * Mu; /* 3rd U coordinate (for vertex C) */

// Calculate the V coordinates
Vector3f V = PM.cross(PMxPN, new Vector3f());
float Mv = 1 / V.dot(PN);
float Va = V.dot(PA) * Mv; /* 1st V coordinate (for vertex A) */
float Vb = V.dot(PB) * Mv; /* 2nd V coordinate (for vertex B) */
float Vc = V.dot(PC) * Mv; /* 3rd V coordinate (for vertex C) */

```

Formatted LaTex represention of the same algorithm: $$ \vec{PM} = \vec{M} - \vec{P} \\ \vec{PN} = \vec{N} - \vec{P} \\ \vec{PA} = \vec{A} - \vec{P} \\ \vec{PB} = \vec{B} - \vec{P} \\ \vec{PC} = \vec{C} - \vec{P} \\ \vec{PMPN} = \vec{PM} \times \vec{PN} \\ $$

$$ \vec{U} = \vec{PN} \times\vec{PMPN} \\ Mu = \frac{1} {\vec{U} \cdot \vec{PM}} \\ Ua = \vec{U} \cdot \vec{PA} \times Mu \\ Ub = \vec{U} \cdot \vec{PB} \times Mu \\ Uc = \vec{U} \cdot \vec{PC} \times Mu \\ $$

$$ \vec{V} = \vec{PM} \times\vec{PMPN} \\ Mv = \frac{1} {\vec{V} \cdot \vec{PN}} \\ Va = \vec{V} \cdot \vec{PA} \times Mv \\ Vb = \vec{V} \cdot \vec{PB} \times Mv \\ Vc = \vec{V} \cdot \vec{PC} \times Mv \\ $$

# Answer
> 1 votes
Because this is a projection from 3D down to 2D, it's not invertible. So we can't recover *the* triangle \\$\triangle PMN\\$ that was used to create the original projection. But we can find a member of a *family* of triangles that fits that bill.

For simplicity, let's choose the member of that family that lies in the same plane as our mesh triangle \\$\triangle ABC\\$. That means our points \\$PMN\\$ are linear combinations of the points \\$ABC\\$. That is, they'll be of the form:

$$A + s (B - A) + t (C - A)$$

...for some real numbers \\$s\\$ and \\$t\\$. Taking a look at the UV coordinates of our points in \\$\triangle ABC\\$, we can define:

$$u\_1 = U\_b - U\_a \quad u\_2 = U\_c - U\_a\\ v\_1 = V\_b - V\_a \quad v\_2 = V\_c - V\_a$$

And with that, we can take any point \\$(s, t)\\$ and get its uv coordinates under this mapping with a matrix multiplication:

$$\begin{bmatrix}u\\v\end{bmatrix} = \begin{bmatrix}u\_1 & u\_2\\v\_1 & v\_2\end{bmatrix} \begin{bmatrix}s\\t\end{bmatrix} \+ \begin{bmatrix}U\_a\\V\_a\end{bmatrix}$$

You can verify that for the points A, B, and C, this gives exactly the UVs we expect, and so it gives correct UVs for any linear combination of them too. And since we decided to place our \\$\triangle PMN\\$ in the same plane, this formula also gives the corresponding UVs for \\$P\\$, \\$M\\$, and \\$N\\$.

Now we can work backwards from their 2D UV coordinates to find their 3D positions on the plane.

By construction, the plane projection mapping algorithm always assigns \\$P\\$ the coordinates \\$(u, v) = (0, 0)\\$ (we always subtract \\$P\\$ from the input point, getting zero if \\$P\\$ was the input, and the subsequent multiplications keep it at zero)

Now we'll solve...

$$\begin{align} \begin{bmatrix}u\_1 & u\_2\\v\_1 & v\_2\end{bmatrix} \begin{bmatrix}s\_P\\t\_P\end{bmatrix} \+ \begin{bmatrix}U\_a\\V\_a\end{bmatrix} &=\begin{bmatrix}0\\0\end{bmatrix}\\ \begin{bmatrix}u\_1 & u\_2\\v\_1 & v\_2\end{bmatrix} \begin{bmatrix}s\_P\\t\_P\end{bmatrix} &=\begin{bmatrix}-U\_a\\\-V\_a\end{bmatrix}\\ \begin{bmatrix}u\_1 & u\_2\\v\_1 & v\_2\end{bmatrix}^{-1} \begin{bmatrix}u\_1 & u\_2\\v\_1 & v\_2\end{bmatrix} \begin{bmatrix}s\_P\\t\_P\end{bmatrix} &=\begin{bmatrix}u\_1 & u\_2\\v\_1 & v\_2\end{bmatrix}^{-1}\begin{bmatrix}-U\_a\\\-V\_a\end{bmatrix}\\ \begin{bmatrix}s\_P\\t\_P\end{bmatrix} &=\frac 1 {u\_1v\_2 - u\_2v\_1} \begin{bmatrix}v\_2 & -u\_2\\\-v\_1 & u\_1\end{bmatrix} \begin{bmatrix}-U\_a\\\-V\_a\end{bmatrix} \end{align}$$

Now we have

$$P = A + s\_P(B-A) + t\_P(C-A)$$

There's a similar trick for finding \\$M\\$ and \\$N\\$.

First, note that we get our \\$u\\$ coordinate for a point \\$X\\$ as \\$U\_X = \frac {\vec U \cdot (X - P)} {\vec U \cdot (M - P)}\\$. So if our input point was \\$M\\$ itself, then this can only give us the number one!

The v coordinate is a bit harder to see, but note that \\$\vec V = (M - P) \times \vec {PMPN}\\$. So it must be orthogonal to \\$(M - P)\\$, so the dot product \\$\vec V \cdot (M - P)\\$ must be zero.

The same argument applies in turn to \\$N\\$, and so we get a clearer picture of what these three points signify: \\$P\\$, \\$M\\$, and \\$N\\$ define three corners of our UV-mapping square:

$$P \rightarrow (0, 0)\\ M \rightarrow (1, 0)\\ N \rightarrow (0, 1)$$

So, we can substitute those UV values, and solve for \\$M\\$ and \\$N\\$ in exactly the same way:

$$\begin{bmatrix}s\_M\\t\_M\end{bmatrix} =\frac 1 {u\_1v\_2 - u\_2v\_1} \begin{bmatrix}v\_2 & -u\_2\\\-v\_1 & u\_1\end{bmatrix} \begin{bmatrix}1 -U\_a\\\-V\_a\end{bmatrix}\\ M = A + s\_M(B - A) + t\_M (C-A)$$

$$\begin{bmatrix}s\_N\\t\_N\end{bmatrix} =\frac 1 {u\_1v\_2 - u\_2v\_1} \begin{bmatrix}v\_2 & -u\_2\\\-v\_1 & u\_1\end{bmatrix} \begin{bmatrix}-U\_a\\1 - V\_a\end{bmatrix}\\ N = A + s\_N(B - A) + t\_N(C-A)$$

In my tests with random triangles, using single-precision floats throughout, this correctly reproduces the UV mapping to within 0.001, which I'd attribute to rounding errors along the way. If you have more sensible triangles, and use double-precision intermediates, you could probably reduce the deviation even further.

---
Tags: textures, projection, uv-mapping
---


# Question
Title: Managers class losing reference to Game Manager when changing scene in Unity
I've got a singleton set up with a overarching Managers class that has references to each of my other managers classes.

I also have a state machine set up that handles changing scenes between the Main Menu, the Gameplay, and the Game Over scene. These are also the corresponding states.

I'm using DontDestroyOnLoad on the Managers class so all that stuff should stay put between scenes.

The problem I'm running into however is that when it switches from the MainMenu to the Gameplay state, it apparently loses the reference to the GameManager object.

The error I get pops when I try to hit the GameManager for the second time when the game tries to change from Gameplay state to the Gameover state. It says it has been deleted, but if I put a debug.Log in the GameManager class's update function, it is still firing. I have tried to put a method in the Managers class that I could call to reassign it after the new level is loaded, but that doesn't seem to work.

I've pretty much tried everything I could think of, and asked on another site but nobody could figure it out there either. Hopefully somebody here can shed some light on what the problem is and how to fix it.

Below is all the code I think should be needed for this and also an image of the error I'm getting. Thanks everyone!

```
public class Managers : MonoBehaviour
{
public static Managers instance = null;

private static GameManager _gameManager;
public static GameManager Game
{
    get{ return _gameManager; }
}

private static UIManager _uiManager;
public static UIManager UI
{
    get{ return _uiManager; }
}

private static LevelManager _sceneManager;
public static LevelManager Level
{
    get{ return _sceneManager; }
}

private static BoardManager _boardManager;
public static BoardManager Board
{
    get{ return _boardManager; }
}

private static PickUpManager _pickUpManager;
public static PickUpManager PickUp
{
    get{ return _pickUpManager; }
}

private static SoundManager _soundManager;
public static SoundManager Sound
{
    get { return _soundManager; }
}

void Awake ()
{
    if (instance == null)
    {
        instance = this;
    } else if (instance != this)
    {
        Destroy(gameObject);
    }

    DontDestroyOnLoad(gameObject);

    _gameManager = GetComponent<GameManager>();
    _uiManager = GetComponent<UIManager>();
    _sceneManager = GetComponent<LevelManager>();
    _boardManager = GetComponent<BoardManager>();
    _pickUpManager = GetComponent<PickUpManager>();
    _soundManager = GetComponent<SoundManager>();
}

void Update ()
{
    if (Managers.Game == null) //this if statement is here simply to show me that Managers does not have a reference to this anymore
    {
        Debug.Log("This is null");
    }
}
}

public class GameManager : MonoBehaviour
{
public static MonoBehaviour monoBehaviour;
public bool isGameActive;
private int level = 50;
private _StatesBase currentState;

// Use this for initialization
void Awake ()
{
    isGameActive = false;
    InitGame();
    monoBehaviour = this;
}

public _StatesBase State
{
    get { return currentState;}
}

void InitGame ()
{
    Managers.Board.SetupScene (level);
}

public void SetState (System.Type newStateType)
{
    if (currentState != null)
    {
        currentState.OnDeactivate ();
    }

    currentState = GetComponentInChildren (newStateType) as _StatesBase;
    if (currentState != null)
    {
        currentState.OnActivate();
    }
}

void Update ()
{
    Debug.Log("THIS IS A GAME MANAGER!!!"); //Just to check that it's still
here. It is still showing even when Managers class reference is null.
    if (currentState != null)
    {
        currentState.OnUpdate();
    }
}

void Start ()
{
    SetState(typeof(MainMenuState));
}
}

public class GamePlayState : _StatesBase
{
public override void OnActivate ()
{
    Debug.Log("GamePlay OnActivate");
    Managers.Level.LoadLevel("Level_01");
    Managers.Game.isGameActive = true;

}

public override void OnDeactivate ()
{
    Debug.Log("GamePlay OnDeactivate");
    Managers.Game.isGameActive = false;
}

public override void OnUpdate ()
{
    Debug.Log("GamePlay OnUpdate");
}
}

public class LevelManager : MonoBehaviour
{
public void LoadLevel (string name)
{
    SceneManager.LoadSceneAsync(name);
    Brick.breakableCount = 0;
}

public void QuitGame ()
{
    Application.Quit();
}

}

```

# Answer
> 2 votes
Changing scenes destroys all game objects in that scene. Your `GameManager` is a `MonoBehaviour` and is therefore likely attached to a game object that is being destroyed.

# Answer
> 0 votes
I'm not sure this will be the answer you're looking for, but for managers I don't let them extend MonoBehaviour, in part because all MonoBehaviours are controlled by Unity processes in the backend and this can have unintended consequences.

I create manager classes as individual singletons. I then create a GameObject that contains a single MonoBehaviour script that pulls the instances of those managers. They don't reflect in the inspector (though that can be worked around with custom drawers and such), but those instances never get destroyed no matter what happens in the scene. In that event, even if the ManagerManager GO gets destroyed and recreated, the instances of the individual managers are static and persistent and therefore don't lose any information when the new GO picks them up.

This is a gist of my skeletal singleton class:

https://gist.github.com/xepherys/34d3d5ce3f44749e8649a25b38127347

I *always* start with this. It's threadsafe, provides easy access via the `.Instance` property, and is used in quite a few of the applications I write and maintain for my day job very successfully.

The ManagerManager script would just look something like this:

```
public class ManagerManager : MonoBehaviour
{
   public PlayerManager _playerMgr = PlayerManager.Instance;
   public GameManager _gameMgr = GameManager.Instance;
   public TimeManager _timeMgr = TimeManager.Instance;
}

```

The additional benefit of having a truly instanced, lazy singleton for your managers is that it's easy to call them from any class. You could have any script anywhere at any time reference `GameManager.Instance.Property` or `GameManager.Instance.Method()`

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


# Question
Title: How can I assign an icon to multiple game objects in the Unity Editor?
In my game, I have hundreds of enemy spawn points represented as invisible GameObjects, with one having an assigned icon as seen here:

However, I would like to give all of the spawn points icons like this through the inspector view like this first point. However, when selecting a group of them, the editor doesn't seem to allow me to give all of them the same icon. Is there a way to perform that task, without going through every single spawn point and assigning the icon?

EDIT: I am using the 2018.2.5f1 Personal version of the editor.

# Answer
As discussed in comments and DMGregory's answer, I think you just need to upgrade Unity.

A few workarounds if you have slow internet or otherwise can't update:

1. If your spawn points are from a prefab, you can simply assign the icon to the prefab and it should show up for all of the prefab instances. If they aren't from a prefab, you might want to consider using prefabs for most things in the future - it can make quick changes to large numbers of objects much easier.
2. If your spawn points are not prefabs, you can assign the icons in bulk using an Editor script. It sounds like you need reflection for this. This answer on Unity's QA site has a solution for setting the icon for a single GameObject (disclaimer: I haven't tried the code). You should be able to adapt it for multiple icons.

```
 private void DrawIcon(GameObject gameObject, int idx)
 {
     var largeIcons = GetTextures("sv_label_", string.Empty, 0, 8);
     var icon = largeIcons[idx];
     var egu = typeof(EditorGUIUtility);
     var flags = BindingFlags.InvokeMethod | BindingFlags.Static | BindingFlags.NonPublic;
     var args = new object[] { gameObject, icon.image };
     var setIcon = egu.GetMethod("SetIconForObject", flags, null, new Type[]{typeof(UnityEngine.Object), typeof(Texture2D)}, null);
     setIcon.Invoke(null, args);
 }
 private GUIContent[] GetTextures(string baseName, string postFix, int startIndex, int count)
 {
     GUIContent[] array = new GUIContent[count];
     for (int i = 0; i < count; i++)
     {
         array[i] = EditorGUIUtility.IconContent(baseName + (startIndex + i) + postFix);
     }
     return array;
 }

```
3. As an alternative to icons, you can use Gizmos. Add this function to your spawnpoint script:

```
void OnDrawGizmos() {
    Gizmos.color = Color.magenta; //you can use any color or a custom color
    float radius = .5f; //change as needed
    Gizmos.DrawSphere(transform.position, radius);
}

```

If you'd prefer to draw something other than a sphere, see the Gizmos documentation.
> 1 votes

# Answer
I'm unable to reproduce this problem in the versions of Unity I've tried (2019 & 2020).

Group-selecting a collection of unrelated game objects and setting their icon in the usual way successfully applied the same icon to all of them.

You may want to check if you can reproduce the problem in a new, empty project. If not, there might be something in your project that's interfering with it. Save a copy of your project and try removing things in stages to see if the problem goes away. That will help narrow down which content might be interfering with it. Your first suspects are any editor scripts or packages that add custom tools or draw custom icons of their own.

If you can reproduce this in an empty project, there might be an issue with your Unity installation. Re-installing or upgrading to a later version might resolve the issue.
> 1 votes

---
Tags: unity
---


title: Texture flipping behaviour

text:
# Question
Title: Texture flipping behaviour
I was having this problem with OpenGL where I'd have all my textures being rendered upside down. I did the most logical thing I could think of and tried reversing the order of the mapping and that fixed the issue. But why? I know that OpenGL's coordinate system is cartesian and that it works by mapping each uv to a specific vertex. I had something like \[0,0\], \[0,1\], \[1,1\], \[1,0\] which would theoretically as far as I understand it go from:

top-left -\> bottom-left -\> bottom-right -\> top-right.

I changed this to: \[1,1\], \[1,0\], \[0,0\], \[0,1\] which would represent:

bottom-right -\> top-right -\> top-left -\> bottom left.

In my understanding it should be quite the opposite. Making a pretty quick sketch on paper it shows me that the initial order would theoretically render my texture correctly and not upside down. Am I correct and theres something else messing with my rendering? Like my perspective matrix?

This is my orthographic matrix:

```
        Matrix4f ortho = new Matrix4f();
        ortho.setIdentity();

        float zNear = 0.01f;
        float zFar = 100f;

        ortho.m00 = 2 / (float) RenderManager.getWindowWidth();
        ortho.m11 = 2 / -(float) RenderManager.getWindowHeight();
        ortho.m22 = -2 / (zFar - zNear);

        return ortho;

```

I can't really say I understand it though, I had quite a hard time with it. And looking through youtube tutorials and articles you can see most people don't really understand it either, they just use it. I do have a good linear algebra background but still can't wrap my head around how is this matrix normalizing my coordinates (screen coords to OpenGL coords (-1,1)). Anyway, I digress, any help is appreciated.

# Answer
In OpenGL, by convention, the bottom-left, not top-left, is the origin (0,0). See also Why is OpenGL point (0,0) not in top-left corner of the screen?
> 2 votes

---
Tags: opengl, textures, projection-matrix
---


# Question
Title: How to make Minesweeper always reveal a large area on first click?
I'm making a Minesweeper app.

I read that if you click mine on the first turn, Windows Minesweeper moves that mine to the top left corner.

It's simple, but I can't find an easy way to always reveal a '0' cell on the first click.

# Answer
> 8 votes
Don't generate your level until the player clicks.

When they do click, mark the 9 tiles at/around their cursor as "reserved". Then place all your mines, re-rolling your mine placement if it tries to place in a reserved cell.

Now you're guaranteed that the site the player clicked contains 0 mines and touches 0 adjacent mines, and for any reasonable map size the generation will be so fast, the player won't be able to tell you did it just-in-time.

You can extend this further, taking a random walk out from the clicked cell to reserve more cells, if you'd like to ensure the player reveals not just a single 0 cell, but a swath of them. Or you could vary the mine spawn probability with a gradient that decreases near the clicked site.

---

Here's an alternative that's a bit cheeky:

Generate your map in advance, and flood-fill the 0 cells, making islands of connected zeros (this is a connected component search). Keep track of the largest such island(s) you find.

When the player clicks, barrel-shift your map data (eg. take a column off the left edge and move it to the right edge, take a row off the top edge and add it to the bottom edge), so that one of the large islands you found moves to include the clicked point. Then re-run your adjacency counter to update the cell numbers.

You'll need to double-check that the move successfully connected the click site to a large island, since it's possible that in the process of the shift, you changed the connectivity of the island (eg. an important connecting tile got pushed off the edge and wrapped around to the other side, breaking the island into smaller pieces) - but you should be able to try a few candidate moves and keep the best one to avoid this pathological case.

Now you ensure the player gets not just one 0, but a nice opening cascade to work with. And it happens in a reasonably organic way. Rather than reserving a "bald spot", you just take advantage of whatever bald spots occurred naturally in the course of the unbiased generation process. This might lead to fewer visible/statistical artifacts that players can exploit beyond the first click.

Note that if your generator routine includes fix-ups for problem cases (like de-clustering mines that would be impossible to deduce), you should run those fix-ups *after* the move, since the relevant adjacency information can change with the wrap-around.

---

A risk to consider here: part of what makes a big opening cascade feel so satisfying is that *it doesn't always happen*. Sometimes you get only a tiny peek into the map, and you have to work carefully to gradually expand it a few cells at a time. So when you do get the big reveal, it's exciting, and you feel like you got lucky and are about to have a great round.

So, weigh whether *always* giving the player a big reveal from the first click is desirable. It might take some of the emotional lows out of the game start, but it can also come at the cost of some of the highs, and that contrast between runs can be the seed for memorable player anecdotes.

---
Tags: algorithm, minesweeper
---


# Question
Title: How does a client thats connecting get all the already connected clients
So I'm currently developing my own protocol on top of the already existing protocol, TCP.

This is what I'm thinking..

When the client connects, it's going to send a packet to the server with the username and password in order for the server to check whether that player exits or not, if it does exist it's going to send back a packet to the client that tried connecting saying "Successful connection". When the client receives this packet it's going to spawn the player into the game world. Once the player has spawned in, it's going to send another packet to the server saying "I'm in" which the server then will interpret as "Okay, a new client has landed in the game world, time to notify all the other already connected clients" so the server sends a packet to all of them in which they can add a new player object to their "internal" list of players.

Here is the issue.. The client that connected has no idea about the already connected clients.. How on earth do I add them to it's internal list of players?

Is this a good structure? What's a good way of notifying the connecting client that there are players already on the server?

# Answer
> 0 votes
As Kevin rightfully noted:

> When the client tells the server "I'm in", have the server send back a list of current clients ("here're clients"). If this makes the packet too large, you can break it into multiple packets.

---

You can also think of this packet to be of the same kind as the one you named *"Okay, a new client has landed in the game world, time to notify all the other already connected clients"*. Make it a "new clients packet". This packet will contain a list of clients. One client when notifying already connected clients about the new client connected. Many clients when server inform newly connected client about already connected clients. This also makes it easy to split large lists into chunks by sending slices of the clients (e.g. 30 per packet).

---
Tags: c#, networking, packet
---


title: Stuttery camera with mouse movement

text:
# Question
Title: Stuttery camera with mouse movement
I'm implementing a framerate independent FPS camera and I'm having a problem with jerky camera. The camera is smooth if I translate it or if I make it rotate at a fixed rate, but as soon as I start to move it with the mouse, it starts stuttering.

This is the part of the code in the main loop that keeps track of the time and calculates the rotation around the y axis:

```
std::chrono::high_resolution_clock::time_point newTime = std::chrono::high_resolution_clock::now();
uint32_t frameTime = static_cast<uint32_t>(std::chrono::duration_cast<std::chrono::microseconds>(newTime - oldTime).count());

oldTime = newTime;

double mouseXInput;
double mouseYInput;

glfwGetCursorPos(window, &mouseXInput, &mouseYInput);
glfwSetCursorPos(window, 0, 0);

float mouseX = static_cast<float>(mouseXInput);
float mouseY = static_cast<float>(mouseYInput);

float rotateSpeedModifier = 0.0000005f;

// Fixed rotation rate
camera.rotation.x += frameTime * 0.0000006f;

// or mouse controled rotation rate (pick just one of the two lines)
camera.rotation.x += frameTime * rotateSpeedModifier * mouseX);

// Overflow and underflow control
if (camera.rotation.x > 2.0f * PI) {
    camera.rotation.x -= 2.0f * PI;
} else if (camera.rotation.x < 0.0f) {
    camera.rotation.x += 2.0f * PI;
}

```

Note that I disabled the cursor and enabled raw mouse motion at the start of the program (it is supported). I also centered it:

```
glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
glfwSetInputMode(window, GLFW_RAW_MOUSE_MOTION, GLFW_TRUE);
glfwSetCursorPos(window, 0, 0);

```

Since the stuttering only appears when I'm moving the mouse, I'm guessing it's some kind of precision problem. Variable frameTime is anywhere between 400 and 5000. I think using milliseconds doesn't give enough precision. Variables mouseX and mouseY are usually within \[-10, 10\] if I'm not too aggressive with the mouse, and they are always a whole number which is odd to me. I don't think casting it to float is the problem then either.

What can I do here to improve mouse tracking precision? Is that even what the problem is? How do I fix this?

# Answer
Rotation should not depend on frame time at all, but only on the mouse delta. If I take out the frame time out of equation, it works as expected.
> 2 votes

---
Tags: c++, mouse, glfw
---


# Question
Title: How to set widget size that is independent of screen resolution/density in kivy
I had coded a simple click game with Python-kivy to android.

You should click dots which are popping out randomly at screen. I set their size 20px to 60px as your level. But it seems when I try on different device screen resolution change the hardness of game. low resolution phones have higher change. I also look at some game (2048 - piano tiles etc) they are also have the same problem.

Should I keep ignore the resolution or try to solve this problem? If so how?

# Answer
> 0 votes
I can't off code itself but i can offer the theory behind it with some pseudo code

First of all some theory: Screens have a resolution this is mesured in pixels so for example, 1920\*1080 on a screen of 10 inches, this is more pixels per inch so 20 pixels on this screen would take up less space then 20 pixels on a 40inch screen, because of this some math before the game starts is needed.

```
int width = getScreenWidth();
int height = getScreenHeight();
int dispWidth = getDeviceWidth();
int dispHeight = getDeviceWidth();
int PPI = caclulate the PPI with algorithm

```

You would then need to change some code to work out the pixels needed to fix say 1/2 inch diameter circle. which would be easy enough.

Another way to do it is looking on the Developer Documentation https://developer.android.com/reference/android/util/DisplayMetrics.html

it lists the size of the screens on different densities and then set variables according to that, It's been a few years since I've done any work with android but i believe you can also set pixel density on a canvas too.

# Answer
> 0 votes
To make sizes independent of screen resolution/pixel density, you need to use kivy.metrics. The dp function gives you a screen independent way to specify distance. The sp function does this as well as scales based on the user font preference. See https://kivy.org/docs/api-kivy.metrics.html for more info. The following should display the same size on different screens:

```
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.uix.button import Button
from kivy.uix.textinput import TextInput
from kivy.metrics import dp, sp

class Test(Widget):
    def __init__(self, **kwargs):
        super(Test, self).__init__(**kwargs)
        wid = Button()
        wid.size = dp(200), dp(50)
        wid.text = "test"
        wid.font_size = sp(20)

        self.add_widget(wid)

class MyApp(App):

    def build(self):
        return Test()

if __name__ == '__main__':
    MyApp().run()

```

# Answer
> 0 votes
To make widget size that is independent to screen resolution you need to know the screen resolution first look at this

```
from kivy.core.window import Window
//import that first

class winApp(App):
 size_x = NumericProperty(0)
 size_y = NumericProperty(0)
 def on_start(self):
     window_sizes=Window.size
     self.size_x , self.size_y = window_sizes
     print(self.size_x, self.size_y)

```

After getting the size of any screen of any device you can do anything Example

```
wid = Button()
    wid.size = self.size_x, self.size_y
    wid.text = "test"
    wid.font_size = sp(20)

```

\`

---
Tags: python, resolution
---


title: Texture uniform does not work

text:
# Question
Title: Texture uniform does not work
So im programming a raytracer at the moment and Im passing a 3d texture from the cpu to the gpu but the gpus texture has not the same values

The uniform part (its made in Unity):

```
RayTracingShader.SetTexture(0, "_VoxelPosTexture", tex);

```

The shader part:

```
Texture3D<float4> _VoxelPosTexture;

float4 color = _VoxelPosTexture.SampleLevel(sampler_VoxelPosTexture, int3(mapPos), 0);

```

# Answer
> 0 votes
Figured it out. I had to use texture.load

---
Tags: unity, shaders, textures, hlsl, raytracing
---


# Question
Title: (Unity) does NativeArray<T0>.Copy, or NativeArray<T0>.CopyTo, allocate any memory?
1. Is there any memory allocation if there are two arrays of the same size and same type? If they are already of the same length, and the values are of struct, when there's the copy, is any more memory used? Like, is it the same as if I did a for loop setting values from one array to the other?
2. Are they the same? https://docs.unity3d.com/ScriptReference/Unity.Collections.NativeArray\_1.CopyTo.html https://docs.unity3d.com/ScriptReference/Unity.Collections.NativeArray\_1.Copy.html

\[What should I write here? Is this enough for a question?\]

# Answer
> 2 votes
```
NativeArray<T>.Copy()
nativeArray.CopyTo()
nativeArray.CopyFrom()

```

Those methods do not allocate memory, that's the point.

> is it the same as if I did a for loop setting values from one array to the other?

This is faster than manual copy operation:

```
// link* credits = https://gist.github.com/LotteMakesStuff/6198f966e414a88d1337b0360cb891f5
using Unity.Collections;
using Unity.Collections.LowLevel.Unsafe;

public unsafe static void MemCpy <SRC,DST> ( NativeArray<SRC> src , DST[] dst )
    where SRC : unmanaged
    where DST : unmanaged
{
    //ASSERTION: sizeof(SRC)<=sizeof(DST)
    fixed( void* arrayPointer = dst )
    {
        UnsafeUtility.MemCpy(
            arrayPointer ,
            NativeArrayUnsafeUtility.GetUnsafeBufferPointerWithoutChecks(src) ,
            src.Length * (long)UnsafeUtility.SizeOf<SRC>()
        );
    }
}
public unsafe static void MemCpy <SRC,DST> ( SRC[] src , NativeArray<DST> dst )
    where SRC : unmanaged
    where DST : unmanaged
{
    //ASSERTION: sizeof(SRC)<=sizeof(DST)
    //ASSERTION: dst.IsCreated==true
    fixed( void* bufferPointer = src )
    {
        UnsafeUtility.MemCpy(
            NativeArrayUnsafeUtility.GetUnsafeBufferPointerWithoutChecks(dst) ,
            bufferPointer ,
            src.Length * (long)UnsafeUtility.SizeOf<SRC>()
        );
    }
}

```

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


# Question
Title: UI Toolkit, Get the topmost Element under the cursor
Basically, I'm making a small node system, Just for fun.

And I need to know if I can get the topmost Element under the cursor. I need it to connect nodes.

Thanks!

# Answer
the answer seems to be IPanel.Pick

```
var picked = rootVisualElement.panel.Pick(evt.mousePosition);

```
> 2 votes

---
Tags: unity
---


# Question
Title: Prefab not working when I import maps form Tiled using Tiled2Unity
I have correctly created the map using Tiled with no errors or warnings, then i imported the package from tiled2unity, imported the map then waited few seconds and the prefab from tiled2unity appears only after some minutes but not working.

the tiled to unity package imported

The error

the map

Basically i dont see the tiled map in unity after it's imported.

# Answer
From the error message, it looks like Tiled2Unity is trying to do something illegal in this version of Unity, and so its operation is aborted.

The website for the tool reads:

> **Warning: Tiled2Unity is old software!**
> Tiled2Unity was created before Unity had support for tiles and tilemaps. It is still available for download but is outdated and unsupported. Consider using SuperTiled2Unity instead. Thanks!

And the SuperTiled2Unity page elaborates:

> SuperTiled2Unity is the second generation of Tiled2Unity, a popular exporter I first released in May of 2014 which is now deprecated.

This means the original version of the tool is no longer supported, and may not perform as desired on more recent Unity versions. I'd recommend using the updated version instead.
> 1 votes

---
Tags: unity, tiled, prefabs, tiled2unity
---


# Question
Title: Can geometry grass shaders be painted to a terrain or are they limited to meshes?
So I was follow the roystan grass shader tutourial and although it works well I don't understand the use for it. From what I understand the shader is basically just a flat plane that calculates grass on top of it. If I wanted to apply this grass to a terrain and place it on uneven ground would I have to manually add in a "grass plane" all over the environment and at different angles or am I missing something? Thanks.

# Answer
The tutorial demonstrates the concept on a flat plane to make it easier to understand. The actual shape of the mesh is arbitrary, so long as it is made of triangles. Each triangle will be broken up into more triangles by the tessellation stage and grass will be created relative to the normal vector of the current triangle. If you fed your terrain mesh into it, it should produce grass blades on it.
> 1 votes

---
Tags: unity, shaders, geometry-shader
---


# Question
Title: Preferred way of calculating run chances in Game of Cricket
For modelling a simple game of cricket, Considering a batsman has a single attribute `rating`. I can go about deciding run chances by weighted probabilities. Something like

```
    if batsman.rating <= 30:
        # map of run: probability
        probabilites = {0: 0.7, 1: 0.1, 2: 0.1, 3:0.5, 4:0.5, 6:0 }
    elif 30 <batsman.rating < 60
        probabilites = {0: 0.7, 1: 0.1, 2: 0.1, 3:0.5, 4:0.5, 6:0 }
    else:
        probabilites = {0: 0.7, 1: 0.1, 2: 0.1, 3:0.5, 4:0.5, 6:0 }

```

Now there are two challenges:

1. What if I want finer control over batsman.rating and probabilities? How do I manage to keep the sum of all probabilities equal to 1?
2. How to manage a second attribute to a batsman, let's say aggression. Which can lower chances of 0 and increase chances of 6?

Initially tried dealing to have finer control like below:

```
# map of batsman.rating: probability,
rating_to_zero_chances = {0: 0.9, 10: 0.7, 30: 0.5, 60: 0.3, 90: 0.1}
rating_to_one_chances = {0: 0.9, 10: 0.7, 30: 0.5, 60: 0.3, 90: 0.1}
chances_of_zero =  <some library>.interpolate(rating_to_zero_chances).yvalue(batsman.rating)
chances_of_one =  <some library>.interpolate(rating_to_one_chances).yvalue(batsman.rating)
.
.
.
#do this for each run

```

The problem with this is that I cannot interpolate the probabilities such that they are equal to 1, Since the slope of runs for the interpolated data are different

For challenge 2, Initially tried handling it by making a probability density function and shifting the `mean` of the curve if the aggression is more. This creates a problem when there is a 3rd or 4th attribute added (such as timing etc are added).

Currently am planning to deal with a single run with its chance, rather than having to sum their probabilities to 1 like below:

```
zero_chance = interpolate(rating_to_zero_chances).yvalue(batsman.rating)
zero_chance += aggression / 100  # assuming aggression on 1-100
is_zero_scored = binom([0,1], p=zero_chance).random()
if is_zero_scored:
    return 0
one_chance = interpolate(rating_to_one_chances).yvalue(batsman.rating)
one_chance += aggression / 90  # assuming aggression on 1-100
is_one_scored = binom([0,1], p=one_chance).random()
if is_one_scored:
   return 1
. # similarly for 2
.
.

```

Is there any neater way to do this? I am new to game development and had learned about probability distributions recently. Are there some theoretical/ practically established concepts I should be looking at? How do game developers handle and balance different chances of an event?

# Answer
> 1 votes
As mentioned in the comments, you can easily normalize a collection of relative weights in an arbitrary range to a set of probabilities summing to 1 as follows:

(Assuming no negative or #NAN weights)

```
float totalWeight

foreach(var item in items)
    totalWeight += item.weight;

foreach(var item in items)
    item.probability = item.weight / totalWeight;

```

Or you can sample from the weights directly, by replacing the division loop with:

```
float sample = random01() * totalWeight;

float accumulatedWeight = items[0].weight;
int selectedIndex = 0;

while(accumulatedWeight < sample) {
    accumulatedWeight += items[++selectedIndex].weight;
}

// selectedIndex now holds the index of your random selection.
return items[selectedIndex];

```

Personally, I like to author all my selection chances as relative weights, and let the computer sort out the mapping to probabilities. That way the tuning data is more robust against errors - I can't break the assumption that all probabilities will sum to 1 by changing one number and forgetting to change the others, because we're not making that assumption. Tuning changes become much easier, and so I get to do more iteration cycles, homing in on the ideal numbers more closely.

So, you could store relative weights for each of your rating tiers, interpolate them just the same as you would interpolate vectors, then use the normalization or sampling strategies above to choose randomly based on those interpolated weights.

If you want to increase the probability of an event with weight `w`, by a ratio of `r`, in the context of other background events with a total weight of `b`, then you can do so by replacing it with a new modified weight `m`, chosen like so:

$$\begin{align} P(m | b) &= r \cdot P(w | b)\\ \frac m {m+b} &= r \cdot \frac w {w+b}\\ mw + mb &= rmw + rwb\\ m (w + b - rw) &= rwb\\ m &= \frac {rwb} {(1 - r) w + b} \end{align}$$

---

Or, I should point out: you could also just stick with hard changes to the probability distributions at particular rating milestones, rather than smoothly blending from one tier to the next. The nature of randomness kind of "fuzzes-out" small incremental changes in probabilities, to the point that players would likely not be able to perceive a difference between being a rating 30 or rating 35. So in the name of simplicity, you could choose to use non-interpolated probabilities, and just space your milestones a little more tightly, so you get distinct, perceptible jumps in performance at key stat values.

---
Tags: game-design, game-mechanics, random, probability
---


# Question
Title: Android Game - Screen Flickers When an Entity Removed From The List
I am using Canvas in my android game. When I remove a no longer displayed entity in my entity list, all other entities are flickering for a brief time. When it's not removed, there is no such problem. But since I am not a big fan of memory leaks, that's not an option.

The canvas rendering system is already double-buffered by design and I have utterly no idea how to fix such a problem. I have thought maybe it is because the list is sorting itself after the item removal and tried changing it to a Set, but that didn't work either.

Does anyone have any idea why this might be happening and how to fix it?

Structure of the code:

```
private val gameObjects: List<GameObject> = mutableListOf()

    fun update(deltaTime: Long)
    {
        gameObjects.forEach {
            it.update(deltaTime)
    }

 fun render(canvas: Canvas)
    {
      gameObjects.forEach {
         when (getVisibilityStatus(it.virtualY))
         {
            VisibilityStatus.VISIBLE -> it.render(canvas, virtualToPhysicalY(it.virtualY))

            VisibilityStatus.BELOW_SCREEN ->
            {
              if (virtualToPhysicalY(it.virtualY) > screenSizePairXY.second)
                gameObjects.remove(it)

            }
         }
    }

```

# Answer
> 1 votes
Apparently removing an item from a list that you are iterating isn't such a good idea. Separating the cleanup/removal process from the render for each loop fixed the issue.

```
      private val gameObjects: List<GameObject> = mutableListOf()
      private val gameObjectsToRemove: List<GameObject> = mutableListOf()

   /**
    * Removes the invisible objects (if any) to save memory
    */
      private fun cleanUp()
        {
            gameObjectsToRemove.forEach {
                gameObjects.remove(it)
            }
            gameObjectsToRemove.clear()
        }

        fun update(deltaTime: Long)
        {
            cleanUp()
            gameObjects.forEach {
                it.update(deltaTime)
        }

     fun render(canvas: Canvas)
        {
          gameObjects.forEach {
             when (getVisibilityStatus(it.virtualY))
             {
                VisibilityStatus.VISIBLE -> it.render(canvas, virtualToPhysicalY(it.virtualY))

                VisibilityStatus.BELOW_SCREEN ->
                {
                  if (virtualToPhysicalY(it.virtualY) > screenSizePairXY.second)
                    gameObjectsToRemove.add(it)

                }
             }
    }

```

---
Tags: java, 2d, android, rendering, kotlin
---


# Question
Title: How do I calculate the bounding box for an ortho matrix for Cascaded shadow mapping?
I've been trying to get a cascaded shadow mapping system implemented on my engine, though it appears to be that the bounding boxes for the cascades aren't correct.

The part I'm interested in can be found here, under the function name "CalcOrthoProjs".

I've been trying to understand the matrix multiplications with this answer, and the ogldev variable and function names are kind of confusing me.

This is how I modified ogldev's function to work with my variables:

```
void Scene::calcOrthoProjections(Camera &camera, glm::mat4 LightView, std::vector<glm::mat4> &orthoContainer, std::vector<GLfloat> &cascadeEnd) {
GLfloat FOV, nearPlane, farPlane, ratio;
camera.getPerspectiveInfo(FOV, nearPlane, farPlane);
ratio = static_cast<GLfloat>(RE::config.height) / static_cast<GLfloat>(RE::config.width);

GLfloat tanHalfHFov = glm::tan(glm::radians(FOV / 2.0f));
GLfloat tanHalfVFov = glm::tan(glm::radians((FOV*ratio) / 2.0));

for (GLuint i = 0; i < NR_CASCADES; i++) {
    GLfloat xn = cascadeEnd[i]     * tanHalfHFov;
    GLfloat xf = cascadeEnd[i + 1] * tanHalfHFov;
    GLfloat yn = cascadeEnd[i]     * tanHalfVFov;
    GLfloat yf = cascadeEnd[i + 1] * tanHalfVFov;

    //The frustum Corners on View(Camera) space
    glm::vec4 frustumCorners[8]{
        //Near Face
        glm::vec4( xn,  yn, cascadeEnd[i], 1.0),
        glm::vec4(-xn,  yn, cascadeEnd[i], 1.0),
        glm::vec4( xn, -yn, cascadeEnd[i], 1.0),
        glm::vec4(-xn, -yn, cascadeEnd[i], 1.0),
        //Far face
        glm::vec4( xf,  yf, cascadeEnd[i + 1], 1.0),
        glm::vec4(-xf,  yf, cascadeEnd[i + 1], 1.0),
        glm::vec4( xf, -yf, cascadeEnd[i + 1], 1.0),
        glm::vec4(-xf, -yf, cascadeEnd[i + 1], 1.0),

    };

    //The frustum Corners in LightSpace
    glm::vec4 frustumCornersL[8];

    GLfloat minX, maxX, minY, maxY, minZ, maxZ;
    minX = minY = minZ = std::numeric_limits<GLfloat>::max();
    maxX = maxY = maxZ = std::numeric_limits<GLfloat>::min();

    glm::mat4 cam = (camera.getProjection() * camera.getView());
    glm::mat4 camInverse = glm::inverse(cam);

    for (GLuint j = 0; j < 8; j++) {
        //View(Camera) space to world space
        glm::vec4 vW = camInverse * frustumCorners[j];
        //world space to light space
        frustumCornersL[j] = LightView * vW;

        minX = min(minX, frustumCornersL[j].x);
        maxX = max(maxX, frustumCornersL[j].x);
        minY = min(minY, frustumCornersL[j].y);
        maxY = max(maxY, frustumCornersL[j].y);
        minZ = min(minZ, frustumCornersL[j].z);
        maxZ = max(maxZ, frustumCornersL[j].z);
    }
    orthoContainer[i] = glm::ortho(minX, maxX, minY, maxY, minZ, maxZ) * LightView;
 }
}

```

LightView represents a matrix created with:

```
glm::LookAt(-glm::normalize(light.direction), glm::vec3(0.0), glm::vec3(0.0, 1.0, 0.0))

```

camera.getProjection() returns the perspective matrix of the main camera

camera.getView() returns a LookAt at the objective the camera is looking at

The orthoContainer values are then fed into the depth rendering unaltered afterwards (by anything other than the model matrix of each model)

I wrote some comments on how I think the math is done, trying to understand what's wrong.

The result is a frustum too wide, resulting on low res shadows(even for the closest shadow map):

and this is the depth map of the closest shadow map:

any insight as to why this isn't working, or any other best practice advice, is welcome.

# Answer
I think the calculation of the frustum corners in ogldev tutorial is a bit confusing and I think I've found some issues with their code:

1. Usually the camera fov specifies the vertical fov (this is also true for their tutorial regarding perspective projection), but as the calculation suggest the fov is assumed to be the horizontal fov. This means that tanHalfVFov should be just the tan and tanHalfHFov should be multiplied by ratio
2. The multiplication by ratio should happen after performing the tan.
3. Since ratio equals height / width, I think you should divide by ratio

To summarize, I think the calculation of tanHalfVFov and tanHalfHFov should be:

```
GLfloat tanHalfHFov = glm::tan(glm::radians(FOV / 2.0f)) / ratio;
GLfloat tanHalfVFov = glm::tan(glm::radians(FOV / 2.0));

```

Also, in your calculation of the world space position of each frustum corner, since the corners are in view space, in order to transform to world space you need to multiply by the inverse view matrix. So cam in your code above should just be the view matrix:

```
glm::mat4 cam = camera.getView();

```
> 0 votes

---
Tags: opengl, c++, shadow-mapping, glm
---


# Question
Title: Get NPC to look at player with only head
I'm wondering how to get an NPC to look at the player, I have tried everything.

Find look at rotation changes depending on character rotation.

Here is a fun drawing if letters are too complicated.

# Answer
> 2 votes
Ok, this works, forward vector from actor rotation.

---
Tags: animation, unreal-4
---


# Question
Title: Issues using NetworkServer.Spawn with Unity and Mirror-Networking
I am using Mirror to handle the networking aspect

When I spawn an object on the network, I Instantiate it on the server and then use NetworkServer.Spawn to notify all clients to spawn the object.

However, when this object is eventually spawned on the client side, it seems to be spawned at the wrong position for a few seconds and then corrected itself and move to the correct position as is reflected by the server. Is there something I am not doing? Is this normal?

Also I noticed if I changed the Network Sync Mode to 0, then it will only spawn in the wrong spot for a split second.

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

public class EnemySpawner : NetworkBehaviour
{
    public uint theId;
    public int maxNumEnemies;
    public int spawnDelay;
    public GameObject enemyToSpawn;
    float curSpawnTime;
    BoxCollider2D boxColl;
    // Start is called before the first frame update
    public override void OnStartServer()
    {
        curSpawnTime = spawnDelay;
        boxColl = GetComponent<BoxCollider2D>();
    }

    void Start()
    {
        if (!isServer) return;
        theId = netId;
    }

    // Update is called once per frame
    void Update()
    {
        if (!isServer) return;
        if (transform.childCount < maxNumEnemies && curSpawnTime <= 0.0f)
        {
            Vector2 spawnPoint = new Vector2(Random.Range(boxColl.bounds.min.x, boxColl.bounds.max.x),Random.Range(boxColl.bounds.min.y, boxColl.bounds.max.y));
            curSpawnTime = spawnDelay;
            SpawnEnemies(spawnPoint,netId);
        } else
        {
            curSpawnTime -= Time.deltaTime;
        }
    }

    [Server]
    void SpawnEnemies(Vector2 spawnPoint, uint theId)
    {
        GameObject gobj = Instantiate(enemyToSpawn, new Vector2(60.7f,1.3f), Quaternion.identity);
        gobj.GetComponent<EnemyController>().parentNetId = netId;
        NetworkServer.Spawn(gobj);
    }
}

```

The way I've organized things, in the hierarchy I have:

```
Enemies
   Area1
      Spider(Clone)
      Spider(Clone)

```

Area1 has the EnemySpawner script. The spider is registered a spawnable prefab. Both Area1 and the Spider have a NetworkIdentity with no boxes checked. Additionally, the Spider has a NetworkTransform and NetworkAnimator.

# Answer
As of what I have experienced before, a lag for like a split second is pretty normal. This is bound to happen if you're trying to run your server on a work desktop or on a local machine. If you wanna spawn stuff really quickly without that displacement in the start, you would need a really good internet and dedicated server, based on how many players you have playing on that server at the moment and the number of objects that you have network transform attached to and want to keep those gameobject positions synced over the server.
> 0 votes

---
Tags: unity, c#, unity-networking, spawning
---


# Question
Title: Getting points inside a circle with a given radius in a 2D array?
Let's say you have a system that removes everything within a square made up of 4 position points. This square is calculated by taking the center point and adding or subtracting the range from this center point seen here:

```
int xmin = x - range;
int ymin = y - range;
int xmax = x + range;
int ymax = y + range;

for (int i = xmin; i <= xmax; i++) {
     for (int j = ymin; j <= ymax; j++) {
          bounds[j, i] = 0;
     }
}

```

How would I change these bounds to be in a circular range instead of a square?

# Answer
> 1 votes
So my solution for this was actually a lot more simple than I thought it would be. Before removing this cell check if this distance between this cell and the circle is less than or equal to the radius of the circle. So before setting the value of the array check the distance:

```
                    if (Vector2.Distance(new Vector2(j, i), originOfCircle) <= radius)
                    {
                        bounds[j, i] = 0;
                    }

```

And it works great!

---
Tags: mathematics, algorithm, geometry
---


# Question
Title: Weird black lines when rendering in my Java Game Engine
I have an issue regarding weird horizontal and vertical lines that occur in my game engine. The lines is in the background color. It occurs when I draw a lot of tiles in this way:

```
for (int y = iy; y < camera.getY() + renderer.getpHeight(); y+= image2.getHeight()) {
    for (int x = ix; x < camera.getX() + renderer.getpWidth(); x+=image2.getWidth()) {
        renderer.drawImage(x, y , image2);
    }
}

```

The lines appear when I move the "camera" around.

The way I am rendering the tiles is not a good way to do it, which I have understood due to the drop in FPS. I am currently thinking on a way to make it more optimized. I don't think that the bad optimization is the reason for the black lines however. Here is a GIF of the phenomenon:

# Answer
The black lines occured due to me not rounding float values properly. In my engine I can only set a pixel on **x** and **y** values that are **integers**. In my case I had a float variable called speed that was added onto the cameras x and y position (which also is of type float).

I solved the issue by rounding the speed and camera variables. This made the black lines / gaps disappear.
> 1 votes

---
Tags: java, rendering
---


# Question
Title: How can I update data saved using PlayerPrefs when there is a new version of my Unity3D game?
I'm using **PlayerPrefs** to store the players' highscore on each level, but in the next version I'll change how scoring works.

* For example, In the old version players could easily reach 250 points on a specific level, while in the new version it's difficult to reach even 50.

I would like to **delete PlayerPrefs data which were saved during earlier versions**, because scores that high would cause some issues in the newer version.

**What is the best way to safely maintain compatibility of saved data between versions, but also be able to reset them if a new update requires it?**

My current solution is that from now on I use new keys to store the data, for example by adding the current version to it.

* For example, in version 2.0 the data that was originally saved with the key *"score-Level8"* would now be saved with *"score-Level8-2.0"*.

This way the player's progression gets *"reset"* after an update, but the old saves remain until another game changer update comes, and I have to increase the version part of the key from *2.0* to *3.0*.

This feels a bit error-prone and unprofessional.

# Answer
> 2 votes
1. Save in your playerprefs the version you are using.
2. Have some migration function in case your current version is higher than the saved version.
3. Always migrate only one version, in case saved version is 1.0 and current game uses 4.0, you should migrate from 1.0 to 2.0 to 3.0 to 4.0 without skipping a version.
4. You can either adjust the score on migrating or just wipe it.

If you change the name of the key, you might run into troubles with backwards availability. Your user might not always use the most current game version and you would have to search/ guess all past naming schema. By keeping the same name and a separate version key, you can handle the loading of keys according to the version.

* You have to keep the loading function of each version you have ever created of your playerprefs for true backwards compatibility.
* You should not override the old data before you successfully migrated to a newer version in case something goes wrong in the middle of converting.
* You should migrate all data at once to not get inconsistent fields between versions. You can migrate the data the first time you need to access it but usually at startup of your application it is a good idea to check if it is up to date.

---
Tags: unity, savegame
---


title: Google Admob GDPR compliance - Unity

text:
# Question
Title: Google Admob GDPR compliance - Unity
I have created a unity game that uses admob to show only rewarded video ads and there are no banner/interstitial ads in my game. Is it mandatory to take user consent (for EU countries) for showing the rewarded ads and if so how do I go about implementing it. I followed some online tutorials to implement admob ads but there was no mention of gdpr in any of those. Can someone please help?

# Answer
> 1 votes
I believe that issue is handled by AdMob itself. When an ad is showing, there's an icon for privacy. Click that, and it takes you to the stuff that makes it GDPR compliant.

---
Tags: unity, admob
---


# Question
Title: How to remove large indentation in TextMeshPro?
When I changed the center text with the size tag, the line height remained the same.

After I used the tag to resize:

How do I remove indentation?

# Answer
> 2 votes
Set line breaks inside tags

```
UPTEXT<size=14>
CENTERTEXT
</size>DOWNTEXT

```

or

```
UPTEXT<size=14>\nCENTERTEXT\n</size>DOWNTEXT

```

---
Tags: unity
---


# Question
Title: How to change the player character size in monogame?
So I made a new project, Loaded up the player sprite(16x16)

but the player is too small(as compared to the level) How should I fix this? Here the code which loads the sprites and the levels(I am using monogame extended)

```
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using MonoGame.Extended;
using MonoGame.Extended.Tiled;
using MonoGame.Extended.Tiled.Renderers;
using MonoGame.Extended.ViewportAdapters;

namespace Dungeon
{
    public class Game1 : Game
    {
        private GraphicsDeviceManager _graphics;
        private SpriteBatch _spriteBatch;
        private TiledMap map;
        private TiledMapRenderer mapRenderer;
        private OrthographicCamera cam;
        private Texture2D player;
        private Vector2 playerPos;
        private InputManager manager;
        public Game1()
        {
            _graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
            IsMouseVisible = true;
        }

        protected override void Initialize()
        {
            // TODO: Add your initialization logic here
            manager = new InputManager();
            playerPos = new Vector2(0,0);
            mapRenderer = new TiledMapRenderer(GraphicsDevice);
            var viewportAdapter = new BoxingViewportAdapter(Window,GraphicsDevice,800,400);
            cam = new OrthographicCamera(viewportAdapter);
            base.Initialize();
        }

        protected override void LoadContent()
        {
            _spriteBatch = new SpriteBatch(GraphicsDevice);
            map = Content.Load<TiledMap>("Dungeon");
            mapRenderer.LoadMap(map);
            player = Content.Load<Texture2D>("player");
            // TODO: use this.Content to load your game content here
        }

        protected override void Update(GameTime gameTime)
        {

            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
                Exit();
            mapRenderer.Update(gameTime);
            // TODO: Add your update logic here

            float move = 2;

                playerPos =manager.moveVertical(playerPos,move);
            playerPos = manager.moveHorizontal(playerPos,move);

            base.Update(gameTime);
        }

        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.Black);
            mapRenderer.Draw();
            var transformMatrix = cam.GetViewMatrix();

            _spriteBatch.Begin(transformMatrix:transformMatrix);
            _spriteBatch.Draw(player,playerPos,Color.White);
            _spriteBatch.End();
            // TODO: Add your drawing code here

            base.Draw(gameTime);
        }
    }
}

```

and the InputManager(You won't need it probably but just in case)

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

public class InputManager
{
    Vector2 position;
    public InputManager()
    {
        position = new Vector2(0,0);
    }

    public Vector2 moveVertical(Vector2 pos,float move)
    {
        var keyboardState = Keyboard.GetState();
        if(keyboardState.IsKeyDown(Keys.D))
        {
            position.X += move;
        }
        if (keyboardState.IsKeyDown(Keys.A))
        {
            position.X -= move;
        }
        return position;
    }
    public Vector2 moveHorizontal(Vector2 pos, float move)
    {
        var keyboardState = Keyboard.GetState();
        if (keyboardState.IsKeyDown(Keys.S))
        {
            position.Y += move;
        }
        if (keyboardState.IsKeyDown(Keys.W))
        {
            position.Y -= move;
        }
        return position;
    }
}

```

# Answer
> 1 votes
Either use a larger sprite, or use a different Spritebatch.draw() overload that allows you to change the sprite's scale.

for example:

```
Vector2 origin = new Vector2(playerPos.x, playerPos.y);
float scale = 1; //1 = default, 2 = twice the size
_spriteBatch.Draw(player,playerPos, null, Color.White, 0, origin, scale, SpriteEffects.None, 0);

```

Personally, I do not recommend sprite scaling through spritebatch, because that can cause the sprite to look blurry. If possible, change the sprite to a larger sprite instead.

---
Tags: monogame
---


title: Component Class / Renderer Class

text:
# Question
Title: Component Class / Renderer Class
I found some code I needed online, but I want to understand how it works.

`Renderer c = (Renderer)b;` What is this `(Renderer)b` action called so I can Google about it?

It looks like it's trying to get a Renderer instance from **b**, but isn't **b** a Component of type Renderer already? Or is this because Renderer is a subclass of Component?

```
void SetTargetInvisible(GameObject Target)
{
    Component[] a = Target.GetComponentsInChildren(typeof(Renderer));
    foreach (Component b in a)
    {
        Renderer c = (Renderer)b;
        c.enabled = false;
    }
}

```

Code is from https://forum.unity.com/threads/how-to-make-all-children-invisible.27259/

Thanks for taking the time!

# Answer
> 4 votes
This is a feature of the C# programming language called an explicit cast.

When you have a reference of a type of a base class or interface, but you are sure that the object it points to is of a certain more specific sub-class, then you can use it to convert that reference to a reference of the more specific class.

In this particular example, a `Renderer` is a sub-class of `Component`. Every `Renderer` is a `Component` but not every `Component` is a `Renderer`. So when you have a reference of type `Component`, then you can only use those methods and properties which all components have in common. The component might actually be a renderer, but the C# compiler can't be 100% sure about that just from this sourcecode. So it won't let you use any methods or properties of that object which are part of the `Renderer` class.

However, in this particular case you as the programmer can be pretty sure that this `Component b` is not any component but a `Renderer`. After all, you acquired it through the method `GetComponentsInChildren(typeof(Renderer))`. So you can actually "promote" that reference from `Component` to `Renderer` by writing `(Renderer)b`. But should you be wrong about that and due to some bug in your code `b` is actually a different component, then this operation will throw an `InvalidCastException` at runtime.

---

But, as Nikaas pointed out, this code example is very outdated. It's from over 10 years ago. In more modern versions of Unity you would use `GetComponentsInChildren<Renderer>()` instead, because that way you get the result set already cast into `Renderer`s and not as `Component`s.

Unity changed a lot in the past couple years. But unfortunately, information from the early years is still abundant around the Internet. So when you want to learn Unity you are well-advised to look at the publication dates of what you are reading/viewing/hearing and take any advise older than a couple years with a grain of salt.

# Answer
> 3 votes
`Renderer` is a subclass of `Component`. So `(Renderer)b` casts current `Component` to `Renderer`.

`GetComponentsInChildren(Type type)` (that returns `Component[]`) was used before its generic counterpart `GetComponentsInChildren<T>()` (that returns `T[]`) was added to Unity.

In today's Unity this code can be simplified to:

```
void SetTargetInvisible(GameObject Target)
{
    Renderer[] renderers = Target.GetComponentsInChildren<Renderer>();
    foreach (Renderer aRenderer in renderers)
    {
        aRenderer.enabled = false;
    }
}

```

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


# Question
Title: Equal 3D icon size visualization in Unity
I have some Icons (Sprite rendered in 3d world) whose icons are equal size (scale 1). Now I am trying to implement a solution that icons visually show at same size. If you see the icon at distance then it looks very small when you near the icon then it look bigger. So I want to visualize them equally.

For this reason, first I got the near scale value which is .5 (suitable) and far scale maybe around 1.5. Now, here is my code but it producing very large scale value.

```
 void Update()
    {
        foreach (var item in iconsObjects)
        {

            float size = Vector3.Distance(activeCamera.position, item.transform.position);
            if (size < 2000)//for optimization purpsose only conside near object under 2000m distance
            {
                float finalSize = Mathf.Clamp(size, 0.5f, 2f);
                item.localScale = new Vector3(finalSize, finalSize, finalSize);
            }

        }
    }

```

I thought Mahtf.Clamp will work within the context but it is not suitable here as it is applying scale 2 to the near objects where it should be around .5.

# Answer
This code tries to scale objects to the visible size they'd have if they were 1 unit away from the camera.

That's awfully close to use as a benchmark size! A sprite that's 1m from your camera would be quite large, so a sprite that's just 1 unit farther away would need to *double* in size to match it.

That means you saturate your upper scaling limit almost immediately, leaving no headroom for the more distant objects.

Instead, you can pick a farther distance to use as your scaling reference point. Something like...

```
// First, only count distance along the camera's axis.
// (This is more uniform across your screen, and cheaper!)
Vector3 fromCamera = item.transform.position - activeCamera.position;

float distance = Vector3.Dot(fromCamera, activeCamera.forward);

// Vary this to set the distance where sprites should have scale 1.
float referenceDistance = 100f;

// Vary this to set the closest objects that should be scaled to match.
// Anything closer will appear larger.
float minDistance = 1.0f;

// Vary this to set the farthest objects that should be scaled to match.
// Anything farther will appear smaller.
float maxDistance = 200f;

float effectiveDistance = Mathf.Clamp(distance, minDistance, maxDistance);

float relativeScale  = effectiveDistance / referenceDistance;

item.transform.localScale = new Vector3(relativeScale, relativeScale, relativeScale);

```
> 1 votes

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