# Question
Title: How can I create a animator parameter in a script, unity?
In unity we can create parameters in the animator tab to help to control changes in animation. I'm able to create this parameters in the unity itself and manipulate them in the C# script, but I want to know how I can do all this process only through code. So I would like to create a parameter and set the condition in the animation, only through coding. How can I do that?

# Answer
Poke around in the Unity API documentation and you'll find the `UnityEditor.Animations` namespace, containing AnimatorController.AddParameter.

Here's an example from the AnimatorController docs showing how to use this to create a custom animator controller with specific parameters and state transitions via script:

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

// Create a menu item that causes a new controller and statemachine to be created.

public class SM : MonoBehaviour
{
    [MenuItem("MyMenu/Create Controller")]
    static void CreateController()
    {
        // Creates the controller
        var controller = UnityEditor.Animations.AnimatorController.CreateAnimatorControllerAtPath("Assets/Mecanim/StateMachineTransitions.controller");

        // Add parameters
        controller.AddParameter("TransitionNow", AnimatorControllerParameterType.Trigger);
        controller.AddParameter("Reset", AnimatorControllerParameterType.Trigger);
        controller.AddParameter("GotoB1", AnimatorControllerParameterType.Trigger);
        controller.AddParameter("GotoC", AnimatorControllerParameterType.Trigger);

        // Add StateMachines
        var rootStateMachine = controller.layers[0].stateMachine;
        var stateMachineA = rootStateMachine.AddStateMachine("smA");
        var stateMachineB = rootStateMachine.AddStateMachine("smB");
        var stateMachineC = stateMachineB.AddStateMachine("smC");

        // Add States
        var stateA1 = stateMachineA.AddState("stateA1");
        var stateB1 = stateMachineB.AddState("stateB1");
        var stateB2 = stateMachineB.AddState("stateB2");
        stateMachineC.AddState("stateC1");
        var stateC2 = stateMachineC.AddState("stateC2"); // don’t add an entry transition, should entry to state by default

        // Add Transitions
        var exitTransition = stateA1.AddExitTransition();
        exitTransition.AddCondition(UnityEditor.Animations.AnimatorConditionMode.If, 0, "TransitionNow");
        exitTransition.duration = 0;

        var resetTransition = rootStateMachine.AddAnyStateTransition(stateA1);
        resetTransition.AddCondition(UnityEditor.Animations.AnimatorConditionMode.If, 0, "Reset");
        resetTransition.duration = 0;

        var transitionB1 = stateMachineB.AddEntryTransition(stateB1);
        transitionB1.AddCondition(UnityEditor.Animations.AnimatorConditionMode.If, 0, "GotoB1");
        stateMachineB.AddEntryTransition(stateB2);
        stateMachineC.defaultState = stateC2;
        var exitTransitionC2 = stateC2.AddExitTransition();
        exitTransitionC2.AddCondition(UnityEditor.Animations.AnimatorConditionMode.If, 0, "TransitionNow");
        exitTransitionC2.duration = 0;

        var stateMachineTransition = rootStateMachine.AddStateMachineTransition(stateMachineA, stateMachineC);
        stateMachineTransition.AddCondition(UnityEditor.Animations.AnimatorConditionMode.If, 0, "GotoC");
        rootStateMachine.AddStateMachineTransition(stateMachineA, stateMachineB);
    }
}

```

I've never used this API, but was able to find it in about a minute of searching, so don't underestimate your ability to answer your own curiosity with a little legwork.
> 2 votes

---
Tags: unity, animator
---


# Question
Title: Why is this back-facing texture showing through?
I have a mesh of some walls and a floor that I want to be visible from both sides. I duplicated the faces and flipped their normals in Blender, then exported it as an FBX to import in Unity. I've set up the texture and material in such a way that the faces that face inwards are green, and the ones that face outwards are red. This works somewhat well, but I'm getting a strange depth issue in some cases.

As you can see in the image, in the corner with the two narrow walls the red outward-facing polygons show through the green inward-facing walls, as if the green wall is transparent.

I checked the model and the normals are all pointing in the right direction. It somehow looks like some sort of depth buffer issue, where the renderer thinks the red wall is closer than the green one it's supposed to be obscured by.

I'm using Unity 2021.1.25f1 with the URP v11. The shader is just the standard URP/Unlit shader.

What could be causing this?

# Answer
> 3 votes
When you set a material to be transparent, by default this also disables it from writing to the depth buffer.

This is important for avoiding ugly cut-out effects, where a transparent or faintly translucent part of a polygon closer to the camera completely blocks the rendering of a polygon further away, which just happened to render after it, leaving a visible hole in the more distant polygon.

Instead of making your mesh double-sided, with a copy of each polygon facing each way, you can instead leave it single-sided but render it in two passes:

* The first pass is opaque (depth buffer writes enabled) and renders only the interior (front-facing) polygons.
* The second pass is transparent (depth buffer writes disabled) and renders only the exterior (back-facing) polygons.

One quick way to test this is to set up two materials: one green, opaque, set to render front faces, and one red, transparent, set to render back faces. Add both materials to your MeshRenderer component.

I *think* you can also implement this with a single material using a custom shader with two passes, but I'd need to double check whether you can put two passes in different geometry queues (opaque geometry vs transparent).

---
Tags: unity, normals, culling, unity-urp
---


# Question
Title: What does the Lock toggle in the Position Constraint Component do?
Even after reading the documentation, I just can't figure out what the parameter does.
I experimented in Unity and set different parameters for Position At Rest and Position Offset. I succeeded in this anyway - both when Lock = false, and when Lock = true.

So what does the Lock affect?

# Answer
This is covered in the documentation:

> **Toggle to let the Constraint move the GameObject**. Uncheck this property to edit the position of this GameObject. You can also edit the Position At Rest and Position Offset properties. If Is Active is checked, the Constraint updates the At Rest or Offset properties for you as you move the GameObject or its Source GameObjects. When you are satisfied with your changes, check Lock to let the Constraint control this GameObject. This property has no effect in Play Mode.

You might have been testing with the "Is Active" toggle in the wrong state to see this in action. Here's the four combinations of behaviour you can observe with a quick test:

|  | Is Active ✅ | Is Active ❌ |
| --- | --- | --- |
| **Lock ✅** | **You cannot move this object** on its frozen position axes with its transform inspector or transform gizmo.

If you move the source objects, **this object will move to follow** along its frozen position axes.

Editing the Position at Rest and Offset properties is **disabled** in the inspector. | **You can move this object**, but re-enabling "Is Active" will make it snap back to its position according to this constraint's properties.

If you move the source objects, this object will **stay where it is** until "Is Active" is enabled.

Editing the Position at Rest and Offset properties is **disabled** in the inspector. |
| **Lock ❌** | **You can move this object** on its frozen position axes with its transform inspector or transform gizmo.

If you move the source objects, this object will **stay where it is**.

Editing the Position at Rest and Offset properties is **enabled** in the inspector. These properties will also **automatically update** if you move the object or its source objects to match, so that it retains its current position if "Lock" is re-enabled. | **You can move this object** on its frozen position axes with its transform inspector or transform gizmo.

If you move the source objects, this object will **stay where it is**.

Editing the Position at Rest and Offset properties is **enabled** in the inspector. These properties will **not** automatically update. |
> 3 votes

---
Tags: unity, animation, skeletal-animation
---


# Question
Title: SFML - How to implement a simple 2D lighting system
Lately, I've been reading a lot about 2D lighting systems in a game, and have observed just how much lighting can add to a game's graphics appeal. However, as for implementing one of these in SFML, I am clueless. The lighting system I would like doesn't have to be too complex - I don't need things such as shadows. What I would like is something like this, which I made in Java using swing:

How this works:

* I draw a black rectangle over the whole image with an alpha that changes based on the in-game time of day - 0 during the day, 128 during the night.
* On top of that rectangle, I draw a gradient on top of the player's x and y coordinates - from (255, 255, 255, 100) to (0, 0, 0, 0)

What would be the ideal way to impement this in SFML?

# Answer
## Without shadows

The most direct approach is to have a PNG image with the texture of a light. If you don't want to use an external file, you can even create it yourself inside the program:

1. Create a new white `sf::Image` of dimensions radius\*radius.
2. Iterate through all its pixels, setting their alpha value as 1 minus the normalized distance to the center of the image.

I recommend you drawing it with additive blend mode `sf::BlendAdd`. Also, check this `substractAlpha` mode; you can use this if you have a `sf::RenderTexture` acting as a layer of darkness. Draw the light in that layer using this blend mode to see through.

```
sf::BlendMode substractAlpha(
        sf::BlendMode::Factor::Zero,              // color src
        sf::BlendMode::Factor::One,               // color dst
        sf::BlendMode::Equation::Add,             // color eq
        sf::BlendMode::Factor::Zero,              // alpha src
        sf::BlendMode::Factor::OneMinusSrcAlpha,  // alpha dst
        sf::BlendMode::Equation::Add);            // alpha eq

```

## With shadows

Although you don't need shadows, I'll leave this here for other people that visit this question.

Dynamic 2D light is a more complex topic, as it involves raycasting algorithms and such. So instead of explaining anything here, I'll point you to a great tutorial (in fact I would recommend anyone to watch all the videos in this channel, they're all fantastic).

Line Of Sight or Shadow Casting in 2D by javidx9.

Although he doesn't use SFML, it is pretty framework-agnostic and everything he does in the OLC engine you can do it with `sf::VertexArray`.

## Alternative: use an existing library

There already exist open source libraries for lighting and dynamic light casting in SFML.

### Let there be light (LTBL2)

GitHub repository
SFML forum thread

* **Pros**
    + Relies on GLSL shaders, so it's probably more efficient.
    + Provides soft shadows (with penumbras/antumbras).
* **Cons**
    + It has very little documentation.
    + Although the project had some updates in 2020, the development stopped in 2016 and doesn't seem to be currently active.

### Candle

GitHub repository
SFL forum thread
Documentation

* **Pros**
    + It is currently actively developed and maintained.
    + It is extensively documented and comes with an out-of-the-box demo to test it (without external dependencies).
* **Cons**
    + As a more recent library, it is not exhaustively tested and might still have glitches.
    + Depending on your needs, it might not be the best performant option.
> 3 votes

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


# Question
Title: Animation cycles abruptly from last frame to first
I was doing some basic interactions with the animation dopesheet and noticed that image 1 to 2 takes certain time, 2 to 3 and 3 to 4 take the same amount of time, but in the loop, 4 goes almost instantly to 1. I would like to add more time before this happens. The timeline is shown below, and it's clear what is happening, but I can't figure how I extend the end part.

# Answer
You need to add a keyframe that matches 0:00 (key frame 1)) at time 0:40 (new key frame 5).
> 3 votes

---
Tags: unity, animation
---


# Question
Title: How can I make a tracing game mechanic more engaging?
I'm working on a puzzle game where you build a model airplane from a box of parts. I'm working on a feature where you actually cut frames out of a sheet of material, which later become building blocks of the puzzle.

It works, and it *is* kind of satisfying, but ultimately the player is simply mindlessly tracing a pattern. There could be dozens of parts in the game like this, but as it stands no one would want to do this twice, let alone multiple times. I'm looking for ideas on how to make this activity more challenging or otherwise engaging, while still resulting in a correctly shaped part when finished.

video: https://www.youtube.com/watch?v=CxsAGTzti0Q

WebGL Demo: https://bomonroe.itch.io/aircraft-in-pixels-parts-cutting-demo

# Answer
> 27 votes
My family is of carpenters. So, that is my bias. However, if you want challenge, hear me out.

The first thing that bugs me is that you start cutting in the middle of the board. You would want to drill a hole first. Which brings me to a few ideas:

* Give the player tools. In fact, unlocking tools can be a reward, and thus extrinsic incentive.
* Let the player use whichever tool they have access to, however they want.
* Have a score of how good the result is.

---

The basic tools would be a saw and a drill. You may add a (woodworking) chisel as beginner tool. And you can add variations of the saw and drill.

If we sort cutting tools by how tight curves they can make, we have: table saw, handsaw, hacksaw, and jigsaw coping saw. By the way, that is also from fast cutting to slow cutting. *And from more lost material (i.e. a wider cut line) to less.*

Upgrades for the drill line are also possible: Bit brace to hand drill (wheel brace), to electric hand drill (by the way, have a look at the drill bits for door nob holes).

But in general you have things that cut (which need to begin on an edge), things that make round holes, and the chisel would make narrow rectangular holes.

---

So, the player have some assortment of tools. How do we make them work so the player can use them however they want?

Well, polygons. You start with a rectangular board. Represent that as a 2D polygon for our operations. And from a 2D polygon you can make a mesh by triangulating it, making two offset copies in 3D, and then adding a triangle strip for the edge. And while working with 2D polygons, we can do polygon subtraction to make the cuts and (approximately round) holes.

*Note: in real life practice there is always some lost material, regardless of tool, which becomes shavings - no mentioned tool would make shavings - and sawdust (which reminds me: particle effects). Thus I suggest subtracted polygons.*

---

Now that the player have tools, and can use them however they want… You need to score them!

First of all, the goal is to cut the piece, and the piece would be a target polygon. This is my suggestion: expand the target polygon by some margin, then subtract it with whatever is left of the board. If there is something left, the player is not done. You can add score as the remaining area decreases.

However, I suggest to remove score as the player cuts more than they should. That is, if you intersect the board with the target polygon and measure the area, if it is any less than the target polygon area, that would remove score.

I think you would need a failing condition too. At every cut or hole the player does, there should always be only one piece that intersects with the target polygon. If there are two pieces that intersect with the target polygon, it means that the player has made a cut that split the target polygon in two. Thus, the piece would be unusable. It should be a failing state. Start over with a new board.

---

And there you go: you have challenge, with a failing condition and a scoring system. *Perhaps there would be a way to replay to try to get a better score.* And you have one possible avenue for rewards in unlocking tools.

---

*Addendum*

As suggested in comments, when the piece is cut in two, you could pick the bigger one, and don't fail if the smaller one small enough. This is something that would require a lot of testing to get right. How small is small is small enough? Would there be sensible areas (some parts of the piece that need to engage other pieces)? How do you communicate that to the player?

If you think you can make it work, feel free to go for it. However, if the goal is to be less punishing, I'm going to suggest an alternative: have an undo option. That would be easier to communicate and to test.

Simplest implementation will be an stack of recent states, so you push a state every cut, and you pop on undo.

Perhaps the player can only undo failing moves. *Which is what I would go with if the goal is to be less punishing*. However, perhaps the player can undo indefinitely. Or perhaps it works like a consumable. *You could make undo cost money. For example, pretend it just means the character took another board and did fast forward every move. In fact, if there is in-game time, it could cost that too. Or you could make it an abstract consumable the player buys… But know that players will stockpile that, and it does not necessarily make for fun mechanic. On that note, "watch this ad to undo" isn't a fun mechanic either.*

# Answer
> 11 votes
Almost this exact mechanic is in the Harry Potter and the Philosopher's Stone PC game. I found it very frustrating and quite difficult to make the mouse do what I wanted.

My suggestion is, make this part of the game 3D. Zoom the camera in and sit it on top of the powered Jigsaw, pointing half forwards, half down. Then get the player to use the keyboard arrow keys, or tilt of the phone, to drive the jigsaw around the pattern like a racecar around a track.

# Answer
> 1 votes
The first thing you need is to devise a way that the player can *fail* making a good part. Without that there's virtually no way to make this interesting. The player needs more direct control on the cutting and perhaps the measuring too.

If you want a gamey way to add interest, make it time-bound. I don't know about others, but a score isn't really a good motivator for me.

Also, make it persistent. In real life you wouldn't have infinite boards to cut to get your aircraft pieces. You could even really have a single chance to cut every piece correctly.

And when I said to add a failure condition, that doesn't necessarily mean to immediately force the player to try again cutting the same piece. You can have a fail-state with or without consequences (as in the example of limited wood). One cool way that could work is if at the end of the game, you try to actually make the plane fly and the pieces used in the plane were the actual shape cut by the player. If a piece doesn't have the right shape, the plane might not fly straight or might just crumble after assembly.

# Answer
> 1 votes
The Vita game Uncharted Golden Abyss has a charcoal rubbing minigame, where the player has to rub their thumb across the screen to trace a pattern. The drawings are collectibles that are used to complete jigsaw puzzles. See 1:15 in this video.

Playing your demo kind of feels like the charcoal rubbing mechanic. In Uncharted's case, the mechanic is kind of just a gimmicky way to use the Vita touchscreen, but also makes the collectathon a little more engaging. You might want to consider making your version simpler, maybe have it be one step instead of two (cut, instead of trace + cut), require less precision, etc. That wouldn't be as interesting as the suggestion from Theraot, but it would help with the problem of users not wanting to do it after the first few times.

One idea I had for making it more interesting would be to have the knife leave scratches on the wood if you don't follow the line. That way, if you're lazy, your final airplane will be all ugly and scratched up. If you don't care about that, then you can just quickly move your mouse/finger across the screen to get past that section quickly.

# Answer
> 0 votes
Give a **score** for the performance (accuracy, or maybe maybe speed, maybe both) after a part has been cut out. A high score means a reward, a higher score means a better reward (or more of the same award).

The award would be a **trained monkey**, which will help you cut out additional parts. Score bad, and you have to work on your own on all the parts (until the accumulated score get large enough to award a monkey). Score high, and a monkey will work in parallel with you on parts. Continuing to cut pieces, you continue to accumulate on your score (the monkey will cut with the same performance as you, so having a monkey will double your increase for the next parts).

Eventually, you'll have an army of monkeys which do most of the work.

They will also poop on the shop floor and the smell of singed monkey hair will be awful when they get too close to the laser cutter. Oh, well, if the wood shop already has laser cutters...ditch the monkey idea and award CNC laser cutters. The monkey will be more charming, though. You could give the score in **bananas**. More bananas, more monkeys, more banana peel and other...."byproducts" on the shop floor.

---
Tags: game-mechanics
---


# Question
Title: How to track when the player collides with another tile?
I'm using Unity to create a 2D platformer game. I ran into an issue I was hoping someone could help me with. I'm using OnCollisionEnter2D() to detect when the player gameobject touches the ground, which is a tilemap. At the most basic implementation, it looks like this:

```
private void OnCollisionEnter2D(Collision2D collision) {

    Debug.Log("Tile collision");

    var map = collision.collider.GetComponent<Tilemap>();
    var grid = map.layoutGrid;

    // Find the coordinates of the tile we hit.
    var contact = collision.GetContact(0);
    Vector3 contactPoint = contact.point - 0.05f * contact.normal;
    Vector3 gridPosition = grid.transform.InverseTransformPoint(contactPoint);
    Vector3Int cell = grid.LocalToCell(gridPosition);

    // Extract the tile asset at that location.
    var tile = map.GetTile(cell);

    if(tile == null)
        return; // No valid tile! Abort!

    // Do something when a new tile is hit
    // TODO: Place function here

}

```

When I run my game, the console displays "tile collision" whenever I jump and then touch a tilemap surface. The console message will not display again until I leave whatever surface I'm on and touch it again. Although this is close to what I want, it's not exactly what I'm trying to achieve.

I'd like to be able to display the message every time the player touches another tile, even if its the same tile the player was previously touching. I'm not entirely sure how to implement this, though. Does anyone have any pointers that might help me achieve my desired outcome?

# Answer
As DMGregory noted in his comment, it sounds like you need to check `OnCollisionStay2D` to check that the player continues to be grounded to the tile. Alternatively, you could check `OnCollisionExit2D` to learn when the player has become ungrounded.
> 1 votes

---
Tags: unity, tilemap
---


# Question
Title: How do I download audio resources and cache them?
I am developing a game in Unity 2019. The instructions of the game must be translated into several languages. Currently they are part of the compilation, but this makes the compilation very large.

I would like, according to the selected language, to be able to download the corresponding audio and cache it.

# Answer
Old question, but the current official best practice is to use Unity's `Addressable Asset System` to manage and asynchronously load asset packages from any location and with any collection of dependencies. The addressable system is built on top of `AssetBundles`, and while a bit of a steep learning curve at first, in my experience it is flexible and robust in action.
> 1 votes

# Answer
https://docs.unity3d.com/ScriptReference/WWW-audioClip.html https://forum.unity.com/threads/download-and-save-www-mp3-file.409470/

these are what you are looking for. but WWW is being deprecated. just try to find **UnityHttpRequest** replacement solution for this. in these threads you problem is dicussed well.

you can check if you have that file in your device. if there isnt, so you have to get it from server.
> 0 votes

---
Tags: unity, memory
---


# Question
Title: My python code has stopped detecting keystrokes
It was working before, then I added the enemy rectangle and it has stopped working.

```
import time, copy
import pygame
import random
import os
WINDOW_WIDTH = 560
WINDOW_HEIGHT = 560
WINDOW = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
red =(255,0,0)
green =(0,255,50)
yellow =(255,255,0)
black = (0,0,0)
white = (255,255,255)
WINDOW.fill(black)
pygame.display.update()
a = 20
b = 20
L = False
R = False
U = False
D = False
##x = [20,40,60,80,100,120,140,160,180,200,220,240,260,280,300,320,340,360,380,400,420,440,460,480,500,520]
##ex = x[random.randint(0,24)]
##ey = x[random.randint(0,24)]
player = pygame.Rect(a,b,20,20)
pygame.draw.rect(WINDOW, green, player)
##enemy = pygame.Rect(ex,ey,20,20)
##pygame.draw.rect(WINDOW, red, enemy)
pygame.display.update()
while True:
    for event in pygame.event.get():
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                L = True
            elif event.key == pygame.K_RIGHT:
                R = True
            elif event.key == pygame.K_UP:
                U = True
            elif event.key == pygame.K_DOWN:
                D = True
        elif event.type == pygame.KEYUP:
            if event.key == pygame.K_LEFT:
                L = False
            elif event.key == pygame.K_RIGHT:
                R = False
            elif event.key == pygame.K_UP:
                U = False
            elif event.key == pygame.K_DOWN:
                D = False
        if(D):
            if b < 540:
                pygame.draw.rect(WINDOW, black, player)
                b = b+20
                player = pygame.Rect(a,b,20,20)
                pygame.draw.rect(WINDOW, green, player)
        elif(U):
            if b != 0:
                pygame.draw.rect(WINDOW, black, player)
                b = b-20
                player = pygame.Rect(a,b,20,20)
                pygame.draw.rect(WINDOW, green, player)
        elif(R):
            if a < 540:
                pygame.draw.rect(WINDOW, black, player)
                a = a+20
                player = pygame.Rect(a,b,20,20)
                pygame.draw.rect(WINDOW, green, player)
        elif(L):
            if a != 0:
                pygame.draw.rect(WINDOW, black, player)
                a = a-20
                player = pygame.Rect(a,b,20,20)
                pygame.draw.rect(WINDOW, green, player)
##        time.sleep(0.2)
##        if ex < a:
##            pygame.draw.rect(WINDOW, black, enemy)
##            ex = ex+20
##            enemy = pygame.Rect(ex,ey,20,20)
##            pygame.draw.rect(WINDOW, red, enemy)
##        elif ex > a:
##            pygame.draw.rect(WINDOW, black, enemy)
##            ex = ex-20
##            enemy = pygame.Rect(ex,ey,20,20)
##            pygame.draw.rect(WINDOW, red, enemy)
##        elif ey > b:
##            pygame.draw.rect(WINDOW, black, enemy)
##            ey = ey-20
##            enemy = pygame.Rect(ex,ey,20,20)
##            pygame.draw.rect(WINDOW, red, enemy)
##        elif ey > b:
##            pygame.draw.rect(WINDOW, black, enemy)
##            ey = ey-20
##            enemy = pygame.Rect(ex,ey,20,20)
##            pygame.draw.rect(WINDOW, red, enemy)
##        pygame.display.update()
##        if ex == a and ey == b:
##            WINDOW.fill(white)
##            pygame.display.update()
##            time.sleep(2)
##            os._exit(1)

```

# Answer
I've never used Pygame, but I'm pretty sure you're supposed to be updating the display in the main loop, not outside.

`pygame.display.update()` on line 28 should be inside the loop, so under the `while True:` part.

I noticed that you had an update further down, but you commented it out.
> 1 votes

---
Tags: python
---


# Question
Title: Find those points lying on a circle from a ton of points
Given a 2d scene and 10,000 players with coordinates in the scene, I want to implement a function, the input is a circle with the center coords and its radius, the output is those players that lie on the circle.
**And the function will be called very often**
My solution is to divide all players into a quadtree according to their coordinates and limit the tree height. Each tree node will contain some players. Then we can compare the center point P of the circle and players in the tree node containing P to calculate the result. In this way, we can cut down many unnecessary calculations.
So is there a more efficient solution?

# Answer
> 1 votes
How about a spatial hash using concentric rings as buckets? Basically the same concept as your quad tree, but much simpler.

Here's a quick example:

```
#include <stdio.h>
#include <time.h>
#include <cmath>
#include <list>

//total number of buckets, tweak as needed
const int NUM_BUCKETS = 100;

//max radius of the circle
const double WORLD_RADIUS = 100'000.0;

const double BUCKET_SIZE = WORLD_RADIUS / NUM_BUCKETS;

struct Player {
    double x, y;
    int ID; //unique player ID
    int bucket;
};

//our circle
struct {
    double x, y;
    double radius;
} circle;

std::list<Player*> buckets[NUM_BUCKETS];

double calcDistance(double x0, double y0, double x1, double y1){
    float dx = x0 - x1;
    float dy = y0 - y1;
    return sqrt((dx*dx)+(dy*dy));
}

int clampi(int v, int min, int max){
    if(v < min) return min;
    if(v > max) return max;
    return v;
}

//returns the bucket that contains an object at distance `dist`
int hashDistance(double dist){
    int ret = (int) floor(dist / BUCKET_SIZE);
    return clampi(ret, 0, NUM_BUCKETS - 1);
}

//returns the bucket that a player is in
int getPlayerBucket(Player *player){
    double dist = calcDistance(player->x, player->y, circle.x, circle.y);
    return hashDistance(dist);
}

//update a single player's bucket
void updatePlayerBucket(Player *player){
    int old_bucket = player->bucket;
    int new_bucket = getPlayerBucket(player);
    if(old_bucket != new_bucket){
        if(old_bucket >= 0){
            buckets[old_bucket].remove(player);
        }
        buckets[new_bucket].push_back(player);
        player->bucket = new_bucket;
    }
}

//brute force update all player's buckets
void updateAllPlayers(Player *players, int num_players){
    for(int i = 0; i < num_players; i++){
        updatePlayerBucket(&players[i]);
    }
}

//prints all of the players in the circle
void printPlayersInCircle(){
    int max_bucket = hashDistance(circle.radius) - 1;

    int total = 0;

    //we can assume that players in these buckets are inside the circle
    for(int i = 0; i < max_bucket - 1; i++){
        for(Player *player: buckets[i]){
            total++;
            printf("[%d] %d: (%f, %f)\n", player->bucket, player->ID, player->x, player->y);
        }
    }

    //we can't assume that all players in the last bucket are in the circle
    //need to double-check their distances to be sure
    for(Player *player: buckets[max_bucket]){
        float dist = calcDistance(player->x, player->y, circle.x, circle.y);
        if(dist <= circle.radius){
            total++;
            printf("[%d] %d: (%f, %f)\n", player->bucket, player->ID, player->x, player->y);
        }
    }

    printf("Total players in circle: %d\n", total);
}

int main(int argc, char **argv){
    //init players
    srand(time(0));
    int num_players = 10'000;
    Player *players = (Player*) malloc(sizeof(Player) * num_players);
    for(int i = 0; i < num_players; i++){
        players[i].ID = i;
        players[i].x = ((double)(rand() % (int)WORLD_RADIUS)) - (WORLD_RADIUS / 2.0);
        players[i].y = ((double)(rand() % (int)WORLD_RADIUS)) - (WORLD_RADIUS / 2.0);
        players[i].bucket = -1;
    }

    //init circle
    circle.x = 0;
    circle.y = 0;
    circle.radius = WORLD_RADIUS / 4.0;

    //place all players into buckets
    updateAllPlayers(players, num_players);

    printPlayersInCircle();
    return 0;
}

```

Things to consider:

* If the circle origin (not radius) ever changes, all buckets need to be recalculated
* WORLD\_RADIUS and NUM\_BUCKETS should be tuned to improve the distribution of players into buckets (if you need that; it's not important for simply querying players in the circle)
* Any players outside of WORLD\_RADIUS will fall into the outermost bucket
* You can optimize this by calling `updatePlayerBucket` only when a player actually moves
* This algorithm can be parallelized relatively easily, such as by storing buckets in thread local storage to avoid locks/syncs, or something similar
* You may be able to use the squared distance to avoid the sqrt operation (10'000 players isn't that huge though, so you probably don't need to bother. Profile as always)
* If you profile this sample code, remember to disable the `printf`s to get an accurate measurement

---
Tags: c++, 2d, mathematics
---


# Question
Title: How can I create a shader which makes an object transparent in bright light and opaque in low light?
I'm trying to set up a shader that, as the title says, functions similarly to the effect appearing in the "Lights Out" horror short film. Cut down to the very basics, I'm looking for advice on how to have the overall Alpha/transparency of the material be affected by Realtime and Directional lights in the scene so that the material is only visible below a certain lighting threshold. I found a similar effect that accomplishes the inverse goal of lowering the alpha of whatever a light is cast on, but I couldn't manage to invert the effect, nor could I get it to function properly in my project to begin with.

I'm currently working in Unity 2019.4.29f1 and was hoping to be able to tack this effect onto some other shaders that I have to avoid having to reconstruct an entirely new shader for this singular purpose.

Edit: As per suggestion, a few extra details:

This gif is more or less the effect I'm trying to accomplish: https://pa1.narvii.com/6743/bf353546d9f30e492077c1cf8d57e3f60f53a36b\_hq.gif

Ideally, I'd like it to not just be based on full mesh coverage of light, but more like a dynamically applied alpha mask based on light intensity on the actual mesh over any given spread of the surface.

The effect that I found and attempted to modify was effectively trying to accomplish the opposite of what I'm trying here. It was attempting to make something transparent if it had light cast on it (at least how I understood it). I hoped to be able to invert this effect with minimal editing, however I either misunderstood how the shader functioned or was simply unable to comprehend was most of the syntax meant and ended up unable to modify it to fit my needs. Additionally, I wanted to have most of the Texture and render options that come with Unity Standard shader, but couldn't figure out how to combine the two shaders due to a flat lack of knowledge regarding shader coding.

Edit: This is the shader that I attempted to reverse engineer that I couldn't get to work: Shader change alpha depending on light

Edit: For further clarification, I WILL need a custom shader for this feature as I'm attempting to implement it on a platform that disallows custom scripting, and requires that whatever changes I make are locally controlled (I will not have control over environmental factors like lights).

# Answer
> 0 votes
**Do you *need* a custom shader?**

Based off the gif you sent, it seems like the entire model will always completely either completely visible or completely hidden. If this is the case, then the simpler, more design controllable, and performant solution would be to simply enable/disable the visuals of the game object as lights are turned on and off.

# Answer
> 0 votes
I don’t know how VRChat shaders work, which inputs are available, etc. but this seems pretty simple. All you need is a basic diffiuse lighting shader, but use the light contribution to affect the alpha channel.

Something like:

```
color.a = dot(normal, light);

```

That’s all the math that’s needed. Just make sure the material is marked as transparent so the renderer knows it needs to be sorted (otherwise you’ll get ugly artifacts)

Or were you looking for something different?

---
Tags: unity, shaders, lighting
---


# Question
Title: Input.GetAxis returns wrong sign only for 1 and -1
I'm using an Xbox 360 controller on Windows 10 with Unity, and the maximum values have the opposite sign as the rest of that side. For example, if I tilt the stick up, I get values from 0.1 to 0.99, but then I get a -1 when the stick is at maximum. Have I configured it to be this way by mistake? I have reproduced the issue in a clean project and using another controller.

```
void Update () {
    float pitch = Input.GetAxis("Vertical");
    Debug.Log (pitch);
}

```

---

I have discovered that if the axis is inverted (i.e. not as shown in the image) then returned values have expected signs. I will add this workaround as an answer for anyone else who may encounter this problem, but I will refrain from accepting it to allow for answers addressing the root cause.

# Answer
> 1 votes
I had previously discovered a workaround that gave me reasonable behavior but did not reveal the underlying problem. I have revisited the project and have determined the root cause.

> **Two axes were named "Horizontal".**

It seems that the InputManager by default has two axes named "Horizontal" and two axes named "Vertical." **Deleting one of the sets completely solved the issue.**

---

The previous solution:

*Setting the axis to inverted causes the returned values to behave in a sensible way. Now if I tilt the stick up, I get values from -0.1 to -0.99 and -1 when the stick is at maximum, and I get values from 0.1 to 0.99 and 1 when I tilt the stick down. I can just as easily write my script expecting an inverted axis, so this allows me to continue. Unfortunately I still don't know what is causing the odd behavior when the axis isn't inverted.*

# Answer
> 0 votes
Thank you very much for the solution. In fact, I found double entries in the Input Manager. "Horizontal" and "Vertical" had each 2 entries. I deleted the second entries, they were empty, and the problem was away. It never came back. Before that, I was searching for a couple of days with no positive result. Goto: Unity -\> Edit -\> Project settings -\> Input Manager -\> Search for the second entries "Horizontal" and "Vertical" -\> Rightclick -\> "Delete Array Element" That was all. I couldn't believe it. Thank you, thank you, thank you !!!

---
Tags: unity, c#, xbox-controller
---


title: Controlling the delta time in Unity

text:
# Question
Title: Controlling the delta time in Unity
I record object data (position,rotation) for objects in a scene and store it to a file. At some stage the player can load this file and "play back" the recording to watch themselves. Obviously they can now have a different view. As its trivial to store each frame to a png and then stitch them together as an movie file, I decided to add an export function.

The png sequence is rendered to have 60FPS at the best quality as the render fps does not really matter anymore.

**The problem :**

Everything else in the scene (clouds/vegetation) is still based on Time.deltaTime. Because it takes much longer to render at ultra and store to an PNG, Time.deltaTime is way off my 60FPS the objects are rendering at. (if that makes sense).

Basically if I render 600 frames, the objects moved for 10 seconds. But everything else moved for the entire render time of 600 frames that will be like 20 seconds. So the backgound looks to be in fast forward.

**The question**

Is there anyway to set Time.detaTime manually or trick the Unity into setting Time.deltaTime to 1/60 ? Then all the other assets will be in sync with the set FPS and render ?

**Ideas**

* If I had access to all the assets (including Unit's vegetation) I could hack the code to use a defined time step.
* Not sure if there is some trick with VSync that could help.

Like I said, I am not sure that this can even be done. Any suggestions will be welcome.

# Answer
> 2 votes
`Time.captureDeltaTime` is provided specifically for this purpose — capturing screenshots between frames.

> If this property has a non-zero value then Time.time increases at an interval of captureDeltaTime (scaled by Time.timeScale) regardless of real time and the duration of a frame. This is useful if you want to capture a movie where you need a constant frame rate and want to leave enough time between frames to save screen images.

---
Tags: unity, timestep, deltatime
---


# Question
Title: Local rotation towards world point, with axis other than forward vector
I have a turret transform which is a child of weapon game object. Which in itself is a child of player object. I want to rotate this turret towards a world point (Raycasthit.point of a ray going forward from center of the screen).

One thing to note is that weapon model is made in blender and turret bone have a default rotation of (90,0,0). It looks like this:

I tried the usual Quaternion.LookRotation method by subtracting raypoint from turret local position, from world position and even by converting the raypoint from world to local by InverseTransformPoint and I also tried changing the world up direction to every possible combination. I also tried SetLookDirection method with every possible combination. But I just can't seem to make the rotation work properly.

# Answer
`Quaternion.LookRotation(forward, up)` gives you a rotation that points the local z+ axis (blue arrow) toward the "forward" argument, and the local y+ axis (green arrow) as close as possible toward the "up" argument.

Since you want to point with the green axis instead, you can just apply an extra rotation to it:

```
// Make a rotation that points z+ at our target, and y+ away from the turret base.
// The second argument is optional, but helps control "twisting" of the barrel.
Quaternion zToTarget = Quaternion.LookRotation(
                          hit.point - transform.position,
                          directionOutFromBase
                       );

// Make a rotation that points y+ toward z+ (and z+ toward y-).
Quaternion yToZ = Quaternion.Euler(90, 0, 0);

// Chain these rotations, so we put the y axis where the z axis was,
// then transform the z axis to point at our target, effectively
// pointing with our y axis instead!
transform.rotation = zToTarget * yToZ;

```
> 1 votes

---
Tags: unity, rotation
---


# Question
Title: Model import generating self-intersecting warnings that weren’t there before
Starting with Unity 2018, when importing my model (FBX) I am getting dozens of "A polygon of \[name of the mesh\] is self-intersecting and has been discarded“ warnings. This is new! The model looks fine when imported despite these warnings, but this model is part of a package I sell on the Asset Store since, I am in the process of updating the asset and at the very least this looks terrible for customers purchasing this asset. Unfortunately, the warning message gives no further clues *which* polygons are now offending. FWIW the model was created in Maya. Does anyone have any advice on how I can track this down and fix this without breaking the prefabs?

# Answer
> 2 votes
I just crossed my fingers that it wouldn't merge unwanted vertices and used "Merge vertices" in Maya. This worked for 95% of the affected polygons, the others were comparatively easy to find manually because their faces were large and Unity discarded them on import. Fortunately, replacing the fbx when exporting the mesh to the project doesn't break anything, unless you mess up the meshes in the fbx itself.

---
Tags: unity, maya
---


title: D3D11 wrong full screen resolution

text:
# Question
Title: D3D11 wrong full screen resolution
I am currently writing a Directx 11 engine and have problems with the resolution when switching to exclusive fullscreen on my 1440p monitor. If i call SetFullscreenState(TRUE, NULL), the screen changes modes from 2560x1440 to 1920x1440 and my windows gets stretched. The WM\_SIZE message also contains the size 1920x1440.

My initialization code (without error checking):

```
DXGI_SWAP_CHAIN_DESC swap_chain_desc = {0};
swap_chain_desc.BufferDesc.Width = window_data.width;
swap_chain_desc.BufferDesc.Height = window_data.height;
swap_chain_desc.BufferDesc.Format = DXGI_FORMAT.B8G8R8A8_UNORM;
swap_chain_desc.BufferDesc.Scaling = DXGI_MODE_SCALING.STRETCHED;
swap_chain_desc.SampleDesc.Count = 1;
swap_chain_desc.SampleDesc.Quality = 0;
swap_chain_desc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
swap_chain_desc.BufferCount = 2;
swap_chain_desc.SwapEffect = DXGI_SWAP_EFFECT.FLIP_DISCARD;
swap_chain_desc.OutputWindow = window_data.window_handle;
swap_chain_desc.Windowed = true;

//swap_chain_desc.Flags |= DXGI_SWAP_CHAIN_FLAG.ALLOW_MODE_SWITCH;

D3D_FEATURE_LEVEL feature_level;
UINT flags = D3D11_CREATE_DEVICE_FLAG.DEBUG;
HRESULT hr = D3D11CreateDeviceAndSwapChain(null, D3D_DRIVER_TYPE.HARDWARE, null, flags, null, 0, D3D11_SDK_VERSION,
                                            &swap_chain_desc, &swap_chain, &device, &feature_level, &device_context);
d3d11_data.current_swap_chain_flags = swap_chain_desc.Flags;

```

When i get a WM\_SIZE message, i resize the swap chain to the size passed as lParam. I also make sure not to change the swap chain flags when resizing:

```
    UINT width = LOWORD(lParam);
    UINT height = HIWORD(lParam);
    d3d11_data.device_context.OMSetRenderTargets(0, null, null);
    d3d11_data.render_target_view.Release();

    HRESULT hr = d3d11_data.swap_chain.ResizeBuffers(0, width, height, DXGI_FORMAT.UNKNOWN, d3d11_data.current_swap_chain_flags);

    ID3D11Texture2D framebuffer;
    hr = d3d11_data.swap_chain.GetBuffer(0, &IID_ID3D11Texture2D, cast(void**)&framebuffer);

    hr = d3d11_data.device.CreateRenderTargetView(framebuffer, null, &d3d11_data.render_target_view);
    framebuffer.Release();

    d3d11_data.device_context.OMSetRenderTargets(1, &d3d11_data.render_target_view, null);

    D3D11_VIEWPORT viewport = {0};
    viewport.Width = width;
    viewport.Height = height;
    viewport.MinDepth = 0.0f;
    viewport.MaxDepth = 1.0f;
    viewport.TopLeftX = 0;
    viewport.TopLeftY = 0;
    d3d11_data.device_context.RSSetViewports(1, &viewport);

```

I do not get any debug output nor do any of these functions return an error code. Things i have tried:

* Messing with the compatibility setting of the application (DPI, "fullscreen optimization").
* Ignoring the size passed with WM\_SIZE and resizing the swap chain to 2560x1440.
* Passing the DXGI\_SWAP\_CHAIN\_FLAG.ALLOW\_MODE\_SWITCH flag and setting the render target to 2560x1440 using ResizeTarget and a DXGI\_MODE\_DESC optained via mode enumaration. This will change the refresh rate to e.g. 60Hz, but the resolution will still be 1920x1440.
* Using a different windowed resolution before going fullscreen.
* Enabling DXGI debug output via DXGIGetDebugInterface

None of them had any visible effect on the result. Windowed fullscreen via SetWindowPos works fine at the correct resolution. Any ideas on what might be happening?

# Answer
> 2 votes
The problem was that i specified the scaling mode to be DXGI\_MODE\_SCALING\_STRECHED, not DXGI\_MODE\_SCALING\_UNSPECIFIED. As per the MSDN doc ( https://docs.microsoft.com/en-us/previous-versions/windows/desktop/legacy/bb173066(v=vs.85) ) this will change the resolution, even if the requested resolution is the entire screen.

# Answer
> 0 votes
One thing that's worth trying is enumerating the supported modes and picking one of those that matches the resolution you need, instead of creating your own `DXGI_MODE_DESC`. See https://docs.microsoft.com/en-us/windows/win32/direct3d11/overviews-direct3d-11-devices-get-adapter-info

Another option is to use IDXGIOutput::FindClosestMatchingMode() which will search through the available modes for you.

Also note that DXGI has a different way to enable debug mode than DX11, and that might help you diagnose what's going on as it generates extra debug output.

---
Tags: directx, directx11, windows, resolution, fullscreen
---


# Question
Title: I'm following a tutorial but I don't get the same result; why are the raytraced shadows not working?
I followed this tutorial called "Ray Tracing in One Weekend" by Peter Shirley. And I implemented the java version of it for studying Ray Tracing.

Everything was all right until Diffuse Materials, but anti-aliasing was okay though.

Please point out my mistakes.

I have tried gamma color correction but the shadows are still invisible. Here's the source code:

In case I screwed up my Sphere intersection code etc., here are the classes:

Sphere class:

```
public class Sphere extends Hitable{

    double r; //radius
    Vec3   p; //position

    public Sphere(Vec3 p, double rad) {
        this.p = p;
        this.r = rad;
    }

    @Override
    boolean hit(Ray r, double t_min, double t_max, hit_record rec) {
        Vec3 oc = r.getOrigin().sub(p);
        double a = r.getDirection().lengthSquared();
        double half_b = oc.dot(r.getDirection());
        double c = oc.lengthSquared()-this.r*this.r;
        double discriminant = half_b*half_b-a*c;
        if(discriminant<0) return false;
        double sqrtd = Math.sqrt(discriminant);

        double root = (-half_b - sqrtd)/a;
        if(root < t_min || t_max < root) {
            root = (-half_b + sqrtd)/a;
            if(root < t_min || t_max < root)
                return false;
        }

        rec.t = root;
        rec.p = r.at(rec.t);
        Vec3 outward_normal = (rec.p.sub(this.p)).div(this.r);
        rec.set_face_normal(r, outward_normal);
        return true;
    }
}

```

Vec3 class:

```
public class Vec3 {

    private double x, y, z;

    public Vec3(double x, double y, double z) {
        this.x = x;
        this.y = y;
        this.z = z;
    }

    double x() { return x; }
    double y() { return y; }
    double z() { return z; }
    double r() { return x; }
    double g() { return y; }
    double b() { return z; }
    double lengthSquared() { return x*x+y*y+z*z; }
    double length() { return Math.sqrt(lengthSquared()); }
    double dot(Vec3 v) { return x*v.x()+y*v.y()+z*v.z(); }
    Vec3 cross(Vec3 v) { return new Vec3(y*v.z()-z*v.y(), z*v.x()-x*v.z(), x*v.y()-y*v.x()); }
    Vec3 unitVector() { return this.div(this.length()); }
    Vec3 neg() { return new Vec3(-x,-y,-z); }
    Vec3 add(Vec3 v) { return new Vec3(x+v.x(), y+v.y(), z+v.z()); }
    Vec3 mul(Vec3 v) { return new Vec3(x*v.x(), y*v.y(), z*v.z()); }
    Vec3 sub(Vec3 v) { return new Vec3(x-v.x(), y-v.y(), z-v.z()); }
    Vec3 div(Vec3 v) { return new Vec3(x/v.x(), y/v.y(), z/v.z()); }
    Vec3 add(double t) { return new Vec3(x+t, y+t, z+t); }
    Vec3 mul(double t) { return new Vec3(x*t, y*t, z*t); }
    Vec3 sub(double t) { return new Vec3(x-t, y-t, z-t); }
    Vec3 div(double t) { return new Vec3(x/t, y/t, z/t); }
    public String toString() { return "("+x+","+y+","+z+")"; }
}

```

Ray class:

```
public class Ray {

    private Vec3 origin, direction;

    Vec3 getOrigin()     { return origin; }
    Vec3 getDirection()  { return direction; }
    Vec3 at(double t) { return origin.add(direction.mul(t)); }

    public Ray(Vec3 origin, Vec3 direction) {
        this.origin = origin;
        this.direction = direction;
    }
}

```

Main class:

```
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.imageio.ImageIO;
import javax.swing.JFrame;

import rt.Hitable.hit_record;

public class Main {

    public static void main(String[] args)
    {
        JFrame frame = new JFrame("Raytracer");
        Canvas canvas = new Canvas();
        frame.add(canvas);
        frame.setSize(Toolkit.getDefaultToolkit().getScreenSize());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null);
        frame.setResizable(false);
        frame.setVisible(true);

        canvas.createBufferStrategy(2);
        Graphics g2 = canvas.getBufferStrategy().getDrawGraphics();

        int w = 640;        //render width
        int h = 480;        //render height
        int sample = 100;   //samples
        int depth = 50;     //depth

        BufferedImage display = new BufferedImage(w,h,BufferedImage.TYPE_INT_RGB);
        Camera cam = new Camera();

        HitableList world = new HitableList();
        world.add(new Sphere(new Vec3(0,0,-1), 0.5));
        world.add(new Sphere(new Vec3(0,-100.5,-1), 100));

        long last = System.nanoTime();

        for(int j=h-1;j>0;--j)
        {
            System.out.println("scanlines remaining: "+j);

            for(int i=0;i<w;++i)
            {
                Vec3 col = new Vec3(0,0,0);

                for(int s=0;s<sample;++s) {
                     double u = (double)(i+Math.random()*1)/(display.getWidth()-1);
                     double v = (double)(j+Math.random()*1)/(display.getHeight()-1);
                     Ray r = cam.getRay(u, v);
                     col   = col.add(hit(r,world,depth));
                }

                double r = col.r(),
                       g = col.g(),
                       b = col.b();

                double scale = 1.0/sample;
                //r *= scale;
                //g *= scale;
                //b *= scale;

                r = Math.sqrt(scale*r);
                g = Math.sqrt(scale*g);
                b = Math.sqrt(scale*b);

                int ir = (int)(256*clamp(r, 0, 0.999));        // R component
                int ig = (int)(256*clamp(g, 0, 0.999));        // G component
                int ib = (int)(256*clamp(b, 0, 0.999));        // B component
                display.setRGB(i, h-j-1, (ir<<16)+(ig<<8)+ib); // plot pixel to the screen.
            }
        }

        long now = System.nanoTime();
        double time = ((now-last)/1000000000.0);
        System.out.println("done, time taken: " + time);

        g2.setFont(new Font("Consolas", Font.PLAIN, 32));
        g2.setColor(Color.BLACK);

        try {
            ImageIO.write(display, "PNG", new File("./gallery/"+time+"--"+new SimpleDateFormat("dd-MM-yyyy").format(new Date())+"--"+w+"x"+h+"--"+sample+".png"));
        } catch (IOException e) {
            e.printStackTrace();
        }

        while(true)
        {
            g2.drawImage(display, 0, 0, frame.getWidth(), frame.getHeight(), null);
            g2.drawString(""+time, 50, 50);
            canvas.getBufferStrategy().show();
        }
    }

    static Vec3 random_in_unit_sphere() {
        while(true) {
            Vec3 p = randomVec3(-1,1);
            if(p.lengthSquared() >= 1.0)  {
                continue;
            }
            return p;
        }
    }

    static Vec3 randomVec3(double min, double max)
    {
        double scale = max-min;
        return new Vec3((Math.random()*scale)+min, (Math.random()*scale)+min, (Math.random()*scale)+min);
    }

    static double clamp(double x, double min, double max) {
        if(x < min) return min;
        if(x > max) return max;

        return x;
    }

    static Vec3 hit(Ray r, Hitable world, int depth) {
        hit_record rec = new hit_record();

        if(depth <= 0)
            return new Vec3(0,0,0);

        if(world.hit(r, 0, Double.POSITIVE_INFINITY, rec)) {
            Vec3 target = rec.p.add(rec.normal).add(random_in_unit_sphere());
            return hit(new Ray(rec.p, target.sub(rec.p)), world, depth-1).mul(0.5);
        }

        Vec3 unit_direction = r.getDirection().unitVector();
        double t = 0.5*(unit_direction.y()+1.0);
        return new Vec3(1,1,1).mul(1-t).add(new Vec3(0.5,0.7,1).mul(t));
    }
}

```

10/19/2021 update:

# Answer
> 1 votes
I found the solution.

It was actually in the HitableList class, where I defined this intersection function;

```
@Override
    boolean hit(Ray r, double t_min, double t_max, hit_record rec) {
        hit_record temp_rec = new hit_record();
        boolean hitanything = false;
        double closest_so_far = t_max;

        for(Hitable h : this.objects) {
            if(h.hit(r, t_min, closest_so_far, temp_rec)) {
                hitanything = true;
                closest_so_far = temp_rec.t;
                rec = temp_rec;
            }
        }

        return hitanything;
    }

```

(Spoiler: I forgot Java is pass-by-value) This function actually does not assign the HitRecord passed by the parameter to the temp\_rec, so leaving the HitRecord default (in effect, normal is set to (0,0,0), leaving no shadows behind). So I changed it to:

```
@Override
    public boolean intersect(Ray ray, double tmin, double tmax, HitRecord record) {

        for(Hitable h : objects) {
            if(h.intersect(ray, tmin, tmax, record)) {
                return true;
            }
        }

        return false;
    }

```

So here is the result: Thanks, everyone for helping me in this thread.

# Answer
> 2 votes
The randomVec3() function used in random\_in\_unit\_sphere() doesn't match the one in the tutorial. A standard unit sphere is centred at the origin with a radius of 1, and your current implementation doesn't give you either of those properties.

I don't know if that's the only problem, but fixing that should help.

Try something like this, which is closer to the code in the tutorial:

```
static Vec3 randomVec3(double min, double max)
{
    double scale = max-min;
    return new Vec3((Math.random()*scale)+min, (Math.random()*scale)+min, (Math.random()*scale)+min);
}

static Vec3 random_in_unit_sphere()
{
    while(true)
    {
        Vec3 p = randomVec3(-1.0, 1.0);
        if(p.lengthSquared() >= 1.0)
        {
            continue;
        }
        return p;
    }
}

```

---
Tags: java, 3d, raytracing, software-rendering
---


# Question
Title: Scaling my pixel art platformer from 720p to 1080p
I'm developing a pixel art 2D platformer for PC and smartphone, but I'm stuck on a technical issue.

I chose to have a 32x32 tile resolution, and a 64x64 character sprite resolution. The levels are divided in to sections that I call "screens", and in each screen I've got 40x22.5 tiles, approximated to 40x23, so the minimum resolution is 1280x720.

In the game, I have got a double-jump mechanic, so I need to have a good vertical view range on each "screen".

Here comes the issue: 1280x720 is not a very high resolution. On HD monitors the window would be not be big, and if I upscale the resolution by 2x, it will be in 2560x1440 and the window would be much larger than an actual HD monitor. If I try sizes in between 1280x720 and 2560x1440 the graphics start to stutter, or are deformed.

How can I solve this issue? Is there a solution that does not require me to redraw all the tiles and the sprites in 16x16 format?

# Answer
> 21 votes
For anyone wondering why this is an issue for pixel art, here's a quick example using a scene from Super Mario World:

If we just scale a pixel art game from 720 to 1080 at runtime (the way a typical game camera might), we get artifacts because of the non-integer ratio of screen pixels per source texel. Check out the inconsistency in the numbers from the scaled example on the right, and how garbled the leaf and Mario's ear look.

It's playable, but it's lost that charming pixel art crispness. And in motion these artifacts can crawl across a sprite, making it look shimmery.

Using a filtering mode that blends adjacent pixels will avoid the ripples, but smear and blur the pixel art instead, so it's also not very desirable.

---

Unfortunately the 1.5x ratio between 720p and 1080p is the worst case scenario we can encounter.

As you note, scaling 1x is too small and 2x is too big, by just as wide a margin both ways, and there's no whole-numbered scaling ratio in between for us to choose.

Your options boil down to:

* **Tolerate 1x scale**, showing your game in a window 1/3 smaller than the screen, adding decorative borders if you need to fill the space.

+ You may be able to extend the cropping, showing more of your scene at a time on high-res screens. This reduces the padding/letterboxing needed, but you'll have to evaluate whether it impacts how the game plays

    (eg. does it give players on some devices an unfair advantage or let them spot secrets they shouldn't see so easily?)
* **Scale up by 2x and crop your scene**, so the player sees less of the scene at a time (about 3/4 as far as they could see before).

This too can affect how the game plays, eg. by making it hard for the player to see the places they need to double-jump to.

+ You may by able to compensate for this with camera logic, having the view pan to follow or anticipate the player, so the important content is still visible in one screen at the smaller crop, but there's no universal best camera to use.

If you decide to go this route, try sharing some details of your gameplay and current camera, and an example scene. With that, we might be able to help tune the camera behaviour to compensate (or your game might just flat-out require more visibility)
* **Create alternate assets at a different resolution**. (Yeah, this is a *lot* of work, but gives you the most options to control the look & feel of the game)

This doesn't mean you have to throw out your existing assets that look great on 720p. This article describes contextually swapping between different asset sets to support a wider range of target resolutions (in Unity, but the principle can be applied in non-Unity games too).

+ As you note, redrawing all your assets at half size (**16x16 tiles, 32x32 character**) will let you handle 720p at 2x scale, and 1080p at 3x scale, with the same number of tiles shown as you have now. You may find the small tile resolution more restrictive visually though.
    + You could also draw an alternate, "large format" asset set that's 150% larger (**48x48 tiles, 96x96 character**), which would handle 1080p at 1x scale. (You'd use your existing assets for 720p or 1440 etc). The larger resolution should help you retain the fidelity of your current art, so you don't have to sacrifice the style & details you have now.
    + A third option is to draw an only slightly smaller asset set (**24x24 tiles, 48x48 character**), which can handle 1080p at 2x scale, and again might mean less sacrifice of detail than halving all your asset sizes.

    All three of these options will let you keep your framing and gameplay exactly the same at 720 & 1080, but at the cost of roughly double the asset work.

So, unfortunately there's no easy win here, just different trade-offs.

---

For comparison, here's the same scene above using Domi's proposed method: Scaling up 2x (the next whole-number multiple) with nearest neighbour, then scaling down to 75% (to get a net scale difference of 150%, matching the 1080/720 ratio) with bilinear filtering. As with the example on the right, I scaled the result up an extra 4x so the pixels are easier to see on high-res screens.

You can see it's more consistent than the fractional nearest neighbour scale alone, but does significantly blur the crisp edges of the pixel art shapes.

# Answer
> 3 votes
Elaborating specifically on @DMGregory's option of creating alternate assets at a different resolutions:

The best solution I know of is probably the least use to you at this this point: develop your art assets in a vector format & rasterize them as needed later. This isn't a magic bullet; most of the time you will find you need to make some small handcrafted modification after rasterizing.

The next best option I know is to try various image scaling algorithms, specifically, pixel art scaling algorithms. As before, this isn't a pancea; selecting a specific scaling algorithm is highly context specific. It has as much to do with your game's 'feel' as with the art itself & even with a good algorithm + art match up, you will probably need to tweak some sprites by hand.

In both cases, the idea is to use a tool to do the bulk of the work for you and focus the human effort on the remaining details. Like @DMGregory said, "there's no easy win here, just different trade-offs."

---

Edit regarding fractional scaling: Most pixel art scaling algorithms only increase by whole numbers. Short of rolling your own custom scaling algorithm, you're probably going to need to combine upscaling & downscaling to get the 1.5x change you're looking for. As a reference, here's the result of combining the scale3x algorithm to upscale & the fant algorithm to downscale by 50%:

Original:

Scaled:

# Answer
> 1 votes
Scaling pixel art by fractional number factors is not trivial, as explained by the other answers.
It is still possible to do while getting good looking results though!

---

Nearest neighbor scaling distorts the shape of pixels.

---

Bilinear filtering significantly blurs the pixels.

---

It is possible to combine those scaling methods, **keeping the benefits of both while reducing side effects**.

You start with upscaling the scene by the next larger whole-number factor using nearest neighbor. Then you downscale that to the target resolution with bilinear (or any other preferred) filtering.

This will keep the centers of sprite pixels untouched, and only blur the boundaries between them. Therefore it will work better for more coarse sprites / larger scaling factors, where a single sprite pixel covers a lot of screen pixels.

Those pictures are taken from https://colececil.io/blog/2017/scaling-pixel-art-without-destroying-it/, where Cole explains how to achieve similar results using a custom shader.

Here is another, admittedly extreme example. The original image was upscaled 9x, and then downscaled by 10%. The blurred boundaries are only one screen pixel in size, barely noticeable until zoomed in.

---

For comparison, here are example images that have not been zoomed in (original image was 64x64 pixels, scaled to 96x96 / 150%):

---

---
Tags: 2d, resolution, scale, pixel-art
---


# Question
Title: Custom inspector values in prefab mode not save to prefab
I have a prefab with a custom `GridModel` component which has a custom editor. For some reason whenever I edit a value in Prefab Mode, the value doesn't save in the prefab asset and vice versa. How can I fix this issue?

Here is my code:

```
public class GridModel : MonoBehaviour, IGridModel
{
    public Vector2Int dimensions;
}

```

```
[CustomEditor(typeof(GridModel))]
public class GridModelEditor : Editor
{
    private GridModel gridModel;

    void OnEnable()
    {
        gridModel = (GridModel)target;
    }

    public override void OnInspectorGUI()
    {
        gridModel.dimensions = EditorGUILayout.Vector2IntField("Size", gridModel.dimensions);
    }
}

```

# Answer
> 1 votes
You should call `Undo.RecordObject` to record the object before changing it, so the editor knows it has modifications that need saving. This also creates an "Undo" entry so the user can reverse the change if they need to.

As the doc linked above points out:

> Important: To correctly handle instances where `objectToUndo` is an instance of a Prefab, `PrefabUtility.RecordPrefabInstancePropertyModifications` must be called after `RecordObject`.

You can also get these benefits automatically by making your changes through the `SerializedObject`/`SerializedProperty` API, which handles the necessary book-keeping and supports multi-object editing.

---
Tags: unity, prefabs
---


title: How to prevent grinding?

text:
# Question
Title: How to prevent grinding?
I am making an investment game where the goal is to have a lot of money from a little as fast as possible. There are banks with join fees and maximum balances.

I added sleeping, which skips to 8:00 the next day, with 22:00 being the bedtime

I want for a savings account to be an invest option, and I ran into a loophole. If you just invest the starting money and sleep till you get max money in the savings account and keep upgrading the bank, you can get infinite money with just spamming sleep for hours, or even using an auto-typer.

While the goal is to make a fortune as fast as possible, I still want to get rid of that loophole. Bills and energy are too complex, and I want to keep both the game and the code relatively simple, without adding inflation.

**Should I just remove saving accounts, or is there a simple solution (or reverse psychology) to grinding I am missing?**

Is there a physiological approach?

*EDIT: This is a single-player text-based game.*

*Each bank has a join fee, max loan, and max balance. Upgrading bank will take around 75% of max money of the previous bank, making "levels". Maybe I will put better savings accounts for bigger banks and add a credit score.*

*I will also add investments like company startup loans, lottery and stock*

*You can only do the following things:*

* Invest
* Change bank
* Wait
* Buy things like caffeine pills to extend bedtime

# Answer
> 1 votes
I see several options to remedy this, all involving the end goal of the game which you did not state in your question:

* Add an ingame time limit of a few years. Savings accounts will just be too slow to increase wealth significantly in the short time.
* Make the end goal purchasing a certain asset, and make the cost of this asset rise with inflation or faster, at least faster than the savings interest. Savings accounts will not help you if the goal moves faster than the savings over time.
* Make the end goal being significantly wealthier than some AI opponents. The opponents should be able to profit faster than the savings account.

The common feature of all these options is that the goal of the game, making money "as fast as possible", should be measured by ingame time, not playtime.

# Answer
> 0 votes
Implement inflation.

In the real world, money just sitting in an account loses buying power over time.
Inflation should be simulated in any game that tries to make a realistic impression of real world investing. You can see here that the Consumer Price Index has steadily risen year after year, so $1 gets you less year after year.

A normal low-risk/low-interest savings account will lose buying power over time due to inflation removing value faster than interest can add value.

So, if the player just puts $1000 in an account and sleeps 365x in a row, they *should* earn the interest rate for 1 year, but the new balance in the account is now less useful than the $1000 that they had 1 year ago.

# Answer
> 0 votes
The simplest solution is to remove the saving account option. The direct path to simplicity is to remove things. Now, I believe you don't want that solution. Thus, you will have to accept some level of complexity.

---

I'll mention an hypothetical scenario here. Don't worry, I'll come back the topic at hand.

The hypothetical scenario: Alice lends some money to Bob, who agrees to pay back in some months plus some extra. Bob uses the money to buy some machines and materials so he can start a - let us say - a bike repair shop. After a while Bob got the money back and then some, so he pays what he owes to to Alice.

This is one of the simplest scenarios for an investment. There is no intermediaries, no taxes, no stock exchange, no minting, no reserve baking…

And it suggest a couple things:

* The person getting a loan must be able to get a return on investment faster than the person lending.
* The return on investment may take some time.

---

Alright, back to the topic at hand. We will keep the saving account, and it will be an investment option. However, as the hypothetical scenario suggests:

* You are going to add the option to get a loan.
* You are going to add other things in which the player can invest, but they imply some risk.

Such that just putting money on the saving account is actually the slow option, but also the safe (risk-free) option.

---

Which remind me, you say the game is about getting money fast, you don't want a time limit, and you want a time skip option.

So, I suggest to not allow to skip to the next day if the day just started. And thus push people to do something else while they wait for nightfall.

Furthermore, if this is a multiplayer game, perhaps you should remove the time skip option altogether.

---

By the way, about the risk. I don't mean gambling. I'm not encouraging to create a casino-like game. Perhaps in a different kind of game I would add skill based mini (or perhaps no so mini) games, and depending on how the player does, they get more or less money.

However, let's us think how can we do this differently… Instead of requiring player skill, we are going to simulate skill. Thus: leveling.

That is, the player will gain level in doing whatever it is they do to get money. *I don't know what they do to get money in the game.* So the more they do or invest on an activity/job/company, the more levels they get. And the more levels they have, the more money they get (as in, the same amount invested will pay back more).

Except putting money on the saving account. That does not level up. It is always the same return on investment. *Wait, is that what you mean by "upgrading the bank"? If so, yeah, remove that.*

And thus, in the long run, leveling up is the best way to get money fast, because it accelerates, while putting money in the saving account has constant speed.

By the way, I say leveling, but it does not have to be called that. For example, it could be that you invest in a company, and the company goes over different stages of growth. Or if it is a job, then it is that they get promotions. For some activities you could say it is mastery. Or for other activities it could be reputation or popularity.

---

Again, I don't know how your game works. However, I suppose return on investment could have variability. For example some investments could be seasonal. Or it might depend on the popularity of a company or product, or something like that. And thus, in an investment game you could give hints to the player of what to invest on in the form of news. That way, investing in the best option remains skill based.

---

Or you could be going for an idle game/auto-clicker. In which case remove the time skip option.

*I don't know. I might be imagining a completely different game than what you have.*

---
Tags: game-design
---


# Question
Title: I can't render faces properly in my DirectX11 project
For some reason, only back-faces are rendering, even if I set the rasterizer and stencil buffer and state to any values. Setting `D3D11_CULL_NONE`, `D3D11_CULL_FRONT`, `D3D11_CULL_BACK` in the rasterizer structure has the same result.

This is how rendering is supposed to look (The code somehow works in the side project that was made using the `Direct3D Win32 Game` Visual Studio template):

The model I'm rendering is loaded using DirectX::Model::CreateFromCMO(). I'm using left hand projection and view matrices.

This is how it looks inside my project:

I'm using the DirectXTK library to draw the sup model itself in both projects. I'm pretty sure that the graphics device, context and swap chain are properly created. I tried copying code from the second project to the first project but I somehow still managed not to fix it.

I'm also sure that the DirectX::CommonStates does contain it's own rasterizer and stencil state, but I don't understand how rendering doesn't work on my own project.

The debug layer is not displaying any errors or warnings at run-time related to the creating of the rendertargets, device, texture buffers, etc.

My only idea remaining is that the stencil buffer is wrongly configured, but I can't find what I did wrong here. The stencil state description is taken from MSDN (this link): https://docs.microsoft.com/en-us/windows/win32/direct3d11/d3d10-graphics-programming-guide-depth-stencil

The main project source is here (I won't post pieces of the code because that would take a lot of time and space, there are like 300+ lines of code related to the rendering pipeline) : https://github.com/NicusorN5/3D\_Rad\_Space/tree/master/3DRadSpace

To mention that you can't compile the project by your own because `Resources.rc` is set to load files from a non-local (i.e some folder on my secondary HDD) path, and because of some dependencies that are also located in non-local paths. Sorry for that.

# Answer
The Model draw method is setting the Rasterizer state as part of the standard setup. If you want to override the state at draw time, you can use custom drawing callbacks per the wiki.

You didn't mention if this model is CMO or SDKMESH or if you are using right-handed or left-handed viewing coordinates. You look like you've mixed those up in some fashion.

For *DirectX Tool Kit for DX11* the way to control the winding of Model is to provide a `ModelLoaderFlag` to `Model::CreateFrom*`.

You are likely using the defaulted parameter. Try the opposite flag:

```
static std::unique_ptr<Model> CreateFromCMO(
    ID3D11Device* device,
    const wchar_t* szFileName,
    IEffectFactory& fxFactory,
    ModelLoaderFlags flags = ModelLoader_CounterClockwise,
    size_t* animsOffset = nullptr

```

```
static std::unique_ptr<Model> CreateFromSDKMESH(
    ID3D11Device* device,
    const wchar_t* szFileName,
    IEffectFactory& fxFactory,
    ModelLoaderFlags flags = ModelLoader_Clockwise);

```

These are setup assuming right-handed viewing and the model was exported with 'traditional winding' (SDKMESH usually assumes left-handed viewing). If you are using left-handed viewing, then you need to flip them. Again, see the wiki.
> 0 votes

---
Tags: c++, graphics, directx11, stencil
---


title: How do game loading screens work?

text:
# Question
Title: How do game loading screens work?
I have successfully developed a 2D game. I display sequential introduction images then load the start screen after that of course I load the game level in a single thread, it is a basic functional game. however the game lacks the loading screen and I lack the experience and idea to create one. I made a research in this and found several different approaches.

From my web searches I deduced that I should implement another thread to display the loading screen until the game thread finishes loading its content.

What are the best practices?

# Answer
> 2 votes
Although in some contexts it is nice to have have another thread for this, you do not *need* a second thread.

You can get away with using only one thread:

1. create some kind of graphical animation looping mechanism, based on "time" (e.g. the looping "loading" animation has 8 frames, make this loop 2 times per second, this will make it 16 fps, )
2. allow this looping mechanism to fire the rendering of the screen
3. when you start loading, cover up the screen with whatever "loading" image you want, and display your "looping/loading" animation
4. then periodically, when you load stuff, poke the "looping/loading" animation mechanism; if the previous poke occurred in the last 1/16th of a second, no need to re-render, if it occurred earlier than this, check how long it's been and display the appropriate animation frame.

This method has the advantage that, well, it's single threaded, so you know exactly what happens when it happens, but it has the inconvenience that the loading/looping animation may not be as smooth as it could be as it could sometimes skip frames, and you have to change the code that loads stuff to allow the poking.

---
Tags: c++, assets, multithreading, loading
---


title: What is wrong with my terrain lighting?

text:
# Question
Title: What is wrong with my terrain lighting?
I've just implemented a simple algorithm to calculate terrain vertex normals and I'm using diffuse and ambient light currently, but for some reason the squares that make up my terrain are visible when I turn on lighting as you can see in the above image. I'm currently calculating the normal for the terrain using the cross product formula between two vectors of the squares that compose the terrain. Is it because I should be using something like the average between the neighbour normals? I'll leave bellow the algorithm I'm using:

```
        //m_Polygon->Position is the 3D position of the vertex.
        XMVECTOR Vector1 = XMVectorSubtract(XMLoadFloat3(&m_Polygon[m_Polygon.size() - 4].Position), XMLoadFloat3(&m_Polygon[m_Polygon.size() - 3].Position));   //  .--
        XMVECTOR Vector2 = XMVectorSubtract(XMLoadFloat3(&m_Polygon[m_Polygon.size() - 4].Position), XMLoadFloat3(&m_Polygon[m_Polygon.size() - 1].Position));   //  |

        XMVECTOR Normal = XMVector3Normalize(XMVector3Cross(Vector1, Vector2));

        m_Polygon[m_Polygon.size() - 4].Normal = XMFLOAT3(XMVectorGetX(Normal), XMVectorGetY(Normal), XMVectorGetZ(Normal));

        Vector1 = XMVectorSubtract(XMLoadFloat3(&m_Polygon[m_Polygon.size() - 3].Position), XMLoadFloat3(&m_Polygon[m_Polygon.size() - 2].Position));   //  --.
        Vector2 = XMVectorSubtract(XMLoadFloat3(&m_Polygon[m_Polygon.size() - 3].Position), XMLoadFloat3(&m_Polygon[m_Polygon.size() - 4].Position));   //    |

        Normal = XMVector3Normalize(XMVector3Cross(Vector1, Vector2));

        m_Polygon[m_Polygon.size() - 3].Normal = XMFLOAT3(XMVectorGetX(Normal), XMVectorGetY(Normal), XMVectorGetZ(Normal));

        Vector1 = XMVectorSubtract(XMLoadFloat3(&m_Polygon[m_Polygon.size() - 2].Position), XMLoadFloat3(&m_Polygon[m_Polygon.size() - 1].Position));   //    |
        Vector2 = XMVectorSubtract(XMLoadFloat3(&m_Polygon[m_Polygon.size() - 2].Position), XMLoadFloat3(&m_Polygon[m_Polygon.size() - 3].Position));   //  --.

        Normal = XMVector3Normalize(XMVector3Cross(Vector1, Vector2));

        m_Polygon[m_Polygon.size() - 2].Normal = XMFLOAT3(XMVectorGetX(Normal), XMVectorGetY(Normal), XMVectorGetZ(Normal));

        Vector1 = XMVectorSubtract(XMLoadFloat3(&m_Polygon[m_Polygon.size() - 1].Position), XMLoadFloat3(&m_Polygon[m_Polygon.size() - 4].Position));   //  |
        Vector2 = XMVectorSubtract(XMLoadFloat3(&m_Polygon[m_Polygon.size() - 1].Position), XMLoadFloat3(&m_Polygon[m_Polygon.size() - 2].Position));   //  .--

        Normal = XMVector3Normalize(XMVector3Cross(Vector1, Vector2));

        m_Polygon[m_Polygon.size() - 1].Normal = XMFLOAT3(XMVectorGetX(Normal), XMVectorGetY(Normal), XMVectorGetZ(Normal));

```

As you can see I'm using DirectXMath Library to calculate everything, I just calculate the normals for the last square(4 vertices distributed in clockwise order).

# Answer
> 0 votes
There was one mistake in my code and one issue.

The mistake was what DMGregory mentioned in the comments, each vertex in my vertex buffer had four copies of itself, which was causing me issues to calculate normals. So after fixing it to just use one copy of each vertex, I could calculate the normals more clearly.

The issue was that the light wasn't having a smooth transition at all. The reason behind this is that each normal vector needed to be composed from an average of the cross product vectors between neighbour vertices.

This is the current state of my terrain lighting: Which also leads me to believe that the amount of averages that one can take between neighbour vertices impacts directly the quality of the ligthing over a mesh.

---
Tags: c++, directx, hlsl, directxmath
---


# Question
Title: In what ways do lawyers and others involved in the legal field impact game development?
Most people have a general idea about what programmers, artists, designers and musicians do in the industry, but I’ve seldom heard about how the law and lawyers impact game development.

I’m especially interested in knowing how lawyers can affect positive outcomes in game development, and if there are any examples of lawyers or others with legal backgrounds who have been involved in one of the more traditional game development roles.

# Answer
> 19 votes
Lawyers rarely have creative influence on the game itself. But they still fulfill two important jobs in the game industry.

The first is intellectual property (IP) law. Games and all their individual assets are IP which is protected by copyrights, trademarks and sometimes patents. Lawyers are required to advise development teams how to not violate the IP of others and how to prevent others from violating their IP. And keep in mind that games are almost always sold internationally nowadays, which means that an IP lawyer worth her money should not just know about the IP law in the state she is licensed in but also have a vague idea about how IP laws differ around the world.

The second is contract law. Many game developers are regular employees, and employment law is a whole legal can of worms in itself. But the basics of labor law are usually accessible enough to legal laypeople that lawyers aren't strictly required until there is an actual dispute. And if there is one, then there is usually not much about those cases which is gamedev-specific. But there are also a lot of game developers who don't collaborate in regular employer-employee arrangements. The game industry does a lot of freelance contracting and b2b contracting which require non-standard contracts. Especially considering that game developers sometimes form agreements which are unusual in other industries, like work-for-work or revenue share. Those contracts need to be complicated and non-standard to cover all possible situations, which makes it important to consult contract lawyers. And if those lawyers have a good idea about the realities of game development and game business, then that can be really useful.

# Answer
> 11 votes
I worked with the legal team at a Chinese game developer/publisher and one important role they played was to help with cease-and-desist and litigation, as IP theft is a pretty big problem there. One of our RPGs was copied lock, stock and barrel, with even the in-game stats were exactly the same as ours. And of course we had to keep our Western colleagues in the loop on all of this, too.

Another important thing that our legal team did handle licensing. We purchased the rights to use a very expensive game engine, with a zillion lines of code and a huge price tag, and the contract for it was fittingly enormous. So in addition to reading through it with a fine-tooth comb, they also conducted research to understand best practices, what they could and should negotiate, etc. I suppose that had something of an effect on the games we used it for.

# Answer
> 1 votes
### Politicians can pass laws that affect video games.

Many politicians have backgrounds as lawyers, and sometimes the laws that they pass affect video games. For instance, the GDPR would affect how online games that operate in the EU handle their player data, and there have been a number of investigations by legislative bodies into the addictive effects of lootbox-based microtransactions with the intent of looking into legislating regulations on them. While they wouldn't be working on the behalf of any particular gaming company, they would definitely have an impact on game development through the creation of the legal regime within which the games are designed.

---
Tags: legal, game-industry
---


# Question
Title: How can I drag a prefab into sceneview and put it into a parent node?
Currently I'm doing like this

```
foreach (var obj in DragAndDrop.objectReferences)
                {
                    GameObject go = GameObject.Find(obj.name);

                    if (go != null)
                    {

                        GameObject parent = GameObject.Find("Parent");
                        if (parent == null)
                        {
                            parent = new GameObject();
                            parent .name = "Parent";

                        }
                        go.transform.SetParent(temp.transform);
                    }
                }

```

However, I try to drag something with the same name and it will be instantiated by other name(like A(1) rather than A), I can't find it with its name.

Also I try to create an instance by my own and put it to my parent node by code when I drag something into scene view. However, it seems unity will create an instance by itself so I will have two copies of instance in the scene view.

So how can I get the instantiated objects and put them to my parent node?

# Answer
> 1 votes
Eventually, I found two solutions.

```
if (currentEvent.type == EventType.DragExited){
    var goes = Selection.gameObjects;
    for (int i = 0; i < goes.Length; i++){
        DoSomething();
    }
}

```

```
if (currentEvent.type == EventType.DragExited){
    var objects = Object.FindObjectsOfType<MyScript>();//every prefab has MyScript component
    for (int i = 0; i < objects.Length; i++){
        DoSomething();
    }
}

```

Then you can get the instances of prefabs that the user drags into the scene view.

---
Tags: unity
---


title: Physics and unit size to feet

text:
# Question
Title: Physics and unit size to feet
I'm dropping a object 1353 feet from a building. I can get the time(t) it lands with manipulating the total displacement of a object(/\x).

---

Gravity is 32 feet/s^2

While doing physics, kinematics or projectiles like above do not return the right results. I cannot rely on the physics which is the real world result in a game. One unit equals how many feet in DirectX? How do you put physics of the real world into a game? How can I convert 1353 feet to how many units...

# Answer
> 1 votes
A unit in DirectX is whatever you want it to be. Meters, feet, microns, screen-pixels, light-years... whatever makes sense in the context of the scene you are rendering. Just make sure you scale any assets you import so that they are the correct scale for your preferred unit-length.

If you then add real-world physics, you have to make sure that you also use the same unit of length in your physics systems. So when you decide that one unit is one foot, then you have to take earth gravity not as 9.81 (m/s²) but as 32.17 (feet/s²). So you seem to have that part correct.

But calculating gravity in a vacuum is relatively simple. What's not so simple to simulate are the aerodynamic forces affecting an object falling through an atmosphere. There are just too many variables which affect the trajectory of flying things in the real world. Any formulas you find are usually just approximations which quickly fall apart in certain edge-cases we observe in reality. For example, consider cases where aerodynamic forces outweigh gravitational forces. Like a leaf getting blown off a tree by an autumn storm. Or a paper airplane. What makes these objects even harder to predict is that they are flexible. Aerodynamic forces affect their shape, which in turn affects their aerodynamic properties. So you have a chaotic system. Good luck predicting those with just a simple formula.

So when you got measurements of falling objects taken in the real-world and want to replicate them as accurately as possible in a virtual environment, then you have quite a challenge ahead of you. You have to create a full-fledged simulation of air-flows, which is a very specialized field. And even the most accurate simulation models (those which are far too slow to calculate in real-time) *still* include a couple inaccuracies which results in slight differences between simulated results and experimental results.

And it's rarely useful for games to go into such detail. Even games like *Kerbal Space Program*, which try to model physics accurately, take a lot of shortcuts and simplifications when it comes to aerodynamics. Which lead to results which are not 100% realistic, but easier to program, quicker to calculate and most importantly easier to understand for the player.

---
Tags: physics, directx, kinematic
---


# Question
Title: Can UE5's Nanite be applied to the low poly aesthetic?
It sounds like a bit of a stupid question; why would anyone want technology for triangle-per-pixel rendering in a low poly aesthetic game? The answer is that Nanite offers continuous LOD with high performance. For my game, I want the geometry to look good and have a consistent level of detail from both close-up and far away while not relying on the graphics card being able to swap and hold the entire high-res model in memory. This situation is warranted in the case of extreme size-changing mechanics (detail is a matter of player scale/distance!) and dense, varied scenes (enormous space stations, BLAME!, etc.) where decomposing the model into smaller elements presents a serious challenge.

The questions, then, are:

* Can Nanite be adapted to target larger triangle sizes?
* Can Nanite, under the above condition, run on older/weaker hardware than it otherwise could?
* Is this possible from within the UE5 GUI, or does it require modifying the source code? If so, to what extent?

# Answer
> 2 votes
**Yes to all, but with caveats.**

Looking at the Nanite deep dive slides, you can see that the continuous LOD breakthrough is in how meshes are decomposed into a DAG of triangle (or cluster-) clusters, where the cluster boundaries are *not* shared between levels - hence forming a DAG instead of a tree. Aided by the some clever error metrics, this results in a very fast CLOD solution which can be adapted to any desired triangle size.

However, part of the efficiency of the whole Nanite pipeline comes from the fact that cluter\<-\>triangle transitions at the pixel scale don't pop. Moving to larger triangles would introduce the need for a geomorphing or blending operation that would balloon rendering cost. Then again, for a sufficiently low poly aesthetic, the reduced number of triangles to draw would make up for it.

For scaling to lower-end hardware, the entire virtualized geometry process relies on the modern programmable pipeline. In principle, you could write a CPU implementation of the CLOD system, but it would not be as efficient per-vertex as Nanite. That aside, if the issue is just the available FLOPs, Nanite scales very well and and would benefit more from a reduced number of instances and larger clusters/triangles than lower triangle counts.

**DISCLAIMER:** I am an amateur gamedev, and Nanite is breakthrough technology. It is entirely possible I have some details incorrect. Please read the slides for yourself - they are very good.

---
Tags: unreal-5
---