# Question
Title: How to sync ticks(Frames) between two peers?
I have a peer to peer game where both clients are running their own frame simulation. I'd like to sync the frame ticks so both peers know eachother's frame. But I"m having a bit of issue with this and I can't figure out why it's so hard to sync the frame tick.

What I attempted was,

Host begins game

Peer joins the game and lets the host know they joined

The host sends a packet

Peer receives the packet and makes a note of its own tick

Host sends another packet one frame later

Peer receives this packet and subtracts the earlier tick from its current to get the one way distance in ticks

Now the peer can assign their own frame tick to the host's and add the travel time to it so they should technically now be sync'd

But for some reason this doesn't work.. they're always off by 2 or 3 ticks and I can't figure out why

# Answer
If I understand your description correctly, your timeline of events during a join looks something like this...

Some things to notice here:

* The time it takes an update to travel across the network from server to client is not always the same - there's some variance due to congestion, buffering, etc.
* The time between receiving your first and second messages from the server is not a good measure of one-way trip latency. What you're measuring is the sum of...

+ the time elapsed on the server between the two messages being sent (either one frame/tick if the join message is processed as part of the tick, or one tick plus some loose change that's just up to the happenstance of when between ticks your message was processed)
    + plus the *difference* in latency between the two messages. So if the first message took longer than usual to reach you and the second took less time than usual, you'll get a smaller result. If the first message arrived quickly and the second was slower, you'll get a larger result. Neither tells you anything about the typical latency.

This is effectively just noise in terms of what you really want to measure, which is "how far into the past should I back-date newly-received server messages?"

To estimate that, you need to do a combination of things:

* Measure from the time the client sent a message to the time it received an acknowledgement. This gives you round-trip time, from which you can estimate one-way latency by dividing by two.
* Send acknowledgements immediately, not deferred until the next tick - otherwise you're adding an unknown amount of loose change into the estimate. (If you need to batch up replies, you can track how long the server held a message before replying, and send that delay number as part of the payload, so the client can subtract it out again)
* Do several rounds of this and filter the results. Any single round trip may be plagued by errors or outliers, but taking the median of several round trips will get you a better estimate of the real trend.

This may mean you spend several ticks "handshaking" before you have enough confidence in the time disparity to join the simulation at the right offset, but this can often happen in parallel/in the background while loading the level, displaying the lobby or join message, or other pre-gameplay fanfare.
> 1 votes

---
Tags: frame-rate, synchronization
---


# Question
Title: Is it possible to move Overlay Canvas away from (0,0,0) in the Scene View?
In our workflow we use a `Screen Space - Overlay` canvas for `UI`. The only problem with it is that you can't change it's position (The values are driven by the Canvas component) and it's left-bottom corner is in the world position (0,0,0).

The issue it creates is that in the scene view we usually create the game objects around (0,0,0) (player, levels etc.) and because of the canvas sitting there, it most of the time blocks our mouse raycasts (we can't click on the world objects) - see below.

To be specific, I'm not talking about the Canvas blocking raycasts in Game View/Play Mode but in the Scene view in the editor:

When I click on the cube the overlay canvas captures my click and selects the canvas, not the cube. Because of that we have to make weird tricks (disabling the canvas manually when we build the levels etc.).

You can't change the component's position at all:

**Is there any way to somehow move the Overlay Canvas away from (0,0,0) in the Scene View?**

# Answer
> 2 votes
As an update to Jacob's answer, his code works correctly, but it sometimes appears to not work because you will only see the UI appear or disappear when the `SceneView` is redrawn (which may not happen by default). Here is a slightly improved version that includes a `SceneView.RepaintAll()` call to ask the Editor to repaint the `SceneView` whenever the UI Layer is toggled on or off. This script should be placed in a folder named Editor. The `MenuItem` attribute places this command at the bottom of the Window menu (so just below the UI Toolkit stuff).

```
using UnityEngine;
using UnityEditor;

static public class UILayerToggleClass {
    [MenuItem("Window/UI Layer Toggle", false, System.Int32.MaxValue)]
    static void UILayerToggle()
    {
        Tools.visibleLayers ^= 1 << LayerMask.NameToLayer("UI");
        SceneView.RepaintAll();
    }
}

```

# Answer
> 1 votes
No. It’s locked to the camera as that’s the function of screen space overlay. Create a child rectransform and use that rather as you can change its position.

# Answer
> 1 votes
Turns out it's not possible. I just created a workaround using the magical Layers menu in Unity (I had no idea such a thing exists):

```
[MenuItem("Zenith/Toggle UI Layers", false, 100)]
static void ToggleUILayers()
{
    Tools.visibleLayers ^= 1 << LayerMask.NameToLayer("UI");
}

```

The menu item above will toggle the entire UI on and off :)

# Answer
> 1 votes
On the left side of the Hierarchy window there are hand and eye icons (mouse over to see them). They do just that, enable/disable mouse select and visibility in scene view.

On the image game objects in the blue rect can not be selected with the mouse in scene view and the object in the red rect is not visible in scene view.

# Answer
> 0 votes
This is the easiest way ive found to implement a moveable overlay canvas:

1. Create a new empty GameObject called "UI" (this is just a container for all your ui elements).
2. Create a new camera called "UI Camera" nested under your "UI" GameObject.
3. Nest your canvas under the "UI" GameObject element and set its "Render Mode" to "Screen Space - Camera" and its "Render Camera" to the "UI Camera" that you just created.

You should now be able to select the "UI" Game object and position it to move your canvas wherever you would like in the scene view.

# Answer
> -1 votes
yes, it is possible to move Overlay Canvas away from (0,0,0) in the Scene View by adjusting its position property in the Transform component.

---
Tags: unity, gui
---


# Question
Title: Generate a fully 3D NavigationRegion/pathfinding in Godot 4
I'm making a spaceship game where the enemies and the player have the full 6 degrees of freedom, so can move forward/backwards, left/right, up/down and can also rotate in all three axes. I'm wanting to add some simple pathfinding so the enemies can move towards the player.

I tried to use the guide in 3D Navigation Overview in the docs but the "3D" navigation really seems to be 2D to me since the agents always only have two translational movement options (forward/backward and left/right) but in 3D there should be three translational movement options (forward/backward, left/right, and up/down).

Most of the "3D" navigation tutorials for Godot also seem to be 2D or 2.5D where the agents can up ramps and onto higher platforms, but they can't fly around or anything.

I tried fiddling around with the settings for `NavigationRegion3D` and its child `MeshInstance3D` but I can't figure out how to get the baked `NavMesh` to actually be 3D. Right now I've made the `MeshInstance3D` a cuboid, but when I bake the `NavMesh` only the upper face is displayed as navigable:

How can I allow my agents to pathfind *anywhere* within a rectangular region? Ideally they'd be able to use all 3 dimensions at all times.

---

Edit: Godot does not support volumetric pathfinding (I ended up implementing it myself). If you'd like to see built in support, please leave a comment on the issue I opened for it here

# Answer
These are 3D in the sense they works with 3D nodes. *2.5D is not a well defined term anyway.*

If the environment is fully enclosed, it might still be useful for a 3D flying agent, given you use some form of obstacle avoidance. Otherwise, it does not really work for 3D flying agents.

In general, I would expect that going directly to the target with obstacle avoidance would work for open spaces. Then if the agent is inside a given area, it might also use navigation... Or to `AStar3D`. *This, of course, requires you to specify the areas where it uses what strategy.*
> 1 votes

---
Tags: 3d, path-finding, godot, navmesh
---


# Question
Title: How to alternate child placement to the left and right in a vertical stack?
Is it possible to arrange alternate children separately in a vertical layout group?

I want to arrange the child elements so that one is aligned to the left, the next one is aligned to the right, and so on, alternating like this:

How can I achieve this layout?

# Answer
Okay, my solution is to create a parent object and set these elements as children. Then, I anchor one child element to the right and the other to the left. This fixed my problem, but I'm not sure if it's best practice.
> 1 votes

---
Tags: unity, unity-ui
---


title: VFX Graph projectile trail shows gaps

text:
# Question
Title: VFX Graph projectile trail shows gaps
I'm learning to use Unity's VFX Graph to create projectiles. One projectile I'm working on is starting to get where I want it to be, but there's an issue where gaps are visible in the trail when I move the game object; this is something I want to avoid.

The game object's transform is bound to a target position property, which I set in in the 'initialize particle' context. I'm also using a `sin` node to alter the velocity of the particles to create a wave effect.

Things I've tried:

* Modifying alpha over life
* Modifying size over life
* Modifying the min & max attributes of the sin node inputs

Nothing seems to work, I thought it's likely I need to use the velocity of the target game obejct with the `sin` node somehow, but I'm not quite sure how.

* Image of my effect so far:
* VFX Graph:
* What I'd like to aim for (sorry the image is low res):

# Answer
> 1 votes
I implemented a new *Particle Strip* system, and in the Spawn context, used the "Spawn Over Distance" block. I couldn't get the target position blocks to work like I did with my previous effect, so I simply attached the effect to a parent gameobject. It creates a much smoother trail (no visisble gaps).

VFX Graph:

---
Tags: unity, particles, trail-renderer, vfxgraph
---


# Question
Title: How to provide the URL which will enable players to delete their data (Playfab at backend) as per the new Data Safety form in Google Play Console
Hi as per the latest data safety form in Google Play Console , it wants me to add a link so that users can use to request that their account and associated data is deleted in playfab. In my game I collect a user's email-id, username and password only for the purpose of multiplayer game as such. But now google is asking me to add the link so that these details can be deleted . How do I do that?

Also how can I make sure that the user himself and not someone else is responsible for the deletion of the data? This can be made possible if there is some confirmation email can be sent to the user's mail box, but how do I do that?

I searched everywhere but I got this answer but it doesn't talk about the user deleting the data so I am asking here

You can see the screenshot of the questions in the google play console here:

I asked the same question here in Playfab forum, but my question has been put in moderation for the past 4 days. I contacted the system administrator but there is no reply from there also. If anyone here can help me that will be great

# Answer
I think you might be misinterpreting the instructions. I don't think that their expectation is for the linked page to be used to request account deletion, but that it prominently feature the steps required to request account deletion.

For example, let's say you place a "delete my account" option in a menu within your game. My read is that you are required to have an 'explainer' web page that a user could follow to find and use that feature.

As to verifying user user credentials before deleting data, the PlayFab GDPR documentation says this:

> It is your responsibility as the game developer to verify that the credentials match the player requesting an export or deletion of their player data. PlayFab does *not* provide any type of verification when using these APIs.
>
> However PlayFab *does* offer an email verification feature. But our solution isn't the only option for verification. You can create your *own* process too.
> 1 votes

---
Tags: google-play, playfab
---


# Question
Title: One scene or multiple scenes for levels?
In my game there are multiple levels (300 levels) You start a level by clicking on it in the level map (like the one in candy crush etc) The levels will be having the same gameplay, character and environment but the items (stored as scriptableobjects) available and the winning criteria will be different. Now I am confused about something. Is it recommended that each level should have its own scene and script?

# Answer
> 0 votes
Usually using only one scene for multiple levels is (almost) never a good choice, unless the game is VERY small(or if you want to generate the levels procedurally) If you are planning to do multiple levels in your game, i would go for a multi-scene approach, to have a better, more organised workflow. At the end of the day it really depends on the type of game you are making.

# Answer
> -4 votes
Yes, you can use the same lighting setup for multiple levels within the same scene in Unity. Unity's lighting system is designed to work across different parts of a scene, so you can create consistent lighting across various levels without any issues. This can be especially beneficial if you want to maintain a consistent visual style and mood throughout your game.

Here's how you can ensure consistent lighting across different levels within the same scene:

1. **Setup Lighting:** Configure your lighting setup using Unity's lighting tools. This includes setting up directional lights, ambient lighting, reflection probes, and any other lighting components you want to use.
2. **Lighting Layers:** Unity's lighting system works on a per-layer basis. You can assign different GameObjects to specific lighting layers to control how they interact with the lighting. For example, you might have one layer for dynamic objects and another for static level geometry.
3. **Reuse Lighting Setup:** Ensure that your lighting setup is consistent across the different levels within the same scene. You can achieve this by reusing the same lighting GameObjects, settings, and lighting components.
4. **Optimize Lighting Baking:** If you're using baked lighting (which is common for scenes with static elements), make sure to bake your lighting after you finalize your level designs. Baked lighting can significantly improve performance and create consistent lighting across levels.
5. **Manage Scene Hierarchy:** Organize your scene hierarchy efficiently. You can create separate hierarchies for each level within the same scene and enable/disable them based on the level progression.
6. **Lighting Quality Settings:** Unity's Quality Settings allow you to control how detailed your lighting calculations are. Ensure that your lighting quality settings match the level of detail you want for your game.

By following these steps, you can use the same lighting setup to achieve consistent lighting across different levels within the same scene. This approach can save memory, reduce loading times, and help maintain a cohesive visual experience throughout your game.

---
Tags: unity
---


# Question
Title: Can I use Unity's free assets for commercial purposes?
i have a question, if someone is developing a game on unity for commercial purposes, can free or even paid assets be used in the game even if it is to sell the game? are assets not subject to copyright?

# Answer
> 2 votes
As explained on the Unity website, the vast majority of assets you find on the asset store can be used in both commercial and non-commercial projects. However, a couple assets are marked as "restricted", which means they come with additional license restrictions you have to abide by. What exactly those restrictions are, and if they could interfere with your intended monetization method, can be found in the description of the asset.

> are assets not subject to copyright?

Every creative work is subject to copyright. People who claim that they publish their creative work "copyright free" usually have no idea what they are talking about. "Free" assets from people who *do* understand copyright law are usually distributed under license terms where the original author nominally retains copyright but gives everyone permission to use the asset as they want.

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


# Question
Title: Bullet not colliding with either plane or drone
i made a godot game in which theres a player and a drone, I got the shooting to work but when i tried to make it so that the bullet attacks the drone/player, it wasnt working properly. Basically i made a area2d in the bullet and if a body enters it, i damage the body (player/drone). or if the body is a wall then i destroy the bullet. When i tried debugging body.name, all i got was 'Wall' in the console. heres the code for the bullet

```
extends Node2D

var angle = 0
var speed = 0

func set_bullet_settings(new_angle, new_speed, pos, amountoffset):
    angle = new_angle
    speed = new_speed
    $BulletSprite.rotation_degrees = new_angle
    $BulletSprite.position = pos

    $BulletSprite.position.x += cos(deg_to_rad(-angle)) * amountoffset
    $BulletSprite.position.y -= sin(deg_to_rad(-angle)) * amountoffset
    $AttackArea.position.x += cos(deg_to_rad(-angle + 90)) * amountoffset
    $AttackArea.position.y -= sin(deg_to_rad(-angle + 90)) * amountoffset

func update():
    $BulletSprite.position.x += cos(deg_to_rad(-angle + 90)) * speed
    $BulletSprite.position.y -= sin(deg_to_rad(-angle + 90)) * speed
    $AttackArea.position.x += cos(deg_to_rad(-angle + 90)) * speed
    $AttackArea.position.y -= sin(deg_to_rad(-angle + 90)) * speed

func _on_attack_area_body_entered(body):
    print(body.name)
    if body.name == 'Walls':
        queue_free()

```

code for player

```
extends CharacterBody2D

const speed = 5
const fast_speed = 7
const shoot_speed = 0.3
const bullet_speed = 50

var win_mode = 'fullscreen'
var bullets_shooten = []
var bullet_scene = preload('res://scenes/bullet/bullet.tscn')
var angle = 180
var can_shoot = true

func isnt_fast():
    return not Input.is_action_pressed("walk faster")

func _ready():
    $BulletTimer.wait_time = shoot_speed
    $BulletTimer.connect('timeout', set_can_shoot)

    DisplayServer.mouse_set_mode(DisplayServer.MOUSE_MODE_HIDDEN)

func set_angle_to_mousepos():
    var direction = (get_global_mouse_position() - self.global_position).normalized()
    angle = int(rad_to_deg(atan2(direction.y, direction.x))) + 90

func set_can_shoot():
    can_shoot = true

func move(amount):
    position.x += amount * cos(deg_to_rad(-angle + 90))
    position.y -= amount * sin(deg_to_rad(-angle + 90))

func shoot():
    var bullet = bullet_scene.instantiate()
    bullet.set_bullet_settings(angle, bullet_speed, position, randi_range(0,16))
    bullets_shooten.append(bullet)
    $'..'.add_child(bullet)
    can_shoot = false
    $BulletTimer.start()

func _physics_process(delta):
    if Input.is_action_pressed("move forward"):
        move(speed  if isnt_fast() else fast_speed)
    if Input.is_action_pressed("move backward"):
        move(-speed if isnt_fast() else -fast_speed)
    if Input.is_action_pressed("shoot") and can_shoot:
        shoot()

    move_and_slide()

func enumerate(iterable):
    var index = 0
    var result = []

    for item in iterable:
        result.append([index, item])
        index += 1

    return result

func removeNullItems(inputArray: Array) -> Array:
    var newArray := []

    for item in inputArray:
        if item != null:
            newArray.append(item)

    return newArray

func _process(delta):
    set_angle_to_mousepos()
    angle = (angle + 360) % 360
    $Sprite.rotation_degrees = angle - 5

    if Input.is_action_just_pressed('fullscreen toggle'):
        if win_mode == 'fullscreen':
            DisplayServer.window_set_mode(DisplayServer.WINDOW_MODE_FULLSCREEN)
            win_mode = 'not fullscreen'
        else:
            DisplayServer.window_set_mode(DisplayServer.WINDOW_MODE_WINDOWED)
            win_mode = 'fullscreen'

    bullets_shooten = removeNullItems(bullets_shooten)

    for bullet in bullets_shooten:
        bullet.update()

```

code for drone

extends CharacterBody2D

const accuracy = 30

var can_shoot: bool = true
var bullet_scene = preload('res://scenes/bullet/bullet.tscn')
var shoot_speed = 0.7
var bullet_speed = 35
var bullets_shooten = []
var player_in_range = false

func _ready():
    $BulletTimer.wait_time = shoot_speed
    $BulletTimer.connect('timeout', set_can_shoot)

func set_can_shoot():
    can_shoot = true

func shoot(playerpos):
    var bullet = bullet_scene.instantiate()
    bullet.set_bullet_settings(rotation_degrees, bullet_speed, position, randi_range(0,accuracy))
    bullets_shooten.append(bullet)
    $'..'.add_child(bullet)
    can_shoot = false
    $BulletTimer.start()

func look_at_player(player_pos):
    look_at(player_pos)
    rotation_degrees += 90

func removeNullItems(inputArray: Array) -> Array:
    var newArray := []

    for item in inputArray:
        if item != null:
            newArray.append(item)

    return newArray

func update(player_pos):
    look_at_player(player_pos)
    if player_in_range and can_shoot:
        shoot(player_pos)

    bullets_shooten = removeNullItems(bullets_shooten)

    for bullet in bullets_shooten:
        bullet.update()

func _on_attack_range_body_entered(body):
    if body.name == 'Player':
        player_in_range = true

func _on_attack_range_body_exited(body):
    if body.name == 'Player':
        player_in_range = false

```

# Answer
I don't have much to see in the code...

What I can give you is a short list of things to check to debug this:

* Make sure your `Area2D` and `CharacterBody2D` have their colliders (with their shape, and not disabled). Double check by setting "Visible Collision Objects" in the debug menu, which will show the colliders when the game is running. *This will also reveal if the colliders are positioned or moving in an unexpected way.*
* Make sure the collision layer and mask of the `Area2D` and `CharacterBody2D` overlap, otherwise, Godot won't even check for a collision between them.
* Make sure the `body_entered` signal is connected correctly. *I'm guessing it is connected since you say you got the output from `print`.* I presume you are connecting it from the editor (since the connection is not being made in the code you shared), in which case you should see in Godot text editor a green icon next to the method connected to the signal, and clicking it should show you what is connected.
> 1 votes

---
Tags: collision-detection, godot
---


# Question
Title: Resolving contradictions in WFC more efficiently than naive backtracking
I just recently got started with the **Wave-function-collapse Algorithm (WFC)** in 3-dimensional space. I got the fundamentals working and wanted to now move on to let the algorithm automatically resolve possible upcoming contradictions/error-states.

For this, I (inspired by this Tweet from Oskar Stålberg) created a highly constricted Tileset that will run into such contradictions quite often.
(Some examples of constructed Levels in a (3x3x3)-Grid using this tileset.)

Note that this tileset will, for example, always run into a contradiction if the number of bottom contacts is odd since every pipe that comes out must also finish at the bottom.I've now implemented basic (naive) backtracking, which means whenever the algorithm runs into a contradiction, it goes back to the last decision made undoes it and tries another. This does work, however, because the possibility space for placed modules can become huge, it may resolve in a really slow generation trying out every possibility before having backtracked far enough to resolve the modules that caused this contradiction. (Gif 1, Gif 2)

### Now I'm looking to optimize this algorithm.

I thought about using Backjumping instead of Backtracking with a quadratically increasing jumping distance each time it runs into **the same** contradiction again (first time we jump back 1, then 2, then 4, 8, 16, ...). But I'm not sure how to detect the overcoming of the first contradiction to be able to then reset the jumping distance.

I also don't get Oskar Stålberg'ssolution to this. In the post's comments, he speaks of cutting out Chunks to try and resolve the contradiction but how does he calculate these chunks?

# Answer
I went ahead and replied to Oskar Stålberg's tweet about this technique to ask for clarification. (Try it yourself! Most game developers who post about their work on Twitter are happy to share more details & insights with their peers)

Here's what he said:

> In an old implementation of WFC I used to rebuild the possibility space around a contradiction. But I don't think that solution is good in most cases. You can't know when the seeds of the contradiction were sowed. Its usually **faster to reset the whole thing**.

Another developer, Ebyan Alvarez-Buylla, agreed:

> I have only used WFC in prototypes but yeah the lazy “**just scrap everything and start over**” seemed simple and performant. Similarly with Markov Chain generators, which I’m more familiar with.

So: attempting to identify the specific root cause of the contradiction, by backtracking or even just estimating its location, may be more trouble than it's worth. Bits that appear salvageable might not be, due to long chains of implications that will inevitably lead to the same or new contradictions. Even a perfect solver might spend a lot of time evaluating what to keep, and end up keeping very little for all that trouble.

These devs find it's faster to start over with a blank canvas. The first round of generation is fast to re-do anyway, and it keeps your solution simple. Or as Ripley would say,

Based on their expertise, I'd recommend that you only try to do a more localized backtrack/reset if you have domain-specific knowledge that you can use to bound the problem for the specific tileset you're using.

Say, if you were generating islands in the ocean, and you know contradictions can't occur in ocean tiles because the set of possible adjacencies in your tileset is complete for those cases. In such a case, when a contradiction occurs in one island, it suffices to clear only that one island: flood-filling (erasing) outward until you reach an ocean tile, and leaving the rest of the archipelago intact.

Or in the absence of a hard guarantee like this, if your tilesets tend to exhibit a behavior where "local" contradictions are common, you could apply an escalating response. The first time you encounter a contradiction (with x/n collapsed tiles), erase & reset a 3x3x3 cube around the site of the contradiction and resume. If you hit a second contradiction with (x+f)/n or fewer tiles collapsed, assume it's from the same cause and you needed to undo more: double the size of the region to erase this time. Continue this way, doubling the size of the erased region each time until you manage to get further than (x+f)/n or you've completely reset the map, then bring your eraser size back to the default for the next contradiction you encounter. This lets you solve small touch-ups without massive regeneration, but still falls back on a full wipe in only a logarithmic number of attempts when the "local" heuristic fails you.

But without these types of domain-specific guidance, solving the problem of bounding the contradiction in the most general case seems likely to fail or perform poorly.
> 7 votes

# Answer
I've found the same issues you have with backtracking, and restarting is often not an acceptable approach for larger generations.

I think backjumping is a fruitful avenue, but I've not seen it expored.

One process that seems to work ok is "Modifying by blocks", which is a specific form of doing WFC in chunks. Unlike more naive reparation approaches, it "locks in" chunks that actually work, which sometimes is better than just guessing where contradictions are.

More information can be found on the authors website, or the writeup on my blog:
> 4 votes

# Answer
The problem with "scraping everything and starting over" is that if the problem instance is big enough, you might always, or very nearly always, get into a contradiction.

One solution is to use a "block based method". That is, like the original question suggests, earmark a sub-chunk of the original space, re-allow all possible tiles at each of those locations, then run WFC as normal to try and find a solution. If no solution is found, revert to the old chunk, otherwise accept it.

(image above taken from github.com/merrell42/model-synthesis)

The question of what chunk size to use will dependent on the tile set and rules involved. I believe there's a "characteristic length" for any given tile set, potentially complicated by whether it's near a boundary or in the middle-bulk section, where the probability of finding a valid configuration rapidly drops beyond it. Finding the characteristic length for a given tile set it probably difficult so practically this should be done empirically.

Implicit in this algorithm is that you can start from a valid "known good" state. Many tile sets in question have an "empty" tile, so the "all empty" configuration is often a valid one to start from. This might not be a drawback but if an initial condition is needed that's constrained the grid in a certain way, normal WFC might be better suited as solving the initial state might be as much work as finding another, valid, configuration.

Merrell, the original researcher behind/inspiration for WFC, talks about this in his "Model Synthesis" thesis \[0\], and even has code available \[1\]. Boris the brave also has an article on using the block based method for a trickier "escher-esque" like tile set \[2\]. Below is an example from BorisTheBrave.com of an overlapping blocks method on a grass and path tile set:

(image above taken from boristhebrave.com)

0. "Model Synthesis" thesis by Paul C. Merrell
1. github.com/merell42/model-synthesis
2. "Model Synthsis and Modifying in Blocks" at boristhebrave.com
> 3 votes

---
Tags: performance, procedural-generation
---


title: Who 'owns' the components in an ECS?

text:
# Question
Title: Who 'owns' the components in an ECS?
Currently looking and reading about entity component systems, and just wanted to ask about who 'owns' or where the components are registered.

I would have thought that each entity has a collection of all the components associated with that entity. Then from a scene/level ypu could iterate through each entity associated with the scene and then each component for updates/renders/input handling etc.

A couple of examples I've been reading however seem to register the components against the scene, grouped by the entity type. So in this case, registering a component on the entity actually passes the component to the scene, where its stored against the component type and entity id.

Is this a performance thing? As scene would then just be able to iterate over all components (even though its a double loop, 1 over each type and then over each component of type). Or is it that the scene can easily load all components of a given type?

# Answer
> 8 votes
In an actual ECS, entities are just IDs, they don't own the components. Components are usually registered into a container that represents the scene/world the game is currently in.

The reason is indeed performance. When you have all the components in the same place and organize them back-to-back in memory, you can reduce CPU cache misses. It sounds like over-optimization, but it actually amounts to a lot of performance saves since you will be applying it over your entire codebase. This is basically AOS (array of structs) vs SOA (struct of arrays) discussion, just with different terms.

In the component architectures of some popular engines such as Unity (with MonoBehaviours, not DOTS), components are owned by the entities. People often mislabel these architectures as ECS, but they are not. In my opinion, it is better to call them *component architectures* instead of ECS for clarity.

---
Tags: architecture, game-loop, entity-component-system
---


# Question
Title: Would it be practical if I used composition for everything?
I've been learning C++ and SDL2 and I'm trying to improve at using composition and for the longest time I thought it was only useful for making things like players, enemies, coins, etc, and I think part of it is because of my understanding of the word "entity" but after some experimenting where I made my camera an "entity" that had some camera specific components, I realized that technically anything could make use composition since to my understanding the point of composition is making a class out of a bunch of smaller classes.

So now I've been thinking if it would be practical to actually use composition for everything. For example, I have a level manager which is just a basic/normal object that parses an XML file and draws the tiles to the screen would it be beneficial to break things into components such as a tile loader component or would doing this be unnecessary?

# Answer
> 4 votes
Composition is a tool. Always use the right tool for the job.

Of course you can use a screwdriver to hit a nail. But using a hammer might lead to faster and cleaner results.

Composition is a pretty powerful and flexible tool. Some popular game engines (like Unity, for example) are built around the concept. But that doesn't mean that it is the best tool for *every* situation. There are problems that are easier to solve with a singleton system approach. Or where inheritance leads to a cleaner and more flexible design.

I've tried to build games in the past where I tried to fanatically cling to one specific pattern. OOP inheritance, everything communicating through a message bus, Entity-Component-System or whatever else was the main subject of the last article on software architecture I read. Sooner or later I always stumbled upon architectural problems where following my one chosen pattern was just ridiculously counter-productive and I decided to diverge from it.

# Answer
> 0 votes
Yes you could! And many people would. However it’s quite possible to go too far where you have hundreds of tiny components that don’t really do anything themselves and it becomes hard to remember which components need which other ones to combine together properly.

A good rule of thumb is to only break up large components when you need to. Whether it’s because the class is getting too long/ difficult to read, or it’s doing too many things, it’s hard to refactor etc.

A kind of heuristic that I use which has served me fairly well, is that if a class starts approaching 200+ lines. I take a quick look to see if I notice any obvious components hiding inside the big one. If not, that’s fine. When a class gets to the 500+ range, there’s almost always something in there screaming to be let out.

It helps to makes sure you add checks to warn you if you are missing a particular component that another depends on.something as simple as a little console message saying “Missing component X in \___”

---
Tags: c++, sdl2, component-based
---


# Question
Title: Finding the closest point on a circle to end of a ray in 3D
I have a circle in 3D space, so we have center **C** with radius **r**, and the normal of plane the circle lies on, **N**. There is also a normalized vector **V** that I am modifying to go far past the circle's center, so I am multiplying it by a large float value such as 99999999.0f. I need to find the point on the *edge* of the circle that is closest to the *end* of this ray.

So far I have tried iterating around the circle parametrically from 0 to 2PI, and for each point I scalar project the vector from the origin to this point onto **V**, and store the largest value which is farthest along **V**. This seems to get close to the expected result but is off by 0.0006 or so in my current test, and I finding an acceptable step amount for this loop is tricky.

I have tried to derive another way of doing this without having to iterate over every point, which seems quite inefficient. I had an idea of forming a triangle with the origin, **C**, and the end of **V**, but given the arbitrary rotation of the circle I am lost on how to possibly do this. Might there be a simpler way to go about this?

# Answer
> 2 votes
First, if we only care about the endpoint of the ray, then we can forget it came from a ray at all (or really, a line segment, since it has a definite, finite extent). Just think of it as an ordinary point. I'll call it `endPoint`.

Next, since we're limited to the plane of the circle, we can ignore the distance parallel to the normal — no matter how we try to move our eventual result point, we'll never get any closer or further away on that axis. So we can take the vector pointing from the circle center to `endPoint` and project it into the circle plane, then look for the closest point to *that*:

```
toTarget = endPoint - circleCenter

inPlane = toTarget - circleNormal * dot(toTarget, circleNormal)

```

(Here I'm assuming `circleNormal` has length one, but you can divide the normal term by the square of its length if not)

Now we have a vector in the plane of the circle, from its center to the point on the plane closest to our target. If that vector is the zero vector, then every point on the circle is equally close to `endPoint`, and we can choose one arbitrarily. Otherwise, we just snap to the circle radius in that direction:

```
onCircle = circleCenter + normalize(inPlane) * circleRadius

```

# Answer
> 1 votes
I believe DMGregory approach is correct:

> Wouldn't this just be the endpoint minus the circle center, projected onto the circle plane, and normalized to the circle radius?

We will break it down to simple operations.

---

I'm aware you have the circle center \\$C\\$. And you have a ray with \\$V\\$ direction. But you didn't provide nomenclature for the ray start and end. Since you are talking about *the end of the ray*, I'll forget this is about the ray and talk instead of a point which I'll call \\$E\\$ (for endpoint).

Also, I would expect the normal \\$\vec{N}\\$ to be already normalized (i.e. it is an unit vector). To normalize you scale it by the inverse of its length: \\$\vec{N}\*\frac{1}{|\vec{N}|}\\$. *Where scaling means multiplying each component by the scalar factor, and the length of the vector is the square root of the sum of the squares of the components of the vector.*

---

First: the endpoint (\\$E\\$) minus the circle center (\\$C\\$).

We are talking about getting a vector that goes from \\$C\\$ to \\$E\\$. Which we do by vector difference:

$$\vec{d} = E - C$$

*The vector difference is component-wise subtraction (i.e. it is making a new vector which components are the differences of matching components of the original vectors).*

*Yes, vectors do not have an inherent position. So when I say that a vector goes from a point to another, I mean that when I place the vector on the first it points to the other.*

We need to do this difference because we want to project a point on a plane... Which will require to project a vector on the normal (I'll get to that). Since the normal \\$\vec{N}\\$ has meaning when placed on any point on the plane... In order for the projection to make sense, we want a vector that goes from some point on the plane to the point we want to project... And \\$C\\$ is a point on the plane. *In fact \\$C\\$ is the only point we know on that plane, so it is our only option.*

---

Second: \\$\vec{d}\\$ projected onto the circle plane.

I want you to think that there are two vectors \\$\vec{a}\\$ and \\$\vec{b}\\$ such that:

$$\vec{d} = \vec{a} + \vec{b}$$

And \\$\vec{a}\\$ is in the same direction as the normal \\$\vec{N}\\$, while \\$\vec{b}\\$ is perpendicular to it.

Thus:

* \\$\vec{a}\\$ is the projection of \\$\vec{d}\\$ on the normal \\$\vec{N}\\$ vector.
* \\$\vec{b}\\$ is the projection of \\$\vec{d}\\$ on a plane with the normal \\$\vec{N}\\$.

We want to get \\$\vec{b}\\$, but we do not get it directly, instead we get \\$\vec{a}\\$ and then find \\$\vec{b}\\$ like this:

$$\vec{b} = \vec{d} - \vec{a}$$

Since \\$\vec{a}\\$ has the same direction as the normal \\$\vec{N}\\$, it will be the that normal \\$\vec{N}\\$ scaled by some magnitude.

What is the magnitude of the projection along the vector? By trigonometry it is \\$|\vec{d}|cos(ϴ)\\$ where \\$ϴ\\$ is the angle between the vector we are projecting \\$\vec{d}\\$ and the vector we are projecting on \\$\vec{N}\\$.

Therefore:

$$\vec{a} = \vec{N}\*\frac{|\vec{d}|\*cos(ϴ)}{|\vec{N}|}$$

We are going to get \\$cos(ϴ)\\$ from the trigonometric identity of the dot product:

$$\vec{d}·\vec{N} = |\vec{d}|\*|\vec{N}|\*cos(ϴ)$$

*Where the dot product is the sum of the components of the component-wise product of the vectors (i.e. we multiply matching components of the vectors and then sum the products we got).*

Solving for \\$cos(ϴ)\\$ we have:

$$cos(ϴ) = \frac{\vec{d}·\vec{N}}{|\vec{d}|\*|\vec{N}|}$$

Replacing in the prior formula we have:

$$\vec{a} = \vec{N}\*\frac{|\vec{d}|}{|\vec{N}|}\*\frac{\vec{d}·\vec{N}}{|\vec{d}|\*|\vec{N}|}$$

Which simplifies to:

$$\vec{a} = \vec{N}\*\frac{\vec{d}·\vec{N}}{{|\vec{N}|}^2}$$

And now we can get \\$\vec{b}\\$:

$$\vec{b} = \vec{d} - \vec{N}\*\frac{\vec{d}·\vec{N}}{{|\vec{N}|}^2}$$

And assuming \\$\vec{N}\\$ is a unit vector:

$$\vec{b} = \vec{d} - \vec{N}\*\vec{d}·\vec{N}$$

*Yes, that is the projection formula you have seen before, barring variable names and notation.*

---

Third: \\$\vec{b}\\$ normalized to the circle radius.

Since \\$\vec{d}\\$ was a vector that goes from \\$C\\$ to \\$E\\$, \\$\vec{b}\\$ is a vector that goes from \\$C\\$ to the projection of \\$E\\$ on to the circle plane... But not necessarily on the circle (edge).

Since the circle (edge) are all the points that are on the circle plane that are at a distance \\$r\\$ from the center \\$C\\$, all we need to do is make sure the length of \\$\vec{b}\\$ is \\$r\\$.

To do that we get a unit vector from it: \\$\vec{b}\*\frac{1}{|\vec{b}|}\\$... And then we scale it by \\$r\\$: \\$\vec{b}\*\frac{r}{|\vec{b}|}\\$. Let us call it \\$\vec{l}\\$:

$$\vec{l} = \vec{b}\*\frac{r}{|\vec{b}|}$$

---

Fourth: ...

We have found a vector \\$\vec{l}\\$ that when placed on the center \\$C\\$ points to the point we want.

However, our points \\$C\\$ and \\$E\\$ are not defined respect to \\$C\\$. To fix that we will add \\$C\\$ to \\$\vec{l}\\$, and that is our solution:

$$S = \vec{l} + C$$

*Vector addition, as you would expect is component-wise addition (i.e. it is making a new vector which components are the sum of matching components of the original vectors).*

This is - effectively - the counterpart to the subtraction we did at the start. Since we subtracted \\$C\\$ as we needed it as common reference for the projection, we need to add it back so we get a point from the original reference (which is whatever origin you are working with).

*You could also think of these subtraction and addition as a translation transformation and its inverse. Such that the transformation takes the vectors from the original coordinate space to another (which is displaced form the former by said translation), and the inverse transformation takes the vectors back to the original coordinate space.*

---

Notes:

* In general, since we work with floating point numbers, any non-finite number sneaking into the components of the vectors will yield unexpected results.
* Similarly, I remind you that I assumed that the length of \\$\vec{N}\\$ is \\$1\\$. If that is not correct, make sure to normalize it. Be aware that \\$\vec{N}\\$ and thus the circle plane would be ill defined if \\$\vec{N}\\$ is a zero vector (in which case you have division by zero when trying to normalize it).
* Speaking of division by zero, If \\$|\vec{b}|\\$ is \\$0\\$, we have division by zero when trying to scale \\$\vec{b}\\$ to \\$r\\$. This is the case where the projection of \\$E\\$ on the circle plane is on the center of the circle. In which case all the points on the circle (edge) are at the same distance to \\$E\\$.
* We have the opportunity for floating point precision errors. In particular, if you compute the distance form the solution point \\$S\\$ to the center \\$C\\$ you might find that it is not exactly \\$r\\$.

---

In this answer we are getting the closest point on the circle to a point. If you actually wanted to find the closes point on the circle to a ray, you would get the closest point on the line of the ray to the center \\$C\\$, and then get the closest point on the circle to that point.

To get the closest point on the line of the ray to the center \\$C\\$, project the center \\$C\\$ on the line of the ray... In other words:

* Get the vector that goes from the origin of the ray to center \\$C\\$. *This is vector difference (which we need to do because we need the vectors to the points from the same point so projecting them makes sense).*
* *If you need to, you might check that the dot product with the direction of the ray is positive (i.e. that the cosine of the angle is positive, i.e that the angle is less than a quarter turn). If it isn't, it would mean that the resulting point is behind the start of the ray.*
* Project it on the direction vector of the ray. *This is vector projection.*
* And add the the origin of the ray to the result. *This is vector addition (which we need to do because we starting by doing a vector difference).*

What you get would a point on the line of the ray. And you would then proceed to get the closest point on the circle to that point (i.e. apply this answer).

---
Tags: c++, mathematics, vector, geometry, linear-algebra
---


# Question
Title: How to loop over labels start from 1 to 4 and not from 0?
```
InitializeComponent();

            Label[] labels = new Label[4];
            for(int i = 0; i < labels.Length; i++)
            {
                labels[i] = new Label();
                labels[i].Text = i.ToString();
                labels[i].Location = new Point(0, i * 30);
                this.Controls.Add(labels[i]);
            }

```

this will display 0, 1, 2 ,3 but I want to display 1, 2 ,3 ,4 and still make the first one at the location 0,0 and the rest with gap on the y double by 30

# Answer
Create a new variable which is `1` more than `i`, so it should look like this:

```
InitializeComponent();

            Label[] labels = new Label[4];
            for(int i = 0; i < labels.Length; i++)
            {
                labels[i] = new Label();
                int j = i+1;
                labels[i].Text = j.ToString();
                labels[i].Location = new Point(0, i * 30);
                this.Controls.Add(labels[i]);
            }

```
> 3 votes

---
Tags: c#, windows-forms
---


# Question
Title: Car gets stuck to the ground when trying to go upwards
When I tried to go on top of the container, my car got stuck.

Here is a picture of the situation:

* I am using `4200` for mass and defaults for drag and angular drag.
* I'm using the `WheelCollider` component.

I've done some research and one thing I found said to change drag and angular drag, but that didn't fix my problem. Another suggestion was to change The value of the wheel collider. I prefer not to change that because fixing the wheel collider was a really hard problem. Also, I don't think it's a wheel collider issue.

# Answer
You haven't given us much information, but I can think of two possible causes based on your screenshot:

1. If you can back off of the ramp after you get stuck, it's possible that the motor doesn't have enough torque to drive up a ramp. Try increasing the torque.
2. If you *can't* back off of the ramp after you get stuck, it's possible that the colliders for the bumpers are too low (or the wheel colliders are too high), and the wheels don't work because the truck is sitting on the bumpers.
> 0 votes

---
Tags: unity, physics
---


title: Creating a Renderer class using SFML

text:
# Question
Title: Creating a Renderer class using SFML
I currently have a `Renderer` class, which as in the example code, looks like this:

```
Class Renderer()
{
private:
    std::vector<sf::Sprite*> sprites;

public:

    void pushSprite(sf::Sprite& sprite)
    {
        sprites.push_back(&sprite);
    }

    void update()
    {
        std::sort(sprites.begin(), sprites.end(), sort_y);
    }

    void render(sf::RenderWindow window)
    {
        for (/**/)
        {
            window.draw(*sprites[i])
        }
    }
}

```

The problem is the following, I have classes like `Projectile` which holds it's own sprite, and I have vectors in my `Game` class, to hold instances of classes like this, but as these vectors increase in size, they may change their position in memory, therefore making all the pointers in the `Renderer` invalid.

I have a few questions:

Having a `Renderer` class structured like that is the usual? If not, how should I do it? If yes, how would I solve the problem?

# Answer
About the rendering class, I don't know if it's the usual.

About the pointers. The most **raw** solution to your problem with the pointers, **without having to change design**, I think it would be to implement some kind of pool.

* Define the **maximum** of entities of each class that could be in a certain time. ie: 5000000 projectiles for a Vampire Survivors clone.
* Create some `std::vector` (or even `std::array`) of **fixed size** for each class of entity you have.
* Reuse the entities when they are disabled. Don't allocate them with `new`, use the body(memory) of a killed one. Have a check with the health or another flag to decide if the entity can be used to "create" a new one, and just replenish health and position it in the correct place. This way, **the memory positions would be the same for the runtime**. For more advanced solutions, look for **object pool**, or the good ol' gameprogrammingpatterns.
> 0 votes

---
Tags: c++, architecture, rendering, sfml, memory
---


# Question
Title: Reduce entity-component system boilerplate
I'm attempting to create an entity-component system in C++.

However, I've run into an annoying issue where a component system function inherently involves a lot of ceremony and boilerplate. This is because each function needs to perform a lot of validation before the actual meaningful code can be executed.

Example:

```
void cmpnt_enemy_damage(cmpntEnemy* cmpnt_enemy, int damage_amount, vec2* force)
{

    // Validation starts here

    cmpntPhys* cmpnt_phys = component_get<cmpntPhys>(cmpnt_enemy.ent);
    if (IS_NULL(cmpnt_phys))
        return;

    cmpntCombat* cmpnt_combat = component_get<cmpntCombat>(cmpnt_enemy.ent);
    if (IS_NULL(cmpnt_combat))
        return;

    cmpntAnimator* cmpnt_animator = component_get<cmpntAnimator>(cmpnt_enemy.ent);
    if (IS_NULL(cmpnt_animator))
        return;

    // Actual function starts here

    cmpnt_animator_set_animation(cmpnt_animator, cmpnt_enemy.hurt_anim);
    cmpnt_phys_impulse(cmpnt_phys, force);
    cmpnt_combat_damage(cmpnt_combat, damage_amount);

}

```

That's a lot of necessary validation for just 3 lines of code.

I was wondering if this is a common problem and if there are any well known solutions. Or is this just a necessary evil when using an entity-component system?

Thanks.

# Answer
Expanding on my comment above:

One way to reduce these checks for necessary components is to arrange your data so that the function is only ever invoked on entities that *definitely* have those components.

This is usually done not so much for simplifying the code, but for eliminating dynamic branches, for better prediction and throughput when processing large sets of similar entities. But it does come with engineering cost of its own.

The way this is commonly implemented is using the concept of **archetypes**. An archetype is a particular combination of components that an entity can have. So a background image with a `Transform` and `Sprite` component would belong to one archetype, while a projectile with a `Transform` and `Sprite` and `Collider` and `PhysicsBody` component would belong to a different archetype, even though they overlap on two components.

Each archetype is realized as a data structure holding arrays of components for entities that belong to it. A system can then iterate over all entities that have a particular set of components by iterating over the *archetypes* that have those components, then iterating over all corresponding components for entities belonging to those archetypes. Because you have a densely-packed collection of entities that match your *whole* system query, you nearly eliminate branch misprediction, and you can sometimes even operate on blocks of consecutive components at a time, where it makes sense to do so.

This adds some overhead for finding/storing the set of archetypes to iterate, and when switching from one archetype to another, but if you're going this route, usually your archetypes number in the dozens while your entities number in the hundreds to thousands, so the savings per-entity outweigh the archetype cost. (If this isn't the case for your game, then this might not be the architecture for you)

I sketch an approach to implementing archetypes in C# in this answer, and some notes on minimizing branches when using archetypes here. Although a C/C++ solution wouldn't be identical, these other answers help make more concrete some of the details I've hand-waved above.
> 1 votes

# Answer
As DMGregory wrote, the key is to move the responsibility for checking whether or not an entity is relevant for a system out of the system's update function.

Archetypes are one approach to this, but I would like to present a way that can do this without this additional abstraction layer.

* Each system maintains an own array of component-tuples (structures of pointers to a set of components that belong to the same entity) that are relevant to it.
* When an entity is created, or when an entity's composition changes, you pass it to a method of each system that checks if that entity has the required components for this system, and then adds/removes the corresponding component tuple in that array.
* When a system is updated, it iterates over that array of component tuples.

Changes to entities will probably be a lot less common than executing the functions that update them. So by pre-processing the eligibility for various systems on composition changes, you avoid checking them again in every single update even though the composition didn't change. That makes your update methods faster and shorter. You also avoid the overhead of calling the `component_get` function again and again in the update (which might or might not be expensive, depending on your overall architecture) and replace it with a simple pointer lookup.
> 1 votes

---
Tags: c++, c, entity-component-system
---


# Question
Title: Is there a way to set custom data per cell in Godot 4?
My idea is to mark a cell as "occupied" when a character is in that cell doing something so no other character can be on that cell working.

My first thought was to set a `custom data layer` in the `TileSet` named "occupied" with a boolean value and change this value when somebody was in there, ie:

```
# mark as occupied
var tile_data: TileData = Station.get_cell_tile_data(Tiles.FLOOR_LAYER, closest_working_cell)
tile_data.set_custom_data(Tiles.OCCUPIED_LAYER, true)

# set occupied to false
var tile_data: TileData = Station.get_cell_tile_data(Tiles.FLOOR_LAYER, working_cell)
tile_data.set_custom_data(Tiles.OCCUPIED_LAYER, false)

```

But, after some unwanted behaviour of the characters, I've understood that this marks/unmarks **all** the cells in the FLOOR\_LAYER as occupied, which I do not want.

I'm thinking of having an `Array[Vector2i]` of occupied cells and adding/removing them. Or maybe another "invisible" `TileMap` with just the occupied cells so I can check for them.

Or maybe I'm missing something and I'm overcomplicating this.

# Answer
> 4 votes
I solved this problem by extending the TileMap class thus:

```
extends TileMap
class_name LevelMap

var grid = [] # for the 2d grid

# Called when the node enters the scene tree for the first time.
func _ready():
    var dimensions = get_used_rect().size
    for y in dimensions.y:
        grid.append([])
        for x in dimensions.x:
            grid[y].append(null)

func SetObjectInGrid(position, object):
    grid[position.y][position.x] = object

func GetObjectInGrid(position):
    return grid[position.y][position.x]

```

This creates a 2d array based on the dimensions of the TileMap.

I have a couple of functions to set the values at the given position (in this case I was storing an object at each location).

When trying to find the right position (global 2d coordinates) to pass in, I make use of the local\_to\_map function of Tilemap:

```
var tile_pos = LevelTileMap.local_to_map(position)
LevelTileMap.SetObjectInGrid(tile_pos, object)

```

Quick note on the \[y\]\[x\] array format I use; I don't think this matters which way round you do it, this is just personal preference for me - I see it as an array of rows (which in turn are an array of columns).

---
Tags: tilemap, godot, godot-4, tilesets
---


title: Why is HttpClient failing in Unity?

text:
# Question
Title: Why is HttpClient failing in Unity?
Before starting, I know I can use the UnityWebRequest class instead. The problem is that it is *another* library the one that is failing: NEthereum's source code, which makes heavy use of the HttpClient.

So I tried this in a behaviour (2021.3.25):

```
using System;
using System.Net.Http;
using UnityEngine;

public class SampleBehaviour : MonoBehaviour
{
    public void Start()
    {
        TestHttp();
    }

    private async void TestHttp()
    {
        using var client = new HttpClient();
        client.BaseAddress = new Uri("http://127.0.0.1:8545");
        await client.GetAsync("/").ConfigureAwait(false);
    }
}

```

(I tried other local addresses, like my LAN ones, considering that http server is attending on 0.0.0.0 and I succeed hitting it with cURL)

**BUT** when I try this, I get this exception:

`SocketException: An address incompatible with the requested protocol was used`

Now, the issue is that I use IPv4 in a daily basis in other places. What's wrong? Is it something in the .NET setup in the current Unity version? (I'm using .NET Framework and, again, 2021.3.25)

More context here:

I made this test in Unity:

*And still* get the error:

While a stand-alone .NET Framework console application does not fail like this:

And, more important: This HttpClient-related things were working before. This happened after moving to a newer version of Unity (the 2021.3.25 I'm using now). This is why I'm posting the question here and not in a pure C#-related site.

# Answer
You specifically say that you want to use SSL/TLS encryption (`SslProtocols = SslProtocols.Tls12,`), but the protocol-part of your address is `http://`, not `https://`. Try this:

```
client.BaseAddress = new Uri("https://127.0.0.1:8545");

```

Also note that you might need a self-signed SSL certificate for the local webserver in order for https to work properly.
> 2 votes

---
Tags: unity, .net, http
---


# Question
Title: why One big texture frames is consuming more RAM compared to be divided into single frame ones
I noticed that composing frames in a big texture will consume more RAM rather than having 1 frame per texture (or sprite if you would like).

The renderer is SDL2 backed by Direct3D.

Is there any reason why Direct3D (or SDL2 /w Direct3D) is consuming more RAM with 1 big texture containing 10 frames, rather than 10 textures with 1 frame each? basically the size is:

```
num_textures * num_frames * frame_width * frame_height * RGBA_bytes

```

so 1 big textures theoretically is equal to 10 single frame textures, e.g.:

```
big texure size    = 1 * 100 * 100 * 100 * 4 => 4000000 (~4MB)
frame_texures size = 100 * 1 * 100 * 100 * 4 => 4000000 (~4MB)

```

but in practice the big texture has a 5-6 times factor of RAM usage:

* Having multiple big textures containing around 10 different animations the RAM consumption goes up around ~1.2GB
* loading the same data into single frame/sprite texture the RAM consumption is around 220MB.

Is there any reason why this discrepancy in D3D Texture RAM usage?

P.S.

The texture size in both cases are exactly the size needed to store the frame/frames

P.P.S

I know that probably I shouldn't be using GPU in this basic case, but i would like to know the why of the RAM consumption if anyone knows, as rotating 2D sprites might be faster anyway using GPUs rather than CPU operations.

# Answer
There is no discrepancy in RAM usage using a texture-atlas or multiple texture per frame/sprite.

The discrepancy that i had it was a small bug that instead of adding one for a remainder, it was adding the remainder itself...

e.g.

```
// wrong version, unreadable, hidden bug, coming out only when the remainder is > 1
 h = _height * (_tot_frames / n) + (_tot_frames % n);

```

```
// correct version, unreadable
 h = _height * ((_tot_frames / n) + (_tot_frames % n > 0));

```

```
 // equivalent version, more readable easier to spot an eventual error.
 h = _height * (_tot_frames / n);
 if (_tot_frames % n > 0)
     h += _height;

```
> 2 votes

---
Tags: textures, directx, sdl2, texture-atlas
---


# Question
Title: Player stays grounded when jumping at the side of a two tile high wall
I am currently developing a simple Super Mario Bros. like platformer in Cocos2d-x v2. I am now at the step of doing wall sliding with two axis-aligned bounding boxes (tiles) but I've not quite found the right way to do it without any issues.

## I've tried two methods:

1- Calculating at which position the player would be at the next frame based on a fixed run speed

2- Checking the overlap on both axis and checking which overlap is smaller/bigger

I decided to stick with option no. 2 as the movement system of the game relies on acceleration and not a fixed speed. However, not everything is perfect as while trying to implement the system in my project, it wouldn't work as intended. The player, while walking left or right to a wall, will get stuck on the wall when pressing the jump key or simply not detect when the player has touched the top side when on a one tile tall wall, video explaining everything as well as a visual of which keys I'm pressing/releasing: https://streamable.com/qw4abu

Here is the Collision and Overlap code:

```
float PlayerObject::RvsRXOverlap(float hX, float hW)
{
    float lov = (this->getPositionX() + this->getContentSize().width) - hX;
    float rov = (hX + hW) - this->getPositionX();

    if (lov <= 0 || rov <= 0)
        return 0.f;

    if (lov < rov)
        return -lov;
    else
        return rov;
}

float PlayerObject::RvsRYOverlap(float hY, float hH)
{
    float bov = (this->getPositionY() + this->getContentSize().height) - hY;
    float tov = (hY + hH) - this->getPositionY();

    if (bov <= 0 || tov <= 0)
        return 0.f;

    if (bov < tov)
        return -bov;
    else
        return tov;
}

bool PlayerObject::CollisionPrediction()
{
    if (pPlayLayer->GetHazards().size() <= 0)
        return false;

    for (GameObject* hazard : pPlayLayer->GetHazards())
    {
        if (hazard->boundingBox().intersectsRect(this->boundingBox()))
        {
            float dtx = this->RvsRXOverlap(hazard->getPositionX(), hazard->getContentSize().width);
            float dty = this->RvsRYOverlap(hazard->getPositionY(), hazard->getContentSize().height);

            if (fabsf(dtx) <= fabsf(dty)) {
                pXAxis = 0;
                this->setPositionX(this->getPositionX() + dtx);
            } else {
                if (dty == 0)
                    pIsOnGround = true;

                pYAxis = 0;
                this->setPositionY(this->getPositionY() + dty);
            }

        }
    }
    return true;
}

```

Here is where CollisionPrediction(); is called:

```
void PlayerObject::update(float dt)
{

    // INPUT DETECTION
    // ...

    if (pIsOnGround) {

        if (GetAsyncKeyState(VK_SPACE) && pYAxis <= 0)
            pYAxis = 1.f * pJumpHeight;

        // this is where i think the issue is from...
        if (pYAxis > 0)
            pIsOnGround = false;

    } else {
        pYAxis -= dt * pFallSpeed;
    }

    // APPLYING PYAXIS AND PXAXIS TO THE X-Y COORDINATES
    // ...

    CollisionPrediction();
}

```

# Answer
> 0 votes
## I fixed This issue!

The solution: Cast a ray from the player's feet and check if it collides with anything and if it's the case, set the player to be grounded. Like this:

```
if (fabsf(dtx) <= fabsf(dty)) {
    this->setPositionX(this->getPositionX() + dtx);
} else {
    if (pGCRay.intersectsRect(hazard->boundingBox(), 2.f)) {
        pIsOnGround = true;
    }

    this->setPositionY(this->getPositionY() + dty);
}

```

---
Tags: c++, collision-resolution, platformer, cocos2d-x, aabb
---


# Question
Title: I want to convert world coordinates into camera coordinates
In world space, I have an axis (eg. \[-1, 0, 0\]) and a point (eg.\[2,5,1\]). I also have a 4x4 viewmatrix. Now I want to transform that axis and point in camera frame.

I am getting really confused. Does anyone have any idea how should I do this?

I am kinda new to computer vision and all this transformation thing confuses me a bit. From one of the comments, my current train of thought is -

1. Add 1 as fourth component in both axis and point.
2. Multiply these 4D vectors by view matrix. (viewMatrix * vec4)
3. Divide the resultig vectors by fourth component.
4. Discard the fourth component.

Is this process correct?

# Answer
> 1 votes
This is how you decide:

* You add `1` if your vector represents a position, and thus should be translated (which is the case of the point).
* You add `0` for common vectors (which makes sense for the axis, or any direction vector).

Adding `1` is the most common case, because the bulk of data that we need to transform are vertex positions.

The idea behind this is that the fourth component of the vector will be multiplied with the part of the transformation matrix that encodes a translation. And thus using a `0` in the fourth component will nullify the translation.

It might be easier to imagine if you consider a transformation that only has translation. For example, let us say the transformation moves 1 unit along the x axis. And you have your axis vector `(-1, 0, 0)`, after the transformation should it be `(0, 0, 0)` (moved 1 unit on the x axis) or `(-1, 0, 0)` (unaffected by translation)? Well, the axis continues to be the same axis, so it is the latter, thus when transforming the latter you augment it with a `0`. *Of course, it still makes sense to have it affected by mirroring, rotation, shearing, and scaling.*

Since there might be scaling, another related decision is if you will normalize the vector after the translation. For example, a direction (such as a surface normal) should be a unit vector, so you will normalize it after you translate it. But for other vectors - despite not representing position - their length is important. For example, if you transformed a velocity vector, it does not make sense to normalize it after the transformation (in this case the scaling could be considered a change in length units).

---

**Addendum**

Dividing by the fourth component results in foreshortening (things appearing smaller due to perspective), which - again - only make sense for points.

Furthermore, the view matrix shouldn't affect the fourth component (or you are doing something odd). Which means that for the view matrix you can skip the step of dividing by the fourth component altogether.

And thus, you shouldn't have to deal with the case of dividing by `0` from the fourth component.

---
Tags: camera, transformation
---


# Question
Title: The Random.Range function isn't activating when I call it. How do I get the function to work properly and call from a range of numbers?
As you can see, I'm attempting to set the random prey integer to a number within a random range like so:

**randomPrey= Random.Range(0,10);**

As I type the code out the .Range doesn't turn yellow and the error code given is CS0117. I tried doing this in another of my scripts for the same project and It's working fine so it must be something within this script that's causing the function/method to not activate. Any ideas what it could be? I would be more than happy to provide more screenshots if needed.

```
using System;
using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEditor;
using UnityEditor.VersionControl;
using UnityEngine;
using Random = UnityEngine.Random;

public class lionBehavior : MonoBehaviour
{

private int randomPrey;

// Update is called once per frame
void Update()
{
    randomPrey= Random.Range(0,10);
}

}

```

# Answer
To use Unity's integrated random methods, you should include the `UnityEngine` namespace in your C# script. This allows you to access Unity's Random class and its `Range` method for generating random numbers within a specified range. Here's how you should do it:

```
using UnityEngine;

// ...

// Now you can use Unity's Random.Range method
float randomValue = Random.Range(minValue, maxValue);

```

Without the `UnityEngine` namespace, attempting to use `Random.Range` directly will result in a compilation error or use of System.Random. So, remember to include the namespace as shown above, and you'll be able to utilize Unity's randomization features seamlessly.

Another common cause of errors is collision with `System.Random`, which can happen if you import the System namespace (with `using System;`). So you can also try to specify which Random class you want use:

```
using Random = UnityEngine.Random;

```

You also may check this video-timecode about use of Unity Random class https://youtu.be/rD8dRtBqTy0?t=3042
> 1 votes

---
Tags: unity, c#, random, debugging
---


# Question
Title: What is the difference between a gameplay programmer and a game designer/developer?
Gameplay programmers write game code, but so do game designers and developers. Where is the line drawn? What skills do gameplay programmers use that game designers or developers do not?

# Answer
"Developer" is sometimes used as another term for "programmer," where it helps emphasize that creating software involves more than writing code. This association of developer = programmer is particularly common in non-game programming.

In games though, we use the word more generally. "Game developer" can also refer to *any* person working on creating a game, not only those who write code.

For example, if I (a game designer) went out for lunch with a programmer, 3D artist, QA tester, and sound designer from my team, and the server asked what we did, we might reply "we're game developers."

A "gameplay" programmer specifically would usually refer to someone who specializes in coding the action of the game's rules — like the movement of your character and camera, the handling of vehicles, the behaviour of your spells or abilities, and the obstacles you use them to overcome. This is in contrast to say an "engine programmer" who works on the underlying systems that support that gameplay, like being able to stream level data off the disc or juggle drawing millions of polygons. Or a "UI programmer" who works on the game's menus and HUD, or an "AI programmer" who handles NPC behaviours, etc.

"Game designer" is another specialty yet, and the definition can be a little fuzzy even to some experienced gamedevs! The most accessible introduction to the role of a game designer I've seen is Liz England's "The Door Problem." Definitely read the whole thing, but here's a quick excerpt to get the flavour:

> Premise: You are making a game.
>
> * Are there doors in your game?
> * Can the player open them?
> * Can the player open every door in the game? Or are some doors for decoration?
> * How does the player know the difference?
>
> ...
> * Can doors be locked and unlocked?
> * What tells a player a door is locked and will open, as opposed to a door that they will never open?
> * Does a player know how to unlock a door?
> * Do they need a key? To hack a console? To solve a puzzle? To wait until a story moment passes?
>
> ...
> * What happens if there are two players? Does it only lock after both players pass through the door?
> * What if the level is REALLY BIG and can’t all exist at the same time? If one player stays behind, the floor might disappear from under them. What do you do?
>
> ...
>
> It’s a pretty classic design problem. SOMEONE has to solve The Door Problem, and that someone is a designer.

Fundamentally, **game designers are problem solvers** \- figuring out how each mechanic or beat in the game should work to deliver the game's target player experience, according to the team's creative direction.

Common problems a designer may be responsible for solving include:

* How does the player move / navigate / use abilities? (3Cs design)
* How does the player level up, upgrade, or grow? (progression or economy design)
* How do the NPCs and enemies behave? (AI design)
* How do we tune the abilities/items/drops to keep the game fair, interesting, and well-paced? (Balancing)
* What can players buy in the game? (monetization design)

All of these questions have many valid answers that can work. The designer needs to pick the answers that best suit the particular game the team is building. As Katie Salen and Eric Zimmermann put it:

> The game designer only *indirectly* designs the player's experience, by *directly designing the rules*

This is sometimes misconstrued to mean the game designer is the "idea person" who comes up with or dictates everything that will be in the game. In my experience, I've never seen such a role and I don't believe it exists (outside of 1-person studios). Rather, designers work in collaboration with all parts of the team to gather ideas, needs, constraints, and options, and refine them into proposals and documented plans that are clear to the whole team. That means they often need to be translators, acting as a bridge between programming and art departments, or between creative direction and the realities of production, synthesizing solutions that wouldn't be visible from within any one silo.

Some designers are also programmers who write native code, some write scripts and flowchart graphs, and some do no programming at all — working in concert with specialized programmers to realize designs. Likewise, some programmers also excel at design, collaborating in the planning of rules and mechanics or filling in the gaps in a high level direction, while others prefer to implement a fully detailed spec.

I'd recommend checking out the Extra Credits video "So You Want to be a Game Designer", along with the rest of their careers playlist, for an entertaining introduction to many of the common roles in game development teams.

There are also other design-related specialties like level designers, narrative designers, mission or quest designers, who I haven't really covered here. In big teams, the delineations between specialties can be very granular. In smaller teams, these roles often overlap, and you may find a single developer who works as a programmer and game designer and level designer and level artist all at once. So don't take these categories as prescriptive limits, just signposts to the variety of fascinating problems there are to solve in games! :)
> 11 votes

# Answer
Usually Gameplay programmers are specialized on getting gameplay mechanics alive and can do some other low level stuff too, game designers can use scripting languages(C# on unity, LUA on Love2D, blueprint on Unreal and etc) and do almost all the game design from the game, developer is just a generalist term(in this case you need to specify a bit more).

Besides those there are a lot of others roles like: Game engine programmer, AI programmer, Physics programmer, UI programmer.
> 0 votes

# Answer
A Game developer can be working on any part of a game's development: HR(hiring/managing), designing, 2d/3d modeling, animation, programing, etc.

A game designer could be working on designing the game concepts, architecture, and/or flow.

A game programmer would be writing code using a game engine, or coding/extending the game engine itself.
> -3 votes

---
Tags: terminology
---


# Question
Title: What is the difference between an "API," a "framework," an "IDE," and an "engine?"
I am just starting out trying to learn to develop games. At first I thought C++ and OpenGL were the tools a beginner would start out to make a game, but quickly found out the OpenGL was just a API for graphics. Then I thought C++ and SFML were what I needed to learn to make a game, but found out the SFML was a media framework that could be used to make games but wasn't a game engine.

I don't want to use a software that does all the work for me, I want to code my own game, the way a game programmer would. I don't understand the difference between a IDE, framework, API, and a engine; What separates them from each other? Do some game programmers use the SFML framework, while other programmers use a game engine?

# Answer
An API (Application Programming Interface) is an interface; a set of methods you use to interact with an object or set of objects to do something. Example: OpenGL, for 3D graphics.

A Framework is a step up; it's not only a set of APIs, but a way to think about and solve problems. Example: SFML, for media. It gives you graphics but also input handling and other auxiliary APIs.

A Game Engine is more specialized than a framework; it's a framework very specifically targeted to make games, and usually only games of some kind. It usually includes a lot of authoring tools around it, like model editors or importers, etc. Example: Unreal Engine. Lets you make 3D shooters. While you can use SFML to make a 3D shooter, you can also use it to make a video player. With Unreal Engine you make 3D shooters.

An IDE is unrelated to all these. It means Integrated Development Environment, and it's a step up from a plain text editor. It produces source code files which are text files, but in general it has some sort of integration with the compiler, offers wizards to automate parts of writing the code, and so on. Example: Visual Studio, Eclipse.

About "coding your game", unless you're experienced, I'd start with a Game Engine. You can write code to customize how it works and what it does, but it will save you a lot of work towards "your first game". Later you may want try writing your own Game Engine, maybe building on top of a Framework. And if you really like it, you can build your own Framework based on system-level APIs (OpenGL, Direct3D). It can be incredibly rewarding and a great learning experience. FWIW, I was quite experienced as a programmer when I started my Game Engine, but I built it on top of SDL; later I replaced the SDL layer with my own Framework.
> 9 votes

# Answer
1. API (Application Programming Interface) is a set of functions/methods
2. Framework is a collection of APIs
3. Game Engine is a specialized framework for developing games. 3D game engine are also used for simulations & animated movies.
4. IDE (Integrated Development Environment) is a development engine for creating software. IDE integrates a plain text editor with GUI, for viewing the result of running the code. A game engine with GUI is an IDE.
> -2 votes

---
Tags: terminology
---


title: JSON Parse Error - Invalid Value

text:
# Question
Title: JSON Parse Error - Invalid Value
I'm trying to create a script that parses a JSON file to get information about the levels in my project. I know this technique *should* work because I have the same code in two other scripts, parsing two other JSON files, and neither of them have any issues. But for some reason, something here is causing me to get an error:

```
ArgumentException: JSON parse error: Invalid value.
UnityEngine.JsonUtility.FromJson (System.String json, System.Type type) (at <f205f134343a4cd1bdc91ba88ac49a88>:0)
UnityEngine.JsonUtility.FromJson[T] (System.String json) (at <f205f134343a4cd1bdc91ba88ac49a88>:0)
LevelSelectScript.Start () (at Assets/Scripts/Menu Scripts/LevelSelectScript.cs:77)

```

Here's the code from LevelSelectScript (irrelevant bits cut out):

```
[SerializeField]
private TextAsset jsonFile;
[SerializeField]
private Levels lvlFromJson = new Levels();

void Start()
{
    jsonFile = Resources.Load<TextAsset>("JSON/levelsJSON");

    lvlFromJson = JsonUtility.FromJson<Levels>(jsonFile.text); //This is line 77, where the error occurs
}

```

The Levels class contains an array called levels\[\], which is made of Level objects. The Level class looks like this:

```
public class Level
{
    public string id;
    public string name;
    public bool challengeComplete;
}

```

And Levels looks like this:

```
public class Levels
{
    public Level[] levels;
}

```

And the JSON file looks like this:

```
{ "levels": [
    {
        "id": "lvl0_lorem",
        "name": "Lorem",
        "challengeComplete": false
    },
    {
        "id": "lvl1_ipsum",
        "name": "Ipsum",
        "challengeComplete": false
    }
]}

```

I'm sure I'm missing something really obvious that's present in my other scripts, but for the life of me I can't figure out what it is. As far as I can tell the JSON has proper syntax and its values match those of the Level class, which are the only areas I can think of that would produce the error.

# Answer
In copying the JSON over, I cut out some of the numerous entries just to show what the format looked like without cluttering up the post. Well, in doing so I managed to crop out the last few lines, which looked like this:

```
    {
        "id": "lvl10_lorem",
        "name": "lorem",
        "challengeComplete": false
    },
]}

```

Yup, an errant comma after the braces. Let this be a lesson to all those who come after: don't trim down your code to look pretty in a post!
> 1 votes

---
Tags: unity, json
---


# Question
Title: Custom GUI with mouse pointer events handling
Recently I heard about possible algorithms to determine if the mouse cursor is on a GUI element such as a button:

* Determine the element's coordinates and size to check whether the cursor is on the element mathematically.
* Giving each element its own color so that the mouse cursor interacts with a specific color. I think this method is better with complex shapes of elements, but I don't know how this method works.

I don't know if those are the actual methods used, or if there are other ways.

I also read that there is a relationship between the GUI and the offscreen buffer for mouse cursor events, but I didn't find much about that.

So based on what I mentioned, my question is:

**What are the algorithms and methods used in the GUI to determine if the mouse cursor is on one of the GUI elements?**

I would be grateful if there were sources to look at or examples to understand the topic.

# Answer
> 0 votes
Assuming your GUI elements are simple shapes like rectangles, detecting if your mouse is on the element becomes fairly trivial. Here's the pseudo code:

```
function IsCursorInRectangle[mouse,rectangle]
Is mouse.x > rectangle.x
     is mouse.x < rectangle.x + rectangle.width
          is mouse.y > rectangle.y
               is mouse.y < rectangle.y + rectangle.height
                    return true;
 return false;

```

This is a simple example of how to check it in C.

```
#include <stdio.h>
struct Coordinate
{
     int m_nPositionX;
     int m_nPositionY;
};
struct GUIElement
{
     struct Coordinate m_csPosition;
     int m_nRecWidth;
     int m_nRecHeight;
};

int IsCursorOnElement(struct GUIElement* pgElement, struct Coordinate* pcCursor)
{
     if(pcCursor->m_nPositionX > pgElement->m_csPosition.m_nPositionX &&
        pcCursor->m_nPositionX < pgElement->m_csPosition.m_nPositionX + pgElement->m_nRecWidth &&
        pcCursor->m_nPositionY > pgElement->m_csPosition.m_nPositionY &&
        pcCursor->m_nPositionY < pgElement->m_csPosition.m_nPositionY + pgElement->m_nRecHeight)
     {
          return 1;
     }

     return 0;
}
int main(void)
{
     struct GUIElement gsButton = {{100,100},50,50};
     struct Coordinate csCursor = {105,120};

     if(IsCursorOnElement(&gsButton, &csCursor))
     {
          puts("We're inside the element");
     }
     else
     {
          puts("We're outside the element");
     }
     return 0;
}

```

If you want to do other shapes like circles, you would need the center x,y of the circle + it's radius.

Here's a resource you can check out . https://www.jeffreythompson.org/collision-detection/point-rect.php

---
Tags: gui, ui-design
---


# Question
Title: How would I generate mipmaps for a 3D texture in Unity (at runtime)?
I have been trying to create a voxel cone tracer for Unity (in Universal Render Pipeline 16).

I have this *(unoptimized)* C# code that turns the \[CubeScale\] area around 0,0,0 of the scene into a 3D texture and saves it in the editor.

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

public class LBTraceArea : MonoBehaviour
{
    public Texture3D Volume;
    public float CubeScale;
    public int CubeQuality;
    public string SaveAs;

    //pre-define texel size so it can be used among all functions
    float texelSize = 1f;

    // Start is called before the first frame update
    void Start()
    {
        Debug.Log(Volume.mipmapCount);
        //define the size of 1 3d texel/volumetric cube pixel/voxel
        texelSize = CubeScale / CubeQuality;
        VoxelizeArea();
        AssetDatabase.CreateAsset(Volume, "Assets/" + SaveAs + ".asset");
        Debug.Log(Volume.mipmapCount);
    }

    //function to create 3D texture AKA voxel image with scene objects.
    void VoxelizeArea(){

        //Setup a 3d Texture

        //Format
        TextureFormat form = TextureFormat.RGBA32;
        TextureWrapMode wrap = TextureWrapMode.Clamp;

        //Defining the Volume
        Volume = new Texture3D(CubeQuality, CubeQuality, CubeQuality, form, false);
        Volume.wrapMode = wrap;
        Volume.filterMode = FilterMode.Trilinear;

        //Create a volumetric color array.
        Color[] color = new Color[CubeQuality * CubeQuality * CubeQuality];

        //Loop to actually create the color volume

        //Define how offset the position of the object is from the center of the Volume.
        //object Offset
        Vector3 oOff = new Vector3(
            transform.position.x + (CubeScale * -0.5f),
            transform.position.x + (CubeScale * -0.5f),
            transform.position.x + (CubeScale * -0.5f)
        );

        //define "Real Tick"/rt or how many loops total of all 3 for loops
        int rt = 0;

        //tx ty and tz is a pun because they are short for texel+(the axis, for example x) and also short for tick+(the axis, for example y)
        for (int tx = 0; tx < CubeQuality; tx++){
            for (int ty = 0; ty < CubeQuality; ty++){
                for (int tz = 0; tz < CubeQuality; tz++){
                    //tick area, ya have access to tx, ty, and tz all in here so you shouldn't need to be outsize of this when calculating coor math and stuff.

                    //Color at Real Tick AKA rt would define the exact pixel at the exact position.
                    //so Color[rt] would be Color at the pixel

                    //color[rt] = new Color(tx, 1f, tz, ty);
                    color[rt] = GetColorAtPosition(new Vector3(tz * texelSize, ty * texelSize, tx * texelSize) + oOff);

                    rt++;
                }
            }
        }

        //Put the colors on the 3d bitmap volume and apply the changes so it gets resent to the GPU.
        Volume.SetPixels(color);
        Volume.Apply();

    }

    //function to get an objects surface color at an exact Vector3 location
    void GetColorAt(Vector3 cpos){

    }

    Color GetColorAtPosition(Vector3 position) {
        Vector4 grabber = Vector4.zero;
        grabber += GetColorAtPosAndRot(position, Vector3.up);
        grabber += GetColorAtPosAndRot(position, -Vector3.up);
        grabber += GetColorAtPosAndRot(position, Vector3.right);
        grabber += GetColorAtPosAndRot(position, -Vector3.right);
        grabber += GetColorAtPosAndRot(position, Vector3.forward);
        grabber += GetColorAtPosAndRot(position, -Vector3.forward);
        return grabber;
    }

    Vector4 GetColorAtPosAndRot(Vector3 position, Vector3 normal){
        RaycastHit hit;
        if (Physics.Raycast(position, normal, out hit, texelSize)){
            Renderer renderer = hit.collider.GetComponent<Renderer>();

            if (renderer != null){
                Texture2D texture = renderer.material.mainTexture as Texture2D;

                if (texture){
                    Vector2 pixelUV = hit.textureCoord;
                    pixelUV.x *= texture.width;
                    pixelUV.y *= texture.height;

                    return texture.GetPixel((int)pixelUV.x, (int)pixelUV.y);
                } else {
                    return renderer.material.color;
                }
            }
            return new Vector4(1f,1f,1f,1f);
        }

        return new Vector4(0f,0f,0f,0f);
    }
}

```

*Please ignore the name of the texture. It does not currently have LODs or Mipmaps, it needs to have them which is why it is called that.*

The Debug.Log used at the end of void Start() returns with 1. which makes me believe there are no mipmaps.

I also have a custom HLSL function in the shader editor to ray march the 3D texture. The desired results are for clean and noise-free global illumination. This may not be that useful for solving the problem, but it demonstrates what I am trying to accomplish. Here is the code for that.

```
Color = float4(0, 0, 0, 0);
Distance = 0;

float MarchSize = 1 / VolumeQuality;

float3 pos = float3(0,0,0);

//Define t and start 4 steps out
//4 because honestly it's the best I could do
float t = MarchSize * 4;
while (t < 1) {

    if (Color.a < 1) {
        pos = Position + (Normal * t);
        Color += SAMPLE_TEXTURE3D_LOD(Volume, Sampler, pos, Roughness * t);
        Distance = t;
    }

    //advance tick size
    t += MarchSize;
}
Color.a = min(Color.a, 1.0);

```

Here is what this raymarch looks like in a scene:

Here is what it SHOULD look like (except this image has a lot of noise because I had to stochastically sample this instead of sampling it with the mipmaps):

I need mipmaps for my Texture3D, otherwise, LOD on the SAMPLE\_TEXTURE3D\_LOD in my HLSL(the fourth parameter of that function) does not do anything. This is bad because if I cannot obtain Mipmaps on my 3D Texture, I cannot get my desired lack of noise, and I would have to resort to using stochastic sampling or giving up. So, I need to know how to generate mipmaps for my 3D Texture.

Additional information: The 3D texture is only saved to the assetdatabase for now. I will later find a way to automatically apply the 3D texture to all raymarching shaders. I need to do this because (after I optimize my script that writes the scene to a 3D texture) I need to write the scene to a 3D texture in real time for some epic reflections and real-time GI. I say this to say that it would be ideal that the mipmapping method would be fast and work at runtime. Also, even though it may not be practical, I would prefer if the solution were to work on most URP-supported hardware if at all possible, so please no Direct-X-only stuff unless it is required.

If someone believes the issue is something else, that information would be greatly appreciated aswell.

# Answer
I finally figured out the issue. Unity will automatically generate mipmaps if the fourth parameter of:

```
Volume = new Texture3D(CubeQuality, CubeQuality, CubeQuality, form, false);

```

is set to true.

So like this:

```
Volume = new Texture3D(CubeQuality, CubeQuality, CubeQuality, form, true);

```
> 3 votes

---
Tags: unity, c#, hlsl, mipmaps, raymarching
---


# Question
Title: Call function with signal on other scene
I'm still getting confused as how to call a function from another script on another scene in Godot 4.x. In my example below, I want to call print\_something() on menu.tscn from main.tscn

On main scene we have:

```
# main.gd
# main.tscn
extends Node2D

func _ready():
    print_something("Hello") #works on main

func print_something(astring):
    print(astring)

```

On menu scene we have:

```
# menu.gd
# menu.tscn
extends Node2D
signal mysignal
@export var message := "Gwen Stefani is bananas!"
# main.print_something(message) # Unexpected "Identifier" in class body.

```

When trying to connect the signal node I'm not given the option of picking another scene.

Undated script as Alex CB suggested still results in error: extends Node2D

```
extends Node2D
# menu.tscn
@onready var main := get_tree().root.get_node("main")
@export var message := "Gwen Stefani is bananas!"
# then you can use
main.print_something(message)

```

# Answer
> 1 votes
To connect a `signal` by code, you do like this:

```
var err := main.connect("signal_name", callable_name)

```

But, for what I understand you want to do, you don't need a `signal`. According to the official documentation:

> (signals) should be used only to "respond" to behavior, not start it. By convention, signal names are usually past-tense verbs like "entered", "skill\_activated", or "item\_collected".

Another way could be to access `main` from the `menu`, like this:

```
@onready var main := get_tree().root.get_node("main")
# or, if menu is a direct child of main
@onready var main := get_parent()

@export var message := "Gwen Stefani is bananas!"
# then you can use inside a function
func _ready():
  main.print_something(message)

```

Also, you'll have to instance `menu` scene in your `main` scene by clicking the `Instance child scene` (chain icon, top left, next to the `+` symbol).

---
Tags: godot-4
---


# Question
Title: How Can I Match the Windows Cursor Latency with a DirectX Rendered Cursor?
My Win32/DirectX 11.1 project requires that I render the mouse cursor myself rather than use the system cursor. This is easy enough; however, I've found that there is a human-perceptible latency when updating the position. I can demonstrate this in a simple test harness when I leave the system cursor on -- in this setup, my rendered cursor lags slightly behind the system cursor as I drag the mouse, catching up when I stop moving it. It is not a major effect, but it is non-zero, and reproduces on more than one system with different hardware (both CPU and GPU).

My test harness is stripped down as much as possible to avoid confounding variables. It merely creates a window and listens for WM\_MOUSEMOVE in the winproc. When this message is received, it renders the cursor at the reported position. Position is passed via a constant buffer to my shaders; the vertex shader operates on a triangle strip with 4 vertices / 2 triangles which makes a quad and the pixel shader just produces a fixed color, resulting in a basic rectangle for my cursor shape.

I have also tried not handling WM\_MOUSEMOVE, but instead polling the cursor position with GetCursorPos/ScreenToClient and rendering in a tight loop. This also reproduces the slight latency, but at least allows me to get a sense of FPS; this loop runs at over 4000hz on my machine, which is obviously well beyond the capacity of human perception. From this I believe the issue is not in the renderer, so I haven't tried other approaches like using a vertex buffer instead of a constant buffer.

If it is not in the renderer, my next guess is that I am experiencing some sort of input latency. For example, if the system cursor is rendered prior to (or racing with) updating the position reported by GetCursorPos I could experience this lag. I don't know this to be the case, so I am just speculating here. To help eliminate that variable I also tried using the raw input APIs (despite being usually counter-indicated for mice); this continued to exhibit the slight latency.

So: can anyone help me mitigate this latency? My desired end state is that I cannot perceive a difference in position between my rendered cursor and the system cursor when moving the mouse. Some additional constraints: I have to stay in user space (no rootkit solutions) and I'd really like to stick with published APIs if possible.

If it isn't possible (for example, if Windows is making use of APIs inaccessible to me), I'd like to at least understand why, if anyone knows.

To forestall requests for my source: unfortunately, I cannot share my code due to it being considered proprietary (yes, even the test harness...I don't make the rules).

Thanks!

# Answer
I ran into the exact same thing. Although it couldn't be helped much in windowed mode, in fullscreen, using the new DXGI `SetMaximumFrameLatency` function really helped:

```
    IDXGIDevice1* pDXGIDevice1;
    pD3DDevice->QueryInterface(__uuidof(IDXGIDevice1), (void**)&pDXGIDevice1);
    pDXGIDevice1->SetMaximumFrameLatency(1);

```

The default latency is 3, and I could feel it in fullscreen. Setting it to 10 confirmed that it DOES work. :)

I'll be looking for solutions in windowed mode in the meantime; it could be related to device settings or maybe the swap chain...
> 0 votes

---
Tags: directx11, windows, mouse, latency
---