# Question
Title: `Awake` with [ExecuteAlways] sometime is not called in edit-mode
I'm trying to use the `[ExecuteAlways]`attribute to have a singleton both in edit- and -play modes. But the `Awake()` method sometimes is not called in the edit-mode. What could be the reason for this and how to fix it?

---

To make a short story long, I've got a not-so-new Unity project that I believe was developed before the age of `ScriptableObject`s, so they used `MonoBehaviour` to store game settings. And they used a kind of *"Singleton"* pattern that was not very stable and sometimes caused artefacts, such as creating an extra instance in edit mode which could often be saved with the scene accidentally and caused some other problems. The "Singleton" was written this way:

```
private static GlobalSettings instance = null;

public static GlobalSettings Instance
{
    get {
        if (instance == null)
        {
            instance = (GlobalSettings)FindObjectOfType(typeof(GlobalSettings));
            if (instance == null)
                instance = (new GameObject("GlobalSettings")).AddComponent<GlobalSettings>();
        }
        return instance;
    }
}

```

to fix it I've changed the code (and added the `[ExecuteAlways]` attribute):

```
[ExecuteAlways]
public class GlobalSettings : MonoBehaviour
{
    private static GlobalSettings _instance;
    public static GlobalSettings Instance => _instance;

    private void Awake()
    {
        if (_instance)
        {
            Destroy(this);
            throw new GameException($"The '{nameof(GlobalSettings)}' is a singleton!");
        }

        _instance = this;
    }
}

```

as I said `Awake()` is not called sometimes in edit-mode and the `_instance` remains `null`. Another problem is that even when `Awake` is called it happens after the first call of `OnInspectorGUI()` where the game settings are needed.

Any suggestions and considerations on how to make this code work stable are welcome!

# Answer
I fixed it this way:

```
[ExecuteInEditMode]
public class GlobalSettings : MonoBehaviour
{
    private static GlobalSettings _instance;
    private static GlobalSettings _editorInstance;

    public static GlobalSettings Instance
    {
        get
        {
            if (Application.isPlaying)
                return _instance;

            return _editorInstance;
        }
    }

    private static readonly string _singletonViolationMessage = $"The '{nameof(GlobalSettings)}' is a singleton!";

    private void Awake()
    {
        Log.Caller(Application.isPlaying);

        if (Application.isPlaying)
        {
            if (_instance)
            {
                Destroy(this);
                throw new GameException(_singletonViolationMessage);
            }

            _instance = this;
        }
        else
        {
            if (_editorInstance)
            {
                Destroy(this);
                throw new GameException(_singletonViolationMessage);
            }

            _editorInstance = this;
        }
    }
}

```

Some of my conclusions and conjectures:

1. `Awake` in edit mode is fired only once. Even if I change the code and then it is recompiled by Unity the `Awake` method is not called again. Still don't understand why...
2. When `Awake` is called in edit-mode the `_instance` is set correctly. Then I press "Play" and it is destroyed and rewritten by a new instance of the play-mode. When I go back to the edit-mode the "play-mode-instance" is destroyed but the \`Awake' method is not called anymore and it remains so-called "null". Thus, it must be stored separately in two different instances for the edit- and play- modes.
> 1 votes

---
Tags: unity
---


title: Button on click event crashes

text:
# Question
Title: Button on click event crashes
I'm trying to create an android game using libgdx with a Titlescreen, you just press start and your game startes. However I'm having difficulty trying to get these buttons to work. The titlescreen works, but as soon as I press 'start game' the game crashes with the error:

> Exception in thread "LWJGL Application" java.lang.NullPointerException
> at com.dinab.onepiecev2.TitleScreen$1.clicked(TitleScreen.java:47)
> at com.badlogic.gdx.scenes.scene2d.utils.ClickListener.touchUp(ClickListener.java:88)
> at com.badlogic.gdx.scenes.scene2d.InputListener.handle(InputListener.java:59)
> at com.badlogic.gdx.scenes.scene2d.Stage.touchUp(Stage.java:351)
> at com.badlogic.gdx.backends.lwjgl.LwjglInput.processEvents(LwjglInput.java:360)
> at com.badlogic.gdx.backends.lwjgl.LwjglApplication.mainLoop(LwjglApplication.java:221)
> at com.badlogic.gdx.backends.lwjgl.LwjglApplication$1.run(LwjglApplication.java:128)

I don't understand what I'm doing wrong and whether the problem is in my TitleScreen.java or in my GameScreen.java

This is my code:

**Main class**

```
public class Onepiecev2 extends Game {
    static public Skin gameSkin;
    public void create () {
        gameSkin = new Skin(Gdx.files.internal("skin/glassy-ui.json"));
        this.setScreen(new TitleScreen(this));
    }

    public void render () {
        super.render();
    }

    public void dispose () {
    }
}

```

**TitleScreen**

```
public class TitleScreen implements Screen {

    Stage stage;
    Game game;
    SpriteBatch batch;
    Texture img;
    TextureRegion mainBackground;

    public TitleScreen(Game aGame){
        batch = new SpriteBatch();
        img = new Texture("start_screen.jpg");
        mainBackground = new TextureRegion(img, 0, 0, 1920, 1080);
        stage = new Stage(new ScreenViewport());
        Gdx.input.setInputProcessor(stage);
        Skin mySkin = new Skin(Gdx.files.internal("skin/glassy-ui.json"));

        Button start_btn = new TextButton("START GAME", mySkin);
        start_btn.setSize(Constantes.screenWidth/4, Constantes.screenHeight/12);
        start_btn.setPosition(Constantes.col_width*3,Constantes.row_height/3);
        start_btn.addListener( new ClickListener() {
            @Override
            public void clicked(InputEvent event, float x, float y) {
                game.setScreen( new GameScreen(game) );
            }
        } );

        stage.addActor(start_btn);

    }

    @Override
    public void show() {
        Gdx.input.setInputProcessor(stage);
    }

    @Override
    public void render(float delta) {
        Gdx.gl.glClearColor(1, 1, 1, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
        batch.begin();
        batch.draw(mainBackground, 0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
        batch.end();
        stage.act();
        stage.draw();
    }

    @Override
    public void resize(int width, int height) {

    }

    @Override
    public void pause() {

    }

    @Override
    public void resume() {

    }

    @Override
    public void hide() {

    }

    @Override
    public void dispose() {
        stage.dispose();
        batch.dispose();
        img.dispose();
    }
}

```

**GameScreen**

```
public class GameScreen implements Screen {

    Stage stage;
    Game game;
    SpriteBatch batch;
    Texture img;
    TextureRegion mainBackground;

    public GameScreen(Game aGame){
        batch = new SpriteBatch();
        img = new Texture("start_screen.jpg");
        mainBackground = new TextureRegion(img, 0, 0, 1920, 1080);
        stage = new Stage(new ScreenViewport());
        Gdx.input.setInputProcessor(stage);
        Skin mySkin = new Skin(Gdx.files.internal("skin/glassy-ui.json"));

        Button start_btn = new TextButton("GO BACK", mySkin);
        start_btn.setSize(Constantes.screenWidth/4, Constantes.screenHeight/12);
        start_btn.setPosition(Constantes.col_width*3,Constantes.row_height/3);
        start_btn.addListener( new ClickListener() {
            @Override
            public void clicked(InputEvent event, float x, float y) {
                game.setScreen( new TitleScreen(game));
            }
        } );

        stage.addActor(start_btn);

    }

    @Override
    public void show() {
        Gdx.input.setInputProcessor(stage);
    }

    @Override
    public void render(float delta) {
        Gdx.gl.glClearColor(1, 1, 1, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
        batch.begin();
        batch.draw(mainBackground, 0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
        batch.end();
        stage.act();
        stage.draw();
    }

    @Override
    public void resize(int width, int height) {

    }

    @Override
    public void pause() {

    }

    @Override
    public void resume() {

    }

    @Override
    public void hide() {

    }

    @Override
    public void dispose() {
        stage.dispose();
        batch.dispose();
        img.dispose();
    }
}

```

# Answer
> 1 votes
It looks like you never assign the `game` member-variable in your `TitleScreen` class, so it is null when the click handler is invoked.

Try setting the `game` variable in the constructor of `TitleScreen`, you are already passing in a `Game` instance called `aGame`, you problably want to assign that to `game`:

```
public GameScreen(Game aGame){
    batch = new SpriteBatch();
    img = new Texture("start_screen.jpg");
    mainBackground = new TextureRegion(img, 0, 0, 1920, 1080);
    stage = new Stage(new ScreenViewport());
    game = aGame; // Add this

```

---
Tags: java, libgdx, android, android-studio
---


# Question
Title: Json Libgdx serialize / de-serialize a Object Map of Object Maps
Any one have any ideas on how I can serialize / de-serialize an

```
ObjectMap<Enum, ObjectMap<String, Object>>();

```

(Object is usually a String Integer or Vector2 ) using libgdx's built in json classes?. On de-serialize the inner ObjectMap, is always null even though the values are written to the json file.

# Answer
> 2 votes
libGDX Json converts Enums to strings and therefore cannot serialize / de-serialize Map keys to anything but strings.

To fix this, either...

1. Use strings for keys in Maps (ObjectMap, HashMap ect.).
2. Use GSON, which can serialize Enum Map Keys just fine.
3. Write lots of special serialization / de-serialization code using a class that implements `Json.Serializer<T>` where `T` is your map and then register that with your libGDX Json instance.

I recommend option one or two.

---
Tags: java, libgdx, data-structure, serialization, json
---


# Question
Title: Why do I get this warning when using a null conditional operator?
In the OnTriggerEnter2D function of my Bullet script, I have the following code:

```
private void OnTriggerEnter2D(Collider2D other)
{
     if (other.CompareTag("Enemy"))
     {
         var enemy = other.GetComponent<Enemy>();
         enemy?.Death();
     }
}

```

The reason for the null conditional operator (the question mark) in `enemy?.Death()` is because the Death function actually destroys the Enemy component script, so it suppresses an error when the bullet hits the enemy again. It's supposed to be shorthand for:

```
if (enemy != null)
    enemy.Death();

```

The code works; the error is suppressed. However, the IDE that I'm using, Jetbeans Rider, gives the following warning:

> '?.' on a type deriving from 'UnityEngine.Object' bypasses the lifetime check on the underlying Unity object.

What does that mean exactly? Should I continue using the null conditional operator?

# Answer
> 3 votes
That is because Unity overrides the `==` operator (and therefore `!=`), changing its behavior, and the `?.` operator does not use their version.

For more information, see Custom == operator, should we keep it?.

To summarize: Unity objects are wrappers around a C/C++ object. When that object is `Destroy()`ed, the underlying C++ object is also destroyed but the C# object has to wait until it is garbage collected.

That also means that *you should not compare to null*, and instead do:

```
var enemy = other.GetComponent<Enemy>();
if (enemy)
    enemy.Death();

```

Another reference: Don't Use == null On Unity Objects

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


# Question
Title: Unity - best way to make intro with images
I have made and rendered an intro in blender for my unity game. The intro currently consists of 150 PNG-images. Should I make it into a video before importing it to unity or should I just import the images to unity and handle the animation there and if so how do you do that?

# Answer
> 2 votes
If it is an animated video, then encode it as a video in one of the formats Unity supports, import it into Unity as a video clip and play it with the video player component. If you want to just play back the video in full screen mode, then I would recommend to use the render mode "Camera Near Plane" and assign your main camera as the target camera.

This will require fewer resources to play back, require a smaller filesize and will likely be far easier to accomplish.

Using multiple PNG images would only be a good idea if you want to show a slideshow of static images which each stay on the screen for multiple frames. Like this hand-drawn intro sequence from Witcher III. If I would create an intro like that, then I would use a timeline to control which image stays on screen for how long and how their positions and scales are animated.

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


# Question
Title: Move enemy left in sin wave motion over time
I'm trying to create a top down shooting game where the enemy moves in sinusoidal motion over time. For the first 10 seconds the enemy needs to move only left and after that it needs to move left in sin wave motion. This is the code I'm using. \`

```
public float enemySpeed;
float frequency = 5.0f;
float magnitude = 1.8f;

void FixedUpdate()
{
    if(Time.time < 10.0f)
    {
        transform.Translate((enemySpeed* Vector2.left) * Time.deltaTime);
    }
    if(Time.time >= 10.0f)
    {
        transform.Translate(enemySpeed* -1.0f * Time.deltaTime, 1.0f * Mathf.Sin(Time.time * frequency) * magnitude * Time.deltaTime, 0);
    }`

```

What's happening is that for the first 10 seconds the enemy just moves left but after that all the enemies in the screen start moving in sin wave motion. What I want to achieve is that if the enemy has already spawned before the 10th second, it should move left without sin motion. Right now if the enemy is in the middle of the screen and the time is over 10 seconds, even this enemy starts moving in sin motion.

# Answer
> 1 votes
Just track a variable counting the seconds since this enemy spawned. It can start at zero, and increment each timestep the enemy stays alive.

```
float secondsSinceSpawn = 0f;

void FixedUpdate() {
    secondsSinceSpawn += Time.deltaTime;

    if(secondsSinceSpawn < 10f) {
        ...

```

# Answer
> 1 votes
You can save the enemy spawn time in Start, then compare that to the current time like this:

```
float enemySpawnTime;

void Start()
{
    enemySpawnTime = Time.fixedTime;
}

void FixedUpdate()
{
    if (Time.fixedTime - enemySpawnTime < 10f)
    {
        // move left
    }
    else
    {
        // move left with sine wave motion
    }
}

```

Note that in FixedUpdate, you should use `Time.fixedTime` or `Time.fixedDeltaTime` instead of `Time.time`.

---
Tags: unity
---


# Question
Title: Best way make static GameObject clickable 2D
I've built a turn based battle combat game (like pokemon) but i'm stuck between a rock and a hard place.

Asfar as i understod UI elements should be inside Canvas, while Players, Enemies, Items and etc... Should not be inside a canvas. Correct me if i'm wrong.

I've tried different ways how to handle this situation. Such as make Enemy as a button, but seems not to fire. Since i think it has to be inside a canvas. Also make enemy which have animations as button, may not be a good idea?

Update event, to check if the mouse is down and mouse position is converted with screentoworldpoint and see if the positions matches with the enemy position.

Update event, to check if the mouse is down and rayCast see if we colide with something. But i dont feel like this is neccesary since the enemy does not move. So the position is always the same.

Also if it's possible to take into consideration that every enemy is different size. But this is a minor detail, i would like firstly tackle the best way handle onClick event without the extra overhead.

I would appericate any feedback on my dilemma.

# Answer
If you are trying to allow clicking on an object in the world, as compared to a UI element, then raycasting is the way to go.

There are two ways to do that:

1) Add a collider to the Enemy's GameObject and add the following script somewhere:

```
public class MouseHandler : MonoBehaviour
{
    public Camera theCamera;

    void Update()
    {
        Ray cameraRay = theCamera.ScreenPointToRay(Input.mousePosition);
        if (Physics.Raycast(cameraRay, out Raycast hit))
        {
            Debug.Log("Clicked on " + hit.collider.name);
        }
    }
}

```

Use the LayerMask parameter of Raycast to limit what results it returns. You can then call `hit.collider.GetComponent<Enemy>()` to get the Enemy script on the object that was clicked.

Also: if your GameObject has a RigidBody, then you might want to use `hit.rigidbody` instead of `hit.collider`.

2) Put a collider on the Enemy's GameObject, a Physics Raycaster to the Camera GameObject, and add the following to the Enemy script:

```
public class Enemy : MonoBehaviour, IPointerClickHandler
{
    public void OnPointerClick(PointerEventData eventData)
    {
        if (eventData.button == PointerEventData.InputButton.Left)
        {
            Debug.Log("Clicked " + name);
        }
    }
}

```
> 1 votes

---
Tags: unity
---


# Question
Title: My app crash using OpenAL but only in Release Mode
I'm building up a complete game engine so, basically, it integrate a sound system. The problem is that a line make me crash in my code. The strange thig is that my app crash ONLY when I compile using Release mode, in Debug Mode it run just fine.

I'm using MSVC 16.XX (I don't know exact version, but it is the latest at the time I am asking this question)

(language used is c++)

```
void PSound::GetDevice()
{
    const ALchar* DeviceList = alcGetString(NULL, ALC_DEVICE_SPECIFIER); //This Line make app crash

    if(DeviceList) {
        while(strlen(DeviceList) > 0) {
            Devices.push_back(DeviceList);
            DeviceList += strlen(DeviceList) + 1;
        }
    }
}

```

# Answer
Ok, I fixed it. It was a very silly problem. There was a project which where not well linked and all the projects were not using the same Runtime Library.
> 0 votes

---
Tags: c++, openal
---


# Question
Title: Figuring out the exponent in a spotlight equation from the angle of a cone
I followed a tutorial on how to build a spotlight using DirectX. This tutorial uses a point light equation plus a line of code to limit the light to the shape of a cone. I have everything working, but the equation for constraining the light uses a constant exponent to control the broadness of the light, which is all well and good if I was just tweaking the value for looks alone, but I also want to know the precise size of the cone in order to do culling on the CPU side. Here's the equation:

```
float lightAmnt = dot(lightToSurfaceVector, inputNormal); // point light

lightAmnt /= attenuationA + attenuationB * distance + attenuationC * distanceSquared; // falloff

// exponentConstant to control broadness
lightAmnt *= pow(max(dot(-lightToSurfaceVector, lightDir), 0.0f), exponentConstant); // spotlight

```

what I'd like to do is create an angle theta for the cone on the CPU, and then create the **exponentConstant** based on that and the range aka cone height, but I don't know how that math would work. And I realize there are other spotlight equations, but I like this one because the attenuation works identically between point and spot lights. Can anybody lend a hand?

link to the tutorial: https://www.braynzarsoft.net/viewtutorial/q16390-21-spotlights

# Answer
> 0 votes
As I mentioned in the comment, raising a number to an exponent won't make the result zero unless it was already zero to begin with. (At least not in infinite-precision real numbers. We could try to exploit floating point precision limits here, but I think that's both more complicated and less efficient than the alternatives we have at our disposal)

So even though raising the exponent does make the bright part of the cone narrower and narrower, there are still non-zero values well out into the dark part. All the way out to 90° from the light direction, in fact (again, discounting numerical precision for the moment).

Since you're rendering in high dynamic range, it's hard to pick a cutoff value that's "dark enough" that it won't have any impact on rendering, even if your exposure is extremely high. We could go super conservative, but then you'd be treating your cone as wider than it needs to be most of the time, reducing the savings you get from culling. Or we could try shifting our cutoff based on our exposure settings, but again - too complex, and we can do better!

Since you say you like your distance attenuation function as-is, let's keep that unchanged. We'll just replace this line:

```
lightAmnt *= pow(max(dot(-surfaceToLightVector, lightDir), 0.0f), exponentConstant);

```

(Note that I changed your variable name - the tutorial calls it "light to pixel" but it really points from the surface pixel to the light! So let's name it in a way that's *not* backwards )

First, we'll note that the inner term is just the cosine of our angle from the light's axis:

```
float cosine = dot(-surfaceToLightVector, lightDir);

```

Within our desired cone wedge, that hits a minimum value we can compute on our CPU, and pass as a uniform:

```
float minCosine = Math.Cos(spotlightAngleLimitRadians);

```

So now we can remap the range from `[minCosine, 1]` into the range \[0, 1\]:

```
float angleFalloff = max((cosine - minCosine), 0.0f) / (1.0f - minCosine);

```

(If you want, you can pre-compute the reciprocal of the denominator and pass it as another uniform so this division becomes a cheaper multiplication per-pixel).

Now you're guaranteed the spotlight brightness hits zero at this limiting angle. But you can still use a power function to shape the falloff curve to your liking a little - here the exponent is arbitrary, we're not counting on it to hit a specific angle width, we're just tuning for look at this point.

```
lightAmnt *= pow(angleFalloff, exponentConstant);

```

---
Tags: shaders, directx, directx11, lighting, geometry
---


# Question
Title: Calculation of perpendicular distance to camera plane explanation
I am following this tutorial for a Wolfenstein 3D engine. https://lodev.org/cgtutor/raycasting.html

Here is the relevant image from the tutorial:

I cannot figure out how dividing by rayDirX or rayDirY causes the distance calculation to work. The explanation given is about halfway down the page, right above this text if you search for it: "Calculate distance projected on camera direction".

# Answer
> 1 votes
I believe I figured it out. This picture shows what I am after. How does perpWallDist = yDist/rayDirY? Using ratios you can deduce that yDist/rayDirY = euclidiean/rayDir. Then you can say that perpWallDist/dir = euclidean/rayDir. RayDir is equal to 1, that is just how the engine is setup, that vector is normalized. Therefore, perWallDist = yDist/rayDirY.

I would have never have figured this out on my own, but this makes sense and I can explain it. If there are other methods to solve this problem I would love to read them :)

---
Tags: mathematics, vector, raycasting
---


# Question
Title: Perspective projection and ultrawide resolution
The problem I'm going to describe did not occur to me until very recently, when I got a super ultra-wide monitor (32:9 aspect ratio) and tried playing videogames on it.

TL;DR: the scenery is stretched near the left and right edges of the screen due to how projection onto a plane works. Question: why isn't the standard to use "spherical" canvas instead of a plane?

I tried several games and I noticed that the objects displayed far left and far right on my screen are stretched and appear way too closer than they actually are. I could not figure out any general setting (field of view, focal distance...) to mitigate this uniformly, until I realized how projection works.

The way 3D objects are displayed on a 2D canvas is as follows: the camera consists of a point (focal point) and an infinite plane (canvas). To calculate where another point in front of the camera will be displayed, this point is connected to the focal point and the point drawn on the canvas corresponds to the intersection of this line with the canvas.

No wonder the far left and far right parts of the screen are so stretched! The rays from these vertices intersect the canvas at a very small angle.

This problem would be eliminated if we chose the canvas to be a sphere, ideally with the same curvature as the monitor (in case the monitor is flat, the sphere degenerates into a plane and we have the same situation as before). That way, if we choose a correct position for the focal point (depends on our screen setup, curvature, aspect ratio etc.), no stretching should occur, since the focal point is literally "surrounded" by the canvas, instead of the canvas running away from it in all directions.

So my question is, **why isn't the standard to implement this "spherical" projection instead of "planar"?** Is it because it happens on such a low level of coding that developers don't care, or the code with spherical projection would be a serious bottleneck compared to what is done now? Or the market with super ultra-wide resolution is so niche that they don't care, but we should expect to see it sometime in the future? Or the standards are so baked in that nobody cares about implementing something new, even if it would make more sense?

Sorry in case this question doesn't quite fit in here, I actually don't know anything about making videogames, but this strikes me as it's more about geometry than actual game-making.

# Answer
> 3 votes
> why isn't the standard to implement this "spherical" projection instead of "planar"?

It looks to me like you answered this yourself here:

> "in case the monitor is flat, the sphere degenerates into a plane"

That is, if most people are using flat screens, then the planar projection is geometrically correct (from the intended viewpoint).

Yes, even if the flat monitor is ultra-wide. If the projection axis and field of view are chosen correctly for where the viewer is seated, then the stretching of the objects at the edge of the screen exactly compensates for the way the edge of the screen itself foreshortens and recedes into the distance away from the viewer, resulting in correct perspective *when viewed from that viewpoint*. But it definitely looks strange if you stand back far enough that you can see the whole monitor without significant foreshortening to balance-out the stretch in the image.

So as you say, the right way to render is to use a projection surface with "the same curvature as the monitor." And most monitors are flat, so a flat projection plane and linear perspective makes sense the vast majority of the time.

If spherically-curved monitors became a large segment of the market, then doing specialized projections for them would likely get correspondingly more popular.

As things stand, only a few types of games are routinely played on curved/wraparound screens - mainly racing and flight sims - so these types of games may sometimes implement special projections and curvature configuration to serve the segment of their players who own these specialized cockpit rigs. Often these projections will be cylindrical, rather than spherical, to match widescreen monitors that curve in one axis but not both.

Just like with the flat case, these projections are correct only from one specially-chosen viewpoint, and will look similarly distorted if you look at them from further away.

There are also other strategies for rendering to ultra-wide displays, such as:

These projections aren't technically geometrically correct for *any* viewpoint - they apply a kind of compromise distortion so that the image looks plausible enough from a range of viewpoints, which can help if you know your player has a super wide display, but you don't know exactly how it is curved or exactly where their head is in relation to it (as you would with a cockpit simulator).

---
Tags: 3d, projection
---


title: Collision Player and Tilemap Unity

text:
# Question
Title: Collision Player and Tilemap Unity
i am a student in austria. I am working on a project for school, where we have to make our own first game with unity. Because it is the first time using unity, i constantly run against problems. Most of them, i fixed already. But this problem got me stuck for a few days now. I am very sorry, that i used that many pictures. Maybe in the picture there is some information i did not give you. The name of the collision map is "FirstLayer\_Col"

This is what i have got so far. My map is pretty big. I used the tile palette, to paint them in. I also used different types of layers. The ground layer is mostly gras or water. On top of that, i put the trees on, which are seen in the next picture. I created a new tilemap to make it a collision tilemap. I took a random tile and put it on everything i want to have a collision on.

I changed to order of layer to 10 for the collision tilemap, so i could see where i have to put the tile to stop the player from, so he cant walk over or through it. After i put the tile on my wanted location, i changed the order of layer back to 0 so i couldnt see it anymore. I dont know if that is a problem or not. I have not found any other solution that worked for me. The collision tilemap has a tilemap collider and the player named "South\_0" ,because of the sprite i used for it, has a box collider and a rigidbody. Every collider is a 2D one.

After i start the application with the collision layer on 10. I can go through it, stand on the place, where the collision should be as there is no collision. When i change the order of layer to 0, so it is not visible, i can walk to the tree, but then my game starts to shake and the player rotates. Then there is some type of collision, but when i try to go through it, my game starts to shake very strong and then my player can stand in the middle of the tree as there is not any collision. It looks very "buggy" and the player rotates in any direction. I can not figure out, how i can make the collision to stop the player from entering the field of my tilemap collision without making the player go crazy and make the whole screen shake. I just want the player to stop in front of it, so that there is no way of bugging through it. I hope i explained my problem so you can understand it. Maybe it is just a small, little fix, but i could not find any solution. The last picture is how my player looks after i ran up against the tree with the collision map on layer 0. The player should not rotate and just go, up, down, left, right.

My Code for my Player:

using UnityEngine;
using System.Collections;

public class PlayerMovement : MonoBehaviour {

    Direction currentDir;
    Vector2 input;
    bool isMoving = false;
    Vector3 startPos;
    Vector3 endPos;
    public float t;

    public Sprite northSprite;
    public Sprite eastSprite;
    public Sprite southSprite;
    public Sprite westSprite;

    public float walkSpeed = 0.5f;

    public bool isAllowedToMove = true;

    void Start()
    {
        isAllowedToMove = true;
    }

    void Update () {

        if(!isMoving && isAllowedToMove)
        {
            input = new Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"));
            if (Mathf.Abs(input.x) > Mathf.Abs(input.y))
                input.y = 0;
            else
                input.x = 0;

            if(input != Vector2.zero)
            {

                if(input.x < 0)
                {
                    currentDir = Direction.West;
                }
                if(input.x > 0)
                {
                    currentDir = Direction.East;
                }
                if(input.y < 0)
                {
                    currentDir = Direction.South;
                }
                if (input.y > 0)
                {
                    currentDir = Direction.North;
                }

                switch(currentDir)
                {
                    case Direction.North:
                        gameObject.GetComponent<SpriteRenderer>().sprite = northSprite;
                        break;
                    case Direction.East:
                        gameObject.GetComponent<SpriteRenderer>().sprite = eastSprite;
                        break;
                    case Direction.South:
                        gameObject.GetComponent<SpriteRenderer>().sprite = southSprite;
                        break;
                    case Direction.West:
                        gameObject.GetComponent<SpriteRenderer>().sprite = westSprite;
                        break;
                }

                StartCoroutine(Move(transform));
            }

        }

    }

    public IEnumerator Move(Transform entity)
    {
        isMoving = true;
        startPos = entity.position;
        t = 0f;

        endPos = new Vector3(startPos.x + System.Math.Sign(input.x), startPos.y + System.Math.Sign(input.y), startPos.z);

        while (t < walkSpeed)
        {
            t += Time.deltaTime * walkSpeed * walkSpeed;
            entity.position = Vector3.Lerp(startPos, endPos, t);
            yield return null;
        };

        isMoving = false;
        yield return 0;
    }
}

enum Direction
{
    North,
    East,
    South,
    West
}
```

# Answer
This problem usually occurs when you try to move a gameObject with a `Rigidbody` / `Rigidbody2D` component through an environment made of `Collider`s / `Collider2D`s by manipulating its `Transform`. Don't do that. Changing the transform isn't "moving" an object, it's "teleporting" an object. Teleporting an object into a solid wall never ends well.

If you want to move an object with a rigidbody, then move it by using the methods of the rigidbody. There are several ways to do that. I made a little demo game a while ago which explains the differences between different movement methods. You can check it out here.

If you want to keep it simple, you might want to use `rigidbody.MovePosition(newPosition)`. But you might also consider to control the movement of your player using `rigidbody.AddForce(forceVector)` to give it physically correct acceleration, deceleration and also the ability to shove (and get shoved by) other rigidbodies in a physically correct way. This requires a bit experimentation with the force strength and the mass and drag settings of the rgidbody to get right, but the end result often feels much more organic.

Regarding the rotation of your character: You can get rid of that by freezing the rotation axis in the Rigidbody / Rigidbody2D.
> 0 votes

---
Tags: unity, 2d, collision-detection, tilemap
---


# Question
Title: Building a flexible GLFW Event handling system (for beginners)
The 2017 Thread "How to improve my input handling in GLFW?" is brilliant! Exactly my question and what seems like some great solutions.

However "Tyyppi\_77" is hard for me to understand as a beginner. For starters:

1) how is addBinding called and when in the flow? Can you describe what the parameter Callback% callback is and its purpose?

I'll stop there for now. Ty!

```
class Window
{
public:
    using Callback = std::function<void()>;

    void addBinding(int key, const Callback& callback)
    {
        m_Callbacks[key].push_back(callback);
    }

    void onKeyPress(int key)
    {
        for (Callback& callback : m_Callbacks[key])
        {
            callback();
        }
    }
private:
    std::map<int, std::vector<Callback>> m_Callbacks;
};

```

# Answer
> 1 votes
**Note**: This answer expands on https://gamedev.stackexchange.com/a/150166/35344.

Let's take a player entity that has a few methods for movement:

```
struct Player {
    void moveLeft() {
        xVel = -1
    }

    void moveRight() {
        xVel = 1
    }
};

```

Then, with a setup such as the following, we can bind the movement methods to our callback manager (called `Window` here). The binding is performed in initialization, but you'd also perhaps want to perform this when new objects that need to listen to keyboard events are instantiated, or even when the player switches their keybindings (all though other approaches might be more suitable for that, however those are beyond the scope of this question).

```
int main() {
    Window window;
    setupGlfw(window);

    Player player;
    window.addBinding(KEY_LEFT, std::bind(&Player::moveLeft, &player));
    window.addBinding(KEY_RIGHT, std::bind(&Player::moveRight, &player));

    // Begin gameloop
}

```

The key here is `std::bind`, which takes a member function pointer, and an instance of the owning class, and creates an `std::function<void()>` for us, that we register as a callback to the specific key event.

The parameter `Callback` that `addBinding` accepts is a bound function call. Its purpose is to allow generic objects and functions to be bound to the same event handler (`Window`), as we could just as well pass around static member functions, functions in the global scope or even lambdas to the callback manager.

Note that our current implementation leaves a few details out, including memory management, which are left as an exercise to the reader (as they are way beyond the scope of this question).

---
Tags: input, events, glfw
---


title: How to determine the cost of new units

text:
# Question
Title: How to determine the cost of new units
Suppose I design a game such as Battle of Wesnoth, where there are many races, each of which with many types of units. Is there any rule-of-thumb for determining how much each unit should cost?

One obvious rule is that weaker units should be cheaper, otherwise no-one would like to buy them. But how much cheaper should they be?

As an example from the above link, is there any formula by which I could decide that "vampire bat" (based on its HP and damage properties) should cost 13 while "blood bat" should cost 21? Or is it just a guess that is validated by extensive playtesting?

EDIT: To make the question more focused, let's assume for simplicity that the units in Wesnoth differ by only two stats: health points ($h$) and damage points ($d$), and all their other stats are equal. Is there a way to calculate a formula to determine the cost as a function of $h$ and $d$?

# Answer
> 2 votes
Such a rule of thumb would aways be specific to your game.

Looking at the numbers and setting the cost linearly can be very misleading. Some stats might be more useful than others. Some stats might have synergetic effects between each other. The usefulness of stats might not always be linear.

And then there might be game mechanics in your game which affect whether few strong units are better or worse than many weak units.

So the only way to really figure this out is through playtesting. Nothing beats playtesting with real human players. But in order to save time and money, you can also cut down the time you need by automatizing your playtesting.

Create a framework which allows you to quickly run a large number of automatic battle simulations with different pairings and tell you which side wins how often.

The most primitive simulation is to simulate simple unit vs. unit combat. Just simulate two units taking turns attacking each other until one is dead. Run that a thousand times, and you can see which unit wins how often. This should tell you which of the two units is superior and thus should cost more.

One further step is to simulate group combat. Extend your previous simulation framework to allow 1 vs multiple or even multiple vs. multiple units. This allows you to answer questions like "are 100 points worth of vampire bats stronger or weaker than 100 points worth of blood bats". But now you need to think about how units should pick their targets. Simulating various strategies and looking at their success rates can also provide you with useful data about which tactics players should choose in different situations. This data can also be very useful for your AI development.

The most comprehensive form of simulation is to run complete matches AI vs. AI. This allows you to run lots and lots of simulation series with slightly tweaked unit attributes and compare win/lose ratios. But this of course requires that you already have an AI for your game which is able to play in a way which is comparable to humans.

Still, in the end, no simulation can replace real playtesting. You players might figure out strategies you never thought about when developing your AI. Such a strategy might completely revolutionize the meta-game and force you to rebalance various units to make the game interesting again. No complex strategy game has really solved this problem yet. Even the most popular AAA strategy games keep releasing balance patches again and again to address balance problems discovered by the player community.

---
Tags: mathematics, game-design
---


# Question
Title: Rotate Sprite in direction it is moving while beeing dragged
I am working on a 2D topdown game where you have cars you can drag around. you can touch any given car and move it around. This kind of works but when I drag a curve the sprit of the car does not turn in direction of its movement but rather moves sideways.

I need a way to rotate the sprite towards input (touch,mouse) and be updated as long as the input "is down" but I am unsure how to calculate and update the angle each frame.

I do not want to use velocity towards the input but rather drag and drop while "clicking" on the sprite.

# Answer
> 1 votes
When you hold the mouse button down, begin tracking the location of the mouse.

Every frame, compare the current location with the location on the previous frame.

If the vector from previous to current is large enough, orient the car in the direction of the vector.

When you release the mouse button, stop: tracking, comparing and rotating.

**EDIT**

```
private bool PerformRotation = false;
private Vector2D LastFramePosition

OnMouseButtonClicked()
{
    PerformRotation = true;
    LastFramePosition = Car.Position;
}

OnMouseButtonReleased()
{
    performRotation = false;
}

Tick()
{
    if(performRotation)
    {
        Vector2D CurrentMouseLocation = Mouse.getLocation();
        Vector2D LastFrameToCurrent = CurrentMouseLocation - LastFramePosition;

        Car.ForwardVector = LastFrameToCurrent.Normalize();

        LastFramePosition = CurrentMouseLocation;
    }
}

```

---
Tags: sprites, angles, direction, rotate
---


# Question
Title: How would I make my player controls respond quicker?
I'm working on this game in Unity 2D where the user swipes to make a game object move in the direction that the user swiped in. Currently, when the user swipes it takes about a quarter of a second for the game object to respond and move in the new direction. What should I do to make the controls respond quicker? I know that with `Input.GetAxis`, I could make it `Input.GetAxisRaw` to make it more responsive. Right now it's like `Input.GetAxis` but I'm trying make it like `Input.GetAxisRaw`. (I can't use `Input.GetAxisRaw` because this is for a mobile game). Thanks.

```
private Rigidbody2D rb;
private Vector2 moveVelocity;

```

in void Update():

```
if (Mathf.Abs(lp.x - fp.x) > Mathf.Abs(lp.y - fp.y)) {   //If the horizontal movement is greater than the vertical movement...
                    if ((lp.x > fp.x)) {   //Right swipe
                        if(moveVelocity != Vector2.left) {
                            moveVelocity = Vector2.right;
                        }
                    }
                    else {   //Left swipe
                        if(moveVelocity != Vector2.right) {
                            moveVelocity = Vector2.left;
                        }
                    }
                }
                else {   //the vertical movement is greater than the horizontal movement
                    if (lp.y > fp.y) {   //Up swipe
                        if(moveVelocity != Vector2.down) {
                            moveVelocity = Vector2.up;
                        }
                    }
                    else {   //Down swipe
                        if(moveVelocity != Vector2.up) {
                            moveVelocity = Vector2.down;
                        }
                    }
                }

```

And void FixedUpdate():

```
void FixedUpdate() {
    rb.MovePosition(rb.position + moveVelocity * speed * Time.deltaTime);
}

```

# Answer
try reducing the linear drag of the player, it sometimes work
> -1 votes

# Answer
Also perhaps you should increase the reaction time of the input.
> -2 votes

---
Tags: unity, c#, movement, mobile, touch
---


title: Unprojeting a line on the screen

text:
# Question
Title: Unprojeting a line on the screen
I have a line connecting two points of my model. I see a projection of this line on my screen and a want to map a point of that projection to the corresponding point in my model PoV.

Let `A = (x_a, y_a, z_a, 1.)` and `B=(x_b, y_b, z_b, 1.)` be the coordinates of two points of my line in the model PoV.

Let `M,V` and `P` be the model, view and projection matrices.

Let `A_s = NDC_to_screen(P*V*M*A)` and `B_s = NDC_to_screen(P*V*M*B)` be the coordinates of `A` and `B` projections on my screen (assume that those two points are distinct).

Let `vec_AB_s = B_s - A-s` be the vector from `A_s`to `B_s` and let `C_s = A_s + lambda_s * vec_AB_s` be a point that lie on the line's projection on my screen.

How can I get the 3D coordinates of `C` so that `C_s = NDC_to_screen(P*V*M*C)` ? Something that would be usefull for me would be to have it in the form `C = A + lambda * vec_AB`

# Answer
> Let `vec_AB_s = B_s - A-s` be the vector from `A_s`to `B_s` and let `C_s = A_s + lambda_s * vec_AB_s` be a point that lie on the line's projection on my screen.

Since the line is being projected onto the screen, then lambda will not change as a ratio between points (assuming your lambda is 0 to 1.0).Simply use the lambda and apply to A and B. `C = A + lambda * vec_AB` like you stated in your post.
> 0 votes

---
Tags: 3d, geometry, computational-geometry
---


title: problems getting a new position vector3

text:
# Question
Title: problems getting a new position vector3
could someone explain to me why i can't get a new position that is outside the update method.

if i set what's inside the void callposic to a Start I can't get any position, only if it's inside the update

what can you do, because I don't want to use them in the update board.

https://www.youtube.com/watch?v=aNzJ5GUYAOA&feature=youtu.be

```
public int index;
public Vector3[] posic;
void Start()
{
    prev.onClick.AddListener(() => void1(-1));
    next.onClick.AddListener(() => void1(1));
    index = 0;

}

void Update()
{
    callposic();
}

void callposic()
{
    transform.localPosition = posic[index];
}

void void1(int value) { index = index + value; }

```

}

# Answer
It looks to me like what you want to do is this:

```
public int currentPositionIndex;
public Vector3[] positions;

public Button previousButton;
public Button nextButton;

void Start() {
    prev.onClick.AddListener(IncreaseIndex);
    next.onClick.AddListener(DecreaseIndex);
    // We don't strictly need to initialize currentPositionIndex here;
    // it'll use its serialized value.
}

// I named these methods for clarity.
void IncreaseIndex() { ChangeIndex(1); }
void DecreaseIndex() { ChangeIndex(-1); }

void ChangeIndex(int delta) {
    // Let's clamp this to ensure we don't go outside our array bounds.
    currentPositionIndex = Mathf.Clamp(currentPositionIndex + delta, 0, positions.Length -1);

    // Our index has (potentially) changed! Update our position to match.
    transform.localPosition = positions[currentPositionIndex];
}

```
> 0 votes

# Answer
```
void callposic()
{
    transform.localPosition = posic[index];

   if (index == posic.Length - 1)
   next.gameObject.SetActive(false);
   else
   next.gameObject.SetActive(true);

   if (index == 0)
   prev.gameObject.SetActive(false);
   else
   prev.gameObject.SetActive(true);
}

void void1(int value)
{
   index = index + value;
    callposic();
}

```
> 0 votes

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


title: Game free publishing website?

text:
# Question
Title: Game free publishing website?
I am making game that will be completely free and I want to publish it. The publishing platform have to be free and it can be done without any contract or specific license. I simply upload my files make my game page and that’s all. Thanks for help, Maratonec.

# Answer
> 3 votes
I think itch.io is what you are looking for.

* No listing fee.
* No approval process.
* You don't sign away any of your IP rights.
* You don't have to promise exclusivity.
* You can choose if people can play/download your game for free, for a fixed price or for a pay-what-you-want optional donation.
* If you choose to monetize your game, you can set a commission percentage to whatever you think itch.io deserves for their services.

---
Tags: publishing, free-to-play
---


# Question
Title: In SDL, what is the difference between using a Surfaces and a Renderer?
I am new to SDL and I've been following some tutorials; in one tutorial he used Surfaces (a window surface and image surface) and a BlitSurface function to draw images without using any renderer (used SDL Image library for JPG, PNG etc.).

And in another tutorial, he used a Renderer.

What's the difference between those two? It seemed to me they do the same thing but I'm assuming if they were the same, one wouldn't exist.

# Answer
This is fairly well documented in the SDL1 to SDL2 Migration Guide.

Essentially, `SDL_Surface` is a tool for CPU side blit rendering, where as `SDL_Renderer` takes advantage of hardware acceleration, and performs the rendering on the GPU. `SDL_Renderer` provides an abstraction over several APIs and even offers a fallback CPU-side implementation if no other implementation suits your platform (unlikely).

There are very few reasons for using `SDL_Surface`s for rendering these days, except if you 100% know what you are doing (and are perhaps writing a low resolution raytracer that runs on the CPU?). `SDL_Renderer` and its `SDL_Texture` is a much better performing choice if you don't need CPU side access to individual pixels.
> 15 votes

---
Tags: sdl
---


title: Bouncing Ball in c++

text:
# Question
Title: Bouncing Ball in c++
**Background**

I've been making my own game from scratch.

I've made my own collision system and there's a situation I'm having an issue with.

---

**Problem**

*Pictured*:

* a ball going in one direction and changing direction when it hits the green segment.

I have the trajectory's angle in correlation with \[relative to?\] OX axes and trajectory's angle (in correlation with)\[relative to?\] the green segment.

---

**Question**

How do I update the initial trajectory angle with the OX to produce the bounce behaviour?

# Answer
> 3 votes
This is not done with angles.

This is done with vectors. Well, actually you could do it with angles...

In any case, the ball has a velocity vector at the instant of collision, and will have a new velocity vector from the collision resolution. There are a few ways we can go about getting that new velocity vector:

* You can use vector projection to extract the components, and use them to construct the new velocity.
* You can express the orientation as a transformation matrix, the flipping as another transformation matrix, compose them... and that is a bounce transformation matrix.
* You can throw trigonometry at it.

I suggest the first path. It is the one that matches intuition more closely. Also optimizes well. *Although, I will not be doing that in this answer.*

---

What intuition?

Consider the simple case. If the ball were bouncing with a vertical wall, all you would do is flip the x axis of the velocity vector. If it were bouncing to an horizontal floor, all you would do is flip the y axis of the velocity vector. That is you flip the component that is normal to collision. We still need to do that, but with arbitrary orientations.

Basically, I'm saying that the collision flips the velocity along the normal of the surface, but not tangentially to the surface. *The component that was going towards the obstacles is flipped so it goes away instead. In order words... it bounces.*

Thus, the new velocity vector, will be the original velocity vector with the component normal to the collision flipped. *Perhaps multiplied by some elasticity factor. But that is beyond the scope of the question.*

---

As I was saying, you need to break the velocity vector into components. One component goes along the normal at the point of collision, the other goes tangent. Then you flip the normal component sign, compose it with the tangent component and that gives you the new velocity vector.

*In case it is not clear, the components of the vector add up to the vector.*

We have the velocity vector `v`, and the normal vector `n`. Then the velocity component along the normal is `v⊥n` (`v` projected on `n`) and the tangent component is `v - v⊥n`. *Because the components add up to the vector.*

Knowing that, we get new velocity vector by flipping `v⊥n`, which gives us `-v⊥n` and adding the other component (`v - v⊥n`). That is, `v' = -v⊥n + v - v⊥n = v - v⊥n - v⊥n = v - 2*v⊥n`.

---

Of course, to actually implement this, we a projection function. Assuming you do not have a library that offers such function, you can implement it like this:

```
v⊥a = (a/|a|)*(v·a)/|a|

```

Where `|a|` is the length of `a`, and `·` denotes dot product.

*You can find this formula in any vector algebra or analytic geometry book. I will not explain how to derive it here.*

As you probably know, `|a|` would be just Pythagoras, and `·` is the sum of the products of the components:

```
|a| = sqrt(a.x * a.x + a.y * a.y /*+ a.z * a.z*/)
a·b = a.x * b.x + a.y * b.y /*+ a.z * b.z*/

```

---

That is enough information to write some code:

```
//This code has not been optimized whatsoever

Vector Add(Vector a, Vector b)
{
    return Vector(a.x + b.x, a.y + b.y/*, a.z + b.z*/);
}

Vector Mult(Vector a, float s)
{
    return Vector(a.x * s, a.y * s/*, a.z * s*/);
}

float Dot(Vector a, Vector b)
{
    return a.x * b.x + a.y * b.y /*+ a.z * b.z*/;
}

float Norm(Vector a)
{
    return sqrt(a.x * a.x + a.y * a.y /*+ a.z * a.z*/);
}

Vector Normalize(Vector a)
{
    return Mult(a, 1/Norm(a));
}

Vector Project(Vector v, Vector a)
{
    return Mult(Normalize(a), Dot(v, a)/Norm(a));
}

Vector Bounce(Vector v, Vector n)
{
    return Add(v, Mult(Project(v, n), -2));
}

```

*What angles?*

---
Tags: c++, mathematics, algorithm
---


# Question
Title: Disable default unity editor behaviour on input
I'm creating a tool to create scenes easier on edition mode. I'm using the right click to delete elements, and I'd like to be able to delete several elements by keeping the right mouse button pressed and moving the mouse around.

The issue is that when I keep the right mouse button pressed over the scene window, the Hand Tool automatically activates, making the camera pan as I move the mouse.

Is there a way to disable this behaviour?

# Answer
I figured it out! You can make an event not reach the default Unity behaviour by consuming the event with:

```
Event.current.Use();

```

So to avoid camera panning with the right click you can just do:

```
if (e.isMouse && e.type == EventType.MouseDrag && e.button == 1)
{
    Event.current.Use();
}

```
> 1 votes

---
Tags: unity
---


title: OpenGL stencil pipe

text:
# Question
Title: OpenGL stencil pipe
Is there a document **describing 2D stencil pipe** ? Static, no rotation etc.

Something in more details then

enable stencil (buffer) write stencil ( mask) to stencil buffer 1st pass write stencil object to stencil buffer .... setup stencil function 2nd pass write object to be analyzed

# Answer
Thanks for the post, it for sure answered my question, appreciate that very much.

In the spirit of KISS, kindly allow me to translate to less fancy English

1. Google it
2. RTFM

Many thanks , problem solved.
> -1 votes

---
Tags: opengl, stencil
---


# Question
Title: In Android, neat way to send input info from `GLSurfaceView` to `onDrawFrame` in `GLSurfaceView.Renderer`?
The input is pinch/drag for camera movement, which modifies a matrix to scale/translate, and sent to a vertex shader. It's working, but ugly.

What's the proper way to do it?

I've noticed:

* `GLSurfaceView` gets `onTouch` callbacks; but `Renderer` has access to `GL`.
* Shaders and textures can only be loaded after the `onSurfaceCreated()` callback, so should be loaded there?
* Touch and graphics are on different threads, so should use `queueEvent()` or similar.

Is there a game/app on github that's a good example to follow? Thanks for any help!

# Answer
---

## General Architecture

If you had input and rendering share a thread, that would allow you to mix input and output(rendering) code, making it easier to make messy code.

What I suggest you to do is to have an Input Model. That is some object that contains a representation of the input of the user. Then you update it from your event handlers (listeners? virtual methods?). By the way, a well done Input Model does not have details of the input devices (for example, if touching a certain part of the screen is how you input a jump, then you store that the user inputs jump in the Input Model, not the details of the touch event).

*The Input Model can be queue, if that is what fits your game. Another common option is a HashMap.*

Let me step back further. Your game has an entry point. This entry point creates an object that serves as Composition Root for your game. What does the Composition Root do? In simple terms, it plugs stuff. This is basically setting up event handlers.

Some event handlers will be used to initialize stuff, such as the Input and Game Models. *Yes, load things into GL in `onSurfaceCreated`.* Other event handlers will receive input events, and these event handler will have code to update the Input Model. etc... *Yes, this is how you would probably do it anyway.*

After the Composition Root plugged all the stuff. The game loop can begin.

In your update/game loop you can read the Input Model and use it to update your world/scene (Domain Game Model). And finally your render method (where you access GL) can read your Game Model and output.

It is OK for the update/game loop to update the Input Model (as long as encapsulation is not broken). *If we go with the queue idea, then update/game loop can dequeue.* In fact, it is OK to have update/game loop swap the Input Model, similar to how double buffering works.

*By the way, in your Game Model is where you would do space partitioning. If you want to use an ECS, you make it part (or the totality) of the Game Model.*

---

These are the guidelines in general:

* There is a Composition Root, created on the entry point, that plugs everything, and starts the game loop.
* Input handlers will depend on the Input Model (they write it). The Input Model should not depend on the input device details.
* Output handlers will depend on the Game Model (they read it).
* The game loop contains logic that updates both Input and Game Models.
* Your game loop should not depend on any device details.

You can further evolve this architecture by breaking the Game Model into multiple sub-models. After all, the above does not have a strong separation between output and logic concerns. For example, one of the sub-models could be only what you need for rendering, and another could be just what you persist when the game is saved, perhaps another for AI, etc. *Yes, this can make ECS appealing. If you are picking an ECS, I would like to encourage picking one that (allows configuration that) makes the kind of queries you need easy and efficient.*

---

## Android Particular

For Android, by default the Composition Root is the `Activity`. It is OK to have it delegate or even to use a different Composition Root. For OP constraints, we will use an object of type `GLSurfaceView` as Composition Root. *Remember, your Composition Root is your glue.*

This means that we will have a class `MyGLSurfaceView` which extends `GLSurfaceView` and its responsibility is to setup everything. However, `GLSurfaceView` has the methods to deal with I/O (touch, render, etc...). How do we separate that?

The architectural line that we have to draw is that any code that does I/O should not be in `MyGLSurfaceView`. Instead we put that in other classes, let us call them Adapters. And the Adapters need a reference to `GLSurfaceView` for I/O.

`MyGLSurfaceView` creates the Adapters, then it can call `setOnTouchListener` on itself and set the Adapter as listener. *Remember that the Adapter has to update the Input Model.*

As alternative, you can have `MyGLSurfaceView` pass itself (as `GLSurfaceView`) in the constructor of the Adapters (dependency injection), and then the Adapters manipulate that reference. That is an inversion of control. *No special container needed.*

---

For rendering, there is the `Renderer`. It will be a separate class, that implements `Renderer`. `MyGLSurfaceView` will instantiate it.

As you know, when you call `setRenderer`, the GL thread will start, and that thread will set up the GL context, and enter a loop. This thread will call the methods of the `Renderer`.

Yet, the `Renderer` needs to know what to render, and that depends on the state of the game/scene/world. We want the `Renderer` to pull this information.

First, add to the `Renderer` interface a method to set a callback. This callback must return an object that represent the state of the game (or at least the part of the state of the game that is relevant for rendering※). The `Renderer` can call it to get what it has to draw on `onDrawFrame`.

※: I would expect the state of the game to have an space partitioning structure where you can query the objects that are nearby the camera, so that the `Renderer` can limit itself to those.

Second, make Game Logic class. This class is responsible for maintaining the state of the game. It has to take the Input Model, update the state of the game, and return it. All game logic, devoid of I/O, belongs there.

*To reiterate, the Input Model is in terms of the game, not in terms of the input device.*

Finally, since `MyGLSurfaceView` is our Composition Root. It is its responsibility to set up the callback. The callback will get the Input Model from the Input Adapter, pass it to the Game Logic class, and return the state of the game to the Renderer.

---

## Threading

The above approach should not have a race condition, given that the Game Logic runs on demand. The object that the `Renderer` gets from the Callback will not change while the `Renderer` is using it.

---

Let us say you want to change it so that the state of the game is updated as soon as input happens.

In that case, we need the Input Adapter to push the input events. That is, add to the Input Adapter a method to set a callback that will run every time the Input Model is updated. *The Input Adapter is still responsible of updating the Input Model.* Next, `MyGLSurfaceView` will setup the callback, making it call the Game Logic.

However, when we do this, the state of the game can update in the middle of rendering.

First notice that it is trivial to cache the state of the game. Have `MyGLSurfaceView` store the sate in a field, and then in the callback for the `Renderer`, it can pass it. This means that the Game Logic does not need to return the same object every time.

Taking advantage of that, we can solve the threading problem by buffering the state of the game. What? You will have two state of the game. One that is being used by the `Renderer`, and one that is being updated. Then have a method in the Game Logic to swap them. The `MyGLSurfaceView` will tell the Game Logic to swap the state of the game when the `Renderer` calls.

*You may, of course, make a queue of states instead.*

Please notice that having two states of the game do not imply to use double the memory. If you make everything in the state objects immutable, there is no problem in both of them referencing the same objects. That means that you only need extra memory for what changed from one state to the other.

What matters is that the state of the game that the `Renderer` is using does not change. If you know that the objects in that state of the game will not change, you can reference them in the other state of the game... just remember to replace them (instead of updating them). Making everything immutable is just the safest way to do that.

*It is also possible to make the read only instead of immutable, and pool them.*
> 1 votes

---
Tags: android, touch
---


# Question
Title: How to change Gravity towards certain object in Unity?
I have two spheres in Unity. One is 1000x in size other is 1x in size. So I want the smaller sphere to be attracted to bigger sphere. So how do I do it. I know that it can be down through gravity using rigid body. But how do I change gravity angle towards the big sphere?

# Answer
Gravity in the Unity physics engine only goes in one direction and is controlled in the Physics menu in the Edit-\>Project Settings menu.

If you want to do something other than that, you'll have to implement your own gravity.

Basically, you can add a sphere collider on the object you want to be the center of gravity. The collider should encompass the entire area where you want objects to be affected by the gravity of that object. Whenever an object collides with this "sphere of influence", you apply a force to it. You continue to apply a force to it as long as it's inside the sphere of influence.

The gravitational constant you use can be tweaked by you, but the standard one used for calculations in the real world is:

> F = Gm1m2/r2

Spelled out that's:

> Force = Gravitational constant * mass of object 1 * mass of object 2 / the distance between the two objects squared.

Do note that Gravitational constant is not 9.81. That's the acceleration caused by gravity at the earth's surface.
> 21 votes

# Answer
In fact, I'm currently working on a game based around gravity: simply, you place stars to move your player through eliptical orbits and the slingshot effect. I disabled gravity, and used this code:

```
using UnityEngine;
using System.Collections;

public class PlanetGrav : MonoBehaviour {

    //Declare Variables:

//Strength of attraction from your sphere (obviously, it can be any type of game-object)
    public float StrengthOfAttraction;

//Obviously, you won't be using planets, so change this variable to whatever you want
    GameObject planet;

    //Initialise code:
    void Start ()
    {
        //Again, you can change the tag to whatever you want.
        planet = GameObject.FindGameObjectWithTag("Planet");
    }

    //Use FixedUpdate because we are controlling the orbit with physics
    void FixedUpdate () {
        //Declare Variables:

    //magsqr will be the offset squared between the object and the planet
        float magsqr;

        //offset is the distance to the planet
        Vector3 offset;

        //get offset between each planet and the player
        offset = planet.transform.position - transform.position;

            //My game is 2D, so  I set the offset on the Z axis to 0
            offset.z = 0;

            //Offset Squared:
            magsqr = offset.sqrMagnitude;

            //Check distance is more than 0 to prevent division by 0
            if (magsqr > 0.0001f)
            {
//Create the gravity- make it realistic through division by the "magsqr" variable

rigidbody2D.AddForce((StrengthOfAttraction * offset.normalized / magsqr) * rigidbody2D.mass);
            }
        }
    }
}

```

PS The code originally looped through an array of all the planets: this is edited and therefore may not be fully correct. It should be okay though.
> 2 votes

# Answer
There's no need to resort to the gravitational equation. Acceleration due to gravity is constant regardless of mass, so all you want to do is accelerate your small objects towards the large-object each frame.

The code would look something like this:

```
public void FixedUpdate()
{
    rigidbody.velocity += gravitationalAcceleration * Time.fixedTime * (largeObject.transform.position - transform.position);
}

```
> 1 votes

# Answer
I've been working on a similar project based in Zero-G in which I need all game objects to generate and react to both gravitational and electromagnetic force based on their volume, density, mass, energy and conductivity. I'm relatively new to scripting, but I've made a few modifications to the script above to make it work for me in a 3D space (as far as gravity is concerned... almost...):

```
using UnityEngine;
using System.Collections;

public class DynamicWeightAnalysis : MonoBehaviour {

//Declare Variables:
//BBB adding volume calculations
//NOPE
//BBB adding density (...does nothing yet...)
public float density;

//BBB NOPE!

//Strength of attraction from your game-object, ideally this will be derived from a calculation involving the objects volume and density, but for now it's entered from the inspector)
public float RelativeWeight;

//BBB Here, we name our target object (s)
GameObject blockALPHA;

//Initialise code:
void Start ()
{
    //BBB here, we define our target object by searching for its tag (setup in editor)
    blockALPHA = GameObject.FindGameObjectWithTag("Block ALPHA");
}

//Use FixedUpdate because we are controlling the orbit with physics
void FixedUpdate () {
    //Declare Variables:

    //magsqr will be the offset squared between the object and the planet
    float magsqr;

    //offset is the distance to the planet
    Vector3 offset;

    //get offset between each planet and the player
    offset = blockALPHA.transform.position - transform.position;

    //Offset Squared:
    magsqr = offset.sqrMagnitude;

    //Check distance is more than 1 to prevent division by 0 (because my blocks are all 1x1x1 so, any closer than 1 and they'd be intersecting)
    if (magsqr > 1f)
    {
        //Create the gravity- make it realistic through division by the "magsqr" variable

        GetComponent<Rigidbody>().AddForce((RelativeWeight * offset.normalized / magsqr) * GetComponent<Rigidbody>().mass);
    }
}
}

```

As you can see, I'm still working on it, basically all my additions so far, annotated with "BBB", aren't yet functioning as I'd like. But as it stands, it allows my "block ALPHA" objects to interact gravitationally in 3d with other "block ALPHA" objects in a fairly predictable way. (although, when placing two or more blocks, the last one is always the "attractor" and will remain stationary until a collision occurs. which I am working on... help would be appreciated :) ) Hopefully that helps..
> 1 votes

# Answer
Have the planet/big sphere with an circle collider, give it a child. Now, the planet should either be tagged planet or static cosmic object, and the child should be labeled Area of influence. Now the small object should have a rigidbody and a sphere with a isTrigger.

Put a script on the planet with a on enter/enterstay trigger, if it is a sphere of influence it should be pulled towards that.

Else you can do it the other way around. But in any case this would probably be better since you most likely want to make gravitational pull different from planet to planet.
> 0 votes

# Answer
What others said, gravity on unity is only towards a certain direction, so maybe you should instead disable gravity completly and script a force that moves the small sphere towards the huge one.
> -2 votes

# Answer
If you want change gravity for specific plane you could use this script attach to plane.

```
using UnityEngine;

public class ChangeGavityToThisObject : MonoBehaviour
{

    private Quaternion rot;
    private Vector3 gravityValue;

    void Start()
    {
        gravityValue = Physics.gravity;
    }

    void Update()
    {
        rot = GetComponent<Transform>().rotation;
        Physics.gravity = rot * gravityValue;
    }
}

```

GetComponent is in Update, because i want to make possibility to change rotation this plane in game.
> -3 votes

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


title: Unity General Prefab

text:
# Question
Title: Unity General Prefab
I have 2 questions about how i should approach this.

I want to make a 2D game, with alot of different creatures.

Question one: If i have alot of monsters and i'm using ScriptableObjects, since they have very similar variables. How can i make one Enemy prefab which will load the right ScriptableObject information? For example i have an Enemy Prefab, then it will load random monster between: Dragon, Frog, Wolf. How can i achive this without creating 3 new Prefabs for each one and instead load just the right ScriptableObject.

Question two: Should i create new prefab for each monster? Or is approach 1 the right way to do it, if you plan to expand over 100+ creatures.

Thanks

# Answer
> 1 votes
> How can i make one Enemy prefab which will load the right ScriptableObject information?

I would put those scriptable objects on the script which spawns said enemies. Give it two inspector variables: Your general Enemy prefab and an array of your enemy ScriptableObjects. When it instantiates an enemy, it picks a scriptable object from that array at random and assigns it to the newly instantiated enemy. This allows you to set the pool of available enemies for each enemy spawner separately.

But if you want to avoid the hassle of assigning each new enemy type to the enemy spawner after you created it, then Addressables might be an option. The new Addressables system allows you to give each asset in your project an unique name. Scripts can then obtain that asset by using that name.

> Should i create new prefab for each monster? Or is approach 1 the right way to do it, if you plan to expand over 100+ creatures.

Prefab variants could give you the best of both worlds. You can create a general Enemy prefab with all the components all the enemies have in common and with reasonable defaults for all settings on those components. And then you can create prefab variants for all the enemies which are based on that basic Enemy prefab. If you change something at the basic Enemy prefab, then that change will also affect all the variants which didn't override that particular setting.

This solution generates the same amount of clutter as the ScriptableObject solution. In both cases you will have one asset per monster in your project folder. But they give you a lot more flexibility because prefab variants allow you to override properties you didn't think about when you programmed your ScriptableObject. Like attaching new components or even new child game-objects to individual prefabs.

Oh, and you can even create prefab variants inheriting from prefabs which are variants themselves. This can be useful if you have families of monsters which share some properties but have a lot of properties in common (like palette swaps).

# Answer
> 0 votes
You need a monobehavior on the prefab that has your ScriptableObject as a variable Whenever you need to access any stats, you read them from the referenced scriptable object

Instantiate will return you a reference to the new GameObject, you can then use getComponent to access the Monobehavior on the newly spawned monster, and set the desired ScriptableObject to the variable.

You can either go on, and set up sprites and such in the same function, or use the start function of the monobehavior on the prefab to do the remaining set up, reading data from the scriptableObject.

---
Tags: unity
---


# Question
Title: How to correctly reset vertex attributes after modification
I am trying to use the same vertex shader for two different use cases to preserve memory, but I am having issues where the modifications of one shader run are passed on to the next run, even after being reset. Specifically, I am trying to use the shader to both show a regular texture, while also modifying the vertex attributes in some cases to show portions of a texture. The problem is, this "cropping" of the texture is applied to the texture that should be shown 100%.

Here is what it looks like, where the sprite on the right is drawn first:

Both textures are showing only a portion of their actual images, but only the one on the left should be doing so. Strangely, the one on the right shows a full texture for a second, before being replaced with what is shown. This tells me that the vertex attributes of the first sprite are modified by the second (left) sprite, but I don't know how to reset them. Here is my vertex shader:

```
#version 330 core
layout (location = 0) in vec3 aPos;
layout (location = 1) in vec2 aTexCoord;

out vec2 TexCoord;

uniform mat4 transform;
uniform mat4 view;
uniform mat4 projection;

void main()
{
    gl_Position = projection * view * transform * vec4(aPos, 1.0);
    TexCoord = aTexCoord;
}

```

Here is how I modify the vertex attributes:

```
void setSelection(Quad selection) {
        vertices[3] = selection.x + selection.w;
        vertices[4] = selection.y + selection.h;
        vertices[8] = selection.x + selection.w;
        vertices[9] = selection.y;
        vertices[13] = selection.x;
        vertices[14] = selection.y;
        vertices[18] = selection.x;
        vertices[19] = selection.y + selection.h;
};
...
float vertices[20] = {
          // positions         // texture coords
          0.5f,  0.5f, 0.0f,   1.0f, 1.0f, // top right
          0.5f, -0.5f, 0.0f,   1.0f, 0.0f, // bottom right
         -0.5f, -0.5f, 0.0f,   0.0f, 0.0f, // bottom left
         -0.5f,  0.5f, 0.0f,   0.0f, 1.0f  // top left
};

```

This code changes the shown vertex array's texture coordinates. They are applied with this code:

```
void Sprite::render() {
    // Set shader uniforms if the shader is initialized
    if (shader != nullptr) {
        applyTransforms();
        shader->useShader();
        shader->setMat4("transform", trans);
        shader->setVec4("color", color.asVec4());
        shader->setMat4("view", Camera::getLookMat());
    }

    glBindBuffer(GL_ARRAY_BUFFER, vbo);
    glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(vertices), vertices);
    glBindBuffer(GL_ARRAY_BUFFER, 0);

    tex->bind();

    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo);
    glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
}

```

However, if I have two objects (both instances of the same class), one with a modified array (left) and one with an unmodified array (right, as shown in the picture), the modified array takes precedence, and I can't figure out how to keep it from being changed without using a different shader object, but I don't want to do that. Is there anything I am missing that would allow me to change the attributes in between draw cycles?

**ADDITION 1** Here is the entire `Sprite` class (right image is an object):

```
Sprite::Sprite(std::shared_ptr<Texture> texture, std::shared_ptr<Shader> shader) : tex(texture), color(1u, 1u, 1u, 1u), shader(shader) {
    glInit();
}

Sprite::Sprite(const std::string& path, std::shared_ptr<Shader> shader) : tex(new Texture(path)), color(1u, 1u, 1u, 1u), shader(shader) {
    glInit();
}

Sprite::~Sprite() {
    glDeleteVertexArrays(1, &vao);
    vao = NULL;
    glDeleteBuffers(1, &vbo);
    vbo = NULL;
    glDeleteBuffers(1, &ebo);
    ebo = NULL;
}

void Sprite::setColor(RGBA color) {
    this->color = color;
}

void Sprite::render() {
    // Set shader uniforms if the shader is initialized
    if (shader != nullptr) {
        applyTransforms();
        shader->useShader();
        shader->setMat4("transform", trans);
        shader->setVec4("color", color.asVec4());
        shader->setMat4("view", Camera::getLookMat());
    }

    glBindBuffer(GL_ARRAY_BUFFER, vbo);
    glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(vertices), vertices);
    glBindBuffer(GL_ARRAY_BUFFER, 0);

    tex->bind();

    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo);
    glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
}

void Sprite::glInit() {
    // GL initialization
    // Buffers
    glGenBuffers(1, &ebo);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indicies), indicies, GL_STATIC_DRAW);

    glGenVertexArrays(1, &vao);
    glBindVertexArray(vao);

    glGenBuffers(1, &vbo);
    glBindBuffer(GL_ARRAY_BUFFER, vbo);
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);

    // Verticies
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * FLOAT_SIZE, (void*)0);
    glEnableVertexAttribArray(0);

    glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5 * FLOAT_SIZE, (void*)(3 * FLOAT_SIZE));
    glEnableVertexAttribArray(1);
}

```

Here's the header:

```
class Sprite : public Object{
public:
    Sprite(std::shared_ptr<Texture> texture, std::shared_ptr<Shader> shader = nullptr);

    Sprite(const std::string& path, std::shared_ptr<Shader> shader = nullptr);

    ~Sprite();

    void setColor(RGBA color);

    inline RGBA getColor() const { return color; };

    virtual void render();

    inline std::weak_ptr<Texture> getTexture() const { return tex; };

protected:
    // Pointers for texture and shader (if initialized)
    std::shared_ptr<Texture> tex;
    std::shared_ptr<Shader> shader;

    GLuint vbo = 0, vao = 0, ebo = 0;

    RGBA color;

    float vertices[20] = {
          // positions         // texture coords
          0.5f,  0.5f, 0.0f,   1.0f, 1.0f, // top right
          0.5f, -0.5f, 0.0f,   1.0f, 0.0f, // bottom right
         -0.5f, -0.5f, 0.0f,   0.0f, 0.0f, // bottom left
         -0.5f,  0.5f, 0.0f,   0.0f, 1.0f  // top left
    };

    GLuint indicies[6] = {
        0, 1, 3,
        1, 2, 3
    };

    // Initialize GL objects
    virtual void glInit();
};

```

And here's the subclass (left image, header only):

```
class SpriteSheet : public Sprite {
public:
    SpriteSheet(std::shared_ptr<Texture> texture, std::shared_ptr<Shader> shader = nullptr) : Sprite(texture, shader) {};

    SpriteSheet(const std::string& path, std::shared_ptr<Shader> shader = nullptr) : Sprite(path, shader) {};

    ~SpriteSheet() { Sprite::~Sprite(); };

    void setSelection(Quad selection) {
        vertices[3] = selection.x + selection.w;
        vertices[4] = selection.y + selection.h;
        vertices[8] = selection.x + selection.w;
        vertices[9] = selection.y;
        vertices[13] = selection.x;
        vertices[14] = selection.y;
        vertices[18] = selection.x;
        vertices[19] = selection.y + selection.h;
    };
};

```

The `Object` class only contains positional vectors, and is therefore not relevant. `RGBA` and `Quad` are abstractions of `glm::vec4`.

**EDIT 2** I have figured out that if two `SpriteSheet` objects are declared, the one declared last will be the one that takes priority with its texture coordinates being applied to all objects, regardless of render order.

# Answer
It turns out that before modifying vertex attributes (VBOs), I had to rebind the VAO of the created object. The modified render code looks like this:

```
void Sprite::render() {
    // Set shader uniforms if the shader is initialized
    if (shader != nullptr) {
        applyTransforms();
        shader->useShader();
        shader->setMat4("transform", trans);
        shader->setVec4("color", color.asVec4());
    }
    glBindVertexArray(vao);
    // ^ This is very important

    glBindBuffer(GL_ARRAY_BUFFER, vbo);
    glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(vertices), vertices);
    glBindBuffer(GL_ARRAY_BUFFER, 0);

    tex->bind();

    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo);
    glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
}

```
> 2 votes

---
Tags: opengl, c++, glsl
---


# Question
Title: How do you draw a random irregular polygon in java? (Asteroids)
I am coding an Asteroids game in Java. In the real arcade game, asteroids are made of irregular shapes like this:

When I code, I can only set asteroids to 1 or another specific shape, like this:

I want to make all of the asteroids in my game of totally randomly generated shapes, and I am already tired of designing specific shapes of my own. Here is a snippet of my code that generates the asteroid's shape. P.S: The image does not show it, but I am using the `Polygon` class and constructor which only enables me to input 2 int\[\]s and a number of sides.

```
   public void makeShape() {
    int x = (int) this.x;
    int y = (int) this.y;
    this.shape = new Polygon(new int[]{x - 15, x - 30, x - 10, x - 13, x,x + 10, x + 10}, new int[]{y - 30, y - 15, y + 5, y + 30, y + 35, y + 30, y}, 7);
}

```

I have tried putting all of the variables on `Math.random()`, but it outputs nothing but a scribble, even if I were using the `Polygon` class.

# Answer
> 1 votes
You could let a point travel on a circle in discreet steps and adjust the radius for each step, that would make it look jagged and irregular.

Something like this might work for you:

```
/**
 *
 * @param px The center X of the shape
 * @param py The center Y of the shape
 * @param numberOfNodes How many dents the shape can have.
 * @param minRadius Radius of the deepest valley
 * @param maxRadius Radius of the tallest mountain
 * @return Some shape
 */
private Polygon makeShape(int px, int py, int numberOfNodes, double minRadius, double maxRadius) {
    // Split a full circle into numberOfNodes step, this is how much to advance each part
    double angleStep = Math.PI * 2 / numberOfNodes;
    Polygon shape = new Polygon();
    for(int i = 0; i < numberOfNodes; ++i) {
        double targetAngle = angleStep * i; // This is the angle we want if all parts are equally spaced
        double angle = targetAngle + (rnd.nextDouble() - 0.5) * angleStep * 0.25; // add a random factor to the angle, which is +- 25% of the angle step
        double radius = minRadius + rnd.nextDouble() * (maxRadius - minRadius); // make the radius random but within minRadius to maxRadius
        // calculate x and y positions of the part point
        double x = Math.cos(angle) * radius;
        double y = Math.sin(angle) * radius;
        shape.addPoint((int)x, (int)y);
    }
    shape.translate(px, py);
    return shape;
}

```

`px` and `py` correspond to your `this.x` and `this.y`

---
Tags: java, mathematics, graphics, swing
---


# Question
Title: Do empty Update() methods get executed and slow down the game while playing?
From an optimization point of view, is it best practice to delete the predefined update() methods in all my C# scripts if there is no code inside them ?

On hundreds/thousands of GameObject(s) with Update() {} empty, does the game slow down ? Can they be left empty or is it better to delete them ?

# Answer
> 5 votes
As stated in the Unity Blog post 1000 Update Calls:

> \[If you have empty MonoBehaviour messages\], all these methods will be called each frame for all your scripts, mostly doing nothing at all!
>
> One might ask why should anyone care about an empty method? The thing is that these are the calls from native C++ land to managed C# land, they have a cost. Let’s see what this cost is.

Check out the full post for the details of all the steps Unity goes through for each script that has an Update function. But it's also a few years old, so how do we know if that still applies?

As Tyyppi\_77 says, the very best way to answer "does X have a performance cost?" is to **profile your game** or a toy test scene with and without X, and compare the results. That way you find out the real, evidence-backed answer instantly, without waiting on hearsay from Internet strangers like me.

Here's what my profiler shows when I put several hundred game objects with an empty Update in a built Unity game, using a development build (so it's possible this is optimized further in a release build)

As you can see, the cost is miniscule - about a tenth of a microsecond apiece - so this likely isn't anywhere *near* the top of your list of optimization priorities. But since these functions are easy to delete with no risk to the rest of the behaviour of your game, it's still good code hygiene to clean up methods you're not using.

This both makes your runtime leaner and faster, and is a useful signal to the development team that this method is not a stub that needs work, but something you've actively decided is unnecessary.

The cost is significantly higher when running in-editor (closer to a fifth of a microsecond apiece in my quick test), due to the extra safety checks and instrumentation Unity uses there, so you might also consider this a slight quality-of-life improvement for your day-to-day testing work.

---
Tags: unity, optimization
---


# Question
Title: How to version control game balance data stored in spreadsheets
Is there any good workflow/tooling for having good version control on spreadsheets for game data? Ideally something that supports branching or merging.

Google spreadsheets allow people to edit data live so it makes "merging" easy, but it gets really hard to link the data that's live in a spreadsheet with the current version of the game in source control (ie. your git repo or other)

Conversely, with a local tool like Excel you at least have actual files that can be stored in the repo, but there doesn't seem to be good tooling for merging different versions of them.

With all that in mind, how can we ensure that a specific branch in a game repo can be linked to a specific version of the game data, and how can we allow people to work on different "branches" of game data in parallel while still keeping the ability to source control?

# Answer
> 1 votes
1. You can store in (any) VCS text-only version of your spreadsheets (CSV, f.e.), but work only with original (binary XLSX) presentation of data (edit/update|export|commit)
2. You can use non-default tools, which can diff|merge your spreadsheets "as is" and have standard workflow

---
Tags: tools, data, balance, version-control
---


# Question
Title: Gravity CharacterController on moving platform
I have a third person character witha character controller. In the C# Player script I set the move direction like this which works pretty nice to simulate gravity

```
private Vector3 _moveDirection = Vector3.zero;

private float Gravity = 20.0f;

void Update()
{
 // ....
_moveDirection.y -= Gravity * Time.deltaTime;

_characterController.Move(_moveDirection * Time.deltaTime + mExternalMovement);
}

```

The mExternalMovement (also Vector3) I set when the player is on a platform that moves. This works as well for platforms the move e.g. from left to right. But when I use the same for platforms that move up and down the player is like trembling- because of the gravity that is always set for the y movement.

But I have to set the gravity as well when standing on the platform.... any ideas?

# Answer
Add a Rigidbody and use the gravity there?
> -1 votes

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


title: How to program destructibles?

text:
# Question
Title: How to program destructibles?
I'm thinking about programming a 2d simulation of a spaceship that takes damage depending on where the projectile came from (e.g. from behind - engine, from the front - lasers, sides - hull, etc.). When a given part is below a certain durability factor it explodes into physics simulated particles. What is a good way of storing such particles (ship built out of parts, parts built out of particles, e.g. 6px triangles) taking into consideration the following:

* different parts have different shapes,
* it might be needed to add more parts in the future,
* possibility of avoiding a pixel-perfect projectile-to-part collision detection,
* the spaceship should be affected by physics but particles shouldn't unless exploding.

# Answer
A rational approach might be to simplify your problem. This is a game, so most of the time there is no need for 100% accurate physics.

Instead of tracking every single component that makes your ship, you can instead prepare several *damaged ship* models and swap then on the fly as it gets more and more damage.

When you swap the models, you could spawn some particles that reflect what probably got damaged at that *life* level of the ship.

By just loading a model, you save the extra time it would have taken per frame to calculate collisions of each piece of the ship with each other (among other things for all the objects), you also have less code to deal with. This will provide less opportunities for bugs and from a gameplay perspective might give you similar output like what you originally wanted.

Note that if your gameplay totally depends on accurate simulation of destruction, then of course this approach will not work.
> 2 votes

# Answer
I ended up not "keeping the particles together" as I originally wanted because it made literally no sense computation-wise but using a bitmap of a white silhouette on a black background as a mask for each of the spaceship modules instead. A whole ship would be made of an array of those bitmaps stuck together. Whenever a module got hit I'd render an irregular black star of rough `radius = blastRadius` on that bitmap to mark an explosion (effectively removing a blackened part of the module on next frame render) and then just made a tiny simulation of some particles flying away to make explosions look as intended in the opening question. Every 500ms or so I make a calculation of the pixels left in each bitmap and when white pixels are below 60% of the original amount I "explode" the whole part. It took some time to figure out but was fun to code and works great, even on my old mobile.
> 1 votes

---
Tags: collision-detection, physics, pygame, data-structure, particles
---


# Question
Title: How to handle data for a competitive multiplayer games
I am kinda new to Multiplayer Games and I am really wondering how I should handle my data

Should each player send and update their data to the database (server) everytime one of their essential variables changes (like health or ingame currencies), or should they save the data as long as the game is running and then update the data all at once at the end of, lets say, each round?

I was thinking about using Firebase and Unity and here's a scenario:

Let's say 2 players connect to a game. Then one of them gets damage and the other one gets gold. Does the data change get sent to the FireBase Database immediatly or should I just update everything when the round ends/they disconnect?

# Answer
> 0 votes
I kind of cover this a little here. Let's see if I can expand it a bit for your situation.

Firebase Realtime Database has a couple of features you'll want to investigate. The first is that, by default, it tries to cache everything locally. That means that if you listen to the ValueChanged event, you'll always get the cached value first (sometimes null) and eventually get an update from the server when it syncs. You can also write data with a transaction, which works in concert with this cache. As data syncs to/from the server, you'll be able to first run your change against your local cache and eventually against the source of truth (the server) if it differs. If you're listening to `ValueChanged` to update your local game state and UI, you can minimize issues relating to users being offline (even for extended durations).

This won't be a silver bullet though, you still have to be able to construct transactions knowing that the user may have gotten into an impossible state and have some way to roll back gameplay (say if you tried to spend money you don't have).

It's worth also learning a bit about the rules system. You can get super complex with these, basically little JavaScript expressions that you can use to validate your database logic. It can get a little unwieldy if the rules get complex, but you can run them offline if you're wanting to write unit tests around critical rules (such as invalid changes to damage or gold).

One last trick is that you might want to build a sort of transaction log into your game. Rather than strictly saying "set player x's health to 2", say "at time x I'm dealing 2 damage" (and doing either both, or using a Cloud Function to turn the log into RTDB values to listen to). You can use ServerValue.Timestamp as a placeholder for "the time when this message syncs to the server" and use database rules as a way of figuring out the order actions resolve in (ex: "you can only write if the timestamp is newer than the last one in the log"). Then you can stop applying damage after one player dies, resolve rules with gold, &c monotonically. If a user was offline for a bit, this could get a little funky so it's entirely up to your game design.

Which (if any of these) work depends 100% on your game, but I hope I've helped a little!

---
Tags: unity, data-structure, databases, data, realtime
---


# Question
Title: How to communicate to an inventory item which character it's being used on?
Currently, I have an `Inventory` that is a `ScriptableObject`, which means it's not tied to any specific game object or player character. I just drag it into a `MonoBehaviour` if I would like expose the data of the inventory.

I have created an `InventoryUI`, which is a `MonoBehaviour` attached to a `GameObject` in my scene, and I assign the `Inventory` SO to it.

The `InventoryUI` contains button `GameObjects` with an `InventorySlot` script, to which I assign the item each slot is holding.

Everything works fine. When I click on one of the `InventorySlot` buttons, I'm able to call item methods, such as `UseItem`.

My problem is if the the item is a potion, for example. **How can i add health to the player?** Of course I could add reference to the player to the slot. But that will reference player repeatedly over 25 slots.

# Answer
Myself, I'd let the `InventoryUI` script own the interaction with the inventory.

When a player opens the `InventoryUI`, you call something like `InventoryUI.ShowInventoryFor(PlayerCharacter character)`.

This procedure handles any initial setup of the menu (populating the slots, etc.) and caches the character it was given as its `currentUser` member variable.

Each of the UI buttons on the menu is wired up to call `InventoryUI.UseItemInSlot(int slotID)` when clicked. That centralizes all of the item use actions onto the one script that knows who's using the menu.

Now the `InventoryUI` can fetch the corresponding item in your inventory structure, and call `inventoryItem.UseItemOn(currentUser)`, passing its knowledge of who is using the item through to the function that performs the item's action.

Finally, that item receives a reference to the character it should modify - by giving it more health, etc.

Doing it this way, you might not need your `InventorySlot` script at all. The buttons in the menu can be just plain buttons, with the knowledge of the meaning behind each button provided by the `InventoryUI` itself.
> 1 votes

---
Tags: unity, c#, gui, software-engineering, inventory
---