# Question
Title: Vector2.Zero unexpected behaviour when used to initialize Vector2
I have base class which contains a `Vector2 velocity` field, which I was initializing in the constructor with `Vector2.Zero`. But that caused an issue so I had to replace it with `new Vector2(0, 0)`

```
public abstract class BaseEntity {
   private Vector2 velocity;

   public BaseEntity() {
     // velocity = Vector2.Zero; // this causes the issue
     velocity = new Vector2(0, 0);  // this I am using now
   }
}

```

The problem was that when I was adding other entities like `Ship`, `Rock` which extend the `BaseEntity` they were always moving in the same direction. So when I was moving the player, rocks and other entities which extend that `BaseEntity` class were following movement of my player.

I am not able to understand why that is; could someone explain to me why that issue occurred?

# Answer
This is obvious from the semantics of Java.

Unlike C# structs, Java class instances are reference types. When you write:

```
Vector2 a = new Vector2(0, 0);
Vector2 b = a;

```

...you have not *copied* the vector `a` into `b`, creating two zero vectors. You have copied a *reference* to the *same* vector into `b`, so now you have two aliases that refer to the same logical object / the same bit of memory.

If I then write

```
b.x = 5;
DebugPrint(a.x);

```

...it will print "5" — because mutating `b` mutates `a`, because they're just two names for the same object.

This is what your code does when it takes a reference to `Vector2.Zero`. It's not initializing a *new* vector with zero for each component, it's saying "I am taking the definition of zero itself, to change how I please". If you mutate this value by setting its `x`/`y` components, you have mutated the shared value of `Vector2.Zero` observed anywhere in your code. If multiple objects have all "borrowed" zero in this way, they'll all see each other's mutations in their "own version" because they don't have multiple versions of the vector at all, just a bunch of references to the same one.

So, lesson: if you want to initialize a new mutable vector to zero, just write `new Vector2()`the default constructor already does exactly that, and it's no more characters to type than what you were doing already.

Use `Vector2.Zero` as a read-only value when you want to do something with a zero vector without constructing a temporary. That's all it's for.
> 1 votes

---
Tags: java, libgdx
---


# Question
Title: Why does today's "Metaverse" look equally or even worse than the 1990s 3D chat worlds?
In late 1990s and early 2000, I tried out "Active Worlds" and more. They let me register an account and then walk around in a vast 3D world and chat with people/avatars. It was surreal and frankly felt more scary and unsettling than exciting, in spite of the bright and colorful visuals.

Fast-forward to ~2007, there was a brief mainstream "Second Life" craze. I tried it out for about 15 minutes then and was forced to conclude that it looked even worse than what I remember from those many years earlier.

Now there's yet again this "Metaverse" being constantly mentioned/pushed. This time, I didn't even bother downloading anything (I bet I couldn't even join it now anyway, as it seems to require a Facebook account or something), but rather just watched gameplay footage on YouTube.

It looks exactly like it did 22+ years ago. No joke.

It's still the same worse-than-cartoony, deadly dull, sterile look. I expected it to be literally photo-realistic at this point, but they seem to not even be trying.

Can somebody please explain to me how it's possible that so much happened up until the late 1990s, but since then, apparently, *nothing* has improved whatsoever? I know for a fact that they are able to make extremely realistic simulations, so why can't I launch an EXE on my desktop right now which lets me walk around in first person in an extremely realistic virtual city and own my own virtual apartment and go down to the store and buy items and have all kinds of exciting adventures which I would never dare or be able to do in real life?

Not only are we "not quite there yet" -- they don't even seem to be *trying*, or even using existing technology. I don't get it.

# Answer
> 3 votes
I believe this is a based on multiple factors:

First of, the concept of a Metaverse mainly makes sense in VR, of which the portable headsets have very strict polygon and material budgets. Secondly, in a Metaverse implementation most of the assets would be user created, which would make it hard to have a unified and polished look and feel. In Facebook's conference there where many depictions of how their Metaverse it will look, and I believe they chose a simple art style to make it easily understandable, attractive to shareholders and hard to under-deliver.

As for the fidelity of virtual characters; Facebook showed of some semi-realistic photoscans of people, but as they are not out of the uncanny valley quite yet, and because users wouldn't want to represent themself with their real body anyway, characters still look very stylized and simple.

I don't think realistic graphics will never be achieved, but currently the focus of Metaverse implementation lies elsewhere.

---
Tags: 3d, mmo, virtual-reality, online, non-photorealistic
---


# Question
Title: How to make trigger function respond to certain collider pairs and not others?
I assigned two colliders to one GameObject. Both are different sizes. I am doing operations with Trigger messages.

I want this Trigger function to work for only colliders 1 and 3, but not collider 2.

# Answer
I gave the number 1 collider to the child gameobject and set it with the collison layer and I solved my problem.
> 0 votes

---
Tags: unity, physics, collider
---


# Question
Title: How do different compositions/types of entities interact in an ECS-system?
I have a working ECS-system set up, largely inspired by this brilliant article (not at all required reading to be able to answer my question) on https://indiegamedev.net/ showcasing an ECS-system with proper data locality. I've modified it quite a bit, but the general layout of the API is pretty much the same.

```
struct SystemFunctor
{
    void operator()
        (float timeSteps, const std::vector<EntityID>&,/*(arrays ->)*/PhysicsComp*, RenderComp*);
};
void system(float timeSteps, const std::vector<EntityID>&,/*(arrays ->)*/PhysicsComp*, RenderComp*);
...

SystemFunctor f;
engine.registerSystem<Engine::RENDER_LAYER_1>(f);

engine.registerSystem<Engine::RENDER_LAYER_1>(system);
/* Both of these calls register a system that operates on entities with at least a
PhysicsComp and a RenderComp, and will be called when the system layer RENDER_LAYER_1 is run. */

```

As the title reads, my question is: How can entities that have no component types in common interact with each other? Since a system only receives data from entities whose types are a subset of the entity composition it operates on, how could it receive the data it needs to perform interactions between wildly different entities?

To get a little more specific, here is the current problem I'm trying to solve:

I'm making a small exercise program where the user draw points on the screen with the mouse, and a point-quadtree for all the points is recomputed and drawn (as boxes) on the screen when new points are added.

The adding and rendering of the points was easy - just one system that checks for input and creates the points and another one for rendering them. But when it comes to storing and managing a quad-tree that can come into contact with the point entities I'm at a loss.

Naturally, you would have some kind of quad-tree component:

```
struct QuadTreeComp
{
// Whatever data your quad-tree implementation uses
};

```

But from there, I can't seem to figure it out. How do you set up a system that operates on one entity (the one with the `QuadTreeComp`) while also operating on a bunch of other entities, i.e. the points?

One possible solution I could see is that the system functor that updates the quad-tree doesn't actually operate on `QuadTreeComp`, but on the points. In its constructor it instantiates an entity with the `QuadTreeComp` and stores the entity id. Then in its actual function body, it can get the quad-tree component using the id and update it with the points.

```
class UpdateQuadTree
{
public:
    UpdateQuadTree(Engine& engine):
        engine_{engine},
        quadTreeEntity_{ engine.newEntity() }
    {
        engine.add<QuadTree>(quadTreeEntity_);
    }
    void operator()
        (float timeSteps, const std::vector<EntityID>& entities, Vector2f* points)
    {
        QuadTree* quadTree = engine.getComponent<QuadTree>(quadTreeEntity_);
        /*
                                      ^
                                      |
                            Already an existing function in my ECS-API
        */

        // Update the quad-tree using the points...
    }
private:
    EntityID quadTreeEntity_;
    Engine& engine_;
};

```

The problem with this one is that don't see how other systems that operate on the quad-tree, like the one that renders it, would know the id of the entity.

What would be the textbook-ECS-way of performing these interactions?

# Answer
> 1 votes
I think your example is very specific, so I don't think there is anything in "textbooks" about this.

I'll start with mentioning that there is no ECS police, and so if an implementation and an approach works for you, your team and your case, then it's fine to go with it and not overthink it.

It's not clear to me what would be the interaction between the Points and the QuadTree in your example, so I'll assume that the QuadTree nodes are modified as new points are added.

I think you're missing a component: `QuadTreeNodeComp`.

You *can* assume that there will be only one QuadTreeComp, but that might backfire in the future. Alternatively, you can assume that there are multiple QuadTrees, and identity it as such. Then you can make sure that your Points should be organized according to this specifically identified QuadTree.

Assuming we have a `QuadTreeNodeComp` that looks like this:

```
struct QuadTreeNodeComp
{
  // If you don't use std::ptrs infrastructure, make sure those values are
  // nullable so that you can identify the type of the nodes (top node, leaf
  // node).

  std::weak_ptr<Entity> mParentQuadTreeNodeComp;
  std::array<std::weak_ptr<Entity>, 4> mChildrenNodes;

  // To identify to which QuadTree this node belongs.
  int mQuadTreeId { -1 };
};

```

... and a `PointComp` struct that looks like this:

```
struct PointComp
{
  Vector2f mPoint;

  // To identify to which QuadTree this node belongs.
  int mQuadTreeId { -1 };
};

```

... and an updated `QuadTreeComp` struct that looks like this:

```
struct QuadTreeComp
{
  int mQuadTreeId { -1 };
  std::weak_ptr<Entity> mRootQuadTreeNodeComp;
};

```

... when a point is added/moved/removed, update your set of Entities that have a `QuadTreeComp` associated with the Points and the QuadTree (based on the QuadTree identifier):

```
UpdateQuadTree::Update(
  const std::vector<EntityID>& entitiesWithQuadTreeComp,
  const std::vector<EntityID>& entitiesWithQuadTreeNodeComp,
  const std::vector<EntityID>& entitiesWithPointComp )
{
  for ( auto& entitieWithQuadTreeComp : entitiesWithQuadTreeComp )
  {
    auto& quadTreeComp = entitieWithQuadComp.getComponent<QuadTreeComp>();
    auto id = quadTreeComp.mQuadTreeId;

    // You can figure of a way to delete the entity/components that no longer
    // have a point in the node, create new Entities/QuadTreeNodeComp that have
    // points in their nodes, etc.
    //
    // For the Entities that have a QuadTreeNodeComp which is a Leaf node, make
    // sure they also have a RenderComp. The ones that are not Leaf nodes, make
    // sure the do not have a RenderComp.
  }
}

```

This is probably not considered purely a "system function" as it does not operate on entities having a subset of components. It's a function that reorganize your entities. (I suppose that this is the answer to your question *"How do different compositions/types of entities interact in an ECS-system?"*.)

After this, you have

* a series of Entities that contain a PointComp and a RenderComp,
* a series of Entities that contain a QuadTreeNodeComp and a RenderComp (those are the leaf nodes),
* a series of Entities that contain only a QuadTreeNodeComp (and no RenderComp, these are the intermediate nodes, they're not rendered),
* and one Entity that contains a QuadTreeComp.

The Points and the Leaf nodes will be rendered, and you can do whatever else you need with those other entities.

Finally, this may not be the only way to go about this, but it's the approach I'd likely take if I faced this kind of situation.

---

> The problem with this one is that don't see how other systems that operate on the quad-tree, like the one that renders it, would know the id of the entity.

I don't know how you've engineered your project, but one of the key features I've seen required is a way to know to which Entity a Component belongs from the Component itself. If you don't have that, then you'll likely need to think of a way to have this.

# Answer
> -1 votes
The point of System (as in ECS) is to update components of a **single entity**. System will be designed around that core assumption, with all the pros and limitations.

Your goal, on the other hand, is to update **entire set of entities**, while using entire table of components as an input to this operation. You'll need to access the input entities all at once (assuming that you want to calculate quad-tree efficiently), and create/update/delete the output entities in a single pass.

Which means that your operation does not fit the idea of System (as in ECS), and there is no point of shoehorning it into a System. Realize that every pattern has a scope, and there is entire game engine outside of it's ECS department.

For example, all games have to have **Services** — those provide centralized access to shared state. I sometimes see people putting those into a "singleton" entity, but this is just a cargo cult programming, and there is no benefit to doing that. The best practice here would be regular everyday normal Dependency Inversion (or it's poor and evil brother Service Locator).

---

The most straightforward solution to your specific problem is to handle the task inside a service, that just reads and writes all the relevant entities and components. If there are no more inputs and outputs besides the ECS stuff, then a service may be as simple as a function (or a functor — so it can hold a reference to the ECS tables).

If you want to follow the data-driven approach, generalize the update step to work outside of a single entity. Let's call the update function **Updater** instead of System (and, quite frankly, the name "System" never made sense to me). During the registration step, an updater may request read or write access to entire table (including the entity-component relation table, to allow creation and deletion of entities). It's up to the updater how to read and update those tables. A System will be just a special case of updater.

---
Tags: c++, software-engineering, entity-system, component-based, entity-component-system
---


# Question
Title: How do I get the consistent time it would take for two points to reach each other in circular motion?
I'm making a 2D game. It involves the player swinging around a grapple hook in perfect circular motion, however, I want to make the cooldown for this ability based on predicted end position for the grapple hook. (I'll probably make it later based on the actual duration of the swing, but for learning purposes I want to try to accomplish this)

Is there any consistent way to calculate how long it would take for point B to reach point C?

```
local radius = adventurer.position:Distance(self.hook.position)
local angularSpeed = self.hook.direction == 0 and 1200/radius or -1200/radius
local angle1 = math.atan2(adventurer.position.y - self.hook.obj.position.y, adventurer.position.x - self.hook.obj.position.x)
local angle2 = math.atan2(self.hook.endPosition.y - self.hook.obj.position.y, self.hook.endPosition.x - self.hook.obj.position.x)
return (angle2 - angle1) / angularSpeed

```

This is how I'm currently accomplishing it, and it works (granted it breaks based on the direction it's facing, but that can be fixed in the future). However, my results come up like this

```
 0.37500011637114
 0.37499976172673
 0.29999967327458
 0.30000022575076
 0.22499981690334
 0.22500003318263
 0.22499987895093
 0.150000220043
 0.14999986219868
 0.074999761129465
 0.075000182872622
 0.074999642457876
 0.074999641417049

```

Is there any way to get consistent time? Where the results would be more like

```
0.10
0.09
0.08
...

```

Instead of like

```
0.22
0.22
0.22
0.14
0.14
0.14
0.07
0.07
...

```

# Answer
> 0 votes
If I understood your problem correctly, you are experiencing one of the "catches" of floating point math - it will give you results like these with a lot of decimals at the end. You're likely best off rounding your number at the end - make sure you do this as little as possible and only before you actually need to present this to the user.

As an aside, this is why you should forget about comparing floating point numbers for equality - you will likely get a lot of false negatives even when the result "should" have been the same.

Another thing to keep in mind is that the more towards the right (= smaller parts of the decimal), the less uncertain the numbers become, so you should do your calculations on numbers with as close order of magnitude of possible - if you add a number that's a small fraction of 1 to a number that's a few million, you'll likely get garbage results...

---
Tags: 2d, physics, geometry, lua
---


# Question
Title: How can I make the X button in the Cardboard XDK exit VR mode?
When I build a game using Unity 2017.2.0f3 and the Cardboard SDK (using XR settings) and run it on my device, I see two controls overlaid on the screen, a cross and a gear:

Currently, pressing the cross control does nothing. I'd like to make the cross exit VR mode when pressed.

# Answer
When clicking ✕ (close), your Unity app should get an escape key press notification & you should be able to handle it the same way as an actual key down event. For example, to quit, you would do this:

```
void Update(){
  if(Input.GetKeyDown(KeyCode.Escape)){
    // close icon pressed, place appropriate code here
    Application.Quit();
  }
}

```

There was an error that prevented this; make sure Unity & your various SDKs are patched & up to date.
> 3 votes

# Answer
It looks like a simple UI. I suppose you need to find right Canvas in the Unity3d Editor window and add OnClickEvent to these elements (cross and settings icons). If cross is containing button component you will simply need to add OnClickEvent that will escape VR mode.
> 0 votes

# Answer
Here i am writing my solution

```
using UnityEngine;
using Google.XR.Cardboard;
using UnityEngine.XR.Management;
using System.Threading.Tasks;
public class UISettingsVR : MonoBehaviour
{
void Start()
{
}
/// <summary>
/// Gets a value indicating whether the VR mode is enabled.
/// </summary>
private bool _isVrModeEnabled
{
    get
    {
        return
        XRGeneralSettings.Instance.Manager.isInitializationComplete;
    }
}

/// <summary>
/// Update is called once per frame.
/// </summary>
public void Update()
{

    if (XRGeneralSettings.Instance == null ||
        XRGeneralSettings.Instance.Manager == null)
        return;

    if (_isVrModeEnabled)
    {
        if (Api.IsCloseButtonPressed)
        {
            ActivateTwoD();
       //Do YOUR STUFF

        }

        if (Api.IsGearButtonPressed)
        {
            Api.ScanDeviceParams();
        }

        Api.UpdateScreenParams();
    }
}

public void ActivateVR()
{
}

public  void ActivateTwoD()
{
}
}

```
> 0 votes

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


# Question
Title: Level Creation - How to achieve seamless race tracks?
I'm aiming to make a racing game in Unity. Please take a look at the image provided below, and suggest me the best technique to achieve something like it. (Keeping the performance as optimized as possible)

**How I'd do it:-** Make a large model in blender, texture it inside a software like Substance Painter, then import it into unity with one texture.

**Problem with my method:-** The model will be destructive, means it'll be really hard to make changes to it once I'm done texturing. Secondly, It'll likely have very large resolution (4k or 8k) which is not desirable for mobile devices (what I'm aiming for).

**Solution I can think of:-** I can think of having the road divided into small pieces, but I just can't figure out how will I join them together? While still keeping the surrounding environment in sync. Thanks.

# Answer
> 0 votes
This is an answer about how *not* to do it. *Don't* make the whole track as a single mesh.

I worked on a racing game for mobile a few years ago where the artist had faced a similar dilemma. The tracks themselves were offroad courses made with Unity's terrain feature, but each track had a barrier around it that the artist made as a single large mesh.

The problem with using a single large mesh is that the engine can't perform frustum culling. Frustum culling is when the engine skips rendering an object that is not within the camera view. This is one of the most basic ways that 3D engines are optimized for performance - there's no point in rendering anything that isn't visible on screen.

At least some part of the barrier was on-screen at all times. Because it was all a single mesh, the engine couldn't perform any frustum culling, so it was always rendering the entire barrier, which was typically several hundred thousand polygons. This was enough to severely impact framerate on low-end and mid-range mobile devices.

Another common optimization that doesn't work with large meshes is Level of Detail (LOD) models. If your entire track or barrier is one mesh, the player will always be near some part of the mesh, so you can't use lower-polygon LOD models for distant parts of the track.

Building your track, and other parts like barriers, in pieces allows you to take advantage of frustum culling and LOD models for maximum performance.

As for texturing, I think generally you create textures that cover a small section of the track and tile these across the track. Here's a very simple, sloppy example:

You may need variations for turns or to prevent the texture from looking too repetitive. Details such as skid marks and oil slicks can be added with decals as another way to prevent the road from looking repetitive.

---
Tags: unity, graphics, models
---


# Question
Title: How do i execute a function after another function ends? Like how can you tell unity that this function is done then executing the next?
```
 void Update()
{
    if (Time.time > nextSpawnTime)
    {
        FirstSpawnScript();
        //SecondSpawnScript();
        //ThirdSpawnScript();
        //FourthSpawnScript();
    }

}
void FirstSpawnScript()
{
    float SecondsBetweenSpawns = Mathf.Lerp(SecondsBetweenSpawnsMinMax.y, SecondsBetweenSpawnsMinMax.x, Difficulty.GetDifficultyPercent());
    {
            print(SecondsBetweenSpawns);
                float SpawnAngle = Random.Range(-SpawnAngleMax, SpawnAngleMax);
                nextSpawnTime = Time.time + SecondsBetweenSpawns;
                Vector2 spawnPosition = new Vector2(Random.Range(-ScreenWrapSpawn.x, ScreenWrapSpawn.x), ScreenWrapSpawn.y + .5f);
                Instantiate(FirstSpawn, spawnPosition, Quaternion.Euler(Vector3.forward * SpawnAngle));
            Spawning = false;

    }
}

void SecondSpawnScript()
{
    float SecondsBetweenSpawns = Mathf.Lerp(SecondsBetweenSpawnsMinMax.y, SecondsBetweenSpawnsMinMax.x, Difficulty.GetDifficultyPercent());
    {
        {
            nextSpawnTime = Time.time + SecondsBetweenSpawns;
            float SpawnAngle = Random.Range(-SpawnAngleMax, SpawnAngleMax);
            Vector2 spawnPos = new Vector2(Random.Range(-ScreenWrapSpawn.x, ScreenWrapSpawn.x), ScreenWrapSpawn.y + .5f);
            Instantiate(SecondSpawn, spawnPos, Quaternion.Euler(Vector3.forward * SpawnAngle));

        }

    }

```

These are the two function i mean

# Answer
I think you are looking for coroutines.

A coroutine is a method which can interrupt itself using the `yield return` statement in order to be later resumed on another frame. This is useful when you have sequences of actions you want to perform within pauses between them instead of all at once. This example will log "1", "2", and "3" to the console with 1 second pauses in between:

```
class CoroutineExample : MonoBehaviour {

    // start a coroutine when this object is created
    void Start() {
        StartCoroutine(Count());
    }

    // the coroutine
    private IEnumerable Count() {
        Debug.Log("1");
        yield return new WaitForSeconds(1f);
        Debug.Log("2");
        yield return new WaitForSeconds(1f);
        Debug.Log("3");
    }
}

```

the `yield return` statement can use more than just `new WaitForSeconds`. For example, you can pass another coroutine method. This allows you to chain coroutines. This example will first execute the first coroutine (logging "1", "2" and "3"). It will wait until the coroutine is finished, then wait for another second, and then start the second coroutine (logging "A", "B", "C");

```
class CoroutineExample : MonoBehaviour {

    // start a coroutine when this object is created
    void Start() {
        StartCoroutine(CountAndSpell());
    }

    // The main coroutine chaining two other coroutines
    private IEnumerable CountAndSpell() {
         yield return Count();
         yield return new WaitForSeconds(1f);
         yield return Spell();
    }

    // Sub-Coroutine 1
    private IEnumerable Count() {
        Debug.Log("1");
        yield return new WaitForSeconds(1f);
        Debug.Log("2");
        yield return new WaitForSeconds(1f);
        Debug.Log("3");
    }

    // Sub-Coroutine 2
    private IEnumerable Spell() {
        Debug.Log("A");
        yield return new WaitForSeconds(1f);
        Debug.Log("B");
        yield return new WaitForSeconds(1f);
        Debug.Log("C");
    }
}

```
> 1 votes

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


# Question
Title: Linux Game Development - Dependency Management
I'm working on a game that I'm trying to build for Linux and distribute via Steam. At present, there are some dependency issues and I'm wondering about the best approach:

1. Bundling .so files with the executable (Is bundling legal/safe? The libraries in question are libopengl.so.0, libopenal.so.1, and libsteam\_api.so which I'm less concerned about)
2. Including a shell script to check for/prompt installation of dependencies (I can apt install all the necessary dependencies, of course. But I want to be respectful and not force install of something without permission.)

Assuming that we're bundling one or more .so files, I'm unclear on whether LD\_PRELOAD or LD\_LIBRARY\_PATH is the preferred approach to inform the executable about their presence. Which is preferable?

# Answer
Is bundling legal?

That depends on the license terms of the library. For example, the GPL says that if you use a GPL-licensed library then your whole game must be licensed under the GPL, while a LGPL-licensed library permits you to bundle your libraries with non-GPL software as long as they are dynamically linked.

Is bundling a good idea?

Yes. There are lots of good reasons for operating systems to manage libraries in a centralized manner. But gaming isn't one of them.

* Giving the user the ability to patch libraries system-wide independently from the applications which use them does not matter, because games are usually not run on high-security systems and usually don't act as public servers (game *servers* are of course another subject).
* Storage space does not matter, because games usually take gigabytes of storage anyway. A couple MB of redundant libraries is not going to matter.
* What does matter for games, though, is having a robust, idiot-proof setup which just works out-of-the-box without the user having to tinker with anything. Shipping your game with all its libraries included makes sure that the game won't malfunction because the end-user happens to have a newer version of a library which happens to work just a slight bit different. Every possible point-of-failure of your game installation process means you are going to get a couple more negative reviews saying "Does not run - refunded". So you want to minimize them as much as you can.
* When you use Steam, you can't install system-wide libraries because you don't know which package manager is used by the Linux distribution the user is using. `apt` is not the only package manager. There are also `pacman`, `yum` and a lot more exotic options. You can't possibly write an install script which detects and supports them all. Technically Steam is also a package manager. But its ability to install system-wide libraries is limited to the list of "Common Redistributables" provided by Valve. You *can* handle dependencies shared between Steam games using "Shared Depots". But in order to share these dependencies, you need to have control over all the games making use of them. So if you plan to release a lot of games which all use the same versions of various libraries, you could *theoretically* turn those into a shared depot so players who install more than one of your games don't need to download your libraries twice. But I doubt it's worth the effort, because again, libraries are rarely the bulk of a game download. Shared depots are mostly intended for shared *assets*.
> 2 votes

---
Tags: linux, steam
---


# Question
Title: How to Correctly Declare Unity's New System Input as an Assembly Definition Reference
I have 3 main assemblies, Core, Character, and Interactable. Interactable and Character both depend on Core. I got an error saying I needed to add TMPro as a dependency for Core, so I did that, and all was right with the world. But when I got the same error with InputSystem I went down a rabbit hole of old forum posts that led to no meaningful results.

I have tried:

* Reinstalling InputSystem
* Regenerating the Project Files
* Relaunching Rider
* Relaunching Unity
* Removing Rider as the default IDE, and re-adding it
* And most of these in combination with each other

I also don't know exactly what to post, as none of the errors seem to be in my code, it seems to be in my project settings. Here's the full error message:

```
Assets\Scripts\Character\PlayerController.cs(3,19): error CS0234: The type or namespace name 'InputSystem' does not exist in the namespace 'UnityEngine' (are you missing an assembly reference?)
Assets\Scripts\Character\PlayerController.cs(66,29): error CS0246: The type or namespace name 'InputValue' could not be found (are you missing a using directive or an assembly reference?)

```

Thanks for any and all help!

# Answer
> 2 votes
So, this is dumb, I ended up figuring it out.

I didn't have to include InputSystem in Core, I had to include it in Character. I don't know why I was selecting the wrong one. So, double-check if it's actually the assembly you think that needs the dependency, and don't always trust what file gets opened when you double click the error.

---
Tags: unity, input, assembly
---


# Question
Title: Unity3D InputSystem works in editor but not in Build
I am trying to move a camera around with controller input using the new Unity Input System package (Ver. 1.2.0) and everything is working great in the editor. However, as soon as I build the project and run it, my inputs don't do anything. Here is my camera controller script which uses my Input Actions map (below it) to move around my camera object (below that).

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

public class CameraController : MonoBehaviour
{

    PlayerControls controls;
    Vector2 move;
    Vector2 rotate;

    private void Awake()
    {
        controls = new PlayerControls();
        controls.Gameplay.Move.performed += ctx => move = ctx.ReadValue<Vector2>();
        controls.Gameplay.Camera.performed += ctx => rotate = ctx.ReadValue<Vector2>();

        controls.Gameplay.Move.canceled += ctx => move = Vector2.zero;
        controls.Gameplay.Camera.canceled += ctx => rotate = Vector2.zero;

    }

    private void Update()
    {
        Vector2 m = new Vector2(move.x, 0f) * 10 * Time.deltaTime;
        transform.Translate(m, Space.Self);

        float f = move.y * 10 * Time.deltaTime;
        transform.Translate(transform.forward * f, Space.World);

        Vector2 r = new Vector2(-rotate.y, rotate.x) * 75 * Time.deltaTime;
        transform.Rotate(r, Space.Self);
    }

    private void OnEnable()
    {
        controls.Gameplay.Enable();
    }

    private void OnDisable()
    {
        controls.Gameplay.Disable();
    }
}

```

Similar topics mention version issues, but those are all for much older versions of the plugin. Has anyone come across this issue or sees anything wrong with my set up?

# Answer
Okay, it seems I had some compatibility issue as remaking everything in a clean project fixed the issue.
> 0 votes

---
Tags: unity, input
---


# Question
Title: How to modify the z depth value inside the vertex function of a surface shader?
I wrote the following surface shader. The idea is to increase the Z depth value of vertices, after projection.

```
Shader "Custom/Highlighted"
{
    Properties
    {
        _Color ("Main Color", Color) = (1,1,1,1)
    }
    SubShader
    {
        Tags { "RenderType"="Opaque" }

        CGPROGRAM
        #pragma surface surf Lambert
        #pragma vertex vert

        struct Input
        {
            float4 pos: SV_POSITION;
            float4 color : COLOR;
        };

        void vert(inout appdata_full v, out Input o)
        {
            UNITY_INITIALIZE_OUTPUT(Input, o);       //
            o.pos = mul(UNITY_MATRIX_MVP, v.vertex); // does not work
            o.pos.z += 0.001;                        //
            o.color = v.color;                       //
        }

        fixed4 _Color;
        void surf (Input IN, inout SurfaceOutput o)
        {
            o.Albedo = _Color.rgb;
            o.Alpha = _Color.a;
        }
        ENDCG
    }
    Fallback "Diffuse"
}

```

The shader compiles, and objects are rendered correctly, however it's like the z depth value is not modified at all (what is inside vert is ineffective).

Here is the equivalent code as a fragment shader (which work perfectly) :

```
struct vertInput {
    float4 pos : POSITION;
    float4 color : COLOR0;
    float4 uv : TEXCOORD1;
};

struct vertOutput {
    float4 pos : SV_POSITION;
    fixed4 color : COLOR0;
};

vertOutput vert (vertInput input)
{
    vertOutput o;
    o.pos = mul(UNITY_MATRIX_MVP, input.pos);
    o.pos.z += 0.001;
    o.color = input.color;
    return o;
}

```

# Answer
> 1 votes
As suggested by DMGregory, one solution to apply depth bias is to use the Offset keyword :

```
Shader "Custom/Highlighted"
{
    SubShader
    {
        Tags { "RenderType"="Opaque" }
        Offset 0, -1 //pulls the polygon closer to the camera
        ...
    }
    ...
}

```

Another way is to transform vertex into view space, modify it as wanted, then transform back, as explained here.

---
Tags: unity, hlsl, depth-buffer, surface-shader
---


# Question
Title: How do i easily clamp my cameras rotation when using transform.rotate()
I'm making a fps controller, and I'm trying to clamp my cameras x rotation. Here's my code so far:

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

public class Player : MonoBehaviour
{
    // Start is called before the first frame update

    [SerializeField] Camera cam;
    [SerializeField] float camSpeed;
    [SerializeField] float walkSpeed;
    [SerializeField] float jumpSpeed;

    float yaw;
    float camPitch;
    Vector3 direction;
    Vector3 worldDirection;

    Rigidbody myrigbody;
    void Start()
    {
        myrigbody = GetComponent<Rigidbody>();
    }

    // Update is called once per frame
    void Update()
    {
        camPitch = -Input.GetAxis("Mouse Y") * camSpeed;
        cam.transform.Rotate(new Vector3(camPitch, 0, 0));
        yaw = (yaw + Input.GetAxis("Mouse X") * camSpeed) % 360f;

        direction = new Vector3(Input.GetAxis("Horizontal") * walkSpeed, myrigbody.velocity.y, Input.GetAxis("Vertical") * walkSpeed);
        worldDirection = transform.TransformVector(direction);

        if(Input.GetKeyDown(KeyCode.Space))
        {
            myrigbody.AddForce(new Vector3(0, jumpSpeed, 0), ForceMode.Impulse);
        }
    }
    private void FixedUpdate()
    {
        myrigbody.MoveRotation(Quaternion.Euler(0, yaw, 0));
        myrigbody.velocity = worldDirection;
    }
}

```

I know that I want to clamp my cameras X rotation within a range of -89 to 89, but no matter what I try I can't figure out how to clamp the rotation while using cam.transform.Rotate(). I don't think I can clamp camPitch, because it is reset every frame, and I can't figure out a way to directly clamp the cameras rotation. The cameras rotation is not resetting, so if I could somehow clamp it it would work. Is this possible, or do I need to try a different method? How do i get this to clamp correctly?

# Answer
> 0 votes
I fixed it! With the help from Kevin's links. So this is the code I ended up with:

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

public class Player : MonoBehaviour
{
    // Start is called before the first frame update

    [SerializeField] Camera cam;
    [SerializeField] float camSpeed;
    [SerializeField] float walkSpeed;
    [SerializeField] float jumpSpeed;

    float mouseAngle;
    float yaw;
    float camPitch;
    Vector3 direction;
    Vector3 worldDirection;

    Rigidbody myrigbody;
    void Start()
    {
        myrigbody = GetComponent<Rigidbody>();
    }

    // Update is called once per frame
    void Update()
    {
        camPitch += Input.GetAxis("Mouse Y") * camSpeed;
        camPitch = Mathf.Clamp(camPitch, -89, 89);
        cam.transform.eulerAngles = new Vector3(-camPitch, yaw, 0);
        yaw = (yaw + Input.GetAxis("Mouse X") * camSpeed) % 360f;

        direction = new Vector3(Input.GetAxis("Horizontal") * walkSpeed, myrigbody.velocity.y, Input.GetAxis("Vertical") * walkSpeed);
        worldDirection = transform.TransformVector(direction);

        if(Input.GetKeyDown(KeyCode.Space))
        {
            myrigbody.AddForce(new Vector3(0, jumpSpeed, 0), ForceMode.Impulse);
        }
    }
    private void FixedUpdate()
    {
        myrigbody.MoveRotation(Quaternion.Euler(0, yaw, 0));
        myrigbody.velocity = worldDirection;
    }

}

```

My problem was pretty simple. In my original code, I used `camPitch = Input.GetAxis("Mouse Y") * camSpeed;`. The problem was that that resets camPitch every frame, so it's value would never actually reach 89 degrees up so clamping it correctly would be impossible. Instead, I changed the `camPitch =` to `camPitch +=`. Now camPitch has the mouse value added instead being of set to the mouses current motion, so it's value will equal what the cameras pitch should be, and can be clamped as i do on the next line. The other change I made, is using `cam.transform.eulerAngles = new Vector3(-camPitch, yaw, 0);` instead of `cam.transform.Rotate(new Vector3(camPitch, 0, 0));`. I used eulerAngles because this uses a set value of what the rotation's value should be on this frame instead of rotating based on the current motion on this frame. I hope this makes sense. I also added `yaw` for the y axis because since the cameras rotation is being directly set instead of rotated, it no longer follows it's parent's (the players) rotation. I hope that was clear, and that this will help someone in the future. Thanks to Kevin for helping me out!

# Answer
> -1 votes
**So Basically How Clamping Works:**

Clamps the given value between the minimum float and maximum float values. Returns the value between the min and max range.

So it returns the min value if the given value is less than the min value and Returns the max value if the value is greater than the max value. Use Clamp to restrict a value between the range that is defined by the min and max values.

Basically what we do is, set the minimum and maximum rotation values before setting up actual Euler angles. Don’t forget to assign a new instance in the rotation when you do clamping with camera rotation.

---
Tags: unity, rotation, first-person-shooter, character-controller
---


# Question
Title: Where should complex state logic in an ECS reside?
I've been using ECS for a while, at the moment I'm using my own, but it's pretty standard. Components are data only, Entities pretty much just a Map with some additional metadata and Systems that match combinations of components and contain the logic.

You have combinations of components that result in the more general functionality. For example Position + Graphics gives me some nice static background image. Position + Graphics + Physics gives me a entity that can move around etc etc

This question is about the various options for implementing more specific game logic.

But say I want to implement a Door. It has Position, Graphics and a Collidable Hull but it needs 2 states, open and closed. When its open it has texture A and its Collidable Hull is disabled, and when its closed it has texture B and its Collidable Hull is enabled. Lets say the state change should be triggered across some internal channel in the engine.

What are the options for implementing this state change?

Option 1 is to create Door component, with say 2 variables, door state and state change channel. I'd also need a door system that handled the logic to manipulate the components when it receive the open/close message.

Option 2 would be to create a FSM. The FSM is probably also a component with a corresponding FSM System. Logic and state would need to reside somewhere, possibly by sub-classing the FSM or having a generic property map in the FSM and static logic functions for the Door defined elsewhere.

There are more exotic alternatives to FSM's i.e. Actions Lists or Behaviour trees, but they are similar to option 2.

What considerations are there for choosing a full component/system over an more generic FSM type solution? What if I had 100 different game objects with different behaviours? Would you really expect 100 component/system pairs for each one or would you try and create a more generalized solution? Are there any other options?

# Answer
I've tried both pure approaches in the past and, not surprisingly, I've found a hybrid approach is best. I tend to create a lot of custom components for individual entities and use a FSM when I need to change a lot of entities at once.

Almost always, the FSM really only cares about one common aspect of the collection of entities. For example, if the components are locked or not, or if they are in their start position, or some heighten state position. So, mostly, the FSM is implemented by adding an abstraction to each of the custom components that handles that aspect and then using the abstraction in the FSM.

In the door example, I would build a custom component that handles the door logic. Imagine the size of it (tiny), and it will do exactly what you want. Now imagine some generic component that will work for your door as well as a toaster. This case is certainly more complicated than the first component and probably doesn't do what you want and is impossible to change.
> 2 votes

# Answer
I would rather treat the component system a means to invoke logic and nothing more. Instead, you design a generic component that manages a logical boolean state of 0/1. As the component's state transitions to 1, you fire the activated script. As it transitions to 0, you fire the deactivated script.

The benefit here is whatever *logic* you need is external to the ECS as the component is merely a means to invoking logic, regardless what it may be.

In fact, the component could have a time factor associated to the transition so that it takes X number of frames or nanoseconds to transition and allows for a tri-state like script executor rather than just two.

Now this component can work for doors, switches, vertical/horizontal moving platforms, flashing lights, etc. Basically anything that manages 2 or even 3 states.
> 1 votes

# Answer
So not an answer per se but an insight. Apples GameplayKit has an implementation that allows you to use a component to encapsulate logic and systems to manage the timing of component updates in relation to other systems. The entities themselves are able to update all of their components without the need for a system at all. My personal addition to this kit allows for the concept of systemic components that, if managed by a system, are ignored by entity updates. My editor is able to update components that need to update themselves during editing by declaring systems of that type and avoid all systems and all entity updates in general since we are not running gameplay systems all the time.

If you want to use a system for components that are specifically data structures then the logic can be included in the system like any traditional ECS. Having entity driven component updates may not be the most data efficient method but I find having the option and a precise method of handling components when a system is introduced makes it trivial to build and debug an entity when components run into conflicts. With a system driven system it is harder to manage simple entity driven updates since all each requires a system to run on instead of their own update method.

They provide a generic Entity, Component and ComponentSystem classes that all contain an update(seconds) method. Creating a new system can be as simple as initializing one for a certain type of component subclass and adding the component with a call addComponent(foundIn: Entity). My subclass manages each component’s isSystemic var and allows you to call update on a specific entity or component system if it needs to process changes.

Sometimes data processing requires efficient systems but during prototyping and development flexibility is key to get an idea working. Not saying this is the best approach but it’s very flexible toolset.
> 0 votes

---
Tags: entity-system
---


# Question
Title: UDK: BSP from Brush-CSG Add cannot be deleted
Once a BSP has been created using Brush-CSG add it cannot be deleted.

Del-DELETE from the keyboard yields no effect. Right click-cut yields no effect.

Is there another way?

# Answer
> 0 votes
*SOLVED* Brush-CSG Subtract deletes everything

---
Tags: unreal, udk, binary-space-partitioning
---


title: Dragging GameObjects out of UI

text:
# Question
Title: Dragging GameObjects out of UI
I want to drag a game object out of a UI. Currently, I am instantiating a game object on top of the UI(on an upper sorting layer), and adding code to make it able to drag the object. However, Unity cannot detect if the mouse is over the object. The object has a box collider 2D and the scene has an event system.

```
public void OnPointerEnter()
{
    mouseEnter = true;
    Debug.Log("mouse enter");
}

public void OnPointerExit()
{
    mouseEnter = false;
}
void Update()
{
    if(Input.GetMouseButton(0) && mouseEnter)
    {
        Vector3 pos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        transform.position = new Vector3(pos.x, pos.y, 0);
    }
}

```

The code is attached to the item I want to drag. It is being properly instantiated on top of the UI element, but it can't be dragged.

Some searching suggested that the UI element might be blocking the raycast...but I don't truly understand how this works or how to fix it.

Maybe the way I am doing this is wrong, so is there any solution?

# Answer
You need another variable to indicate whether the object is dragged or not.

And when dragging, mouseEnter is unrecoginzed.

```
bool dragging;

void Update()
{
    if(Input.GetMouseButton(0))
    {
        if(mouseEnter)
        {
            dragging = true;
        }
    }
    else if(dragging)
    {
        dragging = false;
    }

    if(dragging)
    {
        Vector3 pos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        transform.position = new Vector3(pos.x, pos.y, 0);
    }
}

```
> 1 votes

---
Tags: unity
---


# Question
Title: Why is my player ball's movement bouncy and bumpy?
I've come across an odd effect in Unity and would like to understand why it's happening. Using some simple code I've achieved a horizontal movement effect, of a ball across a flat square surface, yet the movement in any given direction is bumpy, as in, it's like the ball is bouncing slowly until it settles in a hole when the key is let up. I've never noticed anyone else's player object doing this, and there doesn't seem to be any instances of it out there, based on my research. One might describe it as "rolling through the inside of an egg carton". Does anyone knows why this is happening, if it's normal, or at the fault of my code?

Here's my code:

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

public class Player : MonoBehaviour
{
    private Rigidbody rb;
    public float speed;

    //
    void Start()
    {
        rb = GetComponent<Rigidbody>();
    }
    //

    void FixedUpdate()
    {
        var gravity = new Vector3(Input.acceleration.x, Input.acceleration.z, Input.acceleration.y) * 9.8f;
        rb.AddForce(gravity * rb.mass, ForceMode.Acceleration);

        float horizontal = Input.GetAxis("Horizontal");
        float vertical = Input.GetAxis("Vertical");
        Vector3 movement = new Vector3(horizontal, 0.0f, vertical);
        rb.AddForce(movement * speed);
    }
}

```

And here's a GIF of what's happening:

# Answer
Fixed! The ball was rolling rather than gliding, and because it wasn't smooth enough, gave me the feeling it was bumpy.
> 0 votes

# Answer
I don't see any issues with your ball movement. The *shadow* is bumpy.

Shadow maps are textures with pixels, but smoothing is applied so that low resolution shadows don't appear pixelated. However, the shadows in the shadow map can still only move one pixel at a time. When the resolution is low, the pixels are large and the shadow motion will appear jumpy. Here's what it might look like without smoothing:

You can fix this by increasing the shadow resolution.
> 1 votes

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


title: When do you need to add sound effects?

text:
# Question
Title: When do you need to add sound effects?
I am making a small 2D sidescrolling shooter and have all the basics done now. I have a player, enemies, different weapons and a map. I am unsure about at what point in development you should add sound effects. Would it be too early to add them now if the game is not completely done?

# Answer
> Would it be too early to add them now if the game is not completely done?

You can argue this about anything. It is too early to add XYZ because the game is not completely done. Well, the game is not going to be completely done before you add them, will it? Thus, no. You need to add XYZ before the game is complete, otherwise it will never be.

---

> I am unsure about at what point in development you should add sound effects.

For small projects it matters little. For bigger projects this question becomes more important.

Assuming the game is large enough that is matters, the first thing you must consider is that you should iterate. Which implies you should slice your work.

In general, you should begin from the things that you are certain of. And delay decisions you are uncertain of. In other words, you should not design in a way that backs you into a corner.

Regardless of how you slice your work, you need to know what are the goals of your current iteration. And I'd suggest to document it. In particular if you are working in a team. Let there not be problems later.

Bringing that to the issue of sound. When you tell your artist - who might be yourself - that you need some sound, how do you describe it? The artists will use that description to get the sound. And the tester will use that description to verify it is effective in practice. From there you can decide if you need to change it.

Which brings me to this: If you already have a mechanic working, you can add sound to it. Yes, even if other mechanics are not ready. Since the game is not done yet, you can come back later and change it. *And the same goes for all art.*

Some suggestions:

* Keep a document of the things you need to change before release.
* Don't use material you don't have a licence for, in case you release the game with it.

*On that note, I remind you that silence is an option.*

---

I'm going to suggest to make sure your game works without sound. For us, hearing folks, sound and music enhance the experience. But it is not a good idea to rely on sound and music to carry the experience. Make a game that is good without sound and music, so that when you add them, it becomes much better. *And yes, accessibility is important. Have subtitles and directional visual cues.*

---

Another thing that I want to suggest is to complete a vertical slice of the game. That is a game that people can play from start to finish and has the core mechanics - even if it only one scenario. And yes, with sound and music. Then you iterate expanding upon that vertical slice.

Since you say:

> I (…) have all the basics done now

It seems you are approaching that vertical slice. So, yes. Add sound.

Even if that is not the case, it should give you an idea of when to do it: You want to test your mechanics and scenarios without sound, and you also want to add sound to them before moving on to the next ones.

And - to reiterate - that sound you are adding does not need to be the final sound. You might change it later. In fact, you may want to do some extra polish iterations after all the mechanics and scenarios are completed, where you also go over your list of things to change before release.
> 3 votes

---
Tags: sound, sound-effects
---


# Question
Title: How do you make Cube not instantly rotate upon Keypress in opposite direction?
I have this movement script on a `Rigidbody` cube with X,Y,Z Rotation Constraints.

It is working well to move and to rotate in the direction of the movement.

However, if for example you Keypress W and then Keypress S, the rotation is instant! There is no smooth rotating effect. How might you make rotation on such condition be a smooth directional rotation (making cube turn around at a smooth angle), rather than an instant transform flip?

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

public class MoveCube : MonoBehaviour
{
    public Rigidbody r;

    public float horizontalInput;
    public float verticalInput;
    public Vector3 movDirection;
    public float speed = 10f;
    public float heyo;
    private Vector3 prevPosition;

    // Start is called before the first frame update
    void Awake()
    {
        r = this.GetComponent<Rigidbody>();
    }

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

    // Update is called once per frame
    void Update()
    {
        horizontalInput = Input.GetAxis("Horizontal");
        verticalInput = Input.GetAxis("Vertical");
        movDirection = new Vector3(horizontalInput, 0.0f, verticalInput).normalized;
    }
    public void FixedUpdate()
    {
        // Calculate position change between frames
        Vector3 deltaPosition = transform.position - prevPosition;
        deltaPosition.y = 0f;

        if (deltaPosition != Vector3.zero)
        {
            // Same effect as rotating with quaternions, but simpler to read
            transform.forward = deltaPosition;
        }
        // Recording current position as previous position for next frame
        prevPosition = transform.position;

        r.AddForce(movDirection * (speed + 18f), ForceMode.Force);
    }
}

```

# Answer
I don't actually use Unity, but I do some 2D game programming and I use C#, so I'll chip in an idea hopefully it might help.

From what I know a technique to create a smoothing-effect for movement is to linear-interpolate ("LERP") the movement of the target object against the profile of some function. It sounds a little complex but at a high level it's a good approach.

Take for example a straight horizontal line on a graph. If we were to linearly interpolate this function's profile, we'd end up with 'x'-values that change as we go along it, but the 'y'-values would stay the same. So you'd end up with a rigid, un-smooth movement to your object.

But if you alias the movement over time between two ends of say, a diagonal line going up that curves to a straight horizontal line, then your 'y'-values would be "smoothed-out" somewhat. I don't have a code example but I hope this might help a bit.

Research: Advanced Game Development with Programmable Graphics Hardware By Alan Watt, Fabio Policarpo (p.201) - https://www.google.co.uk/books/edition/Advanced\_Game\_Development\_with\_Programma/EUFZDwAAQBAJ?hl=en&gbpv=0

(In the GIF, I basically smoothed out the arrows movement with an acceleration-style functionality that increases linearly up to a threshold, but I didn't apply it to the slow-down due to time. However a naïve "LERP" like this might be what you could use)
> 0 votes

---
Tags: unity, c#, physics, rotate
---


# Question
Title: Finding where ground is in procedurally generated terrain
Terrain in my voxel game is generated by combining 2d and 3d perlin noise.

```
if (y < (noise2d(x, z) + noise3d(x, y, z)) * amplitude)
{
    // place block
}

```

To generate structures like trees, I need to find where the ground is. The simplest way is to just go through every block from min height to max height and check if there is a block with no block above it. This works, but it is slow. Is there a faster way to do this?

I tried using bisection, but it sometimes returns positions one block below the ground.
Simplified code for bisection:

```
float min = minHeight;
float max = maxHeight;
float mid = (min + max) / 2.0f;
while (abs(mid - combinedNoise(mid)) > 0.5f)
{
    if (sign(mid - combinedNoise(min)) == sign(mid - combinedNoise(mid)))
    {
        min = mid;
    }
    else
    {
        max = mid;
    }

    mid = (min + max) / 2.0f;
}

```

I think removing the absolute value might fix the blocks below the ground, but I don't think I can remove it because it can create an infinite loop because of how bisection works.

# Answer
Let's define your block placement rule as a function of position:

```
bool IsSolid(x, y, z) {
    return y < (noise2d(x, z) + noise3d(x, y, z)) * amplitude;
}

```

Looking at this, we can make our initial search bounds tighter.

Let `baseHeight = noise2d(x, y)` then expand that based on your range of values from your `noise3d` function. (Typically 0-1 or -1 to 1, but you may have a custom noise here with other behaviour)

```
int minHeight = floorToInt((baseHeight + minNoise3dValue) * amplitude);
int maxHeight = ceilToInt((baseHeight + maxNoise3DValue) * amplitude);

```

(If you have constraints on the maximum slope of the `noise3d` function, you might be able to make this even tighter)

By construction, we know `IsSolid(x, minHeight, z) == true` and `IsSolid(x, maxHeight, z) == false`, and we'll maintain this as an invariant as we go.

```
while (maxHeight > minHeight + 1) {
    int midHeight = (maxHeight + minHeight)/2; // Compiler will make this >> 1

    if (IsSolid(x, midHeight, z)) {
        minHeight = midHeight;
    } else {
        maxHeight = midHeight;
    }
}

```

At the end of this process, `minHeight` points to a solid block and `maxHeight` points to an empty block directly above it, so this is *a* point on the surface of your terrain. Note that because you're using 3D noise, you can get overhangs or voids, so this procedure does not guarantee that this is the top-most surface in this column, only that it is *some* place where there is a transition from solid immediately below to empty immediately above.
> 0 votes

---
Tags: procedural-generation, terrain
---


title: Should I bother with SDL_WaitEvent?

text:
# Question
Title: Should I bother with SDL_WaitEvent?
When I wrote my first application in SDL, it looked like this:

```
while (!quit)
{
    SDL_PollEvent(&event);

    switch (event)
    {
         // ...
    }
}

```

But then one time I left my app running while I went to do something else, and when I came back my laptop was boiling hot. I checked the system monitor and one of my cores was maxed out by my program! So I did some research, and now my loop looks like this:

```
while (!quit)
{
    SDL_WaitEvent(&event);

    switch (event)
    {
         // ...
    }
}

```

Great, so now my program doesn't max the CPU. But now I need to introduce rendering, and the problem is, currently this loop runs one iteration per event. If input and other events don't occur, my program won't render the next frame, no matter where the rendering code goes in the loop. So that's no good.

I could have threads, but that seems like a lot of extra complexity when I could just do:

```
while (!quit)
{
    SDL_PollEvent(&event);

    switch (event)
    {
         // ...
    }

    SDL_Delay(10)
}

```

This won't melt the CPU, and I can render at about 100 frames per second.

My questions are:

1. Which approach "should" I use? I don't see any reason to not just use (3).
2. What's the point of `SDL_WaitEvent`, if you can't use it the moment you want to do anything other than handle events in your game loop?
3. I assume `SDL_WaitEvent` does something like approach (3) under the hood, so even though ostensibly approach (3) should introduce more latency, in practice it won't. Is this correct? How low should the integer passed to `SDL_Delay` be to get a responsive app?

# Answer
That's an interesting problem, I handle my SDL events like this,

```
while (SDL_PollEvent(&e) != 0)
{
    // handle events here
}

```

This will handle all the SDL events in the queue, and if their aren't any events in the queue it just ignores trying to handle the events in the queue.

P.S. at the end of each iteration of my game loop *(The handle user input, update game world, render world)* I just delay the loop so that it won't iterate more than 60 times a second.

```
// Timing variables
const int FPS = 60;
const int frameDelay = 1000 / FPS;
Uint32 frameStart;
int frameTime;

// Game Loop
while(playing)
{
    // Stores the number of ticks at the start of the loop
    frameStart = SDL_GetTicks();

    // HandleEvents
    // Update World
    // Render World

    // This measures how long this iteration of the loop took
    frameTime = SDL_GetTicks() - frameStart;

    // This keeps us from displaying more frames than 60/Second
    if(frameDelay > frameTime)
    {
        SDL_Delay(frameDelay - frameTime);
    }
}

```
> 3 votes

# Answer
As you pointed out, `SDL_WaitEvent` is not suitable if you need to draw even if there are no input events. That is not desirable for games. But it could be useful, for example, if you have an application that only does UI, because you only need to refresh when the user interacts with the UI.

For games, very often we use a technique called VSync. This technique will make your loop refresh at the same rate as your monitor. So if your monitor has a refresh rate of 60Hz, the loop will match that. Additionally, it will prevent screen tearing artifacts.

In SDL you can enable VSync in different ways depending on what you are doing:

1. If you are using SDL's renderers, you can use the `SDL_RENDERER_PRESENTVSYNC` flag.
2. If you are using OpenGL you can call `SDL_GL_SetSwapInterval(1)`.

Alternativelly, you can use `SDL_Delay`. But, instead of waiting a fixed amount of time, you should wait depending on how much time you have spent doing computations, in order to keep a constant frame time. This approach is what @sketBURD 's answer is about.
> 1 votes

# Answer
LazyFoo's Tutorials use `SDL_PollEvent` in within it's own loop inside the main loop, to ensure all events are handled and not only the 1st one.

The main loop would look like this:

```
//Main loop flag
bool quit = false;

//Event handler
SDL_Event e;

//While application is running
while( !quit )
{
    //Handle events on queue
    while( SDL_PollEvent( &e ) != 0 )
    {
        //User requests quit
        if( e.type == SDL_QUIT )
        {
            quit = true;
        }
    }

    // everything else
}

```

You might also like to take a look at the Calculating framerate and Capping Framerate tutorials.
> 0 votes

# Answer
One idea is that you can use the SDL\_WaitEvent loop, so that the thread blocks and yields the CPU (and can allow the CPU to idle and cool down).

But what you can do is create your own user-defined event - let's call it "SDL\_ANIMATEEVENT" (but you'd use SDL\_RegisterEvents to grab an available event ID for it) - and then have the thread post that to its own queue.

So, for example, the user clicks on a button. This wakes the thread with a mouse event. That mouse event then starts an animation - the button graphic might animate inwards and outwards to make it look like it's being pressed down and released, or you might have it smoothly change colours on hover - and then it posts the "SDL\_ANIMATEEVENT" to its own message queue.

The trick being that when the program returns to SDL\_WaitEvent, the "SDL\_ANIMATEEVENT" message is in the queue, so the call doesn't block, the message gets picked up and we go through the loop one more time.

The processing for "SDL\_ANIMATEEVENT" can move the animation forward by one frame and, if the animation isn't complete, it posts another "SDL\_ANIMATEEVENT" to its own message queue.

So, again, when it reaches SDL\_WaitEvent, it doesn't block, as there's a message waiting for it. And we do one more rendering loop.

Eventually, the animation is complete, so the processing for "SDL\_ANIMATEEVENT" does not put another "SDL\_ANIMATEEVENT" message on the queue. And when we reach SDL\_WaitEvent again, there aren't any messages waiting for it and it actually now blocks waiting for an event.

This way of doing things is good for more "burst-y" animation. Where you're not always animating every single frame - but you might need to "burst" a few frames of animation, before going back to blocking again.

Perhaps less useful for games, where you're animating every single frame all the time (though this scheme could work for that too, but if you're always animating every single frame then it's just overhead, because the branch is always taken) but for GUIs, say, this could be exactly what you need.

When there's truly nothing to be done, you can block on SDL\_WaitEvent. But if you need it to behave like SDL\_PollEvent then keep posting that "SDL\_ANIMATEVENT" onto the message queue, which stops SDL\_WaitEvent blocking, and then you can stop posting "SDL\_ANIMATEEVENT" when you want to go back to blocking again.
> 0 votes

---
Tags: game-loop, sdl, sdl2, timing, latency
---


# Question
Title: How to solve for the angle of a axis/angle rotation that gets me closest to a specific orientation
I’m using a 3D affine transform (a 4x4 matrix of floats) to represent a combination of translations and rotations in 3D space doing a sort of 3D turtle graphics kind of thing. From this state I know the heading that I’m going, and what I’d like to do is roll around this particular axis. The problem that I’m trying to solve is determining the angle (let’s call it θ) to roll that results in one of the heading vectors being as close to vertical (+Y) as possible while still on the plane of rotation that’s constrained to the “heading” axis.

My starting points for the “forward” heading is +1 on the Y axis, and a local “up” heading as +1 on the Z axis.

The way I was trying to tackle this problem was applying the built-up set of translations and rotations using the 3D Affine transform and then figuring out if there was trigonometry I could use to solve for the angle. Since I know the axis around which I want to roll (or can compute it by applying the transform to the unit vector that represents it - the (0,0,1) vector), I was looking at the Rodrigues rotational formula, but my linear algebra (matrix math) skills and understanding are fairly weak - and I couldn’t see a path to solving that equation for θ given known vectors for the heading, or vectors on the plane that can be used to define a cross-product that is the heading, as well as knowing the world vector.

I’m heading towards trying to solve this by iteratively applying various values of θ and homing in on the solution based on the the resulting value that has the Y component value. I can apply the roll as an affine transform that I multiply onto the current transform, and then test the result of a unit “up” vector - rinse and repeat to find the one that gives me the best “Y” component value.

I’d like to know If there’s a way to solve this directly - to compute the value of θ that I can use to directly do the rotation, rather than numerically iterate/solve into the solution.

If the background of "why" makes any difference, I'm implementing a 3D rendering of a Lindenmayer System similar to what's in The Algorithmic Beauty of Plants, and there's a specific roll rendering command that I'm trying to sort out: '$', which rolls about the axis of the current heading, so that the "up" vector is vertical.

# Answer
Here's a similar approach that you may find has better numerical stability / avoids the NaNs you're getting occasionally. I'm assuming a left-handed coordinate system since that's what I use most often, but you can flip it to a right-handed form easily enough if needed.

```
planeRight = normalize(cross(worldUp, heading));

planeUp = cross(heading, planeRight);

```

These two vectors form a basis for the plane perpendicular to your heading.

(Obviously this becomes indeterminate when your heading is pointing exactly up/down - best to pause your rolling then, or gradually fade-out the roll as the heading gets extremely steep)

We can then get the angle from your current up vector to the one in this plane that best aligns with `worldUp` as...

```
angle = atan2(dot(currentUp, planeRight), dot(currentUp, planeUp));

```

You can think of the dot products as getting us the `x` & `y` coordinates of our current up vector in this plane, and from that the two-argument arctangent gets us the angle of the vector from the positive x-axis in that plane. Here I've arranged the basis vectors so that we get an angle of 0 when we're already in perfect alignment, a negative angle when we need to roll in the negative direction, and a positive angle when we need to roll in the positive direction.
> 1 votes

# Answer
I got an answer from a local friend who saw these, and I've mostly implemented it. There's a few numerical instability points I need to sort out, but the gist is: Yes, there's definitely a way to explicitly calculate the angle of rotation needed.

The flow of the process is as follows:

* start with a unit vector that represents the 'up' vector that I want to compare (+Z in my case)
* pull the 3x3 translation matrix from the affine matrix, and use that to rotate the 'up' vector. We'll be comparing against this later to get the angle. Because it's explicitly set as a unit vector in the 'up' direction, we already know it's on the plane that can be represented by the normal of that plane - which is our heading vector.
* Use a similar technique to rotate the 'heading' vector (what starts as +Y for me) by the rotation matrix.

(a quick double check here I did in my testing was that these two remained 90° apart after rotation - primarily to verify that I didn't screw up the rotation calculation)

* Now that we have the heading, we use that as a normal vector for the plane upon which we want to project our two vectors, and from which we can get the angle desired. The vector (the 'rotated up' vector) is already on this plane. The other vector is the +Y world vector - the "as vertical as possible" component of this.

The formula for projecting a vector on a plane is:

`vec_projected = vector - ( ( vector • plane_normal ) / plane_normal.length^2 ) * plane_normal`

You can look at this conceptually as taking the vector you want to project and subtracting from it the portion of the vector that corresponds to the normal vector, which leaves you with just the component that's aligned on the plane.

-tip to Greg Titus, who referred me to ProjectionOfVectorOntoPlan at MapleSoft.

* Once both the vectors are projected onto that base plane, then you can use the equation to calculate the angle between two vectors:

```
acos(
    dot(rotated_up_vector, projected_vector) /
            ( length(projected_vector) * length(rotated_up_vector)
    )
 )

```

There's some numerical instability points I need to work out where my current code is returning 'NaN' from the final comparison, and the directional component isn't included in that - so I need to sort out a way to determine which direction to rotate, but the fundamentals part of it is at least sorted.
> 0 votes

---
Tags: 3d, mathematics, matrix, linear-algebra
---


# Question
Title: Is `if (gameObject)` the same as `if (gameObject != null)`?
If you have a Game Object, and you want to check if it exists, is

```
if (gameObject) { }

```

the same as

```
if (gameObject != null) { }

```

and if not, what is actually being evaluated in the first statement?

# Answer
Here's a slightly more explicit test:

```
public class IfTest : MonoBehaviour {
    public GameObject toAssign;

    void TestIfs() {
        if (toAssign) {
            Debug.Log("if (gameObject) passes.");
        } else {
            Debug.Log("if (gameObject) fails.");
        }

        if (toAssign != null) {
            Debug.Log("if (gameObject != null) passes.");
        } else {
            Debug.Log("if (gameObject != null) fails.");
        }

        if (System.Object.ReferenceEquals(toAssign, null)) {
            Debug.Log("if (ReferenceEquals null) passes.");
        } else {
            Debug.Log("if (ReferenceEquals null) fails.");
        }
    }

    IEnumerator Start() {
        Debug.Log("-------Before assigning:----------");
        TestIfs();

        Debug.Log("-------Assigning:-----------------");
        toAssign = new GameObject();
        TestIfs();

        Debug.Log("-------Destroying:----------------");
        Destroy(toAssign);
        TestIfs();

        // Wait one frame for the destruction to take effect.
        yield return null;
        Debug.Log("-------1 frame later:-------------");
        TestIfs();

        Debug.Log("-------Unassigning:---------------");
        toAssign = null;
        TestIfs();
    }
}

```

Here's the output you get:

```
-------Before assigning:----------
if (gameObject) fails.
if (gameObject != null) fails.
if (!ReferenceEquals null) passes.
-------Assigning:-----------------
if (gameObject) passes.
if (gameObject != null) passes.
if (!ReferenceEquals null) passes.
-------Destroying:----------------
if (gameObject) passes.
if (gameObject != null) passes.
if (!ReferenceEquals null) passes.
-------1 frame later:-------------
if (gameObject) fails.
if (gameObject != null) fails.
if (!ReferenceEquals null) passes.
-------Unassigning:---------------
if (gameObject) fails.
if (gameObject != null) fails.
if (!ReferenceEquals null) fails.

```

So, the takeaways from this experiment that you can do yourself:

* `if (gameObject)` and `if (gameObject != null)` behave the same.
* Both will evaluate as `true` in the frame that their object is destroyed
* Both will evaluate as `false` starting the frame *after* their object is destroyed.
* `!Object.ReferenceEquals(gameObject, null)` will still evaluate as `true` on a destroyed object, because it's only been *marked* as invalid, it's not literally a `null` value.
* In the Editor, `!Object.ReferenceEquals(gameObject, null)` will *also* evaluate as `true` on an unassigned object reference. The Editor inserts a special non-null placeholder object there secretly, so that it can give you better error messages if you try to use a reference you haven't assigned yet. But these placeholders still compare as equal to `null` with the other two methods, and aren't used at all in the built executable.
* All three behave the same for a value that is actually, literally a `null` \- like one you assigned there by hand.

You can repeat this test for a component reference and get the same results.
> 2 votes

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


# Question
Title: How to move a character gradually over a list of waypoints?
I have a list whose elements are `Vector2` points in world space:

1. (9, -9)
2. (9, -13)
3. (5, -13)

What I want is that my enemy character should first go to (9, -9) position, after reaching that target, go to (9, -13) position, and after reaching there, move to (5, -13).

I tried this in the script below. I gave the first element of the list to `MoveTowards` as a target, but before my character could reach its target, the next element of the list was given as a target.

How can I do this without using the for-loop? Or how can I temporarily stop the for-loop until my character reaches its destination?

```
public Rigidbody2D rb;

private float speed = 2f;

public Vector2 target;

public NewNavmesh pathTarget;

private void Update()
{
    for (int i = 0; i < pathTarget.ways.Count; i++)
    {
        target = pathTarget.ways[i]; //Vector2 paths in new list
        transform.position = Vector2.MoveTowards(this.transform.position, target, speed * Time.deltaTime);
        int indexInList = pathTarget.ways.IndexOf(pathTarget.ways[i]);
        pathTarget.ways.RemoveAt(indexInList);
    }
}

```

# Answer
It looks like you meant to write something like this:

```
void Update() {

    // When the ways list is empty, we've reached the last waypoint.
    if (pathTarget.ways.Count > 0) {

        // Move one step toward the next remaining point in the list.
        target = pathTarget.ways[0];
        transform.position = Vector2.MoveTowards(
                      transform.position,
                      target,
                      speed * Time.deltaTime
        );

        // If we've reached the waypoint, remove it from the list,
        // so that next frame we proceed to the next waypoint after it.
        if ((transform.position - target).sqrMagnitude < 0.001)
            pathTarget.ways.RemoveAt(0);
    }
}

```

Or, if you like conceiving of this as a for loop, you could do it non-destructively this way:

```
IEnumerator WalkWaypoints(List<Vector2> waypoints) {
    foreach (var waypoint in waypoints) {
        while ((transform.position - waypoint).sqrMagnitude > 0.001f) {
            transform.position = Vector2.MoveTowards(
                      transform.position,
                      target,
                      speed * Time.deltaTime
            );
            // Wait a frame,
            // and resume the next loop iteration next frame.
            yield return null;
        }
    }
}

```

You can then set this in motion with:

```
Coroutine walk = StartCoroutine(WalkWaypoints(pathTarget.ways));

```

And abort it with:

```
StopCoroutine(walk);

```
> 1 votes

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


# Question
Title: Proper way to handle user input when the game is lagging
I was just learning game programming concepts and was confused on what is the correct way to handle user inputs.

I am used to javascript, so all the below snippets are in js but I assume the concepts should be the same across most of the programming languages.

Lets say our game is a FPS and the playing can use the keyboard arrow keys to move his character around.

This is the sample code that I am playing around with

```
const FPS = 60
let keyMap: {[key in keyCode]: boolean} = {}
let game
const downListener = (event: KeyboardEvent, keyMap) => {
    event.preventDefault()
    keyMap[event.key] = true
    return keyMap
  }

const upListener = (event: KeyboardEvent, keyMap) => {
    event.preventDefault()
    keyMap[event.key] = false
    return keyMap
}

// update
 const update = (game) => {
   // Handle user input
   if (keyMap["ArrowRight"]) {
     /* Move player right*/
   }
   else if (keyMap["ArrowLeft"]) {
     /* Move player left */
   }
   // Other controls ...

   return game
 }

// Game loop
const gameLoop = () => {
    game = update(game)
    game = renderGameScene(game)
}
setTimeout(() => {
    gameLoop()
    setTimeout(() => gameLoop(), 1000 / FPS)
   }, 1000 / FPS)

```

Let's say the game loop has some very intensive code that takes say 10 seconds to execute (extreme cases), So my game loop will be called every 10 seconds.
And the user pressed arrowRight key at t=2, t=3, t=6. But since my game loop executes every 10 seconds and I only store the last status (keyPress/notPress) of key, none of his inputs will be taken into consideration when my gameLoop actually executes. That is, the gameLoop will only consider the input that was pressed exactly at the time it starts executing.

But what I notice in big games (Counter strike for example) is that if my game is lagging and I press arrowRight 4 times, then in the next render my character abruptly moves 4 units right but in my code above my inputs won't be processed at all. How would I solve this issue in a scalable way? How do big games usually do it?

EDIT: 10 seconds is just an extreme number but I beleieve the same issue will arise when the game loop takes 200-300 ms to execute whereas the user input is captured very quickly

# Answer
There are (at least) two different kinds of user input that we can consider. (I don't know what these are most commonly called — I'm making up terms right now, not using standard ones.)

* Continuing inputs: like WASD movement controls in a first-person game, or anything from a controller analog stick. These cause something to continue to happen as long as the key/button/stick is held.
* Command inputs: like taking an action ("shoot gun") or moving one tile on a grid.

The code you have is appropriate for continuing events. In most cases, in a game with free movement that is typically animating smoothly, if the game has a “lag spike” of 10 seconds, the player won't *want* to have 10 seconds of movement off in some constant direction — that's more likely to send them into a hazard than standing still is. Therefore, the game does not implement arbitrary amounts of motion — it has some cap on *how much game time effectively passes* (at least for your character, in a multiplayer game) after the hiccup. The way this usually works is that when the game loop checks the real-time clock to decide how much game time to simulate, if more than some maximum amount of time has passed, it pretends that *only* that amount of time has passed.

On the other hand, if you have a game with movement on a grid, it would probably be more appropriate for *each keypress* to cause exactly one tile of movement. In this case, the simplest possible approach is to have your key-down listener directly modify the game state. Games where things can only happen after a delay might need some amount of “input queueing” as DMGregory put it, to execute actions after they're allowed to execute. (Generally, for very fast actions, you don't want to *ignore* user input just because the game wasn't quite done with the previous action. Hence, store the events you receive until they can be processed, perhaps with some time or count limit.)

In a FPS, an example of a command input might be “click to shoot your gun”. In this case, you don't want to not shoot just because a *small* hiccup caused the mouse-down and mouse-up events to happen in the same frame. So, instead of the game logic checking “is the moue button currently down?”, it's better for your mouse-down event handler to set a flag “should shoot now”, which is cleared when the game logic actually creates the bullet and changes the gun's state and so on. The same principle applies to keyboard keys that take discrete actions, like jumping.

In user interfaces (buttons, menus, etc), either of the last two approaches can be appropriate. It's important that you pick one of the ones that won't discard inputs just because their timing seemed bad, though — imagine if the user opens your game, and the frame rate is terrible, and they need to navigate to the graphics options to reduce some settings, while rendering is still slow. You want to make sure your UI elements react to the inputs as well as possible, without requiring them to do things like "make sure to hold the mouse button down for half a second and not move off this button, then let go and wait another half second without moving the cursor" (actual sort of experience I've had).

---

So: there's no one way to process input that works for all kinds of games or gameplay actions. Instead, think about what *should* happen, and use an algorithm that produces that result — one of the common ones I've described above, or whatever you can think of that produces good results. Consider adding a deliberate frame slowdown option to test how your input feels in those conditions.
> 1 votes

---
Tags: game-design, game-loop
---


# Question
Title: How to restrict an AssetReference to a specific type?
I am using the Addressables package of Unity.

I am trying to restrict an AssetReference type in the Unity inspector to a specific type. Currently a user can assign any Unity object to an AssetReference, but I would like to guide the user to assign the correct types to the correct variables and (if possible) filter the assets type list to include only the assignable types when the user click on the drop-down arrow

According to the Unity documentation https://docs.unity3d.com/Packages/com.unity.addressables@1.6/api/UnityEngine.ResourceManagement.Util.SerializedTypeRestrictionAttribute.html

it seems like there is some sort of annotation available. The documentation is very limited and I have tried:

```
[UnityEngine.ResourceManagement.Util.SerializedTypeRestrictionAttribute(type=typeof(PlayerMaster))]
public UnityEngine.AddressableAssets.AssetReference playerMaster;

```

but it made no difference.

I also tried to create my own AssetReference type:

```
    [Serializable]
    public class Reference : UnityEngine.AddressableAssets.AssetReferenceT<PlayerMaster>, UnityEngine.AddressableAssets.IKeyEvaluator
    {
        public Reference(string guid) : base(guid)
        {
        }
    }

```

but with this new type I cannot select anything!

The following code snippet at least seems to restrict the list to GameObjects which is an improvement, but the user can still assign the wrong GameObjects easily. I was hoping for a more strict filter, but if it is not possible I will settle with:

```
public UnityEngine.AddressableAssets.AssetReferenceGameObject playerMaster;

```

# Answer
I know this question is old but it came up as the first result.

In the current version (1.19), the right approach is to create your own type using generics as you mentioned.

```
    [System.Serializable]
    public class AssetReferencePlayerMaster : AssetReferenceT<PlayerMaster>
    {
        public AssetReferencePlayerMaster(string guid) : base(guid) { }
    }

```

This seems to work as it only allows you to assign objects of the specified type. It definitely works for me with ScriptableObjects.

The reason you're not seeing any assets to pick up is probably because they are not marked as addressables yet.

Hope that helps somebody.
> 3 votes

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


# Question
Title: What does "ray-traced through the lenses" mean in the Oculus VR compositor documentation?
In this link: https://developer.oculus.com/documentation/unity/unity-ovroverlay/

> Objects and textures rendered as compositor layers also render at the frame rate of the compositor, the refresh rate of the HMD, instead of rendering at the application frame rate. Because of this, the compositor layers are less prone to judder and are ray-traced through the lenses. This improves the clarity of the textures or text displayed on them.

What does "ray-traced through the lenses" mean in this case?

# Answer
There are two major complications when rendering content for VR:

* **Head Movement**: between the time you started rendering and the time the frame becomes visible to the user, they may have turned their head slightly, causing the image to lag behind or judder.
* **Lens Distortion**: to achieve a wide field of view and a comfortable focus depth, head-mounted displays use heavy-duty lenses. These have a side effect of substantially distorting the screens behind them – so where you see a pixel in space is displaced from where it's actually located on the screen.

To compensate for these effects, it's conventional to **re-project** the rendered image.

We start with a frame buffer containing a pair of images in linear perspective — each one similar to the image a game would output when rendering to a flat screen. This lets us use all the game engine features we ordinarily would, and take advantage of GPU rasterization hardware that makes drawing 3D content in linear perspective super fast.

Then, just before we send the new frame to the display panels inside the HMD, we re-sample it, moving and distorting the images to compensate for the lens effects and incremental head movement. The trouble is, since we're doing these operations on a raster image, the result is lossy — like scaling up an image that's too small, we can get smeared or blurry pixels in the output.

What the Oculus docs are describing here is an alternate path, where rather than rendering the image first in linear perspective and then bending/warping it, they render it so that it has the right warp to begin with.

I don't know the details of how Oculus implements this, but the basic principle would be like casting a ray from each screen pixel through the lens to see how it gets warped, then casting that adjusted ray back into your overlay geometry. Wherever it hits that overlay, that tells us the exact colour the user should see in that direction, and we send that colour to the screen pixel we started with.

Because we're figuring out one exact colour for each pixel, not blending them according to a resampling algorithm, we can potentially get crisper, more accurate VR rendering this way — especially helpful for text or content with a lot of motion.

But it's likely not as efficient as conventional rasterization and resampling, which is why it's not something we can use for all scene content, like higher-poly animated meshes or layered particle effects — at least not yet.
> 1 votes

---
Tags: virtual-reality, oculus
---


# Question
Title: BoxCollider2D used as reference to Collide with GameObjects but it uses the original size Sprites size to Collide
I'm a beginner in Unity and pretty much copy and pasted the code but I can't figure out why the game is using the size of the sprite and not my `BoxCollider2D` as a reference to collide. I downscaled the Sprite from 1 to 0.32 but in game it collides as if the sprite size would be 1 even though I never used that size.

```
private BoxCollider2D BoxCollider;
private Vector3 moveXYZ;
private RaycastHit2D hit;

private void Start()
{
    BoxCollider = GetComponent<BoxCollider2D>();
}

private void FixedUpdate()
{
    float x = Input.GetAxisRaw("Horizontal");
    float y = Input.GetAxisRaw("Vertical");

    float aktuelleZeit = Time.deltaTime;
    moveXYZ = new Vector3(x, y, 0);

    float size = 0.32f;
    if(moveXYZ.x > 0)
    {

       transform.localScale = new Vector3(size, size, 0);
    }
    if (moveXYZ.x < 0)
    {
        transform.localScale = new Vector3(-size, size, 0);
    }

    hit = Physics2D.BoxCast(transform.position, BoxCollider.size, 0, new Vector2(0, moveXYZ.y), Mathf.Abs(moveXYZ.y * aktuelleZeit), LayerMask.GetMask("Collision", "Player"));
    if (hit.collider == null)
    {
        transform.Translate(0, moveXYZ.y * aktuelleZeit, 0);
    }

    hit = Physics2D.BoxCast(transform.position, BoxCollider.size, 0, new Vector2(moveXYZ.x, 0), Mathf.Abs(moveXYZ.x * aktuelleZeit), LayerMask.GetMask("Collision", "Player"));
    if (hit.collider == null)
    {
        transform.Translate(moveXYZ.x * aktuelleZeit, 0, 0);
    }

    Debug.Log(x);
    Debug.Log(y);
}

```

# Answer
`BoxCollider.size` is the size of your box collider as displayed in its Inspector properties. It does not factor in the scaling you applied with these lines:

```
transform.localScale = new Vector3(size, size, 0);

```

To correct for this, you should adapt your collision query like so:

```
Vector2 actualSize = BoxCollider.size * size;

hit = Physics2D.BoxCast(transform.position, actualSize, 0, ...

```

Two other things to watch for...

* You're applying a negative scale when moving left. This can cause some physics behaviours to misbehave, because it can turn colliders inside-out. You may want to consider using the `flipX` property of the `SpriteRenderer` instead, or putting the sprite(s) on a child object that you can scale and flip (or even squash & stretch) independent of the physics representation.
* You're moving a physics body with `Transform.Translate`. This is a classic way to cause errors. It rips the object out of the control of the physics engine, teleports it, then puts it back into the physics world, breaking interpolation and overriding or disrupting normal collision handling. Consider using `Rigidbody2D.MovePosition` instead, or setting a velocity on your object that matches the displacement you want to achieve in the next time step.
> 0 votes

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


title: Unity serialization with preprocessors

text:
# Question
Title: Unity serialization with preprocessors
I am working on a Unity multiplayer game using mirror, and i separated server- and client-only code using partial classes and preprocessor #if statements based on this answer i found: https://gamedev.stackexchange.com/a/186037/159841

I came across a problem relating to serialized properties and fields with this method. If i switch between client and server define statements, all the inspector values of serialized fields that exist only in the server or client code gets wiped.

Is there any workaround to this? Or should i forget about preprocessor and approach this from a completely different dirrection?

Thanks for any help!

# Answer
You can add an OR case to your preprocessor directives to always include the field when serializing data in the editor, like so:

```
#if SERVER_BUILD || UNITY_EDITOR
    public int someServerOnlyVariableSetInInspector;
#endif

#if !SERVER_BUILD || UNITY_EDITOR
    public int someClientOnlyVariableSetInInspector;
#endif

```

I'm sorry I neglected that case in my original answer. I've corrected the original post so it shows how to use this pattern to persist serialized data in the editor.
> 0 votes

---
Tags: unity, serialization
---


# Question
Title: How should I go about generating a spritesheet JSON file for an existing PNG containing a grid of assets?
To get started with game development I purchased some top-down sprite assets which come arranged in a grid, but to use them with a typical 2D rendering engine (I'm using Pixi.JS), I need a JSON file tracking the coordinates and dimensions of the grid the assets are arranged onto (which was not included in the package I purchased).

So I bought a license for TexturePacker thinking I would be able to somehow generate that JSON. I suppose I could write a program that generates the JSON file (since I do know the assets grid size for the PNG) but I'm wondering if I'm missing some easier way.

The thing is, I purchased probably ten different assets packs and most of them include many of their assets in a plain PNG grid layout with no JSON file tracking the dimensions of the grid. So it seems like a normal format. So I'm perplexed by the idea of having to manually separate the grid into separate PNG assets to then feed it to TexturePacker to re-combine the assets into a grid.

Is there an easier way?

# Answer
> 2 votes
> I suppose I could write a program that generates the JSON file (since I do know the assets grid size for the PNG) but I'm wondering if I'm missing some easier way.

There might be some program that does that, but if you haven't already found one, I encourage you to write your own. Generating rectangles on a regular grid and writing JSON is a simple problem — and you may later be able to adapt the same code, that you're familiar with because you wrote it, to more "asset pipeline" problems as they come up.

---
Tags: spritesheet, pixi.js
---