title: Unity2017 WWW Requests fail

text:
# Question
Title: Unity2017 WWW Requests fail
My WWW requests are returning an error that is empty since I switched my project to 2017. Anyone experiencing the same or have a solution?

```
void Start()
  {
    StartCoroutine(RetrieveQuests());
  }

IEnumerator RetrieveQuests() {
  WWW www;
  www = new WWW("URL that I dont want to share here.");
  yield return www;
  if (www.error != null) {
    Debug.Log("There was an error sending request: " + www.error);
  } else {
    Debug.Log(www.text);
  }
}

```

I get the following log when I run it: "There was an error sending request: ", which means www.error is empty but there is an error.

NOTE: This does work on earlier versions of Unity.

# Answer
> 1 votes
It looks like your check for null might be the issue. Consider this sample from the Unity script docs:
https://docs.unity3d.com/ScriptReference/WWW-error.html

```
IEnumerator Start()
{
    WWW www = new WWW(url);
    yield return www;
    if (!string.IsNullOrEmpty(www.error))
        Debug.Log(www.error);
}

```

---
Tags: unity
---


# Question
Title: How to make the whole game wait until some new feature at beginning is finished? In Unity
I have been working on a driving game and its almost finished. I'm just trying to add some polishing touches. Ironically this part im stuck on now would not have been any issue at all in purely code based frameworks i used before (LibGDX/Xna) because I could just make a boolean that's called ReadyToPlay or something and just put that around all the code i want to wait to start.

I've made a secondary camera which rotates around the players car, it works fine but my problem is that the GUI is also already loading AND the race start countdown occurs still whilst the camera is still spinning.

I'm not sure in Unity how to go about stopping that to allow the time for the camera to spin.

One idea I have to fix this (i'm checking first because this doesnt seem right to me) is to use the yield routine in the GUI loading script and tell it exactly how many seconds the camera is going to spin for. I'd rather have just have the camera detected when its done a full spin and then make a boolean true, or trigger another method to start the game properly.

I promise I have done some research trying to find ways but the only thing i can find except yield, is **Monobehaviour.Invoke** but the invoke method still requires me to specify the time.

The whole strategy for yield or invoke feels wrong to me. I guess my main problem is that the code is spread over a few scripts, instead of being funneled thru a main.cs and then gameManager.cs etc etc so theres no way (that I know) to break the chain higher up. I'd have to add bools to each script to say isLuxuryCameraAlive and that still seems wrong to me as I might have 5-10 scripts and have to also section of bits of code in each script.

How would you experienced programmers attack this issue??

Thank you!!

# Answer
> 1 votes
> in purely code based frameworks i used before (LibGDX/Xna) because I could just make a boolean that's called ReadyToPlay or something and just put that around all the code i want to wait to start.

You can still do pretty much the same thing in Unity, but the difference is that elements laid out in the editor already exist (ie. they don't need to be created from code) so you need to hide them first. Just make controller scripts that set gameObject.SetActive(false) in Awake(), then set gameObject.SetActive(true) later.

Exactly how they are triggered later can vary depending on your code architecture, but it sounds like you want a central Controller that hides and shows multiple objects linked to it, and call the one ShowMultiple() method on that controller from the script that spins the camera.

# Answer
> 1 votes
You can create a "global-ish" class with a static member eg: `public static bool IsReadyToPlay()` and another static member to clear/set the boolean variable.

Then check for that function `GameGlobal::IsReadyToPlay()` to return true in the few relevant scripts.

Setting objects active/inactive will show/hide them which is probably not what you want.

Setting individual components to active/inactive can be messy and error-prone.

A static bool variable could do the job too but being able to put a breakpoint or `Debug.Log` in `SetReadyToPlay` is often a time saver when debugging.

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


# Question
Title: How do I triangulate non-planar polygons correctly?
I've got a super simple octagonal mesh with a bevel around the circumference. When I triangulate for export, the cuts form a valley (proper term here?) – which is to say, they transform a level quad into a pair of tris with some degree of concavity.

The resulting normal bake is horrific, as you might expect. Is this a nefarious rookie mistake I've tumbled into?

PS: For reference, here's before:

And here's after:

# Answer
> -1 votes
Oh. I was being unbelievably silly. There was no issue with concavity – my UV shells just needed to be exploded.

---
Tags: normals, 3d-modeling
---


# Question
Title: Simplistic level system (Math reliant question)
So I've been checking some games to get ideas for my own. Some designs I've reviewed rely on a few variables like:

* Current level
* Current exp
* Exp to next level

I aim for a simplistic design where there is only an exp variable.

Example:

> Level 1
>
> Current exp: 0
>
> Exp to next level: 100
>
> Level 2
>
> Current exp: 100
>
> Exp to next level: 200
>
> Level 3
>
> Current exp: 200
>
> Exp to next level: 400
>
> Level 4
>
> Current exp: 400
>
> Exp to next level: 800

Every level, the exp required for next level doubles.

That's okay. Since I use only an exp variable, I need two formulas:

1. Formula to calculate the current level
2. Formula to calculate the exp required for next level

My progress so far:

> Level = floor((exp + 100)/100)

This works for 0 exp (level 1) because floor(0 + 100)/100 equals 1, with 50 exp works fine too:

50 + 100 = 150 150/100 1.5 flooring 1,5 gets us to 1

If we hit 100 exp, we should be now at level 2.

floor((100+100)/100) = 2

Let's see level three.

floor((100 + **200**)/100) = 3

Since level 3 is at least **200** exp, this thing keeps working.

Level 4 begins with 400 exp.

Let's see what happens if we have 399 exp. 399 + 100 499/100 = 4.9 floor(4.9) 4

No way. 399 should still be level 3.

So let's take into account the doubling factor.

Level = floor((exp + 100)/100)**/2**

399 + 100 = 499... / 100 = 4.99 .. floored -\> 4 / 2 = 2

Level 2? No way , it should be level 3

Another try:

Level = floor((exp/100))

floor(399/100) = 3 floor(400/100) = 4

But if we apply the formula to level 2(starting at 100, ending at 200 which would be level 3)

floor(100/100) = 1

I can't seem to achieve this on my own. Any suggestions?

# Answer
> 2 votes
Because your EXP amount is doubling, simple division isn't enough. You have exponents, and you need to use their inverse, the logarithm function.

# Calculating the Amount Needed for the Next Level

If you're on level `n`, the amount of experience points to get to level `n+1` is `100 * 2^(n-1)`. (eg. if `n` is 1, you get 100; if `n` is 3, you get 400.)

If the notation isn't familiar to you, `2^(n-1)` means "two to the power of (n minus one)." And of course, `2^0 = 1`.

# Calculating the Current Level

If you invert the formula and solve for `n` instead of solving for `exp`, you get:

```
1 + log(exp/100) / log(2)

or

        log(exp/100)
   1 +  ------------
        log(2)

```

`exp` is the current number of experience points; `log` is the logarithm function.

If I plug in in 376 for `exp`, I get a value of `2.91`. Rounding down, the player is on level 2, which is correct.

---
Tags: mathematics
---


title: Shadow casting in 2D OpenGL

text:
# Question
Title: Shadow casting in 2D OpenGL
I´ve read several articles, tutorials about shadow casting and I think that I understand the way how it works. However I miss some of the steps. Here is included my order list:

1. Fill framebuffer with ambient light
2. Render light textures to the framebuffer(adding proper blending)

**3. Lights have vector of shadow casters(convex polygons) and check if they touch them(by checking the distance) and if yes, I do proper math calculation to project the polygon to the right "transformation". Then I draw them as black polygons to the framebuffer**

4.At the end I use this framebuffers texture and blend it with actual game textures to "do lighting (with shadows)".

As you can see I bolded the step 3 because thats where I´m lost. The first thing, how do I project the polygon? (for these polygons I have a vector of points, also a vector of edges). The second thing, is it efficient to do it this way? I mean to iterate through the possible shadow casters for each light.

Thanks for your help.

# Answer
For your last question, yes, you have to iterate through every caster, in same cases even multiple times. I've just made a simple game based on shadow and light ( https://youtu.be/fNp7GeHxInI ). Of course it depends on your game, but I think that with 2d games it's better to draw the light, not the shadow (in this way you can blend together different lights, if you render the shadows you can't in a easy way: when you draw a shadow you can't light that area anymore now that's black (there are of course tricks to avoid this problem)). In my game I use a lot of shadow casters so, if I projected shadows a lot of them would overlapped and that's not very efficient since you're GPU has to redraw the same pixels different times. Anyway to project shadows you need the light vectors that goes to the center of your point light to each vertex of each caster, then you lengthen them till the end of your "light box" (the square which contains the light texture) or to a fixed value based on the height of the caster if the light is in an higher position. Now you have the vertices you need to draw the shadow: the polygon vertices and the end of each light vector. You draw the light and then its shadows. That's has a complexity of O(n\*k) where n are the lights and k the casters.

If you wanna render lights the algorithm it's more difficult, basically you take the light center and the polygons' vertices to draw the light triangles, but you have to calculate which is the nearest wall (the one to be enlightened). That's has a complexity of O(n*k²) but I think you can optimize it to something like O(n*log(k)). This way reduces the calculations done by the GPU (you only render the light pixels once and you don't even render the shadowed areas, before you render both and the shadows even multiple times), remember that the casters in a scene would be at most an hundred or similar while the pixel of a monitor are millions, so k² (the worst case) in this scenario is better than k if you will draw a lot less pixels.

For any question ask in comments. I've not been so specific because there are already a lot of tutorials online. (I can link them if you need).
> 2 votes

---
Tags: opengl, 2d, mathematics, lighting, shadows
---


# Question
Title: Art Style Guide - External Image Sources?
I've been looking into how to structure an art style guide (ASG); it's a document which helps guide artists how a project's visuals should look. They often have sketches and illustrations from artists working on the project, though I am unsure about using external images.

I am working on a commercial videogame project and I have been writing both a game design document (GDD) and currently an art style guide. **Is it legal for me to add artwork I came across while browsing the internet into the ASG?** I know that most artists can add external images outside of their project into a section talking about inspirations, but could this be done for areas that loosely talk about, say, an overall aesthetic of something, such as creature or environment design?

For example, say I have a section which talks about the design of fantasy monsters in a chapter about characters. Would it be legally viable to use various images I come across to help show artists what I'm looking for in each creature? I'm guessing that it is legally viable because I don't think I'd be profiting off of an ASG. I hope somebody could verify this for me; I don't want to cause any trouble.

I apologize for making this a bit wordy; I wish I knew how to articulate myself better.

# Answer
> 1 votes
Legal questions are best asked to legal professionals for the jurisdiction you are working in. Do not rely on anything random strangers on the internet tell you. I am not a lawyer and I can not give you any reliable legal advise.

But personally I would not be afraid of this, because your art style guide is an internal document which should usually not leave your development team. That means there is no distribution of copyrighted material. But you should make your artists aware that you don't own the copyright for these example pictures. That means they should not follow them too closely to avoid plagiarism claims from the original creators. That, in turn, makes them less helpful for your artists.

I would recommend you to use such example pictures just as a rough guide for the general direction you want to go for. Then design the actual look for your project together with your artists by creating original artwork. This process doesn't just create "copyright clean" concept art but also grants your artists more creative input which will be motivating for them.

---
Tags: legal, art, documentation, design-document
---


# Question
Title: Civilization 6 add City States in World Builder
There are instructions to access the Civ 6 Worldbuilder in civfanatics forums.

The TZ mod method allows starting with a custom map, but there are no generated city states.

How can I add city states to the map / mod so the game does not crash on the first turn?

# Answer
> 1 votes
## Meeting the original criteria: no crash

It seems the city state must be **random**. Specific city states seem to crash.

Step by step:

1. Add CS starting position (random) on map.
2. Go to top left corner "Player Editor".
3. Set civilization level to `CIVILIZATION_LEVEL_CITY_STATE`
4. Leave selected cilization at `Random`.

However the map editor only allows adding up to 10 players.

## More City States

A good way of getting past the limit is installing sqlitebrowser and using that to edit the map file. Change the last players to `CIVILIZATION_LEVEL_CITY_STATE` and you will get more city states on the map. :)

---
Tags: civilization-modding
---


# Question
Title: Understanding a client/server relationship
I'm currently designing a simple game in C# and want to implement online multiplayer support. Before venturing onto doing something like this, I just had a few questions about clients and servers.

* Is a server responsible for sending and receiving data to and from clients?
* If a client wants to send data to another client, should it send the data to the server, and let the server send that data to the specified client?
* When it comes to handling data, should the server have access the same classes the client does? This way the server can convert the bytes sent in, to a specific class? Or should the server just handle all the data in bytes, and send it back out if necessary?

Sorry if there are to many questions, any help would be appreciated!

# Answer
> 0 votes
If you're thinking something that will have one global league, like pokemon go, league of legends - things where scores area compared - then you need the communications to go client-server only.

There are a bunch of ways this will make it easier, but among them are that your clients can know the address of the server, and with peer to peer it would be virtually impossible to prevent cheating.

If you're thinking of a LAN game sort of thing where a bunch of people set up a game together, play for a bit and close it down, then you could do peer to peer. This introduces a few problems, the body being network related: discovering the other clients and routing. Often discovery is done using UDP and this doesn't cross network boundaries well.

I'd use the minecraft model myself. (Pretty sure the original Doom did similar back in the day). Basically one machine gets dubbed the server and coordinates objects - location, velocity, creation destruction motivation inventory.

When a client joins they need the address of the server. Minecraft makes it easy for the user to set up a LAN game by telling the person on the server the address to use.

In terms of responsibility, I'd say it goes both ways, but you don't have to agree. Depending on your protocol, some things will be easier to implement.

If you can have open sockets/long connections then both ways will be really efficient. Client tells server when an event happens - a purchase, a death, initiating a ballistic path. Server then tells all of the clients who then update their local data.

You'd probably want to chase this option if you're doing real time action.

It might be simpler though to have your clients polling the server for state change. Your comms code might be simpler but you'd have to think real hard about minimizing the amount of data you transmit.

For same / different classes - it depends. I'd start with the same. At some stage you'll find data that is only needed by the server or the client and you'll have to decide whether to have it on both anyway (which would make switching a local game to multiplayer and back easier ) or separate them (which gives you more code to manage but may improve security). I'd leave that decision as late as possible.

# Answer
> 1 votes
The answer to all of these questions is "It depends".

1.) and 2.): There are two types of networking, one is a traditional one, it only has 1 server and every client is connected to this. The data always goes through the server. This is generally considered as the safer method.

The other method is called peer-to-peer (or P2P) networking. It doesn't have a main server, every client (peer) sends data to the other clients directly. This can be much faster than the first method if the peers live close to each other. It's less safe than the normal method, because the users can modify the data they send. You'd usually implement this with UDP, because with TCP you'd need a separate server and client socket for each peer and you need to store the IPs.

3.) Sometimes the client and server even share most data classes, but you generally want to avoid sending anything other than the input from the client to the server to avoid cheating.

---
Tags: c#, multiplayer, client-server, server, client
---


# Question
Title: How to stitch terrains together in Unity
I'm building a world that consists of multiple terrains and I was wondering, how do I go about stitching them together so that features of my map will "fit" together? I know Unity has the `SetNeighbors()` method, but it appears as though that simply tells each terrain which terrain is next to the other. What I'm trying to accomplish is having multiple terrains and being able to have something like a mountain range move from one terrain to another and make it appear as though it's all one terrain.

# Answer
> 2 votes
This may be what your looking for https://www.youtube.com/watch?v=v8YAyGPhYpw video explains a way of doing this I think. What I think you will need to do is export your terrains into highmaps and then edit them and re put them back in.

---
Tags: unity, terrain
---


# Question
Title: Correctly map a Mount&Blade style aiming rectangle to the projectiles flying direction?
So I implemented a game mechanic where drawing a bow will display a shrinking rectangle that should represent the shooting accuracy. The rectangle is smallest after about 1.5 seconds of drawing the bow.

Now the question is, how do i correctly map the size of the rectangle to the projectiles flying direction?

My first though is to give the projectile a random angle deviation and the aiming rectangle is the max angle deviation, but I guess I somehow have to take the FoV angle into consideration somehow? Furthermore, is the FoV Angle uniformly distributed across a 2D screen or is the change of angle greater at the edges of the screen?

With a uniform distribution I guess it comes down to a very simple calulation.

* FoV = 70°
* Max Yaw and Pitch deviation at 1.5 seconds = 10°
* Screen resolution: 1920x1680

Size of aiming rectangle:

* width: 10/70 * 1920 ~= 274 pixels
* height: 1680/1920 * 274 ~= 239pixels

Is that correct?

For clarity here is a screenshot of that aiming rectangle that shrinks over time: https://www.vintagestory.at/uploads/monthly\_2017\_07/2017-07-22\_22-48-10.png.86e757f209fde73b769726e7c12aaeb1.png

# Answer
I would suggest to think of this square more like a fictive crosshair, like on a rifle, that hovers in front of the view. Let's assume, your square is 10 meters infront of the character and it's there about 1m x 1m when zoomed in, then you can create 3 vectors to calculate your next shooting vector.

q1 to one of the side edges, q2 to a topside edge and t to the center of this square. Now everything you shoot, calculate q1 and q2 in addition to t. Then calculate the arrows flying vector a, like this for example:

```
x*q1 + y*q2 + t = A

```

While x and y are random numbers between -1 and 1. You may want to have a function that is more biased to t, so less deviation.

I have two reasons not two fiddle with the pixels

1. As your other question suggests, if you want the FoV adjustable, things like the gui should scale with that, while the crosshair is gameplay related and should only get thicker for visual purpose.
2. With the vector approach you can project the square on solid walls, so the square gets sheered to reflect w possible angled shooting vector.

And the thing with angles is, that calculating cos, sin and their respective inverts is, that they demand a lot of time. Doing this every frame could be a problem. Alternatively you can set the width and height of the square to reflect the angle, so for my 10m example that would be `sin(10 Degree) * 10m ~ 1.73 m`. Double that for the width of the square.

To the FoV question, it should be stretched equally across the screen, although it can be done otherwise, I have no idea what it would do as a factor for motion sickness.
> 0 votes

---
Tags: mathematics
---


# Question
Title: Sending a Tilemap Layer over a socket connection (GMS2/GML)
I'm working on a multiplayer game in GameMaker Studio 2 using sockets and built-in networking functions. I have a server that can receive and send messages to and from clients.

What I'm trying to do is take the map data (on the server) and send it to the clients, so that I can create a map on the server and have it automatically sent to clients upon entering the game. This map will be a Tilemap Layer.

Does anyone have any ides on how to serialize a GameMaker Studio 2 Tilemap to a data type that can be sent over sockets?

# Answer
As far as I know, there is no easy way to send the entire GM:S' tilemap over the Internet, but what you can do is transform your map into json\xml\etc and send it as one file. On the client side you can now parse the structure and build tiles on the run, andding them with code in previously created empty room.
> 1 votes

---
Tags: networking, game-maker, client-server
---


title: Collision/Trigger with Particle System

text:
# Question
Title: Collision/Trigger with Particle System
I have a fire particle system in my game. I want to over the game when player collides/triggers with that particle system. As I've researched for this on google, I came to know that I can use World Particle Collision component for that. By sending Collision message on colliding, collision can be detected. I've put following snippet in player's script to detect particle collision.

```
void OnParticleCollision(GameObject TargetedParticle)
{
    Debug.Log ("Collided with particle");
}

```

Am I doing this in a right way? Because This code is not enable to detect collision. Help me please.

# Answer
> 1 votes
The player object should have a rigidbody collider. Enable the 'box collider'.

The 'Send Collision Message' should also be enabled in the particle system dropdown(under the collision tab).

---
Tags: unity, particles
---


# Question
Title: Authoritative server controlling objects in multiple scenes in Unity3D
I am working on a multiplayer project that involves loading into different scenes and playing some kind of mini-game with any other players that happen to be in the scene at that time. These mini-games will contain AI that needs to be controlled by a dedicated server. Additionally, there is simulation that needs to happen in these scenes, even if no player is currently in one.

My first idea to take a crack at this was to have my server on startup, load all of the scenes in the game using `LoadSceneMode.Additive` This way, on the server side, each scene would be in one place and available to be simulated.

I made a little sample project with three scenes, a base world, and two other worlds. When the server is started from the Base World scene, it loads World1 and World2 into its scene. From my server, I could spawn a cube in World1 by pressing the 1 key, and I could spawn a cube in World2 by pressing the 2 key.

I used the following code to spawn the cube:

```
    GameObject cube = (GameObject)Instantiate(myPrefab, new Vector3(0, 10, 0), Quaternion.identity);
    NetworkServer.Spawn(cube);

```

The problem is, if a cube is spawned in World1, clients in World2 still spawn the cube. In hindsight this makes sense because the documentation for `NetworkServer.Spawn` states

> Spawn the given game object on all clients which are ready.

My next idea was that I could designate one player in the minigame as a psuedo "host" and his machine would be responsible for running the AI. However, with this method, I really cant simulate things going on when nobody is in the scene.

Is there a better way I should go about solving this problem? How can I create a dedicated server which can simulate multiple scenes at once? Should each scene be handled by its own server? Am I better off just trying to run everything in one scene?

# Answer
> 0 votes
Unity's built in networking honestly isn't meant for this type of stuff, its meant for for stuff like RedAlert, StarCraft, can't remember some of the others that use the peer to peer system but you should get the point with those 2. its more of a peer to peer system although unity *can* run an authorative server but really only 1 scene at a time. I would suggest looking into Photon Server for this. if you get the on premise version instead of the cloud version you can run your own server/servers with authorative logic and even connect them together in a cluster with a master relay server and then run the scenes that way, although you need something like bullet physics to control the objects server side because it doesn't load the actual unity scene but a serialized export of the scene geometry. Photon can even handle a mmo type of game and they have a small example of it using the old Unity Island Demo scene.

Photon servers are also coded in C# as a class library(dll) that the main system loads. Its a pretty nice system.

Just an idea of something to look into for you.

---
Tags: unity, networking, server, client
---


title: Weird Animation Behavior in Unity

text:
# Question
Title: Weird Animation Behavior in Unity
I discovered a weird animation bug and have no idea how to solve it. Below you find the script I attached to my humanoid character.

```
using UnityEngine;
using UnityEngine.AI;

public class PlayerCharacter : MonoBehaviour {

    private Animator anim;
    private NavMeshAgent agent;

    private bool dead = false;

    void Awake()
    {
        this.anim = GetComponent<Animator>();
        this.agent = GetComponent<NavMeshAgent>();
    }

    public void Kill()
    {
        this.dead = true;
        this.anim.SetBool("Dead", true);
    }

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.X))
        {
            Kill();
        }
    }

    public bool IsDead()
    {
        return this.dead;
    }
}

```

My character makes use of the NavMeshAgent and can walk around and idle - everything works fine. But if I want to kill the player the dead animation loops continuously. This also happens if I change the death animation.

This is my AnimationController:

As you can see, the transition has the condition "Death" with is set to true in the Kill() method. The code for walking and idling in combination with the NavMeshAgent is similar, but the script shown above doesn't work as expected and I have no clue why the animation starts to loop continuously (which looks a bit funny btw). Additionally the animation is **not** played to end, it restarts after a few frames.

Any ideas? I could also post a video of the behavior if it would help. Thanks in advance! :)

# Answer
you didn't specify which unity version but I'll assume since this is only 16 hours old its at least 5.6. I believe your having the same issue I did and it would be related to the fact your death state is linked to the any and not the other 2. I had a similar issue with an animation not playing right and I had to create some extra transitions. also make sure your other 2 don't have exit times that tends to wack out the animations but what I would try and it may or may not work is create transitions from walkFWD to the death and then also make transitions from the Idle to the death. I have found sometimes unity when jumping from a state to another state without a direct transition in the newer mechanim (I'm assuming your using mechanim) does some wierd things.
> 1 votes

# Answer
Select the `Unarmed-Death1` state, and if you double-click on the animation (motion) in it, you should see a Loop Time option. Just uncheck that and it should stop looping.
> 0 votes

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


# Question
Title: LibGDX: TextureRegion renders correctly, but .getTexture() doesn't
I have a TextureRegion that I get from an atlas map (which in turn I get from the Asset Manager), eg

```
AssetManager am = myGame.getAssetManager();
TextureAtlas atlas = am.get("my.atlas", TextureAtlas.class);
TextureRegion object = atlas.findRegion("myobject");

```

Now when I draw the object with

```
batch.draw(object, ...);

```

the object is drawn correctly, but if I do

```
batch.draw(object.getTexture(), ...);

```

it is drawn as garbage. Is this expected? I thought it should work the same.

# Answer
> 1 votes
Ok, problem solved. Trying with bigger objects from the same texture atlas, I see that getTexture() actually returns the whole atlas image, and this is by design, see eg this question

---
Tags: libgdx, textures, texture-atlas
---


# Question
Title: Network latency compensation problem for laggy players with collision
Say there are two clients connected to an authoritative game server, using input + state synchronization strategy. Client 1’s has a round-trip latency of 100ms and client 2 with 400ms latency. For now just imagine each player controls a ball that can collide and bounch off each other.

1. Client 1 executes command at t = 100 ms, proceeds with prediction for next 100ms (however many steps depending on timestep and framerate)
2. Client 2 also executes command at t = 100ms, proceeds with prediction for the next 400ms (or capped at some max prediction timestep)
3. Server receives client 1’s commands for the next t = 100ms + dt, simulates up to t = 100ms + dt
4. Say server’s simulation is now at t = 500ms, and client 2’s command for t = 100ms just arrived. In this case I can think of two things to do:

a. Rewind simulation back t = 100ms and re-simulate back to t = 500ms, if client 1 was affected by client 2’s command (such as collision) send correction to client 1. The results are that:

* To client 2, everything looks fine
    * To client 1, his movement constantly rewinds bottlenecked by client 2 as long as client 2 is affecting client 1

b. Simulate client 2’s command as if it was executed at t = 500

* To client 1, everything looks fine
    * To client 2, his motion is constantly corrected (either jerky or the interpolation creates strange movements)

With this method you can really only have smooth gameplay for one person. Are there better methods for smoothing out the gameplay for all players? I understand that for FPS you can easily compensate for the the bullet latency because you don't actually see the bullet. But in the case where physics collision can occur between players this becomes troublesome.

Another idea that I have is spawning of a lava pit that is instant death for players. Lava pit spawning done using client side predication can instant kill the player and sync the state later, resulting in smooth gameplay for the client. But if the other player is lagging it will appear as if he is still standing in the pit (or with full prediction will kill him but he’s not actually dead). How do games handle cases like this?

# Answer
> 2 votes
After much research and readings I think I can answer my own question.

This is not really a solvable problem. All clients are seeing other client’s commands x time from the past, and there are no solutions to synchronize real time behavior if one client intends to directly affect another player without corrections. The best thing you can do is do your best to apply corrections as smoothly as possible so the gameplay still feels responsive. In addition do your best to mitigate the network latency through proper matchmaking and latency/network congestion optimizations.

If you require your simulation to be consistent across all clients, then clients cannot execute a command until server has authorized the command. This means that server has to receive commands from all clients for a certain time/tick before the simulation can proceed. This ensures correct and smooth simulation for all clients but bottlenecked by the slowest client. In RTS games like Starcraft all commands have input latency of about 200ms, so if the network latency is less than that you can effectively hide network latency and produce more or less accurate simulation for all players.

200ms lag in RTS games seems to be acceptable by players but not for FPS games which inputs needs instantaneous responses. And this is done through client side prediction. If player 1 shoots player 2, from player 1’s perspective he is actually aiming at the target sometime from the past. The server rewinds the simulation based on client predictions checks for hits. This kind of lag hiding is acceptable because you don’t actually see the bullet. For weapons where you actually see the ammo, like rockets/grenades/flamethrower they are not lag compensated and require server authorization before they can execute on the client. However the perceived lag affect can often be hidden through animation. For example, client side shows a grenade throw motion when a button is pressed, but grenade actually disappears and reappears when the server responds with grenade’s location. The throwing motion itself is enough to hide the appear/disappear latency.

So in conclusion to address this problem you have to decide what’s more important in your game when compensating for lag: accurate simulation for all clients but induce lag for all clients, or try and hide lag through client side predictions and do your best to hide corrections. If your game requires aggressive physics interaction between players then then this is a really hard problem to try and hide the latency.

If anyone has a better answer or known good models please let me know! Thanks!

# Answer
> 0 votes
We had the same problem in our game.

Finally we decided we don't use any client side prediction, but we tried to minimize latency as low as possible.

Now if I play on a server on same continent, ping is about 30 ms, then the feeling is responsive enough.

---
Tags: client-server, latency
---


title: Alternative to canvases (unity)?

text:
# Question
Title: Alternative to canvases (unity)?
I have a Unity project which requires a bunch of Canvases and, surprise surprise, they're creating a lot of lag. I've already turned off the graphics raycaster for every single one, but they still drop so many frames.

Are there any good alternatives to draw text in the worldspace that are a lot more efficient? (I'm targeting mobile, so this is important).

# Answer
Although I don't have experience with third-party alternatives, if you're experiencing performance issues with canvases there are a couple things you might want to try before deciding on switching to a different UI system:

* Canvases generate meshes that are recalculated whenever an item within the canvas changes. This can cause performance issues if it's occurring every frame. **Try to separate the dynamic elements that will change every frame into their own canvas (or separate ones) so that they won't dirty the canvases with static objects.**
* **If you're using a World Space Canvas, be sure to set it's Event Camera.** If you leave it blank, it will try to get the default camera by calling Camera.main every frame, which searches your scene for the Camera with the "MainCamera" tag. This can cause performance issues in scenes with large tagged objects or mobile.
* Particularly on mobile, rendering images with lots of transparent pixels can cause a performance hit.
* In some cases, having "Pixel Perfect" checked can cause performance issues.
* If your issue is with text rendering with a custom font, ensure that the font size isn't set too high. The font texture that Unity generates may be an unnecessarily high resolution.

If you're still having issues, you can use Unity's profiler to find out what exactly is taking too much time.
> 2 votes

# Answer
One alternative would be to use text meshes. These are texts which are rendered to 3d objects which can then be placed in world space.

The technical implementation of a text mesh is just a quad with a texture which is generated at runtime when the text-string is set. So the resource cost for a text mesh is just two polygons and one texture.
> 0 votes

# Answer
you could also just use a GUIText component its still there just a little hidden in newer versions of unity, just create an empty gameobject in your hierarchy then click the add component button in the inspector go to rendering and choose GUIText. I use them all the time for things like npc or player name banners as they can be rotated to always face the camera and such, and I've not ever seen any performance hit in using them. and to clarify a GUIText is similar to a Text Mesh in its options, but not the same thing. a GUIText does not use a mesh renderer its rendered differently and I have found in my experience its less of a performance hit.
> 0 votes

---
Tags: unity, text, lag
---


# Question
Title: Entity component system design. Should ID of entities be continuous?
I am implementing an entity-component system. Below is my current implementation in c++.

```
using ID = std::uint32_t;

class Entity {
public:
    Entity(ID index): index_{index} {
    }

    ID index() const;

private:
    const ID index_;
};

ID Entity::index() const
{
    return index_;
}

class Entity_factory {
public:
    Entity generate();

    void destory(ID id);
private:
    ID count_ = 0;
    std::unordered_set<ID> idle_IDs_;
};

Entity Entity_factory::generate()
{
    if (!idle_IDs_.empty()) {
        const ID id = *idle_IDs_.begin();
        idle_IDs_.erase(idle_IDs_.begin());
        return Entity {id};
    }

    assert(count_ != std::numeric_limits<ID>::max());
    return Entity {count_++};
}

void Entity_factory::destory(ID id)
{
    assert (id < count_);
    idle_IDs_.insert(id);
}

```

Note I use a hash table to keep track of all "destroyed" ID so I can use it again. This way, all the entity index will be as continuous as possible, so I can store components in a pool and refer them through index without wasting much memory. Another choice I can think is at component pools create a separated "index" array to keep track of entity and store all entity continuous. Which why do you prefer? Or do you have a better solution to this problem?

# Answer
> 2 votes
The concern that @philipp mentioned can be eliminated with a bit of fancy bit manipulation.

Rather than treat your Entity's ID as a single 32-bit value, split that value into two parts, one which represents the index slot in your array and another that represents an ever increasing, potentially rolling over version value.

```
struct EntityID
{
  uint32_t index   : 24;
  uint32_t version : 8;
};

```

In this use case, you can have approximately 16.7 million different entities in your pool. Each entity will be assigned 255 different version values before they roll over, skipping 0 as a sentinel value.

So you end up with an array of `EntityID` indexed based `index`. So when you want to lookup an entity, you simply go to that index, compare the version values between the stored reference and the value in the array and if they match, the index is still valid. If they differ, the reference is stale and you can thus assume that entity has since been destroyed and react accordingly.

My personal choice is to use this approach mainly for cataloging entity ids and validating whether they're still valid at runtime and then store the components in their own separate pools per type.

For this to work, my component pool relies on two arrays to manage its memory. The first array is a simple sparsely populating array where the index from the entity ID holds the offset index in the second array that is maintained as a densely populated array of component types.

The benefit here is during processing of components, I can simply iterate the second array and avoid any lookup performance bottlenecks. Worse case scenario, I take several constant time lookup hits when I fetch a component by entity id which seems reasonable.

```
template<typename T> T** GetComponents() const {
  return componentPool;
}

template<typename t> T* GetComponent(const EntityId& entityId)
{
  if ( IsEntityIdValid( entityId ) )
  {
    uint32_t index = componentEntityArray[ entityId.index ];
    return &componentPool[ index ];
  }
  else
    return nullptr;
}

bool IsEntityIdValid(const EntityId& entityId) const
{
  if ( entityId.index < 0 || entityId.index >= MAX_ENTITIES )
    return false;

  return entityIdArray[ entityId.index ].version == entityId.version;
}

void DestroyEntity(EntityId entityId) {
  if ( entityId.index >= 0 && entityId.index < MAX_ENTITIES )
  {
    entityIdArray[ entityId.index ].version++;
    entityIdFreeListQueue.add( entityId.index );
  }
}

```

The other benefit is that now your `entityIdArray` is also a sparse array but contiguous. The lookup is constant time either way, so that should not impact performance, if at all.

I would suggest however to make the queue use a first-in, first-out strategy. This avoids the concern with version numbers being incremented too high for a single slot, except in situations where you create and destroy a single entity repeatedly in a row.

# Answer
> 0 votes
I would recommend you to always assign a fresh ID to a new entity. Very strange bugs can happen if you try to refer to an entity by ID, but that entity got destroyed and replaced by something completely different in the meantime.

If you want to use object pooling (which usually makes most sense for objects with a large memory footprint and little dynamic allocation), keep separate indexes which are only relevant for the pool itself.

---
Tags: architecture, entity-system, entity-component
---


# Question
Title: Unity text component not updating text properly
It was worked fine previously, but after some point, it's not working.

This is the code. It's not a pseudo code, actual code in game:

```
public Text healthText;

void Start() {
    healthText = GameObject.Find("UI/InGameUI/CharacterStatus/HealthText").GetComponent<Text>();
    }

void Update() {
    if(healthText) {
        print(health);
        // healthText.text = Time.deltaTime.ToString();
        healthText.text = "HP: " + health.ToString();
        // healthText.text = "HP: " + health;
    }
}

```

variable "health" is float value. I just want to print it to the screen, but it's always prints "Health: 100" even it changes.

So I printed the value to the console, but it prints well in the console and only text components was not printed properly.

So I printed Time.deltaTime instead of the health and it works!

Seriously, what the hell is happening? Is this a bug? If health variable wasn't changed, it should be also printed 100 in the console, but it's not!

Try this to another text component, still not working.

# Answer
not sure what version of unity your using but I never use the full hierarchy path to my game objects, secondly since your declaring healthText as public, instead of the GameObject.Find() which by the way is an expensive as far as cpu hit call, you can just select the gameobject that script is attached to then in the inspector panel click the little lock in the top right corner so that the inspector doesn't change, select the text object in the hierarchy, drag and drop it to the healthText field of your script in the inspector and get rid of the GameObject.Find in your start method. doing it like this creates a "reference" as unity calls it to the exact specific gameobject that you drag and drop. Should solve your problem perfectly :)

also don't forget to click the lock again to unlock the inspector :)
> 1 votes

---
Tags: unity, text
---


# Question
Title: How can I use keybord keys like W, A, S and D in GLUT and C++?
I want to use `W`, `A`, `S` and `D` keys like `GLUT_KEY_LEFT`.

My Code:

```
if (key == GLUT_KEY_RIGHT)
    rotate_y += 5;
else if (key == GLUT_KEY_LEFT)
    rotate_y -= 5;
else if (key == GLUT_KEY_UP)
    rotate_x += 5;
else if (key == GLUT_KEY_DOWN)
    rotate_x -= 5;

else if (key == GLUT_KEY_HOME)
    X1 += 0.5;
else if (key == GLUT_KEY_END)
    Y1 += 0.5;
else if (key == GLUT_KEY_INSERT)
    Z1 += 0.5;

```

# Answer
> 3 votes
**glutSpecialFunc** is used to register a callback handler for special keys; as it's documentation notes:

> The special keyboard callback is triggered when keyboard function or directional keys are pressed.

For all other non-special keys you should register a second callback using **glutKeyboardFunc**, then just test for 'w', 'a', 's', 'd', etc in your code.

Again, from the documentation:

> glutKeyboardFunc sets the keyboard callback for the current window. When a user types into the window, each key press generating an ASCII character will generate a keyboard callback. The key callback parameter is the generated ASCII character. The state of modifier keys such as Shift cannot be determined directly; their only effect will be on the returned ASCII data. The x and y callback parameters indicate the mouse location in window relative coordinates when the key was pressed. When a new window is created, no keyboard callback is initially registered, and ASCII key strokes in the window are ignored. Passing NULL to glutKeyboardFunc disables the generation of keyboard callbacks.
>
> During a keyboard callback, glutGetModifiers may be called to determine the state of modifier keys when the keystroke generating the callback occurred.
>
> Also, see glutSpecialFunc for a means to detect non-ASCII key strokes.

So:

```
glutSpecialFunc (SpecialKeyHandler);
glutKeyboardFunc (NormalKeyHandler);

```

And:

```
void SpecialKeyHandler (int key, int x, int y)
{
    if (key == GLUT_KEY_RIGHT)
        ; // do stuff
    if (key == GLUT_KEY_LEFT)
        ; // do other stuff
    // and so on...
}

```

And:

```
void NormalKeyHandler (unsigned char key, int x, int y)
{
    if (key == 'w')
        ; // do stuff
    else if (key == 'a')
        ; // do other stuff
    // and so on...
}

```

---
Tags: c++, keyboard, glut
---


# Question
Title: Errors when calling functions from File class?
When I try something like `File.Delete("Assets/a.txt");` it gives me a error saying

> Unknown identifier: 'File'.

In Unity Documentation https://docs.unity3d.com/ScriptReference/Windows.File.html it gives an note saying "this class is only available when targeting Universal Windows Platform." What does this mean?

In top of unity documentation it says `File` is a class in `UnityEngine.Windows`

So I tried `Windows.File.delete("Assets/a.txt")`.

Now the error changed to

> Language feature not implemented: UnityEngine.Windows.

What is it I am doing wrong?

# Answer
As the documentation states, the function you are trying to call is "only available when targeting the Universal Windows Platform," or UWP. You're not targeting that platform currently, and the function is unavailable to you.

UWP isn't "standard" Windows, it's a cross-device common application platform introduced with Windows 10. It's typically synonymous with "stuff that goes into the Windows app store."

So there's a good chance you don't *want* to be targeting UWP, since you don't need to, and should thus use a different API to delete a file such as the normal `System.IO.File` APIs.

If you really do need to target UWP, you'll have to modify your project appropriately to target the platform. Unity has some guides and tutorials on the subject.
> 1 votes

---
Tags: unity, unityscript, file
---


# Question
Title: LibGDX - Waiting for sound or music to finish
I understand that all sound playing in LibGDX happens asynchronously (for good reasons), however I'm now struggling to do something as simple as:

(Character dies)

* Play a sound
* **When the sound has finished playing**, play another sound
* When the second sound has finished, display a button that has to be pressed for the game to start over

My code is as follows:

```
if (hasDied){
  dieSound.play();
  gameOverSound.play();
  showButton();
}

```

But what it does is, obviously, play the two sounds at the same time, while displaying the button. It's even possible for the user to press the button while the sounds are playing.

Now, I can put a check in the button listener to not do anything if `dieSound.isPlaying()` or `gameOverSound.isPlaying()`, but of course that does nothing to avoid concurrent playing of the two sounds and still displays the button before the sounds have finished playing. Now I see that Music objects, as opposite to Sounds, have a `setOnCompletionListener()` method, which could perhaps be (ab)used this way:

```
if (hasDied){

  gameOverMusicCompletionListener = new OnCompletionListener(){
    @Override
    public void onCompletion(Music a) {
       showButton();
    }
  }

  dieMusicCompletionListener = new OnCompletionListener(){
    @Override
    public void onCompletion(Music a) {
       gameOverMusic.setOnCompletionListener(gameOverMusicCompletionListener);
       gameOverMusic.play();
    }
  }

  dieMusic.setOnCompletionListener(dieMusicCompletionListener);
  dieMusic.play();
}

```

This looks quite kludgy to me, isn't there another way to accomplish what I'd like?

# Answer
> 0 votes
I may have found a solution, although it is untested and will probably only work on desktop.

You can query the state of a sound instance using `AL10.alGetSourcei(id, AL10.AL_SOURCE_STATE)`. This will return an `int` constant signifying the state of the source. To check if the source is playing you check if the returned value is `AL10.AL_PLAYING` like so:

```
// id = the value returned by sound.play()
boolean isPlaying = AL10.alGetSourcei(id, AL10.AL_SOURCE_STATE) == AL10.AL_PLAYING;

```

The problem is that we cannot access the `AL10` class and methods from the `Core` project, so we have to delegate the task to a class created in the `Desktop` project.

1. In your `Core` project create an interface like so:

```
public interface SoundStateChecker {
    public boolean isPlaying(int id);
}

```
2. In your Desktop project define a class like so:

```
public class ALStateChecker implements SoundStateChecker {
    @Override
    public boolean isPlaying(int id) {
        return AL10.alGetSourcei(id, AL10.AL_SOURCE_STATE) == AL10.AL_PLAYING;
    }
}

```
3. Now in your `Lwjgl3Launcher` in your `Desktop` project where you create your `Lwjgl3Application` you simply supply an instance of your `ALStateChecker` to your main game class:

```
new Lwjgl3Application(new MainClass(new ALStateChecker()), config);

```

You can now use a reference to the state checker to see if the sound is playing:

```
int dieSoundID = -1;
int gameOverSoundID = -1;
boolean hasShownButton = false;

if (hasDied){
    // If this sound hasn't played before...
    if(dieSoundID == -1)
        dieSoundID = dieSound.play();

    // If this sound hasn't played before AND dieSound isn't playing...
    if(!stateChecker.isPlaying(dieSoundID) && gameOverSoundID == -1)
        gameOverSoundID = gameOverSound.play();

    // If neither sound is playing AND they have been played before
    // AND we haven't shown the button.
    if(!stateChecker.isPlaying(dieSoundID) && !stateChecker.isPlaying(gameOverSoundID
       && dieSoundID != -1 && gameOverSoundID != -1 && !hasShownButton) {
        hasShownButton = true;
        showButton();
    }
}

```

This code is a bit verbose but you should be able to trim it down a bit.

---

Just a quick comment: There is a way to get how long the audio source is (in seconds) and from this information you can simply run a timer for the same duration as the audio source length and check if it has finished playing that way. But this is only available in the `OpenALSound` class that you cannot access in the `Core` project. If the above method doesn't work I can update my answer with an alternative solution that uses audio length and timers instead.

---

If you're going to go for the Music route you can trim the code down quite a bit by using lambda expressions:

```
if (hasDied){
    dieMusic.setOnCompletionListener(a -> {
        gameOverMusic.play();
    });
    gameOverMusic.setOnCompletionListener(a -> {
        showButton();
    });
    dieMusic.play();
}

```

---
Tags: libgdx, music
---


title: Overriding component behavior

text:
# Question
Title: Overriding component behavior
I was thinking of how to implement overriding of behaviors in a component based entity system. A concrete example, an entity has a heath component that can be damaged, healed, killed etc. The entity also has an armor component that limits the amount of damage a character receives.

Has anyone implemented behaviors like this in a component based system before?
**How did you do it?**

If no one has ever done this before why do you think that is. **Is there anything particularly wrong headed about overriding component behaviors?**

Below is rough sketch up of how I imagine it would work. Components in an entity are ordered. Those at the front get a chance to service an interface first. I don't detail how that is done, just assume it uses evil `dynamic_cast`s (it doesn't but the end effect is the same without the need for RTTI).

```
class IHealth
{
public:
   float get_health( void ) const = 0;
   void do_damage( float amount ) = 0;
};

class Health : public Component, public IHealth
{
public:
   void do_damage( float amount )
   {
      m_damage -= amount;
   }
private:
   float m_health;
};

class Armor : public Component, public IHealth
{
public:
   float get_health( void ) const
   {
      return next<IHealth>().get_health();
   }

   void do_damage( float amount )
   {
      next<IHealth>().do_damage( amount / 2 );
  }
};

entity.add( new Health( 100 ) );
entity.add( new Armor() );
assert( entity.get<IHealth>().get_health() == 100 );
entity.get<IHealth>().do_damage( 10 );
assert( entity.get<IHealth>().get_health() == 95 );

```

**Is there anything particularly naive about the way I'm proposing to do this?**

# Answer
> 3 votes
I think you're making it a little too complicated, or not complicated enough.

One direction I would suggest would be to break apart getting health and doing damage interfaces.

So maybe as an idea, your Armor component would look like this:

```
class Armor : public Component, public IDamageReceiver
{
public:
   void do_damage( float amount )
   {
      // just assume that subtract_health isn't used in client code maybe
      this.get<IHealth>().subtract_health( amount / 2 );
   }
};

```

Alternatively (and probably what I would do), you could make your components a little bigger and just have a generic "Entity" base class that your specific types derive from. This would contain the functionality of both health and armor and you could implement specific entities from that.

# Answer
> 2 votes
Your thoughts are in the right place but I think you are trying to take the component system to a level of detail that it does not need. I would say make a component called Health when all you need is straight up health. But if you need a health component that also has armor in it, then make it a CHealthAndArmor component that still fits the API of Health in general so it can be used like any other, but then provide the manner of also changing the armor levels if needed.. If its completely a load time value then there is no need, that's just the internal workings of that particular health component.

Honestly the concerns you are having (from this and your other post) are how fine a level of detail you break components down into. If you ever find yourself inheriting or encapsulating a component within another component, you should reconsider what you are doing. You generally are trying to avoid inheritance like this in component based architectures.

Hope this helps

# Answer
> 2 votes
Your Component stuff is too much OOP. See what I'm doing here:

https://github.com/thelinuxlich/starwarrior\_CSharp

And this is the Entity System framework I've ported to C#: https://github.com/thelinuxlich/artemis\_CSharp

# Answer
> 0 votes
I use an event driven component system and had this same issue. Basically I subscribe component functions to other component events. For one event I can have x functions subscribed and events are fired in the order they were subscribed. Events also give one parameter which is a dynamic class and passed by reference. All of this means I can create a Stats component and a Health component. I subscribe both to a hurt message but because Stats is subscribed first it'll use the armor stat of the Stat component and modify the damage value that is inside the parameter object. The health component is next in the subscription list and by the time it is called the damage value has already been reduced.

I can't talk up enough the event waynof dealing with components. It really does allow piecing together functionality via components where they don't event know about each other. The user is just setting up the event subscriptions to build up the functionality. Would never look back from this system.

---
Tags: component-based, entity-system
---


# Question
Title: sound stops after scene reloads in unity3d
I'm recently facing problem regarding the inclusion of sounds in my game. Although i have used the technique of DontDestroyOnLoad() for background sounds and that work perfectly fine. But for the casual sound, it is creating problem that it stops during scene reloads. I have my script below that contains AudioClips and AudioSources and that script is attached to an empty game object, and calling that script in different scripts for the playback of the sounds.

**AudioScript.cs**

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

public class AudioScript : MonoBehaviour {

    public AudioClip pinshit;

    public AudioClip rowlingball;

    public AudioSource rowling;

    public AudioSource hit;

    public AudioClip cheer;

    public AudioClip strike;

    public Text counttext;

    public AudioClip spare;

    public AudioClip sorrow;

    public AudioClip winaudio;

    GameObject[] music;

    // Use this for initialization
    void Start () {

        rowling = GetComponent<AudioSource>();

        music = GameObject.FindGameObjectsWithTag("class");

        if (music.Length == 1)
        {

        }
        else
        {
            for (int i = 1; i < music.Length; i++)
            {
                Destroy(music[i]);
            }
        }

    }

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

    }

    private void Awake()
    {
        DontDestroyOnLoad(this.gameObject);
    }
}

```

To play sound on different actions routines

```
sorrow.clip = GameObject.FindWithTag("class").GetComponent<AudioScript>().sorrow;

                sorrow.Play();

                sorrow.volume = 1;

```

# Answer
> 2 votes
Was just making a small mistake. I was not calling the audiosource rowling used in AudioScript in another script. Anyhow the correct format is below

```
   GameObject.FindGameObjectWithTag("class").GetComponent<AudioScript>().rowling.clip = GameObject.FindGameObjectWithTag("class").GetComponent<AudioScript>().sorrow;

   GameObject.FindGameObjectWithTag("class").GetComponent<AudioScript>().rowling.Play();

```

And that's it!

---
Tags: unity, music
---


# Question
Title: Why is the size of glm's vec3 struct 12 bytes?
When trying to determine the size of glm::vec3 (from GLM math library) by using the size of operator like so:

```
sizeof(glm::vec3)

```

I get 12 returned. When I look at the definition of a vec3 struct I see this:

```
    template <typename T, precision P = defaultp>
    struct tvec3
    {
        // -- Implementation detail --

        typedef tvec3<T, P> type;
        typedef tvec3<bool, P> bool_type;
        typedef T value_type;

#       ifdef GLM_META_PROG_HELPERS
            static GLM_RELAXED_CONSTEXPR length_t components = 3;
            static GLM_RELAXED_CONSTEXPR precision prec = P;
#       endif//GLM_META_PROG_HELPERS

        // -- Data --

#       if GLM_HAS_ANONYMOUS_UNION
            union
            {
                struct{ T x, y, z; };
                struct{ T r, g, b; };
                struct{ T s, t, p; };

#               ifdef GLM_SWIZZLE
                    _GLM_SWIZZLE3_2_MEMBERS(T, P, tvec2, x, y, z)
                    _GLM_SWIZZLE3_2_MEMBERS(T, P, tvec2, r, g, b)
                    _GLM_SWIZZLE3_2_MEMBERS(T, P, tvec2, s, t, p)
                    _GLM_SWIZZLE3_3_MEMBERS(T, P, tvec3, x, y, z)
                    _GLM_SWIZZLE3_3_MEMBERS(T, P, tvec3, r, g, b)
                    _GLM_SWIZZLE3_3_MEMBERS(T, P, tvec3, s, t, p)
                    _GLM_SWIZZLE3_4_MEMBERS(T, P, tvec4, x, y, z)
                    _GLM_SWIZZLE3_4_MEMBERS(T, P, tvec4, r, g, b)
                    _GLM_SWIZZLE3_4_MEMBERS(T, P, tvec4, s, t, p)
#               endif//GLM_SWIZZLE
            };

         //other code......
       }

```

For which I see three structs, each with three member variables of templated type T, which in GLM defaults to float type. My question is why is the sizeof() operator returning 12 bytes as the size of glm::vec3 when it looks like it should be 36 bytes:

3 structs, with 3 float members each = 3\*3\*4(number of bytes in a float) = 36.

# Answer
The "`union`" there says that these are three different ways of viewing the same memory.

So the `x` component of the first struct occupies the same bytes of memory as the `r` component of the second struct, and so on. The three different versions just create different aliases by which you can refer to the vector's components - depending on whether you're viewing it as a spatial position / offset / direction (`xyz`), or a colour (`rgb`), or a parametric coordinate (`stp`), for instance.

That gives the expected 3 float members * 4 bytes per float = 12 bytes total size.
> 9 votes

---
Tags: opengl, graphics, glm
---


title: Playing a Song in MonoGame

text:
# Question
Title: Playing a Song in MonoGame
I'm trying to play a song in a MonoGame project, but it always gives me a weird error. Here is the (Very simple) code:

```
Song song = Content.Load<Song>("Song1");
        MediaPlayer.Play(song);

```

But whenever I run the program, it says this:

System.InvalidCastException: 'Unable to cast object of type 'Microsoft.Xna.Framework.Audio.SoundEffect' to type 'Microsoft.Xna.Framework.Media.Song'.'

Do you know why this happens? Any help would be appreciated! :D

# Answer
I believe the content importers are set up in a way that any .wav file must be loaded as a `SoundEffect`, and any .mp3 or .wma file must be loaded as a `Song`.

Your best bet is probably to convert the file to an .mp3, or load and play your music as a `SoundEffect`.
> 2 votes

---
Tags: monogame, audio
---


title: Unity storing many items in an RPG game

text:
# Question
Title: Unity storing many items in an RPG game
I want to ask about the best method of storing data that represents information's about specified objects.

I want to find a better way to storing somewhere items in my RPG game before problems had occurred, I had big ugly class, that was defining armors, weapons etc.

```
[System.Serializable]
public class Item
{
    public string   name;
    public int      cost;
    public float    weaponRange;
    public string   imagePath; //starting from Resources
    public ItemType itemType;
    public enum ItemType   { Item, Armor, Weapon };
    public enum WeaponType { None, ShortSecant, LongSecant, Blunt, Prickly, Bow };
    public enum ArmorType  { None, Cuirass, Helmet, Boots };

    public WeaponType   weaponType;
    //public int          damages;
    public CharacterPropertyList damages = CharacterPropertyList.AttackProperties;
    public bool         twoHanded;

    public ArmorType    armorType;
    //public int          armorPoints;
    public CharacterPropertyList armorPoints = CharacterPropertyList.DefenseProperties;

    public int   infoIndex = -1; // Represents item info position in Model Spawner Coordinate array, -1 when item have not model info -> item can't be spawned.

    [XmlIgnore]
    public bool itemExpanded = false; //expanded item in inspector?
}

```

But I have been able to nicely render it in inspector using PropertyDrawer.. until I had to refactor it...

I add to code some class to have better data management:

```
[Serializable]
public class CharacterProperty
{
    [SerializeField]
    private string name;
    [SerializeField]
    private float value;

    public float Value { get { return value; } set { this.value = value; } }
    public string Name { get { return name; } }

    public CharacterProperty(string name, float value = 0.0F)
    {
        this.value = value;
        this.name = name;
    }
}

[Serializable]
public class CharacterPropertyList
{
    [SerializeField]
    private List<CharacterProperty> properties = new List<CharacterProperty>();

    public List<CharacterProperty> Properties
    {
        get { return properties; }
    }

    public CharacterPropertyList(params CharacterProperty [] properties)
    {
        this.properties.AddRange(properties);
    }

    public CharacterProperty this[string name]
    {
        get
        {
            return
                properties.Find(p => p.Name == name);
        }}
    }

    public CharacterProperty this[int index]
    {
        get
        {
            return properties[index];
        }

        set
        {
            properties[index] = value;
        }
    }
}

```

And I cannot Render it correctly so finally I want to remove that big ugly Item class, and find better, more OO solution, without inspector rendering.

**So I want to ask if my idea is good:**

Let's say that I have a class Item, and that class will have a list that will contain child items of some interface / abstract class and that objects will be representing functionality of that Item, for example:

```
interface IComponent
{
 //some general data
};

public class Valuable : IComponent
{
//override some data
int Value {get;set;}
}

public class DamagesItem : IComponent
{
//damages
}

public class ProtectionItem : IComponent
{
//protection
}

public class Item
{
public List<IComponent> Components {get; set;}

public Item(IComponent [] components)
{
Components = new List<IComponent>();
Components.AddRange(components);
}
}

```

And next I will create those items in code, or via data stored in some XML file, for example:

```
var sword = new Item(new IComponent[]{ new DamagesItem(), new Valuable()});

```

# Answer
I have personally used three different methods to solve this exact same problem. All solutions work, and have different trade offs.

**Method 1: Inheritance**

Simply explained enough: a `BaseItem` class with a derived class for a number of different related item types. May decide to use one derived class for `WeaponItem`, or may decide to go all the way to `ShortSwordItem` and `DaggerItem`.

*Upside*: none to speak of. I suppose it is easy to describe the method.

*Downside*: you wind up with a gazillion little classes and you go crazy when trying to find one. Your solution is brittle and unmaintainable, and you gradually drown in the weight of using OOP.

**Method 2: Property Bag**

More or less your own solution up until now. A `GetProperty` and `SetProperty` method, a `Dictionary<TIdentifier,object>` collection, and a lot of template methods.

*Upside*: All item types look exactly the same code-wise, as they are all one class.

*Downside*: You have moved your problem from the "too many classes" problem of the Inheritance method into the "too many flexible properties" problem.

**Method 3: Descriptor/Instance Pairing**

This is my current method of choice. I have two classes: `ItemDescriptor` and `ItemInstance`.

The `ItemDescriptor` has all properties common to all classes of item, but as `Func<T>` and `Action<T>` values, so you can plug them in. Typically the parameters are `ItemInstance`, so that you can base values on the instance.

Consider `ItemDescriptor` to be more or less static methods for all items of a particular class of items.

The `ItemInstance` has properties common to all instances of items, typically as discreet values. It needs a reference to its `ItemDescriptor` to make use of the descriptor's operations.

*Upside*: Two classes only.

*Downside*: Using a Descriptor/Instance pair looks a lot like using a C API.

Here's an actual code example of what I mean by "C API":

```
//nextCell is the cell to which the creature is moving, and it contains an item.
//note that nextCell.Item has to be passed to a call that starts with nextCell.Item
nextCell.Item.Descriptor.OnPickUp(creature, nextCell.Item);

```

This is still not perfect, as `ItemInstance` winds up with a lot of properties it doesn't need most of the time, as does `ItemDescriptor`. However, I find it better than too many classes or too flexible of properties.

For the record, my answer is "Method 3". At least it is today. Ask me again tomorrow.
> 1 votes

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


# Question
Title: Minecraft Forge 1.8 referencing mod problem
I'm trying to make a Minecraft Forge mod. I've done this before, but I've never worked with entities. So I was trying to add an entity to the `EntityRegistry`, but I can't seem to reference the mod file as an object using `this`. It tells me that it expect `Object mod`, not `TestMobs`. What am i doing wrong?

Here is my code:

```
package com.scriptcoded.testmobs;

import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.Mod.EventHandler;
import net.minecraftforge.fml.common.event.FMLInitializationEvent;
import cpw.mods.fml.common.registry.EntityRegistry;

@Mod(modid = Tutorial.MODID, version = Tutorial.VERSION)
public class TestMobs
{
    public static final String MODID = "testmobs";
    public static final String VERSION = "1.0";

    @EventHandler
    public void init(FMLInitializationEvent event)
    {
        EntityRegistry.registerModEntity(EntityTutorial.class, "Test mob", 1, this, 80, 3, true);
    }
}

```

The problem is in the line `EntityRegistry.registerModEntity(EntityTutorial.class, "Test mob", 1, this, 80, 3, true);`.

Any ideas? Thanks for any help!

# Answer
> 1 votes
For 1.7.10 (and I'm assuming 1.8 too), you need to add an instance of the main class into itself. Just after initialising the `VERSION`, you should put:

```
@Instance(TestMobs.MODID)
public static TestMobs instance;

```

Then when you reference your mod reference it through:

```
TestMobs.instance

```

The only other suggestion I can give is to register it in the preInit or postInit (or the client/common proxy)

# Answer
> 0 votes
I know this is an OLD TOPIC, but I just could not help noticing:

In the line reading: @Mod(modid = you have the following: @Mod(modid = Tutorial.MODID, version = Tutorial.VERSION)

Do you actually HAVE a class file named "Tutorial.java", that defines both the "MODID" and "VERSION" strings?

Because, you ALSO have defined a "MODID" string var. and a "VERSION" string var. right BELOW that line, in the TestMobs class definition ITSELF! So, you have basically told Forge to "look" in a class file named "Tutorial", for the strings "MODID" and "VERSION" (resulting in "Tutorial.MODID" and "Tutorial.VERSION"; you *MUST* therefore HAVE that classfile in your project!

It makes absolutely no difference to Forge if you define yet another string "MODID" and a string "VERSION" anywhere else; it won't know to use THOSE strings for anything!

I mean, that's just what I noticed at a quick glance through your code...

ZTagre.

---
Tags: java, minecraft-modding, modding
---


# Question
Title: MonoGame.Extended.Tiled: Get layers for Vector2 location without iterating over all tiles? Extended
I am trying to get the layers (or better, a special object layer) which contains a Vector2 location from a TiledMap, I know I could iterate over those, but I do not want to. How would I do that?

Thanks!

PS: I already asked at the MonoGame.Extended forums, but I may not get an answer there. That's why I'm asking here, too.

# Answer
Have you tried the `GetLayer` method on the `TiledMap`?

Depending on your use case, you can get the object layer specifically by using either use the generic method:

```
var objectLayer = map.GetLayer<TiledMapObjectLayer>("layerName");

```

Or you can cast it you the object layer yourself:

```
var objectLayer = map.GetLayer("layerName") as TiledMapObjectLayer;

```

In either case it will return `null` if the layer doesn't exist or is of the wrong type.
> 0 votes

---
Tags: c#, monogame
---


# Question
Title: Offscreen arrow indicator appears only when the user go near to the object
I have placed four gameobject at different place.And I have a player and have applied movement to it through keyboard control.I have added script for arrow indication towords this gameobject.But the problem is that,the arrow appeaar only when the user go near to the gameoobject.I need the arrows to appear on the screen so that the user initially know where the gameobject is placed on the scene.

Here is the code for onscreen arrow.I have attached this script to each gameobject

```
public Texture2D icon; //The icon. Preferably an arrow pointing upwards.
public float iconSize = 50f;
[HideInInspector]
public GUIStyle arrow; //GUIStyle to make the box around the icon invisible. Public so that everything has the default stats.
Vector2 indRange;
float scaleRes = Screen.width/200; //The width of the screen divided by 500. Will make the GUI automatically
//scale with varying resolutions.
Camera cam;
public bool visible = false; //Whether or not the object is visible in the camera.

void Start () {
    visible = GetComponent<SpriteRenderer> ().isVisible;

    cam = Camera.main; //Don't use Camera.main in a looping method, its very slow, as Camera.main actually
    //does a GameObject.Find for an object tagged with MainCamera.

    indRange.x = Screen.width - (Screen.width / 6);
    indRange.y = Screen.height - (Screen.height / 7);
    indRange /= 2f;

    arrow.normal.textColor = new Vector4 (0, 0, 0, 0); //Makes the box around the icon invisible.

}

void OnGUI () {
    if (visible) {
        Vector3 dir = transform.position - cam.transform.position;
        dir = Vector3.Normalize (dir);
        dir.y *= -1f;

        Vector2 indPos = new Vector2 (indRange.x * dir.x, indRange.y * dir.y);
        indPos = new Vector2 ((Screen.width / 2) + indPos.x,
            (Screen.height / 2) + indPos.y);

        Vector3 pdir = transform.position - cam.ScreenToWorldPoint(new Vector3(indPos.x, indPos.y,
            transform.position.z));
        pdir = Vector3.Normalize(pdir);

        float angle = Mathf.Atan2(pdir.x, pdir.y) * Mathf.Rad2Deg;

        GUIUtility.RotateAroundPivot(angle, indPos); //Rotates the GUI. Only rotates GUI drawn after the rotate is called, not before.
        GUI.Box (new Rect (indPos.x, indPos.y, scaleRes * iconSize, scaleRes * iconSize), icon,arrow);
        GUIUtility.RotateAroundPivot(0, indPos); //Rotates GUI back to the default so that GUI drawn after is not rotated.
    }
}

public void OnBecameInvisible() {
    visible = false;
}
//Turns off the indicator if object is onscreen.
public void OnBecameVisible() {
    visible = true;
}

```

}

How can I make the arrows to appear on the edges of the screen

# Answer
using Mathf.Clamp() can clamp the indicators to the edge of the screen.
> -2 votes

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


# Question
Title: How to make Scriptable Objects derive from other Gameobejcts?
I encountered a problem where I want to make a Scriptable Object that derives from another class, but C# does not support multiple inheritance. Further, I do not think it would not make sense to make interfaces for this example. There is a lot of duplicate code within methods that only an abstract class could contain implementations of.

Basically, I want an abstract class that models "anything that can take a turn." I call it a TurnTakeable. But I also want the TurnTakeable to be split into friend and foe derived types, as the two are slightly different. Yet they mostly have the same behavior.

Is there a workaround, or do I have to make an interface? :(

# Answer
I decided to make the abstract class the scriptable object.
> -2 votes

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


# Question
Title: Vulkan am I creating too many graphics pipelines?
I have the situation in which I require different VkPrimitiveTopology's for different models, which requires me to have a unique pipeline's that render the different models, but now I require multiple windows open at the same time. Is there any way to use the pipelines for multiple windows or will I require a different set for the new window?

The secondary windows could be a different size to the main window, that's why I ask because I know when a window resizes you require to rebuild the pipeline.

# Answer
As for multiple pipelines for multiple windows - that depends if rendering to those windows is performed using separate logical devices or not. If You have only one logical device, You can also share pipeline objects and use them to render to multiple windows (swapchains). If each window has it's own logical device, You need separate pipelines.

And for the windows' sizes - when You resize a window, You need to recreate a swapchain. This causes swapchain images to be also recreated thus You also need new framebuffers. But You don't have to recreate pipelines.
> 3 votes

---
Tags: pipeline, vulkan
---


title: How should I reload a ball?

text:
# Question
Title: How should I reload a ball?
I am making an angry bird type 2d game using Unity and C#. After I throw the ball from catapult, I have no idea on reloading the ball. Then I use SceneAsync to reload the ball but it is the worst thing I've ever made since I can't make the other sprite objects to continue their movents after the ball is thrown. So what code should I use to reload the balls after throwing?

# Answer
> 1 votes
You can use Instantiate method that unity provides for instantiating new gameobjects. Just keep a static reference for initial position like:

```
private static Vector3 initialPosition = new Vector3(10, 10, 0) //The values are dummy

```

And also keep a reference for the ball's prefab:

```
public Gameobject ballPrefab; //Drag the ball prefab in the editor

```

And finally when it comes to instantiate:

```
Gameobject newBall = Instantiate (ballPrefab, initialPosition, Quaternion.identity) as Gameobject;

```

Now the newBall will appear in the scene with the position you set with "initialPositon". And the newBall variable keeps reference for the new object that you have instantiated

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


# Question
Title: How do I get 'getchar()' to not block the input?
I am working on designing a pong like game but converting a `getchar()` to `getch()` and `getche()`, respectively, but `getchar()` is blocking the input. I am using C++ code, and while there *is* the ncurses library, I heard that this is a better approach; I am only needing to update this one command.

How do I get `getchar()` to not block the input?

The code is as follows:

```
#include<iostream>
#include <termios.h>
#include <stdio.h>

//Prototypes
char inputReader();
void updateWorld();
void renderWorld();
void initTermios(int echo);
void resetTermios(void);
char getch_(int echo);
char getch(void);
char getche(void);

static struct termios oldChars, newChars;
int main()
{
   bool running = true;

   do
   {
      if(getche() == 'q')
      {
         running = false;
      }
      updateWorld();
      renderWorld();
   }

   while(running);
   std::cout << "I exited the loop";
   return 0;
}

char inputReader()
{
   return getch();
}

void updateWorld()
{
  std::cout << "I am updating the world" << std::endl;
}

void renderWorld() {}

void initTermios(int echo) //struct termios &oldChars, struct termios &newChars)
{
  tcgetattr(0, &oldChars); /* grab old terminal i/o settings */
  newChars = oldChars; /* make new settings same as old settings */
  newChars.c_lflag &= ~ICANON; /* disable buffered i/o */
  newChars.c_lflag &= echo ? ECHO : ~ECHO; /* set echo mode */
  tcsetattr(0, TCSANOW, &newChars); /* use these new terminal i/o settings now */
}

/* Restore old terminal i/o settings */
void resetTermios(void)//struct termios &oldChars)
{
  tcsetattr(0, TCSANOW, &oldChars);
}

/* Read 1 character - echo defines echo mode */
char getch_(int echo)
{
  char ch;
  initTermios(echo); //oldChars, newChars);
  ch = getchar();
  resetTermios();//oldChars);
  return ch;
}

/* Read 1 character without echo */
char getch(void)
{
  return getch_(0);
}

/* Read 1 character with echo */
char getche(void)
{
  return getch_(1);
}

```

# Answer
In initTermios() set file descriptor of standard input(that's the '0' parameter) to non-blocking behavior.

```
void initTermios(int echo) //struct termios &oldChars, struct termios &newChars)
{
  fcntl(0, F_SETFL, O_NONBLOCK);
  tcgetattr(0, &oldChars); /* grab old terminal i/o settings */
  newChars = oldChars; /* make new settings same as old settings */
  newChars.c_lflag &= ~ICANON; /* disable buffered i/o */
  newChars.c_lflag &= echo ? ECHO : ~ECHO; /* set echo mode */
  tcsetattr(0, TCSANOW, &newChars); /* use these new terminal i/o settings now */
}

```

Now console will react to your every key press, getchar won't block input.
> 1 votes

---
Tags: c++, input
---


# Question
Title: Checking Collisions Within a Sprite List in MonoGame
I'm trying to learn game dev, and I'm using some of Oyyou's tutorials. My problem is: I have a list of sprites, using a sprite object, and I would like to know how to check for collisions between different sprites. I have a basic understanding of bounding boxes, and can use them to some extent, but I don't know how to check collisions in a list. Any help would be appreciated. :D

# Answer
Bounding Boxes are basically rectangles (mostly). And the rectangle class provides an Intersects(Rectangle) method (https://msdn.microsoft.com/en-us/library/bb464123.aspx)

Depending on your specific usecase you can iterate through your list and check for collisions like this:

```
foreach (Sprite s in sprites)
    if (mySprite.Intersects(s))
        return true;

```
> 0 votes

---
Tags: monogame
---


# Question
Title: Is there any way to make xTile work with MonoGame?
I am currently in the process of planning and developing a game. I use MonoGame as my framework, and I also planned to use xTile with tIDE to manage my tiles, but it *only* works with XNA 4.0, but my project (of course) only references the MonoGame.Framework and not the Microsoft.Xna.Framework, which means that some classes are defined in assemblies which are not referenced.

I know MonoGame is a continuation of Xna, but as the Assembly has a different name/ID, xTile of course doesn't recognise it.

Is there any way to support xTile when using MonoGame? If there isn't, is there any alternative to xTile?

# Answer
> 1 votes
I am currently using MonoGame with Tiled and for parsing I have adapted TiledSharp to fit my needs better. But it works out of the box very well.

There is also the MonoGame.Extended project to support Tiled directly. Long story short: You should switch to Tiled since it's quite popular.

---
Tags: c#, xna, monogame
---


# Question
Title: Looking for a 2D spatial partitioning method for my top down browser game
Hi I am currently using a modified version of spatial hashing algorithm written by Christer Bystrom. This algorithm is OK for collision detection. However when I use it for detecting entities in interested range it has its limits.

I use a huge map. (10000 x 10000 pixels) When I am moving my player, I expect to see what are around my player on the screen. Sometimes some entities are right in front of me or just behind me but I can't see anything on the screen until I get really close.

Here is a visual demo I created for that algorithm. I modified it to work with circle objects. In the demo picture I have already set the powerOfTwo attribute to 9, which is pretty big. The green circle is my mouse position. The red circles are those entities within my player's interested area. But this is not a good solution. The player should be able to see things on all directions around itself and stretch out further to about the same size of the rectangle area holding those red circles.

So I am looking for a better solution out there to implement in my game. I hope it is accurate and fast for detecting entities within interested area, and better not too hard to understand. It can be any other way (quadtree, dynamic tree, RTree or whatever fits the type of game I am making). I have also read about this, but not sure if those methods work well with interests management.

# Answer
The library you're using should do what you want. I tried it — demo here, with the default power of two setting (5):

You have to specify the “area of interest” in the `retrieve` function. The library wants `retrieve` to take a rectangle, so pass in a rectangle *centered* on the player.
> 1 votes

# Answer
Generally with a spatial hash, you will have to grab stuff from more than one cell. This is because even if each cell is larger than a screen width, you could always be close to the edge of your current cell. If each one is larger than a screen width, you could pull the nearest 3x3 cells, and if not, you'll have to loop through "all visible cells" for example like the pseudocode below

```
for (var x = player.pos.x - screen.width /2; x < player.pos.x + screen.width / 2 - cell.width; x += cell.width)
    for (var y = player.pos.y - screen.height/2; y < player.pos.y + screen.height/ 2 - cell.height; y += cell.height)
        // etc etc

```
> 1 votes

---
Tags: spatial-partitioning
---


title: Restricting movement to 3D axis

text:
# Question
Title: Restricting movement to 3D axis
A cube is constructed in a 3D and can be rotated to view any side. I want to be able to drag the cube to any position with the mouse while keeping the Y-coordinate the same. I used project and unproject functions to map the mouse to the 3d world. This method seems to work fine when the green face is parallel to the camera. However, when i rotate the cube say 45 degrees around the x-axis and the cube face is now at an angle to the camera, the y-coordinates do not track the mouse. when the camera is parallel to the red face, the tracking in the y-axis is almost nothing.

When i dont fix the y-coordinate, the cube tracks the mouse perfectly, however, the y-coordinates are changed as well. How can i go about keeping the y-axis fixed and yet having the mouse cube track the mouse?

# Answer
Several solutions could be used here to accomplish this task, depending on how much work you want to put into it.

**Plane Intersection**

If keeping the cube at the position of the mouse is important, you will likely be looking for this method. Essentially, when you first receive a mouse click, you will construct a plane at the Y level of the object (assuming Y is up). Then during your mouse drag you perform a ray-cast each step from camera origin to projected mouse coordinates. Your cube can then be moved to the intersect point of this ray on the plane.

For some detail on the math involved: http://geomalgorithms.com/a05-\_intersect-1.html#Line-Plane%20Intersection

**An easier method**

An alternate method you could try reduces the complexity a bit, but does not allow for the cube to follow the mouse correctly on the screen. As you are wanting the move the cube along only the two axes (X and Z), you can map mouse movement along it's 2 axes (X and Y) fairly easily. To make the movement feel more natural, you'd likely want to modify the effect of the mouse offset to take the camera yaw into account. To accomplish this, you can take the offset X and Y of the mouse, rotate them around 0,0 by the camera's yaw rotation and then apply those new X and Y values to the cube.
> 1 votes

# Answer
I agree with JonBee that a Plane test should work well.

In response to your comment, the world-space intersection that you calculate resides on the plane that you want the cube to move in regardless of the cube's current orientation. The thing I think you have overlooked is that the plane you need to construct has "Up" `(0, 1, 0)` for its' normal and should not be oriented to a cube face.

In any subsequent frame, intersecting the mouse ray with that plane will produce a coordinate with the same Y-component as the entire plane (including the originally clicked point). That means that whatever world-space delta you calculate will automatically have a Y-component of 0. Render the cube at (`actualPosition` \+ `delta`) and, when the drag ends, add `delta` to `actualPosition` and reset `delta` to 0.
> 1 votes

# Answer
At time 1, your mouse coordinates are

`m_1 = [x_1, y_1]`

At time 2, they are

`m_2 = [x_2, y_2]`.

First, project these into camera-centered coordinates to produce two 3D points:

`p_1 = project(m_1, depth=0); p_2 = project(m_2, depth=0);`

Note: take care to make sure these points are in the *camera's reference frame*, not the world. From there, the motion of the mouse in camera coordinates is then:

`dp = p_2 - p_1`

Now, `dp` is a 3D vector in camera coordinates in camera space. Transform `dp` to world space using the camera's rotation matrix `R`, which is a 3x3 matrix defining the orientation of the camera:

`dw = R * dp`

Now you have a 3D vector `dw` in world space. Project this vector onto the plane of interest to find the motion along the plane. Supposing the plane is world-oriented (that is, the world coordinates are the plane coordinates), then you simply have to zero out the `y` component of `dw` giving a vector on the plane:

`motion = [dw.x, dw.z]`.

If the plane you want to move on is anything else, you simply have to first rotate `dw` into the reference frame of the plane, and then project it along the normal of the plane.
> 1 votes

---
Tags: directx11, picking
---


# Question
Title: Could executing OpenGL shaders sent from a server be dangerous?
I just came to the realization that since uncompiled shaders are just text, they can easily be sent over a network from a server and then compiled at runtime and executed on clients. I'm not actually planning on doing this (probably...), but I am curious as to whether or not it would result in any potential security vulnerabilities on the clients executing the shaders.

My gut feeling is that it would not, since even if a shader were to gain unauthorized access (eg by reading unallocated data from a video buffer), it would have no way of sending this data back to the attacker. On the other hand, allowing arbitrary code execution seems like an almost certain way to get hacked. My question is how this would be possible in this scenario (assuming that it is).

# Answer
I think the difficulty of successfully exploiting a machine through shaders is pretty difficult but not impossible or unprecedented.

There's a small chance of that happening -- for example, there was an OSX vulnerability that enabled RCE or crashes http://www.cvedetails.com/cve/CVE-2016-1847/ but the vulnerability itself could be either from the GL library Memory safety errors in libGLES in the ANGLE graphics library or on the application side improperly handling bound buffer memory that could possibly be written to in the shader Buffer overflow in WebGL after out of memory allocation

Another vulnerability is that the shader could access other bits of graphics memory that are shared by the window manager or other applications, allowing it to perhaps be able to read the contents of your other windows. Exfiltration could be a stretch, but either low-quality drivers could allow the malicious shader to write to uncontrolled memory or you could use steganography to embed screenshots of other windows in the current game screenshots.
> 4 votes

---
Tags: opengl, shaders, networking, client-server, security
---


# Question
Title: Procedural terrain generation zooming principle
I am asking myself how to solve the granularity of terrain by zooming into it.

My idea is to create very first just a square represented by four vertices and 6 indices. By zooming in the square is divided into smaller squares each representing a chunk. My question is now: Do I have to scale the whole quad or do I have to generate in the very first state just a very big square?

And how is the granularity of terrain determined? By distance obviously, but what is the formula?

I thank You in advance!

# Answer
This is very broad, but let me try to explain how it might work in a typical case.

You would need to either make or generate a high-res texture for the most detailed level of the terrain. Using a GPU tech like OpenGL or DirectX, we'd then turn on mipmapping for this (power-of-2 sized) texture, to allow the GPU to auto-generate successively coarser versions of that highly detailed quad; each successive level of the mipmap is used when the camera is at some distance away from the surface in question (of course, we use the most detailed when we are very close by, and the least detailed when we are very far away). Even when not using a GPU, this is still a common pattern.

One of the benefits of mipmapping at least in the GPU context, is that sampling the texture is more efficient since not as many texels need be sampled when the player is far away from the textured object. This is typical of any kind of LoD approach - what is further away requires less work to render.

There's no particular formula; you may want to use powers-of-2 distance to determine what level of detail you will display, or this may depend on your field-of-view angle, or some other factors... all down to your implementation and your own choices. Best is to experiment and see what works for you.
> 0 votes

---
Tags: procedural
---