# Question
Title: Remove a tile from a scene with GDScript in Godot
How do I remove a tile from a scene programmatically? I have tried the following to no avail:

```
func _physics_process(_delta):

    ...

    velocity = move_and_slide(velocity, Vector2.UP)

    for i in get_slide_count():
        var collision = get_slide_collision(i)
        if collision.collider.name == "MysteryBox":
            remove_tile(collision.position)

func remove_tile(position):
    var tilemap= get_parent().get_node("Tilesets/MysteryBox")
    tilemap.set_cell(position.x, position.y, -1)

```

I can detect the MysteryBox when the player collides with it, but the remove function is not removing the tile the player touched from the scene. Thanks in advance! Godot version 3.4.2

# Answer
> 2 votes
You need to convert the position from global coordinates (which is what you get in a `KinematicCollision` or `KinematicCollision2D` such as the one returned by `get_slide_collision`) to the coordinates of the `TileMap`.

What I said above can be accomplished like this:

```
var local_position:Vector2 = tilemap.to_local(position)

```

However, you also want the position in tiles. Not pixels. Which you could do using the size of a cell:

```
var local_position:Vector2 = tilemap.to_local(position)
var cell_position:Vector2 = local_position/tilemap.cell_size

```

Or alternatively yet, do it like this:

```
var local_position:Vector2 = tilemap.to_local(position)
var cell_position:Vector2 = tilemap.world_to_map(local_position)

```

And now you know what `world_to_map` does and why you would want to use it. There is also a `map_to_world` that does the opposite transformation.

---

If I understand correctly you want to remove the tile that your `KinematicBody2D` collided with. So you are taking the position of the collision. However, the position of the collision is not inside the tile.

To fix that, you can offset the position in the opposite direction of the normal of the collision (i.e. inwards into whatever it collided with):

```
var tilemap:TileMap = collision.collider as TileMap
var local_position:Vector2 = tilemap.to_local(collision.position)
var cell_position:Vector2 = tilemap.world_to_map(local_position)
cell_position -= collision.normal

```

Then `cell_position` should be inside the correct tile.

---
Tags: tiles, godot, scene
---


# Question
Title: RPG - How to deal with the collision of a sprite with a side-view thinner than its front-view?
I am currently working on a role-playing video game featuring sprites that take the form of antropomorphic objects. These sprites can move around in the four cardinal directions, and turn to face the direction they walk in.

Unlike humans, objects are not as equally proportioned all the way around. What this means is that in the case of at least one of my characters, the side-profile of the sprite is a lot thinner than the front-profile, seeing as the object is a harmonica.

This causes a problem with the character's collisions with objects. If the character walked into, say, a tree while facing sideways, then turned to face the front, a large portion of the sprite will inevitably then be inside the tree.

I've considered multiple potential solutions to the problem, but they all seem to have pretty severe drawbacks.

1. Make the side-view hitbox as large as the front-view hitbox. This would mean that players will not be able to walk nearly as close to an object as they should while facing East or West.
2. Push the player out of the object when they turn. This would end up looking quite strange and unclean.
3. Don't allow the player to turn from a side-view when they're too close to an object. This would be confusing and unintuitive.
4. Allow front-view sprites to clip through objects. This would look pretty bad.

I can't think of any other solutions to this problem, nor am I able to choose a different object for this character (for personal reasons). Is what I am attempting to achieve here not viable/possible?

# Answer
> 11 votes
When you implement characters with weird traits, then it is generally a good idea to not try to glance over their weirdness, but to lean into it and make it a part of their game mechanics.

So let's try to approach this problem from the perspective of an animator. When a wide, anthropomorphic harmonica would run into an obstacle and turn sideways, how would it do that?

It can't just turn on its own axis like a regular humanoid character would, because it would then collide with the obstacle. It would need to take a step back before it turns its unwieldy body around and then waddle in the new direction. It needs to walk through a narrow gap with not enough space to move as it would regularly? Well, then it would have to awkwardly squeeze itself through the path by walking sideways. It would look really clumsy, making the character cute and endearing.

This is also what you could be doing in this situation.

1. Have the sprite walk backwards until it has enough space to turn
2. If there is enough space, turn it into the new direction. Preferably using an animation which visualizes the effort it takes to overcome the momentum of its unwieldy body.
3. If there is not enough space, have it walk sideways with reduced speed until there is enough room to turn around

(a skilled animator could perhaps merge 1 and 2 into one animation)

You wondered if this might be unintuitive to the player. I would argue that it might actually not be unintuitive at all. The character *does* have an awkward body shape, which has implications on how it moves through the world.

This mechanic could actually be used for puzzles. For example, imagine a level like this:

```
################################
                             ###
Start                        ###
                             ###
                             ###
############################ ###
############################ ###
#############                     Goal
#############      ######### ###
#############      ######### ###
#############      ######### ###
#############                  #
#############                  #
#############                  #
################################
################################

```

When the character occupies 1x3 tiles, then it could not enter the passage. But when you give it the ability to move sideways, then it could. However, when it also needs 3x3 unblocked tiles to turn, then it could not take the direct path by turning east at the crossroad. It would have to move through the chamber below in order to find enough space to turn from vertical to horizontal.

Now imagine what else you could do with this mechanic when you introduce movable, destructible or switchable blocks. The player needs to consider where it needs to turn the character and what they need to do beforehand in order to clear up the necessary space for doing so.

---

I am looking forward to guiding that adorkable harmonica person through your game world.

# Answer
> 2 votes
**What depth plane is the character in?**

What is the character's position in the Z plane relative to the obstacle? If the character is directly in the same plane as the obstacle, then it's reasonable to assume that the character cannot freely rotate to face the camera--they either must remain facing the obstacle or they must back up in some way to rotate. Nothing seems odd about that to me in either case.

If on the other hand they're actually in front of the obstacle a little bit, then they could rotate to face the player and you'd just draw them a bit in front of the obstacle so it wouldn't look weird. Of course in that case the obstacle isn't really an obstacle...

**In the end, I think you're worry for nothing**

So I think the options you're worried about aren't actually something to worry about. It makes total sense for the character not to be able to rotate freely when right up against the obstacle without backing up first, possibly in a humorous way as suggested by Phillip.

**Why not do a quick test?**

It's always a good idea to do a quick rough test to see what it feels like for the player in the different scenarios in question (in this case different options for what to do when the player tries to rotate to face the camera). Can you rough out animations showing the different options, or better yet, simple storyboards on paper? Whatever lets you see what it would look like for minimal time and effort. Iterate quickly until you find one that feels good. Show them to other people and get their opinions too. Bottom line: get out of theorizing and do some experiments if you haven't done so already. See this article with tips from the legendary Will Wright, designer of Sim City, The Sims, Spore, etc.: https://www.masterclass.com/articles/will-wrights-tips-for-successful-prototyping-in-video-games#the-2-kinds-of-video-game-prototypes

---
Tags: collision-detection, sprites, rpg
---


# Question
Title: Default ScriptableObject inspector duplicates on every ListView onSelectionChange
I'm creating some sort of database editor window, and one of the things I needed to do was show the default inspector for the currently selected scriptable object. It was a bit complicated to achieve due to the lack of documentation, but thanks to some posts (this, this) I got the result I wanted.

However, a great detail appeared, and that is that every time I select an SO from the list (either the same or a different one), the inspector that is displayed is duplicated.

I don't have much experience working with the UI Toolkit, I have followed some tutorials, read the existing documentation, and followed the advice of some posts. I'm still learning how to properly use it.

So, comparing my code with others, and with what I can get from the documentation, I really don't understand the reason for this behavior.

Here are the methods in charge of both creating the list and displaying the selected object:

```
private void GenerateListView()
    {
        Func<VisualElement> makeItem = () => m_ItemRowTemplate.CloneTree();

        Action<VisualElement, int> bindItem = (e, i) =>
        {
            e.Q<Label>("Name").text = m_LevelsDatabase[i].EditorLevelTitle;
            e.Q<Label>("Goal").text = m_LevelsDatabase[i].EditorLevelGoal;
        };

        m_ItemListView = new ListView(m_LevelsDatabase, m_ItemHeight, makeItem, bindItem);
        m_ItemListView.selectionType = SelectionType.Single;
        m_ItemListView.style.height = m_LevelsDatabase.Count * m_ItemHeight;
        m_ItemsTab.Add(m_ItemListView);

        m_ItemListView.onSelectionChange += ListViewSelectionChange;
    }

```

---

```
private void ListViewSelectionChange(IEnumerable<object> selectedItems)
    {
        m_activeItem = (LevelInfo)selectedItems.First();

        SerializedObject so = new SerializedObject(m_activeItem);

        var iterator = so.GetIterator();
        if (iterator.NextVisible(true))
        {
            do
            {
                var propertyField = new PropertyField(iterator.Copy()) { name = "PropertyField:" + iterator.propertyPath };

                if (iterator.propertyPath == "m_Script" && so.targetObject != null)
                    propertyField.SetEnabled(value: false);

                m_DefaultInspector.Add(propertyField);
            }
            while (iterator.NextVisible(false));
        }

        m_DetailSection.Bind(so);

        m_DetailSection.style.visibility = Visibility.Visible;
    }

```

# Answer
Although quite easy, it was just a matter of removing the property field from `m_DefultInspector`.

I had my suspicions that this was the problem, since sure enough, every time the `ListViewSelectionChange()` method was called, `m_DefultInspector.Add()` was also called, which made me wonder: at what point do we reset the value of `m_DefultInspector`? Having little experience using the UI Toolkit, I thought maybe there was some special method to do that.

But no, it was a matter of clearing the variable with the Clear() method before proceeding to add a property field to it.

```
void YourMethod()
{
   m_VisualContainer.Clear();

   // The rest of your code + m_VisualContainer.Add();
}

```
> 1 votes

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


# Question
Title: Gameobject is moving even though I only rotated it
Ok, this problem is kinda hard to explain, but I have this mouselook script as follows:

```
yaw += speedH * Input.GetAxis("Mouse X");
pitch -= speedV * Input.GetAxis("Mouse Y");

playerHead.gameObject.transform.localRotation = Quaternion.Euler(0, yaw, -pitch);

```

(The place I got this script from had pitch in the x axis, but for some reason up and down is the z axis of this game object, and it didn't work right unless I inverted it)

So as I understand it this should only change the rotation, not actually move the gameobject. (too be clear here the camera is inside a game object called playerHead, which is what I want to move to move the camera and the first person arms). So I test this, and looking forwards, as the game starts off, the position and rotation are all 0, depicted below.

For context in the image playerhead is selected so it's the object with the axis near the front of the plane.

Everything's fine right?

But then I turn around, and playerhead has moved. Not only has it moved despite localRotation, as I understand it, being something that should only effect rotation, but according to the inspector it's position is still 0, 0, 0.

For context in the image below playerhead is is selected so it's the object with the axis near the back of the plane.

I'd really appreciate if someone could explain why playerhead moved, and how I could only change it's position, not it's rotation.

# Answer
Thanks to DMGregory who put the solution in the comments. The trouble was with the game object's pivot point. As pictured below the gameobject doesn't change position when I rotate it any more.
> 1 votes

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


# Question
Title: Is there a way to globally/uniquely reference a node in another scene?
I'd like events/actions (e.g. pressing a button, defeating a mini-boss, etc.) in one area of the game to affect things (e.g. unlock/open door, enable boss spawn) in other areas that are distinct/distant enough to exist in another scene.

When the trigger and target are in the same scene (e.g. switch opens door in the same room), it's easy enough to add `export(NodePath) var door_to_open` to the switch's script so that it has a direct reference to the door and can tell it to open. If I move/rename the door node, I just have to update the NodePath, and immediately get an error if I don't (e.g. `target_door = get_node(door_to_open) as Door` and `assert(target_door != null)` in the switch's `_ready`function).

When they are in different scenes, though, such a link isn't possible (since the target node isn't loaded). I've handled this so far by creating an Autoload/Singleton for tracking door state. When triggered, the switches pass in the name of the door they open (something unique but kinda ugly, like "Building1-Floor7-Door3") and it gets included in a list of open doors. In the `_ready` function of the door script, I call into the same Singleton to check whether the door should be open or closed. This *works*, but is quickly becoming a maintenance headache. Moving things in the scene tree and changing the node path isn't an issue, since each door has a name property associated with it. However, changing the names (infrequent, but happens as I'm building things) breaks the link and requires changing the name in both locations (the door in once scene getting opened, and the switch in some other scene that opens it). The worst part is that forgetting to change it (or just making a typo mistake) just means that the names used by the two ends of the set/get are different, and it just looks like the door is not open yet and no error happens (it's perfectly fine for a door's name to not be in the list; it just means it hasn't been opened). Makes testing/debugging more difficult.

Is there a more straightforward way to establish a (one-way) link between two nodes in different scenes? Or at least to consolidate the name variable so that there aren't two independent String declarations (switch, door) that might get mismatched at some point?

# Answer
> 3 votes
---

**Autoload**

I believe the Autoload approach is correct. In particular if you need to persist the state of the doors, or the door you are opening might not be loaded yet (which - if I understand correctly - is the case).

Perhaps you can work on a naming convention that is more resistant to changes. What comes to mind is to name the door based on the rooms the door connects (you could give code names to the rooms).

---

> Is there a more straightforward way to establish a (one-way) link between two nodes in different scenes?

You can use a signal bus (event bus). That is, you declare signals in an Autoload, and other nodes can connect to it, or emit it (yes, the script of an object can emit signals of another object). *However, it does not persist any state, and requires the node on the other side to be loaded and connected to have any effect.*

---

**Resource based communication**

> Or at least to consolidate the name variable so that there aren't two independent String declarations (switch, door) that might get mismatched at some point?

There is a way: use resources based node communication.

For example, you can create a new script from the File System panel by choosing "New Script...", and there declare a `DoorLink` (or however you want to call it) class that `extends Resource`.

Once you have the resource class, you can make resources of that type from the File System panel (on the context menu choose "New Resource…" and pick your class when asked).

Then you can either export a resource variable (which, to be fair, has lack luster support, see proposal 18), so you can set your resource there (you can drag it from the File System panel to the Inspector panel), and Godot will keep track of it if you rename the resource. *To be clear: drag the resource file, not the script with the resource class.*

Or you can `preload` the resource file, and Godot will report a parse error if the path is not correct.

And, as a bonus, they all get the same object. Everywhere you have set the same resource will have the same object. So you can use it for communication. I suggest to declare a property with a signal when it changes in the resource class.

For example:

*door\_link.gd*

```
class_name DoorLink
extends Resource

signal is_open_changed(new_value)

export var is_open:bool setget set_is_open

func set_is_open(new_value:bool) -> void:
    if is_open == new_value:
        return

    is_open = new_value
    emit_signal("is_open_changed", new_value)
    emit_signal("changed")

```

*By the way, the `Resource` class defines a `"changed"` signal, which is meant to be emitted when the properties of the resource. We have to do that manually for custom resource classes. And so I did in the code above.*

The main drawback is, of course, that you would have a bunch of resource files.

---
Tags: godot, state, gdscript
---


# Question
Title: How do I ignore collision between This object and the Other?
I'm just starting out in Unity and I'm making this cute & janky little rocket game. I want to implement a "medallion" pickup. My code looks like this:

```
public class CollisionHandler : MonoBehaviour {

    void OnCollisionEnter(Collision other)
    {   switch(other.gameObject.tag){
            case1 "Collectable":
                AudioSource.PlayOneShot(AudioClip);
             // Physics.IgnoreCollision(other, GetComponent<Collider>(), true);
                Destroy(other.gameObject);
                break;
            default:
                break;
        }
    }
}

```

Everything works up until the "Physics.IgnoreCollision" line. Specifically, Unity tells me "Error: Cannot convert from 'UnityEngine.Collision' to 'UnityEngine.Collider'". At least I know that "Collisions" and "Colliders" are different objects but I still have no idea what I'm doing wrong because I don't even know how to do this right in the first place.

I want to get the "Collision" component of my rocket doohickey. When I get the medal, it disappears and the audion plays, but it's like I just flew into a floating wall! I want the player to pass through the medal as they collect it. The medal vanishes and the sfx play.

Where am I going wrong? Is there an easier way to do this? I'd love links, advice, tutorials, etc. I have no idea if anybody else has asked this question before me.

# Answer
> 0 votes
After the collision has occurred is too late to ignore it.

Instead, you can click the "Is Trigger" checkbox on one of the two colliders involved in the collision (or set this in code with `collider.isTrigger = true` *before* the collision occurs) to make it a kind of "ghost" collider. It will *detect* collisions with other colliders, and report `OnTriggerEnter`/`Stay`/`Exit` events, but will not alter the motion of the body it contacted or its own rigidbody in response to the collision.

For a medallion pickup, you almost certainly want the medallion's collider to be a trigger, and then pick it up inside `OnTriggerEnter()`.

If you need both objects to use non-trigger colliders (ie. they need to have solid, bouncing collisions with other things, just not with each other), you can use physics layers and collision masks to separate their non-trigger colliders so they don't interact, then add an extra trigger collider to one of them that interacts with the other.

I'd also recommend using physics layers and collision layer masks instead of tag checks when you can. It's much more efficient to simply never process the collision in the first place, because the two layers don't interact, rather than processing the collision and invoking a collision handler routine that does nothing.

# Answer
> 0 votes
I would suggest to move the objects into different layers, then in the Layer collision matrix settings uncheck the layers that you want to ignore collisions between.

Here's the reference: Layer-based collision detection

---
Tags: unity
---


# Question
Title: weird blurring of tiles in unity2d tilemap
My tiles don't have any anti-aliasing because I am going for a pixelated look. But when I add my tiles to a tile map it automatically puts anti-aliasing on them. My tiles look like this:
when they should look like this:
Why is this happening and how can I fix it?

# Answer
I'm guessing you need to change your texture import settings 'Filter Mode' to 'Point':
> 1 votes

---
Tags: unity, sprites
---


# Question
Title: Having a Logic Error in my tile rendering code
I am a novice programmer.

In my program, I can render a 5000 x 500 map, but it renders incorrectly, instead of this :

,,~,,,,~,,,,,~,~,,,,,~~,,,~,,,~,,,~,,~~~,~~~,,,~,,,,~,~,,,~~,~,,~,~,~~,~,,,,,~,,~~,,~,,,,,,~,,,,,~,,~~,~,,,,,,,~,,,,~,~~,,,~,,,~,~~~,,~~~,,,,,,,,~,~~,,,,,~,,,,,~~,,,~,,~~,~~~,,,~,,~,~,,~,,,~~,~~,~,,~~~~~,~,,,,,~,~,~,~,,,,~~,,~,,,,,~,,,~,,~,,~,,,,~~,,,~,,,,,,,~,~,,,,,~,,,,~,~~,~,,,,,,,~,~~,,,,,~~,,,,,,~,~~~~,,~,,~,,,,~~,,,,~~,~~~,,~,~,,~~~~,,,~,,~,,,,~~,~,,,,,,,,,,,~,,~~,,~,~,~,,,,~~,,,,,,,,,~,,,~,,,,~~~,,,~,,~,,,,,~,,~,~~,,~~,,,,~,,~,,,,,,,,,,,,~~,,,,,,,,~,,~~,,,,~,,,~,,,,~,,,,~,,,,,,~,,,,,,~,~,,,,,,,~,,~~~,~~~~,,~~,~,~,~,,,~,~,,~,~~,~,,,,,,~,~,~,,,,~,,,~,,~,,~,,,,,~~~~,,,,,~,,,~~,,,~,,,,~~,~,~~,~,~~,~,~,~~~~,,,~,,,,,,~,,,,,,,~,,,,,~~,~~~,,~~,~~,~,,~,,~~~,,,,,,~~,~,~,,,,~,,,,,,,,,,~~,,,,~,,~,,~~,,,~,,,,~,~,,~,~,,,~~~~,~,,,,,,~~~,,~,,~~~,~~~,~,,~,,,~,,,,,,~~,,,,~,,,~~~,,~,~,,,,~~,~,,,,,,~,~,,~~~,,~~,,,~,,,,~,,~,~,,,,,,,,,~~,,,,,,~~,~~,,,~~~,,~,~,~,,,~~,,~,,,,,,,,,~,~,,~,,,,,,,~,,~,,~~~,~~,~,,,,~,~,,,,,,~,,,~,,,,,,,,,~,,~~~~,,,~~,,~,~,,~,,,,,,~~~~~~,,,~,,,,,~,,,,,,~,~,,,~~~,~,,~,~,,,,,,~,~,~,,,,,,~,,,~~,~,,,,,~~,~,~,,~,~~,,~,,,~,,,~~~,,,,,~,,~,~,,,~,~,,~~~~~~,,,,~,,,,,,,,,~,,,~,~~,,,,,,,,~,~~,,,,,~,,~~,,~,~~,,,,,~,,,~,,~~,~,,~,,,,,,,,,~~,~~,~,,,~,,~~,~~,,,~~,,~~~~,,,,,,,,~,,,,,~,~,,

which was generated using a random coin flip

it renders the tiles in weird lines like this:

```
~.~.~.~.
~.~.~.~.
~.~.~.~.

```

Here is the link to the source code

Here is the rendering code:

```
    // Tile Renderer.

    let screen_w_in_tiles: f32 = ceilf(screen_width() / 32.0);
    let screen_h_in_tiles: f32 = ceilf(screen_height() / 32.0);

    let center_tile_x = ((screen_width() / 2.0) - worldx as f32) / 32.0;
    let center_tile_y = ((screen_height() / 2.0) - worldy as f32) / 32.0;

    let lo_tile_x = floorf(center_tile_x - screen_w_in_tiles / 2.0);
    let hi_tile_x = floorf(center_tile_x + screen_w_in_tiles / 2.0 + 2.0);

    let lo_tile_y = ceilf(center_tile_y - screen_h_in_tiles / 2.0 - 2.0);
    let hi_tile_y = ceilf(center_tile_y + screen_h_in_tiles / 2.0);

    for i in lo_tile_x as usize..hi_tile_x as usize {
        for j in lo_tile_y as usize..hi_tile_y as usize {
            match world_data[i] {
                ','=> tile = grass,
                '*'=> tile = sand,
                '~'=> tile = water,
                '/'=> tile = ice,
                _=>   tile = unknown,
            }
            blit(tile, i as isize * 32 + worldx, j as isize * 32 + worldy, 32, 32);
        }
    }

```

# Answer
> 1 votes
*I think the code is doing what you are asking it to do. However, I have some idea of what you want. I might be wrong but… Well, you try and tell me.*

---

We have 1D data is `world_data`, but it is intended to be 2D. So we are going to map a 2D position of the world to a 1D position on `world_data`. In this particular case I'm going to do it by lines. *Because it is simple, be aware that there are other approaches to do this.*

Since we know the size of the first dimension (the width of the world) is 5000, we are going to assume we have lines of 5000 elements.

The y coordinate will tell us on which line we are, in other words how many lines we have to skip. The start of the y-th line is `5000 * y`. And the x coordinate will tell us the position inside the line. In other words, the position in `world_data` will be given by `5000 * y + x`. Or in you code:

```
world_data[5000 * j + i]

```

*I'll take the opportunity to suggest storing that 5000 in a variable or constant so you can change it in a single place.*

---

**Addendum**: I forgot, it is possible that goes out of bounds, so you will want a check, something like this:

```
for i in lo_tile_x as usize..hi_tile_x as usize {
    for j in lo_tile_y as usize..hi_tile_y as usize {
        let p = 5000 * j + i;
        if p < 0 || p >= world_data.len() {
            // perhaps draw some background here
            continue;
        }
        match world_data[p] {
            /* etc. */
        }
        // …
    }
}

```

---

**Addendum 2**: The above approach does not cut the edges of the world. We could do it with `lo_tile_x`, `lo_tile_y`, `hi_tile_x`, and `hi_tile_y` instead, by clamping them. I believe this works:

```
lo_tile_x = fmin(fmax(lo_tile_x, 0.0), 5000.0); # width
hi_tile_x = fmin(fmax(hi_tile_x, 0.0), 5000.0); # width
lo_tile_y = fmin(fmax(lo_tile_y, 0.0), 5000.0); # height
hi_tile_y = fmin(fmax(hi_tile_y, 0.0), 5000.0); # height

```

*I decided to go with libm::fmin and libm:fmax instead of clamp.*

Then it should not go out of bounds in the loop. Which means it should work without the fix from the prior addendum.

By the way, you could have the world loop instead. Which would be using the remainder. I hope it works like this:

```
lo_tile_x = ((lo_tile_x % 5000.0) + 5000.0) % 5000.0; # width
hi_tile_x = ((hi_tile_x % 5000.0) + 5000.0) % 5000.0; # width
lo_tile_y = ((lo_tile_y % 5000.0) + 5000.0) % 5000.0; # height
hi_tile_y = ((hi_tile_y % 5000.0) + 5000.0) % 5000.0; # height

```

*I know that is not pretty, but I can't figure out what is the correct modulo function in rust. Modulo as in modulo arithmetic, not remainder. The result should be positive.*

---

You can, by the way, use division and reminder to find the 2D coordinantes that will match a position from `world_data`. If do an integer division of the the 1D position by the width of the world, you will get the y coordinate, and x is the remainder of said division. *You may find this useful for generating the world, for example if you need to query a 2D noise function.*

---
Tags: tilemap, tiles, terrain-rendering, rust
---


title: change camera angle in unity2d

text:
# Question
Title: change camera angle in unity2d
I am creating a 2d top-down game in Unity where you can press a button and the camera will cycle into different angles, mainly forward, backward, left & right. I have gotten the cycle to work by toggling on and off the tilemap renderers of rotated duplicates of the main tilemap, but the character does not translate with the "flip" of the tilemap. I am wondering how I would get the character to "flip" with the cycle.

Steps to reproduce:

1. Create a new unity2d project
2. Create a basic 2d character with a character controller script
3. Setup and create a tilemap
4. Duplicate and Rotate the tilemap by 180 on the Y and Z axis.
5. Add this script to your player:

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

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

    public TilemapRenderer forwardTilemap;
    public TilemapRenderer backwardTilemap;

    private bool forward = true;
    private bool backward = false;

    void Start()
    {

    }

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

        if (Input.GetKeyDown("c"))
        {
            if (forward)
            {
                backward = true;
                backwardTilemap.enabled = true;
                forwardTilemap.enabled = false;
                forward = false;
            }

            else if (backward)
            {
                forward = true;
                forwardTilemap.enabled = true;
                backwardTilemap.enabled = false;
                backward = false;
            }
        }
    }
}

```
6. Add the TilemapRenderers to the respective variables:
7. Play the game.

Edit: I should clarify: My player movement script is this:

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

public class PlayerMovement : MonoBehaviour
{
    // public vars
    public float moveSpeed = 5f;
    public Rigidbody2D rigidbody;

    // private vars
    Vector2 movement;

    // Update is called once per frame
    void Update()
    {
        // Input
        movement.x = Input.GetAxisRaw("Horizontal");
        movement.y = Input.GetAxisRaw("Vertical");
    }

    void FixedUpdate()
    {
        // Movement
        rigidbody.MovePosition(rigidbody.position + movement * moveSpeed * Time.fixedDeltaTime);
    }
}

```

And the script that I use to change the perspective does this

See the problem is that the character stays in the same spot when I toggle the perspective.

# Answer
I imagine you are using an animator component for moving your character and there's a parameter that controls the direction and it's in the following order:

* 0 for right
* 1 for back
* 2 for left
* 3 for front

and you set the value according to the key pressed at the time (e.g. "s" means 3)

So what you have to do is add an additional number (according to the current camera) to what you get from user input and then pass it to the animator.

In the "backward tilemap" example, you should add 2 to what you get as input (so if "d" was pressed, you have to pass 0 + 2 to the animator), and don't forget to use `%4` as it keeps the parameter between 0 and 3
> 0 votes

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


# Question
Title: How many command lists should there be in DirectX 12?
I'm new to DirectX 12. I understand some of the basics.

For speed and optimization, is it better if I have more than one command queue, command list, and command allocator? If so, how many should I have of each for a high performance game?

# Answer
> 1 votes
As with all optimization advice: **It depends**.

The basic render loop is one `D3D12_COMMAND_LIST_TYPE_DIRECT` *Command Queue*, one *Command Allocator* per backbuffer swap chain (2 or 3), and each frame has one *Command List* (reset from the appropriate command allocator) for graphics drawing.

Beyond that is really depends on what else you are doing.

* You can upload resources on a distinct *Command Queue* (typically `D3D12_COMMAND_LIST_TYPE_COPY`), which can let you do resource upload on another thread while rendering on a main thread.

> The `ResourceUploadBatch` in DirectX Tool Kit for DX12 supports doing upload batches on any queue type. The main trick there is handling the resource states which are restricted on COPY and COMPUTE queues compared to DIRECT. Each instance of `ResourceUploadBatch` (which would be one per uploading thread) has it's own *Command Allocator*, and each batch of work is it's own *Command List*.

* If you are using asynchronous compute, you can submit the work on it's own `D3D12_COMMAND_LIST_TYPE_COMPUTE` Command Queue. Again, each batch of work is it's own command list.
* If you are doing multi-threaded rendering, you can build different command-lists on each thread. See this sample.

By design, the DirectX 12 work submission design is flexible and largely left up to the developer depending on their application's needs. See Microsoft Docs.

The optimal number of *Command Queue* instances of course depends on the specific GPU you are using, but typical modern GPUs have at least one "Graphics" hardware queue which maps to DIRECT, one "Compute" hardware queue which maps to "COMPUTE", and one DMA engine hardware queue which maps to "COPY".

> See also directx-vs-templates.

---
Tags: c++, directx12
---


# Question
Title: How do I offset a texture pointer in order to store an array of D3D11_SUBRESOURCE_DATA?
I'm attempting to load a sequence of frames from a GIF into a `Texture2DArray` using `stbi_load_gif_from_memory` which returns a pointer to the texture data. I'm stuck on what to do for offsetting into the texture data in order to split it up into the array of `D3D11_SUBRESOURCE_DATA` objects:

Image img = Image(filepath); //Custom class that loads a .gif using stbi_load_gif_from_memory.

D3D11_TEXTURE2D_DESC tex_desc{};
tex_desc.Width = img.GetDimensions().x;  //width...
tex_desc.Height = img.GetDimensions().y; //...and height of image in pixels.
tex_desc.ArraySize = img.GetDimensions().z; //...Depth, i.e. number of frames
tex_desc.MipLevels = 1;
//...Snip setting up D3D11_TEXTURE2D_DESC

// Setup Initial Data
std::vector<D3D11_SUBRESOURCE_DATA> subresource_data{};
subresource_data.resize(img.GetDimensions().z);

const auto width = img.GetDimensions().x;
const auto height = img.GetDimensions().y;
for(int i = 0; i < img.GetDimensions().z; ++i) {
    subresource_data[i].pSysMem = img.GetData(); //Return a pointer to the front of the texture data array.
    //The above is INCORRECT. It sets *every* frame to the first!
    subresource_data[i].SysMemPitch = width * sizeof(unsigned int); // pitch is byte size of a single row)
    subresource_data[i].SysMemSlicePitch = static_cast<unsigned long long>(width) * static_cast<unsigned long long>(height) * sizeof(unsigned int);
}
```
</code></pre>

# Answer
> 1 votes
The offset is what you computed for `SysMemSlicePitch`, so for a 2D Texture array *without mipmaps* something like:

```
const UINT rowPitch = width * sizeof(unsigned int);
const UINT slicePitch = height * rowPitch;
const uint8_t* srcPtr = img.GetData();
for(int i = 0; i < img.GetDimensions().z; ++i) {
    subresource_data[i].pSysMem = srcPtr;
    subresource_data[i].SysMemPitch = rowPitch;
    srcPtr += slicePitch;
}

```

Of course adding mips add more subresources to the mix, and a 3D/volume texture with mips is even more complicated. For examples of *all* the kinds of things you might see here, see DirectXTex and/or the DDSTextureLoader.

---
Tags: textures, directx11, hlsl, array
---


# Question
Title: Why do my point lights disappear when another nearby light is above 1.85 range?
I'm making a game with a dungeon setting in Unity 3D. Many torches line the walls. I'm using a point light over each torch to simulate the flame. However, when two torches are across from each other, and one goes above the 1.85 range, the other disappears completely, giving off no light.

What might be causing this?

# Answer
1. Select the Light object
2. Go to Inspector
3. Light
4. And change rendered mode "Auto" to "important"
> 15 votes

# Answer
Unity only renders a limited number of pixel lights at a time; exactly how many depends on the quality level. The most 'important' pixel lights are chosen, and brightness is a significant part of how 'important' a light is.
> 9 votes

# Answer
You should go to `Edit > Project Settings > Quality` and change the `pixel light count` to a higher value.
> 6 votes

# Answer
I don't know if you guys are still trying to figure this out, but I had the same issue awhile back and solved it by only using a single point light per dueling torches.

Set your torches up with flame particle systems, and then set the point light at the center of the hallway between the two torches. The particle systems draw the eye away from the origin point between them, and the majority of players aren't going to notice that detail anyway. This will cut the number of point lights in your scene while still maintaining the same effect.

If you do the above, or even if you don't, and want to be even more effective with lighting, set a collider as trigger on your torch prefab and use OnTriggerEnter / OnTriggerExit to turn the lights on and off as the player passes through the level (you could even set two box colliders on each light and lay them across the hallway in tactical locations).

This will give you much more control over which lights are on and off, as well as give possible performance boost depending on how many torches you have.
> 4 votes

# Answer
I had the same problem. To solve it, you have to set the light's rendering priority.

Select the Light in your scene hierarchy, and inside the "Light" component, change "Render Mode" to "Important".
> 1 votes

# Answer
Im pretty sure the problem is caused by one point light being in the range of the other point light so, for lag issues Unity only renders one of these lights. This can be fixed by increasing the intensity of the light and decreasing the range of it.
> 0 votes

# Answer
If anybody is still looking for the answer, you could either : \- select the light and change render from 'auto' to 'important' Or \- go to edit-\> project setting -\> quality -\> increase pixel light count to your desired number of lights.
> 0 votes

# Answer
I just ran into this problem in 2021.2.7 with URP and the suggestion of " edit-\> project setting -\> quality -\> increase pixel light count" does not work, as that setting is not there.

Instead, if you are using URP - go to your Universal Render Pipeline Asset and increase the Per Object Limit value, located under Lighting \> Additional Lights.

Alternatively, I was also able to solve this by reducing the radius of my spotlight - which effectively meant that the lights were not overlapping each other as much.
> 0 votes

---
Tags: unity, lighting, debugging
---


# Question
Title: Pygame : having trouble with implementing movement with vectors
I've been struggling a lot to learn how to use vectors in programming. Now I've successfully made my own vector class but I still can't use vectors for movement.

This is my class :

```
class MyVector2(object):

    def __init__(self, x, y):
        self.x, self.y = x, y
        self.tuple = (self.x, self.y)

    def __str__(self):
        return f"({self.x}, {self.y})"

    @property
    def magnitude(self):
        return math.sqrt(self.x**2 + self.y**2)

    def normalize(self):
        self.x /= self.magnitude
        self.y /= self.magnitude

    @staticmethod
    def create_path(destination, pos):
        return MyVector2(destination.x - pos.x, destination.y - pos.y)

    @staticmethod
    def dot(v1, v2):
        return v1.x * v2.x + v1.y * v2.y

```

(there are also other methods for the operations (+/\*-) that I don't need to copy here)

My problem with movement is that the object I want to move doesn't stop at the destination but continues moving infinitely :

```
class Obj(object):
    def __init__(self):
        self.x, self.y = 100, 80
        self.speed = 0.1
        self.pos = MyVector2(self.x, self.y)
        self.img = img
        self.moving = True

    def blit(self):
        screen.blit(self.img, (self.pos.tuple))

obj = Obj()
dest = MyVector2(150, 130)
path = MyVector2.create_path(dest, obj.pos)
path.normalize()
while True:
    obj.blit()
    if obj.moving:
        obj.pos += path * obj.speed
    if dest == obj.pos:
        obj.moving = False

```

I also think that my way of using vectors to move objects is bad, so please provide me with a professional one.

# Answer
A friend of mine has found the issue for my code and it was related to the Vector class :

```
def normalize(self):
    self.x /= self.magnitude
    self.y /= self.magnitude

```

Here in the `normalize()` function, once the `self.x` value gets divided by the magnitude, the magnitude changes as it is related to it. So this means the `self.y` value will be then divided by the 'new' magnitude and this will lead to a disorder.

Therefore, the solution is this :

```
def normalize(self):
    m = self.magnitude
    self.x /= m
    self.y /= m

```

That will prevent the problem from happening by saving the magnitude in a variable inside the `normalize()` function. And after trying this, everything worked well and I successfully implemented vector movement in pygame !
> 1 votes

---
Tags: movement, vector, python, pygame
---


# Question
Title: Game centered around words - Implement language option or separate app?
I created a puzzle game with gameplay about words using the English language. I want to translate the whole game into my native language (Croatian) and don't plan to have any other languages for now, other than English.

Language has a very major impact - from the title of the game, core gameplay, difficulty, all the way to leaderboards.

Should I create the game as a separate app in my native language or incorporate it into a single app?

I should also mention that my main platform of distribution is Google Play so I don't know how this will affect user reach.

# Answer
> Should I create the game as a separate app in my native language or incorporate it into a single app?

It depends on some factors. It is ultimately up to you, but you may want to choose depending on your design and development needs.

### Localising games

When it comes to localisation, developers must consider both visual and audio content. Translators must work on texts, and actors may record dialogues for different locales. Regardless, both audio and text are **assets** that the game can load and use during execution without affecting the core gameplay. Many game engines support this methodology because it encourages asset management over scattering the same codebase across slightly different projects.

### Localising wordplay

Words-centred games are hardly an exception here. However, whereas translating/localising the interface is a trivial task, you may give special attention to the design balance needed for different languages.

Games like Scrabble and Boggle heavily revolve around letters to create words. Different languages have different words and varying letter frequencies in that language. I expect the English version of Scrabble to feature more of some letters than, say, the Italian or Croatian editions, given the different letter frequencies of these languages. (Quick comparison: ENG vs. ITA vs. HRV). The same principle applies to Boggle and its digital derivative Ruzzle. The game rules apply to words, not letters. Balancing the letter draws makes the game balanced because players can easily find/create words common in their language – as they would expect. Some more examples:

* Italian word games have fewer unique letters (no J's, K's, W's, X's, and Y's) because they don't belong in the traditional Italian alphabet. Nonetheless, the game rules are the same, with only the Reference Dictionaries being different.
* Diacritics are taken into account by simply assuming them where needed. If a letter can have diacritics, the game will validate variants if they lead to a correct entry.

I must make a special mention to Wordle, the latest entry in the word games hits. While the above games treat letters as a limited **resource**, Wordle doesn't. You can write whatever you want to guess the hidden word, as long as it's a 5-letter entry. The only limit here is the maximum number of attempts.

In this context, the design focuses more on a word's 'rarity' in its everyday use in a specific language rather than the rarity of individual letters. This shift still adapts to different languages, and this is due to word frequencies. Italian Wordle exists and its rules are the same as the original, with only the reference words being different. A 5-letter word doesn't necessarily translate to another 5-letter word.

### Localising *your* game

To sum up, all the above games (and probably many others) work well in different languages thanks to some tweaks about the game resources (namely, letters), but without altering the core gameplay at all.

> Language has a very major impact - from title of the game, core gameplay, difficulty all the way to leaderboards.

Localising the game title could be just a translation/transcreation task. The game difficulty can rely on the target language without affecting the core mechanics. Leaderboards are an additional feature linked to the game difficulty and region-dependent for word games. But, I'm not going to discuss them further.

Usually, balancing a game requires extensive testing to find the correct parameters for any given level of difficulty the designer intended. For word games, the game difficulty tightly depends on the language used. Then, minor tweaks are perfectly fine if they help support your intended game experience.

If you still want to alter your core game mechanics, you must consider that the final result could be a different game or game variant. Users expect game variants to be in the same app they downloaded, not a different one. In the case of a different game, you should instead differentiate it from the original, pre-localisation project and create a separate app for it. This way, you will prevent users from being confused by a game that behaves differently depending on the geographic location.
> 1 votes

---
Tags: localization
---


# Question
Title: How to generate the in-game world map UI for a large world?
I would like to generate a map of the game world (i.e. a world map for a full screen UI). I am not an artist so would like to automate the process. For small levels I was able to do this by capturing the scene with an orthographic camera offline into a texture. Now that my world is bigger (~100km x 100km) I worry about how big the texture will need to be for this to work. What are some common approaches for solving this?

# Answer
Usually the approach to rendering something "too large" in any sense is to split it into several overlapping small parts, render each part separately and then compose the individual render results, by hand or automatically.
> 2 votes

---
Tags: textures, gui, maps
---


# Question
Title: How to handle mouse wheel events in the Pyxel game engine
I'm trying to handle mouse wheel input (aka scroll wheel) on a plain old mouse.

```
if pyxel.btn(pyxel.MOUSE_WHEEL_Y):
    print(pyxel.mouse_wheel)

```

This never triggers.

The `pyxel.mouse_wheel` value holds small signed integers when I use the wheel while triggering another input e.g. keyboard.

# Answer
> 1 votes
The *yet to be documented* `btnv` function must be used to test the occurrence of 'valued' events such as analog sticks and various wheels:

```
if pyxel.btnv(pyxel.MOUSE_WHEEL_Y):
    print(pyxel.mouse_wheel)

```

---
Tags: events, mouse
---


# Question
Title: Vertex color values are not smoothly transitioning/interpolating in Godot shader
I'm trying to write a shader for terrain that will color the mesh based on slope angle, ie color the sides of mountains or other steep surfaces a different color than the ground. In my shader I am checking the normal of a vertex, and if its angle is past a certain threshold then I set the vertex color to black, otherwise white.

What I'm getting is that solid colors are being applied across entire faces:

But I'm expecting the colors to smoothly transition between vertices:

Here's my shader code:

```
shader_type spatial;

uniform float slope_threshold;
varying vec3 vColor;

void vertex() {
    float slope_angle = degrees(dot(NORMAL, vec3(0, 1, 0)));

    if (slope_angle < slope_threshold) {
        vColor = vec3(0, 0, 0);
    }
    else {
        vColor = vec3(1, 1, 1);
    }
}

void fragment() {
    ALBEDO = vColor;
}

```

Am I writing the shader wrong somehow? Am I exporting my terrain model from Blender incorrectly? Any help would be greatly appreciated!

# Answer
This is what happens: All the vertex of each triangle of your mesh has the triangle Normal. You decide a Color per Vertex based on that Normal. The GPU interpolates the Colors of the Vertex of each triangle. But since they are on the same triangle, they have the same Normal, and thus the same Color, so there is no visible interpolation.

You can enable the visualization of Vertex Normals in Blender. *Ask me where the option is if you want a rant about Blender UI. Search a tutorial if you want to know where the option is.*

Anyway, the solution? Tell Blender to do Shade Smooth.

What actually happens is that flat shading results in duplicate Vertex. So they aren't shared between triangles. With smooth shading, the triangle actually share Vertex.

---

*By the way, the dot product gives you (a value proportional to) the cosine of the angle between the vectors. Not the angle. Applying the conversion from radians to degrees to cosine of the angle makes no sense.*
> 2 votes

---
Tags: shaders, godot, color, vertex, vertex-shader
---


# Question
Title: Unity2D predictive bow aiming using object array only displaying vertically
I am making a bow and arrow game in Unity2D, and I want to use an Angry Birds style predictive aiming system(like in this image https://i.stack.imgur.com/A6Jqy.png).

I have loosely followed a tutorial, but for whatever reason, in my game, it only predicts on the vertical axis. The code works by initializing GameObjects and placing them in a list. Here is the code:

```
for(int i = 0; i < Points.Length; i++){
                Points[i].transform.position = PointPosition(i * time);
            }

```

```
Vector2 PointPosition(float t){
        Vector2 currentPointPos = (Vector2)transform.position + ((direction.normalized * force * t) * 0.5f * Physics2D.gravity * (t*t));
        return currentPointPos;
    }

```

The way I understood it, by using the `+` operand on `transform.position` it would add to both axis'. Am I wrong about this? Do I need to do two operations for both axis'? Or is my error somewhere else?

# Answer
> 1 votes
You have a typo in your formula:

```
Vector2 currentPointPos = (Vector2)transform.position
     + ((direction.normalized * force * t)
     * 0.5f * Physics2D.gravity * (t*t));

```

Should be:

```
Vector2 currentPointPos = (Vector2)transform.position
     + ((direction.normalized * arrowSpeed * t)
     + 0.5f * Physics2D.gravity * (t*t));

```

The gravity term should be added, not multiplied.

Also, the coefficient on the aiming direction is a speed (so that together they make a velocity), not a force. Using a force value in this place will not give you a correct prediction.

You can slightly improve this prediction by adding half a physics timestep's worth of acceleration to the velocity term.

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


# Question
Title: How can I create an instance of an object on mouse click where the cursor is in SFML?
I'm new to coding. I'm trying to make a simple game where you can left click to spawn a salt "molecule" and right click to spawn a water one where the mouse cursor is. I don't know how to spawn a molecule where the mouse cursor is. I've been trying for a couple of days now.

```
//I've tried this:
Texture textureSalt;
textureSalt.loadFromFile("graphics/salt.png");
Sprite spriteSalt;
spriteSalt.setTexture(textureSalt);
spriteSalt.setPosition(/*I don't know what to put here; how to get it to spawn where the mouse is.*/)

```

Please help and thanks!

# Answer
> 0 votes
You can use the `getPosition()` function inside the Mouse class to retrieve the current position of the mouse cursor.

```
const sf::Vector2i mousePosition = sf::Mouse::getPosition();

// Convert the Vector2i, containing the mouse position, to a Vector2f since the setPosition function doesn't accept Vector2i
spriteSalt.setPosition(sf::Vector2f((float)mousePosition.x, (float)mousePosition.y));

```

---
Tags: c++, sfml
---


# Question
Title: Can you call a method from the script of all instantiated prefabs of a cetain object?
I am currently trying to recreate chess and the problem I am having is that I need to instantiate all of the pawns in a loop (I could write it out but it seems inefficient) and I need to be able to call a method from all of the pawns to look for a check (I'll probably use raycast but I haven't gotten to that yet). How can I go about calling the method that looks for checks from all of the instances of the pawn?

*I'm pretty new to unity so please go easy on me if I said something dumb*

# Answer
> 0 votes
One thing you could do is give all the pieces of each player the same tag and then use `GameObject[] whitePieces = GameObject.FindGameObjectsWithTag("white");`. That gets you an array of gameObjects which you can iterate with a for-loop.

Now you need to determine the type of each piece. You could do that in a variety of ways. For example, you are likely going to put a different component on each piece. so you can use `GetComponent<Pawn>()` or `GetComponent<Rook>()` and see if you receive a non-null return value. Or maybe you just have one unified component `ChessPiece` which has a public field exposing its concrete type, so you could do something like `if (piece.GetComponent<ChessPiece>().type == PAWN)`.

# Answer
> 0 votes
> I need to instantiate all of the pawns in a loop...and I need to be able to call a method from all of the pawns

So, keep a reference to them in the loop where you instantiate them. That might look something like this:

```
public class ChessArmy : MonoBehaviour {
    [System.Serializable]
    public struct Prefabs {
        public ChessPiece king;
        public ChessPiece queen;
        public ChessPiece bishop;
        public ChessPiece knight;
        public ChessPiece rook;
        public ChessPiece pawn;
    }

    [SerializeField] Prefabs _prefabs;

    List<ChessPiece> _pieces = new List<ChessPiece>();

    void AddPiece(ChessPiece prefab, int row, int column) {
        var place = new Vector3(-3.5 + column, 0, -3.5 + row);
        var piece = Instantiate(prefab, place, Quaternion.identity);
        _pieces.Add(piece);
    }

    public void SpawnArmy(bool mirror) {
        int backRow = mirror ? 7 : 0;
        int frontRow = mirror ? 6 : 1;

        AddPiece(_prefabs.rook,   backRow, 0);
        AddPiece(_prefabs.knight, backRow, 1);
        AddPiece(_prefabs.bishop, backRow, 2);
        AddPiece(_prefabs.queen,  backRow, 3);
        AddPiece(_prefabs.king,   backRow, 4);
        AddPiece(_prefabs.bishop, backRow, 5);
        AddPiece(_prefabs.knight, backRow, 6);
        AddPiece(_prefabs.rook,   backRow, 7);

        for (int i = 0; i < 8; i++)
            AddPiece(_prefabs.pawn, frontRow, i);
    }

    public bool HasCheck(ChessBoard board, List<ChessPiece> checkers) {
        checkers.Clear();

        foreach (var piece in _pieces) {
            if (piece.HasCheck(board))
                checkers.Add(piece);
        }

        return checkers.Count > 0;
    }
}

```

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


# Question
Title: Sumo with Unity - Generate osm file of 3d model
I am working on **SUMO with unity** using this open-source project. But stuck in a problem: The background is, we need an open-street-map compatible 3D model in unity. I mean the model should be the same as the open-street-map. Sumo generates road network according to osm file. Therefore the traffic simulation properly sync in both applications (Sumo software and in unity). But my problem is I have a changed model. The model is not 100% according to OSM file or it doesn't match 100% road structure of the osm file. The reason is we have modeled slightly upgraded structure.

Is there any way that I easily edit my OSM file according to my model or vice-versa? Or I create an osm file of my 3d environment? So that it can properly sync with simulation?

# Answer
The project you use imports the same OSM data once into SUMO and once into ESRI city engine. So the easiest way to get the same network is to modify the OSM input data either directly in OpenStreetMap which you might prefer if they reflect changes in reality which you want to give back to the community or by using JOSM or a similar local (offline) OSM editor. There is currently no known way (at least to me) to convert a SUMO network back to OSM.
> 0 votes

---
Tags: unity
---


# Question
Title: How do I apply real time physics to a 2D game in Java?
I'm developing a 2D Brick Breaker style game in Java and want to apply some real time physics to it, especially to the paddle/ball interections. Nothing too complex; just applying some of the physics principles, like: friction to transfer horizontal movement from the curved, hemisferic shaped paddle to the ball in order to change its direction; linear velocity, and maybe angular velocity to add spin to the ball, without change the ball speed; and collisions/resultant angles between the ball, the paddle, the walls and the blocks (rectangular, triangular and spherical shapes).

The point is, the few physics engines/codes that I found for Java have a lot of stuff in them, and I only need to apply few of them to my game. So, is there a way to just pick and add the functions and methods that I need, or do I have to put the entire packages of the physics engine/code to my project?

These are the physics engines that I found for Java:

http://kickjava.com/src/JSci/physics/RigidBody2D.java.htm

https://www.javatips.net/api/bdx-master/extern/gbullet/src/com/bulletphysics/dynamics/RigidBody.java

Thanks for your attention!

# Answer
> 2 votes
Don't worry about a package you want to use having more stuff in it than you need. It's unlikely a package will have just what you need... but no more than that.

What's more important is if it can do what you need within your performance constraints, and if you can understand it well enough to work with it. Bigger packages *can* be overkill, but they're not necessarily wrong to use for smaller projects.

Personally, I would recommend using Box2D. There's a Java port of it here, maybe there are other ports of it.

---
Tags: java, 2d, physics, rigidbody, angles
---


# Question
Title: Balancing stats for combat difficulty in RPG Maker MZ
I'm using RPG Maker MZ to make a game but am having extreme difficulty in developing good systems for leveling my characters and making for a challenging, but fair and balanced battle (especially with bosses) to the extent I can't even make a good first intro boss with both win/lose conditions.

What I am specifically having trouble doing is implementing a design using RPG Maker MZ's tools.

As it stands now, ANY combination of all battle related stats (e.g. ATK, DEF, M.ATK etc.) I have tried has resulted in a battle that is too easy, too difficult, or uninteresting, and I am wondering if there is some sort of set of formulas or any agreeable method in determining the specific numerical values and level curves in which to implement battle structures and level scaling to keep the game fun, balanced, and interesting.

Does anyone have methods I can use to build upon this?

# Answer
If there is one evidently best strategy the game is not balanced. Similarly, to make combat interesting, it must have meaningful decisions. *Hopefully you can find ways to achieve that in this answer.*

---

**Puzzle design**

So, if the players are just doing the same thing without thinking, that is not good. Thus, our *first stop* is puzzle design. How can we make a battle into a puzzle?

Good puzzle design shows a path forward to the player, so they are not immediately stuck and can begin exploring how the puzzle works. But this evident path is not the solution. It leads to a road block, and the whole point is figuring out how to deal with that.

So we want a battle that changes kind of in the middle. The first tool we have for that are the skill costs in MP and TP. If MP depletes and TP accumulates during the battle, you will have the enemies doing a different set of attacks as the battle progresses. You can add to that sealing skill (e.g. via status effects or common events). And of course, you can put skills on turn times, or have the enemy use them when they have an status effect or low on HP.

And, of course the change needs to be significant. You want the late battle skills to be powerful. *You, of course, test that this is working and the encounter is possible. At the expected level of the player characters.*

That way the player has to adapt to the change. Or once the player knows it is coming, they need to have an strategy to deal with or to avoid it. Now the player is thinking.

---

In particular for a bosses, another part of puzzle design is letting the player know when their approach is right. For the RPG battle that is in good writing. Script some lines that clue the player on the enemy weaknesses and resistance. Perhaps the enemy says something during battle… So here is an idea: have a common event for each possible weakness, and call the common event from the relevant skills. Then on the common event you set a switch, and now you can check that switch on the battle events of the enemy troops and use that to trigger lines.

---

**Strategy design**

The problem with a puzzle, is that once you know the solution you are just going through the motions. Consequently that kind of design is fine for a throwaway boss, but not much else.

Our *second stop* will be strategy design. Good strategy design has three phases: Planning (and preparation), Practice (execution of the plan), Improvisation. Puzzles are focused on the practice phase. Let us broad the view:

* Planning, of course, happens in the player mind. But the games has features to assist it: we can see our inventory, we can see the stats of the party. And for preparation we might buy items, switch equipment (or go grind levels).
* Practice, happens in the battle proper. We came up with a plan and we execute it.
* Improvisation also happens during battle. It is when our plan went wrong, and we have to come up with a way to win on the fly.

---

Let us start on planning (and preparation) because there are interesting decision that (can) happen there. First and foremost: what equipment to use? *But also what consumibles to buy and what party remembres to bring.*

If the weapons and armor that you give the player are always straight up upgrades, there isn't much to decide. Instead build trade-off on the equipment. For example, in an area with a lot of enemies weak to magic, you want weapons with magic attack, but you make weapons with high magic attack physically weak so they don't work well in areas with a enemies that are weaker to physical attacks. And then you make areas with a log of enemies weak to magic attack, and a few strong enemies weak to physical attacks… And now the player needs two strategies, with only one set of equipment. *Add elemental weaknesses and status resistances and you can add more variaty.*

---

For practice, from an strategy point of view, *as Phillipp was saying*, give the characters multiple options of what to do on their turn. Since the battle is turn based, there is an action economy (each action has an opportunity cost). I want to go beyond that: what synergies can party members have?

But before we talk about synergies, we should talk about roles in combat. Please don't put each party member in a neat box. They should be able to fill at least a couple roles each. Otherwise the player just plays the character as their role and there is no interesting decision. Similarly, you build the party with redundancies. For example: have two characters that can heal, but with different trade-offs, one could heal a lot only one ally, and another heals a little but all of them, or uses regeneration instead of healing, or whatever. And remember that due to the action economy if they heal they can't do something else. And do that for each possible role in combat. So who is the player going to use to heal?

Alright, we have roles. Now I give you a tool for synergies: If you have states that increase element rate or state rate, you can make an attack or skill that imparts one of these states, making it easier for the skill of another character to work. And you can make that other remove the state. *Have a few options of these synergies to use for each party combination (because, again, there must be a decision for the player), but interlocked in a way that if you are using one, you are not using others (by taking advantage of the action economy).*

*By the way, something very effective you can do for skill design is have skills cost HP. In RPG Maker MZ that means making using a common events to reduce the user HP, and to disable the skill when the character HP is too low.*

---

Finally, improvisation. *So you have this character that cast flammable, which makes enemies weak to fire, and this other character that casts fireball. But the enemy has deal significant damage and you need to heal… But the character that heals is the same that casts flammable. So you can't cast flammable this turn. Thus the fireball will not work. What now?*

Consumible items will allow your characters to temporary fill a role they should not (you can make a healer out of healing potions as long as you have healing potions). So the consumibles are tools that the player can pull from when they need to improvise their way to victory.

---

**Boss design**

Out *third and final stop* is boss design. *It goes without saying, but just in cases: a boss should not be a random encounter.*

A good boss (in particular in late game) should break the expectations of what enemies can do. *So, use events.* Here some ideas of what you can do: have the boss seal skills, steal items (events), summon other enemies (events), change its own weaknesses, remove (de)buff and status effects.

Here is an idea: give the boss an attack that inflicts an status effect that gives you restrictions, but also allows you to resists other of the boss attacks. Once the player figures it out, they have to decide if they want to cure the negative status effect, or keep it.

Anyway, breaking expectations for the sake of it does not feel fair. Thus, telegraph the attacks. How? Again, events. For example, have the boss use a "preparing big attack" skill on turn 6, and then use "big attack" on turn 7.

The telegraph should also work as a opportunity window. Make the boss weak on that turn, or even make the boss cancel the "big attack" if the player does a particular damage. They are also a good opportunity to heal for the player if they are low on health. *Should the player heal and try to tank the "big attack" or should the player try to cancel it, knowing that means they be low on health?*

And don't forget that the boss should be a challenge and a test. The player should not be able to beat the boss with regular attacks. Instead the player should have to use the tools they have, and use them well. Use phases to test to give different challenges to the player. *Furthermore, you can design the boss phases on what the player must have acquired recently.* If you don't have something more to challenge the player, don't put a long health bar on the boss (bullet sponges are not great bosses).

*And of course, a good boss is significant for story reasons too. So don't waste the writing opportunity, not only in scripting lines, but also in skill and unique status names. Oh, and the presentation! The boss battle should be an spectacle.*
> 3 votes

# Answer
Interesting battles require interesting choices for the player to make. An interesting choice is one where the player has multiple options of what to do, all (or at least some) of the options seem viable at first glance, but at further examination there are choices which are more advantageous than others, depending on the current combat situation.

When all the characters can do is attack, then there are no choices at all. So not interesting.

The solution would be to give the characters multiple options of what to do on their turn.

When the characters have multiple attacks to choose from, but one of the attacks is superior to others, then there might be a choice in theory. But in practice it's not a very interesting choice, because the ideal course of action is obvious. So what can we do?

We can add tradeoffs. For example, we could add some resource like MP which prevent the player from spamming their most powerful attacks. Now there is a cost/benefit analysis to make when choosing attacks.

Or we can obfuscate which attacks are ideal. A common way to do that are elemental attacks in combination with elemental resistances. Now the player first needs to figure out which resistances and weaknesses their enemies have before they can analyze which attacks have the best cost/benefit.

Or we could create actions which trade the short-term advantage of dealing damage for a long-term advantage. I am talking about buffs, debuffs and status effects here. These are even more interesting for the player, because it is far less obvious if losing the momentum of an attack is worth gaining the advantage on subsequent turns.
> 3 votes

---
Tags: game-design, balance, difficulty, rpg-maker
---


# Question
Title: How can I tell if my raycast hit a tree?
I have a `TerrainGridSystem` grid on a forested terrain. The grid system draws a grid onto the terrain to set up a game board. I want to find all the trees and mark the grid locations with a tree in them as impassable.

(For those unfamiliar with `TerrainGridSystem`, just assume everything does what you'd intuitively expect it does. The question isn't about the grid.)

```
public class TreeDetection : MonoBehaviour
{
    public TerrainGridSystem Grid;

    private static readonly Vector3 UP_HIGH = Vector3.up * 50;

    // Start is called before the first frame update
    void Start()
    {
        foreach (var cell in Grid.cells)
        {
            var pos = Grid.CellGetPosition(cell) + UP_HIGH;
            if (Physics.Raycast(pos, Vector3.down, out var info, 60))
            {
                if (HitATree(info))
                {
                    Grid.CellSetCanCross(cell.index, false);
                    Grid.CellSetColor(cell.index, Color.red);
                } else {
                    Grid.CellSetCanCross(cell.index, true);
                    Grid.CellSetColor(cell.index, Color.white);
                }
            }
        }
    }
}

```

The problem is, I can't figure out how to distinguish between hitting a tree and hitting the terrain. When I hit a tree, `info.collider` is not the `CapsuleCollider` that was on the tree prefab; it's the `TerrainCollider`, and likewise `info.transform` is the Terrain object's transform.

Is there any reasonable way to implement `HitATree` that doesn't require ripping out all of the terrain trees and manually replacing them with `GameObject`s?

# Answer
> 2 votes
I'm not that familiar with Unity's terrain but skimming google this seems like a common issue, without an easy solution.

However for your case where you want to mark cells in the grid, you could probably just iterate through all the trees in the terrain (https://docs.unity3d.com/ScriptReference/TerrainData.html, the treeInstances property) and check which grid cells intersect with their bounds.

---
Tags: unity, collision-detection
---


# Question
Title: Filter PNGs whose filenames end in "_Normal" using preset manager
I have made specific presets for textures like Normal or Emission maps. After they are imported I have to manually select each one and assign the proper preset.

I want to automate this process. To do this, Unity has preset filters.

The problem is I can't get the syntax to work. I have tried so many variations of the documentation examples, but nothing works.

Example:

Let's say I want every png file which ends in "\_Normal" to get a specific preset value.

# Answer
The solution to the example was this: glob:"\*_Normal.png"
> 1 votes

---
Tags: unity, textures, importing, asset-workflow
---


# Question
Title: Why do we use GLSL(Shader) instead of CUDA?
I'm meaning GLSL and CUDA both utilize GPU to their maximum power and in some cases, I heard CUDA runs faster on Nvidia graphic card. So my question is why don't we use CUDA more often for GPU graphic calculation. I know it's not cross-platform since it's exclusive to Nvidia GPU, plus it doesn't have basic 3d math. But Nvidia is kinda Dominant in the gaming community and 3d math it's not that hard to write. (I wrote 3d rendering engine on CPU from scratch). Can someone explain it to me?

# Answer
> 2 votes
The intuition that CUDA is objectively "better than" dedicated rendering APIs for common rendering workloads is not a good guide.

These are not two competing software libraries that serve the same use case, where you have to choose one or the other. They're two different ways of talking to the GPU hardware, and you can use both in a single application if you have some operations to perform that are more convenient with CUDA and others that are more convenient with OpenGL.

Here's an NVidia presentation showing CUDA and OpenGL interop, as one example.

Something you may notice is it takes a bit more code to render a textured quad via CUDA than it does in a vanilla OpenGL app, even though the work the GPU does in the end is the same (and you'd likely find no significant performance difference for well-written code on well-tuned drivers). That's because a rendering API like OpenGL assumes you're going to want to be doing things like rendering textured quads, so it works in abstractions and defaults that make that use case more convenient.

But you'd have to work harder to make the OpenGL pipeline, which expects to be talking about vertices and pixel colours, do general-purpose computing like computing culling volumes. That's why GPGPU tech like CUDA, OpenCL, DirectCompute, and compute shaders in Vulkan and other APIs exist, to step outside the abstractions that are so convenient for basic rendering when what we want to do is *not* basic rendering.

So the real question is: "Is the job I want to do well-served by the rendering pipeline?" If so, use a rendering API for that job. If you have a different job that's not well-served by that pipeline, consider using a general purpose compute API for that job. And when you have a job that needs both, you chop it up into steps that work well with compute shaders or steps that work well with rendering shaders, and tackle each in turn.

Note though that CUDA isn't doing anything fundamentally different than cross-platform compute shader options, so you don't have to lock yourself into NVidia cards to gain the benefits of GPGPU computing - unless you just happen to prefer the style of working in that API.

---
Tags: glsl, gpu, cuda
---


# Question
Title: How do you make sure that a component can be applied to very different entities?
I've been reading about the SOLID principle and component-based game development. Lots of these posts explain it but don't really give examples on it.

For example, in a hypothetical RPG game, say there's a player class. The class consists of components like Inventory, Movement, and let's say a Roll component. You make the roll component so the player can use it, that's great and it works for the player. Now say that an enemy has the same roll component, how do you implement it? The enemy won't necessarily have the same animation, same roll distance, etc. Do you make a database with roll animations for different enemies? Do you have an animation variable in the enemy's class specifically for the roll component (even though this seems to break the SOLID principle)? Do you make the enemy class override the roll animation? It's specific things like this that I don't understand how to implement.

Another example of the inventory component. What would be responsible for equipping, dropping, or removing items? Do you put it in the inventory component and create messy code with dependency on knowing the owner of the inventory?

Maybe I'm not understanding SOLID or component based programming properly, I'm not sure.

If anyone has specific examples like this they could explain to me, that would be appreciated.

# Answer
> 0 votes
You could have each of your components take in entity specific parameters, or load them from entity specific files. If you had an inventory component for instance, and you wanted a shops inventory to be large, you could pass in the number of slots in that components constructor. Then for say a chest entity, you could pass its inventory component a smaller number of slots.

In terms of your roll case I would have a supplementary attribute system in addition to the component system. Attributes are entity specific variables tied to names, much like a Javascript object or a Java Hash-map. Then you could have each entity add its entity specific attribute with a common name. So the player could send Player-Roll-Animation to the attribute 'Roll\_Animation', where the enemy could send Enemy-Roll-Animation to the attribute 'Roll\_Animation'. Then in your roll component when you want the animation or sound or whatever entity specific action to happen you can say execute 'Roll\_Animation'. Each of your entities would react differently to this as they have passed their own specific animations.

# Answer
> 0 votes
I like how bay jose answered the question and just to add some more off of what he said, I assume you have some OOP understanding. You can create a class for each of the things as listed above and make it very abstracted such as a roll animation, you can have a generic class called something like: HumanoidClass that you can pass a string variable to and store an array of animations. You can then build off of that class by instantiating the class like so:

```
public HumanoidClass
{
    //Tip For Generic Classes, don't derive from Monobehavior
    public animation rollAnimation;

    void SetAnimation(string animation)
    {
        this.rollAnimation = animation;
    }
    animation GetRollAnimation()
    {
        return this.rollAnimation;
    }
}

public EnemyClass()
{

    public animator anim;

    HumanoidClass humanoid = new HumanoidClass();

    humanoid.SetAnimation("Enemy_Roll_Animation");

    anim.play(humanoid.GetRollAnimation());
}

```

# Answer
> 0 votes
> Now say that an enemy has the same roll component, how do you implement it? The enemy won't necessarily have the same animation,

You can solve this problem by using Animator Override Controllers. This handy component allows you to replace individual animations in an animator controller without changing the state machine of the controller itself. That means you can have multiple objects with the same animation controller governed by the same parameters but unique animations for certain states of the animator state machine.

> same roll distance, etc.

Assuming the roll distance is not governed by the root motion of the roll animation you assigned through the animator override controller, it should be a serialized field of the `Roll` component.

> Another example of the inventory component. What would be responsible for equipping, dropping, or removing items?

The `Inventory` component would be responsible for keeping track of the content of the inventory, nothing more and nothing less. It would expose certain methods for manipulating the inventory (`AddItem(type, count)`, `TryUseItem(type)`, `GetCountOfItem(type)` etc.) but calling those methods should be the responsibility of other components. For example, there could be a `PlayerInputController` which interacts with an inventory on the same gameObject, and there could be a `PotionThrowerEnemyAI` which also interacts with an inventory on its gameObject.

---
Tags: architecture, component-based
---


# Question
Title: How to look up items by name in lists loaded from JSON data?
I'm using a JSON file for loading texts and dialogs and here's my JSON file:

```
{
  "Story":
  [
    {"Name":"FirstEncounter", "Content":[
      {"id":0, "text":"sample"},
      {"id":1, "text":"sample2"}
    ]},
    {"Name":"LaGrandDuel", "Content":[
      {"id":0, "text":"sample"},
      {"id":1, "text":"sample2"}
    ]}
  ],
  "Quest1":
  [
    {"Name":"FirstEncounter", "Content":[
      {"id":0, "text":"sample"},
      {"id":1, "text":"sample2"}
    ]},
    {"Name":"QuestDetail", "Content":[
      {"id":0, "text":"sample"},
      {"id":1, "text":"sample2"}
    ]}
  ]
}

```

And I can load it using `JsonUtility` like this:

```
private void Start()
{
    Texts = Resources.Load<TextAsset>("Texts/Test").text;
    Root JsonData = JsonUtility.FromJson<Root>(Texts);
}

```

and here are the classes I use:

```
[System.Serializable]
public class Content
{
    public int id;
    public string text;
}

[System.Serializable]
public class Story
{
    public string Name;
    public List<Content> Content;
}

[System.Serializable]
public class Quest1
{
    public string Name;
    public List<Content> Content;
}

[System.Serializable]
public class Root
{
    public List<Story> Story;
    public List<Quest1> Quest1;
}

```

So setting up the whole thing is done. But, for instance, how can I access the `Content` related to `FirstEncounter` in `Story`? `Root` and `Story` classes use a list, not a dictionary. So I'm completely clueless about how to access different contents.

Sorry if the question seems a bit silly, I'm pretty new to JSON files.

# Answer
> 1 votes
> how can I access the Content related to FirstEncounter in Story?

Well, you can always use List.Find:

```
[System.Serializable]
public class Root
{
    public List<Story> Story;
    public List<Quest1> Quest1;

    public List<Content> GetStoryContent(string storyName) {
        var match = Story.Find(s => s.Name == storyName);
        return match?.Content;
    }
}

```

But if you like the convenience of a dictionary, then why not just add a dictionary?

```
[System.Serializable]
public class NamedList<T> {
    public string name;
    public List<T> content;
}

[System.Serializable]
public class Collection<T> : ISerializationCallbackReceiver {
    public List<NamedList<T>> collection;

    Dictionary<string, List<T>> _contentLookup;

    public bool TryGetContent(string name, out List<T> content) {
        return _contentLookup.TryGetValue(name, out content);
    }

    public void OnBeforeSerialize() {}

    public void OnAfterDeserialize() {
        _contentLookup = new Dictionary<string, List<T>>(collection.Count);
        foreach(var item in collection) {
            _contentLookup.Add(item.name, item.content);
        }
    }
}

```

Using generics this way, we don't need separate Story and Quest classes (even if they use different types of content), so we can avoid writing the dictionary boilerplate twice. Your Root class then becomes:

```
[System.Serializable]
public class Root {
    public Collection<Content> story;
    public Collection<Content> quest;
}

```

The `ISerializationCallbackReceiver` interface should cause the Unity deserializer used by `JsonUtility.FromJson<T>()` to call `OnAfterDeserialize()` on your nested types automatically.

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


# Question
Title: Creating variable with the name from user
I'm not sure this is possible or not but I need to create a variable and set its name to whatever the user wants. Is this doable in C#?

something like this is what I want:

```
public string UserInput;
void Start
{
    int "whatever UserInput is" = 0;
}

```

# Answer
> 2 votes
You do not need this type of functionality. User can set string to any value and you can use the string value to access the variable for example.

```
Dictionary<string,int> dict = new Dictionary< string,int>();
dict.add(userInput, 0);

```

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


# Question
Title: How to move a portion of bezier/spline curve along its complete bezier/spline curve?
Based on the image below, I have a curve (orange) which is a bezier sub-curve of an original curve (longer black curve). The original curve consists of a number of cubic bezier curves joined together. How can I move the sub-curve (which could be contain more than one cubic bezier curve) along it’s original curve whiles preserving its length?

Please note that the original curve/spline could be open or closed curve with the ends joining. I know that arc length is key to achieving this, but I’m not sure to do this.

**UPDATE**

The smaller curve was reduced using the solution from How to move points of a multi-segmented bezier curve to one side. DMGregory recommended Moving ships between two planets along a bezier, missing some equations for acceleration, which I have to admit I didn’t understand enough to fully utilise to solve my problem. One thing though that I took away from the solution was I needed to express the smaller curve as percentage of the original curve, so I implemented a slider as below.

```
 public void ReplaceCurveWithSubCurve(float curveVal) {

    subCurve = IntervalFromTo(curve, 0, curveVal);

}

```

In CurveEditor:

```
curveLengthValue = EditorGUILayout.Slider("Curve Length", creator.curveSizeValue, 0f, 1.0f);

if (!Mathf.Approximately(creator.curveSizeValue, curveLengthValue))
            {
    creator.IntervalFromTo(curveLengthValue);
    creator.curveSizeValue = curveLengthValue;
}

```

My general understanding is the original (full) curve say runs from some `t = 0.0` to `t = 1.0` and my sub curve at any given point is made of a subset of those values, so I need to change the values along the full curve whiles preserving the arc length. Below are the methods I use to calculate the arc length. My problem is how to tie all this together to arrive at a working solution.

```
 public float SegLength(int segmentIndex)
{
    var steps = 10;
    var t = 1 / (float)steps;
    var sumArc = 0.0f;
    var j = 0.0f;
    var a = new Vector2(0.0f, 0.0f);

    var b = points[segmentIndex * 3];

    var dX = 0.0f;
    var dY = 0.0f;
    var dS = 0.0f;

    for (int i = 0; i < steps; j = j + t)
    {
        a = SegmentAtPoint(segmentIndex, j);

        dX = a.x - b.x;
        dY = a.y - b.y;
        dS = Mathf.Sqrt((dX * dX) + (dY * dY));

        sumArc = sumArc + dS;
        b.x = a.x;
        b.y = a.y;
        i++;
    }

    return sumArc;

}

public float FullLength()
{
    var totalLength = 0.0f;

    for (int i = 0; i < NumSegments; i++)
    {

        totalLength += SegLength(i);
    }

    return totalLength;
}

```

# Answer
> 0 votes
You can build curve inside a coroutine and fill it with points while it building. You can use particle that will move you curve trajectory and left the tale behind.

---
Tags: unity, mathematics, curves, beziers
---


# Question
Title: Anyone about me how we make games in Android , also about me can we use c# or c++ in blender
> > game development in blender with c#

---

# *hello everyone about me c# coding for games in blender game engine*

**how i can use blender in Android because i'm new student in game developement** *Also about me how i use c# or c++ in game developement*

> > Can we use c++ for games making and development!

**How i use c++ for game development Give me some programming language's example for learn and more knowledge about game development**

`can we use c++ in blender game engine`

# Answer
> 0 votes
1. **Using Blender as a 3D Modelling + Animation Tool & Integrating into an Android Project**

This is definitely possible. Most game engines that run on Android devices will allow importing assets like models, animations, shaders and so on through various standard formats. Learn about common 3D asset formats and go from there.
2. **Using C++ as a Programming Language in Android Projects**

This is also possible but may be needlessly complex if your goal isn't to learn C++ specifically. You may be better suited using Kotlin, Java, or even C# (assuming you're using something like Unity as your core game engine).

---
Tags: c#, c++, graphics-programming, blender-game-engine
---


title: Predictive Aiming To Update Every Frame

text:
# Question
Title: Predictive Aiming To Update Every Frame
I am making a 2D bow and arrow game, and I want there to be a predictive aiming line as you pull the bow back. The problem is, in my current script, it seems to only update every time I go to shoot, rather than updating as you pull the bow back. For clarity, it updates the direction, but not the increased force as you pull the bow back further.

I have put this for loop at the top of `Update()`:

```
for(int i = 0; i < Points.Length; i++){
                Points[i].transform.position = PointPosition(i * time);
            }

```

That calls this method:

```
Vector2 PointPosition(float t){
        force = new Vector2(Mathf.Clamp((startPoint.x - endPoint.x) / damp, powerMin, powerMax), Mathf.Clamp((startPoint.y - endPoint.y) / damp, powerMin, powerMax));
        Vector2 currentPointPos = (Vector2)transform.position + ((-direction.normalized * (force*mult) * t) + 0.5f * Physics2D.gravity * (t*t));
        return currentPointPos;
    }

```

The predicted path is also wrong, but that is a problem for future me. For now, I'm just trying to figure out how I can get the predicted force of this line to update every second. The obvious solutions like setting `force` at the top of `Update()` didn't seem to work, and I don't know if I'm missing a Unity thing or if I've just been staring at my code for too long and can't see the obvious fix.

# Answer
Meta re: your question - I'd suggest adding more code to complete your example. More context around which `GameObjects` you are calling `Update()` from could be useful for folks helping to answer your question.

Shot in the dark - If your goal is to get a bit of code to run once every second, you could probably achieve that fairly easily by keeping a running timer in your `GameObject` and checking it via `Update()`:

// ...

private float timer = 0.0f;
public float timerThreshold = 0.1f;

// ...

void Update () {
  timer += Time.deltaTime;

  if (timer >= timerThreshold) {
    timer -= timerThreshold; // Reset timer
    /*
      Execute code as needed to update projectile path preview
      ...
    */
  }
}

// ...
```

> 0 votes

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


# Question
Title: How to include cross cutting concerns like sound/graphics effects in an ECS?
It does not seem like a good idea to include this functionality in the game logic like that even if the concrete implementation of the sound or graphics effect is abstracted away. Ideally, the game logic/collision logic should not know anything about such things at all:

```
class ProjectilesSystem
{
  Action<string> makeSound;
  public ProjectilesSystem(Action<string> makeSound)
  {
    this.makeSound=makeSound;
  }
  void Update(ProjecttileComponent p)
  {
     if (p.Hit()) makeSound(p.GetSoundName());
  }
}

```

So we would need a separate systems for sounds/effects. But because there are lots of components which can make sounds under lots of circumstances theoretically I would need a `ProjectileSoundSystem, ProjectileParticleEffectsSystem, VehicleSoundSystem, VehicleParticleEffectsSystem, AnimalSoundSystem, AnimalParticleEffectsSystem`.. (you got the idea), would this be practical?

What are the alternatives?

Maybe some kind of event system so that component systems can publish what the component is doing right now:

```
  void Update(ProjecttileComponent p)
  {
     if (p.Hit()) eventSystem.Fire("ProjectileHit");
  }

```

In this approach, how can the consument know how the ProjectileHit should sound like? I mean depending on the projectile the impact can be a different sound. So each entity would need a map for eventType=\>SoundName and similar maps for other stuff like effects and so on. Does this make sense? Are there other solutions?

# Answer
> 2 votes
I'll just answer from the perspective of sound integration here. Not quite sure what all would be included in the graphics side of your cross-cutting concerns.

I've seen these types of cross-cutting sound integrations take a few different shapes, generally. Here's a breakdown on how I see the pros/cons of each approach.

# Singleton Sound Manager

A globally available, "master mix" style sound manager that receives calls from various systems / `Update()` methods directly via `SoundManager.Trigger(soundId)`.

### Pros

* Initially easy to reason about
* All things sound related are here except the triggers; it's centralized and easily modified in broad strokes - assuming a consistent API in consuming code
* Likely higher performance w/r/t fewer disparate sound systems being instanced all at once

### Cons

* Dangerously easy to bloat with complexity (voice counts, choke groups, not to mention larger sound integration concerns like occlusion, dynamic music, etc.)
* Likely to evolve into a number of more specialized `[Foo]SoundManager` singletons, which need to be provided more context as external systems request sound playback (or cancellation, or looping, etc.)
* Consuming classes become more complex as a result

# Sounds in Systems

A list of sounds that can be triggered by a system is stored close to the system and used internally. Some form of ad-hoc configuration might accompany the list of sounds, but it is otherwise fairly fire-and-forget.

### Pros

* Easy to reason about, even at scale (bloat notwithstanding)
* Sound assets are assigned, managed, and triggered close to where they are used

### +/-

* As you mentioned re: collision, suddenly your `CollisionManager` isn't just physics; it's now concerned with sound too.
* Some technical sound designers would argue that this is A Good Thing, as it allows for more nuanced sound integration within each system (e.g. different sounds are triggered based on impact velocity, insert effects are tweaked based on collision state.)

### Cons

* Systems become larger in scope, potentially resulting in more abstraction: `CollisionManager` becomes the tip of an architecture subtree with `CollisionSoundManager` managing sound with knowledge of state provided by separate `CollisionPhysicsManager`, and so on
* Cross cutting concerns (e.g. voice count, choke groups, etc.) are either repeated (bad) or broken into more disparate sound subsystems (e.g. `SoundPlaybackManager`) which sort of just leads you back to the Singleton Sound Manager approach
* Without proper abstraction, systems needing sound can get messy, quickly

# Event Sourcing / `SoundEventManager`

Essentially every notable event in your game becomes logged to some central `EventStore`. This may already be in place for save systems or other databasing needs, but this can be an extremely powerful well from which a `SoundEventManager` can parse events, decide if they warrant a sound, infer context from surrounding events, and trigger + manage sounds appropriately.

### Pros

* Lots of power from a centralized place, though proper abstraction of sound playback concerns is absolutely necessary.
* Enables adding, modifying, or removing sounds long after other systems are created without modifying said systems.

### +/-

* Rather than relying on systems to trigger a sound themselves (Sounds in Systems), or request playback from an orchestrator (Singleton Sound Manager), the systems just publish events with reckless abandon.
* Can go well if the core `EventStore` makes intelligent use of debounces / throttles and otherwise keeps it's memory footprint in check via streaming to disk as needed.
* But it can also go poorly, with far too many useless event records and a monstrous memory footprint to boot.

### Cons

* Absolutely the more complex of the architectures to get right.
* Aside from `EventStore` hygiene gotchas mentioned above, latency can be an issue if the event queue isn't processed on nearly every tick.

# Personal Opinion

I'm a big fan of the Event Sourcing approach because I believe it lends itself to good design in other areas of gameplay, despite the complexity and need to carefully manage + persist incoming events. Having centralized communication is ultimately always needed for systems to cooperate and doing so via event logs is a tried-and-true approach.

All that said, I won't hesitate to recommend mature sound integration platforms like WWise or FMOD. Sound integration is such a deep and nuanced practice that tooling around it has become very full-featured and truly helps lighten the load as a \[solo\] developer just trying to get work done.

---
Tags: architecture, oop, entity-component-system
---