# Question
Title: what is more memory intensive in Unity: 100 GameObjects with PaticleSystems, or 100 GameObjects spawning other GOs
I am making a bullet hell game. Say there are 100 bullets on the screen, and each bullet has a trail effect. Is it more performant to give each GameObject a ParticleSystem, or for each GameObject, instance child particle GameObjects? I am developing the game in Unity.

# Answer
Particles are much more lightweight than full-fledged game objects. So using the standard particle system (or even better: visual effects graph) will likely get better results than trying to build your own particle system based on game objects.

However, if you want to use particle systems in a way which is not just cosmetic but actually affects the game mechanically, then you are trying to fit a square peg in a round hole, and will pay the performance tax for that.

So while it might be feasible to make each bullet a game object with an attached particle system, it might not be such a good idea to try to make the bullets themselves particles.

And by the way, if you want to create a game with a large number of relatively simple objects, then that might be a perfect use-case for the new Entity - Component - System architecture of Unity. The whole feature is still not really production-quality, so dealing with it can be rather frustrating at times. But if you are brave enough to handle it, it can give you amazing performance.
> 1 votes

---
Tags: unity, memory-efficiency
---


# Question
Title: The other animations are not played when I delete idle animation
I'm using Cyber Monsters 2 asset and found some weird stuff. If I delete idle animation or move it away, the other animations stop working and the monster stays in T-pose. When I check the animator, active animations are marked as playing but the actual animation is not played. What could be the reason?

# Answer
The prefab in the asset had an animator component with the avatar from idle animation. When I re-assigned another avatar, things started to work again.
> 0 votes

---
Tags: unity, animation
---


# Question
Title: How do i correctly interpolate between 2 positions recieved from server?
I am trying to implement interpolation in client side. I store Vector2 position data recieved from server in a list and try to interpolate (x,y) from previous position to next position as data comes. But i couldnt implement it correctly and its not smooth. Tried many differet ways, some was actually smooth by luck but i want to learn how to implement it in correct way. here i post an example code which is not smooth at all and has missing parts i guess.

Actually data comes from client1 as it moves his mouse which sends the coordinates to the server which just directs it to client2, so i dont know in which rate they are coming. I mean data is not coming in constant rate from server which is correct way to implement a server authorative game but anyway. if data must come in constant rate i can also implement it.

```
private final float STEP = 1.0f / 240f;
private float accumulator;
public static ArrayList<Vector2> ballPositionList = new ArrayList<>();

public void onPositionData(Vector2 positionVector){ // called when vector2 position comes from server
      ballPositionList.add(positionVector);
}

public void render(float delta) {
        accumulator += delta;
 while (accumulator >= STEP) {

            table.act(STEP);
            accumulator -= STEP;
        }
        table.interpolate(accumulator / STEP);
}

public void interpolate(float delta){ // tables interpolate method
if(ballPositionList.size() >1 ){
        while(ballPositionList.size() > 2){ // feel like i add another boolean check here but idk what should i
            ballPositionList.remove(0);

            Vector2 prevPosition = ballPositionList.get(0);
            Vector2 nextPosition = ballPositionList.get(1);
            float interpolationFactor = delta; // this is wrong. what should it be?
            float x = nextPosition.x * interpolationFactor  + prevPosition.x * (1.0f - interpolationFactor );
            float y = nextPosition.y * interpolationFactor  +  prevPosition.y * (1.0f - interpolationFactor );

            getBall().set(x, y);

        }
    }

}

```

# Answer
> 0 votes
If you're not using a fixed tick-rate, you might receive new, incoming data while your client is still calculating your interpolation. That might be the cause of your implementation being clunky.

You could take into account the distance that you have to interpolate to make it faster or slower, depending on how far the ball has to travel. If it takes the same time to interpolate, regardless of whether the ball moves one foot or ten miles, the end result will look clunky.

---
Tags: networking, multiplayer, interpolation, fixed-timestep
---


# Question
Title: deleting and re-referencing nodes with $
I want to delete a scene and re-load it. This code would fail later, because the new "CoolScene" has in fact a different name, something like "@NotSuchCoolName@34", and thus it cannot be referenced with $CoolScene once the garbage collector destroys the old scene:

```
$CoolScene.queue_free()
var cool_node = load("res://pathto/CoolScene.tscn").instance()
add_child(cool_node )
cool_node.set_name("CoolScene")

```

But if I rename the scene, then it will work:

```
$CoolScene.set_name("oldCoolScenebyebye")
$oldCoolScenebyebye.queue_free()
var cool_node = load("res://pathto/CoolScene.tscn").instance()
add_child(cool_node)
cool_node.set_name("CoolScene")

$CoolScene.whatever #Works now!

```

However this looks like awful code to me, main reason being that I need to invent temp names that are unique everytime a scene gets deleted, something that should be done by the garbage collector. Please help me write better code!

# Answer
Let us look that this code:

```
$CoolScene.queue_free()
var cool_node = load("res://pathto/CoolScene.tscn").instance()
add_child(cool_node)
cool_node.set_name("CoolScene")

```

The first line `$CoolScene.queue_free()` will delete the `Node` referenced by `$CoolScene`. But not yet. *See also What is happening during queue\_free() process?* \- Suffice to say that Godot will remove the `Node` from the scene tree, and free it sometime after the code finished executing, and no, that isn't a garbage collector.

The second and third line instantiates and adds a new child `Node`. Be aware that at this point, this new `Node` will already have a name. Godot would have generated a new name if it collided with the name of the existing `Node`.

And finally the fourth line would change the name of the `Node`. Except it still cannot have that name because the existing node still has it.

---

To fix that we are going to separate removing a `Node` from the scene tree and freeing it.

```
var old_node = $CoolScene
remove_child(old_node)

var cool_node = load("res://pathto/CoolScene.tscn").instance()
add_child(cool_node)

old_node.queue_free()

```

Here the first line `var old_node = $CoolScene` is keeping a reference to the old node in a variable so I can call `queue_free` on it at the end.

The second line `remove_child(old_node)` removes it from the scene tree.

Now the third and fourth lines can instantiate and add the new node. Which can have its expected name - right away (we didn't have to wait until the old `Node` was freed) and without issue - since the old node is not in the scene tree anymore.

Finally the fifth line calls `queue_free` on the old node, which can be deleted sometime later also with no issue.

*And, of course, we didn't have to come up with some other name.*
> 0 votes

---
Tags: godot, instancing, gdscript
---


# Question
Title: How do I get OnTriggerStay2D to consistently work in Unity?
(2D Project) I have a very basic set-up in which I have a Hallway with a door and a bunch of other objects. I have a player that starts on the left side of the hallway and only moves on the x-axis. The player has a Box Collider 2D and a Rigidbody 2D. He has a script that allows him to move and within the script I have a method called "CheckEnterDoor()", which, if the bool "main" is true, \> if you press e, unloads the hallway and its objects and loads a secondary room. If you press e while in the secondary room, the opposite happens, secondary room gets unloaded, main hallway gets loaded (they become invisible, atleast, I am not sure what technically happens to them \[SetActive(false)\])

I call this method from within a different script which, instead of being attached to the player, is attached to the door. The door has a Collider2D which is set to "Is Trigger", so that you can pass through it and use it as more of an "area of interactivity", atleast thats the way I am trying to use it. It just has the basic setup so that the door script can access the player script and then within "OnTriggerStay2D", which, the way I understood it, is supposed to be some sort of a "while(in\_Collider2D\_area)", I try to make it possible to open the door.

The issue comes up when I actually try to do this when playing the game. I gave the door a massive collider2d box and the player a very tiny one

but pressing e while inside of the door box only works SOMETIMES. Sometimes while I'm walking towards it I'll press e and it works. Sometimes I'll do that exact same thing and it doesn't. Sometimes I need to move around a bit within the massive box while spamming e to make it work. I can always get it to work, but it seems to be completely random as to WHEN it actually works. I have seen people have similar-ish issues with this in some 2015 post, the suggested solution was to use a Kinematic OR Dynamic Rigidbody 2D Body Type instead of a static one, because that could apparently cause issues. My Rigidbody2D was set to Dynamic by default and the only option within it that I changed was the gravity so that the player wouldn't just fall through the floor. Using the Kinematic Body Type did not resolve the problem either, though. Another fix I saw was to put the Rigidbody 2D to "Never Sleep" mode, which I did, but it again did not change anything. I might not have been able to find a proper answer to this because I am unsure how to actually formulate my question or describe the issue without making it overly specific.

\**I have used Debug.Log("blabla"); and it has continously given out a ton of messages into the console, meaning the Program seems to fully realise that I AM inside of that Collider2D box, yet will not let me execute the code. I am now thinking it might be a code problem instead of a box-dragging or rigidbody settings problem.

This is my first time posting here and also my first time working with Unity, if I need to send the project or full source code or anything like that somehow please let me know and I will do it.

# Answer
> 1 votes
I'm relatively new to Unity myself, but I ***think*** what's happening here is that GetKeyDown only returns true for the first frame in which it is pressed.

`OnTriggerStay2D` may not fire every frame, and/or it might be a different frame by the time `Input.GetKeyDown` executes. When you spam the key, you eventually get the timing right and hit a frame where `Input.GetKeyDown` is called during that first frame.

I'd suggest capturing any Input flags in the `Update` function which runs exactly once per frame. Compare to how the horizontal and vertical axes are captured in the Update function of the Ruby's Adventure tutorial.

1. Introduce a `bool isPlayerInDoor` to your Movement, either as a public member or with a helper function like `SetPlayerInDoor(bool)`.
2. Instead of calling `CheckEnterDoor` from `OnTriggerStay2D`, instead use `OnTriggerEnter2D` and `OnTriggerExit2D` to update `isPlayerInDoor`. (Side note: this may not be relevant at the moment, but you may want to check that the colliding object is in fact your player!)
3. Capture `Input.GetKeyDown("e")` in Movement's Update function, where it will reliably return true once and only once per press.
4. You can move the code from CheckEnterDoor to the Update function, or you can call it from Update if you pass it the captured value from `GetKeyDown`. In either case, add a check for the new `isPlayerInDoor` bool, which will be true from entrance to exit of the trigger.

Hope this helps. Tangentially, you may also consider `GetButtonDown` over `GetKeyDown`. GetButtonDown opens the door (no pun intended) to using Input Manager to support players who want to reconfigure keys.

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


# Question
Title: How to identify the visible tiles and select them for rendering?
I can render a 5000 x 5000 tile map, but it takes forever to load, and the performance is horrid.

It takes around 30 seconds to Render all the tiles, So how can I render only the visible tiles?

Here is the gist of the rendering code

```
let mut worldx = 0;
let mut worldy = 0;

fn blit(t: Texture2D, x: f32, y: f32, w: f32, h: f32) {
        draw_texture_ex(
            t,
            x,
            y,
            WHITE,
            DrawTextureParams {
                source: Some(Rect::new(0.0, 0.0, w, h)),
                ..Default::default()
            },
        );
    }

loop {
    for i in 0..map_width {
        for j in 0..map_height {
            blit(grass, i as f32 * 32.0 + worldx, *j as f32 + worldy, 32.0, 32.0);
        }
    }

    render_player(screen_width / 2, screen_height / 2)
}

```

# Answer
> 2 votes
I'm not really familiar with this code, so bear with me.

If I understand correctly you use this line to draw the player character - or something akin to that - at the center of the screen, right?

```
blit(player, screen_width() / 2.0 - 32.0, screen_height() / 2.0 - 32.0, 32.0, 32.0,);

```

*I converted the gif to mp4 so I could seek to the end, and found that it draws a lot of green squares with a something in the center, and `screen_width() / 2.0` and `screen_height() / 2.0` looks very center, such middle, to me. So I believe this line is responsible of that.*

That tells me that the bounds of the screen are `screen_width()` and `screen_height()`. And apparently the size of the sprite is `32` by `32`, which I'll assume is also the size of the tiles. Furthermore, this line tells me that the `blit` function is used to draw. So, let us see the `blit` function:

```
fn blit(t: Texture2D, x: f32, y: f32, w: f32, h: f32) {
        draw_texture_ex(
            t,
            x,
            y,
            WHITE,
            DrawTextureParams {
                source: Some(Rect::new(0.0, 0.0, w, h)),
                ..Default::default()
            },
        );
    }

```

Ok, now I have a chance at parsing this:

```
blit(grass, i as f32 * 32.0 + worldx, *j as f32 + worldy, 32.0, 32.0);

```

So this renders:

* The `grass` texture.
* At x coordinate `i as f32 * 32.0 + worldx`
* At y coordinate `*j as f32 + worldy`
* Width `32`
* Height `32`

---

**New approach**

You are going to render `grass` anyway, right? Let us start there.

Now, the size of the screen is `screen_width()` and `screen_height()`, which we can divide by the size of the tile and round upwards to figure out how many tiles must there be visible.

That got to be something like this:

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

```

*I could be introducing an off-by-one error. Yet, I'm erring on the upside, so worst case scenario you render a line of tile out of bounds of the screen.*

Then, let us figure out the `x` and `y` coordinates in tile space of the center of the screen. That got to be something like this:

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

```

Thus, we get a range in tile space. Something like this:

```
let lo_tile_x = floorf(center_tile_x - screen_w_in_tiles / 2.0) as i32;
let hi_tile_x = ceilf(center_tile_x + screen_w_in_tiles / 2.0) as i32;

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

```

Then you can loop:

```
for i in lo_tile_x..hi_tile_x {
    for j in lo_tile_y..hi_tile_y {
        blit(
            grass,
            i as f32 * 32.0 + worldx,
            j as f32 * 32.0 + worldy,
            32.0,
            32.0
        );
    }
}

```

*I appreciate the symmetry between the `x` and `y`, and the lack of `*j`*

---

Furthermore, presumably you can query your data structure with an arbitrary `x` and `y` coordinates. I suppose you could make a class for your data structure, or at least make a function that borrows it, and takes the `x` and `y` coordinates and tells you the kind of tile you need to render, and then you can select a texture based on that.

So you could something like this:

```
for i in lo_tile_x..hi_tile_x {
    for j in lo_tile_y..hi_tile_y {
        let texture = choose_texture(
            get_tile_type(
                i,
                j,
                /*other arguments that reference to the vector or whatever*/
            )
        );
        blit(
            texture,
            i as f32 * 32.0 + worldx,
            j as f32 * 32.0 + worldy,
            32.0,
            32.0
        );
    }
}

```

*I also didn't put check for the bounds, you can add that too.*

---

**Old approach**

Now, are those coordinates within `screen_width()` and `screen_height()`? Well, let me try to understand the coordinates first.

* `i`: you take the first index.
* `i as f32`: you cast `i` to a 32 bit float, right?
* `i as f32 * 32.0`: scale it by 32, which is the width.
* `i as f32 * 32.0 + worldx`: and add some offset.

And…

* `*j`: what? What is this? Some pointer? *Yeah, I don't know.*
* ???

Ok, calm, breathe. I'll work with what I know, and hopefully that is sufficient for you to take it all the way there.

What is the first value of `i` that would be on the screen? It would be the smallest value such that `i as f32 * 32.0 + worldx >= 0`. So, set up the equation, and solve for `i`:

```
i as f32 * 32.0 + worldx = 0

=>

i as f32 * 32.0 + worldx - worldx = 0 - worldx

=>

i as f32 * 32.0 = -worldx

=>

i as f32 * 32.0 / 32.0 = -worldx / 32.0

=>

i as f32 = -worldx / 32.0

```

Thus, you can start iterating at `-worldx / 32.0` (round downwards and cast to integer).

Now, where do we stop? What is the last value of `i` that would be on the screen? That would be the greater value such that `i as f32 * 32.0 + worldx <= screen_width()`. Spoiler: more equations!

```
i as f32 * 32.0 + worldx = screen_width()

=>

i as f32 * 32.0 + worldx - worldx = screen_width() - worldx

=>

i as f32 * 32.0 = screen_width() - worldx

=>

i as f32 * 32.0 / 32.0 = (screen_width() - worldx) / 32.0

=>

i as f32 = (screen_width() - worldx) / 32.0

```

So want to loop up to `(screen_width() - worldx) / 32.0` (round upwards and cast to integer).

Be aware that the range from `-worldx / 32.0` (round downwards and cast to integer) to `(screen_width() - worldx) / 32.0` (round upwards and cast to integer) might go outside the vector you have, so you may want to clamp the range.

I believe that instead of this:

```
for i in 1..tile_list.len() {
    // …
}

```

It should be something similar to this:

```
let lo_i = min(1, floorf(-worldx / 32.0) as i32)
let hi_i = max(tile_list.len(), ceilf((screen_width() - worldx) / 32.0) as i32)
for i in lo_i..hi_i {
    // …
}

```

*By the way, I have finally settled in `floorf` and `ceilf` from `libm` after disappointments with the functions rust has for floats.*

Also, by the way, are you sure the vector goes from `1` to `.len()`? That does not sound right to me, but hey this is arcane code to me. Which reminds me, the vertical bounds are up to you because I don't know what `*j` is. However I suppose the formulas would look similar to these.

---
Tags: rust
---


# Question
Title: How to add antialiasing to my circle shader?
I made a circle shader by following this tutorial: https://www.youtube.com/watch?v=Ww1GbfnBH\_Q. It is simple flat circle shader. The problem is that there are visible jigged lines on the circle edges. Here is how it looks:

And here is shader code:

```
  Shader "Custom/CircleShader"
{
   Properties {
        _ForegroundColor("Foreground Color", Color) = (1,1,1,1)
        _BackgroundColor("Background Color", Color) = (0,0,0,1)
        _ForegroundMask ("Foreground Mask", 2D) = "white" {}
        _ForegroundCutoff ("Foreground Cutoff", Range(0,1)) = 0.5
        _BackgroundCutoff("Background Cutoff", Range(0,1)) = 0.5
    }
    SubShader {
        Tags { "RenderType"="Transparent" }
        Blend SrcAlpha OneMinusSrcAlpha
        LOD 200

        CGPROGRAM
        // Physically based Standard lighting model, and enable shadows on all light types
        #pragma surface surf Standard fullforwardshadows keepalpha

        // Use shader model 3.0 target, to get nicer looking lighting
        #pragma target 3.0

        sampler2D _ForegroundMask;

        struct Input {
            float2 uv_ForegroundMask;
        };

        fixed4 _ForegroundColor;
        fixed4 _BackgroundColor;
        half _ForegroundCutoff;
        half _BackgroundCutoff;

        void surf (Input IN, inout SurfaceOutputStandard o) {

            fixed x = (-0.5 + IN.uv_ForegroundMask.x) * 2;
            fixed y = (-0.5 + IN.uv_ForegroundMask.y) * 2;

            // Albedo comes from a texture tinted by color
            fixed radius = 1 - sqrt(x*x + y*y);
            clip(radius - _BackgroundCutoff);
            o.Albedo = _BackgroundColor;
            if (radius > _ForegroundCutoff) {
                o.Albedo = _ForegroundColor;
            }
            o.Alpha = 1;
        }
        ENDCG
    }
    FallBack "Diffuse"
}

```

How would I add antialiasing to the shader to remove jigged lines on edges of the circle?

# Answer
> 2 votes
Right now your code outputs either foreground colour, or background colour, or nothing — no in-between values. That's what creates the harsh stair-step between the three levels.

To disguise the pixel grid rather than call attention to it, we need to output some pixels with intermediate colours — partway between foreground and background, or between background and transparent.

If you mostly see this graphic straight-on/at the same size, a simple lerp will do OK:

```
Shader "Custom/CircleShader"
{
   Properties {
        _ForegroundColor("Foreground Color", Color) = (1,1,1,1)
        _BackgroundColor("Background Color", Color) = (0,0,0,1)
        _ForegroundMask ("Foreground Mask", 2D) = "white" {}
        _ForegroundCutoff ("Foreground Cutoff", Range(0,1)) = 0.5
        _BackgroundCutoff("Background Cutoff", Range(0,1)) = 0.5
        _Sharpness("Sharpness", float) = 20.0
    }
    SubShader {
        Tags { "RenderType"="Transparent" }
        Blend SrcAlpha OneMinusSrcAlpha
        LOD 200

        CGPROGRAM
        // Physically based Standard lighting model, and enable shadows on all light types
        #pragma surface surf Standard fullforwardshadows keepalpha alpha:fade

        // Use shader model 3.0 target, to get nicer looking lighting
        #pragma target 3.0

        sampler2D _ForegroundMask;

        struct Input {
            float2 uv_ForegroundMask;
        };

        fixed4 _ForegroundColor;
        fixed4 _BackgroundColor;
        half _ForegroundCutoff;
        half _BackgroundCutoff;
        half _Sharpness;

        void surf (Input IN, inout SurfaceOutputStandard o) {

            fixed x = (-0.5 + IN.uv_ForegroundMask.x) * 2;
            fixed y = (-0.5 + IN.uv_ForegroundMask.y) * 2;

            // If you call a variable "radius", make it
            // actually the radius, not its complement!
            fixed radius = sqrt(x*x + y*y);

            float inside = _BackgroundCutoff - radius;
            clip(inside);
            // Feather the outer edge a little.
            o.Alpha = min(inside * _Sharpness, 1);

            // Feather the transition a little.
            float fore = saturate(_Sharpness * (_ForegroundCutoff - radius));
            o.Albedo = lerp(_BackgroundColor, _ForegroundColor, fore);
        }
        ENDCG
    }
    FallBack "Diffuse"
}

```

Play with the "Sharpness" parameter to control how wide the blending region is.

You'll find though, if you need to show this graphic at different sizes/distances, or tilted, you want different degrees of sharpness at each: the bigger the object on screen, the more pixels it occupies, so the transition region can be smaller without disappearing between the pixel grid cells.

To dynamically adapt to the display scale, you can use screenspace derivatives to compute how many pixels you are from the transition threshold, and blend only the pixels immediately adjacent to the threshold line.

That technique is shown in past answers, so I won't repeat it here just now:

---
Tags: unity, shaders, hlsl
---


# Question
Title: Handling acks during 1+ second packet loss with Glenn Fiedler's Reliable UDP Solution
I've read through Glenn Fiedler's awesome guide on Reliability over UDP and I'm currently working on my own implementation for fun and learning purposes.

One pretty cool piece of Glenn's guide is that it implements redundant acks as a bitset: when a packet is acking a message, it includes a bitset indicating which of the previous 32 sequence numbers were also acked by flipping that particular bit to 1.

However, one issue I'm running into is what to do when packets are dropped at the *beginning* of the bitset, e.g. the 32nd bit is not acked.

Let's say my message header is the following:

```
Ack: 42
Bitset: ack everything from 10 to 41, but _not_ SequenceNumber 9!
// or even Bitset: nothing previously acked

```

In this scenario, I cannot begin processing SequenceNumber 43 and beyond from the remote client otherwise I would have data loss for acking SequenceNumber 9.

Do I just stall and not process any further SequenceNumbers until I receive SequenceNumber 9? This should ideally be rare, but I worry that stalling everything may not be the correct solution and there's another possible solution.

# Answer
> 0 votes
At some point, you would have to process the next packet, so as DMGregory said, you might want to interpolate the value based on the previous state and the next information available. You should not stall because you might never receive information at the end.

---
Tags: networking, client-server, udp, lag, packet
---


# Question
Title: Deffered shader with alpha : orient target writing
I have this bit of shader code to orient SV\_target writing depending on alpha value for SV\_Target0 : color0 = (input.a == 1)? float4(some value) : float4(0,0,0,0); for SV\_Target1 : color1 = (input.a \< 1)? float4(some other value) : float4(0,0,0,0); works fine to orient drawing on the targets depending on input.alpha value

As in fact I don't need to write float4(0,0,0,0) I've tried this: if ( input.a == 1 ) color0 = float4(some value); else color1 = float4(some other value); but here the shader write all objects on the two targets. Any idea on how to better write this code or solve this problem thanks in advance PhilB

# Answer
Thanks for your interest in this question. I've seen somewhere that deffered rendering is not fully suitable for alpha rendering. So I'm trying to separate opaque and transparent objects while using deffered shaders anyway. The two targets(opaque left and alpha right (3rd is depth)) are then blended for the final result (see picture). The blending is not perfect but you have the idea. So target0 need to receive only opaque and target1 alpha. but in fact target0 draw alpha with color 0,0,0, and the same for opaque in target1. As alphablending is enable in alpha pass nothing appear in target0. But for target1 the opaque objects aer drawn (I've checked by using white color instead of black). So with black colors you see only what you need to see. I really want to try avoiding drawing "black" objects to save some fps. I'was thinking of clip but I'm not sure you can put it in a if then statement and I'm not sure you can use it for a given target in multitarget purposes. PhilB
> 0 votes

---
Tags: shaders, directx11, alpha
---


# Question
Title: Why am I getting Null Reference Exception inspite of checking if the Object is not null to execute something
Hi I am just trying to convert a simple flappy bird game into multiplayer game.

So In the multiplayer game using Photon , I want the bird to collide with the ground or pipe but not with the enemy bird .i.e., ignore the enemy's bird collision. I somehow worked it out,code below.

So I have tagged the bird under a name called "BirdClass" , and in the start I have the following code to ignore the coillision for the first time:

```
void Start()
    {
       PV = GetComponent<PhotonView>();
        playerBird = GameObject.FindGameObjectWithTag("BirdClass");
        if (playerBird != null)
            Physics2D.IgnoreCollision(playerBird.GetComponent<Collider2D>(), GetComponent<Collider2D>());

    }

```

Over here I get the following error:

ArgumentNullException: Value cannot be null. Parameter name: collider1 UnityEngine.Physics2D.IgnoreCollision (UnityEngine.Collider2D collider1, UnityEngine.Collider2D collider2) (at \<4e5075cf57c3416eb788a8bd41817a84\>:0) BirdPigeon.Start () (at Assets/Scripts/BirdPigeon.cs:45)

and the onCollider2d function looks like this:

```
private void OnCollisionEnter2D(Collision2D collision)
    {
        playerBird = GameObject.FindGameObjectWithTag("BirdClass");
        if (isMultiPlayerGame && playerBird != null && PV.IsMine)
        {
           if (collision.gameObject.tag == playerBird.gameObject.tag)
            {
                Physics2D.IgnoreCollision(collision.gameObject.GetComponent<Collider2D>(), GetComponent<Collider2D>());
            }
            else
            {
                BirdCollided?.Invoke(true);
            }
        }
        if (!isMultiPlayerGame)
        {
            BirdCollided?.Invoke(true);
            rigidBodyOfBird.velocity = Vector2.zero;
        }
    }

```

and here I get the error like:

```
"NullReferenceException: Object reference not set to an instance of an object
BirdPigeon.OnCollisionEnter2D (UnityEngine.Collision2D collision) (at Assets/Scripts/BirdPigeon.cs:81)"

```

I can't understand, though I am checking whether it is null or not ,why I am still getting these errors?

# Answer
> 1 votes
It appears like your "playerBird" game object has no component of type `Collider2D`. Make sure that one of the 2D colliders is attached. When you want to find it via `GetComponent`, then it must be attached to the object directly. When the collider is attached to a sub-object of the "playerBird", use `GetComponentInChildren` instead.

Also keep in mind that there are also colliders which do not have the suffix "2D". These are 3D colliders used by the 3D physics engine. 2D and 3D colliders are completely separate systems and do not interact with each other.

# Answer
> 0 votes
While this is not fixing your nullpointers, it will have the same result in the end. You are trying to solve a collision exception manually. Good for you that Unity ships this with a simple collision matrix. If you are using 2D physics, you need to use the 2D version.

https://docs.unity3d.com/Manual/LayerBasedCollision.html

# Answer
> 0 votes
Your `playerBird` is not null, but apparently does not have `Collider2D` attached, hence this call:

`playerBird.GetComponent<Collider2D>()` returns null

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


title: Entity iteration order in ECS system

text:
# Question
Title: Entity iteration order in ECS system
While learning ECS architecture, I found out that some ECS libraries gives me unsorted entity ids when iterating over filtered entities in system. (Seems like deletion algorithm in sparse set is the reason...)

Won't it be a problem if you need deterministic results(Networked game, replay feature, etc...) for your game?

For example, assume there's entity 1 and 2. They have a `CollisionBox` component.

When they hit an entity with a `GoalBoundary` component, the one who hits it first wins.

If somehow entity 1 and 2 arrived Goal at the exact same frame, then iteration order will be critical to the game's result.

Maybe my example is not perfect, but hope you get the point - Sometimes iteration order is so critical in game logic and I am confused about understanding how these kinds of issues must be solved in ECS architecture.

Any help will be appreciated, thanks!

# Answer
> 0 votes
Firstly - check your ECS dictionary implementations - are they really producing non-deterministic results and why, what is the source of randomness there?

I'm suspecting this could be isolated and resolved. If not - you might need to re-introduce the order yourself. Iterating over stably sorted list of entities is so much simpler than any competing conflict resolutions.

However there's a second side to it - do you really need the identical results? In some cases (RTS lockstep) this is vital, but on others (e.g. FPS) you can just record the resulting world state and replay from that (without re-simulating it).

---
Tags: entity-component-system
---


# Question
Title: Unity3D - How would you add a ConstantForce gradually rather than instantly setting?
I'm trying to change the ConstantForce of a gameobject upon collision with a tagged object:

```
public class MyScript()
{
    public ConstantForce fakeGravity;

    private void Awake()
    {
        fakeGravity = GetComponent<ConstantForce>();
    }

    private void OnTriggerEnter(Collider other)
    {
        if (other.CompareTag("IncreaseGravity"))
        {
            fakeGravity.force = new Vector3(0.0f, 5.0f, 0.0f);
        }
    }
}

```

This causes a sudden change in the ConstantForce, but what I would really like is to apply this force gradually from 0 to 5, so that it feels more natural. How could this be achieved?

# Answer
Instead of using the standard Unity ConstantForce component, you could create your own component which is not so constant but increases its force over time.

Untested code example:

```
public class IncreasingForce : MonoBehaviour {

    public Vector3 finalForce;
    public float timeUntilFinalForce;
    private float timeExisting;
    private Rigidbody myRigidbody;

    void Start() {
        myRigidbody = GetComponent<Rigidbody>();
    }

    void Update() {
        timeExisting += Time.deltaTime;
        float timeFactor = timeExisting / timeUntilFinalForce;
        Vector3 currentForce = Vector3.Lerp(Vector3.zero, finalForce, timeFactor);
        myRigidbody.AddForce(currentForce);
    }

}

```

This component increases the force linearly between 0 and the final force as soon as it is added to the game object. If you want more control over the way the force changes over time, then you could control the magnitude of the force with an `AnimationCurve`.
> 1 votes

---
Tags: unity
---


# Question
Title: How to check multiple rings of tiles around a center tile on a 2D grid
In my game project I create the terrain programmatically by creating tiles on a 2D grid as the player moves around the game map. I have it working where I select the current tile and check all 8 positions around the tile, then I create a new tile at those positions unless one already exists there. This works in a "hard-coded" way, where I can take any given grid position like `(x: 0, y: 0)` and then I check all the positions around it in this fashion:

```
(x: thisPosition.x - 1, y: thisPosition.y + 1)  // POSITION UP-LEFT
(x: thisPosition.x,     y: thisPosition.y + 1)  // POSITION UP
(x: thisPosition.x + 1, y: thisPosition.y + 1)  // POSITION UP-RIGHT
(x: thisPosition.x - 1, y: thisPosition.y)      // POSITION LEFT
(x: thisPosition.x + 1, y: thisPosition.y)      // POSITION RIGHT
(x: thisPosition.x - 1, y: thisPosition.y - 1)  // POSITION DOWN-LEFT
(x: thisPosition.x,     y: thisPosition.y - 1)  // POSITION DOWN
(x: thisPosition.x + 1, y: thisPosition.y - 1)  // POSITION DOWN-RIGHT

```

This works, but I can only check one "ring" around the selected tile at a time (as shown below in the image on the left). I want to replace this function with a new, improved version that works in a more programmatic way, something using nested loops. I want to be able to give the function a number, and then it will check that many "rings" around the selected tile and add terrain tiles to those positions. For example, if I ask it to check 3 rings, it will check all of the tiles shown in the image on the right:

I have some ideas but I'm not sure yet how to put them into code. I'm sure that someone online has solved this exact problem before, only I can't find it. I thought I'd put this question out here and see if this rings any bells for someone.

If anyone has any code suggestions, it would be helpful if you could write pseudocode, since the only language I know right now is Swift. I'd like to learn C and C++ someday, but I'm just a greenhorn hobbyist and starting with Swift was easiest for me.

# Answer
When the order does not matter, then you can simply check a whole square from top-left to bottom-down, and skip the position of the origin. I never programmed in Swift before, so here is how I believe how that would look in Swift based on a couple examples I could find:

```
func checkAround(centerX: Int, centerY: Int, radius: Int) {
     for var x = centerX - radius; x <= centerX + radius; ++x {
         for var y = centerY - radius; y <= centerY + radius; ++y {
              if x != centerX || y != centerY {
                  check(x: x, y: y);
              }
         }
     }
}

```
> 1 votes

# Answer
Theraot's comment got me on the right track. See my function below. I also included a `GridPoint` structure to represent points on the 2D tile grid.

In my game, the starting position will already have a tile so it doesn't need to be included in the array of points that I will use to generate new tiles. But if you want to include the starting position in the array, just remove this line: `if i == 0 && j == 0 { continue }`.

I did this in Swift; sorry to the C/C++/C# folks. I will tackle those languages someday...

```
// Conforming to CustomStringConvertible for nicer printing.
struct GridPoint: CustomStringConvertible {
    var x = 0
    var y = 0

    var description: String {
        return "\(x),\(y)"
    }
}

func selectSurroundingPoints(forPosition p: GridPoint, howManyRings r: Int) -> [GridPoint] {
    var arrayOfPoints = [GridPoint]()

    for i in 0...r * 2 {
        for j in 0...r * 2 {
            if i == 0 && j == 0 { continue }

            var point = GridPoint()

            if i <= r {
                point.x = p.x + i
            } else {
                point.x = p.x + (r - i)
            }

            if j <= r {
                point.y = p.y + j
            } else {
                point.y = p.y + (r - j)
            }

            arrayOfPoints.append(point)
        }
    }

    return arrayOfPoints
}

// Usage
let checkPosition = GridPoint(x: 0, y: 0)
let surroundingPoints = selectSurroundingPoints(forPosition: checkPosition, howManyRings: 1)

for point in surroundingPoints {
    print(point)
}

```

**UPDATE:**

Philipp's answer is more concise than mine. I like his better so I wrote it here in Swift:

```
func checkAround(centerX: Int, centerY: Int, radius: Int) {
    for x in (centerX - radius)...(centerX + radius) {
        for y in (centerY - radius)...(centerY + radius) {
            if x != centerX || y != centerY {
                print("\(x), \(y)")
            }
        }
    }
}

// Usage
checkAround(centerX: 0, centerY: 0, radius: 1)

/*
 Prints:
 -1, -1
 -1, 0
 -1, 1
 0, -1
 0, 1
 1, -1
 1, 0
 1, 1
 */

```
> 0 votes

---
Tags: algorithm, procedural-generation, tilemap, grid, swift
---


title: Find vertical angle between two objects

text:
# Question
Title: Find vertical angle between two objects
I'm working on a project that involves a battleship with multiple turrets on it. The turrets have limited movement on both horizontal and vertical axis. When checking if they can target the player I need to check if the player is within both fields of view.

I'm using the acos of the dot product to get the horizontal angle. For the vertical angle, I'm taking the X and Z components and ignoring the Y, creating two new vectors and repeating the process, but it seems a little buggy and not correct. I tried searching online but there is very little information for getting both angles.

The project is in Unreal and Z is the up axis.

WeaponTransform is the FTransform of the AActor.

TForward is the initial forward direction WeaponTransform-\>GetRotation() * FVector::ForwardVector;

actorLocation is the location of the player using actor.GetActorLocation();

```
float hAngle = CalculateAngleBetween(tForward, actorLocation, WeaponTransform->GetLocation());
    inAngle = CheckAngle(hAngle, HMinAngle, HMaxAngle);

// This seems incorrect
FVector weaponForwardXZ = FVector(tForward.X, tForward.Z, 0.f);
    FVector actorLocationXZ = FVector(actorLocation.X, actorLocation.Z, 0.f);
    FVector weaponPositionXZ = FVector(WeaponTransform->GetLocation().X, WeaponTransform->GetLocation().Z, 0.f);
    float vAngle = CalculateAngleBetween(weaponForwardXZ, actorLocationXZ, weaponPositionXZ);
    inAngle = CheckAngle(vAngle, VMinAngle, VMaxAngle);

CalculateAngleBetween(FVector turretForward, FVector targetPosition,
FVector turretPosition)
{
auto dir = targetPosition - turretPosition;
dir.Normalize();
auto safeForward = turretForward.GetSafeNormal();
auto cross = FVector::CrossProduct(dir, turretForward);
cross.Normalize();

float axisSign = FVector::DotProduct(cross, FVector::UpVector) >= 0.f ? 1.f : -1.f;

auto dot = FVector::DotProduct(dir, safeForward);
auto rad = FMath::Acos(dot) * axisSign;
return FMath::RadiansToDegrees(rad);
}

```

# Answer
Assuming `WeaponTransform` is an `FTransform` representing the transformation of the turret base/pivot (against which we should be measuring any angular deviation), then I'd propose that we use this to move the calculation into the local coordinate system of this base to make things simpler.

```
// Get the offset from our position to the target, relative to our base.
FVector local = WeaponTransform->InverseTransformPositionNoScale(actorLocation);

// Discard the distance so we keep only the direction (a point on the unit sphere)
local.Normalize();

// The Z coordinate of that direction is the sine of the elevation angle.
float elevatonAngle = FMath::RadiansToDegrees(FMath::Asin(local.z));

// The XY coordinates give us a horizontal bearing relative to our local X+.
float relativeBearing = FMath::RadiansToDegrees(FMath::Atan2(local.y, local.x));

```

This is a standard spherical coordinates conversion that you can find covered in many previous answers.
> 0 votes

---
Tags: mathematics, unreal-4, aiming
---


title: NVidia Physx Get Orientation problem

text:
# Question
Title: NVidia Physx Get Orientation problem
For a game that I am developing I moved from Bullet physics to NVidia Physx. The problem that I have is the following. I used to have a translation from bullet's rigid body orientation quaternion to Front , Right and Up vector for each object on the screen. This was working fine but after I moved to Physx I noticed that there is only one quaternion in the transform of the object (probably representing rotation) and no orientation quaternion. Here is the code that I was using in Bullet to get the 3 vectors translated to Physx :

```
physx::PxQuat ori = mBody->getGlobalPose().q;

auto Orientation = glm::quat(ori.x, ori.y, ori.z, ori.w);

glm::quat qF = Orientation * glm::quat(0, 0, 0, 1) * glm::conjugate(Orientation);
glm::quat qUp = Orientation * glm::quat(0, 0, 1, 0) * glm::conjugate(Orientation);
front = { qF.x, qF.y, qF.z };
up = { qUp.x, qUp.y, qUp.z };
right = glm::normalize(glm::cross(front, up));

```

This apparently doesn't work for Physx. Is there another way to retrieve the 3 vectors from the rigid body ?

# Answer
Based on this line:

```
glm::quat qF = Orientation * glm::quat(0, 0, 0, 1) * glm::conjugate(Orientation);

```

It looks like glm::quat() is taking arguments in the order `w, x, y, z` (ie. real component first, then the three imaginary components), so that `glm::quat(0, 0, 0, 1)` represents a pure imaginary quaternion (a 3D vector) pointing along the z+ axis.

But this line puts `w` last instead of first:

```
auto Orientation = glm::quat(ori.x, ori.y, ori.z, ori.w);

```

This should probably be like this instead, to match the convention used elsewhere in your code:

```
auto Orientation = glm::quat(ori.w, ori.x, ori.y, ori.z);

```
> 0 votes

---
Tags: c++, glm, physx
---


# Question
Title: How can I make the overlapping object's outlines merge and not display on top of other objects that have the outline shader?
This is what I am trying to achieve. I was following https://www.youtube.com/watch?v=SlTkBe4YNbo but the outlines show on top of other if the objects overlap. I tried looking through various outline shaders but couldn't find much. I found that it has something to do with Z-Depth but I am not sure how.

My reason for doing this was to replicate the Unity Editor's object selection in the project. I somehow got the gizmo partially working(using a 2nd camera) and am now stuck on object highlighting on selection.

# Answer
> 1 votes
i don't know much about HLSL but i managed to hodge-podge some different scripts to make something that works.

*The only thing is*\- whichever sprites you apply this to need to already have a white outline around them. I uploaded all of my UI sprites with a black fill and a white outline, and then I was able to customize both colors via the shader.

here's a little example:

and here's the code!

```
Shader "2D Overlap Outline"
{
    Properties
    {
        _ColorMain("Main Color", Color) = (0.5, 0.5, 0.5, 1.0)
        _ColorBorder("Border", Color) = (1.0, 1.0, 1.0, 1.0)
        _MainTex("Texture to blend", 2D) = "" {}
    _StencilComp("Stencil Comparison", Float) = 8
        _Stencil("Stencil ID", Float) = 0
        _StencilOp("Stencil Operation", Float) = 0
        _StencilWriteMask("Stencil Write Mask", Float) = 255
        _StencilReadMask("Stencil Read Mask", Float) = 255

        _ColorMask("Color Mask", Float) = 15

        [Toggle(UNITY_UI_ALPHACLIP)] _UseUIAlphaClip("Use Alpha Clip", Float) = 0
    }

        SubShader
    {
        Tags
            {
                "Queue" = "Transparent"
                "IgnoreProjector" = "True"
                "RenderType" = "Transparent"
                "PreviewType" = "Plane"
                "CanUseSpriteAtlas" = "True"
            }

        Pass
        {
        Cull Off
        Lighting Off
        ZWrite On
        ZTest Always
        Offset -1, -1
        Fog { Mode Off }
        Blend SrcAlpha OneMinusSrcAlpha
        ColorMask[_ColorMask]
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag
            #include "UnityCG.cginc"

            uniform sampler2D _MainTex;
            half4 _ColorMain;
            half4 _ColorBorder;

            struct v2f
            {
                float4 pos : SV_POSITION;
                float2 uv  : TEXCOORD0;
            };

            v2f vert(appdata_base v)
            {
                v2f o;
                o.pos = UnityObjectToClipPos(v.vertex);
                o.uv = v.texcoord.xy;
                return o;
            }

            half4 frag(v2f i) : COLOR
            {

                half4 color = tex2D(_MainTex, i.uv);

                half4 delta = _ColorBorder - _ColorMain;

                half4 main = _ColorMain + (color * delta);

                main.a = color.a;

                return main;
            }

            ENDCG
        }

        Pass
        {
            Offset -1, -1

            Blend SrcAlpha OneMinusSrcAlpha

                AlphaTest Greater 0.5

                CGPROGRAM
                #pragma vertex vert
                #pragma fragment frag
                #include "UnityCG.cginc"

                uniform sampler2D _MainTex;
                half4 _ColorMain;
                half4 _ColorBorder;

                struct v2f
                {
                    float4 pos : SV_POSITION;
                    float2 uv  : TEXCOORD0;
                };

                v2f vert(appdata_base v)
                {
                    v2f o;
                    o.pos = UnityObjectToClipPos(v.vertex);
                    o.uv = v.texcoord.xy;
                    return o;
                }

                half4 frag(v2f i) : COLOR
                {

                    half4 color = tex2D(_MainTex, i.uv);

                    half4 main = _ColorMain;

                    main.a = min(color.a, 1 - color.r);

                    return main;
                }

                ENDCG
            }
    }
}

```

hope it helps!

links to where i found the different scripts:

(last response) https://forum.unity.com/threads/merge-sprites-by-color.172037/

https://blog.hamaluik.ca/posts/a-unity-4.6-ui-shader-to-ignore-depth-testing/

---
Tags: unity, shaders, outline
---


# Question
Title: Why the transform is not moving to the target form it's current position?
When the transform is start moving it's like "jumping" to a position near the position it is now and start moving from that position and not the position the transform is currently at.

It was working before but i can't figure out why it's not now. The transform does moving to the target but ot starting moving from it's current position but from a nearby position.

Things to clear :

* The transform start as child of another object.
* The target is the destinationTransform variable.
* The transform is child of fingers of hand of my character and the character have animator so when the character is in idle animation his body is moving including the hands.

This screenshot image show the transform as child before running the game. This is the transform originPosition in the Start() but then when running the game the idle animation make the hand moving so the transform originPosition has changed and keep changing because the idle animation so the originPosition in the Start() is anymore the real originPosition.

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

public class MoveToTarget : MonoBehaviour
{
    public enum TransitionState
    {
        None,
        MovingTowards,
        Transferring
    }

    public Transform destinationTransform;
    public bool isChild = false;
    public AnimationCurve curve = AnimationCurve.EaseInOut(0.0f, 0.0f, 1.0f, 1.0f);
    public float duration = 10.0f;
    public bool go = false;

    private float t;
    private Transform originTransform;
    private float timer;
    private TransitionState state = TransitionState.MovingTowards;
    private Vector3 originPosition;
    private SphereCollider col;
    private bool enableCollider = true;

    void Start()
    {
        t = 0.0f;

        curve.postWrapMode = WrapMode.Once;
        originPosition = transform.position;
        col = GetComponent<SphereCollider>();
    }

    void Update()
    {
        if (go)
        {
            if (col != null && enableCollider)
            {
                Destroy(col);
                Destroy(transform.GetComponent<Rigidbody>());
                enableCollider = false;
            }

            switch (state)
            {
                case TransitionState.MovingTowards:
                    var v = destinationTransform.position - transform.position;
                    if (v.magnitude < 0.001f)
                    {
                        state = TransitionState.Transferring;
                        originTransform = destinationTransform;
                        timer = 0;
                        return;
                    }

                    t += Time.deltaTime;
                    float s = t / duration;

                    transform.position = Vector3.Lerp(originPosition,
                        destinationTransform.position, curve.Evaluate(s));

                    break;

                case TransitionState.Transferring:
                    timer += Time.deltaTime;
                    this.transform.position = Vector3.Lerp(originTransform.position, destinationTransform.position, timer);

                    if (timer >= 1.0f)
                    {
                        this.transform.parent = destinationTransform;
                        transform.localPosition = new Vector3(0, 0, 0);
                        isChild = true;

                        go = false;

                        state = TransitionState.None;
                        this.enabled = false;
                        return;
                    }
                    break;

                default:
                    this.enabled = false;
                    return;
            }
        }
    }
}

```

# Answer
> 0 votes
I found a solution.

I added a new flag boolean variable called `updateOriginPosition`. Then, I update the `originPosition` variable in the `Update()` function once instead of in the `Start()` function.

```
void Update()
{
    if (go)
    {
        if (updateOriginPosition == true)
        {
            originPosition = transform.position;
            updateOriginPosition = false;
        }
        // ...
    }
    // ...
}

```

And the script after the changes.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using Cinemachine;

public class MoveToTarget : MonoBehaviour
{
    public enum TransitionState
    {
        None,
        MovingTowards,
        Transferring
    }

    public Transform destinationTransform;
    public bool isChild = false;
    public AnimationCurve curve = AnimationCurve.EaseInOut(0.0f, 0.0f, 1.0f, 1.0f);
    public float duration = 10.0f;
    public bool go = false;

    private float t;
    private Transform originTransform;
    private float timer;
    private TransitionState state = TransitionState.MovingTowards;
    private Vector3 originPosition;
    private SphereCollider col;
    private bool enableCollider = true;
    private bool updateOriginPosition = true;

    void Start()
    {
        t = 0.0f;

        curve.postWrapMode = WrapMode.Once;
        col = GetComponent<SphereCollider>();
    }

    void Update()
    {
        if (go)
        {
            if (updateOriginPosition == true)
            {
                originPosition = transform.position;
                updateOriginPosition = false;
            }

            if (col != null && enableCollider)
            {
                //col.enabled = false;
                //transform.GetComponent<Rigidbody>().isKinematic = true;

                Destroy(col);
                Destroy(transform.GetComponent<Rigidbody>());
                //transform.GetComponent<InteractableItem>().enabledInteraction = false;

                enableCollider = false;
            }

            switch (state)
            {
                case TransitionState.MovingTowards:
                    var v = destinationTransform.position - transform.position;
                    if (v.magnitude < 0.001f)
                    {
                        state = TransitionState.Transferring;
                        originTransform = destinationTransform;
                        timer = 0;
                        return;
                    }

                    t += Time.deltaTime;
                    float s = t / duration;

                    transform.position = Vector3.Lerp(originPosition,
                        destinationTransform.position, curve.Evaluate(s));

                    break;

                case TransitionState.Transferring:
                    timer += Time.deltaTime;
                    this.transform.position = Vector3.Lerp(originTransform.position, destinationTransform.position, timer);

                    if (timer >= 1.0f)
                    {
                        this.transform.parent = destinationTransform;
                        transform.localPosition = new Vector3(0, 0, 0);
                        isChild = true;

                        go = false;

                        state = TransitionState.None;
                        this.enabled = false;
                        return;
                    }
                    break;

                default:
                    this.enabled = false;
                    return;
            }
        }
    }
}
```

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


# Question
Title: Script not working on object in unity 2D
I was following a tutorial where the gameobject was to spawn randomly within the screen. The code I used is as follows.

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

public class NewBehaviourScript : MonoBehaviour
{
    // Start is called before the first frame update
    // jump location support

    //screen dimensions
    float minX = -3.77f;
    float maxX = 3.73f;
    float minY = -2.13f;
    float maxY = 2.16f;

    //timer support
    const float TotalJumpDelaySeconds = 1;
    float elapsedJumpTimeSeconds = 0;

    // Update is called once per frame
    void Update()
    {
        //update timer and check if its done
        elapsedJumpTimeSeconds += Time.deltaTime;

        if(elapsedJumpTimeSeconds >= TotalJumpDelaySeconds)
        {
            elapsedJumpTimeSeconds = 0;
            Vector3 position = transform.position;
            position.x = Random.Range(minX, maxX);
            position.y = Random.Range(minY, maxY);

        }

    }
}

```

But on running the game it stays in the same location

Here is the code in text

# Answer
> 0 votes
You have to assign your random position to your `transform.position` i.e.

```
        if(elapsedJumpTimeSeconds >= TotalJumpDelaySeconds)
        {
            elapsedJumpTimeSeconds = 0;
            Vector3 position = transform.position;
            position.x = Random.Range(minX, maxX);
            position.y = Random.Range(minY, maxY);

            transform.position = position;
        }

```

I think your code can also be written as

```
        if(elapsedJumpTimeSeconds >= TotalJumpDelaySeconds)
        {
            elapsedJumpTimeSeconds = 0;
            transform.position = new Vector3(Random.Range(minX, maxX),Random.Range(minY, maxY), transform.position.z);
        }

```

---
Tags: unity, c#, 2d, timer
---


# Question
Title: NVidia Physx get yaw pitch roll from rigid body orientation
I am using NVidia PhysX in the game that I'm developing and I stumbled upon a math problem. I need to retrieve Yaw, Pitch and Roll from the orientation quaternion stored in the rigid body of some object.

The game is developed with OpenGL, using a right hand coordinate system (x right, y up, z back).

I tried many examples online but none of them gave a correct result. One of them is from Wikipedia, which I list below :

```
#define _USE_MATH_DEFINES
#include <cmath>

struct Quaternion {
    double w, x, y, z;
};

struct EulerAngles {
    double roll, pitch, yaw;
};

EulerAngles ToEulerAngles(Quaternion q) {
    EulerAngles angles;

    // roll (x-axis rotation)
    double sinr_cosp = 2 * (q.w * q.x + q.y * q.z);
    double cosr_cosp = 1 - 2 * (q.x * q.x + q.y * q.y);
    angles.roll = std::atan2(sinr_cosp, cosr_cosp);

    // pitch (y-axis rotation)
    double sinp = 2 * (q.w * q.y - q.z * q.x);
    if (std::abs(sinp) >= 1)
         angles.pitch = std::copysign(M_PI / 2, sinp); // use 90 degrees if out of range
    else
         angles.pitch = std::asin(sinp);

    // yaw (z-axis rotation)
    double siny_cosp = 2 * (q.w * q.z + q.x * q.y);
    double cosy_cosp = 1 - 2 * (q.y * q.y + q.z * q.z);
    angles.yaw = std::atan2(siny_cosp, cosy_cosp);

    return angles;
}

```

As my quaternion skills are not that good, I was wondering if someone can provide some sample as to what has to be done to get the yaw, pitch and roll from the orientation quaternion?

# Answer
> 1 votes
The solution was found here

And here is the code :

```
///////////////////////////////
// Quaternion to Euler
///////////////////////////////
enum class RotSeq { zyx, zyz, zxy, zxz, yxz, yxy, yzx, yzy, xyz, xyx, xzy, xzx };

void twoaxisrot(float r11, float r12, float r21, float r31, float r32, float res[]) {
    res[0] = atan2(r11, r12);
    res[1] = acos(r21);
    res[2] = atan2(r31, r32);
}

void threeaxisrot(float r11, float r12, float r21, float r31, float r32, float res[]) {
    res[0] = atan2(r31, r32);
    res[1] = asin(r21);
    res[2] = atan2(r11, r12);
}

void quaternion2Euler(const physx::PxQuat& q, float res[], RotSeq rotSeq)
{
    switch (rotSeq) {
    case RotSeq::zyx:
        threeaxisrot(2 * (q.x * q.y + q.w * q.z),
            q.w * q.w + q.x * q.x - q.y * q.y - q.z * q.z,
            -2 * (q.x * q.z - q.w * q.y),
            2 * (q.y * q.z + q.w * q.x),
            q.w * q.w - q.x * q.x - q.y * q.y + q.z * q.z,
            res);
        break;

    case RotSeq::zyz:
        twoaxisrot(2 * (q.y * q.z - q.w * q.x),
            2 * (q.x * q.z + q.w * q.y),
            q.w * q.w - q.x * q.x - q.y * q.y + q.z * q.z,
            2 * (q.y * q.z + q.w * q.x),
            -2 * (q.x * q.z - q.w * q.y),
            res);
        break;

    case RotSeq::zxy:
        threeaxisrot(-2 * (q.x * q.y - q.w * q.z),
            q.w * q.w - q.x * q.x + q.y * q.y - q.z * q.z,
            2 * (q.y * q.z + q.w * q.x),
            -2 * (q.x * q.z - q.w * q.y),
            q.w * q.w - q.x * q.x - q.y * q.y + q.z * q.z,
            res);
        break;

    case RotSeq::zxz:
        twoaxisrot(2 * (q.x * q.z + q.w * q.y),
            -2 * (q.y * q.z - q.w * q.x),
            q.w * q.w - q.x * q.x - q.y * q.y + q.z * q.z,
            2 * (q.x * q.z - q.w * q.y),
            2 * (q.y * q.z + q.w * q.x),
            res);
        break;

    case RotSeq::yxz:
        threeaxisrot(2 * (q.x * q.z + q.w * q.y),
            q.w * q.w - q.x * q.x - q.y * q.y + q.z * q.z,
            -2 * (q.y * q.z - q.w * q.x),
            2 * (q.x * q.y + q.w * q.z),
            q.w * q.w - q.x * q.x + q.y * q.y - q.z * q.z,
            res);
        break;

    case RotSeq::yxy:
        twoaxisrot(2 * (q.x * q.y - q.w * q.z),
            2 * (q.y * q.z + q.w * q.x),
            q.w * q.w - q.x * q.x + q.y * q.y - q.z * q.z,
            2 * (q.x * q.y + q.w * q.z),
            -2 * (q.y * q.z - q.w * q.x),
            res);
        break;

    case RotSeq::yzx:
        threeaxisrot(-2 * (q.x * q.z - q.w * q.y),
            q.w * q.w + q.x * q.x - q.y * q.y - q.z * q.z,
            2 * (q.x * q.y + q.w * q.z),
            -2 * (q.y * q.z - q.w * q.x),
            q.w * q.w - q.x * q.x + q.y * q.y - q.z * q.z,
            res);
        break;

    case RotSeq::yzy:
        twoaxisrot(2 * (q.y * q.z + q.w * q.x),
            -2 * (q.x * q.y - q.w * q.z),
            q.w * q.w - q.x * q.x + q.y * q.y - q.z * q.z,
            2 * (q.y * q.z - q.w * q.x),
            2 * (q.x * q.y + q.w * q.z),
            res);
        break;

    case RotSeq::xyz:
        threeaxisrot(-2 * (q.y * q.z - q.w * q.x),
            q.w * q.w - q.x * q.x - q.y * q.y + q.z * q.z,
            2 * (q.x * q.z + q.w * q.y),
            -2 * (q.x * q.y - q.w * q.z),
            q.w * q.w + q.x * q.x - q.y * q.y - q.z * q.z,
            res);
        break;

    case RotSeq::xyx:
        twoaxisrot(2 * (q.x * q.y + q.w * q.z),
            -2 * (q.x * q.z - q.w * q.y),
            q.w * q.w + q.x * q.x - q.y * q.y - q.z * q.z,
            2 * (q.x * q.y - q.w * q.z),
            2 * (q.x * q.z + q.w * q.y),
            res);
        break;

    case RotSeq::xzy:
        threeaxisrot(2 * (q.y * q.z + q.w * q.x),
            q.w * q.w - q.x * q.x + q.y * q.y - q.z * q.z,
            -2 * (q.x * q.y - q.w * q.z),
            2 * (q.x * q.z + q.w * q.y),
            q.w * q.w + q.x * q.x - q.y * q.y - q.z * q.z,
            res);
        break;

    case RotSeq::xzx:
        twoaxisrot(2 * (q.x * q.z - q.w * q.y),
            2 * (q.x * q.y + q.w * q.z),
            q.w * q.w + q.x * q.x - q.y * q.y - q.z * q.z,
            2 * (q.x * q.z + q.w * q.y),
            -2 * (q.x * q.y - q.w * q.z),
            res);
        break;
    default:
        break;
    }
}

```

solve for ZYX

---
Tags: c++, rotation, quaternion, euler-angles, physx
---


title: Unity object won't look at target

text:
# Question
Title: Unity object won't look at target
I have a box in Unity that I want to turn to face in a direction. I tried to use `Transform.lookAt()` and `Transform.rotation` but neither seem to work. Here are my code examples for both lookAt and rotation.

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

public class Move : MonoBehaviour
{
    float mouseX;
    float mouseY;

    // Start is called before the first frame update
    void Start()
    {
        Cursor.lockState =  CursorLockMode.Locked;
        Cursor.visible = true;
    }

    // Update is called once per frame
    void Update()
    {
        mouseX = Input.GetAxis("Mouse X");
        mouseY = Input.GetAxis("Mouse Y");
        Vector3 mousePosition = new Vector3(mouseX, mouseY, transform.rotation.z);
        transform.rotation = new Quaternion(0, 0, mouseX-mouseY, 0);

    }
}

```

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

public class Move : MonoBehaviour
{
    float mouseX;
    float mouseY;

    // Start is called before the first frame update
    void Start()
    {
        Cursor.lockState =  CursorLockMode.Locked;
        Cursor.visible = true;
    }

    // Update is called once per frame
    void Update()
    {
        mouseX = Input.GetAxis("Mouse X");
        mouseY = Input.GetAxis("Mouse Y");
        Vector3 mousePosition = new Vector3(mouseX, mouseY, transform.rotation.z);
        transform.LookAt(mousePosition, Vector3.forward);
    }
}

```

Here is what the scene looks like in unity

I am trying to make the cube turn on the z axis towards the mouse pointer and then move towards it.

# Answer
> -1 votes
So I figured it out. In the update method I had to add to the mouseX and mouseY instead of setting them.

```
public class Move : MonoBehaviour
{
    float mouseX = 0;
    float mouseY = 0;

    // Start is called before the first frame update
    void Start()
    {
        Cursor.lockState = CursorLockMode.Locked;
    }

void Update()
    {
        mouseX += Input.GetAxis("Mouse X");
        mouseY += Input.GetAxis("Mouse Y");
        Vector3 mousePosition = new Vector3(mouseX, mouseY, 0);
        transform.LookAt(mousePosition, Vector3.left);
        transform.Translate(Vector3.forward/100);
    }
}

```

I tried this and it worked like I wanted it to.

# Answer
> 0 votes
This code fundamentally misunderstands the different coordinate systems it's attempting to bodge together.

* `Input.GetAxis("Mouse X");` returns the *change* in the mouse's screen position (in the horizontal direction, or vertical for "Mouse Y") since the previous frame, measured in *pixels*.
* `transform.rotation` and `new Quaternion` expect a unit quaternion: a vector in a four dimensional space with three imaginary components and one real component, whose squares sum to one. This has no meaning as a position in 3D space.
* `transform.LookAt` expects a position in world space as its first argument (measured in world units), and an upward direction as its second argument.

So this code is meaningless gobbledygook:

```
mouseX = Input.GetAxis("Mouse X");
mouseY = Input.GetAxis("Mouse Y");
Vector3 mousePosition = new Vector3(
              mouseX /* displacement in screen pixels */,
              mouseY /* displacement in screen pixels */,
              transform.rotation.z /* imaginary number,
              sine of half of rotation angle
              times z component of rotation axis*/
);

transform.LookAt(
               mousePosition /* position in the world? Definitely not!*/,
               Vector3.forward
 );

```

None of the three inputs you've passed to the `Vector3` constructor represent positions, distances, or even directions in world space.

It sounds like you want to project the mouse cursor onto the horizontal plane, and rotate to face that. We can do that easily:

```
public class Move : MonoBehaviour
{
    // Update is called once per frame
    void Update()
    {
        // Get the position of the mouse on the screen, in pixels.
        Vector2 screenPosition = Input.mousePosition;

        // Cast this point through the camera viewpoint/projection
        // to form a ray shooting through world space.
        Ray worldRay = Camera.main.ScreenPointToRay(screenPosition);

        // Form a horizontal plane through this object's origin.
        Plane worldPlane = new Plane(Vector3.up, transform.position);

        // Check if the ray from the cursor hits this plane.
        // If not, skip it.
        if (worldPlane.Raycast(worldRay, out float distance) {

            // If we got a hit, get the world space coordinates
            // of the point on the plane where the cursor ray hits.
            var worldPosition = worldRay.GetPoint(distance);

            // Rotate to look toward that point.
            transform.LookAt(worldPosition);
        }
    }
}

```

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


# Question
Title: Rotating to face a world position only on the Z axis
I have a Transform with a mesh and a material to represent an in-game direction indicator.

This is parented to another Transform called Pivot.

**I am trying to rotate the Pivot transform on its own Z-AXIS only so that it points in the direction of the target.**

https://i.stack.imgur.com/KzucI.jpg

I feel like i'm missing a variable here but I cannot figure out what, I have tried many versions of code found online and I could not get any of them to work for my specific case, some didnt work at all, some got close but we're always off, some seemed to do the opposite of what I wanted but inverting that result got me an entirely different result.

I have read many answers on here about this topic already, **some I'm positive answer my question** but I cannot take that information and apply it to my own problem, I am just not very good with this kind of problem, so I apologize if you are reading the same question again.

Thanks.

i'm not sure what good code from failed attempts will do, but I have tried setting the Pivots.right to the direction to the target.

```
  Pivot.transform.right = offset;

```

The below code also got me close but didnt seem to follow the sphere correclty sometimes it would at that the target, other times slightly to the side, never really correct.

```
    Quaternion rotation = Quaternion.LookRotation(
                              Vector3.up + Vector3.forward,
                              offset
                          );

    // Apply a compensating rotation that twists x+ to y+ before the rotation above.
    Pivot.transform.rotation = rotation * Quaternion.Euler(90f, 0, 0);

    Pivot.transform.eulerAngles = new Vector3(0f, 0, Pivot.eulerAngles.z);

```

This gets me pretty close but gets weird when it comes to doing a full rotation when passing below zero.

```
        Vector3 offset = target.position - Pivot.transform.position;
        Pivot.right = offset;
        Pivot.localEulerAngles = new Vector3(0,0, Pivot.localEulerAngles.z);

```

# Answer
> 1 votes
`Quaternion.LookRotation(forward, up)` creates a quaternion that will rotate the z+ axis to point exactly along the `forward` argument, and the y+ axis as close as possible to the `up` argument.

So we can apply this in two steps. First, make a quaternion that rotates the x+ axis to the y+ axis, then a quaternion that makes the y+ axis point toward the target, and chain the two together:

```
var xToY = Quaternion.LookRotation(Vector3.forward, Vector3.left);
// Quaternion.Euler(0, 0, 90) would also do this job. Note this is a constant either way.

var yToTarget = Quaternion.LookRotation(transform.forward, targetPos - transform.position);

transform.rotation = yToTarget * xToY;

```

This is also equivalent to:

```
// Make a vector perpendicular to the direction we want our x+ to point.
var perpendicular = Vector3.Cross(transform.forward, targetPos - transform.position);

// Point our y+ axis that way, so our x+ axis points the way we want.
transform.rotation = Quaternion.LookRotation(transform.forward, perpendicular);

```

Of course, you could save some steps if you just orient your arrow graphic so that it points along the y+ axis to begin with.

---
Tags: unity
---


# Question
Title: Control different speeds for moving left/right, and facing that direction
I have a game idea... and I need a script where I can control the speed for moving left, and control another speed for moving right. But, I also need to let my player face that direction.

```
using UnityEngine;

public class NewBehaviourScript : MonoBehaviour
{
    void Update()
    {
        if (Input.GetKey(KeyCode.LeftArrow))
        {
            Vector3 position = this.transform.position;
            position.x -= .5f;
            this.transform.position = position;
        }

        if (Input.GetKey(KeyCode.RightArrow))
        {
            Vector3 position = this.transform.position;
            position.x += 1f;
            this.transform.position = position;
        }

        if (Input.GetKey(KeyCode.A))
        {
            Vector3 position = this.transform.position;
            position.x -= .5f;
            this.transform.position = position;
        }

        if (Input.GetKey(KeyCode.D))
        {
            Vector3 position = this.transform.position;
            position.x += 1f;
            this.transform.position = position;
        }
    }
}

```

That is my code. I need make it better I guess... and to make the player face that direction.

# Answer
If I understand the idea you want to achieve correctly, I would suggest that you :

* Store **Vector1** : a vector of movement speed values in different directions as you would like
* Store **Vector2** : another vector (Horizontal and Vertical Axis) for player inputs (more on that here).
* Scale **Vector1** by **Vector2** which is component-wise multiplication store that in **Vector3** (more on that here).

Now you have read the input from user and have **V3** a vector representing the final velocity.

Add that to your player position by any update method.

You can also make it rotate and face the same vector(similar to this reference).
> 0 votes

---
Tags: unity, c#, 2d, movement
---


# Question
Title: Why are URP render settings limited in terms of rendering light sources? ( Unity )
The amount of simultaneous rendering of multiple lights is not just limited, it is severely limited. Do more than 8 light sources affect the performance so much?

# Answer
The 8-light limit is a hard limit of the Forward Rendering pipeline, and it exists to avoid performance issues such as expensive processing and low frame rates on most devices.

Please note that this is a **per-object** limit, i.e. only up to 8 real-time lights can illuminate a single object. However, you can place as many light sources in your scene as you wish.

During the rendering phase, the engine must:

* Consider each object to render.
* Determine which light sources illuminate the current object.
* Compute lighting for each fragment.

Let \\$L\\$ be the number of real-time light sources, \\$O\\$ the number of GameObjects in a scene, and \\$P\_i\\$ the number of fragments the *i*-th object requires for rendering. Then, the number of operations needed to render your scene can be estimated as:

$$ N = L\*O\*\sum\_{i=0}^n P\_i $$

If our scene features 50 lights and 20 objects, we are performing 1000 checks per frame, times the total number of fragments that are to be drawn during the current frame.

If we only consider up to 8 lights per object, we go down to 160 checks per frame, times the total number of fragments. Additionally, we can discard light sources too far from the current object (e.g. light radius is 100 but the distance from object bounds is 300).

Efficiency is key during this phase. Since rendering can become quite expensive, much preprocessing is done per frame so that we draw only what's strictly needed. Stationary objects don't need real-time lights, since they aren't moving. Bake that. Real-time reflections for far away objects are just a waste of resources. Use probes instead.

You can also force real-time lights to only affect moving objects so that GameObjects marked as *Static* will use lightmaps generated from the same light source instead.

---

Such a limit is not uncommon in game engines. Real-time light sources are expensive to compute since lighting happens on a per-fragment basis. Also, the same game must run on many different devices. That's the reason why many computationally-efficient lighting solutions exist: baked lights, reflection probes, light probes (for lighting). The tradeoff here is less precision for more performance, as discussed in this Unity Forums thread by staff members.
> 1 votes

---
Tags: unity, rendering
---


# Question
Title: My object didnt "dash" on a new Input system. I have put in a code but didn't work
```
  [SerializeField] float baseSpeed = 5f;
float newSpeed;

public float DashPower;
public float DashTime;

bool isDashing = false;

Vector2 moveInput;
Rigidbody2D rb;

void Start()
{
    rb = GetComponent<Rigidbody2D>();
    newSpeed = baseSpeed;
}

void Update()
{
    Run();
}

void OnMove(InputValue value)
{
    moveInput = value.Get<Vector2>();
}

void OnDash(InputValue value)
{
    if(value.isPressed)
    {
        if(!isDashing)
        {
            StartCoroutine(Dash());
        }
    }
}

void Run()
{
    Vector2 playerVelocity = new Vector2(moveInput.x, moveInput.y) * baseSpeed;
    rb.velocity = playerVelocity;
}

IEnumerator Dash()
{
    isDashing = true;
    newSpeed *= DashPower;

    yield return new WaitForSeconds(DashTime);

    newSpeed = baseSpeed;
    isDashing = false;
}

```

# Answer
Your `Dash()` coroutine modifies `newSpeed`.

```
newSpeed *= DashPower;
...
newSpeed = baseSpeed;

```

Your `Update()` method calls `Run()`, and `Run()` scales the movement with `baseSpeed`, not `newSpeed`:

```
Vector2 playerVelocity = new Vector2(moveInput.x, moveInput.y) * baseSpeed;

```

So: you're applying the dash to a variable that you never use. This has nothing to do with the New Input System, you just need to write code that actually uses the variable you're modifying.
> 0 votes

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


# Question
Title: What is the legality of in-game composed music?
Assume there is an MMO with a feature similar to Mario Paint Composer, where you can create music with original instrument samples.

Would the players be able to share and play (in-game) the music they create freely? or would there be copyright issues?

Would there be a difference if it's an original song vs a cover of a copyrighted song?

# Answer
*I'm not a lawyer, you are not my client, this is not legal advice, I will not represent you in court and so on.*

---

I'm assuming that the music/songs will be stored and transferred by your servers. The reason for this assumption is that we are talking about an MMO.

---

What Almo comments is correct: The EULA for the game in question should have language about this issue.

> What if one were to create the MMO in question?

Then the EULA should still have language about this issue. The difference is that you need to create the EULA. Thus, I would suggest to get the help of a lawyer to write it.

The way I see it the main decision is the following:

* The players agree to transfer ownership of the works to you.

If the players transfer ownership to you, you will be able to do whatever you want with their work (sans obscuring the identity of the original author, unless they prefer to remain anonymous).

However, it also means that any works in the game that violate some other copyright are your responsibility. In other words: you would be liable. And thus you must actively police for copyright violations to make sure that does not happen.
* The players retain ownership of the works, and license them to you.

If players retain their ownership, you need to include in the EULA that by playing the game they agree to license their works to be used in the game. You will also need language to the effect that you are not responsible for the works created by the players. And then you probably *only* have to deal with copyright when reported (e.g. notification of infringement).

If you ask for my opinion, letting the players retain the ownership of the works is good for the players (because they have the copyright of their works, they can use them outside of the game) and for you (you are less liable, and it is cheaper to not have to actively police for copyright violations). In fact, if I were a potential player and this game wants me to transfer ownership of any works I create inside of it, I - personally - would not play it, because I would consider this as the game taking my labor.

---

Then you need to decide what to do when you find a copyright violation. Be aware that whatever you do, it will not erase the past, and copyright holders might still want to collect from you or your players.

Now, that you are aware that there is infringing content in your system, you can remove the work, or you can try to get a license for it. *You can guess which is the cheaper option of these two. Getting the rights would be at a loss unless you can monetize the music. Consider also that such monetization might be attractive.*

---

Other decision include:

You need to decide *how* will the music/wongs be shaded in the game. Will players send messages that allow access to specific works, or will there be a public list from which they can choose what to listen to, or will the game decide what they will listen to from what is available, or something more complex like you can approach another player and listen to what they are listening, or ven listen as they create the music?

And you need to decide If you are going to monetize or not, and how. For example will players pay by listening time or purchase songs.

I mention these decisions because it is not clear to me when you would need performance rights or broadcasting rights. Thus, I'm suggesting you bring this topic to a lawyer.

*Furthermore, there might be some caveats I'm missing. For instance you mention original samples, which would have their copyright. Also be aware that the law is not uniform across the world. Ask a lawyer.*

---

> Would the players be able to share and play (in-game) the music they create freely?

Will the music/songs be stored or transferred by your servers? If so, you need the right to distribute it (*you might need other rights, ask a lawyer*). And this are rights you need to get from the players (*or get ownership of the work*). In other words there must be a legal agreement that grants you these rights, that you present it to the players, and have them agree. Otherwise your servers would be copying and presumably sending the work to another player without the permission of the author, and that is a copyright violation.

> Would there be a difference if it's an original song vs a cover of a copyrighted song?

So... Is the player really the author of the music/song? In other words, can the player really give you rights over the work?

I believe that if you take the player authorship on good faith a lawyer can help you right a disclaimer for this situation. However, be aware that if you actively police for copyright violations, that means that you are not taking the player on good faith.
> 2 votes

# Answer
*Disclaimer: Not a lawyer. This is not legal advice, only an opinion on the Internet after doing a modest amount of exploration and research on the subject. Talk to an actual lawyer if you have financial or legal concerns about user-uploaded content in your game project.*

## If a user makes a cover of a copyrighted song with custom instruments, it falls under a legal gray area due to generative content lacking legal precedent, performance copyright, and mechanical licensing. Ask a lawyer.

The main part of your question that makes this a weird grey area is that you say **the users make custom songs with original instrument samples,** instead of being able to upload preexisting and possibly copyrighted mp3 or wav files. The question then becomes: would a user making a meme cover of Nickelback with bongo drums still count as infringing on Nickelback's copyright? Or does the copyright only hold on the original performance of the song?

The answer is *usually* that even a cover of a song still counts as infringing the copyright. In order to legally publish a performance or cover of a song, you usually have to obtain what is called a mechanical or "compulsory" license. You can legally monetize your cover once you've obtained that license. But again, this is custom music generation in a video game, not an actual person performing an actual song cover on video. This falls into a similar vein as the whole issue of who owns the copyright to generative content to begin with (the person who made the content generator? the person who hit the "generate" button? the hosting service? the generator or AI itself?). So where does that leave us?

**I don't know.** It's a grey area and you might need an actual lawyer to give you the answer. However...

## If you allow users to store, distribute and share custom music submissions on the servers, DMCA copyright restrictions concerning the hosting of user-generated content *probably* apply.

Looking at the current legal landscape around user-generated content hosting and associated copyright issues in the U.S. and Europe, the copyright concerns of allowing users to create and upload custom music in an MMO probably don't differ from existing copyright issues around other games, platforms, etc. that allow users to create and share content and host that content on the platform. Usually this applies to social media platforms like YouTube, Reddit, Facebook, Twitter, etc. that host user-submitted songs, videos and photos. However, it could theoretically also apply to games if they allowed users to host copyrighted music samples on a public-facing server, given that the only main requirements are 1) that a piece of copyrighted content is uploaded by the user and that 2) it is uploaded onto a public Internet domain. In your case, that content would just be hosted on your MMO servers and databases.

In most cases surrounding user-generated or user-submitted content on a hosting platform, a user cannot lawfully create, sell or share copyrighted content with other users without permission, and usually an unlawfully created copyrighted piece of content will be claimed by the financial stakeholder/IP holder for monetary rights/damages. In the United States and the European Union, this is known as a **Digital Millennium Copyright Act (DMCA) takedown**. (Think copyright claims and DMCA takedowns for using copyrighted music tracks on YouTube.)

## How does a DMCA takedown work?

The DMCA notice and takedown process is a tool for copyright holders to get user-uploaded material that infringes their copyrights taken down off of websites, servers, and hosting domains. For an MMO, this would include any hosting servers or databases you would use to store user-generated music. Because the DMCA process is designed to limit the actual liability of your service for (presumably inadvertently) hosting that copyrighted content, you are presumed innocent in the matter, since in most cases you simply can't screen every single piece of content that is uploaded in a reasonable manner. Instead, you will receive a **notification of an infringement claim** from the copyright holder or a representative agent, and you have the option to respond with either a counternotification defending the material and the user, or to respond promptly by blocking access to the infringing material and removing it from your servers.

## tl:dr;

In short:

* The *generation* of custom music is probably fine, but definitely exists in an odd legal grey area that the law hasn't caught up to yet.
* The *hosting* and *distribution* of the content is where you get into murky legal territory and may have to research dealing with DMCA claims, on the off chance that somebody uploads *Never Gonna Give You Up* and you get body-slammed by Sony.

As usual, ask an actual lawyer for definitive answers.
> 1 votes

---
Tags: mmo, legal, music
---


title: Get local position of a skinned vertex

text:
# Question
Title: Get local position of a skinned vertex
I have a formula for skinning, where a vertex is attached to 2 joints with some proportions:

```
B = M1*A*K1 + M2*A*K1

```

Where:

* K1 and K2 are the proportion coefficients (can be any positive numbers, but the sum is always 1.0)
* M1 - first joint transformation matrix
* M2 - second joint transformation matrix
* A - initial (local space vertex position)
* B - global space vertex position. With this formula I can compute vertex global position, when I know the vertex local position.

Out of this formula I get this formula to compute local space position for known global space position:

```
A = B*(M1*K1 + M2*K2)^-1

```

The formula works, but there are situations, when the result of this formula is incorrect. For instance, if I have these input values, I get correct result:

B:

```
9.52913, 20.4455, 0.0326125

```

K1: 0.4999

K2: 0.5001

M1:

```
1         0         0         0
0         1         0         0
0         0         1         0
0         0         0         1

```

M2

```
-1         0         0   9.58201
0         1         0   18.0092
0         0        -1         0
0         0         0         1

```

A:

```
-23685.4, 11.4392, -163.06

```

But if I slightly change K1 and K2, and make them 0.5, the result is not valid. I get the matrix, which I need to invert:

```
0         0         0         4.791
0         1         0         9.0046
0         0         0         0
0         0         0         1

```

But it is not possible, as the determinant is 0. Could somebody help me to get A for these input parameters? Thanks in advance!

# Answer
I tried what you have in Godot like this:

```
var A = Vector3(-23685.4, 11.4392, -163.06)
var M1 = Transform(
    Basis.IDENTITY,
    Vector3.ZERO
)
var M2 = Transform(
    Basis(
        Vector3(-1, 0, 0),
        Vector3(0, 1, 0),
        Vector3(0, 0, -1)
    ),
    Vector3(9.58201, 18.0092, 0)
)
print(M1*A*0.4999 + M2*A*0.5001)

```

*Mind you, these aren't truly 4x4 matrices, but since you are not using the last row, it works.*

The result is:

```
(9.529297, 20.445601, 0.032616)

```

Which looks pretty close to what you have:

```
9.52913, 20.4455, 0.0326125

```

So I will blame this to rounding errors.

---

Let us try with this now:

```
print(M1*A*0.5 + M2*A*0.5)

```

And we get:

```
(4.791016, 20.4438, 0)

```

Please notice that the z axis is zero. Furthermore, what we got on the x axis looks very close to half the translation you have `9.58201 * 0.5 = 4.791005`.

Why did that happen?

Well, look at the matrix you got:

```
0         0         0         4.791
0         1         0         9.0046
0         0         0         0
0         0         0         1

```

The first three elements of the first row are zero. So the value the output `x` depends entirely on the last element of the first row. And the third row is all zero, which is why we get output `z` to be zero.

The last column is - of course - the factors for the fourth component of the vector. Which we are assuming to be `1`, because we are using a 3D vector. Thus, if we say that the output `x` only depends on the element on the last column, we are implying the output `x` does not depend on the input 3D vector.

Similarly we can see that the first and third columns are zero. Which tells us that the values of input `x` and `z` do not affect the result. **The input `x` and `z` could be any value, which when multiplied by zero go away (do not affect the result).**

---

Alright, now we know that the values of `x` and `z` do not depend on the input 3D vector. In other words, regardless of the input 3D vector, they are going to always have the same values. Which are `x = 4.791` and `z = 0`.

So, let us see at the value you want to get: `9.52913, 20.4455, 0.0326125`.

Nope. Just Nope. The value of `x` will always be `4.791` with this transformation. And the value of `z` will always be `0` with this transformation. Thus, there is no possible input 3D vector that will yield `9.52913, 20.4455, 0.0326125`.

**We can't solve this.**

I don't know what you are trying to solve, but my advice in general is to look for another approach. *To be clear, I don't mean another approach to invert this transformation. That can't be done. I mean another way to combine then in the first place, or another approach to solve whatever you are trying to solve that led you to this (for example, can you just store the original position?)*
> 0 votes

---
Tags: matrix, vertex, position
---


# Question
Title: How to deal with rapid acceleration/deceleration from physics forces?
I'm working on a game in LOVE2D using Lua, where you pilot a drilling vehicle. The idea is that as you drill into different surfaces, you speed up/slow down depending on how dense that surface is. I'm simulating it using drag forces, something like this:

```
engineForce = engineForce + userInput * dt -- increase the engine speed based on user input
dragForce = .25 * dragCoefficient * speed^2 -- a simple implementation of the drag equation
acceleration = engineForce - dragForce
speed = speed + acceleration*dt

```

What's supposed to happen is velocity will increase until dragForce = engineForce and it maintains speed. This mostly works except occasionally it gets into a weird feedback loop where speed overshoots slightly (not sure if it's due to a rounding error or what) so drag becomes stronger than the engine causing it to decelerate. But because it decelerated, drag decreases and now the engine is stronger than drag, causing it to accelerate again. And again it will overshoot the target, causing the process to repeat again.

Does anyone know best practices for programming physics like this?

# Answer
> 2 votes
in case anyone's curious, I think I figured it out. I calculated a "terminal velocity" for a given engineForce, that is the speed where drag and the engine would balance out (in this case that's sqrt(4\*engineForce/dragCoefficient)) and cap your velocity at that. So far, it seems to work!

---
Tags: physics, lua, love2d
---


# Question
Title: How to find the maximum distance a target point can be hit from a launched projectile
I'm determining a trajectory necessary to hit target B with a projectile launched from point A with a given velocity. No problems there. Obviously, not all points B can be hit with a fixed velocity, so I'm trying to find the maximum distance along AB that can still be hit by the projectile. How might I find this?

# Answer
Using the code in this answer:

```
Vector3 toTarget = target.position - transform.position;

// Set up the terms we need to solve the quadratic equations.
float gSquared = Physics.gravity.sqrMagnitude;
float b = speed * speed + Vector3.Dot(toTarget, Physics.gravity);
float discriminant = b * b - gSquared * toTarget.sqrMagnitude;

// Check whether the target is reachable at max speed or less.
if(discriminant < 0) {
    // Target is too far away to hit at this speed.
    // Abort, or fire at max speed in its general direction?
}

```

We can see that the limiting threshold between reachable and unreachable targets occurs when `discriminant == 0`

Let's rewrite this in math form, using \\$x \vec d\\$ to represent the displacement from our launch position to our farthest reachable point, with \\$0 \le x \< 1\\$. Here \\$\vec d\ = \vec B - \vec A\\$, represents the total displacement from our launch point \\$\vec A\\$ to the target point \\$\vec B\\$, if \\$\vec B\\$ itself is not reachable.

$$\begin{align} b = v^2 + x\vec d \cdot \vec g\\ b^2 - \\|x \vec d\\|^2 \\|\vec g\\|^2 &= 0\\ (v^2 + x^2\vec d \cdot \vec g)^2 - x^2 \\|\vec d\\|^2 \\|\vec g\\|^2 &= 0\\ v^4 + 2 x v^2\vec d \cdot \vec g + x^2(\vec d \cdot \vec g)^2 - x^2\\|\vec d\\|^2\\|\vec g\\|^2 &= 0\\ x^2\left((\vec d \cdot \vec g)^2 - \\|\vec d\\|^2\\|\vec g\\|^2\right) + x (2v^2 \vec d \cdot \vec g) + v^4 &= 0 \end{align}$$

That last line is a basic quadratic which you can solve with the quadratic formula, since all the coefficients are known in terms of your inputs: the target displacement \\$\vec d\\$, the acceleration due to gravity \\$\vec g\\$, and the maximum launch speed \\$v\\$.

This will give you two answers: the positive one is the farthest fraction of the way toward your target \\$\vec B\\$ that you can hit (or overshoot, if the value is greater than 1, meaning you can hit the target itself no problem). The negative one is how far you can shoot diametrically opposite your target (not super interesting in this case).

In the event that the displacement is parallel to the direction of gravity, then the first term disappears and it's a linear equation with a single solution instead - even easier!
> 2 votes

---
Tags: physics, mathematics, projectile-physics
---