title: nullException issue

text:
# Question
Title: nullException issue
I have a problem when I was trying to change a state within my character. I wrote the code below

```
 public class playerController : MonoBehaviour {
 private CharacterController characterC;
 private Animator anim;
 // Use this for initialization
 void Start () {
     characterC = GetComponent<CharacterController> ();
     anim = GetComponent<Animator> ();

 }

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

 }
 // put a line attack!
 public void Attack(){

     anim.SetBool ("attack", true);
     anim.Play ("attack");
 }
 // when we got a box
 public void Doubleattack(){
     anim.SetBool ("hitBox", true);
     anim.Play ("doublechop");
 }
 //  dying animation gameover loser
 public void Die(){
     anim.SetBool ("isDead", true);
     anim.Play ("die");
 }

```

}

and i use one of my methods in my "mainmanager"

```
public class MainManeger : MonoBehaviour
{

    private bool isOnlineGame=false;

    private playerController plyC;`

public void start2PlayersGame()
         {
             isOnlineGame = false;
             StartLevel();
             PlayerManeger.set1VS1players();
             AnimationManeger.showGridWindow();
             plyC.Attack ();
             SoundManeger.PlayBackgroudOnPlay();
         }}`

```

I got this :NullReferenceException: Object reference not set to an instance of an object at ''plyC.Attack ()'' why?

# Answer
> 2 votes
`plyC` is *declared*, but not *initialized*.

I don't know about your exact needs, but maybe you want to add `= new playerController()` after `private playerController plyC`. Or maybe Unity's way is to do it in `Awake` or `Start`.

Or maybe it exists as a component somewhere else and you have to get it.

In any case, it is not sufficient to only write the line with the type and the variable name, this only creates a null reference, you'll have to assign an instance to it, and that's basically what the error is telling you :)

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


# Question
Title: Why does the score increase faster the second time the user plays my game?
In my HTML game, if you press the "play" button, the game will start and the score will increase by one every second. If you then press the back button and click the play button again, the score resets to 0 (what I want it to do) but for some reason it starts counting up *faster* than one a second.

Why does that happen?

The JS is below:

```
var pscore = 0;
var scoretimer;
var counter = 1;

// ...

$(document).ready(function() {
  $("#playbutton").click(function() {
    showScreen("#game");
    moveEnemy();

    // Start score counter:
    countdown();
    startdifficulty();
  });

  $(".backtomenu").click(function() {
    showScreen("#splash");
    resetgame();
  });

function updatescore() {
  pscore++; // Idiom - Accumulation. Keeps adding points to the pscore.
  $("#score span").text(pscore);
}

function countdown() {
  scoretimer = setInterval(updatescore, 1000);
}

function resetscore() {
  pscore = 0;
}

function stoptimers() {
  clearInterval(difficultytimer);
  clearInterval(spawnTimer);
}

// Function that will determine whether a player is hitting an enemy and will use the reset function to show the player they decided

function processcollisions() {
  var i = 0;
  var e = $(".enemy");
  if (e.position().left <= $("#player").position().left) {
    console.log("Process Collisions is Working");
  }
}

function resetgame() {
  pscore = 0;
  difficulty = 5000;
  clearInterval(difficultytimer);
  clearInterval(spawnTimer);
  console.log("game reset");
}

```

# Answer
> 2 votes
I am not terribly familiar with JavaScript, but it looks like you are probably ending up with two callbacks to `setInterval` that increase the score.

When you hit the play button, you call `countdown()`, which uses `setInterval` to register a callback to `updatescore()` periodically.

You don't clear that callback when you click on the back button; you call `resetgame()`, which clears two *other* timers, but not (apparently) the one you used to call `updatescore()`. So when you hit play again, you just start calling `updatescore()` *twice* every second.

You probably need to `clearInterval(scoretimer)` in `resetgame()`.

---
Tags: javascript, html
---


# Question
Title: How to find a safe path for an AI snake?
I have been working on a game in which a player can compete with a snake ai to get the most apples. The current path finding technique i use (A\* Pathfinding) works fine. But I am struggling with coming with an effective way to make sure that the AI snake does not go for an objective that leads to it trapping itself. Consider that the snake can teleport and that there may be max 4 apples on the map at any given time. The decision tree I am trying to create looks somewhat like this:

* If path to goal is safe : go for apple!
* Else check next apple until a safe path is found or all apples are checked.
* If no path to any apple is safe including the paths produced if teleportation is possible, Then find the farthest path to the tail and remain chasing the tail until a safe path to an objective becomes available. If no path to tail is found : stall until death!

The problem is that it is really hard to find a fast and efficient way to determine if a path is safe!

My question is: what is a good way to determine if a path into an enclosed area is safe given that you cannot take the same path back out of that area?

# Answer
Take a look at https://github.com/stevennl/Snake, a project demonstrating a few AI algorithms for the game Snake. The project README has a very nice explanation of the algorithm.

The key is for the snake to follow a *Hamiltonian circuit* (a path that visits every square, and loops back on itself). Many such paths exist for a simple 2D grid, you just have to find one. So something like this:

Finding such a path is also known as the longest path problem. If you make your AI follow this circuit, it will never trap itself and will be able to grow to the largest size possible - filling the entire grid. If you're lazy you can stop here - your AI doesn't even need to care where the fruit is. Of course, this AI will be horribly slow, and maybe boring to watch.

To make the snake faster at eating fruit, you can make it take shortcuts within the Hamiltonian circuit, as long as taking such shortcuts won't make its head overlap its body after taking the shortcut. Here's an image covering the key points:

> https://johnflux.com/2015/05/02/nokia-6110-part-3-algorithms/

This algorithm is much better, but still not the best, since it is still following the original Hamiltonian circuit. It's possible that finding other circuits will allow it to take better shortcuts.

Other things that can complicate the algorithm include:

* Grids with obstacles; these can really complicate the longest path algorithm
* Multiple snakes
> 5 votes

# Answer
I assume this is in 2D,

Wouldn't this be doable with iterating? Like, generating a straight line from snake head to goal. Then checking the line for errors, like if there's an obstacle in the way, then create a midpoint that dodges the obstacle.

Like, this: https://www.youtube.com/watch?v=-L-WgKMFuhE

But after you find the path, do two things: 1. With the current state, check if the goal is in an enclosed space with the snake, like the snake is the lid of the jar (terrain) that surrounds the goal. Then confirm there's enough space to jam the snake in there and coil it out. 2. Simulating the "head touches goal in most efficient path", check if you generated a jar, like in (1.)

Either way you'll need to do a lot of pixel crawling, unless you index everything somehow. But with modern day processing power, I doubt you'd need any indexes or optimizations.

I trid to help.
> -1 votes

---
Tags: algorithm, ai, path-finding, snake
---


# Question
Title: Why do game studios need graphics programmers if they're using game engines?
In the credits section of the games I play, there are names of *graphics programmers*. If they used a game engine, why do they need a *graphics programmer*? Isn't the game engine doing their job?

# Answer
> 93 votes
Even with an engine, getting something to display on the screen the way you want it is not always trivial. There will be many instances where someone with programming knowledge is required to make the graphics display correctly. These people may be called graphics programmers in the credits (graphics programmer is not a certified or protected title, and the difference between different titles can vary a lot by company).

Let's bring a concrete example. We need an animated rotating circle, as follows:

Some of our options are:

1 Put the circle on a billboard, write a script to rotate the billboard.

2 Use an animated gif as the source.

3 Do the whole thing in a shader, which allows 2 different options:

* Rotate the billboard in the vertex shader
* Draw a rotated circle in the fragment shader.

In 1. someone needs to write that script, which is some kind of programming task that has to do with graphics. For 2. we don't need a programmer, unless the engine - like most - doesn't support import of animated gifs, in which case somebody needs to program that part. In 3. someone has to program the shader, which could be an artist or a programmer.

EDIT to address downvotes:

The downvotes seem to be because the effect is too simple and thus wouldn't be implemented by a "real" graphics programmer. I don't really know who else it would be implemented by if there is a dedicated graphics programmer on the team, and I occasionally do implement such rotation effects in shaders - although usually the rotation is just a part of a bigger whole, as in this example.

# Answer
> 65 votes
Game engines are like kitchens, and developers (i.e. programers) are like cooks.

Game engines offer possibilities, while the programmers exploit these possibilities to the needs of the game.

Thus, game companies need graphics programmers to tailor the engine's graphics possibilities to the game's needs.

If the game engine were to manage everything, without tweaking, all the games produced by that engine would look like they come out of the same mould: the artists can produce different 3D models and 2D art tailored to the vision of the designers, but the in-game customization to these graphics will be limited to what the engine offers out of the box.

---

Note that while they let you change the art used, *some* game engines don't offer the possibility to tailor the other graphic aspects to the needs of the game. I think RPG Maker was like that: it let you change the *art* but you were limited in terms of how you could tweak your game to give it a very distinctive touch. This may have changed in the past years as I have not touched that software for a while.

# Answer
> 20 votes
The specific meaning of most titles in the games industry vary widely from studio to studio, so keep that in mind. What constitutes "graphics programming" in one studio may really mean just making shader or material tweaks, where in another studio it might mean doing relatively low-level optimization work near the underlying graphics API, et cetera.

That said, in larger studios it's relatively rare to take some engine middleware and use it without making any modifications whatsoever. Most of the time, specific aspects of the engine will need to be tweaked because it doesn't quite meet requirements, or because there is a bug in that version and the company cannot yet upgrade to a newer version that may fix the bug, et cetera.

Graphics are one such area where people tend to do a fair bit of tweaking. It might not involve *rewriting the use of Direct3D* or similar within the engine, but could still involve work customizing or optimizing shaders, improving graphics resource management to better account for the usage profiles of the specific game, adding new rendering features or options, streamlining the graphics asset pipeline to better suit the studio's workflow, et cetera.

Further, there are many cases where a studio will want to take integrations of additional graphics-related middleware. There are middleware packages like Granite, Enlighten, and TrueSky which offer various graphics-related features (texture streaming, global illumination, sky simulation and rendering, et cetera). All of these middleware packages integrate with Unreal, but work is required to integrate them. Some of them may conflict with each other or need some tweaking to work nicely together, since they're all developed by different companies. Graphics programmers will likely be involved in that kind of work as well.

# Answer
> 7 votes
You can ship games without a graphics programmer pretty easily now-a-days because of all the engines. What you generally need a graphics programmer for are things like

1. optimization

A graphics programmer would know and/or learn how a particular engine works and be able to direct the artists or modify the materials or merge models or use other techniques etc to get better performance from the engine.
2. understanding and instruction

A artist wants to achieve a certain effect. The graphics programmer who understands how the engine works can explain how to achieve that effect.
3. customizations and effects

Certain effects might require programming. Much of the rendering of Bound is custom.

This is no different than movies. With 100s of programmers, a large budget and bad writing you might get Star Wars: The Phantom Menace. With no programmers and good writing you might get Primer. Programmers (or other technical people) can allow new things. Programmers brought CG mud to Shrek, CG hair to Monsters Inc, Bullet Time to The Matrix, etc. But, movies themsevels are not about the effects and it's fully possible to make amazing movies without effects or new custom tech.

The same is more or less true for games now. Graphics programmers might allow the fluids in Pixel Junk Shooter or all the dynamic geometry of Bound but plenty of games can be made with standard engine tech and no graphics programmers.

# Answer
> 4 votes
A lot of times, game engines would not fulfill 100% of the requirements and specifications of a game project. This is especially true for triple-A titles that are always pushing the boundaries of games technology. If some of the graphics part of the game engine does not match what the artists and designers want to achieve out-of-the-box, they might hire a graphics programmer/specialist that can help them figure out whether their expectation is feasible, and if it is, how to achieve it. It might involve tweaking the shader/art assets, or reworking parts of the rendering, or even using a middleware. Or a combination of them.

# Answer
> 3 votes
Most standard techniques will be implemented in any decent commercial engine, like FXAA, lighting, cel shading, normal mapping etc, but not all.

In the case where a game designer has specified that a particular effect has to happen, you either build it out of what is already there, or you code a new shader, or modify the graphics engine to allow it. In both scenarios, a graphics programmer is required.

# Answer
> -7 votes
Define engine, then define graphics engine. If your using an existing engine to make a game then that isn't the same as writing a game from scratch in code. If through code one can define what is graphics or engine, doesn't matter what you call it if your code is strong. Creating games in said engine, its limits and or its strong points are based purely on the programmer(s) ability. Using something like Unity or even Unreal or any other pro engine doesn't define your ability, game engines are just abstractions coding in say pure C++ is not. You can for example hire programmers hell even artists but you would be limited to the vision or limits of the engine. So it is better to code from scratch then use something already in existence. Problem is you won't find answers online like the Stackexchange I doubt many people have even bothered to code a game let alone finished a 2d project. I'm just procrastinating a little, meaning that not many self serving answers spell it out. The best way is study and practice!

---
Tags: graphics-programming, game-industry
---


title: Clearing a gizmo list (OnDrawGizmos)

text:
# Question
Title: Clearing a gizmo list (OnDrawGizmos)
I have a list of gizmos in a simple gizmo drawing manager. This list is updated from different parts of the codebase, usually from Update() methods. It goes something like this:

```
public class RenderGizmos : Singleton<RenderGizmos>
{
    private List<GizmoData> gizmos = new List<GizmoData>();

    public void AddNewGizmo(GizmoData[] gizmos)
    {
        this.gizmos.AddRange(gizmos);
    }

    public void AddNewGizmo(GizmoData gizmo)
    {
        this.gizmos.Add(gizmo);
    }

    void OnDrawGizmos()
    {
        if (gizmos == null) return;
        for (var i = 0; i < gizmos.Count; i++)
        {
            //draw gizmos
        }
    }
}

```

Can you advise me on when to clear the gizmo list? Ideally I would like to clear it every frame. However:

* Clearing it at the end of the OnDrawGizmos() method will render no gizmos (as I suspect this method might be called several times a frame).
* Clearing it in an LateUpdate()/Update() method is dependent on execution order, sometimes it draws gizmos, sometimes it doesn't
* Clearing it in a Coroutine has rendered no gizmos (but it might just be dependent on the execution order as well)

I would like not to be dependent on the execution order so I prefer not to use the Script Execution Order system.

# Answer
> 1 votes
Figured it out. I can extend the AddNewGizmo method to check if we are in the same frame, this works fine for my case.

```
public void AddNewGizmo(GizmoData gizmo)
{
    ClearIfReady();
    //add
}

private void ClearIfReady()
{
    if (lastClearedFrame != Time.frameCount)
    {
        lastClearedFrame = Time.frameCount;
        gizmos.Clear();
    }
}

```

# Answer
> 1 votes
Using **LateUpdate** instead of **Update** can be helpful - LateUpdate functions are run after all of the other Update functions have been called.

I use something similar to maintain a 'blacklist' of spots on the screen that shouldn't respond to clicks or other mouse-interactions.

https://docs.unity3d.com/ScriptReference/MonoBehaviour.LateUpdate.html

---
Tags: unity
---


# Question
Title: Collider does not call callback functions
I have a script that will create new GameObjects and will place it where the mouse is placed on the terrain. Now I need to have a check for collision on other already placed GameObjects on the field.

I check different tutorials and documentation and cannot find a way to do this in code.

My code looks like:

```
objectToPlace = (GameObject)AssetDatabase.LoadAssetAtPath("Assets/Game/3D Models/Buildings/" + objectName + ".fbx", typeof(GameObject));
objectToPlace.SetActive(true);
objectToPlace.transform.localScale = new Vector3(1, 1, 1);
objectToPlace = Instantiate(objectToPlace);

objectToPlace.transform.Rotate(Vector3.right * 90);

BoxCollider collider = (BoxCollider)objectToPlace.AddComponent(typeof(BoxCollider));
collider.isTrigger = true;

```

In the same class as the above code I have OnTriggerEnter function. But that function is not called. How can I link the Collider to that function in Unity 5.6?

I also tried using the Physics.CheckBox for checking if my new create gameObject does not collide to any other object. But without any succes.

# Answer
> 1 votes
I created a custom class for the collision detection with the OnTriggerExit, OnTriggerStay and OnTriggerEnter funtions. Also in my class where I place my models I added:

```
objectToPlace.AddComponent(typeof(BuildingColliderHandler));

```

---
Tags: unity, collider
---


# Question
Title: How to use images as Sprites in Visual Studio 2010 C++?
So i'm trying to create my first videogame, a simple code of "Space Invaders" for a project at school and I'm always getting stuck at images. I'm using C++ to code and I've tried both SFML and Magick++ as libraries but i just can't set them up properly it seems. Can someone help me through setting up either one of them or even another method?

# Answer
First of all, if the text you pasted in your comment was copied verbatim, you have a typo. Should be `#include <Magick...` not `#incude`.

If that's just a typo here, then you may have a configuration error when adding Magick++ to your solution. For VisualStudio you'll want to add the directory containing .h files in project properties -\> VC++ directories -\> include directories and make sure the .dlls are in your working directory.

Having said that, I'm not sure ImageMagick is what you're looking for. It will sort out any loading and processing of images, but not displaying it in the game window (as far as I know). You may be better off using SDL. It has a pretty gentle learning curve and will certainly allow you to easily load images and display sprites in your game window. You can get SDL and look at the documentation on the SDL website.
> 0 votes

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


title: Rotate camera around point of view

text:
# Question
Title: Rotate camera around point of view
I'm trying to rotate the camera around the view point of the camera. So when the user looks at a build the camera rotate around that building. But the camera does not need to have the building to rotate around. So therefore I want a camera that can rotate around his own point of view. So that the camera behave everywhere the same in the game.

How can I achieve this in Unity 5.6?

# Answer
> -1 votes
The answer you're looking for is Arcball rotation, similar to the rotation button in the scene view.

There's a pretty good answer (though related to OpenGL and not Unity) here:

How can I orbit a camera about it's target point?

A cursory search for Arcball rotation with Unity doesn't net any specific code examples, that I could find, though the accepted answer in the above link is a great jumping off point.

# Answer
> -1 votes
I would create a Transform variable and set it to the building's center point. Then rotate the camera around it depending on the mouse input.

---
Tags: unity, camera, rotate
---


# Question
Title: Use code to disable player input unreal engine
I have seen a lot of ways to use the node based visual scripts to stop player input; However, I have not seen a single example of how to disable the player input in visual studio?

# Answer
You can disable player input using the function:

`AActor::DisableInput(APlayerController* PlayerController)`

This should be called on the actor you wish to disable input for. You need to have a pointer to the current player controller, and pass this as the function's argument. You can easily get the first (and usually *only*, in single player game) player controller from the current world:

`UWorld::GetFirstPlayerController();`

Quick example, with `PlayerPawn` being a pointer to the AActor that you wish to disable input for:

```
APlayerController* PlayerController = GetWorld()->GetFirstPlayerController();
PlayerPawn->DisableInput(PlayerController);

```
> 1 votes

# Answer
Documentation on PlayerInputComponent

It's been quite some time since I've used UE4 in a moderate-sized project, but what I would do first is:

1. Get `UInputComponent* Temporary = PlayerInputComponent;`
2. Set `PlayerInputComponent = nullptr;` to block input
3. Later restore input by `PlayerInputComponent = Temporary;`

You might be able to use C++ standard move semantics with UE4, though I wouldn't guarantee it because usually UE4 does things in it's own weird but necessary way. What I posted above would be the first thing I'd do, so no guarantees if it works. Would be great if someone could confirm or deny.

**ALSO**: Please note that Visual Studio is not the only way to access/modify C++ code in UE4 environment. You can basically use any text editor to do so.
> 0 votes

# Answer
Set (Pawn)-\>InputEnabled() to true or false. If you can find a blueprint node to do what you want, there's a good chance the code function is very similarly named.
> 0 votes

---
Tags: c++, unreal-4
---


# Question
Title: Strategy for Levels That Blend 2 Maps Concurrently
Levels like A Crack In The Slab from Dishonored 2 allow you to jump back and forth between 2 time periods at the 'same' location.

The blending is not just a case of toggling map objects on and off, as the Timepiece in this instance gives you a view into an alternate time period, whilst the player is in a separate time period.

The drawn bounds of this Timepiece lens view are not axis aligned to x and y either, meaning you not only have to render the two time periods concurrently, but have to slice into game objects to partially occlude them (shader magic? post processing?).

I was wondering what strategies you might use to achieve such a transition/mixing of two views of the 'same' map effectively and efficiently? Maybe there is an existing library for a game engine like Unity?

Many thanks

(originally posted this question on Reddit but had no luck)

# Answer
> 2 votes
I can think of two strategies off hand, both require two (or more depending on effect) cameras. Both essentially have a camera that is rendering different content, and then map that content to a texture on an object.

So for the effect at: https://youtu.be/j4pmhvUtjic?t=434 It'd map the second camera as the texture for the shards.

That's the core concept.

How you relate or store the content is the difference, and is based on what you want the gameplay to be like.

1. Duplicate content with positional tracking
2. Rendering layers/settings per object

# Duplicate Content

Imagine an entirely separate copy of your game world, perhaps offset on one of the axis such that the two copies don't intersect. For example, Timeline 1 is z=0, timeline 2 is z=1000, timeline n is z=(n-1) * 1000.

Then when the character moves you update all cameras, with those offsets.

When the player transitions between timelines, you move their model by the offset.

# Rendering Layers / Settings

Each timeline is still a separate camera, however just with different rendering settings. Every object in your game would then have a set of rendering data per timeline.

This could be as simple as just textures to give them old, dilapidated feel. Or different meshes that could be rendered. You could give them translations (chandelier on the ceiling in one timeline, translated to the floor in another). It'd also be possible to essentially turn off an object in one timeline so it no longer exists (like the NPCs).

When the player shifts, you also need to update any physics objects, AI, audio, however you want for effect.

# Summary

The trick is really to create two sets of content and have a camera looking at each set. Then you render the "off" camera to a texture for an object.

## Notes

Keep in mind level of detail as well. If you're experiencing performance issues rendering two scenes at once, you could create a really scaled down rendering on the off camera. So, for 2 timelines, maybe 4 copies or sets of render data, one for active rendering, and one for quick low quality, distorted rendering.

For a simpler effect, it should be possible to overlay a portion of the second camera on top of the render of the first camera. Possibly building an alpha map to describe transparency. So it would blend the two renders, only including some portions of the second camera with varying levels of transparency.

## How it was actually done

Here's a video about how they manage this: https://youtu.be/P\_JKT2rHg50?t=229

---
Tags: unity, rendering
---


# Question
Title: How to use camera in Google VR SDK 1.50 for Unity?
I have looked at many tutorials on making an Android app for Google Cardboard in Unity, but all of them were for older versions of the GVR SDK. How do I simply add a stereo camera in version 1.50 (with Unity 5.6)?

# Answer
With previous versions on Google VR SDK, you added a prefab called `GvrViewerMain` to the scene to get a stereoscopic camera. The `GvrEditorEmulator` prefab has replaced `GvrViewerMain` in 1.50+.

The preview in Unity will *not* appear as stereoscopic, but it will be stereoscopic when built for Android.

Check out the release notes for Google VR SDK 1.50 for more details.
> 1 votes

---
Tags: unity, android, virtual-reality, google-cardboard
---


# Question
Title: Unable to Execute code in (what i expect to be) the correct order
I have become completely stummped on this. I have a login screen i have created, i have everything working except 1 thing. When i click "login" i want to hide the Login screen object (wm.LoginSWindowHide()) below. and show a small window that shows "Authenticating", then change that text when done.

my code is below the ActionAuthentication method is called on click of the button method. The outcome i am seeing is the Rest call being done successfully then the authenticating window popup. even though i have specifically done it the other way around (change the windows, then make the call)

```
public void ActionAuthentication()
    {
        wm.AuthenticatingWindowShow();  //runs after DoAuth()
        wm.LoginWindowHide(); //runs after DoAuth()

       DoAuth();
    }

public void DoAuth()
{
    loginAPI.wwwData = null;
    loginAPI.Authenticate(UserNameInput.text, PasswordInput.text);
    //this sets wwwData to the WWW result within the class.  which is why i can call
    //it later on and why i reset it to null before calling it (Clear the variable
    //in case they failed a previous login)

    hasLoginBeenAttempted = true;
    PostAuth();

}

public void PostAuth()
{

        if (loginAPI.wwwData.isDone)
        {

         //Exeucte my code.... this is currently successful but runs before updating the windows.

        }
    }
}

```

i have tried using co routines to do this as i suspect it's running my code and blocking Update from occurring, but i get exactly the same result.

```
public void ActionAuthentication()
{
    wm.AuthenticatingWindowShow();
    wm.LoginWindowHide();
    StartCoroutine("DoAuth");

}

IEnumerator DoAuth()
{
    loginAPI.wwwData = null;
    loginAPI.Authenticate(UserNameInput.text, PasswordInput.text);
    yield return new WaitForRest(loginAPI);

}

public class WaitForRest : CustomYieldInstruction
{

    private bool isDone = false;

   public override bool keepWaiting
    {
        get
        {
            return isDone;
        }
    }

    public WaitForRest(API loginAPI)
    {
        if(loginAPI.wwwData.isDone)
        {
            isDone = true;
        }
    }
}

```

In case it helps, my API class contains the following code.

```
public WWW wwwData;

public API()
{
    wwwData = null;
}

public string Authenticate(string UserName, string Password)
{

    AuthData authData = new AuthData(UserName, Password);

    string body = JsonConvert.SerializeObject(authData);
    string url = "http://RandomURL/api/aPath/Authorise";

    byte[] postBody = Encoding.ASCII.GetBytes(body.ToCharArray());

    wwwData = DoPost(url, postBody);

    if (wwwData.error != null)
    {
        return wwwData.error;
    }
    else
    {
        return wwwData.text;
    }

}

public WWW DoPost(string url, byte[] requestBody)
{

    Dictionary<string, string> headers = new Dictionary<string, string>();
    headers.Add("Content-Type", "application/json");
    headers.Add("Accept", "application/json");

    WWW www = new WWW(url, requestBody, headers);

    return www;

}

```

I'm not adding the REST API Code because i don't think that's relevant and is successfully returning what i expect. (even to the code above, i just can't get it to execute in the right order)

# Answer
Any UI changes (like showing and hiding UI elements) only get applied when the currently executed event method (in this case `ActionAuthentication`) is finished. But that takes a while because your `Authenticate` method is blocking. It blocks because it requests the property `wwwData.error` before the webserver responded. As the documentation says:

> If the object has not finished downloading the data, it will block until the download has finished. Use isDone or yield to see if the data is available.

Wrapping the call to that method with a coroutine doesn't help, because coroutines aren't actually doing multithreading. When you call `StartCoroutine`, the passed method is executed immediately until the first `yield`.

What you can do instead is make the method `Authenticate` a coroutine and have it do `yield return new WaitForFixedUpdate()`'s until the server responded:

```
wwwData = DoPost(url, postBody);

while (!wwwData.isDone) {
    yield return new WaitForFixedUpdate();
}

if (String.IsNullOrEmpty(wwwData.error))
{
    // handle error
}
else
{
    // handle success
}

```
> 2 votes

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


# Question
Title: How can I simulate relatively realistic weather?
I'm trying to create relatively realistic weather patterns for my game. The simulation should handle temperature, wind, cloud formation and evolution, fog/mist, rain, snow, etc., and account for terrain (including seas/oceans).

My question: how can I achieve this? I've tried looking up how weather systems work but it hasn't been that helpful.

I've given it a shot anyway. I started with a 2D pressure grid that diffused and advected in the regular fluid-dynamical way (which generates a pressure-velocity grid, i.e. wind). Then I added a humidity grid that is pushed according to the wind. I made clouds form / un-form (rain?) based on the humidity (I gave the air a humidity 'carrying capacity' based on its pressure. Any extra humidity is converted into cloud).

Anyway, I've sort of lost faith in my work so far. Am I going in the right direction? One idea would be to simulate warm / cloud fronts themselves. Would that work out?

Any direction would be nice, I really don't know what I'm doing here. Thanks.

# Answer
> 7 votes
Fake it. At least to some extent.

There is a field of programming that is concerned with simulating weather, as you're probably aware. It has come a long way, and we have very accurate weather predictions because of it. However, all of that stuff is designed to run on supercomputers based on a stream of data, not as a standalone simulation on a laptop. You'd be on your own.

In my experience, realistic simulations in games are huge timesinks. The more complex it is, the more like a black box it becomes, which actually makes it harder to get it to behave in a realistic way. You'll likely end up with something that a player wouldn't understand enough to give you much benefit over just randomly spawning storms.

So, don't start with 'simulation'. Work backwards from what you want the player to see. If you want them to see storm fronts, program in storm fronts. Maybe have them randomly spawn based on terrain, like mountains or bodies of water, and also time of year. Maybe have them behave differently on different terrain. Maybe have a few special interactions when a couple of them meet. I think that's all you need to make a player feel like there is an in-depth simulation happening.

---
Tags: simulations
---


title: Rotate camera around its center in 2D

text:
# Question
Title: Rotate camera around its center in 2D
I'm currently trying to develop my own little game engine (trying to understand maths in games).

I have implemented 4x4 matrices and 2d vectors (I don't need 3d since I'm aiming at orthographic projection in 2d).

I have a Camera class that has a position and a rotation angle as members.

Every time my camera moves (keyboard input), I update its view matrix.

I do it this way:

* I translate the camera to its position and then create a Z-axis rotation matrix.
* I multiply both and have my view matrix.

Everything looks fine, and by that I mean that translation works, as well as rotation and projection is fine too.

But my problem is that objects in my scene do not rotate around the camera position.

It looks like my objects rotate around a point that is translated by the camera too, not like objects rotate around the actual camera center.

And here is my source code: https://github.com/yann-kaiser/kyengine

I do not know if I shall tweak things in my camera transformation or if it's a model-matrix related thing or anything else; could someone explain this to me?

**EDIT:** Finally found the solution. I needed to first create a translation matrix to the center of the screen (translate by w/2 and h/2), then apply rotation and only then apply my position translation.

# Answer
> 0 votes
That usually happens, when you apply the matrices in the wrong order, it should be `translation * rotation * scale`

---
Tags: opengl, c++, camera
---


title: Procedural 3D Environment Generation

text:
# Question
Title: Procedural 3D Environment Generation
I am concerning a 3D Scroller game which is like Subway Surf or Temple Run. The thing I am confused about is their way of generating 3D environment. For example for 2D games like Flappy Bird, there is a camera and player which have fixed positions respect to the X axis. And the environment is being generated, moved into camera's viewport, and finally gets destroyed after getting out of viewport. I mean, player and camera does not move in general, the environment does.

Is this approach efficient by means of performance for 3D scrollers? Do they use a box which covers the camera's viewport, and when objects get out of the box, destroy them? **Or** do they create the environment via code as the player goes further, then make the camera follow the player and they are moving both? Is this a valid approach and what are the advantages or disadvantages of these implementations?

Thanks in advance!

# Answer
> 1 votes
Either one is valid. It is not a performance concern.

If you play for a very long time (or go very fast) while moving the player instead of the world you might run into floating point accuracy troubles. But 'very' back there was something of an understatement.

Its a personal preference more than anything. Some developers like intuitive movement, some like the game to fit neatly into a little space instead of running off into infinity.

---
Tags: procedural-generation
---


# Question
Title: How can I improve rendering speeds of a Voxel/Minecraft type game?
I'm writing my own clone of Minecraft (also written in Java). It works great right now. With a viewing distance of 40 meters I can easily hit 60 FPS on my MacBook Pro 8,1. (Intel i5 + Intel HD Graphics 3000). But if I put the viewing distance on 70 meters, I only reach 15-25 FPS. In the real Minecraft, I can put the viewing disntance on far (= 256m) without a problem. So my question is what should I do to make my game better?

The optimisations I implemented:

* Only keep local chunks in memory (depending on the player's viewing distance)
* Frustum culling (First on the chunks, then on the blocks)
* Only drawing really visible faces of the blocks
* Using lists per chunk that contain the visible blocks. Chunks that become visible will add itself to this list. If they become invisible, they are automatically removed from this list. Blocks become (in)visible by building or destroying a neighbour block.
* Using lists per chunk that contain the updating blocks. Same mechanism as the visible block lists.
* Use nearly no `new` statements inside the game loop. (My game runs about 20 seconds until the Garbage Collector is invoked)
* I'm using OpenGL call lists at the moment. (`glNewList()`, `glEndList()`, `glCallList()`) for each side of a kind of block.

Currently I'm even not using any sort of lighting system. I heard already about VBO's. But I don't know exactly what it is. However, I'll do some research about them. Will they improve performance? Before implementing VBO's, I want to try to use `glCallLists()` and pass a list of call lists. Instead using thousand times `glCallList()`. (I want to try this, because I think that the real MineCraft doesn't use VBO's. Correct?)

Are there other tricks to improve performance?

VisualVM profiling showed me this (profiling for only 33 frames, with a viewing distance of 70 meters):

Profiling with 40 meters (246 frames):

**Note:** I'm synchronising a lot of methods and code blocks, because I'm generating chunks in another thread. I think that acquiring a lock for an object is a performance issue when doing this much in a game loop (of course, I'm talking about the time when there is only the game loop and no new chunks are generated). Is this right?

**Edit:** After removing some `synchronised` blocks and some other little improvements. The performance is already much better. Here are my new profiling results with 70 meters:

I think it is pretty clear that `selectVisibleBlocks` is the issue here.

Thanks in advance!
Martijn

**Update**: After some extra improvements (like using for loops in stead of for each, buffering variables outside loops, etc...), I now can run viewing distance 60 pretty good.

I think I'm going to implement VBO's as soon as possible.

PS: All source code is available on GitHub:
https://github.com/mcourteaux/CraftMania

# Answer
You mention doing frustum culling on individual blocks — try throwing that out. Most rendering chunks should be either entirely visible or entirely invisible.

Minecraft only rebuilds a display list/vertex buffer (I don't know which it uses) when a block is modified in a given chunk, and so do I. If you're modifying the display list whenever the view changes, you're not getting the benefit of display lists.

Also, you appear to be using world-height chunks. Note that Minecraft uses *cubical* 16×16×16 chunks for its display lists, unlike for load and save. If you do that, there's even less reason to frustum cull individual chunks.

*(Note: I have not examined the code of Minecraft. All of this information is either hearsay or my own conclusions from observing Minecraft's rendering as I play.)*

---

More general advice:

Remember that your rendering executes on two processors: CPU and GPU. When your frame rate is insufficient, then *one or the other is the limiting resource* — your program is either *CPU-bound* or *GPU-bound* (assuming it isn't swapping or having scheduling problems).

If your program is running at 100% CPU (and doesn't have an unbounded other task to complete), then your CPU is doing too much work. You should try to simplify its task (e.g. do less culling) in exchange for having the GPU do more. I strongly suspect this is your problem, given your description.

On the other hand, if the GPU is the limit (sadly, there aren't usually convenient 0%-100% load monitors) then you should think about how to send it less data, or require it to fill fewer pixels.
> 15 votes

# Answer
What's calling Vec3f.set so much? If you're building what you want to render from scratch each frame then that's definitely where you'd want to start to speed it up. I'm not much of an OpenGL user and I don't know much about how Minecraft renders, but it seems that the math functions you using are killing you right now (just look how much time you spend in them and the number of times they get called - death by a thousand cuts calling them).

Ideally your world would be segmented up such that you can group stuff to render together, building Vertex Buffer Objects and re-using them across multiple frames. You'd only need to modify a VBO if the world it represents changes somehow (like the user edits it). You can then create/destroy VBO's for what you're representing as it comes into range of being visible to keep memory consumption down, you'd only take the hit as the VBO was created rather than every frame.

If the "invocation" count is correct in your profile, you're calling an awful lot of things an awful lot of times. (10 million calls to Vec3f.set... ouch!)
> 3 votes

# Answer
My description (from my own experimentation) here is applicable:

For voxel rendering, what is more efficient: pre-made VBO or a geometry shader?

Minecraft and your code likely uses the fixed function pipeline; my own efforts have been with GLSL but the gist is generally applicable, I feel:

(From memory) I made a frustum that was a half-block bigger than the screen frustum. I then tested the center-points of each chunk (minecraft has 16\*16\*128 blocks).

The faces in each has spans in an element-array VBO (many faces from chunks share the same VBO until it is 'full'; think like `malloc`; those with the same texture in the same VBO where possible) and the vertex indices for the north faces, south faces and so on are adjacent rather than mixed. When I draw, I do a `glDrawRangeElements` for the north faces, with the normal already projected and normalized, in a uniform. Then I do the south faces and so on, so the normals are not in any VBO. For each chunk, I only have to emit the faces that will be visible - only those in the center of the screen need to draw left and right sides, for example; this is simple `GL_CULL_FACE` at an application level.

The biggest speedup, iirc, was culling interior faces when polygonizing each chunk.

Also important is texture-atlas management and sorting faces by texture and putting the faces with the same texture in the same vbo as those from other chunks. You want to avoid too many texture changes and sorting the faces by texture and so on minimizes the number of spans in the `glDrawRangeElements`. Merging adjacent same-tile faces into bigger rectangles was also a big deal. I talk about merging in the other answer cited above.

Obviously you only polygonize those chunks that have ever been visible, you may discard those chunks that haven't been visible for a long time, and you re-polygonize chunks that are edited (as this is a rare occurrence compared to rendering them).
> 2 votes

# Answer
Where are all your comparisons (`BlockDistanceComparator`) coming from? If it's from a sort function, could that be replaced with a radix sort (which is asymptotically faster, and not comparison based)?

Looking at your timings, even if the sorting itself isn't that bad, your `relativeToOrigin` function is being called twice for each `compare` function; all of that data should be computed once. It should be faster to sort an auxiliary structure e.g.

```
struct DistanceIndexPair
{
    float m_distanceSquaredFromOrigin;
    int m_index;
};

```

and then in pseudoCode

```
// for i = 0..numBlocks
//     distanceIndexPairs[i].m_distanceSquaredFromOrigin = ...;
///    distanceIndexPairs[i].m_index = i;
// sort distanceIndexPairs
// for i = 0..numBlocks
//    sortedBlock[i] = unsortedBlocks[ distanceIndexPairs.m_index ]

```

Sorry if that's not a valid Java struct (I haven't touched Java since undergrad) but hopefully you get the idea.
> 1 votes

# Answer
Yeah use VBOs and CULL facing, but that goes for pretty much *every* game. What you want to do is only render the cube if it is visible to the player, ***AND*** if the blocks are touching in a specific way (let's say a chunk that you cannot see because it's underground) you add the vertices of the blocks and make it almost like a "bigger block", or in your case- a chunk. This is called greedy meshing and it drastically increases performance. I am developing a game (voxel-based) and it uses a greedy meshing algorithm.

**Instead of rendering everything like this:**

**It renders it like this:**

The downside to this is that you have to do more calculations per chunk on the initial world build, or if the player removes/adds a block.

## pretty much any type of voxel engine needs this for good performance.

What it does is checks to see if the block face is touching another block face, and if so: only render as one (or zero) block face(s). It is an expensive touch when you are rendering chunks really fast.

```
public void greedyMesh(int p, BlockData[][][] blockData){
        boolean[][][][] mask = new boolean[blockData.length][blockData[0].length][blockData[0][0].length][6];

    for(int side=0; side<6; side++){
        for(int x=0; x<blockData.length; x++){
            for(int y=0; y<blockData[0].length; y++){
                for(int z=0; z<blockData[0][0].length; z++){
                    if(data[x][y][z] > Material.AIR && !mask[x][y][z][side] && blockData[x][y][z].faces[side]){
                        if(side == 0 || side == 1){
                            int width = 0;
                            int height = 0;
                            loop:
                            for(int i=y; i<blockData[0].length; i++){
                                if(i == y){
                                    for(int j=z; j<blockData[0][0].length; j++){
                                        if(!mask[x][i][j][side] && blockData[x][i][j].id == blockData[x][y][z].id && blockData[x][i][j].faces[side]){
                                            width++;
                                        }else{
                                            break;
                                        }
                                    }
                                }else{
                                    for(int j=0; j<width; j++){
                                        if(mask[x][i][z+j][side] || blockData[x][i][z+j].id != blockData[x][y][z].id || !blockData[x][i][z+j].faces[side]){
                                            break loop;
                                        }
                                    }
                                }
                                height++;
                            }
                            for(int i=0; i<height; i++){
                                for(int j=0; j<width; j++){
                                    mask[x][y+i][z+j][side] = true;
                                }
                            }

                            if(side == 0)
                                meshes.get(p).add(new Mesh(new VoxelVector3i(x+1, y, z), new VoxelVector3i(x+1, y+height, z+width), new VoxelVector3i(1, 0, 0), Material.getColor(data[x][y][z])));
                            else
                                meshes.get(p).add(new Mesh(new VoxelVector3i(x, y, z+width), new VoxelVector3i(x, y+height, z), new VoxelVector3i(-1, 0, 0), Material.getColor(data[x][y][z])));
                        }else if(side == 2 || side == 3){
                            int width = 0;
                            int height = 0;
                            loop:
                            for(int i=x; i<blockData.length; i++){
                                if(i == x){
                                    for(int j=z; j<blockData[0][0].length; j++){
                                        if(!mask[i][y][j][side] && blockData[i][y][j].id == blockData[x][y][z].id && blockData[i][y][j].faces[side]){
                                            width++;
                                        }else{
                                            break;
                                        }
                                    }
                                }else{
                                    for(int j=0; j<width; j++){
                                        if(mask[i][y][z+j][side] || blockData[i][y][z+j].id != blockData[x][y][z].id || !blockData[i][y][z+j].faces[side]){
                                            break loop;
                                        }
                                    }
                                }
                                height++;
                            }
                            for(int i=0; i<height; i++){
                                for(int j=0; j<width; j++){
                                    mask[x+i][y][z+j][side] = true;
                                }
                            }

                            if(side == 2)
                                meshes.get(p).add(new Mesh(new VoxelVector3i(x, y+1, z+width), new VoxelVector3i(x+height, y+1, z), new VoxelVector3i(0, 1, 0), Material.getColor(data[x][y][z])));
                            else
                                meshes.get(p).add(new Mesh(new VoxelVector3i(x+height, y, z+width), new VoxelVector3i(x, y, z), new VoxelVector3i(0, -1, 0), Material.getColor(data[x][y][z])));
                        }else if(side == 4 || side == 5){
                            int width = 0;
                            int height = 0;
                            loop:
                            for(int i=x; i<blockData.length; i++){
                                if(i == x){
                                    for(int j=y; j<blockData[0].length; j++){
                                        if(!mask[i][j][z][side] && blockData[i][j][z].id == blockData[x][y][z].id && blockData[i][j][z].faces[side]){
                                            width++;
                                        }else{
                                            break;
                                        }
                                    }
                                }else{
                                    for(int j=0; j<width; j++){
                                        if(mask[i][y+j][z][side] || blockData[i][y+j][z].id != blockData[x][y][z].id || !blockData[i][y+j][z].faces[side]){
                                            break loop;
                                        }
                                    }
                                }
                                height++;
                            }
                            for(int i=0; i<height; i++){
                                for(int j=0; j<width; j++){
                                    mask[x+i][y+j][z][side] = true;
                                }
                            }

                            if(side == 4)
                                meshes.get(p).add(new Mesh(new VoxelVector3i(x+height, y, z+1), new VoxelVector3i(x, y+width, z+1), new VoxelVector3i(0, 0, 1), Material.getColor(data[x][y][z])));
                            else
                                meshes.get(p).add(new Mesh(new VoxelVector3i(x, y, z), new VoxelVector3i(x+height, y+width, z), new VoxelVector3i(0, 0, -1), Material.getColor(data[x][y][z])));
                        }
                    }
                }
            }
        }
    }
}

```
> 1 votes

# Answer
It would seem that your code is drowning in objects and function calls. Gauging the numbers, it doesn't seem like there is any in-lining happening.

You could try to find a different Java environment, or simply mess with the settings of the one you have, but a plain and simple way of making your code, not fast, but a good deal less slow is at least internally in Vec3f to stop coding OOO\*. Make every method self containing, don't call any of the other methods just to perform some menial task.

Edit: While there is overhead all over the place it would seem that ordering the blocks before rendering is the worst performance eater. Is that really necessary? If so you should probably start out by going through a loop and calculate each blocks distance to origin, and then sort by that.

\*Overly Object Oriented
> 0 votes

# Answer
You could also try to break down Math operations down to bitwise operators. If you have `128 / 16`, try to make a bitwise operator: `128 << 4`. This will help a lot with your problems. Don't try to make things run at full speed. Make your game update at a rate of 60 or something, and even break that down for other things, but you would have to do destroying and or placing voxels or you would have to make a todo-list, which would bring down your fps. You could do an update rate of about 20 for entities. And something like 10 for world updates and or generation.
> 0 votes

---
Tags: opengl, java, performance, minecraft-modding, voxels
---


# Question
Title: Dynamic chunk loading with high FPS. But still chops
I am creating a voxel world, (like any other person), but I currently have a small performance hit when loading/unloading chunks.

Right now I can load and unload chunks dynamically with "infinite" type world. I am using VBO's to store chunk data with float buffers. Also, (my big point), I am using Greedy meshing to only render the edges I need. My only thought of why it's not loading well is that I am using SSAO shading, which should have a hit on my FPS, but my FPS stays in the high 200's. Also, I am using frustum culling and normal culling. What I want is the player to have a really large render distance without actually rendering the chunks until the player is close. Almost like fog but instead of covering up unloading, it's actually reducing the detail as you move away.

Also, when a player creates a voxel or destroys a voxel (basically any change in the chunk) it saves the chunk to a file in the corresponding world folder.

Any ideas?

Here is a video of the game in its' current stage.

Here's a screenshot with a far render distance. Anything with a render distance that is far, hits the performance BAD

# Answer
> 1 votes
I can see two problems with what you're describing;

Saving to a file on voxel change is unnecessary, you only need to save a chunk when it's unloaded (or the user requests a save).

I strongly suspect you are loading/unloading on the main thread, this is going to cause stuttering; you need to do this off the main thread (and so allow it to go over multiple ticks if needs be)

So the program should initiate loads at a point in it's cycle then "check back later" to see if the load has finished, if it hasn't that's fine it'll catch it later, once the load has finished the chunk gets attached to the main world

# Answer
> 0 votes
Alright, I did what needed to be done. There is a greater number of people on this stackexchange that need help then actually help. Here's what helped me:

1. Make sure you aren't using "new" in your main loop, use ObjectPools, garbage collectors can kill games unexpectedly.
2. Increasing draw distance greatly increases drawcalls. You need a LOD system to group far away chunks to the same VOB
3. Measure how many drawcalls, texture and shader switches you have and try to find some relation between that and fps. If that doesn't help, try GPU/CPU profilers, to find out where the bottleneck is.

---
Tags: opengl, java, lwjgl, voxels
---


title: How do point clouds become polygons?

text:
# Question
Title: How do point clouds become polygons?
I have reached some limits in my game experiments that seem to be solvable by working with content as 'point clouds'. My main concern now is how to convert the resulting point clouds into polygon meshes? I can't seem to find any algorithms anywhere, but I see people doing it in various programs, so it is clearly possible.

EDIT: Some elaboration. I am doing some simulation of, among other things, geological forces, and a polygon surface simply does not allow the needed detail. My goal is to create a landscape as a point cloud and use that to better simulate forces on it. But the changes are expected to be so complex that simply starting with a flat polygon surface and warping it will not be useful. So I need to taake the point cloud landscape and create a polygon surface for it, from the data it holds.

# Answer
> 2 votes
Usually you (or your artist) uses a modelling program and makes **models**. These already contain the information about the order they are in. This can be either done by indexing them (having an array, that basically says in which order they come, like `0, 1, 3, 3, 1, 2` for a quad) or by repeating them in the vertex list. The latter is usually only used when you want to have sharp edges, because you can't define a vertex and a normal vector separately.

There are however procedurally generated meshes. Those need to be triangulated using one of the algorithms, like Delauney triangulation.

GPUs always use triangles to draw things, because there are already a lot of optimized algorithms to draw them. Some APIs allow you to render quads or polygons, but those functions are deprecated, because GPUs have to triangulate them every frame, which is ineffiecient.

After you have a the vertices in order, you have to rasterize them. Rasterization is the process of converting points to triangles. This is also a pretty optimized. Most games don't do this part, they instead rely on an API such as OpenGL or DirectX, which can communicate with the GPU.

# Answer
> 1 votes
The process of converting data (for example, point clouds) into polygons is called **meshing** (since you produce a *mesh*) or *Isosurface extraction*. There are lots of techniques out there - marching cubes, marching tetrahedrons, surface nets, greedy meshing, dual conturing and many, many more. If you look for "Isosurface extraction", you'll find lots algorithms with different stenghts and weaknesses. Without knowing more, its hard to ecommend an approach.

For starters, marching cubes is a safe bet, though.

---
Tags: 3d, point-cloud
---


title: How to make a game people can mod?

text:
# Question
Title: How to make a game people can mod?
In C++, how can one make it's game load content developped by other people?

For instance in Java you can look for jar files and load specific class from it.

# Answer
> 4 votes
There are 2 primary approaches to this:

1. Make your game open source. People have access to the source of the game and can make changes to the code.
2. Design a modular game. For the modules you want to allow people to mod, for example the Game AI, provide hooks. These hooks in C++ will either be in the form of dll calls (or COM, even) to user provided C++ implementations, or by a script, such as lua. You can allow people to introduce new content, such as textures, models, levels, etc by using standardized formats (e.g. png, fbx, json, xml), or specifying the proprietary format you use.

Further information, such as how to best design such dll interfaces are usually opinion based or highly dependent on specifics.

---
Tags: c++, architecture, modding
---


# Question
Title: How to procedurally generate materials with text in Unity
I'm designing a virtual library that dynamically loads sections of a database and need to display text on the books. As such, I need a runtime interface to somehow load book titles and author and put them on the book covers.

I've looked into Substance Designer to make a procedural material, but the Text Node in the program is not yet supported by Unity. I've also stumbled across `TextGenerator` in the Unity API, but it seems to be mesh not texture based, and I'm not sure what the performance penalty will be, given I'm rendering a lot of books.

**Edit:** For now I had some luck creating a child object and using the `TextGenerator`, since it turns out the mesh is minimal and in fact does create a texture to display the text. I suppose I can use this solution until something better comes up.

# Answer
For now I had some luck creating a child object and using the TextGenerator, since it turns out the mesh is minimal and in fact does create a texture to display the text. I suppose I can use this solution until something better comes up.
> 0 votes

---
Tags: unity, procedural-generation, text, materials, substance-engine
---


# Question
Title: Can I publish a game with a name similar to a videogame developer?
I'm currently developing a game and hoping to sell it in the future. Right now I'm about to make a facebook page and release a trailer, and I realised my game has a similar name to an already existing game developer, "lucid games", and in their website they call themselves just "lucid" which is what I was expecting to call my videogame (lucid). But also it's a British studio, and I'm from Ecuador. So I was wondering if this could be an issue?

# Answer
“Lucid” might or might not be ok for you to use.

They may argue it may create confusion in users and send a cease & desist.

**Note**: some companies may even send a cease & desist without a good case. Just because you may comply.

---

Therefore, consult a lawyer.

I will not even attempt to argue about trademark law in an international context.

---

With that said, you need to consider, what would be the cost of changing your name.

You might find it is cheaper to change it than:

* Going through the process of consulting a lawyer and them telling you to change your name anyway.
* Going into a legal dispute – which has another cost to consider – which may result in you being legally obliged to change the name.

On the other hand, there is a chance that that the name you has chosen is ok to use. You consult the lawyer, who tells you that you are on legal clear. In addition, this result is cheaper. I cannot tell you the odds of that happening.

---

Now, let us see… how expensive is to change the name:

* If changing the name is cheaper than consulting a lawyer, just change the name.
* If changing the name is more expensive than consulting a lawyer but cheaper than a legal dispute (which is probably the case)… The advice is to consult a lawyer. If you are confident you can just go to court (which is unlikely, given that since you are asking here, you are probably not the head of a big company), you could take the risk of using the name anyway, I am not telling you what to do.
* If changing the name is more expensive than the legal dispute, you have done something wrong. This situation suggest that you have invested too much in the game – but not too much in getting a safer name. Have a look into the concept of sunk cost, and prepare for commercial failure.
> 8 votes

# Answer
The first thing to note is that users here are mostly game developers, not lawyers, and won't necessarily have detailed knowledge of the jurisdictions that would apply to you. Since I'm not a lawyer, the following is not legal advice.

The second thing to know is that companies tend to be *very* protective of their trademarks. It's not because they're mean and want to snuff out indies and competition — in many jurisdictions, if a company fails to act to protect their trademark in one case, that can count against them if they try to defend their trademark against a more serious infringement later on. Right to a trademark has an aspect of "use it or lose it" in this way. So if they want to maintain any control of their brands, they have to go after anyone who comes close.

So, even if the developers and businessfolk at Lucid are totally chill and don't see a problem with you naming your game Lucid, their legal team might very well be forced into sending you a cease & desist anyway.

To find out for sure where you stand, you should definitely consult a lawyer. If you don't have the time or budget for that though, then your safest bet (much as it may suck) is to change your game's name. It's not worth the risk of having your game taken offline or being put through an expensive legal battle.
> 2 votes

# Answer
Before I answer, a disclaimer; I am not a lawyer, and the law is often fickle. You can be sued for practically anything; as long as the other side is willing to front the legal fees. You should always consult an actual lawyer before making any decision with potential legal issues. It has also been noted that a company name falls under a *trademark*, while a game name falls under *copyright*. I have only looked up this clear distinction, using Google, and can not comment on any clear distinction this makes.

That said, we can at least say that this has *previously* not been an issue; although, in context, this actually suggests that using the name "Lucid" *may* have further issues in regards to copyright.

There is already a game by the name of "Lucid". Regardless of company names, you still face the issue of copyright on an existing name, and would face potential legal issues, regardless.

Either way, it is entirely plausible that the trademarked company may file for legal claims. If you are not in the position to consult a lawyer, or fight said claims regardless of position, it might be significantly easier to simply change your name. Legal dispute costs money, regardless of whether you win or lose.
> 1 votes

---
Tags: copyright, trademark
---


# Question
Title: Average for damage formula (Min-Max Attack - Min-Max Defense)
We wanted to create a quick spreadsheet to rapidly adjust enemies' Attack and Defense from players' estimated values of Attack and Defense.

One of the key values to adjust is the "hits until dead", and to derive this we need an average of the damage.

A basic calculation of the damage is done as following. Both players and enemies have `minimum` and `maximum` values for `attack` and `defense`. Two random values are generated between these and the difference is the damage received. Note that the minimum damage is zero (or *miss*).

```
attack = random(attack_min, attack_max);
defense = random(defense_min, defense_max);
damage = max(attack - defense, 0);

```

When `attack_min > defense_max`, a **simple formula** like this can be used to obtain the average damage:

```
attack_mean = (attack_min + attack_max) / 2;
defense_mean = (defense_min + defense_max) / 2;
damage_mean = attack_mean - defense_mean;

```

But in the other case, there is a **chance of missing**, and this formula is not accurate.

---

Let this be an example where the initial formula works:

```
attack_min = 10; attack_max = 20;
defense_min = 0; defense_max = 5;

attack_mean = (10 + 20) / 2 = 15;
defense_mean = (0 + 5) / 2 = 2.5;
damage_mean = 15 - 2.5 = 12.5;

```

And, this is an example where it does not:

```
attack_min = 10; attack_max = 20;
defense_min = 5; defense_max = 35;

attack_mean = (10 + 20) / 2 = 15;
defense_mean = (5 + 35) / 2 = 20;
damage_mean = 15 - 20 = -5;

```

There is low chance, but there is damage between 5 and 15! Empirical values suggest an average of around 2.

---

So, **the request** is the following: we need a **formula** that gives us the **average damage** regardless of whether defense is higher than attack or not. (We need a *formula*, not a *procedure*, so RNG is off the table).

Can anyone enlighten us on this? Thank you!!

---

**Thanks to @DMGregory's answer**, a reader may find the Excel VBA custom formula below, in case it can suit they.

```
Function TriangleSum(n)

TriangleSum = WorksheetFunction.Max(n ^ 3 + 3 * n ^ 2 + 2 * n, 0) / 6

End Function

Function GetMeanDamage(attackMin, attackMax, defenseMin, defenseMax)

GetMeanDamage = ( _
                TriangleSum(attackMax - defenseMin) _
                - TriangleSum(attackMax - defenseMax - 1) _
                - TriangleSum(attackMin - defenseMin - 1) _
                + TriangleSum(attackMin - defenseMax - 2) _
            ) / ( _
                (attackMax - attackMin + 1) * (defenseMax - defenseMin + 1) _
            )

End Function

```

# Answer
> 6 votes
We can construct a table of damage values, for each possible attack and defense roll. Then the expected damage is the sum of all the cells in this table, divided by its area (so long as your attack & defense rolls are evenly weighted).

The zeros for `attack < defense` make it a bit complicated though, potentially chopping the area we need to sum over into three different shapes:

We can sum over this by adding up each shape in turn, skipping over it for the cases where it's empty. The procedure gets a bit involved though:

```
float ExpectedDamage(int attackMin, int attackMax, int defenseMin, int defenseMax)
{
    int damageMax = Mathf.Max(attackMax - defenseMin, 0);
    int damageMin = Mathf.Max(attackMin - defenseMax, 0);

    // Early-out when attack & defense are constant,
    // or defense completely dominates the attack.
    if (damageMin == damageMax)
        return damageMax;

    // From here on in, we don't care if it's attack or defense that has greater
    // range - we just want to distinguish the narrow side of the table.
    int broad = attackMax - attackMin + 1;
    int narrow = defenseMax - defenseMin + 1;
    if (narrow > broad)
    {
        int swap = broad;
        broad = narrow;
        narrow = swap;
    }

    int result = 0;

    // Upper Triangle
    {
        int depth = Mathf.Min(narrow, damageMax);
        result += (depth * (3 * damageMax * (depth + 1) - 2 * (depth * depth - 1)))/6;
    }

    // Middle Parallelogram
    if (damageMax > narrow && broad > narrow)
    {
        int peak = damageMax - narrow;
        int depth = Mathf.Min(broad - narrow, peak);

        result += narrow * depth * (2 * peak - (depth - 1))/2;
    }

    // Lower Trapezoid
    if (damageMax > broad && narrow > 1)
    {
        int peak = damageMax - broad;
        int depth = peak - damageMin;

        // Fill bottom triangle with the minimum value.
        result += damageMin * (narrow) * (narrow - 1) / 2;

        // Add the diagonals that exceed that minimum.
        result += (narrow * depth * (depth + 1) - (depth * (depth + 1) * (depth + 2)) / 3) /2;
    }

    return result/((float)(broad * narrow);
}

```

...so that's ugly as sin and full of magic algebra formulas with no obvious reason why they're correct. It took a lot of figuring and debugging to get it working, and if an accidental change breaks it, it would be hard to track down the problem.

There's a neat trick we can use to make this more uniform, based on summed area tables.

If we imagine the values carried on past the bottom & right edges of the table, we could take the sum of the full triangle starting at our upper-left corner, then subtract the sums of the triangles past the bottom & right edges, and add back the sum of the triangle off the bottom-right corner (since otherwise we'd have subtracted it twice, in the overlap of the right & bottom triangles)

And there's a closed-form formula for the sum of a triangle peaking at some value `n`:

```
TriangleSum(n) = max(n * (n + 1) * (n + 2), 0)/6

```

Still a magic formula, but at least it's just one this time!

So then our expected damage is:

```
( TriangleSum(attackMax - defenseMin)
- TriangleSum(attackMax - defenseMax - 1)
- TriangleSum(attackMin - defenseMin - 1)
+ TriangleSum(attackMin - defenseMax - 2)
)/((attackMax - attackMin + 1) * (defenseMax - defenseMin + 1))

```

Rewriting this a bit with `A = attackMax a = attackMin - 1 D = defenseMax + 1 d = defenseMin` helps it look a bit neater:

```
( TriangleSum(A - d)
- TriangleSum(A - D)
- TriangleSum(a - d)
+ TriangleSum(a - D)
)/((A - a) * (D - d))

```

---
Tags: mathematics
---


# Question
Title: How to detect and prevent the resolution of fake collisions?
I'm creating my own physics engine and I came across a small inconvenience. Here how it goes: when a body tries to push into something it really can't push, it gets pushed back (which is completly fine). But when it tries to push that solid plus another simple box, the box gets pushed as if the body has really moved even if it can't.

Here's a visual explanation:

My current collision resolver is solving collisions by altering position of bodies. Here is its pseudo code simplified for the question.

```
/**
 * Resolves the collision by pushing a body or another
 *
 */
void resolve(Collision collision) {
    float weightA = getWeight(collision.world, collision.bodyA, -collision.normal);
    float weightB = getWeight(collision.world, collision.bodyB, collision.normal);

    //This resolves who gets to push who in a collision
    DynamicBody toPush = weightA > weightB ? collision.bodyB : collision.bodyA

    Vector normal = toPush == collision.bodyA ? -collision.normal : collision.normal;

    float replaceX = normal.x * pene;
    float replaceY = normal.y * pene;

    if(replaceX != 0f) {
        //getCollisionShifting() is the total shifting done by collisions in this frame.
        //When this resolver will be done, it will be added to the position

        float dirX = signum(toPush.getCollisionShifting().x);

        if(!original || dirX != signum(replaceX))
            toPush.getCollisionShifting().x += replaceX;
        else if(dirX == 0 || replaceX * dirX > toPush.getCollisionShifting().x * dirX)
            toPush.getCollisionShifting().x = replaceX;
    }

    /* Here, exactly the same thing is done with Y */
    //...
}

/**
 * This finds the weight of a body based on his own weight plus all the bodies its colliding with in a direction
 *
 * Uses a recursive method
 * This method might not be the best but it works and only becames inefficient for really big stacks of objects
 * Since my game won't include giant stacks, its viable for now
 */
float getWeight(World world, Body body, Vector normal) {
    float weight = body.getWeight();

    for(Collision collision : world.getCollisions()) {
        if(collision.bodyB == body)
            collision = Collision.swap(collision); //turns the collision around so bodyB becomes bodyA

        if(collision.bodyA == body && collision.normal.dot(normal) == 1f)
                weight += getWeight(world, collision.bodyB, normal);
    }

    return weight;
}

```

I included this code for you to have a better look at my current approach but I do not ask anyone to write the solution into that code. A theoric explanation of a working solution is what I'm looking for.

Currently, collisions aren't solved in any particular order. Will I have to sort the collisions ? I hope not since it would slow down the whole thing just for this. So, how can I fix this issue ?

P.S. : Please note that this physics engine is open source and you can access the original code of this example here.

# Answer
> 1 votes
You can fix this specific problem by performing collision detection and resolution against immovable objects first, then doing the same against movable objects in a second pass.

But in the general case, you have a multi-body collision problem, which is in a different class of difficulty than the two-body collision. As you've found, you run into situations where you've calculated the collision between the first pair, but then realise that collision between the second pair affects the first pair's results, so you go back to re-do the first pair, which might lead you to re-do the second pair... and so on, until you run out of energy and collisions.

One example is where B is against a wall C, and A collides into B. What happens? Well, A pushes B, but B is against a wall so all the force is reflected back, which should transfer back into A.

Lots of physics engines deal with this using **multiple iterations**, which nevertheless produces jittering in edge cases. And to prevent this from getting out of hand, there are lots of hacks, like *slop*.

---
Tags: 2d, collision-resolution, physics-engine
---


# Question
Title: What is the memory impact of having a pointer to the containing class type as a member of that class?
If I have a class called `Something`, what will the consequences for memory be if I include, in that class, a pointer to another object of the same class? So if the objects `ThingOne` and `ThingTwo` are both `Something` objects, `ThingOne`'s contained pointer could point to `ThingTwo` (and vice versa, I assume)? I am trying to create a very simple alternative to both typical arrays (I need something more dynamic) and classic vectors (they keep gumming up my work. Please do not misinterpret this question as asking for help on vectors, though).

Needless to say, the pointers would be empty in the class, only to be set when an instance of the object has already been created.

# Answer
If I understand you correctly you are talking about creating a memory structure which is called a Linked List in CompSci.

A linked can be single-linked or double-linked and each node will hence contain pointers to the next and previous object respectively.

This memory structure is, as you mention, more or less efficient, as it does not allocate any more space than it needs. There is an overhead for the pointers, but that is negligible in most cases.

---

A consideration that has to be taken is the fact that you do not get *random access* on the elements of a linked list. Every access has to iterate from either the head or tail of the list (in case of a doubly linked one, otherwise you only have a head) up to the desired node.

This means it will perform better in cases where you only have sequential access and fast changing lists. But will be outperformed in virtually any case where you need random access.
> 2 votes

# Answer
I'm not sure your question got answered. You can check the memory cost of a pointer by using `sizeof(Type*)`. It will in practice be 4B in a 32-bit programme and 8B in a 64-bit programme.
> 1 votes

# Answer
The "very simple alternative" is called a *Linked List* and it's been around for a very long time.

There is, fundamentally, nothing wrong with what you are doing. You will need to forward declare the type, or your `Something` field inside your `Something` class will not compile.
> 0 votes

---
Tags: c++
---


# Question
Title: How does one make both movement and animation to sync up and happen simultaneously?
I am very new to Unity and game making and would appreciate if you would cope with me.

I have made a very basic prototype of character animation and movement, however trigger that is supposed to fire animation happens after character already moved. I just can't seem to find a way to fix it as `SetTrigger` is `void` and not a `Task`.

See this video for what I mean

The script I am using to fire off animation is the following:

```
public class Hero : MonoBehaviour {

    public Animator animator;
    public void Down()
    {
        var move = GameObject.Find("Hero").transform.position;
        animator.SetTrigger("moveDown");
        transform.position = Vector3.Lerp(move, move + new Vector3(0, -1f, 0), 1f);
    }
}

```

**How does one make both movement and animation to sync up and happen simultaneously?**

# Answer
> 2 votes
You are trying to move the character from one point to another within the single method `Down`. This is not going to work, because that whole method is executed in a single frame. `Vector3.Lerp` just by itself doesn't cause a position to change slowly. All it does is calculate a position between two positions and return that as a new vector. This is a tool which can be useful for doing a gradual transition, but just by itself it doesn't do that.

What you should do instead is have `Down` set the information that the character is walking somewhere and then do the actual position updating in `Update`.

It should look something like this (untested!):

```
public class Hero : MonoBehaviour {

    public Animator animator;
    private Vector3 moveDestination;
    private float moveTime = 0.0f;

    private void Start() {
         moveDestination = transform.position;
    }

    public void Down()
    {
        // when the character isn't already moving, move it down
        if (moveTime <= 0.0f) {
            moveDestination = transform.position + new Vector3(0, -1f, 0)
            moveTime = 1.0f;
            animator.SetTrigger("moveDown");
        }
    }

    public void Update() {
          if (moveTime > 0.0f) {
              moveTime -= Time.deltaTime;
              transform.position = Vector3.Lerp(moveDestination, transform.position, moveTime);

              if (moveTime <= 0.0f) {
                  animator.SetTrigger("idle");
              }
          }
    }
}

```

Also you need to remove transition duration
Click on transition arrow in Animator window, then in Inspector window expand `Settings` under `Has Exit Time` and set both `Transition Duration` and `Transition Offset` to 0.

---
Tags: unity, 2d, animation, movement
---


# Question
Title: Special Texture Stretching without deformation
I am trying to achieve a special texture stretching effect in my shader. Here is how I define my uv before sampling my texture, nothing really special.

```
// uv_ST contains the tiling and offset values
uv.xy = uv.xy * uv_ST.xy + uv_ST.zw

```

This gives the standard tiling/stretching and offset behaviour when you tile/stretche a clamped texture as you can see in the image below. First is normal, second is offset and last is stretching.

But I want to avoid the deformation behaviour when stretching, I want to keep margins when stretching my texture or simply cut it in the middle and stretching it. Here is an illustration below.

How could I do that inside my shader when defining my uvs before sampling the texture ?

# Answer
The **Nine Patches** algorithm is a really nice and powerful solution if you are using textures but I ended up by using a fully procedural solution.

I am just drawing a round box like this.

```
float udRoundBox( vec3 p, vec3 b, float r )
{
  return length(max(abs(p)-b,0.0))-r;
}

```

You can simply avoid the 3rd dimension if you don't need it. This method comes from the Distance function article from **Inigo Quilez**.
> -2 votes

# Answer
So, essentially what you're looking for is 9 Slice Scaling. However that's only good for stretching out a texture so the *edges and corners* remain undeformed (sort of).

* The corners are 1:1 in both directions.
* The edges are 1:Y or X:1 depending on if they're horizontal or vertical (that is, non-uniform, but such that the stretched direction is unnoticed because all the pixels are the same).
* The center is then X:Y and is usually unnoticed because its just a solid fill.

But it seems like you're needing the center to be unstretched too. There is a way to accomplish this, but you'll have to code it yourself using the same sort of math that makes 9-slice scaling work. And you seem to only be stretching in one direction (that'll make it easier).

There's no pre-build solution for your use-case, but it should be easy to work out! Just count how many pixels you need to leave undistorted and make sure that you draw that area at it's exact size. Then you can stretch out the middle to fill the needed space (or at least, stretch out the next *chunk*) and then draw the other edge at the exact size again.
> 4 votes

---
Tags: opengl, shaders, directx, glsl, hlsl
---


# Question
Title: Using unity Rigidbody 2D gravity, how to add to velocity?
I am creating a top-down game, and have an object I want to create a small bouncy illusion for. Since I dont have anything to collide with I'll have to do it with Scripts.

Without Unity I would probably do something like:

```
function fall ()
{
    this.vertical_speed = this.vertical_speed + GRAVITY;
    if (this.vertical_speed > TERMINAL_VELOCITY)
    {
        this.vertical_speed = TERMINAL_VELOCITY;
    }
    this.vertical_position = this.vertical_position - this.vertical_speed;
}

```

However in Unity we have the `Rigidbody 2D`, so I want to somehow use that for this.

if I set `rigidBody.velocity = new Vector2(1, 0) * speed * delta;`, it gets a constant speed, and ignores gravity. How can I add gravity?

i.e: I want to create a curve like:

# Answer
> 2 votes
Preserve the existing vertical (ie. Y) movement. That is, when you create the vector to assign, use the existing velocity.y for the y component of the vector, and only create a new x component.

# Answer
> 1 votes
If you are using gravity on the rigidbody and also setting the rigidbody using new Vector2 then just add the current velocity y to it

```
new Vector2(1, rigidBody.velocity.y);

```

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


# Question
Title: Why does AudioSource not initializes itself?
Why does AudioSource not initializes itself?

Here is my code:

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

public class CameraConfig : MonoBehaviour
{
    public GameObject objToFollow;

    public bool followRabbit;

    // Use this for initialization
    void Start()
    {
        followRabbit = true;
        LevelController.current.cameraWhichLooksForRabbit = this;

        setMusicSource();
        setSoundSources();
    }

    public AudioClip music, rabbitWalksSound, rabbitDiesSound, rabbitFallsSound, enemyAttacksSound;
    private AudioSource musicSrc, rabbitWalksSrc, rabbitDiesSrc, rabbitFallsSrc, enemyAttacksSrc;

    private void setMusicSource()
    {setClipForSrc(musicSrc, music, true);}

    private void setSoundSources()
    {
        setClipForSrc(rabbitWalksSrc, rabbitWalksSound, false);
        setClipForSrc(rabbitDiesSrc, rabbitDiesSound, false);
        setClipForSrc(rabbitFallsSrc, rabbitFallsSound, false);
        setClipForSrc(enemyAttacksSrc, enemyAttacksSound, false);
    }

    private void setClipForSrc(AudioSource src, AudioClip clip, bool loop)
    {
        src = gameObject.AddComponent<AudioSource>();
        src.clip = clip;
        src.loop = loop;
    }

    void Update()
    {
        checkMusicAndStopOrStartIfNecessary();

        if (!followRabbit)
        { return; }

        Transform rabit_transform = objToFollow.transform;
        Transform camera_transform = this.transform;

        Vector3 rabit_position = rabit_transform.position;
        Vector3 camera_position = camera_transform.position;

        camera_position.x = rabit_position.x;
        camera_position.y = rabit_position.y;

        camera_transform.position = camera_position;
    }

    public void playSoundRabbitWalks()
    {
        if (!rabbitWalksSrc.isPlaying)
        { rabbitWalksSrc.Play(); }
    }

    public void playSoundRabbitDies()
    { rabbitDiesSrc.Play(); }

    public void playSoundRabbitFalls()
    { rabbitFallsSrc.Play(); }

    public void playSoundEnemyAttacks()
    { enemyAttacksSrc.Play(); }

    public void stopSoundRabbitWalks()
    {
        if (rabbitWalksSrc.isPlaying)
        { rabbitWalksSrc.Stop(); }
    }

    public void stopSoundRabbitDies()
    { rabbitDiesSrc.Stop(); }

    public void stopSoundRabbitFalls()
    {rabbitFallsSrc.Stop();}

    public void stopSoundEnemyAttacks()
    {
        enemyAttacksSrc.Stop();
    }

    private void checkMusicAndStopOrStartIfNecessary()
    {
        if (SoundManager.Instance.isMusicOn() && !musicSrc.isPlaying)
        { musicSrc.Play(); }
        else if(!SoundManager.Instance.isMusicOn() && musicSrc.isPlaying)
        { musicSrc.Stop(); }
    }
}

```

Here are screenshot of the exceptions in console and inspector view:

# Answer
> 2 votes
`AudioSource` is a class, which means it is a reference type. The default value of a reference type that is declared without initialization

```
SomeReferenceType someThing;

```

is null. That's how C# works.

Even if it were *possible* for `AudioSource` to "initialize itself" when declared the way you are declaring them, how would it know what to initialize itself *with*? `AudioSource` is about playing back audio clips, so an individual audio source needs to know which clip to play, et cetera.

You need to either explicitly initialize your `AudioSource` instances in your code (`musicSrc = new AudioSource(...)` and so on) or expose them to the inspector and set them there. It sort of looks like that latter option is what you *expected* to be doing, given the screenshot of the inspector in your original screenshots, but what you've shown there is exposure and initialization of the audio *clips*. Not the sources.

---

Actually, it looks like you expected `setClipForSrc` to do this initialization for you, but if that's what you want you need to pass the clip using `ref`:

```
private void setClipForSrc(ref AudioSource src, AudioClip clip, bool loop)
{
    src = gameObject.AddComponent<AudioSource>();
    src.clip = clip;
    src.loop = loop;
}

```

and then call it as `setClipForSrc(ref musicSrc, ...)`. Without `ref`, what you are doing is simply reseating the local reference inside the function to refer to a new value, you are not actually changing what the member variable references `musicSrc` et cetera refer to. This would work if all you wanted to do is call functions on `src` or otherwise mutate it, but if you to completely re-assign it to point to a new object, and you want that re-assignment to propagate beyond the function `setClipForSrc`, you need to pass the reference `src` by reference itself, using the `ref` keyword.

---
Tags: unity, audio, initialization
---


# Question
Title: Change width and height of 2D object based on pixel size and count
I'm working on a shooting simulator with shooting goals that need to be in real world size. I know the certain size of screen display and pixel counts.

Is there anyway to change their size based on screen information?

let me explain more about question.

its a real shooter simulator with real guns. image of unity simulation is projected on a wall or... by a video projector. I want to scale goals as real ones. I know size of screen and even size of every pixel. so I want to scale my rectangular goals with size of real ones.

I think the question now is obvious

# Answer
If you mean that they need to have static sizes regardless of screen size, you would need to calculate by resolution AND exact screen size (this is actually difficult, as you'd need a database of all possible screens this can run on).

So, for instance, 1cm x 1cm images are going to be different pixel sizes on an iPhone 4 and an iPhone 6 Plus, not to mention on a Galaxy S7.

iPhone4 = 960 x 640 resolution on a 7.4cm x 4.9cm screen = ~130px x 130px

iPhone 6 Plus = 1334 x 750 @ 12.2cm x 6.8cm = ~110px x 110px

Galaxy S7 = 2560 x 1440 @ 11cm x 7cm (roughly) = ~ 230px x 230px

Needless to say, this isn't an ideal scenario to try to pull off, which is why it's rare for games to use real-world sizes for things.
> 0 votes

---
Tags: unity
---


# Question
Title: Rendering only a part of the screen in high detail
If graphics are rendered for a large viewing angle (e.g. a very large TV or a VR headset), the viewer can't actually focus on the entire image, just a part of it. (Actually, this is the case for regular sized screens as well.)

Combined with a way to track the viewer's eyes (which is mostly viable in VR I guess), you could theoretically exploit this and render the graphics away from the viewer's focus with progressively less details and resolution, gaining performance, without losing perceived quality.

Are there any techniques for this available or under development today?

# Answer
> 7 votes
There are examples of such effects you are talking about in many games. First, there is **Depth of field**, which makes object at a distance look blurred, just as if the camera is focusing on things only close to it, like in this example. You can explore more samples related to this in the DirectX SDK package- they have sample code there too. For OpenGL, you will get them on the net if you search.

The second thing you may want to see is what is maybe known as **Geometry MipMaping or Progressive Meshes** which, like the name suggests, is similar to texture mip-mapping, but for geometry. The number of polygons in a mesh is reduced as the object gets further away from the camera. This helps in increasing performance. In D3D, there exists a function which will help in generating Progressive meshes automatically. Here it is:

```
HRESULT WINAPI D3DXGeneratePMesh(
                                  LPD3DXMESH pMesh,
                                  const DWORD *pAdjacency,
                                 const D3DXATTRIBUTEWEIGHTS *pVertexAttributeWeights,
                                  const FLOAT *pVertexWeights,
                                  DWORD MinValue,
                                  DWORD Options,
                                  LPD3DXPMESH *ppPMesh
                                 );

```

Here's an example of this:

**EDIT:** Consider the following image-

This is the camera's culling frustum. The line that goes right through the middle is the LookAt vector. Now, assuming the player will always want to focus at the centre of the screen, you define the angle x. Any object that will be positioned at an angle more than the decided x will have a low resolution rendering, and the ones which are within the angle will be rendered with detail. Like this, the objects at the centre of the screen will be more detailed than the ones on the sides. For if the player is not looking at the centre, then just adjust that centre line to the direction in which the player is looking at. ( or maybe rotate the whole camera to that direction).

# Answer
> 2 votes
Yes, Foveated Rendering utilizes eye tracking to only render what the user is looking at in high detail. Everything else, can be rendered in lower detail.

While it's fairly obvious when looking at a screenshot like this, it's reportedly invisible to the user in VR.

The existing mainstream headsets don't include eye tracking (yet), but there are a few after-market solutions to add eye tracking. Further a small amount of additional processing is required for the rendering process. However the benefits are significant. With foveated rendering implemented, only a small percentage FOV needs to be rendered in high detail, this can result in dramatically higher frame rates. Exact numbers depend on the implementation.

Further, this isn't even limited to VR headsets. It can be used on desktop monitors as well (with the addition of eye tracking and to a more limited effect).

# Answer
> 1 votes
Expanding on Byte56's answer, yes this sort of thing is being developed in the industry. Fixed Foveated Rendering is a technique employed by Valve in their robot repair demo (https://youtu.be/DdL3WC\_oBO4?t=769) and in a few commercial games (Resident Evil VII for PSVR comes to mind). Fixed Foveated Rendering does not employ eye tracking but this means it works well with current versions of VR headsets which currently do not have any sort of eye-tracking capabilities. Though right now the Vive is supposed to get an eye-tracking upgrade kit so you may see some AAA VR titles utilize that.

You won't find many code-samples available related to this sort of thing but Nvidia does have some hardware extensions that are decently documented. Multi-resolution is fairly well explained but is a feature tied to their hardware.

---
Tags: opengl, directx, rendering, virtual-reality
---