# Question
Title: Do delays after losing and before restarting serve as a defense against burnout, or are they addiction machines?
In games like Super Hexagon or even Everwing, there's a very brief but noticeable delay from losing to starting over: waiting for the restart button to appear, pressing it, etc...

Is this a defense against player burnout? If there's no pause that separates one game try from next, the game might feel never-ending and burn out the player quickly.

Or is it a way to keep the player addicted? I often suspected this in Everwing, because that game's hardly shy about its avaricious nature. Perhaps there's a psychological effect in making the player wait before they can play again — like building the *craving* part of a habit?

Or perhaps a lack of this delay is to keep the flow going, so to speak? *Ori and the Blind Forest* does something similar in its *Ginso Tree* level. It has very fast restarts, no button or anything, and deaths do not restart the music that's playing in the BG. The result is that deaths do not break the flow of the game, and despite them the whole level feels seamless.

So, are there any studies on this? Barring those, anecdotes? I couldn't find *anything, anywhere.*

# Answer
While it's possible that some delays are deliberately crafted for the reasons you've described, I suspect that in general, they are simply the result of the time it takes the application to perform any reset related activities: loading textures & assets, clearing buffers, reading & writing to save game files and so forth.

In the event that designer / developer is creating an intentional delay, it's most typically based on 'feel' &/or play testing feedback. Often, studios face enough challenges just getting a game to release stage. Things causing obvious & correctable friction (bugs, poor controls, framerate) usually receive priority. Thus, if players say it loads to slow or the designer notices that players are recklessly repeating mistakes, they may attempt to decrease or increase reset times accordingly.

Generally, only the largest of AAA studios hire professional expertise for tuning this level of a games psychological impact. There are some exceptions: anything from the gambling industry and anecdotally, I've heard that some mid-tier mobile developers tinker with this sort of thing (sometimes via AB-testing).

If you're interested in the psychology aspect of this, you might try looking up things related to athletics, attention & performance to repeated tasks (sometimes experiments use games to simulate other activities) and psychological refractory periods.
> 19 votes

# Answer
In my opinion, the primary reason (apart from technical reasons) to consider having a delay before loading or restarting is:

# To give dying some impact

**A short delay**

... is good if you're playing some simple game where you typically die in a minute. Death will rarely have an impact - you die, you restart, a minute later you're back where you were. That's really not a big deal.

You should, in general, avoid delays (intentional or not) with such games.

Death *will*, however, have an impact when you've reached some epic high score, or barely missed it. In such cases it could make sense to add a small delay to give the player some time to process it. This could also help with retention, in that they're presumably more likely to stop playing if you give them some time to think between games, and stopping on a high will leave a better impression of the game. One way this is (unintentionally?) done is by asking whether players want to post their score to social media.

**A long delay**

... can be useful for a game that tries to be more immersive.

A game with no suspense is generally not immersive - it's hard to care if you don't have some "what will happen" / "will we win" moments.

You can potentially do this with good story-telling, or having some other consequences, but the easier way and more common way to do it is with the threat of death.

The problem is that death typically doesn't really *mean* anything in a game - you just reload and keep going. Thus there needs to be some *consequence* to dying. Some games have perma-death, other take away things you earned. If you have neither of those things, you need to have some way to make the player believe that them dying is something they should actually try to avoid, otherwise they'll just stop caring when they die, and stop fearing the threat of death, which could remove all suspense from a game.

Thus you add a delay between dying and the player getting back to where they were.

# In-game versus out-of-game delays

You have out-of-game delays (e.g. loading times) and, in the case of loadable games, in-game delays (how long it takes to play the game until back to where you were).

These two are usually (or should be) closely linked. If you separate those two, that can lead to problems in itself:

* A short time to restart with a long time to get back to where you were in-game means players won't really be given time to process their death and decide if they want to continue, and may be frustrated by the long trek to where they died if they didn't really want to keep playing.
* A long time to restart with a short time to get back to where you were in-game means players will want to restart often, so they'll be frustrated by the long waiting time.

# To make players think

... could be another purpose for a delay, but this applies to different types of games (generally).

Consider some story-focused decision-based game.

Such games are meant to be highly immersive, and death may not really come into play there.

Yet you still wouldn't want players to just instantly restart or load.

You want to give them some time to process and think about what just happened.
> 15 votes

# Answer
This is a question with many answers. Aside from the ones in the other answers, some possibilities are:

* To allow a player to get their bearing. In many games on the more immersive side (or games that put you right in the action after spawning), suddenly respawning can be jarring. A few seconds of waiting time can help players: 1) realise they died 2) prepare for being teleported to a different location 3) prepare to re-engage with the game.
* Preventing the player from doing the wrong contextual action accidentally. If you're busy smashing the "attack" button when you are killed and you respawn into a conversation with a friendly NPC, it'd be annoying if you accidentally killed your friend because you couldn't react to dying in time.
* To balance the game. In team shooters, you want a kill to have an impact on the overall game. If someone you kill immediately is able to respawn, potentially very close to the place they were killed, there is a higher chance of any game ending up in a stalemate, where getting a kill does nothing but push one of the opponents back a bit. Capture the flag scenarios are especially vulnerable to this.
> 5 votes

# Answer
In a game that doesn't require touch input in any particular place, showing the "new game" button immediately runs the risk of the user starting a new game when they did not mean to.

Super Meat Boy! doesn't have a restart button, it just assumes you want to restart until you quit. For me, in that game it serves the purpose of allowing my brain to reset for the next attempt.

Geometry Wars 3 has a Quick Restart button that is only visible for a second or two during the initial Game Over screen. This button is not used for anything else during the game, so as soon as you die you can instant restart if you want. Otherwise, you go to the stats page with the "exit to main menu" and "restart" options.
> 3 votes

# Answer
Having the player watch their character die in an elaborate death sequence and then having them repeat content they already passed is a form of **punishment**. Punishment and reward are essential tools in game design. They are your main methods to guide the player to improve their gameplay. When you punish the player for playing badly, you teach them to recognize their mistakes and avoid them. So a little punishment once in a while can be useful to keep the player engaged.

But too much punishment can quickly turn into frustration. So you want to adjust the intensity of your punishment accordingly to the severity of the mistake.

The majority of games, especially in the AAA sector, are designed in a way that the player will die very rarely. Most challenges are designed with the goal that most players will beat them with their first attempt. You only want to kill the player if the player makes a gross mistakes or refuses to put serious effort into your game. So *if* the player manages to get themselves killed, the punishment should be quite severe. That way you convince the player to take the game serious again. So show the player an elaborate animation where their character dies, do a *slow* fade-to-black, followed by an equally slow fade-in of the words "You died", put them into the loading screen (don't bother to check which assets are already loaded - just dump the whole level and make them suffer through a complete reload) and respawn them at a checkpoint which was a few minutes ago.

On the other hand, there are games where the player is *supposed* to fail over and over again until they succeed. When you design a section in such a game, then you expect that even the most skilled player will fail at least a few times until they finally figure out how to beat your section. You often see such games in the Indie sector. When you are creating such a game, then death is not a punishment. It is your way to tell the players that they haven't figured out the solution yet. So you want to keep the death sequence as short as possible to minimize the punishment effect and let the player retry ASAP. Examples:
> 2 votes

# Answer
Devil's advocate here: It's an addiction mechanism.

If you spend a lot of time on a game you become invested. This 3-5 seconds isn't enough for you to quit or to put it down and also forces you to wait before quitting. This builds both time played and holds attention to the game for short periods of time to pad the playtime and hold interest. Playing again is the reward at the end of a 3-5 second timeout.
> 0 votes

---
Tags: game-design
---


title: Unity pattern for multiple game views

text:
# Question
Title: Unity pattern for multiple game views
What are some proven and preferable patterns to realise multiple "screens" in the game? Not in the sense of displays (monitors) but "views" within the application.

Say it's a Civ/Heroes-type game. We will typically have these screens during the proper gameplay:

* Main map (strategic)
* Battle map (tactical)
* City management screen
* Research screen
* etc.

As you can see, some of them are UI-like in nature but some are full-blown interactive scenes.

We need to be able to:

* Quickly switch between them
* Keep a global game state between them (e.g. the (in-)famous GameManager instance must stay intact)
* Bonus points if able to make a fancy transition (e.g. city screen rolling down from above)
* Bonus points if able to keep one screen (e.g. city screen) only partly covering another (e.g. the strategic map) and both are animated

Theoretical solutions I can imagine (I'm still a Unity noob):

* Separate scenes for each screen. But will the engine be able to switch between them fast? (I read that a scene is akin to a "level" in a traditional game, which usually means a loading time?) Also, how will I track the global state (GameManager)? Can I overlay one screen over another?
* Everything in one Unity scene but multiple cameras looking at different objects, with switching between them or nesting. E.g. one camera looking at the map grid, another at a city screen etc. But then I run the risk of objects from one "scene" (only virtually) affecting others (e.g. lights or particles) unless I place them sufficiently far apart.

Is any of my ideas going in the right direction? Is there a better pattern that I'm missing?

# Answer
The intended solution would be to use a different scene for each of these "views". You can have multiple scenes loaded at once by using `SceneManager.LoadAsync` with the parameter `LoadSceneMode.Additive`. However, loading a complex scene while the game is running can cause notable loading times. One popular Unity game which is plagued by that issue is *Kerbal Space Program*.

An alternative option would be to have each of these views in your scene at the same time, but wrap each of them in an own game object. You can then activate and deactivate these objects as needed. This is less memory-friendly, because no matter what the player does, all views are constantly kept in memory. But inactive views shouldn't consume much CPU power, because deactivated game objects are relatively cheap in this regard (not free, though).

Interactions between the different views can be avoided by putting each of them on a different layer. Set the physics collision matrix so that each layer only collides with itself. Use a different camera for each view, and set its culling mask to only render the view the camera is for. If you want to render multiple views at the same time, use the camera *Depth* and *ClearFlags* to control in which order they are drawn to the screen.

When it comes to placing the views in your scene space, then you might still want to place them far away from each other to make editing easier. But you shouldn't have to worry about intersection effects during the game anymore.

If you want one view to include a cutout of a different view (like a rendered minimap), have the camera for the sub-view render to a render texture and integrate that texture into the host-view. An alternative solution is to change the camera's viewport to not cover the whole screen.

One thing which might get a bit frickly with this setup could be positional audio. Unity only allows one AudioListener in the scene, which you would usually attach to the main camera. When you want some game object to make noise, you would attach an AudioSource to it, and Unity would make sure the sound plays with the expected volume and stereo panning. But when you have multiple cameras in different locations rendering multiple views which all want to play 3D sound effects, then this is not going to work.

One possible solution could be to build an own audio system similar to the one I described in this answer. Build a separate "sound studio" section in your scene with an AudioListener. If you want to play a sound, spawn a new game object with an audio source near that listener to play the sound and remove it when the sound finished playing.

I'm looking forward to playing your game.
> 2 votes

# Answer
You appear to be treating all screens as the same; they are most likely not. What you really have are UI screens, and Maps that form the game world.

As you have pointed, many of these screens are UI like in nature. Thus, the obvious solution is these should be implemented as UI. This will also allow things like fancy transitions. This should be for things like the City Management screen, and Research screen ect. Have them start off screen, and swing into the map when clicked. Or as prefabs that get added to the UI when a button is clicked, and removed when clicked off. You can have UI elements have their own cameras, but just as easily implement something to add and remove, and move about, a single UI layer (or perhaps one per map).

Meanwhile, your "world" maps; the strategic and tactical maps, should be treated as part of the world space. As Philipp has suggested in his answer they should each have a parent GameObject that can be disabled and enabled (thus disabling the map entirely), and likely separate cameras, and place them on different layers to avoid physics interactions.

Finally, while Unity was originally intended to use Scenes for this, a large number of developers do not, and scene transitions can have issues with keeping data between scenes. I would not recommend using scene transitions for this, except *maybe* for transitioning between maps.
> 0 votes

---
Tags: unity, design-patterns
---


# Question
Title: Locking or overriding game object scale property coordinates in inspector window
I want to know if it is possible to lock or override the X and Y coordinates of the scale property in the inspector window so that changing one coordinate immediately changes the other and scrubbing through one coordinate changes the value of the other. If yes, how can it be done?

# Answer
For doing that, you'll need to create something called "Editor script". This is a script (Here: MonoBehaviour) that's being executed in the Editor. In this script you access the Transform component of the object and modify the scale value (Vector3). Here's some example code:

```
using System.Collections;
using UnityEngine;

[ExecuteInEditMode]
public class EditingScaleInEditMode : MonoBehaviour {

    void Update() {
        int x = transform.localScale.x;
        int y = transform.localScale.y;

        //TODO calcualtions
        //example:
        //y = x*x;

        transform.localScale = new Vector3(x, y, transform.localScale.z);
    }
}

```

Just copy and paste this code into a file called EditingScaleInEditMode.cs and add as a Component to an active GameObject in the hierachy.
> 1 votes

---
Tags: unity
---


# Question
Title: How to change object curve path in playmode in Unity?
I would like to make some sort of this simulation below, where user can interact with the white rod and drag it into the magnetic fields, which in resulting the blue line that represent the magnetic field of the permanent magnet to move in semi-circular motion.

I managed to get that kind of effect using animation

I wish I do not have to make an animation for it by manipulation path for the sphere to be automatically correcting it's own path after colliding with the round object since the sphere will suddenly moving faster than usual when colliding with much bigger round object.

I have tried using splines etc, but most tutorial I've seen are not editable in play mode, which is I cannot alter any of the curve values inside my script. So can anyone could provide me some insight or another better alternative than this? I've been stuck here for three days now.

Thanks!

EDIT:

# Answer
> 0 votes
So I decided to use Line Renderer instead and implemented Bezier spline on it, and I managed to get the same result as the first picture where I can control each points that will effect the Line Renderer curves as well. Here is the link of the tutorial.

---
Tags: unity, movement, path
---


title: Confused by scaling, units, and more

text:
# Question
Title: Confused by scaling, units, and more
Ok, so I've already waded through a bunch of questions around this, and it's just making me even more confused.

Let's say I am trying to model a card table in a 2d game. Behind (beneath) the table is a quad with a floor texture. The "table" is a sprite that is just an oval (using basic shapes at this stage until I have real artwork).

I've read plenty of questions on how to scale to different device resolutions. And, that is certainly one way to do it (bit seems like a lot of work). I've also read posts about changing the size of the orthographic camera to match the device (this seems easier). But i'm left not quite understanding what the frame of reference is.

Let's say I design the game to work in 16:9 at HD resolution (1920x1080). I size the "floor" to fill the entire space (and maybe extend a little beyond). I size the "table" to fit within a smaller portion of that space.

If you have a fixed scene (ie, not a scroller), and you want the contents to fill the entire viewport, what is the best way to go about this? Scaling the objects, scaling the camera?

As far as units, what's the best choice? 1 PPU? What rule of thumb do you use when choosing PPU? What are the reasons to choose different PPU's?

I think i'm missing the forest for the trees. I understand so many of the basic concepts from reading so many questions, I just don't know how to put them together and when to choose which method.

# Answer
> 2 votes
When your game is rather UI-heavy (you have lots of buttons, text fields and containers which hold card images) then you might want to consider to build most of your game with the UI system. It is pretty well-equipped to handle responsive layouts which automatically fit to the screen size and aspect ratio (See the layout elements for details).

But if you prefer to use objects in world-space instead, then your primary tool to control how much of the screen is visible is the camera size. The camera output will render that amount of view-space by sampling it in the current screen resolution. The size of the camera is the vertical size. The horizontal size is derived from the screen aspect ratio.

So if you have an orthographic camera pointing at `0 : 0`, your camera size is 5 and your horizontal to vertical ratio is 1.777 (16 divided by 9), then your visible world area reaches from `-8.888 : -5` to `8.8888 : 5`.

If you are using a perspective camera, it gets more complicated, because you need to take distance and FOV angle into account. But you said you are creating a 2d game, so you are likely not using a perspective camera anyway.

If you want specific images to appear larger or smaller, then there are two ways to control this:

* The "pixels per unit" value in the import settings of the image asset. For example, if you have a 128px by 256px card image, and you want that image to cover 1 unit by 2 units in your game world, you would set the PPU value to 128.
* The scale-values in the transform of the game object.

I would recommend you to go with the first variant, unless you want certain objects to be larger or smaller than usual. The usual intention of scale is that a scale of 1 means "normal size" (whatever "normal" means in the context of your game). You might notice that any new object you add to the scene starts out with a scale of (1:1:1). So if you want another value than 1 to be the "normal" value, then you will have to adjust it for every new game object manually, which would be inconvenient.

---
Tags: unity, geometry, scale
---


title: CS 1.6 server's request cartography

text:
# Question
Title: CS 1.6 server's request cartography
Is there a way to request a CS 1.6, CS:Sourse or CS:GO servers to get the location coordinates of the recent deaths of players on the game map?

PS I'm using C# for my project

# Answer
I know you are using C# for the project, but amxmodx & sourcemod can be used to achieve this. They are third party addons you can make plugins for.
> -1 votes

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


# Question
Title: How to collapse a structure after procedural destruction
When considering this temple structure with procedural damage in pink:

How can I efficiently determine the collapse of such structure as below?

Even if the model is defined on a voxel grid, it would still require possibly wide-ranging searches for connected-ness?

In the 2D case, flood-filling and labeling disconnected components is probably doable, but what about the 3D-case?

Can this be done without traversing the entire world space, every frame -- which I imagine, wrecks havoc to a data cache?

Lastly, what is the technical term for this problem of "making stuff fall down after procedural damage?"

# Answer
> 1 votes
I have done pretty much exactly this, in a 3d world. The key to not requiring processing the entire world is to focus on what is making the change; the removal of a voxel. The algorithm on removing a voxel (either by the player or procedurally\*) would be as follows

1. Voxel is removed
2. Determine non air blocks previously connected to the removed voxel
3. Each of those blocks is marked as being in its own region (so up to 6 regions)
4. Iterate over the regions and expand them based on connections, **always process voxels closest to the removed voxel first**. If a region cannot expand mark it as "finished"
5. If a region expands into annother region combine them.

With this you very quickly end up with 1 of 2 results:

* The (up to 6) regions combine; no detachment occures
* All but one region is "finished" (i.e. can't expand anymore) and there is one unfinished region; the unfinished region remains part of the original world, all other regions detach.

As you can see in your diagram you'd very quickly loop round the arch and connect the 2 initial regions. on the other hand if the damage was a bit more extensive on the left you'd very quickly finish one of the two regions (detaching the top) and leaving the bottom (unfinished) region as part of the main world

\*You can probably get clever when removing many voxels simultaneously to avoid repeated work but this is a good start

---
Tags: physics, procedural-destruction
---


# Question
Title: "Create Test Script in current folder" button is grayed out in Unity
I thoroughly read the Unity Test Runner documentation.

It is said in the documentation that the button may be disabled only if the creation of the script will lead to an error.

> This option is disabled if adding a test script would result in a compilation error.

But I do not understand this. How could a creation of the script possibly lead to an error?

I will be grateful for any help provided.

I found here a little bit more info, but it did not help me out.

# Answer
To enable **Create Test Script in current folder** button you should change **Project** presentation to **Two column layout**.

Then choose **Editor** folder.

And then open or click **Test Runner** tab - it works!
> 0 votes

# Answer
That button is disabled to prevent you from creating a Test Script in an unsupported location.

According to the Unity Test Runner documentation you linked, tests need to be placed in a special folder such as an Editor folder. Valid locations:

* Project Editor folder
* Assembly Definition file that references test assemblies that are Editor-only
* Precompiled assemblies that are in the Project’s Editor folder

A test script outside these valid locations would result in a compilation error (in Unity 2018.1) because `UnityEngine.TestTools` and `NUnit.Framework` namespaces which are required for test scripts would not be recognized.

To fix this issue, use that Test Runner window when you're in an Editor folder (or another valid location). The button will be enabled once you open or click on the Test Runner window while your Project is at a valid location.

For PlayMode tests, for that button to be enabled, you also need to make sure that "Enable playmode tests runner" has been toggled on in the Test Runner context menu. (The context menu button is at the top-right corner of the Test Runner window, just under the "x" button to close.) Once this is enabled and you re-open the Editor as prompted, the Test Runner window should look like this with the button enabled:

(Also, see Unity's documentation on Special folder names for more details about the Editor folder.)
> 1 votes

---
Tags: unity
---


# Question
Title: How to make a motorcycle running on a vertical circular track(loop-da-loop) without falling down due to gravity?
I am currently developing a game, motorcycle type game. Of course, my map is not just made up of simple line or curve. For example: a vertical circular track in the map. i've seen most 2D motorcycle games have this design.

How do you prevent the motorcycle from falling off the vertical circular track by correlating the motorcycle's forward speed? If the forward speed is 0, it will fall down naturally, because this is the physical essence, but if the speed is fast enough, it should firmly grasp the track and not fall down. so how to exert force on it to counteracting gravity? what's math behind it? looking forward to your reply,i really appreciate it, thank you!

# Answer
A proper looping should work out-of-the-box in a good physics engine. "Proper" in this context means that the upside-down section is constantly curved. As long as the curving forces the vehicle to change its direction, the resulting ~~centrifugal~~ ~~centripetal~~ whatever force should cause it to cling to the track.

If it doesn't work, then possible reasons could be:

* The vehicle is not fast enough
* The looping is not tight enough
* The collider of the looping is not smooth enough
* You are somehow adding artificial force or torque which interferes with the simulation
* The physics engine itself is not very realistic

But when you want the vehicle to drive through a half-loop and then drive along a straight segment upside-down for a while without falling: I'm sorry, but this is not how physics work in real life. So if your physics engine makes the vehicle fall off in this situation, then it is working as intended. So if you want the players to be able to drive on the ceiling under certain conditions (which I can understand, because it looks and feels awesome), then you need to cheat. Detect this situation and temporarily switch off gravity for that vehicle. Remember to switch gravity back on again if the wheels disconnect from the straight section for any reason, if the player breaks or if the straight section ends.

I'm looking forward to playing your game.
> 2 votes

---
Tags: mathematics, box2d, physics-engine
---


# Question
Title: Unity: How to apply bloom to only some objects in the scene?
In my game I want to apply bloom, from the standard assets, to only a few objects in the scene. To do that, I set up 2 cameras at the same position and orientation, one with the bloom component and the other without. Then I put the blooming objects on a "Bloom" layer, set the blooming camera to only render objects on this layer, and the main camera to render everything else.

Then I noticed that, if the main camera has a depth lower than the bloom camera, then the bloom camera will apply bloom to everything in the scene. I guess that's because the bloom effect works on everything rendered up to the point the script is executed.

So I made sure that the bloom camera has the lowest depth and clears with a solid color. Main camera does not clear. However, now I lose the illuminated pixels around the blooming objects. I guess they are overwritten by the main camera, since the blooming camera probably did not give them any depth.

Here's a simple scene to illustrate the problem:

Currently the game looks like this:

If I swap the configuration of the 2 cameras (Main camera: lower depth, clear with solid color; Bloom camera: higher depth, don't clear), the game looks like this (exaggerated for demonstration):

What I want is the yellow object to look like that in the last image, and the purple object to look like that in the second last image. How?

Because of company policies, I am limited to Unity 5.4.1f1, and cannot use anything not made by Unity in the Asset Store.

# Answer
Bit late, but here is how you do it with emission/HDR. Just use one camera that renders everything. Make sure "Allow HDR" is checked. Add a post-processing profile with bloom enabled, and set the bloom threshold to 1. This prevents anything non-HDR from getting bloomed, so normal lighting/materials are unaffected.

Then you can simply choose the models you want to bloom, and enable emission on their materials.

Choose the hue to set the bloom color, then set the brightness to set the amount of bloom. You can add extra amounts of bloom by setting the number to the right of the color selector to go past a brightness of 1.

If unintended objects in the scene are receiving too much bloom, you can turn down the bloom threshold and turn up the brightness on your emission materials.
> 4 votes

---
Tags: unity, rendering, bloom
---


# Question
Title: Create a white background for the texture and then blend using GLSL
I have a transparent png texture and I'd like to create a white background and then blend this on top of that. Is this possible using just GLSL? I can't multiply, add or mix colors because I don't want to overlay the color white. I want it to be in the background of the texture.

I can achieve what I want by creating 2 objects with the exact same dimensions and position, set the color of the object behind to white and the object in the front to the transparent texture. But this seems less than ideal to me.

Any suggestions will be much appreciated!

# Answer
> 1 votes
Okay this is explained on this page. The following code in the fragment shader works perfectly for me:

```
#version 330 core
uniform sampler2D in_texture;
uniform bool fill_transparent;

in vec2 tex_coords;
out vec4 vertex_color;
void main() {
  vec4 vcolor = texture(in_texture, tex_coords);

  if (fill_transparent) {
    vec4 white = vec4(1.0f, 1.0f, 1.0f, 1.0f);
    vertex_color = (vcolor * vcolor.w) + (white * (1 - vcolor.w));
    // vertex_color = mix(white, vcolor, vcolor.w); // This also works.
  } else {
    vertex_color = vcolor;
  }
}

```

---
Tags: opengl, glsl
---


# Question
Title: How to make a 2D sprite slowly vanish as it crosses a line — as if disappearing behind a wall?
...Except there is no wall. Only one of its edges.

Here is what I mean. Notice how the lines "sink" into the center square.

I've been trying to do something very similar, in Unity. My approach is to detect when the lines come into contact with the center square (hexagon, in my case), and first initiate an animation that decreases the width of the lines, precisely timed via math to last exactly as long as needed.

But there's a problem. The animation doesn't play. I've spent the last few hours debugging it, to no avail, and now have finally given up, because the problem is too complex to post here. Too many variables.

Are there any better methods of achieving this?

My own, even if it had worked, wouldn't have been perfect, because the width would've decreased on *both* sides (of the line running in the middle of the thick squares or hexagons that are to disappear), giving it a strange, swallowing effect, but I'd be satisfied, since it's just a practice project.

So, I'm giving up on this approach. What are easier ways to do this? (Preferably in Unity, but I'll take anything.)

**Hasty edit:** Keep in mind that my "lines" are not sprites but line renderers, but I'm looking for ways to work on either.

# Answer
> 1 votes
# Use a Depth Mask

A Depth Mask shader renders an object only to the depth mask, causing objects rendered after it (and behind it) to be invisible, while objects drawn before the depth mask (on a previous render pass) are visible as normal.

You may have to play around with shaders a bit to get things to render in the right order, but its just a matter of setting their queue in the shader tags; e.g. `Tags {"Queue" = "Geometry+10" }` or `Tags {"Queue" = "Geometry-1" }`, etc. Some shaders might expose this value as a configurable property in the inspector. Note that the depth mask shader linked is set to run after Geometry objects, but you might need it to run *before,* hence the queue number. See subshader tags for more information.

As an example (that I can't access at the moment for pictures) I needed to create a second standard shader that ran before the depth shader (which also ran before the default shader) so that I could layer objects the way I wanted, so that I could create the effect of a pit in a floor without having to remove the floor. Or how Offworld Trading Company does its buildings:

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


# Question
Title: World position reconstruction from depth fails when viewport size does not match window size
I'm facing very strange issue. My code for world pos reconstruction works correctly when the viewport size is equal to window size (or framebuffer size in other words). Below is the part for reconstruction to view space, later I multiply the result by inversed view matrix:

```
vec3 posFromDepth(in vec2 Tex, in float depth) {
    vec3 pos = vec3(Tex, depth) * 2.0 - 1.0; // clip-space position

    float z = -projection[3][2] / (pos.z + projection[2][2]);
    float x = pos.x * halfTanFovX * -z;
    float y = pos.y * halfTanFovY * -z;

    return vec3(x, y, z);
}

```

When I change the viewport light and shadow calculations seems to be incorrect. The shadows for example instead of being "glued" to the object, floats a little bit along with camera movement.

When I switched my deferred renderer to use world pos stored in G-buffer then everything was calculated right. Is there some transformation of texture coordinates which I'm missing? I tried pass fullscreen quad coords in vertex attributes and compute using below formula:

```
gl_FragCoord.xy * texelSize

```

but the results were the same.

I'm searching for the issue more than week and slowly running out of ideas what could be wrong. Maybe you'll come up with something useful.

# Answer
Looks like I found the solution and it was pretty obvious but I did not found similar case in any website which mentions about position reconstruction.

In my code I used texture coordinates computed using below formula:

```
gl_FragCoord.xy * texelSize

```

where `texelSize` is just an inverse of screen width and height. Then I used the same texture coordinates to define xy position in clip-space coordinates. So I **transformed** screen space coordinates to clip space coordinates.

The formula to perform such inverse transform is

```
vec2 clipPos = ((2.0 / screenSpace.xy) - (2.0 * viewport.xy)) / viewport.zw - 1.0;

```

where `viewport.xy` is an origin of the viewport and `viewport.zw` are width and height of the viewport.

If viewport is the same as the screen then it's origin point is equal to 0 what simplifies the equation to the one used by me. And that's why it worked in that case and did not work for viewports with different origin and size.

Hope it will be helpful for others.
> 0 votes

---
Tags: opengl, depth-buffer, deferred-rendering, viewport
---


# Question
Title: How to implement a clipped shadow in 2D?
I want to create a shadow effect similar to the one found in JoyMasher's Blazing Chrome.

Notice that the shadow clips when you're on a ledge, and projects to the geometry below.

Currently, my shadows are just sprites which I disable when the character is not grounded.

I don't care how JoyMasher did it, I just want to achieve something similar.

**How might I achieve an effect similar to the one in Blazing Chrome?**

I am working in Godot, but would be fine with an engine-neutral description of a technique.

I have access to all the normal stuff (raycasts, shaders, and so on). That said, I am working in pure 2D, so I can't use any kind of 3D light source emitting downward to achieve the effect.

# Answer
> 4 votes
1)Cast a set of rays from origin to the ground evenly distributed through the width of your object.

2)Draw your shadow as a small portions of black sprites with varying height so you can round the edges. Make sure width of a sprite portion is enough to cover distance between rays.

3)Tweak height of shadow sprite portions and make sure your shadow looks as you want it to look.

As a way to optimize algorithm, you can also pre-calculate ray hits for the whole stage and then only check X coordinate of the object along with its width to find out which area object covers and then draw shadow according to the ray hits data (shadow portion heights) in the covered area.

# Answer
> 3 votes
If you're rendering the shadow as a texture in hardware (which most 2D renderers do as well), you can specify **texture coordinates** so you only render part of the texture.

So imagine you have a shadow split into two halves here:

You need to render two shadow textures; the left half will have texture x-coordinates going from 0 to 0.5; the right half 0.5 to 1.

3D renderers like OpenGL use ratios for the numbers, i.e. 1 is 100%. 2D renderers tend to specify the actual size of the source and destination rectangles in pixels. For example in SDL's `SDL_RenderCopy` you specify a source and destination rectangle. I'm not familiar with Godot but it appears `draw_rect_region` has a `src_rect` parameter you can try.

---
Tags: 2d, lighting, platformer
---


title: Temporarily ignore collision?

text:
# Question
Title: Temporarily ignore collision?
Same premise as this question. When the ball bounces off of a wall, I want the ball to temporarily ignore all further collision events of the wall it just collided with, for three seconds for example. What's the best way to accomplish this?

# Answer
There are several ways to do this, using a coroutine:

### Disabling the collider

```
GetComponent<Collider>().enabled = false ;
StartCoroutine( EnableCollision( 3 ) ) ;

// ...

private IEnumerator EnableCollision( float delay )
{
    yield return new WaitForSeconds( delay ) ;
    GetComponent<Collider>().enabled = true ;
}

```

### Turning the collider into a trigger

```
GetComponent<Collider>().isTrigger = true ;
StartCoroutine( EnableCollision( 3 ) ) ;

// ...

private IEnumerator EnableCollision( float delay )
{
    yield return new WaitForSeconds( delay ) ;
    GetComponent<Collider>().isTrigger = false;
}

```

### Changing the layer

As indicated by Battle, you can use three layers and the collision matrix. Supposing your wall is in the `Wall` layer, you can have another layer `Ball` and `PhantomBall`. `Ball` / `Wall` will allow collision while `PhantomBall` / `Wall` won't.

```
gameObject.layer = LayerMask.NameToLayer("PhantomBall") ;
StartCoroutine( EnableCollision( 3 ) ) ;

// ...

private IEnumerator EnableCollision( float delay )
{
    yield return new WaitForSeconds( delay ) ;
    gameObject.layer = LayerMask.NameToLayer("Ball") ;
}

```

### Using Physics class

Supposing you have a reference to the wall collider

```
Physics.IgnoreCollision( GetComponent<Collider>(), wallCollider, true ) ;
StartCoroutine( EnableCollision( 3 ) ) ;

// ...

private IEnumerator EnableCollision( float delay )
{
    yield return new WaitForSeconds( delay ) ;
    Physics.IgnoreCollision( GetComponent<Collider>(), wallCollider, false ) ;
}

```
> 3 votes

# Answer
You can use different layers which do not collide with each other. When bouncing one time, wait 0.5 seconds (maybe not necessary), then switch from layer A to B. After 3 seconds, set it back from B to A.

See also:

Unity Editor \> Edit \> Project Settings \> Physics. You will find a table in which you can set it up as you need. Consider using your own custom layers for your game specific objects.

And some documentation.

And how to set layer via script.
> 0 votes

---
Tags: unity
---


# Question
Title: Creating orientation Quaternion from forward vector
Suppose that I have an orientation Quaternion `Q`, I can compute its forward vector from `V = Q * Vector3.forward` easily.

Inversely, **suppose that I have its forward vector `V`, how do I compute `Q`?**

I know that is not possible, please tell me what's needed beside `V`, in order to compute `Q`.

Motivation behind the problem: I have a forward direction of a game object, I want to find out its up direction and its right direction. I can find out all these 3 directions if I have the orientation Quaternion.

# Answer
> 0 votes
You can calculate a `right` and `up` directly from the forward. however it is not going to be a unique `up` and `right` because there is an extra degree of freedom you need to consider.

Code from Building an Orthonormal Basis, Revisited

```
void branchlessONB(const Vec3f &n, Vec3f &b1, Vec3f &b2){
    float sign = copysignf(1.0f, n.z);
    const float a = -1.0f / (sign + n.z);
    const float b = n.x * n.y * a;
    b1 = Vec3f(1.0f + sign * n.x * n.x * a, sign * b, -sign * n.x);
    b2 = Vec3f(b, sign + n.y * n.y * a, -n.y);
}

```

# Answer
> 1 votes
Unless your forward vector is directed exactly up, you can easily find the right and up vectors in Unity:

```
Vector3 right = Vector3.Cross(Vector3.up, forward);
Vector3 up = Vector3.Cross(forward, right);

```

Otherwise, `right` and `up` will be zero and you will be experiencing gimbal lock, a problem that has plenty of different solutions depending on your case. Choosing an arbitrary `right` vector may be a solution. The final code could be:

```
Vector3 right = Vector3.Angle(Vector3.up, forward) < 0.001)
              ? Vector3.right : Vector3.Cross(Vector3.up, forward);
Vector3 up = Vector3.Cross(forward, right);

```

# Answer
> 0 votes
In order to convert a direction-vector to a quaternion, use `Quaternion.LookRotation(v)`. The (optional) second argument isn't the up-vector of the object. It's the up-vector of the world.

---
Tags: unity, rotation, vector, quaternion
---


# Question
Title: Particles in particle system not being lit
I have a sprite that I want to use in my particle systems (it's just 4x4 white square). I'd also like for the particles to be lit (react to lighting within a scene).

Since I'm using 2D Toolkit, I simply created a new tk2d sprite collection of just the single texture, generating normals for it within the sprite collection settings, set the shader for the atlas0 material that's generated to LitBlendVertex and attached the atlas0 material to the particle system.

However, the particles are not reacting to light. I've tried different shaders (both Unity and tk2d) but to no avail. I also messed with the particle systems normal direction setting but still nothing.

Is there something I'm missing to get particles in a particle system to be lit?

# Answer
> 1 votes
Certain shaders don't react to light, and it's possible certain lights won't effect particles.

Make sure the light you're testing with is set to Auto or Important Render Mode.

Also make sure you're using a shader that gets affected by lighting. For performance reasons, none of the default particle shaders are affected by lighting but many are transparent and get affected by their background's lighting (i.e. Additive). For example, a water splash will take on the lighting of its background. If it's in a dark cave, the water splash will be a similar color, thus indirectly affected by lighting.

Do you think you can get away with that? If not, your best bet is to create your own shader.

# Answer
> -1 votes
I had the same problem and was the fog. When i turn it off the particles show up again!

---
Tags: unity, shuriken
---


# Question
Title: Algorithm to produce a 2D 'flying through space' effect like the old Windows screen saver
I am old. My high school maths is a long way in my past and I am struggling to devise an algorithm that will produce a 2D 'flying through space' effect like the old Windows screen saver. It has—

* stars generated close to the screen centre, which move outwards at increasing speed, and
* on a key press, a hyperspace effect is generated with the stars turning to lines stretching to the edge of the screen.

I've figured out that I can use arctan and x,y offsets from screen centre to identify a direction, but given that the trig functions work in a 90 degree field. My old brain is struggling to pull it all together.

How can I create this effect?

# Answer
Every frame—

1. If enough time has elapsed since the last star, create a star at a slight random offset from the middle of the screen. You can get the x and y components of a random point on a circle by (as @Philipp mentions), using `sin` and `cos` on a random angle between 0 and 2π radians (= 360°).
2. Multiply the x and y value of each star by 1+ε to taste of ε. I used a random value between 1.01 and 1.05. This makes stars move away from the middle, faster the further they are from the middle. Greater values of ε cause the star to move faster, creating the illusion that it's closer.
3. Clear the screen. (Or don't, if you want the hyperspace effect. This makes the streaks of stars stay on screen instead of being cleared.)
4. Draw a circle for each star at its position, with a radius scaled to its distance from the middle of the screen.
5. Remove stars that have moved outside the window.

Here's a demo in a runnable JavaScript snippet, using HTML Canvas to render:

```
let canvas = document.getElementById('canvas');
let ctx = canvas.getContext('2d');

let middle = { x: canvas.width / 2, y: canvas.height / 2 }

// Each star is stored as an { x, y } object representing
// its offset from the middle of the screen

function canvasStarPosition(star) {
  return { x: middle.x + star.x,
           y: middle.y + star.y }
}

function starSize(star) {
  // Size is proportional to distance from the middle
  return Math.max(Math.abs(star.x), Math.abs(star.y)) / 100
}

function drawStar(ctx, star) {
  let { x, y } = canvasStarPosition(star)
  let r = starSize(star)
  ctx.fillStyle = 'white'
  ctx.beginPath()
  ctx.arc(x, y, r, 0, 2*Math.PI)
  ctx.fill()
}

let start = 0
let stars = []
let timeSinceLastStar = Infinity
let starInterval = 10000 // milliseconds

function makeStar() {
  let angle = Math.random() * 2*Math.PI
  stars.push({
    x : Math.cos(angle),
    y : Math.sin(angle),
    // The multiplier affects how quickly the star moves.
    // Varying this makes some stars appear closer (faster
    // movement), some further (slower movement).
    multiplier : 1.01 + Math.random() * 0.04
  })
}

function step(timestamp) {
  if (!start) start = timestamp
  var progress = timestamp - start

  // Create a new star if it's been long enough since
  // the previous one
  timeSinceLastStar += progress
  if (timeSinceLastStar > starInterval) {
    timeSinceLastStar = 0
    makeStar()
  }

  // Clear the screen.
  // If you want the hyperspace effect, skip this.
  ctx.clearRect(0,0,canvas.width, canvas.height)

  stars.forEach((s) => {
    // Increase the star's distance from the middle
    // proportionally to its current distance
    s.x *= s.multiplier
    s.y *= s.multiplier
    drawStar(ctx, s)
  })

  // Remove stars outside the view boundary
  let i = stars.length;
  while (--i) {
    let {x, y} = canvasStarPosition(stars[i])
    if (x < 0 || x > canvas.width || y < 0 || y > canvas.height) {
      stars.splice(i, 1)
    }
  }
  window.requestAnimationFrame(step)
}
window.requestAnimationFrame(step)
```

```
<body style="background:black">
<canvas id="canvas" width="600" height="150"></canvas>
</body>
```
> 1 votes

# Answer
Supposed you have a vector described by an angle and a length, you can convert it to its x:y form like this:

```
x = sin(angle) * length
y = cos(angle) * length

```
> 0 votes

---
Tags: 2d, graphic-effects, trigonometry
---


# Question
Title: How to deal with standing/walking models?
I'm developing a game using bullet for the physics logic, but rendering using my own isometric algorithm (sprites). I'm currently dealing with the issue of how the physics object of the player would work when they're standing and walking. Standing is easy enough, the model basically just looks like a rounded rectangle. Handling walking is more difficult.

I have a couple of options on how I can handle walking.

1. Keep the object the same. However, problems arise when the sprite the player sees doesn't match the player's movement (e.g. the player's leg might appear to go 'into' a wall).
2. Alternate between two objects, one standing, one with legs spread as far apart as they would when walking. So, at a certain point in the walking animation, the object would switch to the latter. However, if the player walks into a wall, they would constantly oscillate against the wall.
3. Same as option 2 but have the object where the legs are spread apart active whenever the player walks. This removes the problem with option 2 (as the player would never touch the wall whilst standing), but this is a disadvantage in itself; the player would not be able to climb up walls (assuming I use a system where the player has to be touching said wall), for example.

I'm pretty stuck as to what other options are available, any ideas would be great.

# Answer
Typically the collision capsule remains the same most of the time, and is large enough to contain the full length of the locomotion animation (that is, the diameter is large enough that it will always contain the feet, even at full extension).

In cases where specialized animations extend beyond this basic capsule, additional collision primitives are added temporarily if needed; generally these have different interaction properties *anyway* (such as triggering damage to another actor, in the case of an arm extended outside the main capsule in a punch, for example).

Handling specialized interactions such as "pressing" against a wall or similar kinds of leans that make it *look* like the collision geometry is more complex is generally a matter of detecting the case and applying specialized animation blending.

You can make the collision capsule expand and contract with the bounds of the locomotion animation, if you want (this is more typical in 2D games), but you will still need to handle special cases as such. The oscillation problem you mention is, like the "press against the wall" problem above, a matter of detecting that and setting the appropriate state on the character controller code so you don't keep trying to play the walking animation while the player pressed into the wall (even if you have no sensible leaning animation, you don't want the player walking in place, presumably).
> 1 votes

---
Tags: libgdx, bullet-physics
---


# Question
Title: What is the difference between a "ping" and "RTT" (round-trip time)?
**RTT**, or round-trip time, is the time that it takes to send a message and receive the result from server. As I searched this, this seems to be the same as **ping** in network jargon.

Are there some important differences between the two concepts/terms or ping can be considered as RTT?

# Answer
A ping is a method to measure round trip time.

The process of "pinging" is to send a "ping". A "ping" is a network message which serves no other purpose than to get an immediate response from the receiver. This can be used to measure the round trip time. It can also be used to verify that another system is able and willing to respond to network messages at all. For example, some games use regular "keep-alive" pings so they notice when a player disconnects without logging out properly.

You can also measure round trip time by measuring responses to network messages which are not just pings but actually do have other practical purposes. You can use any network message which results in an immediate response from the other side and where the response can be clearly attributed to the message. But such a measurement might not be as accurate as with a dedicated ping message, because the receiver might require additional time to process and respond to the primary purpose of the message.

However, in general language usage, "ping" is sometimes used as a synonym for round trip time. Especially among players.
> 12 votes

# Answer
While Philipp is mostly right, a ping may not be identical to the round-trip time. It differs in that most ping tests are executed within the transport protocol using ICMP packets. In contrast, RTT is measured at the application layer and includes the additional processing delay produced by higher level protocols and applications (e.g. HTTPS). Here's a blog post that clears up some of the misconceptions around RTT.
> 6 votes

---
Tags: networking, terminology
---


# Question
Title: Is it secure to use UDP socket for a game server?
I'm working on a multiplayer android game with Unity. For server side I use python. There is no login system or username. Basically, there is a matchmaking system and rooms. I send json object which contains room key , position of user and etc. from client to server. Room keys are unique and 10 digit hexadecimal numbers. I use udp socket for communication. Here is my questions.

Is it secure only using udp socket for gameplay. Clients already has source code and can change it easily. So they can change data that coming from client to server. Do I need implement an algorithm to make more secure from hack or cheat? Can anybody change apk file and ruin everything in this game?

# Answer
No, UDP isn't "secure" in the sense that it will prevent hacking or tampering by the client. TCP isn't either, for that matter. If you want to prevent tampering by clients you need an authoritative server to validate the data sent over the network *regardless* of the transport mechanism.

Additionally, or if you don't have a central server you can rely upon (that you're hosting), you can do things to make tampering *harder* such as trying to obfuscate the data you send or implement "voting" mechanisms where all peers in the game vote on what they believe the game state to be and boot clients who differ (who are "cheating").

But ultimately anything running on and accessible to the client can be compromised with effort, and you can only take steps to deter such tampering.
> 2 votes

# Answer
Your question is a bit ambiguous.

First you write "Clients already has source code and can change it easily" and then you ask "Can anybody change apk file and ruin everything in this game?".

When the user has the sourcecode, they can of course change it and build their own APK file which does what they want it to do. And there is no way to detect this kind of tampering via a network, regardless of protocol. So there is nothing you can do on the network level to prevent players cheating by hacking their own game client.

---

But maybe that's not actually what you are asking. Maybe you are asking about a man-in-the-middle attacker tampering with the game by intercepting and manipulating the UDP packets of another player. UDP has no encryption or authentication layer, so if some evil hacker controls a router between another player and your server, they can do that.

Very few games bother to account for that scenario, though. It is usually assumed that a successful man-in-the-middle attack on another player requires more resources and criminal energy than you would see from the average online game cheater.

But if you believe that encrypting your network protocol is a worthwhile endeavour, then you can of course do that. One IETF standard protocol for encrypted UDP is DTLS.
> 0 votes

---
Tags: unity, android, networking, server, socket
---


# Question
Title: How to make a custom event system framerate friendly?
I have a simple event system:

```
class GameEvent{
    float executionTime;
    Action action;
}

class EventMgr : MonoBehaviour{

    List<GameEvent> events = new List<GameEvent>();

    void Update(){

        float timeNow = Time.time;

        for(int i=events.Count - 1; i >= 0; i--)
        {
            if(timeNow >= events[i].executionTime)
            {
                exents[i].action();
                events.RemoveAt(i);
            }
        }
    }

    public void ScheduleEvent(float delay, Action action){
        events.Add(new GameEvent(){
            action = action,
            executionTime = Time.time + delay;
        });
    }
}

```

Then,

I schedule events like this:

```
eventMgr.ScheduleEvent(0.1f, () => {
    // EVENT A - should be fired first
};

eventMgr.ScheduleEvent(0.15f, () => {
    // EVENT B - should be fired second
};

```

Everything works fine when I play on `60 FPS`. `Update()` is fired once every `~0.016s`. When I play the game on a device with `20-40FPS` \- things got a little bit tricky. Events seem to run in an incorrect order (Event B fired before event A).

The only possible cause is of course the framerate itself. If the game runs at `20FPS`, `Update()` would be called less frequently and both of these events would be fired in the same frame - and then, the order of their execution depends on the list itself.

What to do here? Is there any trick to prevent this, is there any pattern for accurate, ordered event system in games which is FPS friendly?

# Answer
This looks like you could solve it with a priority queue or min-heap. The code to process the queue would look something like this:

```
while(eventQueue.Count > 0 && eventQueue.Peek().executionTime <= Time.time) {
    eventQueue.Dequeue().action();
}

```

This means you have only one check to do on frames when no events happen - you don't have to scan the whole list.

The nature of the priority data structure ensures that the next event to fire is always the first one you check, and when multiple events fire in the same frame, you process them in non-decreasing order of `executionTime`.

Insertion and removal from such a data structure are typically logarithmic, so they remain reasonable even for large collections of events.
> 10 votes

# Answer
If sufficient time passes between `Update` calls to trigger multiple events, then as you note the actual firing order depends on the order in which you process the list. Since you process the list backwards you will evaluate and thus potentially fire "later" events sooner.

If you want your events to create an implicit dependency through their firing time (e.g., an event `A` with an absolute time `Ta` must fire before any events with absolute time `Tn` \> `Ta`), then you need to ensure you process them in that order.

In your case, you could just sort the list by absolute time, either before you process it in `Update` or by ensuring during scheduling you put new events in the proper sorted position.

Sorting the list *backwards* by absolute time means you can continue to process it backwards and rely on the efficiency of removing items from the end of the list (versus from the beginning, which would require moving the remaining items down).
> 2 votes

---
Tags: unity, events, frame-rate
---


title: OpenGL scene performance optimization

text:
# Question
Title: OpenGL scene performance optimization
I am writing my 3D engine for Linux, and I ran into a performance problem. What was included at the time of testing:

* Bloom
* DOF (Depth Of Field)
* Soft shadows
* Point light source
* 1k, 2k textures (ambient, diffuse, specular, normal mapping)

And I get only 48 fps

Framebuffer size - 1366x768

Shadow map resolution - 1024x1024

**Nvidia GeForce 920mx, Intel Core i5-6200u**

Here is the order of my actions:

1. Rendering to the shadow map (cost: 0.5 - 1 frame)
2. Basic rendering: drawing shadows, lighting, and more
3. Blur vertically and horizontally (each pass is performed 2 times): bloom with fixed kernel and dof with generated (cost: bloom 10-15 frames, dof 12-16 frames; total = 30 frames)
4. Blending

How normal are the results for this video card? Are there ways to optimize rendering, or is this the norm for this video card? Below is my implementation of the blur.

Fragment blur shader:

```
#version 330

#algdef

in vec2 texCoord;

#ifdef ALGINE_BLOOM_MODE_ENABLED
layout (location = 0) out vec4 bloomFragColor;
uniform sampler2D image; // bloom
uniform float bloom_kernel[BLOOM_KERNEL_SIZE];
vec3 bloom_result;
#endif

#ifdef ALGINE_DOF_MODE_ENABLED
layout (location = 1) out vec4 dofFragColor;

uniform sampler2D image2; // dof
uniform float max_sigma = 8.0;
uniform float min_sigma = 0.0001;

float dof_kernel[DOF_KERNEL_SIZE];
vec3 dof_result;

vec4 tmp;
float fdof;

const int DOF_LCR_SIZE = DOF_KERNEL_SIZE * 2 - 1; // left-center-right (lllcrrr)
const int DOF_MEAN = DOF_LCR_SIZE / 2;

void makeDofKernel(float sigma) {
    float sum = 0; // For accumulating the kernel values
    for (int x = DOF_MEAN; x < DOF_LCR_SIZE; x++)  {
        dof_kernel[x - DOF_MEAN] = exp(-0.5 * pow((x - DOF_MEAN) / sigma, 2.0));
        // Accumulate the kernel values
        sum += dof_kernel[x - DOF_MEAN];
    }

    sum += sum - dof_kernel[0];

    // Normalize the kernel
    for (int x = 0; x < DOF_KERNEL_SIZE; x++) dof_kernel[x] /= sum;
}
#endif

void main() {
    #ifdef ALGINE_BLOOM_MODE_ENABLED
    vec2 texOffset = 1.0 / textureSize(image, 0); // gets size of single texel
    #else
    vec2 texOffset = 1.0 / textureSize(image2, 0); // gets size of single texel
    #endif

    #ifdef ALGINE_DOF_MODE_ENABLED
    tmp = texture(image2, texCoord);
    fdof = tmp.a;
    makeDofKernel(max_sigma * fdof + min_sigma);
    dof_result = tmp.rgb * dof_kernel[0];
    #endif

    #ifdef ALGINE_BLOOM_MODE_ENABLED
    bloom_result = texture(image, texCoord).rgb * bloom_kernel[0]; // current fragment’s contribution
    #endif

    #ifdef ALGINE_BLUS_HORIZONTAL
    #ifdef ALGINE_BLOOM_MODE_ENABLED
    for(int i = 1; i < BLOOM_KERNEL_SIZE; i++) {
        bloom_result +=
            bloom_kernel[i] * (
                texture(image, texCoord + vec2(texOffset.x * i, 0.0)).rgb +
                texture(image, texCoord - vec2(texOffset.x * i, 0.0)).rgb
            );
    }
    #endif

    #ifdef ALGINE_DOF_MODE_ENABLED
    for(int i = 1; i < DOF_KERNEL_SIZE; i++) {
        dof_result +=
            dof_kernel[i] * (
                texture(image2, texCoord + vec2(texOffset.x * i, 0.0)).rgb +
                texture(image2, texCoord - vec2(texOffset.x * i, 0.0)).rgb
            );
    }
    #endif
    #else
    #ifdef ALGINE_BLOOM_MODE_ENABLED
    for(int i = 1; i < BLOOM_KERNEL_SIZE; i++) {
        bloom_result +=
            bloom_kernel[i] * (
                texture(image, texCoord + vec2(0.0, texOffset.y * i)).rgb +
                texture(image, texCoord - vec2(0.0, texOffset.y * i)).rgb
            );
    }
    #endif

    #ifdef ALGINE_DOF_MODE_ENABLED
    for(int i = 1; i < DOF_KERNEL_SIZE; i++) {
        dof_result +=
            dof_kernel[i] * (
                texture(image2, texCoord + vec2(0.0, texOffset.y * i)).rgb +
                texture(image2, texCoord - vec2(0.0, texOffset.y * i)).rgb
            );
    }
    #endif
    #endif

    #ifdef ALGINE_BLOOM_MODE_ENABLED
    bloomFragColor = vec4(bloom_result, 1.0);
    #endif
    #ifdef ALGINE_DOF_MODE_ENABLED
    dofFragColor = vec4(dof_result, fdof);
    #endif
}

```

And C++ code:

```
// configuring textures
for (int i = 0; i < 2; i++) {
    glBindFramebuffer(GL_FRAMEBUFFER, pingpongFBO[i]);

    // bloom
    glBindTexture(GL_TEXTURE_2D, pingpongBuffers[i]);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB16F, ALGINE_SCR_W, ALGINE_SCR_H, 0, GL_RGB, GL_FLOAT, NULL);

    // dof
    glBindTexture(GL_TEXTURE_2D, dofBuffers[i]);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F, ALGINE_SCR_W, ALGINE_SCR_H, 0, GL_RGBA, GL_FLOAT, NULL);
    glClearColor(0, 0, 0, 1);
}

horizontal = true;
firstIteration = true;
for (int i = 0; i < ALGINE_BLUR_AMOUNT; i++) {
    glUseProgram(blusPrograms[horizontal].programId);

    glBindFramebuffer(GL_FRAMEBUFFER, pingpongFBO[horizontal]);

    // bloom
    glActiveTexture(GL_TEXTURE0);
    glBindTexture(GL_TEXTURE_2D, firstIteration ? colorBuffers[1] : pingpongBuffers[!horizontal]);

    // dof
    glActiveTexture(GL_TEXTURE1);
    glUniform1i(blusPrograms[horizontal].samplerDof, 1);
    glBindTexture(GL_TEXTURE_2D, firstIteration ? colorBuffers[0] : dofBuffers[!horizontal]);

    // rendering
    renderQuad(blusPrograms[horizontal].inPos, blusPrograms[horizontal].inTexCoord);
    horizontal = !horizontal;
    if (firstIteration) firstIteration = false;
}

```

Screenshot:

I will be grateful for your answers

# Answer
Bottlenecks come in many forms.

A quick way to rule out if the fragment shading is the bottleneck, render in a small 320x200 window.

If the frame rate stays the same, your bottleneck lies somewhere else. If it increases, your fragment shaders are too expensive.

Next, make your post-processing steps optional. Switch on/off DOF and BLOOM, and see what happens.

Also, disable texturing, and see its impact.

And try skipping the shadow map generation, as it could be the limiting factor as well, or cause synchronization issues.

You may have unneeded GPU/CPU synchronization going on if you upload stuff to your GPU every frame. Look into buffer orphaning.

There are some free tools available to profile your GPU. Look into Intel's Graphics Performance Analyzers and the similar Renderdoc tool.
> 1 votes

---
Tags: opengl, optimization
---


title: Determining Player "Forward" in VR

text:
# Question
Title: Determining Player "Forward" in VR
EDIT: I've removed some vagueness and replaced it with more of a description of the intended use case.

I'm looking for some suggestions for ways to infer what the player's "forward" vector is in a room-scale 360 experience. I'm not currently worried about extreme edge cases, especially if it sounds like the user may be intentionally not doing the intended thing, but I am interested in getting a decently accurate forward vector when they could be looking or facing any direction. I also don't care about "upness" or magnitude of the vector, so it'll end up being projected onto the (Unity's) X/Z plane and normalized.

I'm exploring the idea of punching as a means for locomotion. The player should move in the direction that they punch, which in itself I feel is an easy solve. The problem is, much like the problem of arm-swing movement, it is very hard and unnatural to punch exactly straight forward. People tend to punch at least a little across their body. This causes the player to weave back and forth through the world, like some sort of drunken master. I don't like the idea of using the headset's forward vector either. I want the player to be able to look around while playing; I feel it is an integral part of the experience to be able to look ahead one punch and plan the next move.

It's also important that sensor set up and room orientation should not be taken into account. I'm looking for something that could work in a large space with 360 tracking.

I've considered:

* Grabbing an average position of the hands, getting the vector from the head to this new position. This is where I've spent most of my time, I think. I've tried a weighted average, where hand position gets more or less weight depending on distance from head. In practice, this ends up exacerbating the problem
* Grabbing the vector from the head to the dominant hand
* Dropping a raycast to the floor and using the hit geometry's forward vector
* Getting a complicated IK rig setup, potentially hiding the geometry, and using the rig's hip placement/orientation to infer "forward"

None of these quite feel right to me, although the average-hand-position vector feels the right-est.

Is this a solved problem that I'm just not searching hard enough for? Anybody else have interesting solutions to this problem? Am I being too vague and should really just seek out a solution for a much more specific use-case and be happy with that?

# Answer
> 2 votes
# You need a calibration step.

Exactly what you are measuring isn't that important (ie all of your suggested solutions should function) but you need to compare with the player's sense of direction. Its why (early) touch devices and current VR tech have it: the programmers can't be sure that their assumptions are true, but I'd they're *close* they can get the user to configure offset approximations (its also fun to mess with these calibrations, just don't mess with it so much you can't get back into them!).

Present a target to the player and all them to punch at it. Do this several times against targets in different places and you can get a feel for where the player expects "forward" to be (essentially by averaging the measured vectors together and computing an offset from mathematically precise). Eg. if you have them punch forward three times and left three times, you average both sets of 3 separately relative to the mathematical direction and can interpret any direction in between.

You'd want to take readings in three or four directions a bunch of times, then a roundup test against six or eight directions to check the results (eg left 3 times, right 3 times, forward 3 times, and up 3 times, then once each left, right, up, down, a little left and a little right) to check your computed offset against an unseen direction.

Oh and then round to the nearest 5 degrees during play. The player won't ever be 100% on target, but give a little leeway ("ehh, that was forwardish, we'll move the player mathematically forward") and they won't even notice (because the system works!). You can even autocorrect / aim assist to see if solid ground, goal, or similar object exists around (within a small distance of) the selected point. If so, move the player there instead. It allows some flexibility, as the player will aim in a general direction and the system will be able to intuit "yeah, that's what they meant."

---
Tags: game-design, transformation, virtual-reality
---


# Question
Title: How to move the object with same pace regardless their target distance?
so I tried to get those first and third ball to be able to move with same pace no matter how curvy their target path is, I tried to get the y position of the target that the ball is moving to, but I cannot figure out how to actually control the speed of the ball when the target y position is higher or lower than the ball y position, it seems that the ball will keep on speeding and not at the same pace with other ball as well.

Here is the code so far..

```
float yDistance = transform.position.y - targetWayPoint.transform.position.y;

    if(yDistance != 0)
    {
        speed = speed + 0.5f;
    }
    transform.position = Vector3.MoveTowards(transform.position, targetWayPoint.position,  speed*Time.deltaTime);

    if(transform.position == targetWayPoint.position)
    {
        currentWayPoint ++ ;
        targetWayPoint = wayPointList[currentWayPoint];
    }

```

Any ideas? Thanks alot!

# Answer
> 1 votes
I assume that the code posted is in some update function? It appears as if you are continuously increasing the speed if you increase the y distance. Doesn't seem like that is necessary.

# Answer
> 1 votes
What you want to do is calculate the distance between each waypoint, and then adjust the speed so the time it takes to reach the next waypoint is the same.

First, decide how long you want it to take the sphere to travel between waypoints. Let's say you want 1 second, so...

```
travel_time = 1.0;

```

Next, assume you are at a given waypoint, and want to figure out how fast to go to the next waypoint. Start by calculating the distance to the next waypoint...

```
distance = calculate_distance(current_waypoint.position, next_waypoint.position);

```

Now given you have a distance, you can calculate what speed to use...

```
speed = distance / travel_time;

```

So if you have a distance of 1 for example, the speed is 1 / 1 = 1. But if the distance was 2 (twice as far), the speed is 2 / 1 = 2 - meaning you have to travel twice as fast to cover the distance in the same time.

If you recalculate this speed at each waypoint, that will make the spheres all travel across the lines in the same amount of time, meaning they will both reach the far side at the same time.

**Notes on your code**

Your code has a couple of errors in it I wanted to point out. Fixing these won't get you the desired outcome, but I thought it would be important to point them out for your education.

First, the problem with your current code is that when you grab and move the waypoint upwards, you're triggering the following bit of code...

```
if(yDistance != 0)
{
    speed = speed + 0.5f;
}

```

So as long as your waypoint is moved up, the speed will just continue to increment more and more, making the sphere move faster and faster. It will just keep getting faster and faster until you move it back down to zero.

Second, I think this test is not doing what you think it should...

```
if(transform.position == targetWayPoint.position)
{
    currentWayPoint ++ ;
    targetWayPoint = wayPointList[currentWayPoint];
}

```

You are trying to compare the two positions to determine if the current position is the same as the target waypoint. But unless the positions are EXACTLY the same, this won't work. So if the position goes just slightly past the waypoint, then they won't be equal - but clearly the sphere will have reached the waypoint. Instead you'd want to do something simple like check if the sphere X value was \> the target waypoint X value.

---
Tags: unity, movement-prediction
---


# Question
Title: OpenGL different sized textures for the same framebuffer?
With OpenGL 3.3, is it allowed/okay to bind different sized textures to a frame buffer?

I.e.

```
glBindFramebuffer(GL_FRAMEBUFFER, fbo);
glFramebufferTexture2D, GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texture200x200,0);
glViewport(0,0,200,200);
/*....
some time later
... */
glBindFramebuffer(GL_FRAMEBUFFER, fbo);
glFramebufferTexture2D, GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texture500x500,0);
glViewport(0,0,500,500);

```

I.e. `texture200x200` is a 200x200 sized texture, and `texture500x500` is 500x500, `fbo` is the same framebuffer each time.

My use case is a need to render to texture several times in a frame, and each of these textures is arbitrarily sized.

# Answer
There is nothing in the documentation that suggests that you can't do this, and thus it should not cause a problem.
> 1 votes

---
Tags: opengl
---


# Question
Title: Project line segment onto a vertical line
If I had a vertical line (which its *x* is 0) and 2 vectors which connected together to form a line segment, would it be possible to "project" the line segment onto the vertical line?

Eg.

If all I had was *Vector 1* and *Vector 2*, would it be find where *Vector 3* is along the vertical line?

# Answer
> 0 votes
If vector1 is `(x1, y1)`, vec2 is `(x2, y2)` and vec3 is `(x3, y3)`, and the vertical line has the equation `x = c`, then

```
x3 = c
y3 = (y2 - y1) / (x2 - x1) * (c - x1) + y1

```

---
Tags: mathematics
---


title: Keeping 2 objects within cameras view

text:
# Question
Title: Keeping 2 objects within cameras view
I have two object to control and I wanted to keep them at cameras view without adjusting the cameras size but the camera can move only in positive y-axis meaning ones it goes up it shouldn't move down but it's okay if one object gets out of bounds. Since its 2D the camera is Orthographic view.

# Answer
> 1 votes
If you can't make the camera view larger, then just set the camera's y position halfway between the two objects'

```
cameraY = (obj1Y +obj2Y) / 2

```

To make it stop at y = 0, use Mathf.Max:

```
cameraY = Mathf.Max(obj1Y + obj2Y, 0) / 2

```

This won't work if the camera can't display the two objects at once because they're too far apart

---
Tags: unity, camera
---


# Question
Title: Is Apple Game Center Multiplayer Online?
I'm trying to build a real-time multiplayer game on Unity. I was thinking of using services such as PUN or UNet, but then I ran into Game Center's multiplayer API.

I've read that Apple doesn't give servers and only provides matchmaking services. Is that true? How does that work? Would I still need PUN/UNet with Game Center?

I guess what I'm trying to ask is, will Apple host my game's multiplayer instance, where position of players is synced across, and replace PUN/UNet?

Any help is appreciated. Thank you. Also, if you can provide a source with your answer, that'd be great.

# Answer
# So, its a little weird, but...

I used it once a number of years ago using Prime31's Game Center plugin. What it does is facilitate two (or more) copies of the game communicating with each other in a serverless multiplayer context.

What that means is: one of the clients *is also the server* (they are the "host" and act like a server for all of the connected clients).

You *can* do multiplayer this way and for some games it works really well (things like Space Team, Spyfall, or Codenames, where 'cheating' isn't important because the game is short and fast paced and switching to a different person as host if someone's cracked their copy is easy.

What you *can't* do is any thing that requires:

* A lot of server computation (e.g. lag compensation for a first person shooter: your host won't have the system resources)
* Any persistent data storage (e.g. any sort of RPG with stats and items, as changing hosts means restarting)
* Lots of players (you're going to be harshly limited by the network capacity of the host)
* Out-of-line-of-sight multiplayer (Game Center is set up to work on single-wifi-network or bluetooth connections)

In my project I was making a Tower Defense game and used Game Center to let each copy of the game that was running know about where different towers had been placed by the other people playing and give a damage, rate of fire, special effect, or range boost to towers placed in the same spot. So a poison tower placed by Player 1 would mean that Player 2's bullet tower in the same position got a small DOT effect. If Player 3 also placed a poison tower, then their tower and P1's tower would do slightly better poison, and P2's bullet tower's small poison effect would increase (the bullet tower also applied a small buff to the poison towers, but I forget what it was).
> 3 votes

# Answer
Draco18s is mostly correct about the no-server limitations, but in fact GameCenter does allow multiplayer across the internet. I have released at least two games that use multiplayer via GameCenter on iOS and both are successful at playing with any opponent, regardless of where they are. You simply start a multiplayer game and either choose a random opponent(s) or send an invitation to somebody via a built-in integration with the Messages app, or pick a “nearby” player from a list, as long as both devices are running the app. I’m not sure exactly how it determines what devices are nearby to put into the list, but WiFi is not even required to use it.

In any case Prime31’s plug-in is just a wrapper around the native functionality.
> 2 votes

---
Tags: unity, multiplayer, ios, game-center
---


# Question
Title: How are semitransparent polygons rendered in the correct order?
It is my understanding that while opaque triangles can be rendered in any order thanks to the Z buffer (especially when rendering in hardware), semitransparent triangles cannot. Instead, they need to be rendered from furthest to closest (from the camera's point of view) in order to get the correct result. If you render them in the wrong order, the result will be incorrect (and may even suddenly visually change if the rendering order changes as the camera moves).

Sorting polygons, even triangles, from furthest to closest is actually a difficult problem. In fact, in the general case it's an impossible problem (even with triangles) because in some pathological cases there is no unambiguous order in which they can be rendered correctly. For example, three triangles may overlap each other in a cyclic manner so that each one is partially in front of another (and thus it's impossible to render them without error, unless they are opaque and using a Z buffer, or without splitting at least one of the triangles). Using a naive sorting of triangles is very inefficient, especially if the need arises to split a triangle due to a cyclicity problem.

I know that there exist clever data containers that solve this exact problem and allow very quickly traversing the triangles from furthest to closest, regardless of where the camera is located, without the need to sort anything, and with any splitting of triangles already having been done in preprocessing. One example of such a data container (which name I can't remember now) is a binary tree where there's a triangle at each node which splits the entire space into two halves, with the rest of the triangles being on the left or right branches depending on which side of the plane defined by this triangle they are (and if a triangle intersects said plane, it's split in preprocessing into two using that plane). This binary tree allows traversing all the triangles from furthest to closest with a simple dot product (against the normal vector of the triangle) comparison at each node, regardless of where the camera is located.

While this construct is very clever, there's one problem with it: It only works with a completely static scene. The tree has to be precalculated (and triangles possibly split) as a preprocessing step (usually while building the project). Doing it at runtime on each frame would be madness.

But games use dynamic semi-transparent polygons all the time, for all kinds of particle effects etc. So how are they rendered properly?

# Answer
# TLDR; this is one of the holy grails of computer science.

It is *very hard* to correctly sort transparent polygons, especially when they intersect. See also painter's algorithm and this SO question.

There've been some advancements in this regard, such as detecting intersecting surfaces and automatically splitting these polygons so that they can be rendered in the correct sorting order, but I can't find that paper now, and it still doesn't help in the case of 3 mutually overlapping polygons as there's no intersection on which to split.

This paper suggests using a per-pixel sorting, effectively using a raycast to figure out which object is on top and sorting that way (however this is more computationally expensive, as it requires 2 or more render passes: one for the depth mask and then a second for the actual result). In any case, such solutions are often implemented at a very low level (e.g. within OpenGL) and not modifiable by a game developer in most cases.
> 3 votes

# Answer
**Option 1: Additive blending**

One easy trick you can use for explosions and such is using a special blend function.

```
glBlendFunc( GL_ONE, GL_ONE );

```

This is called additive blending, which is useful if you are drawing things that add luminosity. White smoke clouds, or fire particles would do well with this.

With additive blending, the order in which you draw does not matter. No sorting required, just draw them after the opaque stuff.

**Option 2: screen door transparency**

If you need to draw transparent objects that can darken what is behind it, like glass in buildings, you need something else.

In that case, you should consider screen-door transparency.

It is quite easy to achieve, just discard all fragments on a checker board pattern. This is easily achieved by testing the modulo 2 value of the fragment coordinate.

```
mediump float xm2 = mod( gl_FragCoord.x, 2.0 );
mediump float ym2 = mod( gl_FragCoord.y, 2.0 );
if ( int(xm2) != int(ym2) ) discard;

```

This option is even easier to use: not only can you skip the sorting of transparent objects. You don't even have to draw opaque before transparent geometry!

I find that especially in recent years, this has become more viable because our render resolutions are so much higher now. Take for instance iOS retina displays. The pixels are too small to see, so the checkerboard is no longer visible. You just see a transparent surface.
> 2 votes

# Answer
Thinking about this for a while, some ideas have come to mind to make the task easier. These are purely speculations of mine, and I have no idea if games actually do it like this, or if they do something completely different.

Firstly, rather than treat all the translucent triangles in the entire scene as one huge mesh to render, the scene could use distinct translucent objects (such as glassware, etc), and as long as no such objects ever intersect each other, it makes much easier to render entire objects in the correct order. In other words, you just need to sort entire objects from furthest to closest, and if the objects are not pathological (like two C-shaped translucent objects simultaneously overlapping each other), you can just render an entire object at a time without worrying about the others. (This is in no way a generic sureproof way because, as mentioned, you can create pathological cases with such objects where they simultaneously overlap each other even though they aren't intersecting. But the objects, levels and animations could be designed in such a manner that this never happens.)

Secondly, rendering one translucent object itself becomes easier depending on its geometry. If its geometry is simple enough, its triangles could be sorted by simply comparing their mid-points. (Again, this is in no way a generic solution, but if the objects are designed properly, it could work perfectly.) In fact, some data container similar to what I described above could be used to traverse the triangles in a simpler manner, without having to resort to an actual sort.

Even if the object is too complex for that to work, a binary tree like I described in my question could be used for it, if the object is rigid and never changes shape.

In some cases a changing translucent surface could perhaps still be rendered in the proper order without having to resort to complicated algorithms. For example, a waving water surface could probably be rendered with a naive sorting of the triangles, or even by simply traversing through them in the proper order (especially if they form a grid, which makes traversing them in a proper order very easy).
> 0 votes

# Answer
All the games I've worked on just relied on depth sorting, combined with some carefully control of render order. This works even on a game like Geon: Emotions which featured a transparent game board and overlaid particle effects above and below the board. The state of the art in rendering has changed quite a bit since I last worked on a game professionally, so there may be newer techniques that enjoy success, but I suspect for most games it's just not an issue.

You're correct that there are theoretically pathological states where depth sorting cannot work, issues with large transparent objects, and other edge cases. However, in practice, the solution is usually to just make sure these problems aren't encountered. Game developers can simply design their game to avoid the situations where these methods don't work happening much or, indeed, at all. This isn't unique to transparencies, all games and game engines have their limitations, so part of the skill of game development is to work around these limitations without it being obvious to the player.
> 0 votes

---
Tags: rendering, transparency
---


# Question
Title: Read access violation, pointer was nullprt
Im trying to figure out how to use pointers to make a single instance of an object that in this example will just change direction on x-axis.

Splav.h (eng. Paddle.h)

```
#pragma once
#include "SDL.h"
#include "Prikazi.h"

class Prikazi;

class Splav
{
private:
    int splavTrenutniX = 0, splavTrenutniY = 0; //current x and y axis position of the paddle
    int splavPocetniX, splavPocetniY; //starting position of paddle

public:

    Prikazi *pr; //pointer to the Prikazi (eng. Draw) class

    SDL_Rect rectSplav; //Rect used to store texture of paddle

    Splav(); //default constructor, used to initialize paddle for 1st load or reset
    Splav(int trenutniX, int trenutniY); //overload constructor where current x and y points on axis become points on paddle movement

    void gibanjeSplavi(); //move the paddle

};

```

Splav.cpp (eng. Paddle.cpp)

```
#include "Splav.h"

Splav::Splav()
{
    splavPocetniX =pr->sirinaEkrana / 2; //sirinaEkrana = Screen width
    splavPocetniY = pr->visinaEkrana - pr->visinaSplavi; // screen height- paddle height

    rectSplav.x = splavPocetniX;
    rectSplav.y = splavPocetniY;
    rectSplav.w = pr->sirinaSplavi;
    rectSplav.h = pr->visinaSplavi;
}

Splav::Splav(int trenutniX, int trenutniY)
{

    splavTrenutniX = trenutniX;
    splavTrenutniY = trenutniY;

    gibanjeSplavi();
}

void Splav::gibanjeSplavi() //when paddle starts to move
{
    const Uint8 *tipka = SDL_GetKeyboardState(NULL);

    if (tipka[SDL_SCANCODE_A] && rectSplav.x > 0)
        rectSplav.x--;

    if (tipka[SDL_SCANCODE_D] && rectSplav.x < 1280-pr->sirinaSplavi) //1280-200(paddle width)
        rectSplav.x++;
}

```

Prikazi.h (eng. Draw.h)

```
#pragma once

#include "SDL_image.h"
#include "Splav.h"

class Splav;

class Prikazi
{

private:

    SDL_Window * ekran = NULL;
    SDL_Renderer *renderer;

    SDL_Texture *pozadina;
    SDL_Texture *splav;
    SDL_Texture *loptica;

    SDL_Rect rectPozadina;

public:

    Splav *sp ;

    const int sirinaEkrana = 1280, visinaEkrana = 720; //screen width and height
    const int sirinaSplavi = 200, visinaSplavi = 10; //paddle width and height

    Prikazi();
    ~Prikazi();

    void crtajPocetno();

    SDL_Rect initRect(int x, int y, int sirina, int visina);
};

```

Prikazi.cpp (eng. Draw.cpp)

```
#include "Prikazi.h"

Prikazi::Prikazi()
{

    ekran = SDL_CreateWindow("Breakout", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, sirinaEkrana, visinaEkrana, SDL_WINDOW_SHOWN);
    renderer = SDL_CreateRenderer(ekran, -1, 0);
    pozadina= IMG_LoadTexture(renderer, "Assets/pozadina1.png");
    loptica = IMG_LoadTexture(renderer, "Assets/loptica.bmp");
    splav = IMG_LoadTexture(renderer, "Assets/splav.bmp");

    rectPozadina = initRect(0, 0, sirinaEkrana, visinaEkrana);

//this is where I get nullptr value
    sp->rectSplav = initRect(sp->rectSplav.x, sp->rectSplav.y, sirinaSplavi, visinaSplavi);

    crtajPocetno();
}

Prikazi::~Prikazi()
{
    //SDL_DestroyWindow(ekran);
}

void Prikazi::crtajPocetno()
{
    SDL_RenderClear(renderer);
    SDL_RenderCopy(renderer, pozadina, NULL, &rectPozadina);
    SDL_RenderCopy(renderer, splav, NULL, &(sp->rectSplav));

    SDL_SetRenderTarget(renderer, pozadina);
    SDL_SetRenderTarget(renderer, splav);

    SDL_SetRenderTarget(renderer, NULL);
    SDL_RenderPresent(renderer);

}

SDL_Rect Prikazi::initRect(int x, int y, int sirina, int visina)
{
    SDL_Rect r;
    r.x = x;
    r.y = y;
    r.w = sirina;
    r.h = visina;

    return r;
}

```

My question is: How to define that pointer so I can just use it to store Rect coordinates to my Prikazi class (eng. Draw) so It can use that info to render it on the screen? Same question goes to creating Prikazi pointer inside Splav.h ( so I can use constants for screen height, width etc. )

# Answer
As far as I can see you never initialise your pointer.

You declare `Splav *sp` but never create a new `Splav` instance which means trying to call a method later is undefined behaviour. So you would need to pass in a Splav pointer into the constructor, or construct a new pointer inside it, however....

The bigger problem is that in `Splav` you have a pointer to `Prikazi` and in `Prikazi` you have a pointer to `Splav`. This is a circular dependency - you need a Splav to create a `Prikazi` but you need a `Prikazi` to create a `Splav`. This is a bad situation to be in, essentially having a chicken & egg situation.

```
#include "Prikazi.h"

class Prikazi;

```

You don't need to forward-declare if you are already including the header. Forward-declaring is essentially promising the compiler that there will be a class when it needs it, but not right now.

You need to ask yourself if these two classes really need to know about each other before coupling them so closely. For example in `Splav` all you really seem to do is take the width and height from `Prikazi` and store them internally - that in itself is a bit questionable but if you need to do it then just pass in two integers in the constructor. Then you need to instantiate a `Splav` item and pass it into `Prikazi` and store it in the `sp` variable.

Overall, your problem is stemming from poor design and I would really recommend picking up a book (or watch a tutorial) on the very basics of c++ programming. A tip for the future is to write all your code in English, makes it much easier to follow along which helps when you need to ask questions. Also upon reaching this point I realise we're in the gamedev section and this isn't really related to game programming but really the basics of programming - but I already typed it out so there we go.
> 1 votes

---
Tags: c++, oop, objects
---


# Question
Title: How to download material files (including shaders) from external source on runtime?
My game has a lot of different materials, shaders and textures. When a bunch of players are dropped into the same game, I want those assets to be loaded from an external source instead of being built into the game from the start.

Problem is, with C# being such a non-agile language, and `UnityWebRequest` being unable to read .mat or .shader from the box, I don't know how to work with those files.

Ideally, I just want to write:

```
UnityWebRequest req = UnityWebRequest.Get("http://pathToMaterials/material.mat");

Material material = req.downloadHandler;

```

Or something...

# Answer
> 1 votes
Put your assets into an asset bundle file.

After you retrieved the raw binary data representation of your asset bundle from your UnityWebRequest, use `AssetBundle.LoadFromMemory` (or the non-blocking variant `LoadFromMemoryAsync`) to get an `AssetBundle` object and then call the method `LoadAsset` (or `LoadAssetAsync`) on it to retrieve the material asset from it.

But just as DMGregory wrote in a comment: This really only makes sense if you allow users to program their own shaders. When the materials you want to load at runtime use the same shader and only differ by their texture (and maybe other shader parameters), then it might be better to ship a material with that shader but without a texture with the game. Download only the texture (and other parameters) and set it at runtime via the `renderer.material` of your game object.

By the way: when you change something at `renderer.material`, then Unity actually creates a new, nameless material and assigns it to the renderer. If you want to change the material directly in a way which affects all game objects with the same material, use `renderer.sharedMaterial`.

---
Tags: unity, materials, http
---