# Question
Title: Tilting a game object left/right/forward/back with gyroscope, regardless of player's heading
I'm working on a mobile game in Unity and using the gyroscope to rotate an object along the x and y axes.

```
float x = Input.gyro.attitude.x;
float y = Input.gyro.attitude.y;

```

This code give me the rotation I want when pointed in a certain direction along the z-axis. I want the rotation to not depend on the z-axis. I want the rotation to act the same no matter what direction I'm pointed in the real-world.

Here is a 12 second clip of what I get using a mobile gyroscope when pointed at 1 or North on the z-axis:

I want the rotation to be the same no matter what direction I am pointed on the z-axis with the gyroscope. Is there some way to rotate the whole coordinate system?

# Answer
`Input.gyro.attitude` gives you a quaternion representing (a best estimate of) the device's absolute orientation in space - including its orientation relative to the north pole.

But that's not what you want here. You want a measure of how the device is tilted relative to the gravity vector - no matter how we're oriented to north/south/east/west.

```
// Get the vector representing global up (away from gravity)
// within the device's coordinate system.
Vector3 localDown = Quaternion.Inverse(Input.gyro.attitude) * Vector3.down;

// Extract our roll rotation - how much gravity points to our left or right.
float rollDegrees = Mathf.Asin(localDown.x) * Mathf.Rad2Deg;

// Extract our pitch rotation - how much gravity points forward or back.
float pitchDegrees = Mathf.Atan2(localDown.y, localDown.z) * Mathf.Rad2Deg;

```

This gives 0 pitch when the gravity vector points along the phone's z+ axis. If you want your neutral pitch to sit somewhere else, or adapt based on the player's resting pose when holding the phone, you can shift & wrap the angle accordingly using `Mathf.DeltaAngle`
> 2 votes

---
Tags: unity, rotation, mobile, accelerometer, gyroscope
---


# Question
Title: Change object's location at instantiated moment
I'm trying to instantiate object(scene) and set it's spawn position at the spawn time. Here's the code I wrote:

```
func spawn_asteroid():
    var spawn_position: Vector3 = get_spawn_position()

    var asteroid_instance = asteroid_scene.instance()
    asteroid_instance.transform.origin = spawn_position
    spawned_asteroids.append(asteroid_instance)

    add_child(asteroid_instance)

```

asteroid\_scene is PackedScene, so get instance first, and then update it's position, and finally use add\_child to append current scene's tree.

It seems fine to me, however when I run the game, the object was spawned at (0,0,0) and then move spawn\_position.

I changed it's position before it appended to scene, but why it still (0,0,0) and right after move to the specified position?

In Unity, change object's location right after instancing works. In Godot Engine, is this approach invalid?

# Answer
I was able to reproduce this and filed an issue. Two things to note:

1. There was a similar issue that was fixed in Godot 3.1, so ensure you're on the latest release.
2. This only happened for me if I instanced a scene during `_ready`. If I instance a scene in `_physics_process` the object is immediately placed at its final destination.
> 1 votes

---
Tags: godot, instancing
---


# Question
Title: Wwise: play specific audio clip without specific event (for dialogue)
Is it possible to play a specific audio object in Wwise without having a separate event for it? I'm implementing a dialogue system, and I have thousands of audio clips for dialogues, and making an event for each and every one would be extremely time consuming and error prone and impossible to maintain.

So either play an audio object from a bank directly or somehow giving the event an argument as to which object to play (I know that goes against the idea of events and the fact that the caller shouldn't know exactly what clip is going to be played).

I believe what I'm looking for is something akin to FMOD's audio tables.

# Answer
Use Wwise External Source plugin, described relatively well here. The docs on this feature are not the best, but the general workflow I used went something like this:

1. Stored voice over files outside the Wwise project and Unity streaming assets folder (could be anywhere, I used a folder next to the Assets folder)
2. Create a new Voice audio object in Wwise and add an External Source to it (edit the audio object, click "Add Source" and select External Source)
3. Wrote a simple python script to generate a .wsources XML file that reads all the files in the voice files folder
4. Add the .wsources file to the external sources in Project Settings in Wwise
5. Post the event from Unity with path being whatever you used as "Destination" in the .wsources file, ie. it's *not* an absolute path
> 1 votes

---
Tags: unity, wwise
---


# Question
Title: Identify an object currently selected in the game
I am making a 2D isometric game that uses the mouse. When I left click on an object, this object should be selected, but how do I determine what object that's currently selected and show a halo around it?

My objects are stored in a list of game objects as `std::vector<Game_Object *> Object_Game`. I am using the SDL library with C++. I did some research on Google but only found articles about Unity. Can someone help me with this?

# Answer
> 0 votes
Your use-case is two-fold:

1. Projecting your 2d mouse coordinates to 3d world coordinates, to create a ray.
2. Performing collision detection on the new coordinates, compared to your game objects.

**NDC to 3D world coordinates**

To do this, you need your view and projection transform matrices:

```
mat4 view = lookat(camPos, camPos+camDir, vec3(0.0f,1.0f,0.0f);
// For 3D
mat4 projection = perspective(fovAngle, aspectRatio, znear, zfar);
//for 2D
mat4 projection = ortho(0, width, height, 0);

```

combine these matrices using affine transformations:

```
mat4 worldToScreen = projection * view;

```

then invert them:

```
mat4 screenToWorld = inverse(worldToScreen);

```

Now, we take our mouse coordinates, and transform into world coordinates:

```
vec3 worldMouse = screenToWorld * vec4(mouseX,mouseY,-1.0f,1.0f);

```

Then finally we create our ray:

```
vec3 ray = normalize(worldMouse - camPos);

```

**Collision Detection**

Now, we can iterate through a vector of game objects, to determine which one has been clicked on:

```
gameObject *selectedObject; = nullptr;
for (auto &gameobject: gameObjects)
{
    if (gameobject.collide(ray))
    {
        selectedObject = gameobject;
        break;
    }
}

```

Then you can have some rendering code that draws a halo on the ground at the targeted object position:

```
void render()
{
    if (selectedObject != nullptr)
    {
        selectedHalo.drawAt(selectedObject->getPosition());
    }
    // then draw your game objects as normal.
}

```

This technique is known as "3D picking". There are plenty of more detailed tutorials available, but I covered the basic gist of it.

---
Tags: c++, 2d, sdl, isometric
---


# Question
Title: Projection Matrix Causes Clip Cuttoff Problem
I'm trying to setup my renderer and I'm configuring the matrices. I currently have a View Matrix and a Projection Matrix which I then multiply and send to the shader(there's no need for model matrix since I'm just testing).

The problem is I just can't seem to get the projection matrix right. My model of a sphere appers cut in half in the center of the screen, I can move it around but once the Z value for the transform in the matrix goes beyond 1(Vulkan's max value for NDC) the model cuts off.

This is the code for the view matrix:

```
ViewMatrix(3, 0) = CamPos.X;
ViewMatrix(3, 1) = -CamPos.Y;
ViewMatrix(3, 2) = CamPos.Z;

```

The numbers on the left are the rows and those on the right the columns. Matrices are row-major. And my renderer's coordinate system is left handed.

This is the code for the projection matrix:

```
auto f = 1 / tan_half_fov;

_Matrix(0, 0) = f / _AspectRatio;
_Matrix(1, 1) = -f;
_Matrix(2, 2) = _Far / (_Near - _Far);
_Matrix(2, 3) = -1;
_Matrix(3, 2) = (_Near * _Far) / (_Near - _Far);

```

The matrix is just an identity matrix and the every frame it gets set those values. `tan_half_fov` is 0.41421356, since it's tan(45 deg / 2). `_Near` is 1, and `_Far` is 500.

The vertex shader:

```
void main()
{
    gl_Position = inData.Pos * vec4(inPos, 1.0);
}

```

`inPos` is the vertex data input for vertex position and `inData.Pos` is the ViewProjection matrix.

The matrix multiplication code is working alright, I tested it. When sending to the shader just the view matrix the sphere appears all flat on the screen and moves around correctly. I am using Vulkan.

Any help is appreciated!

# Answer
> 2 votes
To solve your problem, you need to understand how a projection matrix works:

A projection matrix represents a frustum, shown in this image:

As you can see, it looks a bit like a pyramid with the cap cut off, or trapezium.

The near and far values tell the shader which fragments to draw, via a depth test.

Fragments, once translated to screen space, will be culled, if they have a z value of less than 0, or greater than 1.

Now let's look at "handed-ness":

OpenGL uses a right handed coordinate system, whilst Vulkan uses a left handed coordinate system, with the exception that the Y axis is flipped.

If your perspective transform maps a z value outwith the range of \[0-1\], then it will be culled, so check your perspective transform construction.

---
Tags: c++, vulkan
---


title: C++ inheriting functions problem

text:
# Question
Title: C++ inheriting functions problem
So I am creating a game with C++ and SDL. I have a "gameobject" header file and no cpp (I do not need it) the game object has 2 functions `void render()` & `tick()`.

The `player` class inherits from the `gameobject`. the problem is I don't know how to inherit functions. I tried virtual but I still can't figure it out. I am used to Java so C++ is quite complicated.

My code:

gameobject.h :

```
#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>
#include "game.h"

class gameobject
{
    public:
        virtual ~gameobject();

        void virtual tick() = 0;
        void render();

    protected:

        int width = pos.w;
        int height = pos.h;
        int posx = pos.x;
        int posy = pos.y;

        float velox;
        float veloy;

        SDL_Rect crop;
        SDL_Rect pos;
};

#endif // GAMEOBJECT_H

```

player.h:

```
#ifndef PLAYER_H
#define PLAYER_H

#include "gameobject.h"

class gameobject;

class player : public gameobject
{
    public:

    private:

        player(SDL_Renderer* renderer,int pwidth,int pheight);
        ~player();
};
#endif // PLAYER_H

```

player.cpp :

```
#include "player.h"

player::player(SDL_Renderer* renderer,int pwidth, int pheight)
{
    this->pos.w = pwidth;
    this->pos.h = pheight;
};

void player::tick(){} /// the problem here

```

# Answer
> 1 votes
In the future, make sure to write the error the compiler gives.

In c++, for a function to work, you need (generally) two things: a declaration, and a definition. (In some situations, both can be combined.)

However, here,

```
void virtual tick() = 0;

```

will only *declare* the function. You basically tell the world "I, the mighty `gameobject`, hereby declare this function, now *you*, subclasses, define one." (This is because you use `= 0`.)

You need to declare and define such a function in your `player` class so you can use it there. Here you define a function that you did not declare, so you need to declare it.

Declare (in the header file):

```
class player : public gameobject
{
    public:
        void tick() override;
    ...

```

# Answer
> 1 votes
Java is object oriented, that is, it makes heavy use of inheritance, but the syntax is a little different.

In C++ we declare a *base class*, which can be viewed as an *interface*, thusly:

```
class Base
{
public:
    Base(){} //simple constructor
    virtual void foo() = 0; //this is known as a pure virtual function
    virtual ~Base(){} //virtual destructor
};

```

Now we can derive a child class:

```
class A:
    public Base
{
public:
    A(){}
    virtual void foo() override { //do something }
    virtual ~A(){}
};

```

Ok, now that we have defined our base and child class, we can explain how this works.

When we *instantiate*, that is, create an instance of the class A, we can do so thusly:

```
Base* b = new A();

```

Then we can call foo:

```
b->foo();

```

What happens, is that when your program runs, for the class family, a *virtual function table*, or vtable, is created for virtual functions.

Think of it like this, in simplistic terms:

```
b: ctor : 0001 //address of Base constructor
        : 0002 //address of A constructor
 : foo  : 0000 //address of Base::foo(): null, as it is declared as pure virtual (0)
        : 0003 //address of A::foo()
 : dtor : 0004 //address of Base::~Base()
        : 0005 //address of A:~Base()

```

This is a table of pointers to functions. When a function is called, the table is referenced, and the pointer to the appropriate function retrieved, and then executed.

Every child class declaration must provide a definition for any virtual functions declared in a parent class, and if using a \*.cpp (definition file), the header must also have a declaration of the function.

The `virtual` keyword tells the compiler to create a vtable entry for the class, and the `override` keyword tells the compiler that for that class you are overriding any previous implementations of the foo() function

So, armed with that information, we can see that in your child class, you have not provided a declaration, nor implementation, of the tick() pure virtual function declared in your base class.

Thus, when you try to compile your code, you will be given an error telling you that you have created a child class (Player), which does not implement the interface specified in GameObject.

Long story short: The compiler will not allow instantiation of a class which does not implement it's parent class's interface.

See Here for more information.

---
Tags: c++, sdl2, inheritance
---


# Question
Title: How to handle all the customization data for a Loot and Shooter?
Games like Borderlands, Fortnite, Destiny all have some sort of mechanic where your skills are modifiable by the equipment you carry.

For example in Borderlands, you can equip a pistol with generic damage of 100. The shield you equip also increases the damage of pistols only by 10%. Equipping a class mod increase any gun damage by 25%. And equipping an artifact reduces pistol damage by -10 points (Not a percentage). Your skill tree adds another 5%. And your Guardian rank adds another 2.9% of damage over time of 10 seconds. Moreover, your skill tree gives you the ability to add 5% to your health of the gun damage inflicted on an enemy for 10 seconds.

As you can see the forumla for calculating just gun damage for a pistol has a lot of moving parts.

There can literally be hundreds of possible combinations.

Then you have shields, grenades, and other buffs that are also practically endless with their own individual customization. On top of possibly modifying the other items you have equipped. By increasing your guns reload speed or your magazine size etc...

Is every possible attribute an `interface`? There may be instances where your equipped shield gives Shotguns a 5% increase in reload speed, but you dont' have a shotgun equipped.

Is there some master abstract character class with every possible key/value attribute? Then when you pick a character like a "Gunner" or "Siren" you inherit from the master character class so you have a base stat to start working with?

I know that some bullets are actual objects that travel through space and not just a ray-cast. Is every bullet equipped with some `struct` that carries along a bunch of information relevant to the gun that shot it and what it should do?

For example an "acid bullet" might have a base damage, a damage over time, and then a spread chance. On top of stealing 5% of the health of the target to give back to the shooter for `x` amount of time.

I've beent trying to wrap my head around how to implement such a system. How is such a system implemented?

# Answer
I solved this problem in many different ways in the past. Unfortunately there is no silver bullet here. Every architecture has advantages and drawbacks. So I am going to describe several approaches here so you can choose which one is most appropriate for the game you want to create.

First of all, such mechanics usually requires that a modifiable character attribute (like maxHp, attackSpeed or even exotic attributes like perAttackLifeStealChance) is more than just a `int` or `float` member variable of your character. It usually requires that you store all the modifiable attributes in an array. That way you can generalize the code which calculates them. You don't use `character.attackSpeed`, you use the function `character.GetAttribute(ATTACK_SPEED)` with `ATTACK_SPEED` being a constant representing the position of the attack speed in the character attribute array.

This function might or might not cache its results. This is an optimization question which depends on how computationally expensive this function gets and how often it is called. But be weary of premature optimization here! You won't know yet if your attribute handling is going to become a bottleneck. So you should prioritize readability and maintainability over performance until you have profiled it with real gameplay and the data shows that you have to optimize.

OK, but how do we implement `GetAttribute`?

# Calculate everything in one place

Have the GetAttribute function go through every single system in the game which could modify attributes and apply it to the return value. Character perks, equipment, area effects, temporary effects, you name it.

This has the advantage that it is pretty easy to find bugs. If an attribute comes out on some nonsensical value, you know exactly where you have to set your debugger breakpoint.

But on the other hand, it creates a very tight coupling between this function and everything which changes an attribute. When you have a lot of attribute modifying features, this function could turn out pretty gargantuan and with dependencies on a lot of different game systems.

# Register and unregister modifiers

OK, so let's make this more generic. Make the stat calculation system unaware of which systems can cause stat modifiers. Any other system can call `character.AddAttributeModifier` to add an attribute modifier and then `character.RemoveAttributeModifier` to remove it again. The `character.GetAttribute` calculation function now only needs to go through all the modifiers and apply them. It doesn't need to concern itself with where that modifier comes from.

This has the advantage that the attribute calculation function becomes very simple. You can hide the complexity of exotic conditional modifiers in those systems where they belong. It might also have performance advantages, because the function no longer needs to look into modifiers from systems which currently don't modify anything. (But again: be weary of premature optimization here).

But the disadvantage is that this architecture is very prone to bugs resulting from systems not unregistering modifiers when they should be. Have you heard of exploits in games where repeating some unlikely sequence of actions allows the player to raise a character attribute to unlimited values? Instructions like "use temporary buff, quicksave, change area, quickload, die before the buff runs out, respawn, and suddenly the temporary buff is permanent and can be cast again and it stacks"? Whenever I read about something like that I suspect that they are using this architecture and have a system which forgets to unregister some temporary attribute modifier in some edge-case they didn't think about.

# Apply modifiers every game tick

OK, so we need to make sure that something which isn't active anymore no longer affects the character attributes. How can we make sure of that? We could insist that each game system which modifies attributes modifies them again for every game tick. That modifier is then active for only the next game tick. If the system wants to maintain that modifier for longer, it has to keep posting it every tick.

This architecture could be realized by maintaining 3 values for every attribute:

* base value
* current value
* modification value

Every system can increase or decrease the modification value for each stat. But no system is allowed to ever change the base or current value. They are only allowed to read those.

Then you would have a separate attribute recalculation system which would run every tick and for each attribute:

1. reset `current` to `base`
2. add `modification` to `current`
3. set `modification` back to 0

This architecture relies on the premise that every system gets executed exactly once between two calls to the attribute recalculation system. But is this actually true in your architecture? There might be systems which would benefit from doing only occasional updates. So forcing them to run every tick just to maintain their modifiers might become restricting for your architecture. You also have that "spooky action at a distance" problem which comes with shared access to global values. If you suddenly end up with a ridiculous modification value in your attribute system update, you might have to go on a wild goose chase to find out which system set that value and why.
> 1 votes

---
Tags: architecture, game-mechanics
---


# Question
Title: How to avoid game starting before start button is clicked?
I've made a game with a Title Screen (Canvas), and a Start Button attached to the Title Screen. Points, GameOver, Restart, and even the Start Button sort of works, but it's possible to play the game *before* the user presses start.

Is there a way to make the GameObjects only appear *after* the button is clicked? I've tried to move and change the "public void StartGame()", but I can't get it right.

This is my first game ever, so hope the code provided is relevant.

Enemy.cs

```
 void Start()
{
        enemyRb = GetComponent<Rigidbody>();
        gameManager = GameObject.Find("GameManager").GetComponent<GameManager>();
        player = GameObject.Find("Player");
}

```

GameManager.cs

```
 public void StartGame()
{
    powerup.transform.rotation);
    score = 0;
    UpdateScore(0);
    isGameActive = true;
    titleScreen.gameObject.SetActive(false);
}

void Update()
{
    enemyCount = FindObjectsOfType<Enemy>().Length;

    if (enemyCount == 0)
    {
        roundNumber++;
        SpawnEnemyIntruders(roundNumber);
        Instantiate(powerup, GenerateSpawnPosition(), powerup.transform.rotation);
    }
}

void SpawnEnemyIntruders(int enemiesToSpawn)

{
  for (int i = 0; i < enemiesToSpawn; i++)
  {
      int enemyIndex = Random.Range(0, enemies.Length);
      Instantiate(enemies[enemyIndex], GenerateSpawnPosition(), enemies[enemyIndex].gameObject.transform.rotation);
  }
}
public void GameOver()
{
    restartButton.gameObject.SetActive(true);
    gameOverText.gameObject.SetActive(true);
    isGameActive = false;
}

```

PlayerController.cs

```
    void Start()
{
    playerRb = GetComponent<Rigidbody>();
    playerAudio = GetComponent<AudioSource>();
}

```

StartButton.cs

```
    void Start()
{
    button = GetComponent<Button>();
    gameManager = GameObject.Find("GameManager").GetComponent<GameManager>();
    button.onClick.AddListener(StartThis);
}

```

# Answer
welcome the community.

that is so simple. you need to define some flag for running of your game and instead of writing logic of start game in Start(){} function that is called on start of game object, you should call it for example on button press and make your update function that is called every frame only Work if a bool flag is True. i re-write your code for your approach:

```
public Button StartButtn;

public void StartGame
{
// everything on start function was called
}

 void Start()
{
StartButton.OnClick.AddListener(StartGame);
}

bool GameStarted;

void Update()
{
if(!GameStarted) return;
// everything that was called in update function

}

```
> 0 votes

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


# Question
Title: Should fields in components in an ECS use polymorphism?
I've just started to try and learn how to use ECS (Entity component systems), but I'm having trouble understanding the concepts behind components.

Should adding more types of components, or trying to make a component reusable through its fields be favored? For example, if I'm trying to give all entities a shape for collision detection, should I have a different component for every shape (`RectangleComponent`, `CircleComponent`, `PolygonComponent`), or should I have one ShapeComponent, and in there have a field which is of type `Shape`, with `class Shape` having subclasses `Rectangle`, `Circle`, and `Polygon`.

I'm unsure because using a `Shape` seems to be much more flexible and easier to implement systems, but it also feels like I'm violating the ECS rule of not having any functionality in components.

# Answer
> 3 votes
> feels like I'm violating the ECS rule

There is no ECS police that will come and put you in ECS Jail. This is your architecture, you set it up how it fits your needs.

> having any functionality in components.

I don't see any *functionality* in what you suggest. I only see *data*.

At their core, all of those are effectively shapes and will have to be treated more or less all in the same fashion when they'll go through your systems. If you set them up as different individual component types, you'll have a hard time deciding which of those shapes will be processed by the system first, then second, then third, etc., or you'll have a hard time to group them together to process them in a consistent fashion.

It's fine to have a ComponentShape, and have data about the shape in it.

---
Tags: entity-system, component-based, logic, entity-component-system, data-oriented
---


title: Recursively find neighbors

text:
# Question
Title: Recursively find neighbors
I'm making a Bubble Shooter game in Unity. I came to the point where I can hit another bubble and it destroys all of its neighbors.

Now I'm trying to use recursion to destroy all of its neighbors neighbors and it causes a stack overflow.

```
private List<Bubble> FindAllRecursiveNeighbors(Vector2Int originPosition)
{
    List<Bubble> allNeighbors = FindNeighbors(originPosition);
    List<Bubble> result = new List<Bubble>();

    foreach (Bubble bubble in allNeighbors)
    {
        if (result.Contains(bubble)) { continue; }
        result.Add(bubble);
    }

    // Recursion starts here.
    foreach (Bubble bubble in result)
    {
        List<Bubble> neighbors = FindAllRecursiveNeighbors(FindPositionOfBubble(bubble));
        foreach (Bubble neighbor in neighbors)
        {
            if (result.Contains(neighbor)) { continue; }
            result.Add(neighbor);
        }
    }
    return result;
}

```

# Answer
> 2 votes
You're trying to limit double-counting using your results list:

```
if (result.Contains(neighbor)) { continue; }
    result.Add(neighbor);

```

The trouble is, you're using a *different* result list in each iteration:

1. We call `FindAllRecursiveNeighbours` with bubble A's position.
2. We make a new `result` list for A, and find all A's neighbours, including bubble B.
3. Bubble B is not in A's `result` list (it's a new, empty list), so we add it.
4. We walk through A's `result` list and recurse on its contents.
5. In this walk, we call `FindAllRecursiveNeighbours` with bubble B's position.
6. We make a new `result` list for B, and find all B's neighbours, including bubble A.
7. Bubble A is not in B's `result` list (it's a new, empty list - we didn't pass our results so far from the A steps above), so we add it.
8. We walk through B's `result` list and recurse on its contents.
9. In this walk, we call `FindAllRecursiveNeighbours` with bubble A's position.
10. ...uh-oh, we're back at a situation identical to the beginning of this process. So we repeat the steps above infinitely, ping-ponging back and forth between bubble A and bubble B, because each generation of the search doesn't know they've already been checked in past generations.

To fix this, we need to make the later generations aware of what we've searched so far. That can look like this:

```
public static void FindNeighboursRecursively(Bubble start, List<Bubble> foundSoFar) {

    foundSoFar.Add(start);

    foreach(var bubble in FindNeighbors(FindPositionOfBubble(start))) {
        if(foundSoFar.Contains(bubble))
            continue;

        FindNeighboursRecursively(GetPositionOf(bubble), foundSoFar);
    }
}

```

Now all the recursive calls share one result list, `foundSoFar`, so we can skip bubbles found later that were already visited in earlier generations.

Also, passing this in as an argument means the calling code can choose to keep one persistent list as a member variable, and recycle it between uses, saving some unnecessary re-allocations. That's how Unity's `NonAlloc` physics queries do their work too.

Just remember to clear the list before starting a new search:

```
private List<Bubble> connectedBubbles = new List<Bubble>();

void UpdateConnections(Bubble start) {
    connectedBubbles.Clear();
    FindNeighboursRecursively(start, connectedBubbles);
}

```

One note on `List.Contains()`: this searches the whole list, checking if the argument matches each entry along the way. So as your list grows, this search takes longer (\\$O(n)\\$). If you're gathering collections of dozens of bubbles, it's likely not an issue. If you're working with hundreds or more though, you'll likely want to use a different method to mark & check whether an item has been visited already - like a boolean flag on each item as iQew suggested, or a Hashset, both of which will give you \\$O(1)\\$ lookups.

# Answer
> 1 votes
The thing is that you look for neighbours and then you call the same method again on the neighbours, which means that you can find the origin again, as well. This causes an infinite loop meaning StackOverFlow in this case. It might make more sense to find a clever way to give each Bubble an Array or List of Bubbles (Neighbours) and set them during the level creation. So when you shoot a bubble and want to destroy all neighbours, you have more control since some bubbles might have neighbours set and some don't (exit condition).

---
Tags: unity, recursion
---


# Question
Title: Twine disabling style characters not working when using Harlowe format
According to the Twine documentation, if a word has asterisks around it, it's rendered in italics:

*Italics* = \*Italics\*

If I want to literaly show the asterisks, then I need to put some extra characters around it:

\*Boom!\* == \`\`\*Boom!\*\`\`

What is ``` ?

Is it `'`? Because I don't get the desired results when writing ' '\*Boom!\*' ' or "\*Boom!\*".

In fact, ''text'' seems to be equivalent to \**text\** even though it doesn't say that on the doc pages the program links me to.

# Answer
> 0 votes
``` is the backtick character. On a standard QWERTY keyboard, you can find it to the left of the row of number keys, just under the tilde (~):

> In fact, ''text'' seems to be equivalent to **text** even though it doesn't say that on the doc pages the program links me to.

Sure it does, right in the very first cell of the table explaining Harlowe formatting:

> **Bold** = \**Bold\** or ''Bold''

You can select the text to verify that the two ticks on each side of Bold are separate apostrophe characters, not a single double-quotation mark.

---
Tags: twine
---


# Question
Title: How to stop counting point when player dies (Destroy)
In my game, I'd like to stop counting points when the player's y is -4. When the pink and red balls fall off the Plane the player gets points. But it seems a bit strange to be able to collect points after the player dies.

This is the code for the player:

```
     if (transform.position.y < -4)
    {
       Destroy(gameObject);
       gameManager.GameOver();
    }

```

And in the GameManager.cs I have this:

```
   public bool isGameActive;

   public void UpdateScore(int scoreToAdd)
   {
      score += scoreToAdd;
      scoreText.text = "POENG: " + score;
   }

   public void GameOver()
   {
      isGameActive = false;
      restartButton.gameObject.SetActive(true);
      gameOverText.gameObject.SetActive(true);
   }

```

And this is the code for adding points when the enemies fall over the edge:

```
    if (transform.position.y < -4)
    {
       Destroy(gameObject);
       gameManager.UpdateScore(pointValue);
    }

```

How can I make the game stop counting points when the player dies?

# Answer
In the updatescore method you simply ask, whether isGameActive is true or not.
> 1 votes

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


# Question
Title: unity: input event consumed by image raycast target that is "under" a sprite with a 2D collider
I am having a hard time getting my UI to work.

Basically I have a canvas with a UI image A that is the size of the screen. This image has raycast enabled and if effectively receiving inputs.

Not in the canvas I have a sprite B that have a 2D collider attached to it. No matter what I try, the UI image is always consuming the input event when I click on the sprite.

When I disable the image A , the sprite B gets the events, so the setup looks right (camera with Physic2D raycaster for the sprite B, layerMask set to the layer of the sprite B, canvas with Graphic raycaster for the image A, no blocking object, no mask).

What do I need to do so that the sprite B gets the input event BEFORE the image A and consume it?

**EDIT:** Those two elements are part of the UI and must be interactable at all time. I use a sprite for the second element as it is dragged from the UI inside the game and I don't want to make it an image.

The image A is a big cancel button with opacity 0 on the whole screen that must be active at all time.

I just want to know if the Collider of sprite B can intercept the input before the image A. If it isn't possible, I'll create an Image B instead of the sprite B and destroy it to create a Sprite with the same texture when the is interacted with.

# Answer
> 1 votes
If you need the Image enabled during the process but also do not want it to 'receive input' you can get a reference to the image and disable the **Raycast Target**. Then re-enable it when you need it.

If you never want it to be selectable you can just uncheck the box in the bottom right.

```
image.raycastTarget = false;

```

# Answer
> 0 votes
As per the comments it doesn't look possible to mix input systems together. I will use the answer given by IQew and use plain Image UI Element to interact with the mouse, drag the object and then, when it is in game I will switch it to sprite , either by destroying the gameObject with the image attached and creating a new Sprite in place, or just toggling the Image component off and the spriteRederer component on.

Thanks!

---
Tags: unity, 2d, input, raycasting, events
---


# Question
Title: How to make a new powerup reset the WaitForSeconds from previous powerup?
I'm making a game where the player is pushing objects outside a plane. Every round there's an additional ball (GameManager.cs):

```
 for (int i = 0; i < enemiesToSpawn; i++)

```

But every round the player gets a powerup as well:

```
 if (enemyCount == 0)
    {
       roundNumber++;
       SpawnEnemyIntruders(roundNumber);
       Instantiate(powerup, GenerateSpawnPosition(), powerup.transform.rotation);
    }

```

In the PlayerController.cs the code looks like this:

```
   private void OnTriggerEnter(Collider other)
{
    if (other.CompareTag("Powerup"))
    {
        hasPowerup = true;
        Destroy(other.gameObject);
        StartCoroutine(PowerupCountdown());
        powerupParticle.Play();
        playerAudio.PlayOneShot(powerupSound, 1.0f);
    }
}

IEnumerator PowerupCountdown()
{
    yield return new WaitForSeconds(5);
    hasPowerup = false;
    powerupParticle.Stop();
}

```

How can I reset the WaitForSeconds, or do something similar, every time the player gets a powerup?

# Answer
You could have a timer as class' member instead of a local variable in your coroutine.

```
private float powerupTimer;
private IEnumerator powerupCoroutine;

private void OnTriggerEnter(Collider other)
{
    if (other.CompareTag("Powerup"))
    {
        hasPowerup = true;
        Destroy(other.gameObject);
        powerupTimer += 5;
        if(powerupCoroutine != null)
            StopCoroutine(powerupCoroutine);
        powerupCoroutine = PowerupCountdown();
        StartCoroutine(powerupCoroutine);
        powerupParticle.Play();
        playerAudio.PlayOneShot(powerupSound, 1.0f);
    }
}

IEnumerator PowerupCountdown()
{
    for(; powerupTimer > 0 ; powerupTimer -= Time.deltaTime)
       yield return null;
    hasPowerup = false;
    powerupParticle.Stop();
}

```

---

However, I believe you should rework your power up system. The player class should not be responsible for all this logic (handling timer, particles, ...)
> 0 votes

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


# Question
Title: Can't change anchor position and TextureRect size
I'm making UI, and want to set anchor to middle of the image, but changing anchor from Layout -\> Anchors Only or setting Anchor value directly doesn't work. The value was updated, but anchor point not moved at all. Is it bug or is there are something that I missed?

Here's the node tree:

* CanvasLayer
    + Control
        - TextureRect \<- Anchor is not moving at all

Using Godot 3.1.1.

Also I can't find how to resize texture rect. I can set the min-size, but change size doesn't work, the value immediately set back to original size. How to change the texture rect size?

# Answer
The layout options *will* change the anchor points of a `Control`, and you can resize a `TextureRect` by setting `expand` to `true`. You can demonstrate this to yourself:

1. Start a new project
2. Create a `Control`
3. Add a `TextureRect` as the child
4. Set the included "icon.png" as the texture
5. Set `expand=true`
6. Click `Layout > Full Rect`

Note that the Anchors are now set to `(0, 0, 1, 1)` and the rect size is `1024x600`.

> want to set anchor to middle of the image

The way you descibe this suggests that maybe you mean the "pivot point" and not the "anchors". The pivot point is the little red cross in the UI, and is set under the `Rect` category of `Control`.

Here's screenshots of the pivot at 0x0 and 32x32:
> 1 votes

---
Tags: gui, godot
---


# Question
Title: How to wait until other script is ready?
I have two scripts, first is AsteroidSpawner script that literally spawns object named Asteroid, and second is HUD that control all UI related stuffs.

There are some labels in UI, so I used onready to get those nodes:

```
extends CanvasLayer

class_name HUD

onready var asteroids_label = $Control/RightContainer/AsteroidCountLabel

func set_asteroids_label(value: float):
    asteroids_label.text = "Asteroids: " + str(value)
    pass

```

However, when I try to access HUD script, with setasteroidlabel, it gives me null error:

```
var spawned_asteroids: Array = []
onready var hud: HUD = get_tree().get_root().find_node("HUD", true, false)

func _ready():
    spawn_asteroids()

func spawn_asteroids():
    ... spawn asteroid ...

    spawned_asteroids.push_back(asteroid_instance)

    hud.set_asteroids_label(spawned_asteroids.size()) # UPDATE HUD

```

> Invalid set index 'text' (on base: 'Nil') with value of type 'String'

I guess that HUD is not ready, but AsteroidSpawner script try to accessing it, wasn't it? Then how should I wait until HUD is loaded?

# Answer
You can `await` until it's ready:

```
func _ready():
   await hud.ready # Godot 4
   hud.set_asteroids_label(spawned_asteroids.size()) # Works

```

In earlier versions of Godot, you can use `yield` instead:

```
func _ready():
    yield(hud, "ready")
    hud.set_asteroids_label(spawned_asteroids.size()) # Works

```
> 3 votes

# Answer
`Invalid set index 'text' (on base: 'Nil') with value of type 'String'` indicates that the issue is with `$Control/RightContainer/AsteroidCountLabel`, *not* `et_tree().get_root().find_node("HUD", true, false)`. Make sure that you actually have the correct path to `AsteroidCountLabel` within the HUD.

One easy way to do this is by selecting the node in the editor and pressing `Ctrl+C` -- this will copy the relative node path to your clipboard, so you can paste it into the script.

You could also export a var of type `NodePath` from your HUD and set it to the path of the label in the editor.
> 0 votes

---
Tags: godot
---


# Question
Title: Select a block of tiles from tilemap by click and dragging
I'm creating my first game in Godot 3.1, a top-down 2D sim game where you can build rooms on a space station. I am using a tileset I created inside a TileMap node. I placed a script inside the node that checks for the mouse position in the world, converts it into a tilemap coordinate, then loads a tile into that tilemap coordinate.

```
func _input(event):
if (event is InputEventMouse):
    var button = event.get_button_mask()
    if (button == 1):
        var tile_pos = world_to_map(event.position)
        var name = _tileset.tile_get_name(0)
        set_cellv(tile_pos, _tileset.find_tile_by_name(name))

```

Works like a champ! As long as the left mouse button is held down, any tile the mouse pointer touches is filled with the tile from the tileset.

Now I am trying to expand this function so that I can click the world and drag across several tiles to form a rectangle or square, then have all of the tiles inside the selected area filled with the selected tile.

```
func _input(event):
if (event is InputEventMouse):
    var button = event.get_button_mask()
    if (button == 1):
        var tile_pos = world_to_map(event.position)
        if (dragStart == Vector2(-1,-1)):
            dragStart = tile_pos
        var name = _tileset.tile_get_name(0)
        if (dragStart != Vector2(-1,-1) && dragStart != tile_pos):
            var newX = dragStart.x - tile_pos.x
            var newY = dragStart.y - tile_pos.y
            while (newX != 0 && newY != 0):
                var next = Vector2(-1,-1)
                if newX > 0:
                    next = Vector2(dragStart.x - 1,dragStart.y)
                    newX = newX - 1
                elif newX < 0:
                    next = Vector2(dragStart.x + 1,dragStart.y)
                    newX = newX + 1
                elif newX == 0:
                    if newY > 0:
                        next = Vector2(dragStart.x,dragStart.y - 1)
                        newY = newY - 1
                    elif newY < 0:
                        next = Vector2(dragStart.x,dragStart.y + 1)
                        newY = newY + 1
                print(next)
                set_cellv(next, _tileset.find_tile_by_name(name))
    else:
        dragStart = Vector2(-1,-1)

```

However, it seems to only load some of the tiles and functions sporadically. Am I not understanding how the system iterates through the while loop or am I missing something else?

# Answer
Sometimes, you just need a break to see what you were missing. I had the code all wrong. After the lightbulb went off, here's what I came up with:

```
func _input(event):
if (event is InputEventMouse && buildOn == true):
    var button = event.get_button_mask()
    if (button == 1):
        var name = _tileset.tile_get_name(14)
        var oldRect = get_used_cells_by_id(14)
        var i = 0
        while (i < oldRect.size()):
            set_cellv(oldRect[i],-1)
            i = i + 1
        var tile_pos = world_to_map(event.position)
        if (dragStart == Vector2(-1,-1)):
            dragStart = tile_pos
        if (dragStart != Vector2(-1,-1)):
            var newX = dragStart.x - tile_pos.x
            var next = Vector2(-1,-1)
            var startX = dragStart.x
            while (newX != 0):
                var newY = dragStart.y - tile_pos.y
                var startY = dragStart.y
                if newX > 0:
                    while (newY != 0):
                        if newY > 0:
                            next = Vector2(startX,startY)
                            newY = newY - 1
                            startY = startY - 1
                        elif newY < 0:
                            next = Vector2(startX,startY)
                            newY = newY + 1
                            startY = startY + 1
                        set_cellv(next, _tileset.find_tile_by_name(name))
                    if newY == 0:
                        next = Vector2(startX,startY)
                        set_cellv(next, _tileset.find_tile_by_name(name))
                    newX = newX - 1
                    startX = startX - 1
                elif newX < 0:
                    while (newY != 0):
                        if newY > 0:
                            next = Vector2(startX,startY)
                            newY = newY - 1
                            startY = startY - 1
                        elif newY < 0:
                            next = Vector2(startX,startY)
                            newY = newY + 1
                            startY = startY + 1
                        set_cellv(next, _tileset.find_tile_by_name(name))
                    if newY == 0:
                        next = Vector2(startX,startY)
                        set_cellv(next, _tileset.find_tile_by_name(name))
                    newX = newX + 1
                    startX = startX + 1
            if newX == 0:
                var newY = dragStart.y - tile_pos.y
                var startY = dragStart.y
                while (newY != 0):
                    if newY > 0:
                        next = Vector2(startX,startY)
                        newY = newY - 1
                        startY = startY - 1
                    elif newY < 0:
                        next = Vector2(startX,startY)
                        newY = newY + 1
                        startY = startY + 1
                    set_cellv(next, _tileset.find_tile_by_name(name))
                if newY == 0:
                    next = Vector2(startX,startY)
                    set_cellv(next, _tileset.find_tile_by_name(name))
    elif (button == 0 && dragStart != Vector2(-1,-1)):
        var name = _tileset.tile_get_name(15)
        var tile_pos = world_to_map(event.position)
        if (dragStart != Vector2(-1,-1) && dragStart != tile_pos):
            var newX = dragStart.x - tile_pos.x
            var next = Vector2(-1,-1)
            var startX = dragStart.x
            while (newX != 0):
                var newY = dragStart.y - tile_pos.y
                var startY = dragStart.y
                if newX > 0:
                    while (newY != 0):
                        if newY > 0:
                            next = Vector2(startX,startY)
                            newY = newY - 1
                            startY = startY - 1
                        elif newY < 0:
                            next = Vector2(startX,startY)
                            newY = newY + 1
                            startY = startY + 1
                        set_cellv(next, _tileset.find_tile_by_name(name))
                    if newY == 0:
                        next = Vector2(startX,startY)
                        set_cellv(next, _tileset.find_tile_by_name(name))
                    newX = newX - 1
                    startX = startX - 1
                elif newX < 0:
                    while (newY != 0):
                        if newY > 0:
                            next = Vector2(startX,startY)
                            newY = newY - 1
                            startY = startY - 1
                        elif newY < 0:
                            next = Vector2(startX,startY)
                            newY = newY + 1
                            startY = startY + 1
                        set_cellv(next, _tileset.find_tile_by_name(name))
                    if newY == 0:
                        next = Vector2(startX,startY)
                        set_cellv(next, _tileset.find_tile_by_name(name))
                    newX = newX + 1
                    startX = startX + 1
            if newX == 0:
                var newY = dragStart.y - tile_pos.y
                var startY = dragStart.y
                while (newY != 0):
                    if newY > 0:
                        next = Vector2(startX,startY)
                        newY = newY - 1
                        startY = startY - 1
                    elif newY < 0:
                        next = Vector2(startX,startY)
                        newY = newY + 1
                        startY = startY + 1
                    set_cellv(next, _tileset.find_tile_by_name(name))
                if newY == 0:
                    next = Vector2(startX,startY)
                    set_cellv(next, _tileset.find_tile_by_name(name))
            dragStart = Vector2(-1,-1)
            #set_cellv(next, _tileset.find_tile_by_name(name))
    else:
        dragStart = Vector2(-1,-1)

```

This code will let you left-click and drag across the tilemap, filling each cell with a tile from the tile set, then changing the tiles in all of the cells to another tile when the button is released. Works great from what I can see, but if anyone has some pointers to improve performance or clean up my code, please share!
> 1 votes

---
Tags: godot
---


# Question
Title: Optimizing spawning 500 objects every 3 seconds
Using Object Pooling, assuming I'll like to spawn 500 cubes once every three seconds. How do I make it performance friendly? I need ideas, not the code itself.

# Answer
in unity basically pooling means: instead of using `Instatntiate()` that makes new object in the scene that takes cpu performance to allocate, make all of needed object on the start of the scene and only enable and disable them and only make new object when all of you instantiated objects are active and are not ready to reuse.

you can use a `foreach` or `for` loop to look for in-active object to use it on a list but its not much performant. using a static array is much more performant than a list. as i searched on unity its best to use queue to make pooling. just en-queue an object that is ready to use and de-queue when it gets active.

just check this *brackes* link to check how its used:

https://www.youtube.com/watch?v=tdSmKaJvCoA
> 0 votes

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


# Question
Title: body_entered signal won't emit when rigidbody collided to rigidbody
I have multiple rigidbody object floating away in the space. When they hit each other, they push away each. I want to destroy object if they hit something, but connect body\_entered signal won't invoked when they impact each other:

```
func _ready():
    connect("body_entered", self, "destroy")

func destroy(body):
    print("HIT!")
    queue_free()

```

How do I check Rigidbody hit something?

# Answer
> 1 votes
By default, a `RigidBody` will not emit a signal when it collides with another `RigidBody`. This is usually a good thing, as `RigidBodies` may collide frequently, and could fire many signals that you don't care about, negatively impacting performance.

If you *do* care about detecting `RigidBody` collisions, you should set `RigidBody.contact_monitor` to `true` and `RigidBody.contacts_reported` to a value greater than `0`.

From the docs on `contact_monitor`:

> If true, the RigidBody will emit signals when it collides with another RigidBody.

---
Tags: collision-detection, rigidbody, godot, hit
---


# Question
Title: Disconnect signal that connected from script
I connected signal when a scene is instantiated.

```
# AsteroidSpawner.gd
func spawn_asteroid():
    var asteroid_instance = asteroid_scene.instance()
    asteroid_instance.connect("destroy", self, "handle_asteroid_destroy")
    add_child(asteroid_instance)
func handle_asteroid_destroy():
    ... # TO SOME STUFFS WHEN ASTEROID DESTROYED...
    ... # How to disconnect this handler from here?

```

But the problem is, I want to disconnect handle\_asteroid\_destroy handler when object destroyed(or will destroy, use queue\_free). How do I disconnect signal on specific object? Is Godot Engine will free the handler automatically?

# Answer
You do not have to worry about disconnecting a signal when an object is destroyed -- the engine will handle that for you. See the connect docs:

> If the target is destroyed in the game’s lifecycle, the connection will be lost.

You can also use `CONNECT_ONESHOT` to ensure that a signal is disconnected after firing once, though it is not necessary in this situation.
> 2 votes

---
Tags: events, godot
---


# Question
Title: Is there a way to customize the Game-view Editor GUI?
I need to add a simple slider like scale slider in Game-view to change the timescale because I usually test my games by changing timescale.

# Answer
> 3 votes
Simple answer would be no, you can't. This is done in this internal class (In the 'DoToolbarGUI' private method to be precise), meaning you can't just overwrite it easily. See also this question if you still want to try to do that.

The best alternative that I can come up with, is a custom editor window that you can dock somewhere on a fixed place below the Game window or hierarchy window, so you can alter this setting (And perhaps other settings) from there like so:

```
public class ExampleWindow : EditorWindow
{
    public ExampleWindow()
    {
        minSize = new Vector2(100, 16);
    }

    [MenuItem("Window/ExampleWindow")]
    public static void ShowWindow()
    {
        GetWindow(typeof(ExampleWindow));
    }

    void OnGUI()
    {
        Time.timeScale = EditorGUILayout.Slider("Speed", Time.timeScale, 1, 10, GUILayout.ExpandWidth(false));
    }
}

```

If the window above is docked below the Game window, it would look like this:

---

EDIT

By looking a bit more at my custom window, I found a way to get it to look exactly like you want it to, it is however a bit cheating, as I'm just setting the position of my custom window on top of that bar basically...

```
public class ExampleWindow : EditorWindow
{
    private static ExampleWindow _instance;

    public ExampleWindow()
    {
        _instance = this;
        minSize = new Vector2(100, 16);
    }

    [MenuItem("Window/SettingsWindow")]
    public static void ShowWindow()
    {
        if (_instance == null)
        {
            ExampleWindow window = ScriptableObject.CreateInstance<ExampleWindow>();
            window.ShowPopup();
        }
        else
        {
            _instance.Close(); // Close existing window instead of opening it
        }
    }

    private void Update()
    {
        System.Type T = System.Type.GetType("UnityEditor.GameView,UnityEditor");

        var window = EditorWindow.focusedWindow;
        if (window?.GetType() == T)
        {
            Rect gameRect = window.position;

            // Set our position to the free space of the toolbar, you might need to alter this to be more exact as I just made some quick hardcoded guess here.
            float leftOffset = 500;
            float rightOffset = 315;
            float width = gameRect.width - leftOffset - rightOffset;

            position = new Rect(gameRect.x + leftOffset, gameRect.y + 19, width, 16);
        }

        //Close(); // Uncomment to force close all open windows (Don't forget to re-comment after they are closed)
    }

    void OnGUI()
    {
        GUILayout.BeginHorizontal(EditorStyles.toolbar);
        Time.timeScale = EditorGUILayout.Slider("Speed", Time.timeScale, 1, 10);
        GUILayout.EndHorizontal();
    }
}

```

After you initially open this window, click the game view to automatically move it into the correct place. Same applies when you resize the game view. The reason you need to do this is because I can't find a way to get a reference to the GameView without opening it. Meaning I can only get it by checking if the focussed window is the gameview.

Result looks like this for me:

# Answer
> 2 votes
I made a custom toolbar. I uploaded it in my github

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


# Question
Title: Is there a way to set a shader define in Löve?
I know I can use shader:send() to change variables, but is there a way to set/change a #define?

# Answer
> 1 votes
Shaders don't really work that way. Once the shader is compiled, any instance of the name you defined will be replaced with its value. If you want something that changes throughout your program, use a variable.

# Answer
> 1 votes
No, there is no way to do that. However, you can prepend a `#define` macro to the shader code when creating the shader.

---
Tags: shaders, love2d
---


title: Derivatives usage in FBM core

text:
# Question
Title: Derivatives usage in FBM core
So I learned now about derivatives and fbm, but can not figure out the effect of this code example (credits https://www.iquilezles.org/www/articles/morenoise/morenoise.htm, bottom of page):

```
const mat2 m = mat2(0.8,-0.6,0.6,0.8);

float terrain( in vec2 p )
{
    float a = 0.0;
    float b = 1.0;
    vec2  d = vec2(0.0);
    for( int i=0; i<15; i++ )
    {
        vec3 n=noised(p);
        d +=n.yz;
        a +=b*n.x/(1.0+dot(d,d));
        b *=0.5;
        p=m*p*2.0;
    }
    return a;
    }

```

What effect does `(1.0+dot(d,d))`? As the slope is more `/` it flattens the fbm sum?

# Answer
You can just play with the code to get a feel for how this term affects the output.

Here I've made a Shadertoy using a piece of Inigo Quilez's code with two extra parameters added to the terrain function:

```
float terrainH( in vec2 x, int o, float e)
{
    vec2  p = x*0.003/SC;
    float a = 0.0;
    float b = 1.0;
    vec2  d = vec2(0.0);

    for( int i=0; i<o; i++ )
    {
        vec3 n = noised(p);
        d += n.yz;
        a += b*n.x/(1.0+e*dot(d,d));
        b *= 0.5;
        p = m2*p*2.0;
    }

    return SC*a;
}

```
* `o` controls how many octaves of noise we sum.

You can click & drag left and right to vary this parameter, from one octave at the left, to 7 at the right.
* `e` controls how much we apply the pseudo-erosion factor.

You can click & drag up and down to vary this parameter. At the bottom, when `e` is zero, we apply no erosion, just vanilla fbm. At the top, when `e` is 1, it's the same as Inigo's original.

Taking a look at a cross section through the resulting heightmap, here's what it looks like as we play with it:

You can see that this pseudo-erosion term makes the terrain sink down wherever there's a steep slope - as though water and landslides running down the incline carved away some of its material, leaving little mounds in the valleys.

It also changes the character of the curves. The interpolation between grid points gives the base noise a symmetric sigmoid shape, and both the terrain under the curve and the empty sky above keep a similar-looking profile as we add octaves (you could flip the image over to exchange land and sky and the terrain would look roughly the same). But as we erode, the high parts of the terrain fall faster because they lose more to division even with the same denominator, leading to sharper peaks and steeper cliffs, slumping down into more gradual valleys, breaking the symmetry between land & sky.

It's most noticeable in the first octave, since its amplitude dominates the rest, but it applies fractally at all scales.
> 2 votes

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


# Question
Title: FBM alteration based on derivative and noise value
I'm still working on my procedural terrain generation and kind of sniffing ideas from Sean Murray (No Man's Sky programmer). So I watched this GDC17 presentation, but some things just don't make sense to me:

> # Amplitude Damping
>
> ```
> lfSum += lfDampedAmplitude * lfFeatureNoise * (1.0f /
> (1.0f + dot(lSlopeErosionDerivativeSum, lSlopeErosionDerivativeSum)));
>
> lfAmplitude *= lerp(lfCurrentGain, lfCurrentGain
>              * smoothstep(0.0f, 1.0f, lfSum), lfAltitudeErosion);
>
> lfDampedAmplitude = lfAmplitude * (1.0f - (lfRidgeErosion /
> (1.0f + dot(lRidgeErosionDerivativeSum, lRidgeErosionDerivativeSum))));
>
> ```

Altering amplitude based on `currentGain` AND noise value? This just makes all heights (large noise values like 1) do no alteration and the small ones to make the amplitude really tiny. How does that represent Altitude Erosion?

The audio also doesn't help much, as he isn't going into code detail.

Any ideas to makes sense out of this?

# Answer
This sounds like a technique similar to the one Giliam de Carpentier describes in his "Swiss Turbulence" example in this article:

> Normally, lots of material on the surface of mountains gets displaced from the peaks to the valleys over time, carving gulleys on its slopes and smoothing the valleys below.
>
> ...
>
> To smoothen the valleys, the algorithm also uses an \[amplitude update\] calculation that is slightly different from the original turbulence function. Here, the \[amplitude\] is not only multiplied by gain for each octave, but also by the (clamped version of the) intermediate values of the sum of the noise octaves. **This causes the amplitude for finer details to fade out quickly near valleys, but remain quite potent near peaks**. To compensate for the on-average decrease in amplitude, the gain parameter should be a bit larger than ‘normal’ (for example, 0.6 instead of 0.5).

Does that idea of attenuating amplitude more aggressively in low-lying zones to smooth them, while allowing higher-altitude regions to stay more bumpy, help answer your question?
> 2 votes

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


# Question
Title: Changing node's translation affects to sibling node
I have a node which looks like this tree:

FPSController (Root node, and it's KinematicBody)

* CollisionShape
* Camera
* GroundCheckRayCast

When I moved CollisionShape's location down, camera also going down together. There's no code that change Camera's translation, but why this kind of thing happens?

Another weird thing is that y position of Camera won't changed even it's clearly moved down.

Is this some kind of bug or something? Why Camera's y position was changed, also not updated it's own y position value?

Using Godot 3.1.1 and reproduced repo: https://github.com/rico345100/godot-glitch-reproduction

# Answer
Solved. This caused because when height of CollisionShape was changed, KinematicBody responded and overall height was reduced and that's why my camera was moved.
> 1 votes

---
Tags: transformation, godot
---


title: How to pass renderer through classes?

text:
# Question
Title: How to pass renderer through classes?
I am making a game with SDL and C++. I am trying to render simple image to the screen but I can't. **I am not getting any error** but I see only black screen.

I think because the renderer in `player` is not the same in `game` they do not have the same memory address.

\**my question \**: is how to pass the renderer?

I have tried passing it through `init()` in `player` directly but it didn't work then.

**game.h**

```
#ifndef GAME_H
#define GAME_H

#include <SDL2/SDL.h>
#include <iostream>

using namespace std;

class game
{
public:

    game();
    ~game();

    void init(char *title,int xpos, int ypos ,int xsize ,int ysize ,bool fullscreen);
    void loop();
    void input();
    void update();
    void render();
    SDL_Renderer* renderer;
    SDL_Window* window;

private:

    const int target_Fps = 60;
    const float TFEF = 1000/60; // time for each frame
    int delta;
    long int start_time;
    bool isrunning = true;
    int fps_counter = 0;
    unsigned int counter = 1;
};

#endif

```

**game.cpp**

```

#include "game.h"
#include "player.h"

player* pla;

game::game()
{
    cout << "something"<<endl;
    if (SDL_Init(SDL_INIT_EVERYTHING) == 0)
    {
        cout << "another thing" << endl;
        init("game",10,15,500,500,false);
    }

    loop();
}

game::~game()
{
}

void game::init(char *title,int xpos, int ypos ,int xsize ,int ysize ,bool fullscreen)
{
    window = SDL_CreateWindow(title, xpos,  ypos , xsize , ysize , fullscreen);
    renderer = SDL_CreateRenderer(window,-1,0);
    //SDL_SetRenderDrawColor(renderer, 0, 0,0, 255);
    SDL_RenderClear(renderer);
    SDL_RenderPresent(renderer);

    cout << "another another something" << endl;

    pla = new player(renderer,32,32);
    pla->init();

    //SDL_Texture* tex = IMG_LoadTexture(renderer,"res/pss.png");
}

void game::loop()
{
    while(isrunning)
    {
        start_time = SDL_GetTicks();

        input();
        update();
        render();

        delta = SDL_GetTicks() - start_time;
        if (delta < TFEF)
            SDL_Delay(TFEF - delta);

        fps_counter++;

        if (start_time >= 1000 * counter)
        {
            //cout <<"the FPS is : "<< fps_counter << endl;
            counter++;
            fps_counter = 0;
        }
    }
}

void game::input()
{
    SDL_Event e;
    SDL_PollEvent(&e);
    if (e.type == SDL_QUIT)
        SDL_Quit();
}

void game::update(){}

void game::render()
{
    SDL_RenderClear(renderer);
    pla->render(renderer);
    SDL_RenderPresent(renderer);
}

gameobject::~gameobject(){};

```

**player.h**

```

#ifndef PLAYER_H
#define PLAYER_H

#include "gameobject.h"

class gameobject;

class player : public gameobject
{
public:

    void init() override;
    void tick() override;
    void render(SDL_Renderer* renderer) override;
    SDL_Renderer* renderer;
    player(SDL_Renderer* renderer,int pwidth,int pheight);
private:

    ~player() override;
    SDL_Texture* playertex;
};

#endif // PLAYER_H

```

**player.cpp**

```

#include "player.h"

player::player(SDL_Renderer* renderer,int pwidth, int pheight)
{
   this->pos.w = pwidth;
   this->pos.h = pheight;
   this->pos.x = 0;
   this->pos.y = 0;

   this->renderer = renderer;
}

void player::init()
{
    this->playertex= IMG_LoadTexture(renderer,"res/pss.png");
    cout<<"int in player \n"<<endl;

    crop.x = 0;
    crop.y = 0;
    crop.w = 32;
    crop.h = 32;

    cout<<"pos x :"<<this->pos.x<<endl;
    cout<<"pos y : "<<this->pos.y<<endl;
    cout<<"pos w : "<<this->pos.w<<endl;
    cout<<"pos h : "<<this->pos.h<<endl;
    cout<<"crop x :"<<this->crop.x<<endl;
    cout<<"crop y :"<<this->crop.y<<endl;
    cout<<"crop w :"<<this->crop.w<<endl;
    cout<<"crop h : "<<this->crop.h<<endl;
}

void player::tick()
{
}

void player::render(SDL_Renderer *renderer)
{
/*
    cout<<"pos x :"<<this->pos.x<<endl;
    cout<<"pos y : "<<this->pos.y<<endl;
    cout<<"pos w : "<<this->pos.w<<endl;
    cout<<"pos h : "<<this->pos.h<<endl;
    cout<<"crop x :"<<this->crop.x<<endl;
    cout<<"crop y :"<<this->crop.y<<endl;
    cout<<"crop w :"<<this->crop.w<<endl;
    cout<<"crop h : "<<this->crop.h<<endl;
*/
    SDL_RenderCopy(renderer,playertex,&crop,&pos);
}

player::~player(){};

```

# Answer
> 0 votes
You should look at C++ language concepts, such as passing by reference, address, and value.

If I have a class, Foo, and another, Bar:

```
class Bar
{
public:
    int num;
};

class Foo
{
public:
    void doSomethingV(Bar bar);
    void doSomethingR(Bar& bar);
    void doSomethingA(Bar* bar);
};

```

Look at the `doSomething*` member functions: the first one passes the object *by value*, which means inside the function, a copy (new instance) is made of the Bar object. Typically we do not do this.

The second version is passing *by reference*. This is basically a pointer, but it has the extra safety of not allowing null values:

```
foo.doSomethingR(NULL); //generates a compiler error
foo.doSomethingR(bar); //works, as long as bar is an instance of an object(not pointer)

```

Do this when you can. Function definitions can treat the variable as an instance of an object instead of a pointer, but what really gets passed is the address of the object.

The final version, is passing *by address*, or pointer. As above, the calling convention is as follows:

```
foo.doSomethingA(NULL); //valid
foo.soSomethingA(&bar); //valid. '&' means "address of"

```

Use this when you have to.

Now to your case:

If you wish to *store* a copy of the renderer, then pass by value, or reference. Preferably reference.

If you wish to *use* the renderer, pass by reference only.

If you wish to store the address of the renderer, pass by pointer, or reference;

If you pass by pointer, your storing class must have a pointer member variable to receive the address like `Renderer* m_renderer;` which is then assigned like so:

```
player::player(SDL_Renderer* renderer,int pwidth, int pheight)
{
    pos.w = pwidth;
    pos.h = pheight;
    pos.x = 0;
    pos.y = 0;
    m_renderer = renderer;
}

```

If you pass by reference:

```
player::player(SDL_Renderer& renderer,int pwidth, int pheight)
{
    pos.w = pwidth;
    pos.h = pheight;
    pos.x = 0;
    pos.y = 0;
    m_renderer = &renderer;
}

```

Also, as a side note: the keyword `this` is only necessary when the argument name is the same as the member variable, which is whilst syntactically correct, considered poor practice. See my examples above for a better way to do it. Another use for `this` is when a class instance wishes to pass itself as an argument, like so:

```
Bar::doSomething(Foo& foo)
{
    foo.doSomethingA(this); //passes itself by pointer
    foo.doSomethingR(*this); //pass itself by reference.
    // '*' is opposite of '&' operator and is called de-referencing a pointer
}

```

---
Tags: c++, rendering, sdl2, oop
---


title: Unity Error importing any video clip

text:
# Question
Title: Unity Error importing any video clip
When I try to import a video file to play in a VideoPlayer component, I get the following errors in the Console:

```
WindowsVideoMedia error 0xc00d5212 while reading C:/Users/Jonas/OneDrive/Projects/Project1/Assets/Videos/output.mp4

Context: Setting media type for first video stream
Error details: No suitable transform was found to encode or decode the content.
Track types:
   Audio Track, type: U
UnityEngine.GUIUtility:ProcessEvent(Int32, IntPtr)
-----------------------------------------------------------
Error while reading movie: C:/Users/Jonas/OneDrive/Projects/Project1/Assets/Videos/output.mp4
UnityEditorInternal.InternalEditorUtility:ProjectWindowDrag(HierarchyProperty, Boolean)
UnityEngine.GUIUtility:ProcessEvent(Int32, IntPtr)
-----------------------------------------------------------
VideoClip import error for Assets/Videos/output.mp4
UnityEditorInternal.InternalEditorUtility:ProjectWindowDrag(HierarchyProperty, Boolean)
UnityEngine.GUIUtility:ProcessEvent(Int32, IntPtr)
-----------------------------------------------------------
WindowsVideoMedia error 0xc00d5212 while reading C:/Users/Jonas/OneDrive/Projects/Project1/Assets/Videos/output.mp4

Context: Setting media type for first video stream
Error details: No suitable transform was found to encode or decode the content.
Track types:
   Audio Track, type:
UnityEngine.GUIUtility:ProcessEvent(Int32, IntPtr)

```

The video file is just an ordinary H.264/AAC MPEG-4 video file transcoded using ffmpeg. But I also tried the same format and H.264/AAC QuickTime MOV (both rendered from Blender) and AVI (JPEG) from Blender as well.

**System Details:**

* Unity 2018.4.12f1 (LTS) Personal
* Build target: Android (Minimum API Level 25)
* Windows 7 Home Premium 64 Bit (SP1)
* Blender 2.80
* ffmpeg version N-85588-g6108805

---

<sup>*I tried to post this to the Unity Forums before, but as of writing this, the thread has yet to be greenlighted by moderation, so I might as well try posting it here, as you usally get an answer much more quickly*</sup>

# Answer
Depending on where you are playing the video from, either local or from a url. You have to set the video player to the clip. The paths change depending on what platform you build to so if you want android then you would get the file from streaming assets path

```
#if !UNITY_EDITOR && UNITY_ANDROID
            url = Application.streamingAssetsPath + "/" + "VideoName.mp4";
        #endif

```

to just quickly check if your video will work, which it should no problem then you can

```
 public VideoClip vidClip;//drag or dynamically set your clip

```

and then you would set the clip

```
if (VideoSource == VideoSource.VideoClip)
    {
        player.source = VideoSource.VideoClip;
        player.clip = vidClip;
    }

```

also note that you normally want to use this inside a Coroutine. then for the rest to work properly you can prepare the player and set the audio.

```
    player.audioOutputMode = VideoAudioOutputMode.AudioSource;
    player.EnableAudioTrack(0, true);
    player.SetTargetAudioSource(0, audio);

    player.Prepare();
    WaitForSeconds waitTime = new WaitForSeconds(5);
    while (!player.isPrepared)
    {
        yield return waitTime; break;
    }
    image.texture = player.texture;
    player.Play();

    audio.Play();
    while (player.isPlaying)
    {
        yield return null;
    }

```

Update :

1-updating the adapter- if the files playable in windows media then that error should disappear.

2-Changing the default media player on the machine. Then importing the clip should work without error.
> 1 votes

---
Tags: unity, video
---


# Question
Title: How can I adjust the direction of my rigidobody.velocity without stuttering?
Stuttery movement has been plaguing me for the whole development of this project.

Some info on the game:

* It's a 2D, top-down space game, and you control a spaceship that can accelerate or rotate.
* If the ship isn't accelerating, rotation simply rotates the ship.
* If the ship *is* moving, rotation also happens on the rigidbody's velocity, so that you're moving in the direction you're accelerating (like in racing games when you aren't drifting).

To get simple, unmoving rotation to work smoothly, I'm using `rb.MoveRotation(rb.rotation + angle)` (`rb` references the RB2D component). Doing this with Transform instead causes jitter.

For when accelerating, I'm modifying the `rb.velocity`'s direction manually, as I could find no other way to do this.

The code is called from `FixedUpdate()`. Here's what it looks like:

```
public void Rotate(float axis, bool isAccelerating) {
    if (isAccelerating) {
        float angle = (rotationSpeed) * axis * (-1);
        rb.velocity = Vector2.Lerp(rb.velocity, Quaternion.Euler(0f, 0f, angle) * rb.velocity, (1f - smoothness) * Time.deltaTime * sm);
        transform.up = Vector3.Lerp(transform.up, Quaternion.Euler(0f, 0f, angle) * transform.up, (1f - smoothness) * Time.deltaTime * sm);
    } else {
        float angle = (rotationSpeed) * axis * (-1);
        rb.MoveRotation(rb.rotation + angle);
    }
}

```

As you can see, I tried everything to get the latter smooth. First, I tried simple lerping it. When that made the stutter *worse*, I tried multiplying the value by Time.deltaTime (and another multiplier, `sm` — for smoothness multiplier — to speed it up). That didn't help either.

For my camera, I'm using Cinemachin's 2D virtual camera (using Framing Transposer). I made sure to check that it's not the camera causing the stutter; it isn't.

I took a couple videos so that you can see the problem better. I turned the time scale down to 0.3 so it can be seen better on video, but it's there on normal speed, as well.

Here's the whole CharacterController2D.cs, or the relevant parts at least. (There's a variable, `molasses` and its corresponding `_molasses`, which is an artifact from old code. Its purpose was to slow down the ship's rotation speed when accelerating, but I've since changed the logic to rotate `rb.velocity` also, so you can safely ignore it.)

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

[RequireComponent(typeof(Rigidbody2D))]
public class CharacterController2D : MonoBehaviour {
    // "public" fields
    [Header("Rotation\n")]
    [SerializeField] private float rotationSpeed = 10f;
    [SerializeField] private float molasses = 2f;
    [SerializeField] private AnimationCurve catchUp;
    [Header("Acceleration\n")]
    [SerializeField] private float acceleration = 40f;
    [SerializeField] private float topSpeed = 30f;
    [SerializeField] private float boostForce = 100f;
    [SerializeField] private float rollDistance = 5f;
    [SerializeField] private float rollDuration = 0.25f;
    [Range(0f, 1f)] public float smoothness;
    public float sm;

    // private fields
    private float axis;
    private float _molasses;

    // references
    public Rigidbody2D rb; // exposed for debugging; change to private later

    private void Start() {
        // caching references
        rb = GetComponent<Rigidbody2D>();
    }

    public void Rotate(float axis, bool isAccelerating) {
        if (isAccelerating) {
            float angle = (rotationSpeed / _molasses) * axis * (-1);
            rb.velocity = Vector2.Lerp(rb.velocity, Quaternion.Euler(0f, 0f, angle) * rb.velocity, (1f - smoothness) * Time.deltaTime * sm);
            transform.up = Vector3.Lerp(transform.up, Quaternion.Euler(0f, 0f, angle) * transform.up, (1f - smoothness) * Time.deltaTime * sm);
        } else {
            float angle = (rotationSpeed / _molasses) * axis * (-1);
            rb.MoveRotation(rb.rotation + angle);
        }
    }

    public void Accelerate() {
        rb.AddForce(transform.up * acceleration / _molasses);
    }

    public void LimitSpeed() {
        if (rb.velocity.magnitude > topSpeed)
            rb.velocity = rb.velocity.normalized * topSpeed;
    }

    public void Boost() {
        rb.AddForce(transform.up * boostForce, ForceMode2D.Impulse);
    }

    public void SetMolassesActive(bool isActive) {
        if (isActive)
            _molasses = molasses;
        else
            _molasses = 1f;
    }
}

```

And here's PlayerMovement.cs, which calls the methods. Again, relevant parts to slim it down.

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

[RequireComponent(typeof(CharacterController2D))]
public class PlayerMovement : MonoBehaviour {
    // references
    private CharacterController2D cc;

    //private fields
    private float axis;
    private bool fired1;
    private bool shouldSpin;

    private void Start() {
        cc = GetComponent<CharacterController2D>();
        particles.Stop();
    }

    private void Update() {
        // updating fields
        axis = Input.GetAxis("Horizontal");
        fired1 = Input.GetButton("Fire1");

        if (Input.GetKeyDown(KeyCode.Space))
            cc.Boost();
    }

    private void FixedUpdate() {
        if (fired1 && Mathf.Abs(axis) > 0) {
            cc.SetMolassesActive(true); // ignore this
            cc.Rotate(axis, true);
        } else if (Mathf.Abs(axis) > 0) {
            cc.Rotate(axis, false);
        }

        if (shouldSpin)
            cc.Rotate(1f, false);

        if (fired1) {
            cc.Accelerate();
        }

        cc.SetMolassesActive(false); // and this

        cc.LimitSpeed();
    }
}

```

Finally, here's my .gitignore-d Unity project: https://we.tl/t-3F6IhPHHzY. It's 5 MB.

**To re-iterate the problem:** `rb.MoveRotation()` is the only way I've found that smoothly rotates my player game object, but it's not enough for my 2nd logic case, because I need to adjust my `rb.velocity` to follow. But simply adjusting it, or even lerping it, causes stuttering. How can I fix this?

# Answer
> 2 votes
## Answer

I figured it out: there's absolutely nothing wrong with changing the direction of your rigidbody's velocity.

The problem was using `transform.up` to rotate the game object itself. I replaced that with `rb.MoveRotation(rb.rotation + angle)` and it's buttery smooth now.

---

## Takeaway

In general, if there's anything I've learned from this project, it's that everyone should learn the ins and outs of their game engine of choice. If I had better understood how Unity and its physics engine work under the hood, many of the problems I encountered with jittery movement could've been avoided altogether.

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


# Question
Title: Stop current animation and re-play immediately?
When the player hit something, I'm playing hit animation from animation\_player. However when player hit something while hit animation is playing, it just ignored and play previous hit animation.

I need to stop the animation, but couldn't find any related information. How do I stop the animation and play again immediately?

# Answer
> 1 votes
> it just ignored and play previous hit animation

I'm assuming you mean that the animation continues playing from its current position rather than resetting to the beginning.

> How do I stop the animation and play again immediately?

By stopping it and playing it again:

```
animation_player.stop()
animation_player.play("my_animation")

```

The docs on `stop` say:

> Stops the currently playing animation. If reset is true, the animation position is reset to 0 and the playback speed is reset to 1.0. If reset is false, then calling play without arguments or play("same\_as\_before") will resume the animation.

As `reset` defaults to `false`, calling `stop()` is sufficient.

---
Tags: animation, godot
---


# Question
Title: How to load large arrays to gpu and render with OpenGL?
I am trying to make a volumetric rendering of a cloud. I have been defining the cloud density functions on the glsl shaders and performing ray-marching methods successfully. But now I would like to render a 3D grid (100x100x100) representing the density of a cloud that I calculated using the cpu. The idea that I was trying was to make use of the storage buffer objects, but when I access the array to get the density value and render it, it doesn't work.

This is at the beginning of the glsl fragment:

```
#version 440 core
layout(std430, binding = 3) buffer layoutName
{
    float data_SSBO[100*100*100];
};

```

And the density function definition is:

```
float density(vec3 position, float t){
    const float dx = 1./100., dy = 1./100., dz = 1./100.;
    int i, j, k;
    if( (position.x >= 0.)&&(position.y >= 0.)&&(position.z >= 0.)&&(position.x <= 1.)&&(position.y <= 1.)&&(position.z <= 1.)){
        i = int(position.x/dx);
        j = int(position.y/dy);
        k = int(position.z/dz);

        return data_SSBO[i*100*100 + j*100 + k];
    }
    else
        return 0.;
}

```

And in the c code there are the buffer creation, bindings, etc:

```
    glGenBuffers(1, &ssbo);
    glBindBuffer(GL_SHADER_STORAGE_BUFFER, ssbo);
    glBufferData(GL_SHADER_STORAGE_BUFFER, 100*100*100*sizeof(float), grid, GL_STATIC_DRAW);
    glBufferSubData(GL_ARRAY_BUFFER, 0, 100*100*100*sizeof(float), grid);

```

and in the rendering function there is:

```
    glClearColor(1.f, 1.f, 0.f, 1.0f);

    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    glBindBuffer(GL_ARRAY_BUFFER, VBO);

    glBindBuffer(GL_SHADER_STORAGE_BUFFER, ssbo);

    glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 3, ssbo);

//  glBufferSubData(GL_ARRAY_BUFFER, 0, 3*2*2*sizeof(float), buffer);

    glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 2* sizeof(float), (void*)0);      // coordenadas

    glEnableVertexAttribArray(0);

    glUseProgram(shaderProgram);

```

I believe the problem has to do with the binding, I have been trying different combinations, like binding after and before glUseProgram, etc. I literally have no idea what is wrong, I see this is really confusing.

# Answer
> 1 votes
A 3D texture will suit this use case much better, and it can be set up to automatically handle clamping for you rather than requiring conditions.

You're using GLSL version 440, which means OpenGL 4.4+, so you have support for everything that is required:

---
Tags: opengl, rendering, glsl
---


# Question
Title: How to use GameManager to get GameOver() from another script?
I'm trying to make a gameover-text show when the player is leaving the plane-area. In GameManager.cs I've written:

```
public void GameOver()
{
    gameOverText.gameObject.SetActive(true);
}

```

And in PlayerController.cs I've used the following code:

```
private GameManager gameManager;

```

and:

```
void Update()
{
    float horizontalInput = Input.GetAxis("Horizontal");
    float verticalInput = Input.GetAxis("Vertical");

    playerRb.AddForce(Vector3.right * speed * horizontalInput);
    playerRb.AddForce(Vector3.forward * speed * verticalInput);

    if (transform.position.y < -4)
    {
        gameManager.GameOver();
    }
}

```

But this doesn't really work, and the console is giving me this message:

> Assets/Scripts/PlayerController.cs(8,25): warning CS0649: Field 'PlayerController.gameManager' is never assigned to, and will always have its default value null

I've already used the `OnTriggerEnter` (for powerups) and `OnCollisionEnter` (for enemies). How can I get the GameOver-text to show when the player leaves the "Plane"?

# Answer
> 0 votes
*TLDR:* Add the `SerializeField` attribute to the `GameManager` variable in the `PlayerController`, then reference the desired `GameManager` instance through the inspector.

---

In the `PlayerController` class you have included a variable of the type `GameManager`, but you have not populated the variable with any instance of `GameManager`.

Populating variables and referencing can be achieved in a variety of ways, but one simple method I like in Unity is to use the inspector to manually populate variables. Here is one example of how to populate this variable with a reference to the specific instance of `GameManager`, through the inspector via the `SerializeField` attribute.

In `PlayerController` class:

```
[SerializeField] //added this attibute which will affect the `gameManager` variable
private GameManager gameManager;

```

By adding the `SerializeField` attribute the variable will be visible in the inspector, even though normally only public variables are shown in inspector. You can then drag the `GameManager` instance in your scene into this serialized variable on the `PlayerController`. Now when your scene starts up it will actually have a reference to a specific instance on the `GameManager` class, so it should be able to call functions etc.

---

edit: Note that the `SerializeField` attribute only works for certain types, I am assuming that your `GameManager` inherits from `Unity.Object` (or one of its children like `GameObject`, `Component`, etc). For more details on serialization through this attribute, check out the official docs for SerializeField

# Answer
> 1 votes
In a case like this you would either want to make that a `public GameManager gameManager` or add a `[SerializeField]`above the variable and simply drag it to the slot to set it.

If you would like to keep it private you could either use a `Gameobject.Find();` or something like `FindObjectOfType()` to set that manager in `Start()`

After assigning your manager when you call `gameManager.GameOver()` you will no longer have a null value.

# Answer
> 0 votes
Some developers hate singletons, but the canonical answer is to make a single long-lived class instance into a singleton, so there is one instance which can be accessed from any other script.

```
public class GameManager : MonoBehaviour
{
    public static GameManager Instance { get; private set; }

    void Awake()
    {
        Instance = this;
    }
}

```

Then any other script can call its public methods as so:

```
GameManager.Instance.DoSomething();

```

To simplify this logic so other classes can be singletons easily, use the following helper (this interesting inheritance pattern is called the curiously recurring template pattern):

```
public abstract class Singleton<T> : MonoBehaviour where T : Singleton<T> // or where T : MonoBehaviour, depending on which types of subclass you need
{
    public static T Instance { get; private set; }

    protected void Awake()
    {
        Instance = (T)this;
    }
}

public class GameManager : Singleton<GameManager>
{
    protected new void Awake()
    {
        base.Awake();
        // do other needed init
    }
}

```

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


# Question
Title: When I press play in my scene, the camera turns in the opposite direction?
In my scene, I have my character facing a certain direction, with a camera attached. Now, when I press play, for some reason, the character immediately faces the other way. I've tried turning the model and camera to face the opposite way of that, to make up for it, but it still faces that same direction.

I've had a look at the script for the camera, but I'm not sure what could be causing this to happen. There's no target assigned that should cause that reaction, as the camera is a child of the player.

Below is a copy of my script:

```
public class FirstPersonCamera : MonoBehaviour
{
    Vector2 mouseLook;
    Vector2 smoothV;
    public float sensitivity = 5.0f;
    public float smoothing = 2.0f;

    GameObject character;

    void Start()
    {
        character = transform.parent.gameObject;

        Debug.Log("Camera is operating");
    }

    void Update()
    {
        var md = new Vector2(Input.GetAxisRaw("Mouse X"), Input.GetAxisRaw("Mouse Y"));

        md = Vector2.Scale(md, new Vector2(sensitivity * smoothing, sensitivity * smoothing));
        smoothV.x = Mathf.Lerp(smoothV.x, md.x, 1f / smoothing);
        smoothV.y = Mathf.Lerp(smoothV.y, md.y, 1f / smoothing);
        mouseLook += smoothV;

        transform.localRotation = Quaternion.AngleAxis(-mouseLook.y, Vector3.right);
        character.transform.localRotation = Quaternion.AngleAxis(mouseLook.x, character.transform.up);

        Cursor.lockState = CursorLockMode.Locked;
        Cursor.visible = true;

        if (Input.GetKeyDown("escape"))
        {
            Cursor.lockState = CursorLockMode.Locked;
        }

    }

}

```

Does anyone see what could be causing this issue? I've using Unity version 2019.2

I'm also including screenshots of the player's position, as well as the camera's.

Player:

Camera:

There's something in the script that is causing the character to turn around, as I placed the script on another model and it had the same effect P:

# Answer
I figured out what it is (with the help of an amazing dev friend of mine)

This line, right here, was causing the issue:

```
 transform.localRotation = Quaternion.AngleAxis(-mouseLook.y, Vector3.right);
        character.transform.localRotation = Quaternion.AngleAxis(mouseLook.x, character.transform.up);

```

Now I've deleted it, it stops the rotation issue. Essentially those two lines of code were telling the model to face a specific direction on Start, and while the controls work fine aside from that spin/rotation, I didn't want the game to start with the player facing the wrong way.
> 0 votes

---
Tags: camera
---


# Question
Title: Is it worth planning to be cross-platform in mobile game development?
Disclaimer: my goal is not to use cross-platform frameworks like Unity.

I am currently planning a mobile game which I intend to first launch on iOS. However, I am wondering if it is better to write everything in Objective-C, thus locking the code into the platform, and to do a complete rewrite for other platforms (ie: Android). The other option would be to write the game logic in C or C++ and to only write the code that interfaces with each OS in the preferred language (Objective-C(++) or Java).

I understand that this must depend on the size of the code base, so what program size should mark the separation? Finally, if I write cross-platform code, should I stick to C (since Objective-C is a superset of C, making it easy to use C and to use the code samples and because the NDK and the JNI interfaces are more C oriented)? The only advantage I see with C++ in that case is the fact that it is object-oriented and thus it is easier to represent game entities).

# Answer
The "worth" of something can only be determined by you. For some people it isn't worth porting to android for the amount of time spent vs. sales.

That being said there's no reason to just use C++ for everything. Sure, the interfaces for certain things is C or Objective-C, but you can call both of those easily from C++.
> 6 votes

# Answer
I'm into XNA for Xbox360 development, and some of the developers that have written games for Xbox and PC in C# reported that porting to C++ and other platforms wasn't very hard at all.

Full portability is probably not a good idea, as the UI should be tied to the platform. This means you'll probably need to design specific UIs for iPad, iPhone and various Android devices.

The game logic on the other hand, can be written in such a way that it does not reference the OS directly, allowing to share the code among platforms, or at least make it painless to port between languages and platforms.

Finally, it's worth mentioning .net and C#, which are available on PC, Xbox 360, iPhone/iPad (mono touch), Android (mono for android), Windows Phone 7 and PlayStation Vita. That's quite a wide range of platforms.
> 2 votes

# Answer
You could rewrite everything for both platforms, but that would take a lot of time. Another option is, like you suggested, to write the OS dependent code in Objective-C and Java and then write the core of the app in C. If it is a little app, then the first option shouldn't be too much of a hassle, especially if you're just embedding a web page or something similar. But for larger apps (ex. 3d multiplayer games) the second option is better. You said you didn't want to use a cross-platform framework like Unity, but if you went with the second option you'd essentially be writing your own library. If your game requires a lot of OS specific things than this could be difficult to implement as well. And there are some frameworks which do almost exactly what you said (implement OS specific stuff then let you use C or C++ to write code) like MoSync.

As for C vs C++, if you really like C++ and can't stand to code in C, then it's worth using C++, but otherwise I'd say stick with C because it could be very difficult to use C++, though I don't know for sure. I'd look into using C++ with the NDK.
> 1 votes

# Answer
While this falls in line with some of the other answers, I'll make this case: Cross-platform development can mean not only two different platforms at the same time, but also the same platform at two different times.

By that, I mean that every line of code that depends on a platform/OS specific feature is one that will have to be rewritten should the exposed functionality of the platform be changed at a later date. If you keep your codebase platform agnostic, you only have to worry about updating the OS abstraction layer to accommodate new changes.
> 1 votes

# Answer
It definitely depends on your audience. You should figure out first who they are and what platforms are used by them and in what proportion. When thinking over this issue it's worth deciding on the geographic region, since the findings might differ not only within user groups but also for different locations. Next, you must reflect on the priorities for product growth and the resources available. Start working on several platforms from scratch at once might lead to uncertain results Thus, it's worth prioritizing based on the audience research. After releasing your prototype on one platform, it might be easier and safer to invest in other relevant platforms.
> 0 votes

# Answer
you definitely want to think cross platform. iOS may be most lucrative now but a lot of developers are now quietly moving to Android. if your game is successful, you will want to localize and release in other markets and, for example, Asia is more of an Android world.

There are platform independent toolkits, like Unity, so investigate those. You also have HTML5 as a possibility.

bottom line is this - if you are successful, you will want to go cross platform. If you are not, that could also be because you did not try all platforms. so better think cross platform right away :)
> -1 votes

---
Tags: android, ios, objective-c, cross-platform, mobile
---


# Question
Title: How do I create a single tile in Unity 2019+
I going through the "Ruby's Adventure: 2D Beginner" tutorial, chapter 4, section 3 with Unity 2019.11.

In the tutorial you create a folder for tiles and you are then supposed to right-click in the asset folder and select "Create \> Tile" from the menu. There's even a screenshot showing the menu where the option is right below the sprite sections. However, in version 2019.11 of unity, there is no such option :)

I checked the documentation, and for 2019.3 and 2020.1 the manual states that this should be possible via the assets menu (there's no docs for 2019.11 specifically), but my Unity editor doesn't have the option.

It seems unlikely that the option is just missing from my version, so I'm guessing something about my project setup is wrong. Is there anything special I need to set up to have the project support tiles?

***Edit:** I found the feature in the 2018 LTS version. I'm new to Unity, so maybe out of date documentation is the norm.*

# Answer
> 3 votes
The tutorial, "Ruby's Adventure: 2D Beginner" is a 3D project.

I restarted the tutorial and changed it to 2D using the menu "Edit -\> Project Settings... -\> Editor -\> Default Behavior Mode".

Next, I followed Cedric Degottex's suggestion in the comments for the tutorial by opening "Window \> Package Manager", and installing the "2D Sprite" and "2D Tilemap Editor" packages.

I'm leaving this here in case anyone else hits this relatively minor snag.

---
Tags: unity, tiles
---