# Question
Title: How to improve performance of LiBGDX Android app?
After creating a few bodies and a map with collisions, the app performance clearly goes down. However, RAM and CPU don't seem fully stuck, but the game experience is horrible nonetheless.

GameScreen class:

```
public class GameScreen implements Screen {
    Main main;
    Joystick joystickL, joystickR;
    public static Player player;
    public static Array<Bullet> bullets;
    public static float angle;
    private Text ammo_view;
    public static Array<Enemy> enemies;
    private TiledMap map;
    private OrthogonalTiledMapRenderer mapRenderer;
    public static World world;
    private Box2DDebugRenderer b2dr;
    private HitContactListener hcl = new HitContactListener();
    public GameScreen(Main main){
        this.main = main;
    }
    @Override
    public void show()  {
        loadActors();
        Gdx.input.setInputProcessor(new InputProcessor() {
                                            @Override
                                            public boolean keyDown(int keycode) {
                                                return false;
                                            }

                                            @Override
                                            public boolean keyUp(int keycode) {
                                                return false;
                                            }

                                            @Override
                                            public boolean keyTyped(char character) {
                                                return false;
                                            }

                                            @Override
                                            public boolean touchDown(int screenX, int screenY, int pointer, int button) {
                                                screenY = (Gdx.graphics.getHeight() - screenY);
                                                multitouch( screenX, screenY, true, pointer);
                                                return false;
                                            }

                                            @Override
                                            public boolean touchUp(int screenX, int screenY, int pointer, int button) {
                                                screenY =  (Gdx.graphics.getHeight() - screenY);
                                                multitouch(screenX, screenY, false, pointer);
                                                return false;
                                            }

                                            @Override
                                            public boolean touchDragged(int screenX, int screenY, int pointer) {
                                                screenY = (Gdx.graphics.getHeight() - screenY);
                                                multitouch(screenX, screenY, true, pointer);
                                                return false;
                                            }

                                            @Override
                                            public boolean mouseMoved(int screenX, int screenY) {
                                                return false;
                                            }

                                            @Override
                                            public boolean scrolled(float amountX, float amountY) {
                                                return false;
                                            }
                                        }
            );
        }

    public void loadActors() {
        bullets = new Array<Bullet>();
        enemies = new Array<Enemy>();
        //MAP
        b2dr = new Box2DDebugRenderer();
        world = new World(new Vector2(0, 0), false);
        world.setContactListener(hcl);
        map = new TmxMapLoader().load("map/kartapapka/суперготовая карта.tmx");
        mapRenderer = new OrthogonalTiledMapRenderer(map, 1.5f);
        MapLoader.buildShapes(map.getLayers().get("Obstacles").getObjects(), world);

        //PLAYER
        player = new Player(Main.mainChar_ak,  new Vector2(52.8f, 7.5f).scl(PPM), 7, world);
        player.getGun(new Ak(player));

        //GRIPS
        joystickR = new Joystick(Main.joystickImg, Main.gripImg, new Vector2((float) (Main.WIDTH - (Main.WIDTH * 0.15)), (Main.HEIGHT / 3) / 2 + (Main.HEIGHT / 3) / 4), Main.HEIGHT / 3);
        joystickL = new Joystick(Main.joystickImg, Main.gripImg, new Vector2((float)(Main.WIDTH - (Main.WIDTH * 0.85)), (Main.HEIGHT / 3) / 2 + (Main.HEIGHT / 3) / 4), Main.HEIGHT / 3);

        //FIRST BULLET TO AVOID SPAWN TROUBLES
        bullets.add(new Bullet(new Vector2(), new Vector2(), 0, 0, world));
        //world.destroyBody(bullets.get(0).body);

        //ENEMIES GENERATION
        enemies.add(new Enemy(new Sprite(new Texture(Gdx.files.internal("main_sprites/enemy_handgun.png"))), new Vector2(21.6f,27f).scl(PPM), 6, world));
        enemies.add(new Enemy(new Sprite(new Texture(Gdx.files.internal("main_sprites/enemy_handgun.png"))), new Vector2(61.4f,18f).scl(PPM), 6, world));
        enemies.add(new Enemy(new Sprite(new Texture(Gdx.files.internal("main_sprites/enemy_handgun.png"))), new Vector2(80.6f,35f).scl(PPM), 6, world));
        enemies.add(new Enemy(new Sprite(new Texture(Gdx.files.internal("main_sprites/enemy_handgun.png"))), new Vector2(58f, 38.4f).scl(PPM), 6, world));
        enemies.add(new Enemy(new Sprite(new Texture(Gdx.files.internal("main_sprites/enemy_handgun.png"))), new Vector2(31.5f, 39f).scl(PPM), 6, world));
        enemies.add(new Enemy(new Sprite(new Texture(Gdx.files.internal("main_sprites/enemy_handgun.png"))), new Vector2(39.2f, 54f).scl(PPM), 6, world));

        //GIVING GUNS TO ENEMIES
        for (int i = 0; i < enemies.size; i++) {
            enemies.get(i).getGun(new Enemy_handgun(enemies.get(i)));
        }

        //FONT GENERATION
        ammo_view = new Text("fonts/ammo.ttf",(float) Main.WIDTH - 100, (float) Main.HEIGHT - 80);

        //ADDING ACTORS
        Main.stage.addActor(joystickR);
        Main.stage.addActor(joystickL);
        Main.stage.addActor(ammo_view);
        Main.stage.addActor(fm);
    }

    @Override
    public void render(float delta) {
        world.step(1 / 45f, 6, 2);
        Gdx.gl.glClearColor(1,0,1,1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
        gameUpdate(delta);
        main.shapeRenderer.setProjectionMatrix(main.camera.combined);
        main.camera.update();
        main.camera.position.set(player.body.getPosition().x * PPM, player.body.getPosition().y * PPM, 0);
        //MAP RENDERING
        mapRenderer.setView(main.camera);
        mapRenderer.render();
        b2dr.render(world, new Matrix4(main.camera.combined).scl(PPM));
        Main.batch.setProjectionMatrix(main.camera.combined);
        Main.batch.begin();
        gameRender(Main.batch);
        Main.batch.end();
        //STAGE DRAW
        Main.stage.act(delta);
        Main.stage.draw();

        main.shapeRenderer.begin(ShapeRenderer.ShapeType.Filled);
        main.shapeRenderer.setColor(Color.GRAY);
        for (int i = 0; i < bullets.size; i++) {
            main.shapeRenderer.circle(bullets.get(i).position.x, bullets.get(i).position.y, bullets.get(i).size);
        }
        main.shapeRenderer.end();

    }

    @Override
    public void resize(int width, int height) {
        main.camera.viewportWidth = width;
        main.camera.viewportHeight = height;
        main.camera.update();
    }

    @Override
    public void dispose() {
        map.dispose();
        mapRenderer.dispose();
        main.dispose();
    }
    public void gameRender(SpriteBatch batch) {
        //PLAYER ROTATION
        if (joystickL.direction.angleDeg() != 0) angle = joystickL.direction.angleDeg();
        if (joystickR.direction.angleDeg() != 0) angle = joystickR.direction.angleDeg();
        player.img.setRotation(angle);
        ammo_view.update(player);

        //ENEMY ROTATION
        for(int i = 0; i < enemies.size; i++) {
            enemies.get(i).img.setRotation(enemies.get(i).direction.angleDeg());
            enemies.get(i).draw(batch);
        }

        player.draw(batch);
    }

    private void sweepDeadBodies() {
        Array<Body> bodiesToDestroy = new Array<>(hcl.getBodiesToDestroy());
        Set<Body> bodiesToDestroySet = new HashSet<>();
        for (Body body : bodiesToDestroy) {
            if (body.getUserData() != null && body != null) {
                bodiesToDestroySet.add(body);
            }
        }
        //System.out.println(bodiesToDestroySet);
        for (Body body : bodiesToDestroySet) {
            world.destroyBody(body);

        }
    }
    public void gameUpdate(float delta){
        for(int i = 0; i < enemies.size; i++) {
            //enemies.get(i).player_detection(player);
            enemies.get(i).update();
            enemies.get(i).handgun.update(joystickR);
            bullets.addAll(enemies.get(i).handgun.getBulletsArray());
        }
        bullets.addAll(player.gun.getBulletsArray());
        Gdx.app.postRunnable(new Runnable() {
            @Override
            public void run() {
                sweepDeadBodies();
            }
        });
        player.update();
        //sc.update();
        player.direction.set(joystickL.direction);
        player.gun.update(joystickR);
        for (int i = 0; i < bullets.size; i++) {
            //bullets.get(i).direction.rotateDeg(bullets.get(i).direction.angleDeg() + (float)getRandomDoubleBetweenRange(-10, 10));
            bullets.get(i).update();
        }
        if (player.gun.isFire && player.gun.ammo > 0) {
            if (Rumble.getRumbleTimeLeft() > 0){
                Rumble.tick(delta);
                main.camera.translate(Rumble.getPos());
            }
        }

        hit_detection();
    }
    private void multitouch(float x, float y, boolean isDownTouched, int pointer) {
        for (int i = 0; i < 5; i++) {
            joystickL.update(x, y, isDownTouched, pointer);
            joystickR.update(x, y, isDownTouched, pointer);
        }
    }
    private void hit_detection() {
        for (int j = 0; j < enemies.size; j++) {
            for (int i = 0; i < bullets.size; i++) {

                //HIT DETECTION
                    if (bullets.get(i).bounds.overlaps(enemies.get(j).bounds) && enemies.get(j).isAlive) {
                        bullets.removeIndex(i--);
                        enemies.get(j).die();
                    }
            }
        }
    }
}

```

I want to increase efficiency or follow any other suggestions. I can append any other classes, if necessary.

# Answer
* You are loading 6 times the same texture of the enemy, you can load it only once and give the reference to your enemy instances.
* You should use the `AssetManager` to store and load your textures.
* Try to draw as much things with one `SpriteBatch` as possible, you can merge some of the batch processes to one.
* Check if the map you are loading isn't too big. If it's too big, try to render/update visible tiles only.
> 0 votes

---
Tags: java, libgdx, android, box2d, performance
---


# Question
Title: How do I save the player's level progress in GameMaker?
My game, made in **GameMaker**, consists of various rooms (levels) through which you go on progress. So, imagine I'm on level 7, and I leave the game, it goes back to room 1. Also, the only thing I have to save is just the level I'm in, I don't want to keep any coins or else!

Does anyone know how to stop and save the game and go back to it later on? I'm programming using the built-in GML scripting language.

Thank you so much in advance.

# Answer
> 1 votes
Games are applications, and application data in memory is non-persistent. Then, if you want to keep using previously seen data, you must first save it somewhere. Regardless of file format, compression, encoding, encryption... You are saving information on a device for subsequent retrieval.

A simple way to store the level you're currently in is via INI files. They allow you to store small pieces of information and retrieve them later using key-value pairs.

Let's say your game is designed (i.e. you want it to) to open a file named **progress.ini**, which is an INI file located in the game's working directory. You can, for example, create such a file dynamically (if it doesn't exist yet) when the game starts via the Game Start Event, and it will be saved where your game can access it.

Then, a simple implementation would be as follows:

* When the game starts, try to open the file **progress.ini** and read the value saved in the key `last_level` in the section `[levels]`.
    + *If the value exists*: update the internal game variable for the current level, and make the game continue from that room.
    + *If the value OR the section OR the file doesn't exist*: use a default value ("level 1" or similar), and update the internal game variable for the current level. The game will continue from that level (which, coincidentally, is the first level of your game).
* Every time the player progresses through the game (e.g. at the end of a level, before the next starts), save the current level index in an INI file named **progress.ini** (the same name as the file we loaded before) so that the level progress will persist even if the game closes unexpectedly.

---
Tags: game-design, game-maker, savegame, game-maker-studio-2
---


# Question
Title: How to implement diminishing returns for multiplicative character stats?
I'm very bad at math, ridiculously so. I'm making attributes that work as multipliers.

1 Agility means : `animation speed * agility`, `movement speed * agility` and dodge skill cooldowns are divided by agility

Which means that 1 point in agility grants you the basic and default movement and cooldowns for evasive and dodging skills.

1 Strength means :

Your bodyweight is multiplied by Strength since in real life weight is the base of strength.

So how much weight you can lift, push, throw, carry and hold is literally just your mass multiplied by strength.

A character of 60kg with strength of 1 can only lift 60kg at most, which is representative of light skinny and weak people in real life.

And also since pulling and holding applies, a character with a strength less than 1 will not be able to climb or hold themselves onto ledges, because 1 means you can lift up to your own bodyweight minimum.

**Math question here**

I want attributes to be increased by spending points. Each point at first increases the value of an attribute from let's say 1.0 to 1.1.... and then each subsequent point loses value and being less effective, let's say 70% as effective as the previously spent point.

So the first point will be 0.1 and the second 0.07 and so on just as an example...

How can I tell a software to do that?

# Answer
> 2 votes
It sounds like you're looking for the `pow` function, that raises a number to a power.

If we've already spent `n` points to increase this attribute, the increment the next point will add is `0.1 * pow(0.7, n)`

Calling your first `0.1` increment `a`, and calling `0.7` `r` for the "ratio" between consecutive increments, that means that spending `n` points will bring you to a total attribute value of:

$$1 + a + a r^1 + a r^2 + ... + a r^{n-1} = 1 + \sum^{n-1}\_{k = 0}ar^k$$

This gives us a geometric series, which we can express in closed form as:

```
totalAttribute = 1.0 + a * (1.0 - pow(r, n)) / (1.0 - r)

```

Here's the table of stats that gives us:

| Points Spent | Total Attribute |
| --- | --- |
| 0 | 1 |
| 1 | 1.1 |
| 2 | 1.17 |
| 3 | 1.219 |
| 4 | 1.2533 |
| 5 | 1.27731 |
| 6 | 1.294117 |
| 7 | 1.3058819 |
| 8 | 1.31411733 |
| 9 | 1.319882131 |
| 10 | 1.323917492 |
| 11 | 1.326742244 |
| 12 | 1.328719571 |
| 13 | 1.3301037 |
| 14 | 1.33107259 |
| 15 | 1.331750813 |
| 16 | 1.332225569 |
| 17 | 1.332557898 |
| 18 | 1.332790529 |
| 19 | 1.33295337 |
| 20 | 1.333067359 |

We can also get the maximum possible attribute value this converges toward:

```
maxAttribute = 1.0 + a / (1.0 - r)

```

For `a = 0.1` and `r = 0.7` that gives 1⅓, so your strongest character will only ever be able to lift 33% more than your weakest character. As you can see, we're already pretty much there after spending 12 points, and the rest is just whittling down that rounding error. So this diminishing return schedule might be a bit aggressively tapered if you want to keep players feeling value in each point after dozens of upgrades.

# Answer
> 1 votes
You need a distinction between **primary stats** and **secondary stats**.

Primary stats do nothing by themselves in the game world, they just influence secondary stats. For example, raising your **Strength** (primary stat) increases your **Melee Attack** (secondary stat).

The player will distribute points between primary stats. For example, he can choose to put 1 point in Strength, raising it from 15 to 16.

You then define Melee Attack as follow:

```
Melee Attack = Strength ^ (1/2)

```

The X axis represents Strength here, while the Y axis represents Melee Attack. As you can see:

* going from 0 to 4 Strength raise Melee Attack from 0 to 2.
* going from 4 to 16 Strength raise Melee Attack from 2 to 4.

So that's an example of diminishing returns. Obviously, you need to tweak the formula for your own needs.

---
Tags: mathematics, rpg, design-patterns, godot-3
---


# Question
Title: How to make texture look sharper and more detailed, when you look closer?
I have this material of a rocky wall. At far it seems okay, but often when walking close by it's obvious that the texture actually has not enough resolution and seems way too blurry.

Far: https://imgur.com/a/LsczzhF

Close: https://imgur.com/a/gcJMQUe

I remember some techniques used in Serious Sam 1 game, where they added some kind of noise layer on the textures which managed to give impression of better detailed textures.

How can I achieve effect of a super high resolution texture when player looks closer?

In game engine I'm using I can use/write shaders, materials next passes, etc.

I though about using triplanar normal textures blending, also with albedo textures blending too. With the help of triplanar texture coordinates I can use small seamless detailed textures that can blend with the original texture, but I lack knowledge of algorithms for blending normal maps, albedo textures without distorting them.

# Answer
> 4 votes
This is usually solved using detail maps. (See e.g. Unity's documentation about the technique here)

For this you make a tiling texture with fine-scale detail, either as an albedo (surface colour) or normal map, or both. This could be random noise for a rough sandy surface, or fractal cracks and pitting for rock or crystal, scuffs for metal, thread weaves for fabric, pores for skin, etc.

You choose this texture so it has no large-scale variation: when crunched down to a smaller mipmap, it blurs out to an average grey (or average blue for a normal map - meaning no left/right/up/down bias). In signal processing terms, we take a "high pass" to the texture and keep only the higher-frequency components. Your main textures will provide the low frequencies, and this will fill in the high frequencies they're missing above their texture resolution.

In your shader, you multiply your usual UV coordinates by some number larger than one when sampling this detail map, so that it tiles multiple times for each repeat of your main texture (and crucially so that its texels appear smaller/finer than your main texture's texels). Then mix the detail sample into the regular albedo colour or normal direction of your surface at that point.

When you're far away from the surface, this fine detail blurs out to nothing, thanks to the averaged-out mips, and you see your original designed surface appearance as-is. You can even use a shader branch or LoD version of the model to skip the detail map code beyond a certain distance. As you get closer, the fine detail in the detail map starts to show up, and helps break up the texture filtering artifacts you see in the main map, making it appear as though the texture is much more detailed than it is.

# Answer
> 0 votes
The texture you showed is simply too small. If it would be in 4K you would be able to get really close and still have the illusion of detail. The minimum is now (2023) anything that can be called "HD" (Ca. 2K).

---
Tags: shaders, textures, level-of-detail
---


# Question
Title: How do I change a game's description in Roblox?
In the Roblox documentation for basic place settings, it mentions how you can change the name and description of your game:

> Once on this page, you can change the Name and Description by editing the corresponding boxes.

However, I can only see a box to change the game's name and privacy:

How do I change the description of the game?

# Answer
As per the documentation:

* Access game settings by clicking on the Game Settings button from the Home tab of Roblox Studio
* Once open, you’ll see five tabs on the left side of the window: Basic Info, Permissions, Avatar, and Options, and World.
* The **Basic Info** tab contains options for general game settings, including the game description that players see.
> 3 votes

# Answer
As of June 2023 (v 0.580), the description can be changed from the File menu \> Game Settings. The Game Settings icon should also be visible on the far right of the Home ribbon.
> 2 votes

---
Tags: roblox
---


title: Substance Painter: Fix color addition

text:
# Question
Title: Substance Painter: Fix color addition
Substance Painter appears to add colors together wrongly when selecting "Normal Blending Mode"

The right side is what photoshop does correctly, meaning R+G+B values in the border region never exceed 255. On the left side is what Substance Painter does incorrectly, the green dot appears to have a glow around it.

If there is no quick way to fix this, I will have to export Red and Green and Blue layers individually and blend them together in Photoshop.

# Answer
From provided image, left variant looks like to be more correct (meaning evenly bright). Where's right variant has a clearly noticeable black-ish circle.

We can also check out the desaturated image (Photoshop -\> Adjustments -\> Desaturate) on the left looks more even in brightness. Of course even better desaturator would be using color perception ratios (of 0.299R + 0.587G + 0.144B, which is not the case in this case).

To the explanation: IIRC mathematical approach to color handling is not correct, since the colors are written down in non-linear scale.

Aforementioned median result of 192 could be related to calculation being made in sRGB colorspace. If the gamma is set to be default 2.2, then (1^2.2 / 2)^(1/2.2) * 255 = 186, seems kinda close.

So yeah, Painter seems to be doing a better job at accurately mixing colors. Can it be "fixed"? I can not say, sorry.
> 2 votes

---
Tags: color, blending, substance-engine
---


# Question
Title: Apply a shader to the right face of a mesh
Given that I don't have the basic concepts to work with 3d, I would still like to experiment and learn.

What have I done:

1. I imported an SVG of the world map into Blender
2. I extruded the SVG
3. I converted everything to mesh
4. I exported the FBX and imported into Unity. Great, it works!

I then created a flag shader (following a tutorial), India in this case, and then applied the material to the India mesh.

The result is that it applies to the wrong faces! Obviously I wanted it to apply to the surface, not the extruded side.

**What are the notions I'm missing, how do I correct this dynamic?**

*Thank you.*

# Answer
To solve the problem, as suggested by DMGregory, I did the following steps (on Blender):

1. Enter the "UV Editing" workspace
2. I selected all the meshes that I needed to export. So:
3. Press `TAB` to enter Edit Mode
4. Press `a` to select all meshes
5. Press `u` to open the `UV Mapping` menu
6. Select `Unwrap`

Export.

I hope it's accurate, I've been using Blender for a few days.
> 1 votes

---
Tags: unity, blender, unity-shader-graph
---


title: Texture gets botched when loads in?

text:
# Question
Title: Texture gets botched when loads in?
I got this weird issue with my block texture,it gets botched after loading the block, the issue though doesn't affect other textures as the the paddle texture gets rendered properly:

I tried debugging it in render doc and it seems like it gets loaded in botched, my loading process looks something like this: Resource\_Manager -\> Texture\_Generator -\> Sprite\_Renderer

**game.cpp**

```
//texture loading
void Game::init_game()
{

    Resource_Manager::load_shader("resources/shaders/sprite.vs",
                                  "resources/shaders/sprite.frag",
                                  "sprite");

    glm::mat4 projection = glm::ortho(0.0f,
                                      static_cast<float>(this->width),
                                      static_cast<float>(this->height),
                                      0.0f,
                                      -1.0f,
                                      1.0f);
    Resource_Manager::get_shader("sprite").use_current_shader().set_integer(
        "image", 0);
    Resource_Manager::get_shader("sprite").set_matrix4("projection",
                                                       projection);

    renderer = new Sprite_Renderer(Resource_Manager::get_shader("sprite"));

    Resource_Manager::load_texture("resources/textures/block.png", true, "block");
    Game_Level level_1;
    level_1.load("resources/levels/one.lvl", this->width, this->height / 2);

    this->levels.push_back(level_1);

    this->current_level = 0;
}

//texture rendering
void Game::render()
{

    if (this->State == GAME_ACTIVE)
    {
        this->levels[this->current_level].draw(*renderer);
    }
}

```

**texture.cpp**

```
void Texture::generate(GLuint width, GLuint height, unsigned char* data)
{
    this->width  = width;
    this->height = height;

    glBindTexture(GL_TEXTURE_2D, this->ID);
    glTexImage2D(GL_TEXTURE_2D,
                 0,
                 this->internal_format,
                 width,
                 height,
                 0,
                 this->image_format,
                 GL_UNSIGNED_BYTE,
                 data);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, this->wrap_s);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, this->wrap_t);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, this->filter_min);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, this->filter_max);

    glBindTexture(GL_TEXTURE_2D, 0);
}

```

**game-level.cpp**

```
void Game_Level::init(std::vector<std::vector<unsigned int>> tile_data,
                      unsigned int                           level_width,
                      unsigned int                           level_height)
{
    unsigned int height     = tile_data.size();
    unsigned int width      = tile_data[0].size();
    float        unit_width = level_width / static_cast<float>(width),
          unit_height       = level_height / height;

    for (unsigned int y = 0; y < height; y++)
    {
        for (unsigned int x = 0; x < width; x++)
        {
            if (tile_data[y][x] == 1)
            {
                glm::vec2   pos(unit_height * x, unit_height * y);
                glm::vec2   size(unit_width, unit_height);

                Game_Object obj(pos,
                                size,
                                Resource_Manager::get_texture(
                                    "block"),
                                glm::vec3(0.8f, 0.8f, 0.7f));
                this->bricks.push_back(obj);
            }
        }
    }
}

```

**resource-manager.cpp(shows use of texture.generate())**

```
Texture Resource_Manager::load_texture_from_file(const char* file, bool alpha)
{

    Texture texture;
    if (alpha)
    {
        texture.internal_format = GL_RGBA;
        texture.image_format    = GL_RGBA;
    }

    int            width, height, nrChannels;
    unsigned char* data = stbi_load(file, &width, &height, &nrChannels, 0);

    texture.generate(width, height, data);

    stbi_image_free(data);
    return texture;
}

```

The image is taken from JoeyDeVrieses github repository:link

**Debugging**

Running `block.png` through debugger I get these results:

1. width - 128 pixels
2. height - 128 pixels
3. nr channels - 3 data
4. 0x555555e23240 'G' \<repeats 200 times\>

Running `paddle.png` I get these results:

1. width - 166 pixels
2. height - 25 pixels
3. nr channels - 4
4. data - 0x555555e1dc60 ""

Difference: the paddle has four nr channels and a single memory pointer while the block has three nr channels and 200 memory pointers?

# Answer
> 2 votes
It looks to me as if at least some of the problem is that you're ignoring the `nrChannels` value returned by stbi\_load().

I think it makes sense to use that to choose an image format for the texture, instead of using the `bool alpha` parameter to do that. Something like this:

```
Texture Resource_Manager::load_texture_from_file(const char* file)
{
    Texture texture;

    int            width, height, nrChannels;
    unsigned char* data = stbi_load(file, &width, &height, &nrChannels, 0);

    if (data == nullptr)
    {
        // TODO: Better error handling
        assert(false);
        return texture;
    }

    switch (nrChannels)
    {
        case 1: texture.internal_format = texture.image_format = GL_RED; break;
        case 2: texture.internal_format = texture.image_format = GL_RG; break;
        case 3: texture.internal_format = texture.image_format = GL_RGB; break;
        case 4: texture.internal_format = texture.image_format = GL_RGBA; break;
        default: assert(false); return texture; // TODO: Better error handling
    }

    texture.generate(width, height, data);

    stbi_image_free(data);
    return texture;
}

```

---
Tags: opengl, textures, rendering
---


title: How do I get my character to move?

text:
# Question
Title: How do I get my character to move?
This is my code:

```
import pygame
import time
import math
from utils import scale_image

WIDTH, HEIGHT = 1300, 800
WIN = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("MK1")
BG = pygame.transform.scale(pygame.image.load("imgs/mk 11 dragon grotto.jpg"),(WIDTH,HEIGHT))
pygame.display.update()

Raiden = scale_image(pygame.image.load("imgs/Raiden pose.png"),0.4)

run = True
while run:
    WIN.blit(BG, (0,0))

    r_x = 150
    r_y = 0

    Raiden_start_pos = (r_x,r_y)
    WIN.blit(Raiden,(Raiden_start_pos))

    pygame.display.update()

    keys = pygame.key.get_pressed()
    if keys[pygame.K_s]:
        r_y += 5
        WIN.blit(Raiden,(Raiden_start_pos))
        pygame.display.update()

    if keys[pygame.K_w]:
        r_y -= 5
        WIN.blit(Raiden,(Raiden_start_pos))
        pygame.display.update()

    for event in pygame.event.get():

        if event.type == pygame.QUIT:
            run = False
            break

```

I'm essentially hoping by pressing the W and S keys the character(Raiden) can move up and down through updating the y coordinate. However, it doesn't seem to be working and nothing changes when I press W or S. What should I do?

# Answer
> 2 votes
Your problem lies in the scope of `r_x` and `r_y`. You're updating `r_y` inside the `if` block, but then when you call `WIN.blit(Raiden,(Raiden_start_pos))` again, it's still referring to the initial `Raiden_start_pos` tuple you defined before the `if` statements, which are not updated after their initial definition. You should move the `Raiden_start_pos = (r_x, r_y)` line to after you handle the key presses.

# Answer
> 0 votes
You're going to want to move the following code:
`r_x = 150`
`r_y = 0`
out of the while loop. I recommend putting it after:
`Raiden = scale_image(pygame.image.load("imgs/Raiden pose.png"),0.4)`
So that you can keep your related code closer together.

As your code is now, r\_x and r\_y are reset back to 150 (r\_x) & 0 (r\_y) every frame.
You should also be able to remove the `WIN.blit(...)` and `pygame.display.update()` from the keyboard section, because you are already blitting and updating before that.

As it stands (and assuming the change in code doesn't cause bugs), the `.blit` and`.update()` in the keyboard section does a second blit and second update of the window. It may look like some weird effect is being applied to Raiden's sprite, as you aren't 'clearing' the screen between the blitting of Raiden's sprite.

I think the blitting of the background image 'clears' the screen in your current iteration, but to make sure that you don't have an issue in the future related to clearing the screen, add `WIN.screen.fill((color_of_your_choosing))` to the beginning of your while loop, where `color_of_your_choosing` is any 3-tuple whose values range from 0 to 255.

Your current 'main' function could look like:
`clear_color = (0,0,0)`
`while run:`
`WIN.screen.fill((clear_color))`
`WIN.blit(BG, (0,0))`
`Raiden_start_pos = (r_x,r_y)`
`WIN.blit(Raiden,(Raiden_start_pos))`
`pygame.display.update()`
`...`

---
Tags: python, pygame
---


# Question
Title: Should game data be encoded in configuration files, given that it will almost always contain logic?
Question inspired by the accepted answer to another question: Wondering if there is a more efficient way to store level data in my game?

The answer, by @Evorlor, says:

> You should have the data for your level in an external source, such as an XML, JSON, YAML, CSV, or even a .txt file. Then you write your logic to read from the file, and generate the level procedurally.
>
> This will let you play all of the levels with the same code, and you can make changes to levels, or add new levels, without touching the code. This also lets designers who aren't familiar with programming to create fun levels.
>
> This also opens the door for user-generated content. You can create a level editor that auto-generates this file. A level editor will also make it easier to make fun levels, since they can be visually designed, instead of by writing text into a doc.

I have great doubts about this line of reasoning.

Years ago I tried (and failed) to make my own Pokemon-like game. Inspired by The Battle for Wesnoth and its WML (Wesnoth Markup Language) config files that could encode entire scenarios, units and abilities I thought I'd do the same. I'd encode monsters, abilities and types in configuration files; then my game would read these config files on startup. There'd be next to nothing hardcoded.

This proved to be a terrible idea. Especially abilities proved to be absolutely horrible to encode in configuration files. I started seriously doubting if I was really doing the right thing when I saw `<if></if>` and `<not></not>` tags in my config files. But how else was I supposed to implement abilities that place a debuff (that can do absolutely arbitrary things) provided another debuff is already in place? I've also run into problems with composition: Debuff A was working properly on its own, Debuff B was also working properly on its own, but when both debuffs were placed at the same time there were no longer working properly: it turned out that iterating the list of buffs and debuffs on each turn and applying each of them separately was not always working. So my code grew complex and unwieldy when, in my homebrew config files encoding a debuff I had to test for the presence of other debuffs, etc, etc.

Then I read The Daily WTF article on Soft Coding and I thought I found my error. In fact, my config files syntax grew to become my own programming language, but one that was deeply inferior to what I already had, namely C#. I ditched config files and instead moved all data to `.cs` files. It turned out only monsters remained trivially serializable to a data format; abilities, damage types and (de)buffs were so cluttered with logic that it was nigh impossible to serialize them (at least not without creating my own programming language based on XML).

The aforementioned question and answer deals with levels in an SMB-like game. OK, I yield that serializing level data could seem more affordable than, say, serializing enemy data. Still, I think I can foresee imminent difficulties. What if I wanted to put in my level, say, a catapult that can launch 'Mario' to some otherwise inaccessible parts of the map? Note that, inspired by Wario Land, I have put a Rusty Spring as a treasure in this very level; but also I have put a Titanium Powered Adamantium Spring as a treasure in another level. Depending on which spring the hero brings to the catapult, it operates differently. With no spring, it is not functional at all; with a Rusty Spring it launches the hero to a secret area; with Titanium Powered Adamantium Spring it launches the hero to another, even more dangerous bonus area that is filled with even more treasure; with both springs, the player may chose the area they wish to be teleported to.

Not to mention typical various switches, booby traps activating / deactivacting on conditions, NPCs saying different things depending on if you've beaten a boss (or another arbitrarily complex conditions), etc, etc. Level data can easily become cluttered with logic!

If, from the very beginning, I put my level data in config files, I will start banging my head against the wall whenever I decide to implement any of the aforementioned features. If, however, I never touch the 'config files' route and instead always keep level data hardcoded (even when it still seems that this data is trivially serializable) I will not run into problems when I have an idea to implement any of the aforementioned ideas.

Which is probably why level editors in various games typically allow us to define variables and conditions by clicking through their GUI. Essentially, a level editor doubles down as a... visual programming language.

It seems to me that the cost of developing such tools is enormous and should be very carefully weighted against any possible gains from doing so. The situation where making a program (any program, not just a game) more configurable leads to defining and implementing my own programming language (whether by overly complex config files, overly complex config menus or both) should be avoided at all costs.

In particular, if someone just tries making their first game, then this is one of the first features that should be cut (under the general rule to scope smaller).

But even if this is indeed necessary, then game logic should still not be put in config files, but perhaps in Lua code (this is also how, if I'm not mistaken, Factorio can be modded; and also Wesnoth started moving logic in user generated contents from ther Wesnoth Markup Language to Lua).

Do I fail to see something? Why is it recommended that game devs, by default, put their game data in config files? Is it not the case that, over time, these config files will have to store logic rather than just data, making them unwieldy?

# Answer
> 4 votes
## A game or an engine

If you were making a game, then you write the code for each case in your game. Then the configuration only needs to specify which of the possibilities it uses. Which seems to be what you ended up doing.

On the other hand, if you were making an engine or a game to be modded, then it makes sense to provide some scripting language (e.g. Lua, as you point out). The configuration system can remain simple, by having it point to a script file if necessary. *So, no, configuration does not have to become a programming language, nor become unwieldy over time.*

*To give you a world of nuance, I believe some particular cases will look like programming anyway. See dialogue at the end of the answer.*

Even if you are providing an script language, whatever you find is implemented often is probably better to be implemented in the game proper, in such way that the script can call it. *Thus, the complexity of the script files would also be bounded.*

However, advocating for configuration is not advocating for scripts. **There is nothing wrong with having all the logic hard-coded in the game.**

---

## What do you gain with configuration

It might be worth remembering that the context of the question that inspired this one was a web game. It would download files from a server. In that context there is no clear distinction between hard-coded and loaded in runtime.

In fact, **There is nothing wrong with hard-coding the scenario description.**

Furthermore, "configuration" does not have to be loaded from storage in runtime. In fact what we have been calling "configuration" can be arrays hard-coded the source code. What we really want is the ease of reading it and modifying it (i.e. easy to maintain).

If you have a hard-coded string or array of characters where each character represents a tile, and you arrange it in a way that resembles the shape of the scenario, you might be able to visualize it directly, which makes it easier to modify it too.

Take the example by Evorlor, it could easily be hard-coded:

```
var scenario = "" +
"                                F" +
"          ?*?    C              F" +
"                                F" +
"     M           G              F" +
"======================    =======";

```

And even hard-coded it remains relatively easy to visualize and modify.

*And it still requires the code that iterates over it and instantiates the real thing.*

While this is not the full advice, doing this already gives you a game that is easier to maintain. There configuration is not the goal, it is a means.

---

Of course, you can have some file that you can open in some external editor (which might be visual or not). *And it still requires the code that iterates over it and instantiates the real thing.*

Having a separate file, while still being part of the source code gives you one more perk: you have separate diffs in version control for changes to the scenario and changes to the logic.

Furthermore, as pointed by Evorlor, it make it easier for designers who are not familiar with coding:

> This will let you play all of the levels with the same code, and you can make changes to levels, or add new levels, without touching the code. This also lets designers who aren't familiar with programming to create fun levels.

Thus, a third perk is to allow designers to create and modify content without messing with the source code. Again, configuration is not the goal, it is a means.

*I disagree with Evorlor that a configuration file "opens the door" for content generation, although I agree it makes it massively easier. For example, the approach shown in the question that inspired this one would have been easy to modify to include randomness. However, a configuration file creates a nice boundary between the logic that instantiates the level and the logic that generates it, which will result in much simpler code.*

---

**About tools**

Creating your own tools is an investment. But that does not mean creating a tool is always a good investment.

It makes sense to pick existing tools first. Consider if there is some format you can load for which there are existing editors. There are editors for tiles maps, and interactive fiction, and so on, that use format that you might be able to use in your code. In fact, there might be plugin for whatever engine you are using already.

An advice similar to that we often give about optimization of code applies here: find the bottlenecks of your development process and focus on those. For example, if you find that a lot of time goes into modifying scenarios, then perhaps developing tool for that is worth it.

---

## Making a powerful scenario descriptor

First of all, I remind you that these are means to the goals. The goals in this case include supporting the different situations you describe where complexity can become hard to manage. But what I describe below is not the only means to those goals.

*This more of a "hey, this works for me and other people like me" and not a "this is the law of how to do things". OK? OK.*

---

**Scenario and entities**

To begin with you have a description of the scenario. Presumably this description includes the starting position of enemies. The behavior of enemies - hopefully - is in the core game, and the description of the scenario only specifies which one it uses.

Well, scratch the word "enemy". The description includes the position of *entities*. And these entities can have arbitrary logic. Perhaps they have an associated class, from which an instance is created to handle each one - or something more fancy, for example they might be entities of an ECS - or, sure, they execute a script loaded at runtime.

Thus, the catapult you describe is an entity. The code for it is not part of the description of the scenario. And it does not have to be loaded from storage in runtime.

If anything the behavior could be configured. That is, the description of the scenario can include values that are passed to the code in runtime. Furthermore the entity code might be able to query the scenario in runtime. *So you don't implement bird that flies at height 3 and bird that flies at height 8, you use a variable. Similarly, you don't need warp that goes to level 2 and warp that goes to level 5, you use a variable, or multiple.*

The catapult in particular would need a list of keys and values that map items to destinations.

---

**Game state**

So you need switches that activate things, and those things are other entities.

In the simplest case you need a way to refer to entities in the description of the scenario, so you can write that such switch points to such door or whatever.

However, as it turns out, it is more flexible to have an intermediary. You will have a global game state (e.g. a blackboard) where the switch can write, and the door can read. *And it might also send notification when data changes, so that different entities can subscribe to react to the changes.* With that you can implement a switch that open multiple doors, or a door that checks multiple switches... Plus, this global game state can be serialized to save the game! And load it continue!

Of course the global game state can become a mess. The minimum implementation would resemble a key-value storage. However you will find it useful to have hierarchical keys. So you can give a sub-key to specific entities, or players (plural in case of multiplayer) where they store their own state, while keeping it all collected in a place from where you can easily save it and load it.

---

**Dialogue**

How to write interactive fiction is a thing of its own. Most games will have the dialogue hard-code because it is part of fixed story beats that the game always follow. But that is not every game. In fact, configurable dialogue is a powerful tool for designers making quests.

So here is my approach: You have storylets. Each storylet has:

* Has some preconditions.
* Have some effect.
* Text, and whatever else you need to show the dialogue (portraits, etc).
* Plus I find it useful to have a list of functions it can call asynchronously (e.g. move the camera, fade, change the music, and so on).

The preconditions can check the global game state (e.g. such boss has been defeated) the state of the entity (e.g. what have you talked already) and the player (e.g. if they have some item in inventory). *This would all be part of the global game state if you follow my advice of giving sub-keys to entities and the player, except you will use some shorthand to specify "hey use the sub-key of this entity or this player"*

Similarly the effect can write to global game state, the entity, or the player. The changes would be setting the value of keys to new values, and the change can be relative (i.e. increment or decrement).

Plus, *always* have as part of the state of the entity if it has already said a given dialogue (so that you can always have it as precondition for another dialogue, and that is how you chain them).

Then the entity has a pool of these storylets. And it has some strategy to pick them, for example, it might go in order, or at random, or you might implement a priority system, or something else. You might have logic for the different strategies and write in the description of the scenario which one the entity uses.

---

Thus, yes, I believe dialogue will have expressions (e.g. comparing values, assignments, or calling a function - from a predefined list, of course). Although the programming paradigm is not structured (it is not based on if-then and similar statements)... In fact, storylets have no branching.

With that said, modern interactive fiction tools use custom programing languages. Yet, I believe it is still better to have anything that requires complex logic taken out of it... So that it does not grow too complex, writers don't need to be programmers, and changes to the dialogue are separate from the rest of the code.

# Answer
> 1 votes
Moving game data into config files has several advantages:

* You can edit these files without having to recompile the game. Which can, depending on your technology stack and the scope of your game, save you a lot of annoying waiting time in your testing loop. With a bit of extra work, you can even make data files hot-reloadable, so you can experiment with them without even having to restart the game.
* You can edit these files without having to know the programming language and the development tools. This can be extremely useful if you aren't working alone but collaborating with people who are not programmers.
* You are not bound to the syntax of your programming language. Not every programming language is equally good at encoding data literals in the shape you need and in a way that is easily readable and editable. So moving that data to a configuration file can make your life a lot easier.
* You have *the option* to create editing tools that allow you to create content a lot faster (whether or not you should is a question of how much time it would take vs. how much time it would save. These are highly dependent on the project).

However, I agree with the TDWTF article on "Soft-Coding" logic to a level where the configuration language basically becomes so convoluted that all the above advantages are lost. When everything is soft-coded, then nothing is soft-coded. It's hard-coded in a proprietary programming language that is often worse than the language that was used to build it.

My general rule of thumb: **Logic belongs into code. Data belongs into files.**

But very complex games made by large teams often do move some logic to script files. That way they create a layer between the "arcane", highly technical code of the core game and the "dumb" configuration files that are just data. A scripting language you can teach to level- and game designers that allows them to do trivial logic without asking a programmer for help, but which isn't powerful enough to seriously break things. A common example are dialog trees in RPGs. If a writer wants the NPC to say one thing if the player made decision A and another thing if the player made decision B, then they shouldn't have to bother a programmer with that. Especially when there are about a hundred situations like that in the game.

Where to draw that line between what to program and what to script is a judgment call. There is really no hard rule to follow here, except the obvious one: Do what you think is less work.

To take the example of the one-off spring catapult thing from the question: I would turn this thing into an entity that can be placed in the level files. Even when it's just supposed to exist once in the game. That way the level designers can easily experiment with where to place it exactly. It also makes sure that when you look at the level file, you get the full picture of what is and isn't in that level. You can see that this empty plateau in the middle of the level isn't just wasted space, because that catapult is there. However, the actual logic behind it, might work better if it is hard-coded in a class.

# Answer
> 1 votes
# Only externalize if you solve a problem with it

Configuration files and similar external resources are an option which should be used if the benefits outweigh the costs. Generally speaking I would always start with the simplest solution which solves my problem. Refactoring a simple solution to a more complex one is usually not very expensive. On the other hand using an unnecessary complex solution for a simple problem is a waste of time.

## To decide which is the easier approach consider Pro/Con of data in code:

* PRO: You are already proficient with code, have a nice editor, it is checked/linted and bundled automatically
* PRO: Needs no additional code to load, parse or handle errors or interact with the file system
* PRO: Easily extensible and customizable - you can add individual code at any point for any level
* PRO: If your language/debugger supports hot code replacement, you might even see your changes in real-time without restarting the game.
* CON: If hot code replacement doesn't work, you might have to rebuild your game to see changes, which might take longer (but is mitigated by incremental builds).
* CON: If collaborating with designers/community editing a simple file for data can not as easily break things as editing code. And if the file is read on game startup, collaborators can edit and test levels/enemies/… without any IDE installed/without building the game.
* CON: If designing a lot or big levels a good specialized editor might save you a lot of time. By using a standard-format you can use standard tools like level-editors

## Weigh your options

Depending on the project and the type of game/data you should decide each time, if using an external file solves a problem for you. If it does then use it - if it doesn't then just keep the data in your code.

---
Tags: architecture, data, configuration, time-management
---


# Question
Title: simplest combat system i can do with code?
This is my actual set up, and for the moment I'm using this tutorial : https://www.youtube.com/watch?v=Mek4XtMhcMs&t=4s

which is one of a kind, never found any other guide on how to make 3D melee combat in godot without using some kind of rays which are useless...outside of a shooter game.... especially when your character is using a 1.8meters long greatsword.

BUT this method is very tedious, the tutorials have me add all the impact collision logic inside animations and for this to work, animations must be imported separately, which means that every time I notice something wrong with an animation and have to repair it in blender, or every time I need to add a new animation.... everything is gone and I have to re add all the collisions again.

which can be ok if you have 1 character with 1 combat ability... but when you have multiple characters with multiple combat abilities...it just gets depressing.

That's why I need something simpler, something that doesn't use the animation player, something that just a piece of code I can go and apply to every time and edit it a little bit.

# Answer
> 3 votes
One of the "tricks" I mentioned in another answer was using an `AnimationPlayer` to play animation from another `AnimationPlayer` using an "Animation Playback Track". Doing that the imported `AnimationPlayer` can be untouched in Godot (and thus you do not lose work if you have to import it again), and the other `AnimationPlayer` can have additional tracks such as "Call Method Track" to enable/disable colliders.

Or you could split the animations, so you have Windup (a.k.a anticipation), Strike, and Recovery. Then instead of enabling/disabling colliders, when there is a collision you can check which is the current animation. Which you could `queue` in the `AnimationPlayer`, or chain with an `AnimationTree`. *I suggested a similar approach in yet another answer.*

OK, let us say you don't want to split the animation either... Then what? You could check the current position within the animation by reading `current_animation_position` of the `AnimatinPlayer`. I'd expect a small timing error given that the animation usually runs on graphic frames and physics on physic frames, but it should not be a big issue. *You would have to code the time intervals for each animation, so you can compensate for any timing problem there.*

Or you could take control of the playback by setting the `playback_process_mode` to "manual" (`ANIMATION_PROCESS_MANUAL`) then using `seek` and `advance`, in which case you are in control of the animation timing and there would be no timing error.

---

**Addendum** You might do the attack animations in Godot. I'm aware that Godot 3 does not let you manipulate bones directly (as Godot 4 does), but Godot 3 has an IK solution (`SkeletonIK`) and you can key frame the target of the `SkeletonIK` in an `Animationplayer`, so you don't need to do round trips to Blender. *It is even possible to do it all programmatically, even skipping `SkeletonIK`, but that is more work.*

---
Tags: 3d, rpg, gdscript, combat, godot-3
---


# Question
Title: Raycast from isometric view without camera position?
I'm trying to cast a ray so I can implement mouse picking. My game uses 2:1 isometric with a 3D world sim that uses AABBs. Positive X points to the bottom right, positive Y points to the bottom left, positive Z is up.

I currently have a screen -\> world conversion function that will tell me where a mouse click intersects with Z==0:

```
    // Offset the screen point to include the camera position.
    float x{screenPoint.x + camera.extent.x};
    float y{screenPoint.y + camera.extent.y};

    // Calc the scaling factor going from screen tiles to world tiles.
    float TILE_WIDTH_SCALE{TILE_WORLD_WIDTH / TILE_SCREEN_WIDTH};
    float TILE_HEIGHT_SCALE{TILE_WORLD_WIDTH / TILE_SCREEN_HEIGHT};

    // Calc the world position.
    float worldX{((2.f * y) + x) * TILE_WIDTH_SCALE};
    float worldY{((2.f * y) - x) * TILE_HEIGHT_SCALE / 2.f};

```

Is there maybe an alternate form of this conversion that will get me a ray? I don't have a set of matrices to unproject, I'm just using these iso conversions.

Another thought I had is: the direction vector out of the camera is constant, so I could just calculate that and use it for my ray. The issue is, I don't know my camera's position so I don't know the ray's origin. My camera is very simple, it's just centered on a world-space position using the following steps:

* Set the world-space floor (Z==0) position that you want to center the camera on.
* Convert the world position to a point in isometric screen space.
* Render anything within (point.x - screenWidth/2, point.y - screenHeight/2, screenWidth, screenHeight).

Edit: As requested, here's my world -\> screen conversion:

```
    // Calc the scaling factor going from world tiles to screen tiles.
    float TILE_WIDTH_SCALE{TILE_SCREEN_WIDTH / TILE_WORLD_WIDTH};
    float TILE_HEIGHT_SCALE{TILE_SCREEN_HEIGHT / TILE_WORLD_WIDTH};

    // Convert cartesian world point to isometric screen point.
    float screenX{(position.x - position.y) * (TILE_WIDTH_SCALE / 2.f)};
    float screenY{(position.x + position.y) * (TILE_HEIGHT_SCALE / 2.f)};

    // The Z coordinate contribution is independent of X/Y and only affects the
    // screen's Y axis. Scale and apply it.
    screenY -= (position.z * Z_SCREEN_SCALE);

```

# Answer
> 0 votes
Practically, the best way to achieve this is likely to just switch to matrices. This will minimize the amount of repetitive and error-prone code you have. You would

1. Create a matrix that contains the same offsets and scale factors as your world-to-screen coordinate converter does.
2. Compute the inverse of that matrix for screen-to-world.
3. Replace both conversion functions with matrix multiplication.
4. Produce a ray by executing screen-to-world with two different Z coordinates.

However, it is *possible* to work out the same ray manually (and, technically, slightly more efficient because you don't need two matrix·vector operations).

A ray can be seen as an origin and direction, *or* as a pair of points on a line. Your screen-to-world function already knows how to find one of those two points — the one that has `z = 0`. Your world-to-screen function says:

```
    screenY -= (position.z * Z_SCREEN_SCALE);

```

So, in order to find a *second* point that does not have `z = 0` but still lands on the same screen point, we can imagine this process as:

* Change the `z` to be different.
* Adjust the other coordinates so the screen position does not change.

Step by step:

1. Let's say that we add 1 to `position.z`.
2. This will cause `screenY` to differ by `-Z_SCREEN_SCALE`.
3. Therefore, we must change `position.x` and `position.y` so that `screenY` is moved by `+Z_SCREEN_SCALE`.
4. We don't want to change `screenX`, so `position.x - position.y` should stay constant. The difference must stay the same, so we can conclude we should add the same quantity to both `x` and `y`.
5. If we add the same amount to `x` and `y` then `position.x + position.y` changes by twice that, so if we find a quantity for `position.x + position.y` to change by, we should halve that.
6. `screenY = (position.x + position.y) * (TILE_HEIGHT_SCALE / 2.f)`, so if we invert that we get

`(position.x + position.y) = screenY / (TILE_HEIGHT_SCALE / 2.f)`
7. This is a linear equation with no constant term, so we can just substitute in the deltas:

`Δ(position.x + position.y) = ΔscreenY / (TILE_HEIGHT_SCALE / 2.f)`
8. Now let's plug in the amount we want to change:

`Δ(position.x + position.y) = Z_SCREEN_SCALE / (TILE_HEIGHT_SCALE / 2.f)`
9. From steps 4-5 we know we want equal change in x and y:

`Δx * 2 = ∆y * 2 = Z_SCREEN_SCALE / (TILE_HEIGHT_SCALE / 2.f)`
10. Now let's apply basic algebraic simplification to that formula:

`Δx * 2 = ∆y * 2 = Z_SCREEN_SCALE * 2.f / TILE_HEIGHT_SCALE`

`Δx = ∆y = Z_SCREEN_SCALE / TILE_HEIGHT_SCALE`

Now putting it all together, we've got the offset for our second point from the first point, *which is also* the direction-vector of the ray.

```
(Δx, Δy, Δz) = (
    Z_SCREEN_SCALE / TILE_HEIGHT_SCALE,
    Z_SCREEN_SCALE / TILE_HEIGHT_SCALE,
    1
)

```

Since the length of a direction vector doesn't matter (except when you want a normalized one), you can multiply the whole thing by `TILE_HEIGHT_SCALE` and get a different equivalent one:

```
(Δx, Δy, Δz) = (
    Z_SCREEN_SCALE,
    Z_SCREEN_SCALE,
    TILE_HEIGHT_SCALE
)

```

Either way, since I chose to start with increasing Z, this is a direction vector that points upward, out of the screen. You can just negate it to point inward.

Also, I may have made some math error — getting signs backwards is a classic. But I have tried to lay out the logic by which I got there, so you can check it or apply it to a different starting point yourself.

And if you use matrices instead, there's a lot fewer chances for error.

---
Tags: rendering, vector, raycasting, isometric
---


# Question
Title: How to get area of 2D shape bounded by vertical and horizontal line segments?
I am making a game similar to Volfied using Unity:

The player outlines an area using straight lines, either horizontal or vertical.

I am stuck at the algorithm to decompose the area into rectangles so that I can :

* count for the percentage of area claimed by multiplying the width and height of the rectangles then summing the result.
* Add "Sprite mask" component to the generated rectangles for masking effect.
* I am currently not dividing my game into grids/cells so probably flood filling algorithm may not be the best option.

I am not sure if this is the easiest way to do it or not but what algorithm I could apply to this situation?

Thank you.

# Answer
> 1 votes
As long as your polygon has no holes, and you have a list of the corners of the shape in order as you walk clockwise around the perimeter, you can calculate the area directly using the shoelace formula, like so:

```
float area = 0;

// Start with the edge joining the last corner back to the first corner.
Vector2 start = corners[corners.Count - 1];

// Visit the edge ending at each corner in the list.
foreach (Vector2 end in corners) {
    // Accumulate the area attributable to this edge.
    area += start.x * end.y - start.y * end.x;

    // Advance our edge start point for the next edge.
    start = end;
}

// The above calculates double the area, so we halve it to get the true area.
area /= 2;

```

How this works is that for each edge of the polygon, you're computing the signed area of the triangle formed by that edge and a point at the origin - positive for triangles wound clockwise, negative for triangles wound counter-clockwise. (Technically you're getting the signed area of the parallelogram formed from two copies of that triangle, but we divide by two at the end to get rid of that).

The counter-clockwise triangles subtract out the excess area covered by the positive triangles, leaving you with the complete area of the polygon.

This keeps the workload proportional to the number of edges in the polygon, not its area, and does not require discretizing the problem to a grid.

This also works if your edges are diagonal, and even if the polygon is self-intersecting (though you will count the overlapped area twice).

If you find you're getting negative areas, you've wound your corners list counter-clockwise, and you can multiply by -1 or take the absolute value to get back to a positive area.

# Answer
> 0 votes
Since all you need is the area and this is a calculation that runs infrequently (i.e. it's not running every frame), here's how I would approach the problem:

First I would create a bitmap representing the play area. This could be a bitmap in the image sense (i.e. data structure that backs a .BMP or other image type) it doesn't need to be. A 2D array of Boolean would also work. The idea here is that you want a rasterized representation for the area of interest.

When lines are made in the play area also make them on the bitmap. Ideally, your bitmap should be the same dimensions as your play area. If the bitmap is not a one-to-one representation of the player area, scale and round the coordinates accordingly. For example, let's say your bitmap is 1000x900 but your actual game area is 800x700. Then some point x,y in the game area would be represented by location (1000x/800),(900y/700). Obviously scaling & rounding can introduce a degree of error. For that reason I would initially start with a one-to-one representation & only consider alternatives if there are performance problems that can be traced back to that decision via profiling.

Whenever a section is completed, use a flood fill algorithm on the bitmap to flag that area as complete.

Finally, calculate the area that has been flagged. If you're making a custom flood fill, this step could be part of the previous step (by keeping a running tally of the pixels/cells changed by the flood fill). If not, you can also brute force it by iterating over the entire bitmap and compare the flag count to the previously recorded count. While not the most efficient, it's easy to code, less prone to error and unlikely to noticeably affect performance.

The key aspect of this solution is that you're abstracting your problem (how to keep track of area) from your player facing game aspects (whether or not the player sees a grid, where things are on the physical screen, etc).

Note: while a logical bitmap is probably a more memory efficient way to solve the problem as stated, there are a couple of reasons why an image based data structure might be better:

* If there's already a flood fill available in your image API, that's one less thing to write & debug.
* You might also have an in-game use for the image; for example it could be used as a mini-map if your play area spans more than one screen's worth of space.

If you prefer to calculate the area directly as a series of rectangles, it's an example of a dissection problem (see also). Most of the solutions I've seen are interested in various constraints (for example solutions with the minimum number of rectangles for an area), though there may be simpler solutions that aren't concerned with those complications. There appears to be a good explanation on Stack Overflow along with links to related problems.

---
Tags: unity, c#, algorithm, geometry
---


# Question
Title: New Unity input system not working/responding
I'm trying to use the new input system for my 3rd person character in Unity. However, whenever I press the WASD keys, or try to move the camera, nothing happens. I've looked everywhere, but can't find an answer!

Here's a picture of the different values and such.

Here's some of my code

```
using UnityEngine;
using UnityEngine.InputSystem;

public class CharacterController : MonoBehaviour {

    [Header("Mouse Input Settings")]
    public bool cursorLocked = true;
    public bool cursorInputForLook = true;

    public void OnMove(InputValue value)
    {
        Debug.Log("Moving");
        move = value.Get<Vector2>();
    }

    public void OnLook(InputValue value)
    {

        Debug.Log("Looking");
        if (cursorInputForLook)
        {
           look = value.Get<Vector2>();

        }
    }

    public void OnJump(InputValue value)
    {
        Debug.Log("Jumping");
        jump = value.isPressed;
    }

    public void OnSprint(InputValue value)
    {
        Debug.Log("Sprinting");
        sprint = value.isPressed;
    }
}

```

*I also have the active input handling turned to both input systems in the projected settings menu.* What could I possibly be doing wrong? Is my project just bugged, and I have to just make a new one? Any help would be appreciated!

# Answer
I'm just using the documentation as an answer for your case (since I usually do the binding of via code and not the editor)

The binding of your events for `player input` should be `Behaviour: Invoke Unity Events` according to the docu. From there you can set the methods you want to call in your `character controller`.
> 1 votes

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


# Question
Title: Is it appropriate to design heroes as items in game development?
If you were to design a multi character game like "Genshin Impact", would you design the character(hero) as a item?

What is an item: in our game design, an item is an object within the game world that can be collected by a player or a non-player character. For example, a blood-recover drug, or an equip, whether it is disposable or permanent, are perceived as a item.

Why I think characters could be designed as items:

1. Characters, like items, are such a thing that can be stored in or taken out of a backpack for use, let's say character backpack.
2. Characters, like equips, could possess many levels or attributes, e.g. starLevel, qualityLevel, ordinaryAttr, supremeAttr and so on.

So I write some classes in Java:

```
public interface IItem {

    int getType();

}

public interface IHero {

    int getType();

    int getStar();

    int getLevel();
}

@Data
public class Item implements IItem, IHero {

    @Tag(1)
    private long id;

    @Tag(2)
    private int type;

    @Tag(3)
    private long count;

    @Tag(4)
    private int place;

    @Tag(5)
    private HeroData heroData;

    @Tag(6)
    private EquipStatus equipStatus;

    @Tag(7)
    private EquipData equipData;

    @Exclude
    private long[] params;

    ....

```

But sometimes I worry if such design would bring some problems in subsequent development. I has some puzzle like:

1. How to define the holding relationship? An character item could use other non-character items seems wired.
2. An character has many skills, skins, attributes. Would it bring some troubles in the design?

Based on your game development experience, how do you design the Item system and Character System?

# Answer
**Can characters be objects?**

Yes.

First of all, a player (the person playing) is not a character. But the player has characters, and items, and so on. And yes, you can think of them existing in inventories.

A player might have a currently "equipped" character. There are games where the user controls a party of characters. There are also games that you switch characters. These are not new concepts.

And, of course characters might have their own inventories. *Or they might share a single inventory.* And yes, items could have inventories too (i.e. containers such as bags or chests).

None of this prevents characters from being items.

---

*I would like to challenge that items exist in the game world. Instead I would say that there are wrappers for items (and also for characters) in the game world. But the question is not about that, so let us not dwell on it.*

---

**Classes**

For your classes, it is probably better to think about the things that the player has. For example: vehicles, buildings, decorations, characters, pets, weapons, tools, consumables, keys, crafting materials, etc... And cosmetics for those things that apply.

Using the type system of your programming language each of these could be a different class, and they might or might not share interfaces.

Now, thinking about inventory and equipment, what I see is they are mostly different data structures (ordered/unordered, with/without stacking, with/without named slots, fixed size or not). And you could have these data structures containing any kind of objects (regardless if they are "items" or not).

Thus, even if characters are in an "inventory"-ish structure, it does not imply they must be items.

*If there is any benefit for characters being items, it is probably something specific of your game.*

---

**Constraints**

When using an item it makes sense to specify by who and on what or whom, in particular if there are multiple characters (be them from a party controlled by the player, bots, or multiplayer).

And you might want to constraint on what or whom an item (or a spell or attack for that matter) could be used on.

Similarly you want to be able to constraint what you can put inside of those or any other inventories (e.g. again, containers such as bags or chests).

*Furthermore, you want to constraint what bots can target, etc.*

The first filter is the type system of your programing language, but you can have more checks (e.g. inventories might have weight and size limits).

Plus, I explicitly say "the type system of your programming language", because there is something else might look like a type system that you can use: flags and tags.

That is you would define some checks in terms of flags and tags that an object must match to be placed inside a container, or to be the target of an effect (e.g. the target must not be an enemy).

Two reasons to not hard-code these come to mind:

* To make it easier for designer to specify them.
* To allow changing them in runtime.

Thus, if we say that a healing spell can be used on characters or pets, but not vehicles or buildings, although it sounds like we are talking about the type system of your programming language, it does not have to be.

*Thus, issues of the type "can you put a character in a backpack?" could be resolved at this level instead.*

Of course the actual constraints will vary from game to game.

---

**Can items be characters?**

You seem to be doing something different from what you ask. You ask if it is it appropriate to design heroes as items, but the in code looks like you are making items as heroes (`Item implements IItem, IHero`).

That does not seem right, but there might be a game idea hiding in there.

*Still from the movie Everything Everywhere All at Once.*
> 2 votes

# Answer
I don't foresee any benefits to implementing characters as items.

If you had a proliferation of dozens of specialized "user inventory ownable" entity types like items and characters, lumping them all under a single type might be a significant savings. But if characters are the only special case, you're probably not gaining much by combining them when most code will need specialized paths for each of them anyway.

The menus where you select characters and the menus where you select items are different menus — you're unlikely to ever have a situation where you need to store/iterate/manipulate a mixed collection of both characters and items, where being able to treat both as items would be a convenience. The same goes for the operations you'd perform on the two — you'll never "consume" or "wear" a character like you would a potion or an armour piece, and you'd never "embody" an item like you would a character. It might make sense to have a stack of multiple copies of an identical item in your inventory, where that may not make sense for characters (depending on the particulars of your gacha system).

Similarly, these types likely need different data stored. Every character might have a set of core stats like strength/defense that don't apply to all items, while an item might have a purchase price that doesn't apply to characters. If your data type for one of them either is or descends from the other, it gets saddled with these extra unused fields, redundantly wasting memory and reducing cache locality for batch operations.

Any low level system that you might want to use for both — like a menu widget for displaying a list or grid of icons to select — can and probably should be written generically so that it can work for collections of *any* entity, rather than only those that descend from `Item` or implement `IItem`.

Keeping these separate can even save you from bugs. If all characters are items distinguished only by an integer type marker, your compiler won't stop you from using an invalid integer there (and accidentally interpreting a character as a potion that can be consumed or currency to be spent, etc). Instead, if `Item` has an `ItemType` enum with values like `CONSUMABLE`, `CURRENCY`, `WEAPON`... AND `Character` has a `CharacterType` enum with values like `SUPPORT`, `TANK` etc, then you get compile-time support protecting against this kind of error.

More generally, I recommend minimizing "is-a" relationships in game code wherever "has-a" can do the same job. This is the principle of composition over inheritance, and it helps guide toward more flexible, modular code that's simpler to read and modify. A potion can be an entity that "has-a" consumption effect component and an carrying weight component etc, while a character can be an entity that "has-a" base stats component and a melee attack component, for example. (This leaves open the possibility of creating a character you can drink/spend down the line, if that's a combination you decide you want to create deliberately, rather than stumbling into as a data bug)
> 1 votes

---
Tags: java, software-engineering
---


# Question
Title: How to keep track of 'already happened' in-game events in (event cascade/chain of events)?
Basically title. Let's say, for example, I walk into Room, and Event A happens. Next time I enter Room A, Event B happens, because Event A already happened. I don't actually want to save this information to a file, at least not for now. I only want a way to keep track of it at runtime.

I suppose a system like this one should be 'engine-agnostic', but just to give some more context, I'm working with Godot 3.5.2 MONO version (C#).

Right now, what I imagine I could do, it's an autoload (persistent) scene that listens and saves every event-action (that is, only the events that could trigger more events) in an array. We can later check if that specific event-action already happened by looking at the array (if it's there, it happened). But I think this only works with a single event (unless that single event is actually a holder for many other events). I'm thinking of something like this:

Buuuut maybe there's an easier way? Maybe there's ANOTHER way?

# Answer
> 2 votes
## Using an autoload

> what I imagine I could do, it's an autoload (persistent) scene that listens and saves every event-action (that is, only the events that could trigger more events) in an array.

Yes, something like this is what I've been advocating (e.g. here, here and here).

You can have an autoload with whatever properties you want. There you can define setters to also emit signals.

Then when something loads it can read the properties from the autoload and change to reflect their current value, and also subscribe to the signals so they can react in real time. This way it does not matter if the change happened in the same scene or another, it works.

Plus, having everything in the same place also makes it easy to save it and load it (for the save game feature).

---

However, I'm also aware that as your game becomes large the autoload also grows and can become hard to manage.

Something you could do is have a dictionary in the autoload, then there would be no need to add more variables to it, instead associate keys for different parts of the code. And you can nest dictionaries!

For example, each scene could save a nested dictionary to a different key of the autoload dictionary, and then different nodes in the scene might save to different keys of that nested dictionary. *I hope that makes sense.*

*An bonus trick is to use `get_indexed` and `set_indexed` of the autoload to access the dictionary.*

**Note**: By using dictionaries in Godot we lose type safety, since Godot does not support specifying the type of the keys and values, instead it always works with Variant.

---

## Using `Resource`s

There is another solution if you prefer something more decentralized: `Resource`s.

The idea is that everywhere you `preload` (not `load`) a `Resource` you are going to get the same instance, also anywhere you load it from the inspector you are going to get the same instance.

So make custom `Resource` types with the fields you need (and you can have signals there too), you create resource files of that custom `Resource`, and `preload` them. Any changes to the values of those fields will survive changes of scene.

This is **resource based communication** (I have an example here).

Plus, being `Resources` you can save them and load them with `ResourceLoader` and `ResourceSaver`.

This approach also means that an scene with the resources it uses can be self-contained (not requiring an autoload or anything external to work).

---

Now, there is a reason why this is not what I recommend: Godot does not check what it is loading. On one hand this is a way you can have some malicious code injected in the game... On the other this is a way you can provide modding support. Thus, this is not an entry level approach.

The following is what I had to do to make this both safe and easy to use:

Have a custom `ResourceFormatLoader` and `ResourceFormatSaver` that saves the `Resources` in a custom format, that:

* Does not save specific types (e.g. do not save `Script`s). Please note this is not just checking the type of the `Resources`, instead we traverse the object graph of everything it references, saving item by item, but skipping the undesired types.
* And does not load them either. Which means it has to load value by value. Which is the reason you cannot use the default format that Godot uses (which would have you load everything as a single unit without checking).

Plus I use code generation (a `tool` script creating script files) for the boilerplate code of `ResourceLoader` and `ResourceSaver` \- What boilerplate code?

Well, when it comes to how we use `Resource`s there are three cases:

* `Resource`s that I just `load`. Nothing special about these.
* `Resource` that I `load` and I might want to `save` (mostly used for save games). In this case I want to load from an `user://` path if it exists, if it does not I want to load from the `res://` path. But I will only save to the `user://` path, because the the `res://` path is read only on release... So I need to load from the `res://` path and change the save path to the `user://` path.
* `Resources` that I `load` and I want to `save` any time they change (mostly used for configuration and unlockable content). They do all the above, plus I also want to subscribe to the `changed` signal of the `Resource` and save them automatically.

*I have no plans of releasing this at the time of writing.*

---

## Something else

Being speculative, perhaps something in the middle would be interesting, for example using code generation to create autoloads. But hat is an avenue I have not explored.

You might also use some database system with Godot. For example, there are modules for SQlite which might work for you.

Similarly, there is interest in including some kind of key-value storage solution in Godot that would replace the need of making the autoloads... But that would be for Godot 4.2 or later.

By the way, you might want to Change scenes manually. This would allow you have scene transitions, loading screens where you use background interactive loading, or - yes - keep things around from one scene to the other.

---
Tags: c#, game-loop, godot-3
---


title: Lining up GameObjects in unity

text:
# Question
Title: Lining up GameObjects in unity
I am trying to make a script that lines up a list of GameObjects. Currently, I do this by generating a set of positions and then lerping the objects to them, the code works but does not account for the object's size so if it is large enough clipping will occur. I don't care if the solution is an improvement to the existing code or something entirely new. This is my current code:

private List GenLinePos(List objs) {

```
    float curHoldOffset = lineOffset;
    List<Vector3> positions = new List<Vector3>();
    positions.Add(lineAnchor.transform.position);
    int side = 1;
    for(int i = 1; i < objs.Count; i++)
    {
        //set initial position
        Vector3 pos = lineAnchor.transform.position;
        //change position
        pos += (lineAnchor.transform.forward * curHoldOffset) * side;
        side *= -1;
        if(side == 1)
        {
            curHoldOffset += lineOffset;
        }
        positions.Add(pos);
    }
    return positions;
}

```

Note: the line anchor is parented to the main camera which will be moving and rotating

# Answer
> 0 votes
How about this?

```
private List<Vector3> GenLinePos(List<GameObject> objs) {
    float curHoldOffset = lineOffset;
    List<Vector3> positions = new List<Vector3>();
    positions.Add(lineAnchor.transform.position);
    int side = 1;

    for (int i = 1; i < objs.Count; i++) {
        // Set initial position and rotation
        Vector3 pos = lineAnchor.transform.position;
        Quaternion rot = lineAnchor.transform.rotation;

        // Get the object's renderer and transform
        Renderer renderer = objs[i].GetComponent<Renderer>();
        Transform objTransform = objs[i].transform;

        if (renderer != null) {
            // Calculate the additional offset based on object size
            float objectSize = renderer.bounds.size.z;
            curHoldOffset += objectSize;
        }

        // Apply rotation to the position
        pos += rot * (lineAnchor.transform.forward * curHoldOffset) * side;

        // Apply rotation to the object's transform
        objTransform.rotation = rot;

        side *= -1;
        positions.Add(pos);
    }

    return positions;
}

```

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


title: Rigid bodies sliding off slopes

text:
# Question
Title: Rigid bodies sliding off slopes
Kinematic bodies have a simple class that makes the player not slide on slopes, but for rigid bodies? I tried using rays and areas, either to lock the player on an axis or to just straight up disable gravity when the player touches the floor, bur this doesn't work.

It is very important to prevent sliding since I need this for a climbing mechanic. The climbing already works, the only problem is, imagine being able to climb up a 90 degree wall, but slide off terrain steeper than 40 degrees.

The best I managed to do so far is to set movement in Y axis to 0 while the player is on a slope. For some reason it does slow the sliding, actually makes it so slow that is hard to notice, but the player still slides down.

# Answer
> 0 votes
I have just done this in godot 4. Essentially instead of projecting gravity straight down, you detect the normal of the floor and project along that. If you do this your character should stay stationary. I also set the physics material to rough and the friction to max as a precaution.

I based most of this on the following unity tutorials for creating a rigid body based character: https://catlikecoding.com/unity/tutorials/movement/ (in particular https://catlikecoding.com/unity/tutorials/movement/physics/#3 for slope handling).

It should be reasonably straightforward to convert what is there to godot. At least with godot 4 I haven't had any trouble findng the right calls etc.

---
Tags: physics, 3d, movement, rigidbody, godot-3
---


# Question
Title: Should I use singleton or object persistence?
I have a situation where I have levels in my game and a start screen. For the levels, there is a persistent empty GameObject. My code for setting the game over and level complete canvases active (Also button initializations eg. restart, quit, next level...)is attached to that empty game object. Further, the canvases mentioned are attached to the persistent object.

Would converting my persistence script into a singleton script be the best way to manage the behavior so that the canvases don't land up on the start screen (and unnecessarily slow the game) when I quit a level? I am planning on putting the persistent object in every level to test each level specifically.

As of right now this is what I'm planning on doing unless there are better patterns or suggestions. Any help would be appreciated!

```
     if (instance == null || (SceneManager.GetActiveScene().name != "StartScreen"))
    {
        instance = this;
        DontDestroyOnLoad(gameObject);
    }
    else
    {
        Destroy(gameObject);
    }

```

# Answer
I would stick with what you have. If it works, it works. Only make changes if you notice a problem or something that is making development in other areas difficult.

You mentioned you are worried about performance. Did you measure it? Is there actually an issue? Did you confirm that the issue is coming from this system? Only worry about performance when those 3 things have already been determined.

Now to get back to your original question. I think your proposed solution looks fine. For a small or medium sized game that’s probably all you need. If you need to massively scale up your game, I would look into using additive scene loading. And keep a persistent scene around in the background with all the persistent objects/UI on them. That way you only load them once and know they’ll always be there.

But. Like I said. Only look into this if you start seeing problems with your initial approach. As the commenters said. Better to finish a game then to have a well designed unfinished game.
> 1 votes

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


# Question
Title: How can enemies detect a player at the same platform level
**Problem**

There's a platformer level where I want the enemy (red) to detect the player (green) within a given range. I have this currently working using an overlap circle check (dotted red circle). However, this circle can extend onto higher platforms but I only want the player to be detected if it is on the same level.

**Tried Solutions**

* Checking the Y-level difference between the player and the enemy.
* Raycast from the enemy to the player to check if there is a platform between them. This half works because there are cases when the player is high above the enemy but there is no platform between them (e.g. jumping between platforms)

What is a robust solution that I can employ here?

# Answer
> 3 votes
Your tried solutions can work *together*. You don't have to choose one over the other since you want to simulate both **gaze direction** and **line of sight**.

Let's start with your base assumption: enemies must detect the player if the latter is within their detection range. An overlap circle check (or, similarly, a distance-to-point within range) will detect the player within a radius, but nothing more. The pseudocode would look like this:

```
// Detect the player
if ( player_in_circle() )
{
    detect_player()
}

```

On top of **distance**, we check for **direction**. Instead of considering the Y-coordinate difference, I suggest checking whether the angle between each enemy and the player lies within a given range. We can do this with trigonometry: we first define a "limit angle" relative to the ground beyond which enemies cannot "see"; then, we check the enemy-to-player direction doesn't exceed such limit value.

Since we are *ignoring* all directions beyond the limit angle (let's say 75°), the enemies' detection area will be altered as follows:

Our pseudocode will now look like this:

```
// Detect the player
if ( player_in_circle() )
{
    if ( player_direction_in_range() )
    {
        detect_player()
    }
}

```

Finally, we want to check for **line of sight**. Platforms and solid objects should *obstruct* the enemies' vision, therefore a raycast check will be enough for this purpose. This enables ignoring all player positions where a raycast would return a hit ("I can't see the player"), and will alter the enemies' detection area like this:

Our ugly pseudocode will finally look like this:

```
// Detect the player
if ( player_in_circle() )
{
    if ( player_direction_in_range() and not platforms_raycast_hit() )
    {
        detect_player()
    }
}

```

The above code is supposed to run at every frame. If you are using a trigger collider, you may use the `OnTriggerStay()` callback to check only as long as the player overlaps the circle. A quick (untested) sample code here:

```
using UnityEngine;
using System.Collections;

public class PlayerDetector : MonoBehaviour
{
    [Range(0f,90f)]
    public float maxAngle = 75f;

    void OnTriggerStay(Collider other)
    {
        if (other.CompareTag("Player"))
        {
            // Is the player within the enemy's vision range?
            Vector2 _en2pl = other.transform.position - transform.position;
            if (Mathf.Abs(_en2pl.normalized.x) <= Mathf.Cos(maxAngle * Mathf.Deg2Rad)
            {
                // Check for platforms and solid objects
                RaycastHit2D hit = Physics2D.Raycast(transform.position, _en2pl, ...);
                if (hit.collider == null)
                {
                    // PLAYER DETECTED
                }
            }
        }
    }
}

```

---
Tags: unity, c#, level-design
---


title: Application.Open URL

text:
# Question
Title: Application.Open URL
I am developing a simple application on Unity, on a Mac. I am trying to open an URL with the simple command Application.OpenURL on visual studio when it doesn't work : When I start to write application on visual studio it doesn't show the commands available. Do I miss something?

# Answer
The method call must be in an active method for it to be called. Try something like this if you want it to be called at the initiation of the script:

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

public class OpenURL : MonoBehavior
{
    void Awake()
    {
        Application.OpenURL("https://www.romainlalire.com");
    }
}

```
> 2 votes

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