# Question
Title: Find coordinates in one space from another
I'm trying to determine what coordinates are in one space when given a point in another space.

For example, I've got a Matrix4x4 that I can use to convert a point in unity's world space to a skewed space defined by that matrix.

The inverse of this matrix returns me to the original world space.

```
private float HALF_SQRT_3 = Mathf.Sqrt(3) / 2;

private Matrix4x4 mWorldToSkewGrid = new Matrix4x4(
    new Vector4(HALF_SQRT_3, 0, 0, 0),
    new Vector4(0, 1, 0, 0),
    new Vector4(Mathf.Cos(Mathf.PI / 3) * HALF_SQRT_3, 0, Mathf.Sin(Mathf.PI / 3) * HALF_SQRT_3, 0),
    new Vector4(0, 0, 0, 1)
);

private Matrix4x4 mSkewGridToWorld = mWorldToSkewGrid.inverse;

```

I'm attempting to figure out how I can go about getting the coordinates of the skewed space AT the default world space rather than transforming a point in default space to the skewed space.

I assumed it was something similar to how unity converts a screen point into a world point. Something like this:

```
Vector4 p = mSkewGridToWorld * new Vector4(defaultWorldPos.x, defaultWorldPos.y, defaultWorldPos.z, 1.0f);
p.w = 1.0f / p.w;
p.x *= p.w;
p.y *= p.w;
p.z *= p.w;

```

Where `p` is intended to hold the position of `defaultWorldPos` but in the skewed coordinates where it would overlap in the skewed space.

Edit: Below is an example of the "default world space" in green being transformed into the "skewed space" in red, represented by a 10x10 grid. Rather than transforming say the grid cell 5x5 to the other space resulting in the point moving and being still at 5x5 in the skewed space, I want to know what skewed point is under 5x5, in this example it would be something like 2x6 in the skewed space.

# Answer
> 0 votes
Personally, I find that thinking in terms of "reference systems" makes this sort of reasoning a bit easier than thinking about transforming the space.

If you know the coordinates of the point in world space, and are trying to figure out what the coordinates of that same point would be from the grid's reference system, it's just

`pointInGridSpace = worldtoGridMatrix * pointInWorldSpace`.

# Answer
> 0 votes
Unity usually doesn't require you to work with transformation matrices yourself, because the Transform component abstracts them away for you. If you want to translate a point from the coordinate system relative to one component to another, you can use `transform.TransformPoint(Vector3)` with the transform of the first gameObject to transform a point from local space to world space, and then `transform.InverseTransformPoint(Vector3)` with the transform of the second gameObject to transform that point into the coordinate of the second object.

And by the way, if the whole reason why you want to do this is because you want to convert between screen pixels and world position, then you can do that with some useful utility methods of the Camera component rendering the scene. Like `Camera.main.ScreenToWorldPoint(Vector3)` and `Camera.main.WorldToScreenPoint(Vector3)`. Or if you want to find out which collider the mouse cursor is currently pointing at: `Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out RaycastHit hit);`

---
Tags: unity, c#, matrix, transformation
---


# Question
Title: Walk on any surface, how to make a defined space around character not pass through any collider
I'm working on an 3D insect/spider controller that will walk on any time of surface. Currently my character scan the environment around him by shooting a very big number of spherecasts and based on hit points data and some weights multiplication for precision improvements, it calculate a new rotation for the player. the new position direction is calculated based on camera forward projected on character's up dir and the actual speed is reduced based on difference between new rotation and old rotation of the character( the more we rotate, the less we'll travel).

Currently this solution works good but I would like to upgrade the controller to do more: I want to have a defined space, a disk, around player position and i want the controller to makes sure no matter where and how is travelling, this disk will always be outside any surface collider. The bottom image is describing the situations that I want to avoid and what would be a better approach for the character (it is 2d but my controller walk in a 3d space and the blue line represent the disk I'm talking about).

I'm not really sure how to do it correctly and I feel there exist a good mathematically formula for this but I'm not sure where to look.

Any help will be appreciated.

# Answer
> 1 votes
While not really a perfect solution, you can sort of do this with the Physics.Overlap\[colliderType\] and ComputePenetration functions. This gives you the shortest distance (and direction) that the collider you use for the overlap needs to be moved to stop overlapping.

It can cause weird behaviour when moving really fast or dealing with very narrow walls and such, as you are only testing the final position of the collider, not "the movement" (as would happen if you were doing a cast of some sort), but it's often good enough.

Below is some code that I'm using in my own project, mostly based off the example in the ComputePenetration docs.

public static void DoNotGoIntoWalls(Collider collider, Transform object_transform, int layerMask){
    //It is very important to correct for rotations and scales, since all the collider properties are local space
    //and the physics functions require global space
    int numberOfCollisions=-1;
    if(collider is CapsuleCollider){
        CapsuleCollider capsule = (CapsuleCollider) collider;
        Vector3 height;
        if(capsule.direction == 0){
            height = collider.transform.localToWorldMatrix.MultiplyVector(new Vector3(capsule.height/2f - capsule.radius, 0, 0));
        }
        else if( capsule.direction ==1 ){
            height = collider.transform.localToWorldMatrix.MultiplyVector(new Vector3(0, capsule.height/2f - capsule.radius, 0));
        }
        else{
            height = collider.transform.localToWorldMatrix.MultiplyVector(new Vector3(0, 0, capsule.height/2f - capsule.radius));
        }
        Vector3 p0 = collider.gameObject.transform.localToWorldMatrix.MultiplyPoint(capsule.center) + height;
        Vector3 p1 = collider.gameObject.transform.localToWorldMatrix.MultiplyPoint(capsule.center) - height;
        float radius = collider.gameObject.transform.localToWorldMatrix.MultiplyVector(new Vector3(capsule.radius, 0, 0)).magnitude;

        numberOfCollisions = Physics.OverlapCapsuleNonAlloc(p0, p1, radius, colliderList, layerMask);
    }
    else if(collider is BoxCollider){
        BoxCollider box = (BoxCollider) collider;

        Vector3 center = collider.transform.localToWorldMatrix.MultiplyPoint(box.center);
        //express the size of the box in world units
        //the transform matrix is not enough, sadly
        Vector3 ext = collider.transform.localToWorldMatrix.MultiplyVector(box.size*0.5f);

        Quaternion inv = Quaternion.Inverse(collider.transform.rotation);
        ext = inv * ext;
        numberOfCollisions = Physics.OverlapBoxNonAlloc(center, ext, colliderList, collider.transform.rotation, layerMask);
    }
    else if(collider is SphereCollider){
        SphereCollider sphere = (SphereCollider) collider;
        Vector3 center = collider.gameObject.transform.localToWorldMatrix.MultiplyPoint(sphere.center);
        float radius = collider.gameObject.transform.localToWorldMatrix.MultiplyVector(new Vector3(sphere.radius, 0, 0)).magnitude;
        numberOfCollisions = Physics.OverlapSphereNonAlloc(center, radius, colliderList, layerMask);
    }

    for(int i = 0; i<numberOfCollisions; i++){
        Vector3 direction;
        float distance;
        if (colliderList[i]!=collider && Physics.ComputePenetration(collider, collider.transform.position, collider.transform.rotation,
                colliderList[i], colliderList[i].transform.position, colliderList[i].transform.rotation, out direction, out distance)){
                    object_transform.position += direction*distance;
                }
    }
}
```

---
Tags: unity, 3d, mathematics, movement, vector
---


# Question
Title: How to change GameObject position using new Input System?
I was asking myself if you could change the position of a game object with the input of the player, with the new input system.

That is, with something like this:

```
OnMove() {

//Code to change game object's position

}

```

I want to make a script where the position of the game object is changed to a specific position, based on the joystick value and the WASD keys. That is, there are multiple positions the game object can go to.

This is for a top-down game where a gameobject should go to differnt places around the player. Since this gameobject is parented to the player and the gameobject is always touching the player, positions from -1 to 1 are enough.

# Answer
I assume you already have an Input Action asset with an action "Move" of control type "Vector2" that has bindings for both the joystick and the WASD keys and that you added a PlayerInput component to your scene.

If your PlayerInput component is configured to "Send Messages", then your method needs to be on the same gameobject as the PlayerInput component and have a method which looks like this:

```
public void OnMove(InputValue value)
{
    Vector2 input = value.Get<Vector2>();
}

```

If your PlayerInput component is configured to use UnityEvents, then the method you bind to the Move action via inspector needs to look like this:

```
public void OnMove(InputAction.CallbackContext context)
{
     Vector2 input = context.Get<Vector2>();
}

```

The vector you receive has x and y components between -1 and +1. For keyboard keys and other digital input buttons, those will always be `1.0f`, `0f` or `-1.0f`. But joysticks are analog input devices which will deliver floating-point values anywhere in this range. So if you want to support both digital and analog input devices, you need to check for ranges, not for equality.

Now all you need to do is map the possible values of the input vector to specific positions and then set the `transform.position` to that position. I could go into further detail, but your question is too vague to tell what your actual requirements are in this regard.
> 1 votes

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


# Question
Title: How to organize game entities that are stored inside other entities?
In my GPS based game, there are certain structures the players can build that store units. For example, airbase structures store aircraft objects. Currently, the way I have this organized is the airbases and aircraft each have their own ID number. The aircraft also have a "homebase id" that stores the ID of the airbase they currently belong to. When the aircraft returns to base and "lands," the aircraft ceases being in a "flying" state, stops moving, and becomes invisible, on the location of the airbase. This works okay, but it's also kind of janky and I'm not sure it'll work in the future when I add aircraft carriers that store aircraft, troop transport planes and ships that store infantry units, etc.

I'm not very experienced in game design and I'm wondering if there is a better way I could do this.

# Answer
I'm not familiar with Java, but if I read this correctly, then the airplanes are all stored in the airbase, which means that if the airbase gets destroyed/removed, the airplanes will be deleted as well?

I think it works if destroying the airbase is the key objective, but if it's not intended, then I would make a global list and store the airplanes in there. They will still relate with the homebase thanks to the ID, but they're not forced to only persist if the airbase does.

Same also goes for the other sub-units to make a global list to keep them detached. Perhaps the units could also have a "parent garrison id" or "garrison type" (made up terms) so it can be decided by which unit type (an airbase or an aircraft carrier ect.) and which ID of that unit (in the case of multiple airbases or aircrafts) they're currently "landed" at.
> 0 votes

---
Tags: java, software-engineering, gameobject, hierarchy
---


# Question
Title: Shortest distance between edges of a circle and a rectangle?
I have different kinds ob objects. An object can either be a rectangle or a circle. I want to calculate the shortest distance between the edges of each two objects.

For two circles it's just the distance between the two center points, minus radius1 and radius2.

For two rectangles I found this answer, and it works really well: Efficient minimum distance between two axis aligned squares?

But how can I calculate the minimum distance between the edges of a rectangle and a circle?

# Answer
I found a solution, that fits my needs:

If the centre of the circle is at right angles to one of the sides of the rectangle, the distance is simply the distance between the centre of the circle to that side minus the radius of the circle.

Otherwise, I take the nearest corner of the rectangle to the centre of the circle and calculate the distance using the Pythagorean theorem. Here you also have to subtract the radius of the circle.

Note: This code doesn't check if the circle is inside the rectangle, or vice versa.

```
function getDistanceCircleRect(circle, rectangle){

    // x and y are the centre coordinates

    xC = circle.x;
    yC = circle.y;
    r = circle.width/2;

    xR = rectangle.x;
    yR = rectangle.y;
    wR = rectangle.width;
    hR = rectangle.height;

    topR = yR - hR/2;
    bottomR = yR + hR/2;
    leftR = xR - wR/2;
    rightR = xR + wR/2;

    if(yC >= topR && yC <= bottomR && ((xC+r) >= rightR || (xC-r) <= leftR)){

        d1 = Math.abs(xC - rightR);
        d2 = Math.abs(xC - leftR);

        min_distance = Math.min(d1, d2) - r;
    }
    else if(xC >= leftR && xC <= rightR && ((yC+r) >= bottomR || (yC-r) <= topR)){

        d1 = Math.abs(yC - topR);
        d2 = Math.abs(yC - bottomR);

        min_distance = Math.min(d1, d2) - r;
    }
    else{

        nextX = Math.min(Math.abs(xC - leftR), Math.abs(xC - rightR));
        nextY = Math.min(Math.abs(yC - topR), Math.abs(yC - bottomR));

        min_distance = Math.sqrt((nextX)**2 + (nextY)**2) - r;
    }

    return min_distance;
}

```
> 0 votes

---
Tags: 2d, collision-detection, mathematics, overlap2d
---


title: Input processing on the server-side

text:
# Question
Title: Input processing on the server-side
*The problem:* Let's say we want to create top down MMORPG in browser, and we started with implementing movement of your character. Okay, so how it works?

* Character gets inputs and compares if they are the same with the old frame, if they are different it sends to the server that inputs change. So if you press D and release after 0.1sec it will send 2 packets, when you pressed D and when you released it.

So far so good, but now on the server. How do we sync the server with a client? Okay

2 Options

1. Fixed timestep, we just process inputs in a while loop which will run at 60fps so it will be using the same fixed timestep as a client, but we need somehow fix the issue when you don't receive inputs.
2. We just store input A with client Tick, and wait for next input, if we receive next input we know it's a start so we know how many times we should play input A. Using B.clientTick - A.clientTick we know how many times we should process this input, but what if client modifies the clientTick on input B? perhaps 1) is better in this case.

The problem, we never know in advance when player releases D and in networking behavior it is not guaranteed that if the client press D and after 0.1sec release it, it will be same for server, in this case server will move more or less, if you receive release packet after 0.15sec, you can play one more frame and your positions on client and server will be not synced.

What are possible solutions? This is why i am asking you, i can't find proper solution.

Solutions i know:

1. Run client at fixed timestep (60fps) and send 60 packets a sec (or as fast as possible). This is not the best especially on TCP connection. This is why i want send only packets when player inputs change.
2. All packets the client send can play at max 3 times and client will send packet if you change inputs or every 3rd frame (considering it is in fixed timestep). Server will store last 3 inputs in buffer so if let's say you receive: CTick: 0 - Input D - Server Tick 0 CTick: 3 - Input D - Server Tick 3 CTick: 5 - Release D - Server Tick 6 (it will must rewind one frame because Release D was released after 2 frames from last packet not 3 frames)

But problem can be here Tick: 0 - Input D - Serve Tick 0 Tick: 3 - Input D - Server Tick 4 (Now we have gap and one frame is not played on server)

* To overcome this problem we can replay "last received input" and if we get same input next, we can just throw it. If we get different input we rewind the position

I feel like whole this implementation is quite more complex than it should be and I am not sure if this is proper solution, what are your thoughts or suggestions?

# Answer
Thanks to @DMGregory who help me to solve this issue.

The final approach

* The client sends inputs when they change and current tick/Ack
* Server receives input and stores it in a buffer
* In server-tick, the server will replay the last input received until new input is received and increase the simulated tick by 1
* When new input is received, it compares the client tick/ack of new input and if it is lower or higher than the simulated tick, the server will instantly play missing frames or rewind the last X moves (should be limited to a certain value) and play them with the received input. If the server must rewind more than 4 frames, it will not do so and it will force the client to update its position smoothly (Also known as rubberbanding?)
> 0 votes

---
Tags: 2d, networking, game-loop
---


# Question
Title: Reduce coupling between various singletons
I'm working on a game that makes use of several singletons such as a game manager, audio manager, and a level loader. The game manager I created has references to the audio manager, level loader, and the player, so there's a high degree of coupling that I'm not sure is optimal:

```
private Player currentPlayer;
private CinemachineVirtualCamera CVC;
private AudioManagerScript AM;
private LevelLoader LL;

```

Is there a better way to write this to reduce coupling or is this kind of unavoidable?

# Answer
> 3 votes
Tight coupling between classes can often be avoided by using UnityEvents.

For example, let's say you want to play a sound when the player attacks. The tightly-coupled code would look something like this:

```
class Player : MonoBehaviour  {
    void Update() {
        if(Input.GetKeyDown("Attack")) {
             AudioManagerScript.Instance.PlayAttackSoundFor(gameObject);
        }
    }
}

```

This code has a tightly-coupled dependency between AudioManagerScript and Player. We don't want that. So what we can do instead, is this:

```
class Player : MonoBehaviour  {

    public UnityEvent<GameObject> onAttack;

    void Update() {
        if(Input.GetKeyDown("Attack")) {
             onAttack?.Invoke(gameObject);
        }
    }
}

```

Now the inspector for the player has an event "onAttack" which looks similar to this (reused a screenshot from another answer of mine to a different question).

We can now use the inspector to bind this event to any number of methods from other gameObjects. We can use any method for this which receives a GameObject as their first parameter or which has no obligatory parameters.

The nice thing about this is that the Player doesn't need to know which (if any) other objects react to it attacking. And we can add as many objects as we want. For example, we could also delegate the spawining of a projectile to a separate class "ProjectileSpawner" that also subscribes to this event. And we can later refactor that class to use an object pool.

This also mean that the AudioManagerScript doesn't need to be a singleton anymore. It would be possible to have multiple instances of AudioManagerScript in the same scene and decide which one to use for what by binding the events of different objects to different managers.

And if the AudioManagerScript doen't really do more than calling the Play() method of the right AudioSource, then you might not even need the audio manager anymore, because you can just bind the Play method of the AudioSource to the event directly.

---
Tags: unity, c#, software-engineering
---


# Question
Title: Seams on tiled wall after lightbaking in unity
I spent several days now trying to fix the seams in my unity scene whenever I hit the lightbaking button.

My setup is a wall out of different parts created in blender and then stitched together in unity.

I already tried to change every single setting in the Lighting\>Scene window. Nothing seams to fix the problem -\> after baking there are light seams between the wall parts and when I zoom out the seams are dark/black. See screenshots, they probably explain best.

# Answer
> 0 votes
Try using the baked global illumination debug view to see what the texel density. You can also check UV charts to see if there is a hard break at the seams. Your lighting settings look good, I suspect it's an issue with the models themselves.

---
Tags: unity, tiles, lightmap, seams
---


# Question
Title: Delay confirmation pop-up for in-app purchase
I'm trying to implement IAP in my game where the user can buy 100 coins. I have used this video tutorial to implement the IAP and this works fine. I want to implement a functionaltiy where once the purchase has been made, a panel opens up stating that the purchase was successful. This is the code in the IAP manager that handles a successful purchase:

```
public void Coin_100()
{
    BuyProductID(coin_100);
}

public PurchaseProcessingResult ProcessPurchase(PurchaseEventArgs args)
{
    if (String.Equals(args.purchasedProduct.definition.id, coin_100, StringComparison.Ordinal))
    {
        GameManager.currentCoinScore += 100;
    }
}

```

And here is the PurchaseButton script and I call the Coin100 method when the user click on the purchase button:

```
public void Coin100() {
    IAPManager.instance.Coin_100();
    PurchaseSuccess.SetActive(true);
}

```

The issue is that as soon as the the button is clicked the panel opens up. Is there any way to delay activating the panel i.e once the purchase is successful and not as soon as the button is clicked. I thought of adding a static bool to the IAP script and then in the Update function of the PurchaseButton script, check if this bool is true and then activate the panel. But this effects the performance. Can someone please help me with this?

# Answer
> 1 votes
First, remove the "PurchaseSuccess.SetActive(true);" from Coin100 method. Create a new public method called ShowSuccessDialog and add the code there.

Then, in your IAP manager, create a new event, and add your GameManager function as a listener for the event.

```
UnityEvent m_PurchaseSuccess = new UnityEvent();

void Start()
{
    m_PurchaseSuccess.AddListener(FindObjectOfType<GameManager>().ShowSuccessDialog);
}

```

Then the event can be invoked at the proper time and the listening method will be executed. In your PurchaseProcessingResult, after adding 100 coins, invoke the event like this:

```
m_PurchaseSuccess.Invoke();

```

The ShowSuccessDialog is listening for the event to fire, then the dialog should show once the purchase process is finished.

I haven't tested this code, but here's the documentation on Unity events if you're still stuck: https://docs.unity3d.com/ScriptReference/Events.UnityEvent.html

---
Tags: unity, c#, gui, in-app-purchase
---


title: Loading WAV and MP3 files with LWJGL 3?

text:
# Question
Title: Loading WAV and MP3 files with LWJGL 3?
Whenever I research audio in LWJGL 3, they always use STB which can only load Ogg files. All of my audio files are in either WAV or MP3 format, and it would be annoying to have to convert all of them. Is there some other library or method I can use that would allow me to load these file formats?

# Answer
In LWJGL2 there was a loader class called `org.lwjgl.util.WaveData`, used for *\*.wav* files, that is missing in LWJGL3. You can simply download the source of this class from the legacy LWJGL website and add it to your project. Replace `org.lwjgl.LWJGLUtil.log()` with `System.out.println()` in the source since `LWJGLUtil` does not exist in LWJGL3.

Also, if you are on JDK9 or later, you have to download three source files from the package `com.sun.media.sound` in JDK8 and put them into your project. The package needs to be renamed or you will get a loading error otherwise, since that package still exists in the current JDKs but is hidden.

Such classes are:

* `com.sun.media.sound.WaveFileReader`.
* `com.sun.media.sound.WaveFileFormat`.
* `com.sun.media.sound.SunFileReader`.

Then you can write:

```
WaveData data = WaveData.create(url);
AL10.alBufferData(bufferHandle, data.format, data.data, data.samplerate);

```
> 0 votes

---
Tags: assets, audio, loading, lwjgl3, format
---


# Question
Title: Looping through children in a foreach loop
I have a gameobject with a bunch of empty gameobjects as children that I want to use as spawn positions.

I want to loop through each of these positions and have a certain amount of probability that an object spawns.

How could I write a foreach loop that takes the parent object and loops through all its children like it would with an array?

# Answer
By itself, the transform class implements the **IEnumerable (with Transform as the generic type)** interface, which allows you to use a **foreach** with a transform as the interable object. You could also use a normal for loop, using **Transform.GetChild(int)**. Examples:

```
foreach(Transform child in transform)
{
    /// All your stuff with child here...
}

for(int i = 0; i < transform.childCount; i++)
{
    /// All your stuff with transform.GetChild(i) here...
}

```

Hope it helps.
> 4 votes

# Answer
A good coding practice would result in the following code:

```
[SerializeField]
GameObject gb;    //outside the function

foreach (Transform child in gb.transform)
{
    Debug.Log("Name Of Child " + child.transform.name);
}

```
> 0 votes

---
Tags: unity, gameobject, hierarchy
---


# Question
Title: How can I create a dice toss that results in a specific value?
I am trying to create a 3D dice for a game. Normal dice has been created by setting cube for dice with Rigidbody and apply force to throw a dice.

Now the problem is, the user wants to give a value 1 - 6 in the text box then they will press the roll button. The dice have to rotate and need to show the dice value as the user enters in the text field once it stops rolling.

For example:

1. In the Input box the value entered as 5,
2. Now the dice want to roll on the table and show the value as 5.

Anyone, please help me to solve this

Thanks in Advance

# Answer
> 4 votes
I wouldn't rely on the physics for this. If you have one dice, then you should just have some prebaked animations. You can have more than one animation per outcome to add variation. If you have multiple dice then we can take a different approach. Prebake several animations (you can use physics and record the keyframes) for rolling the dice. For each dice, mark the side that ends up face up at the end of the animation. When the user rolls the dice, select a random animation (multiple animations so it's not obvious they are prebaked) then find the side of each dice to set that ends faceup at the end of the animation. Find where that face is at the start of the animation. Rotate the dice as a child object before the animation (or swap texture UVs) such that the side you want up is in the correct position before the animations starts. In this way you can rig the dice roll.

For example let's say normally the 2 ends up on top for Animation A. At the start of the animation, the 2 side is facing in the -y direction. The user picks the 1 side. Rotate the dice at the start of the animation so the 1 side is facing the -y direction. Now at the end of the animation the 1 will end up on top.

It's difficult to explain clearly but hopefully you get what I'm trying to say. If not, comment.

# Answer
> 3 votes
Revisiting this question, I just got a new idea: you could make a physics simulation in the background and cache the result, determine which face ended up, put the textures in the right place and play the simulation back to the user.

# Answer
> 2 votes
If you are determined to do this strictly with physics in unity with rigidbodies..This is a somewhat silly answer but what about making a "loaded dice"?

Make a die that is comprised of 3x3x3 set of cubes. Each cube's mass can be modified via a script that is interacting with your input fields from your UI with C#.

If a user inputs "1" for example and the desired 3D dice roll result is a "1" you would make your UI input script look for "1" and as a result increase the mass of the 9 cubes on the side that your "6" is on , or whichever side is opposite to the "1".

This weighting process is not guaranteed to work but im sure if you adjusted the parameters enough you could find a nearly optimal solution using physics.

Hope this helps! I like the other replies as well. Very fun problem here..

EDIT: My father is a machinist and has told me that weighting the corners of the dice was a tactic used by fabricators of these "loaded dice". I hope this helps.

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


# Question
Title: How to use scriptable objects for class selection?
I'm trying to make a class selection system for learning and I've decided to use scriptable objects for the classes since it seems like scriptable objects are good for that(?) however I start to get confused when it comes to setting the class and using the values.

This is my scriptable object for a class.

```
[CreateAssetMenu(fileName = "New Class", menuName = "Classes/New Class")]
public class BaseClass : ScriptableObject
{
    public float health;
    public float walkSpeed;
    public float fallSpeed;
    public float jumpForce;

    public string displayName;

    public List<BaseAbility> abilites;
}

```

I currently have 2 instances one is called "No Class" which is just default values for when no class is selected (which I dragged into the Player component so it's there when the game starts) and then I have a Warrior one.

This is my player script which uses an event to set the players class when they press a button

```
public class Player : MonoBehaviour
{
    public BaseClass selectedClass;

    void Start()
    {
        ClassSelectButton.OnClassSelected += SetPlayerClass;
    }

    void SetPlayerClass(BaseClass newClass)
    {
        selectedClass = newClass;
    }
}

```

And here's where I start to get confused. So I set the players class to the new class in the Player script, but now I need to get the new values in the scripts that need them like my movement script so my solution was to just use the same event.

```
    public BaseClass playerClass;

    void Start()
    {
       playerClass = GetComponent<Player>().playerClass;
        ClassSelectButton.OnClassSelected += (BaseClass newClass) => { playerClass = newClass; };
    }

    void FixedUpdate()
    {
        rigidBody.MovePosition(transform.position + moveDirection * playerClass.walkSpeed * Time.fixedDeltaTime);
    }

```

Although this works I feel like it's not a good approach (perhaps I'm wrong though) so I'm trying to figure out other methods I can do.

# Answer
> 0 votes
**Don't** have everything in your game listen to the ClassSelectButton directly! On that path lies headaches. If you ever decide you'd like to change how classes are selected in the future (or let people advance to subclasses halfway through the game, or anything of that sort), you'll have to update every single consumer.

There are two ways to do this which I've used in different contexts, and the advantages of each.

## Option 1: Store a handle to Player

Your movement script wants to know what the player's class is, and it wants to always have the current value of that. Have it look up the current value every time it needs it.

```
class Movement
{
    private Player Player;

    private BaseClass PlayerClass => this.Player.playerClass;

    void Awake()
    {
        this.Player = this.GetComponent<Player>();
    }

    void FixedUpdate()
    {
        rigidBody.MovePosition(transform.position + moveDirection * this.PlayerClass.walkSpeed * Time.fixedDeltaTime);
    }
}

```

Advantages of this approach relative to option 2:

* It's intuitive. I didn't have to add any API/documentation links to explain what I did here.
* It's easy to implement - you can re-use half the code in the sample for everything else that consumes PlayerClass.
* It's easy to maintain - the property will always be correct, and will update instantly. No need to worry about accidentally changing class and forgetting to notify the consumers.

## Option 2: Dispatch an event within the event

```
public class Player : MonoBehaviour
{
    public BaseClass selectedClass;

    void Start()
    {
        ClassSelectButton.OnClassSelected += SetPlayerClass;
    }

    void SetPlayerClass(BaseClass newClass)
    {
        if(selectedClass != newClass)
        {
            selectedClass = newClass;

            // Tell all the other classes to update using the SendMessage API. See https://docs.unity3d.com/ScriptReference/Component.SendMessage.html for details.
            SendMessage("ClassChange", newClass);
        }
    }
}

```

```
class Movement
{
    private float WalkSpeed;

    void FixedUpdate()
    {
        rigidBody.MovePosition(transform.position + moveDirection * this.WalkSpeed * Time.fixedDeltaTime);
    }

    void ClassChange(BaseClass newClass)
    {
        this.WalkSpeed = newClass.walkSpeed;
    }
}

```

Advantages of this approach relative to Option 1:

* Easy to add visual/audio cues on class change, since the event already exists.
* Decouple movement from character classes - you can re-use the movement script on an object that doesn't have a character class without getting NullReferenceExceptions.
* You can see and change the walk speed in the inspector of the movement script while debugging, without needing to open up the character class data.
* Very slightly more performant (like, *very* slightly. You won't notice and neither will your players)

# Answer
> -1 votes
Basically, you can use the same event of course. Multiple objects can subscribe to the same event and do their respective things. For example, EnemyDied is an event and Sound Manager along with ScoreManager subscribes to this event.

When OnEnemyDied() is called within these classes, SoundManager plays the sound and ScoreManager updates the score using the same event which is the correct approach so no need to worry about another approach.

Using the same event isn't the wrong approach, in fact, it is probably a very good approach if not the best (I am not the expert yet). However, try to use listeners so each class can do its own unique thing upon an event that it is subscribed to.

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


# Question
Title: Rendering Objects with dynamic data in OpenGL
I am currently working on a OpenGL Renderer in C++. I have created a base *Object* class that looks a bit like this:

```
class Object
{
...
private:
    std::vector<Vertex> vertices;
    std::vector<uint16_t> indices;
};

```

*Vertex* is a simple struct containing the data of a vertex.

```
struct Vertex
{
    glm::vec3 location;
    glm::vec4 color;
};

```

Anything being rendered is considered an *Object*. The vertex data of each Object needs to change every frame, so my vertex buffer allocates a certain amount of memory on startup and the vertex data of all Objects is uploaded to the GPU each frame using glBufferSubData. I then have a *Scene* class which stores a vector of all the existing *Objects*. The Renderer merges the vertex data of each object every frame like this:

```
std::vector<Vertex> all_vertices;
std::vector<uint16_t> all_indices;

for (const Object* object : objects)
{
    all_vertices.insert(all_vertices.end(), std::make_move_iterator(object->get_vertices_begin()), std::make_move_iterator(object->get_vertices_end()));
    all_indices.insert(all_indices.end(), std::make_move_iterator(object->get_indices_begin()), std::make_move_iterator(object->get_indices_end()));
}

draw(vertices, indices);

```

My concern here is the performance of these operations, especially all the heap allocations by std::vector. The Renderer can't know how many total vertices and indices there are, since this could change any frame

# Answer
You could use `std::vector::reserve` to reserve the same amount of space that you have determined the GPU will need. Then use `std::vector::clear` in each frame before you start pushing things in.

This way you only allocate from the heap once, as long as you don't push more than you reserved.

It's worth noting that you can override the `std` allocator and provide your own one if you want to take control of `std` container allocations. But that's another topic for another question. As is whether you should even use `std` containers.

Top tip: measure performance before and after making optimisation changes to check that your assumptions are correct.
> 1 votes

---
Tags: opengl, rendering
---


# Question
Title: Alpha blending only working on 5 of 6 sides on a cube
I'm rendering a cube with a texture mapped to all sides of it and somehow the alpha channel from the texture isn't being applied on one side of the cube. all other sides are rendered properly (transparent) but there's one side that is completely opaque. I've tried to change ordering of the vertices being used to render the quad and played around with tweaks on the texture coordinates but nothing seems to take effect.

This is the setup of the texture blending

```
glClearColor(0.1f, 0.1f, 0.1f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glEnable(GL_DEPTH_TEST);

// bind Texture
glBindTexture(GL_TEXTURE_2D, texture);
// set the texture wrapping parameters
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
// set texture wrapping to GL_REPEAT (default wrapping method)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
// set texture filtering parameters
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

```

The code is gathered from the LearnOpenGL repository and there are some files included to simplify loading shaders and textures. The code builds with CMake on Ubuntu 22.04 as well as on Arch Linux and leverages GLFW3 and GLM.

The vertices are specified as:

```
float vertices[] = {
// positions            // normals          // texture coords
-0.5f, -0.5f, -0.5f,    0.0f, 0.0f, -1.0f,  0.5f, 0.75f,
 0.5f, -0.5f, -0.5f,    0.0f, 0.0f, -1.0f,  0.0f, 0.75f,
 0.5f,  0.5f, -0.5f,    0.0f, 0.0f, -1.0f,  0.0f, 0.25f,
 0.5f,  0.5f, -0.5f,    0.0f, 0.0f, -1.0f,  0.0f, 0.25f,
-0.5f,  0.5f, -0.5f,    0.0f, 0.0f, -1.0f,  0.5f, 0.25f,
-0.5f, -0.5f, -0.5f,    0.0f, 0.0f, -1.0f,  0.5f, 0.75f,

-0.5f, -0.5f, 0.5f,     0.0f, 0.0f, 1.0f,   1.0f, 0.75f,
... continued...

```

In the image above, it's apparent that the leftmost quad is opaque, while the other sides are transparent (as expected).

Is there something simple that I'm missing?

# Answer
The issue is in the drawing order of the triangles and the depth buffer. The first drawn triangle uses the alpha blending against the background color.

```
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

```

But even if it draws a transparent pixel, the depth buffer is updated with its Z position.

So when you draw a new triangle behind the exiting front one, it CANNOT be drawn because the depth buffer Z is lower than the current drawn Z.

***Solutions***

1.Disable depth buffer before rendering the transparent triangles. That way, all the triangles will be drawn independently the order you draw them. And reenable it when you finish.

```
glDisable(GL_DEPTH_TEST);
/* draw the translucent cube here */
glEnable(GL_DEPTH_TEST);

```

2.Sort the faces (triangles) to be drawn from back to front (aka painter's algorithm) using the distance to the camera position as the reference.

3.Discard the transparent pixel in the Shader with `discard()`. That way depth buffer is not updated and triangles behind this one can be drawn filling the holes (discard pixels). This only works for transparent, not for alpha blending, translucent object. It can impact performance.

**Recommendations** Option 2 is the best one, but if you move the camera, or move/rotate the object. The faces need to be reordered. The vertices that are part of a face don't need to be sorted.

**Note about CULL\_FACE** I guess that you are drawing the back face of some faces. So GL\_CULL\_FACE is disable. You don't need to sort the triangles of a face to look to the camera, you can just disable CULL\_FACE to draw them.
> 1 votes

---
Tags: opengl
---


# Question
Title: Render texture not rendering camera output correctly
I have a strange problem that I am not sure if it is a bug from Unity or not. I have render texture that renders camera output to a raw image. Camera looks at a object that consists of 2 parts: the Ball and a round objects in front of the ball. The render texture doesn't always render the object in front of the ball, but it seams that this happens randomly sometimes object is there and sometimes it isn't so I am not sure if this is a Unity bug or I did something wrong.

Here is the setup and the bug:

1.The ball object camera is looking at: 1a: The ball that always get render 1b: The with object that is in front and gets render sometimes 2.The output on the raw image when the bug appears (when everything is ok results is like in the camera preview) 3.Camera preview that is always the same

As I said this seams to happen randomly. Also to note I am reloading the scene with this bug on several occasions in my game and on some loops it is fine on some not. I am using URP.

# Answer
Ok so with the help of the comments I fixed it. I changed the Deapth Stencil Format of my render texture and it worked. Note that this comes with bigger texture size. Here are my render texture settings:
> 1 votes

---
Tags: unity, rendertexture, unity-urp
---


# Question
Title: Best Approach For Static Background Image?
I want to have a static background image of a sky that stays completely flat on screen and perfectly fits my games 1920 x 1080 display. Similar to what most old 2D side scrollers did. In other words, I **don't** want to simply drag an image of the sky backward on the Z-axis in 3D space.

Originally, what I was doing to accomplish this was having a 2D "base" camera solely dedicated to rendering this sky image behind everything. I then used a a separate 3D "Overlay" camera to render everything else on top of it.

Here's an example, the blocked out sky section would be the base 2D camera and everything else on screen would be the 3D overlay camera:

This accomplished exactly what I needed, but I think having my base camera only render the sky, and having an overlay camera render everything else is a bad idea.

Does anyone have a better way of accomplishing this? Thanks so much!

# Answer
> 0 votes
Myself, I'd just make this image/sprite renderer a child of the camera, so that no matter how the camera moves, the sky stays attached to it and gets rendered in exactly the same way. By moving it sufficiently far away along the camera's z axis, it won't clip anything rendered closer.

---
Tags: unity, camera
---


# Question
Title: GUI Using WorldToScreenPoint is Out of Control
I want to have a GUI float over a game object using `WorldToScreenPoint`, similar to this tutorial. However, I am experiencing strange behavior with the GUI. I assume that this is due to the character's movement. I have already tried using Screen Space - Overlay and have kept a constant pixel size.

```
void Update() {
    Vector3 loc = transform.position;
    Collider[] colliders = Physics.OverlapSphere(loc,Radius);
    foreach (Collider hit in colliders){
        if(hit.gameObject.tag == "Player"){
            pressgui.transform.position = Camera.main.WorldToScreenPoint(transform.position);
        }
    }
}

```

Here is a video showing the problem.

# Answer
The video tutorial you're following is relying on using a very particular canvas setup to create a coincidental alignment between the UI's world space and screen space coordinates. Since you have not configured your canvas in exactly the same way (we can't tell you how yours differs because you did not show us), this coincidence doesn't align so neatly for you. This is why you get non-sensical results from assigning a screen space position to a world space transform.

Fortunately, Unity has utility functions for converting between screen space and UI coordinates more robustly:

```
// In the inspector, set this to the layer the player object
// (and only the player) is on.
public LayerMask playerLayer;

void Update() {
    // Use a layer rather than a tag to distinguish your player,
    // for more efficient physics checks - allocation free!
    if (Physics.CheckSphere(transform.position, radius, playerLayer)) {
        // No need for a loop anymore.
        var screenPosition = Camera.main.WorldToScreenPoint(transform.position);

        RectTransformUtility.ScreenPointToLocalPointInRectangle(
            (RectTransform)pressgui.transform.parent, // pressgui's container
            screenPosition,          // position measured in pixels
            null,                    // use this for Screen Space - Overlay canvas
            out Vector2 uiPosition;  // local UI space position
        )

       // You may want to use anchoredPosition instead,
       // depending on your anchor setup (which you have not shown us).
       pressgui.transform.localPosition = uiPosition;
    }
}

```
> 0 votes

---
Tags: unity, camera, gui
---


title: Data in blackboards of behavior trees

text:
# Question
Title: Data in blackboards of behavior trees
In Ian Millington's "AI for Games" it is stated that behavior trees should not actually own any data, and instead a blackboard can be used to store data nodes of a behavior tree need to know about and act upon. A blackboard is defined as an associative container that holds pretty much any kind of information.

But what should actually go into a blackboard specifically? When we have an NPC that follows the player, should it store the current location of the player or an entire reference/pointer to the player object? Is there any benefit to this approach over passing a reference of the NPC to the currently executing node, and allowing the node to access data of the NPC object directly?

# Answer
> 2 votes
> When we have an NPC that follows the player, should it store the current location of the player or an entire reference/pointer to the player object?

Not necessarily. You might want to store a reference to the player, depending on how do you want the AI to work.

For example, if you don't want the AI to work on the current position of the player, but on the last seen position of the player, you can put that on the blackboard instead.

*You would have to decide if your agents are always aware of the player, of if they are all aware if only one of them sees it (you can add an animation of the agent talking on intercom for verisimilitud), or if only the agent that sees the player is aware of it… And how do they communicate among themselves when they see the player (e.g. do they organize in groups? do they notify nearby agents?).*

For another example, you could have your NPC reference what it is following, which allows you to have it follow something other than the player.

*Perhaps the player can make decoys, and have the agents follow those. Or perhaps the same behavior can be reused in other cases.*

---

> Is there any benefit to this approach over passing a reference of the NPC to the currently executing node, and allowing the node to access data of the NPC object directly?

First of all, are you sure your NPC is not a blackboard? *It might be, or it might have one.*

Having your behavior work with a generic blackboard class keeps them independent form other implementation details.

*You might also want to advantage of a blackboard to hold the data that you need to persist (for saving and loading the game) together.*

Furthermore, there is something you get with blackboards that you don't get with a reference to your NPC: Communication. Without a way for agents to communicate they are oblivious of each other. And a blackboard is a way to archive that communication. *I'm NOT saying a blackboard is the only way to do it.*

Also, the agent might need some information that changes beyond their control to work correctly. For example: should the enemies be alerted, should they be using lethal weapons, or it could be weather or day time, or if the player has completed some objectives, etc. And the AI can get this information form the blackboard.

Thus, consider the scope of the data. You might have data that is local to the behavior, to the agent, to the room where the agent currently is, to the building, and so on… Until you get to global for everybody. If each of these scopes uses different blackboards, you need to organize the blackboards in parent-child relationships. *The book mentions this "scope chain".*

I would also like to encourage you to look into the concept of an AI director in game development.

---
Tags: npc, behavior-tree
---


# Question
Title: Why does it take around 5 times longer to sample large RenderTextures vs. sampling large Texture3D/2Ds in a Compute Shader?
Firstly I am in Unity 2021.3.11f1 using DX12.

So the situation is the following. I have a large 3D RenderTexture, and I have a large 3D Texture3D with the same data, same format, same dimensions, same size in memory, as the RenderTexture.

Now I have a compute shader that samples from these many times (volume rendering).

* If I use the Texture3D, the compute shader takes 50ms to run in total.
* If I use the RenderTexture instead, changing nothing else, the compute shader takes 170ms to run in total.

Why does this happen? It also happens with large 2D textures as well.

I would just say whatever and use the Texture2D/3D, but the problem with that is that not only does it take a lot longer to create a new large Texture2D/3D, it creates large lag spikes when I need to copy from the RenderTexture to the Texture2D (I use another compute shader to write the data to the texture), which is a big problem because in the case of the 2D Texture/Rendertexture that gets recreated frequently (dynamic atlas).

What can I do and why is this happening in the first place?.

Code if I want to use a rendertexture:

```
RenderTexture TempVolumeTex = new RenderTexture((int)OrigionalSize.x, (int)OrigionalSize.y, 0, RenderTextureFormat.RFloat, RenderTextureReadWrite.sRGB);
TempVolumeTex.enableRandomWrite = true;
TempVolumeTex.volumeDepth = (int)OrigionalSize.z;
TempVolumeTex.dimension = UnityEngine.Rendering.TextureDimension.Tex3D;
TempVolumeTex.Create();
VolumeShader.SetTexture(1, "DDATextureWrite", TempVolumeTex);
VolumeShader.Dispatch(1, Mathf.CeilToInt(OrigionalSize.x / 8.0f), Mathf.CeilToInt(OrigionalSize.y / 8.0f), Mathf.CeilToInt(OrigionalSize.z / 8.0f));

```

and if I want to use a texture3d, I still have to do the exact same as above, but then I have to do:

```
VolumeTex = new Texture3D((int)OrigionalSize.x, (int)OrigionalSize.y, (int)OrigionalSize.z, TextureFormat.RFloat, false);
Graphics.CopyTexture(TempVolumeTex, VolumeTex);

```

# Answer
I can think of three possible causes of this:

1. The RenderTexture will be bigger in memory because it's not compressed. This will consume more memory bandwidth on the GPU to sample, and is also likely to cache miss more often.
2. The RenderTexture probably won't have mip maps. Those can improve performance significantly if you make use of them when sampling the texture.
3. The RenderTexture might well be swizzled / tiled in a way that's good for writing to, but not as cache friendly for reading from.

To improve performance I'd suggest:

1. Optimize the format of the render texture to minimize the number of bytes per pixel that it uses (an 8bpp texture should be faster than 128bpp).
2. You could add mip maps to the RenderTexture, but that would require extra work to generate them between writes to and reads from the texture.
3. If the writes to the RenderTexture are infrequent, then it's possible to use a compute shader to compress the texture after writing to it, but doing so is going to be quite expensive.
> 1 votes

---
Tags: unity, textures, performance, compute-shader
---


# Question
Title: Where can I find free images for game development?
I am developing a game. Writing a program is not too difficult for me. But I have a problem with drawing images. So my question is: where can I find free images for game development? Like characters walking towards directions, etc. Can somebody share some good websites where they have a ton of free images to download? Thanks.

# Answer
Itch.io has some great community-provided free assets. You can filter by 2D, pixel art, or whatever tags are appropriate for the assets you need.
> 1 votes

---
Tags: image
---


title: Bullets shooting all over the place

text:
# Question
Title: Bullets shooting all over the place
I have created a simple player controller, which contains the player logic for a movement, aim and shooting bullets from a gun. Everything almost works, except the bullets shoot in random directions, so either the player is a really bad shooter or there is something wrong with the logic (or rigidbody).

Posted below is the code. Is there anything wrong with the code / logic?

Here is the update code:

```
void Update()
{
    // Move the character
    Move();
    // Aim the character
    Aim();
    // Start the shooting animation and the shooting coroutine if the shoot button is pressed
    if (shootInput && !isShooting)
    {
        anim.SetTrigger("Shoot");
        StartCoroutine(ShootCoroutine());
    }
    // Change ammo
    ChangeAmmo();
}

```

Aim code:

```
void Aim()
{
    // Get the input direction
    Vector3 inputDirection = new Vector3(aimInput.x, 0f, aimInput.y);
    // Check if there is aim input
    if (aimInput != Vector2.zero)
    {
        // Calculate the angle between the input direction and the forward direction
        float angle = Vector3.Angle(inputDirection, transform.forward);

        // Check if the angle is within the max aim angle
        if (angle < maxAimAngle)
        {
            // Rotate the weapon to aim in the input direction
        transform.rotation = Quaternion.Euler(0f, Mathf.Atan2(aimInput.x, aimInput.y) * Mathf.Rad2Deg, 0f);
            // Rotate the shootPosition to match the weapon's rotation
            shootPosition.rotation = transform.rotation;
        }
    }
}

```

Shoot code:

```
IEnumerator ShootCoroutine()
{
    isShooting = true;

    // Make sure the player has ammo
    if (ammo > 0)
    {
        // Create a new bullet at the shoot position
        GameObject bullet = Instantiate(projectilePrefab, shootPosition.position, shootPosition.rotation);
        // Add force to the bullet
        bullet.GetComponent<Rigidbody>().AddForce(shootPosition.forward * shootForce, ForceMode.Impulse);
        // Reduce ammo
        ammo -= 1;
        //Start the animation
        anim.SetTrigger("Shoot");
        // Visualize the direction of the bullet using Debug.DrawRay()
        Debug.DrawRay(shootPosition.position, shootPosition.forward * 50f, Color.red, 2f);
    }
    // Wait for the cooldown time before allowing the player to shoot again
    yield return new WaitForSeconds(cooldownTime);
    isShooting = false;
}
}

```

# Answer
> 0 votes
As DMGregory suggested, the most likely explanation is that the bullet is either bouncing off of the gun's collider or the player's collider. There's an easy way to determine if that's happening - attach this script to your bullet prefab:

```
public class CollisionLogger : MonoBehaviour {
    void OnCollisionEnter(Collision collision) {
        Debug.Log($"{this.name} collided with {collision.gameObject.name}", this);
    }
}

```

If the bullet is bouncing off of the gun or player, you can fix this with the layer collision matrix or using `Physics.IgnoreCollision()`. For example:

```
[SerializeField] private Collider gunCollider;
//...
IEnumerator ShootCoroutine()
{
    isShooting = true;

    // Make sure the player has ammo
    if (ammo > 0)
    {
        // Create a new bullet at the shoot position
        GameObject bullet = Instantiate(projectilePrefab, shootPosition.position, shootPosition.rotation);
        //make sure bullet can't bounce off of gun
        var bulletCollider = bullet.GetComponent<Collider>();
        Physics.IgnoreCollision(gunCollider, bulletCollider);
        // Add force to the bullet
        bullet.GetComponent<Rigidbody>().AddForce(shootPosition.forward * shootForce, ForceMode.Impulse);
        // Reduce ammo
        ammo -= 1;
        //Start the animation
        anim.SetTrigger("Shoot");
        // Visualize the direction of the bullet using Debug.DrawRay()
        Debug.DrawRay(shootPosition.position, shootPosition.forward * 50f, Color.red, 2f);
    }
    // Wait for the cooldown time before allowing the player to shoot again
    yield return new WaitForSeconds(cooldownTime);
    isShooting = false;
}

```

As the documentation for `Physics.IgnoreCollision()` says:

> This is useful, say, for preventing projectiles from colliding with the object that fires them.

---
Tags: unity, c#, physics, rigidbody, projectile-physics
---


# Question
Title: Unity Recorder - Frame Interval Mode NOT Working
All I get from this setting is a single image. **I'm not sure why the Frame Interval and Time Interval Recording modes won't work.** Every other option works, including the Movie and Animation Clip options.

I've read the documentation extensively and it seems like these frame modes should be straightforward.

Anyone know why this might not work (or why my current configuration could be problematic? **The only thing I can think of is that the recorder is overwriting each file frame, but it isn't clear how to fix that.** "Verbose mode" didn't show anything unusual either.

# Answer
> 1 votes
The `<Take>` wildcard in the file name will increment once for each recording *session*, helping you distinguish attempt #1 from attempt #50 at recording the same sequence.

If you've selected a video format as your output, that's enough. All the frames for a given take get packed into the same single video file.

But when you switch to outputting a still image, just a `<Take>` number isn't enough: now we need a separate file name for each frame, so saving the next frame doesn't overwrite the previous.

You can click the "+ Wildcards" drop-down to add a `<Frame>` wildcard to your filename, or type it out yourself. This will increment for every frame in a take, keeping the latest frame from overwriting the previous, and ensuring that you can later reassemble the frames in the right order.

Unity doesn't add this automatically because it doesn't know where in the file name you want it. Many game studios use pipeline tools that expect a very specific file naming convention to work, so having Unity automatically alter the text in that box when you change another setting somewhere else in the dialog would be an easy way to get sneaky bugs that silently break your pipeline.

---
Tags: unity, settings, screen-recording
---


# Question
Title: Any clue to create natural shadow like this?
I only use **skylight** with hdri map for overcast lighting. The corner isn't dark enough compare to other's work. Any clue to achieve this natural falloff soft shadow?

*What I want*

*What I get*

*My world settings*

# Answer
It is all about the directional light intensity , try to lower the intensity of directional light and the build the lighting , you will get the output you want .
> 0 votes

---
Tags: architecture, unreal-4
---


# Question
Title: Strange lighting/shadows in Unreal Engine game (shadow suddenly gets darker or lighter)
As the title suggests. I have made a level for Unreal Engine. It uses `RectLights` in the ceiling without any directional lighting. There is a Lightmass Importance Volume and Post Processing.

I show GIF animation to show the problem, but similar stuff happens all over the maps I have made.

Is this a problem from the Light, the Level Geometry or something else?

Thanks

# Answer
> 0 votes
Firstly , make sure that you have made your rect light to static mesh , the try to change the position of light and again replace it at the position and then make sure you have builded the lighting .

---
Tags: unreal-4, lighting, unreal
---


# Question
Title: Understanding the math behind perspective matrix in OpenGL
I've been trying to figure out the math behind perspective matrix for 2 weeks now but I'm failing badly. I understand the theory behind the perspective matrix but I am not sure how the math works.

**The code:**

```
def perspective(fov: Float, aspect: Float, zNear: Float, zFar: Float) = {
  val h = Math.tan(fov * 0.5f).toFloat
  val c00 = 1.0f / (h * aspect)
  val c11 = 1.0f / h
  val c22 = (zFar + zNear) / (zNear - zFar)
  val c23 = (zFar + zFar) * zNear / (zNear - zFar)

  Matrix4(
    c00,    0,      0,     0,
    0,    c11,      0,     0,
    0,      0,    c22,   c23,
    0,      0,     -1,     0
  )
}

```

## What I understand

I've seen video tutorials by Jorge Rodriguez & Arpan Pathak but I cannot fully relate it to the perspective matrix in the function above.

* **Congruent triangles**: Following Arpan's video I understand that to project a point P=(x, y, z) onto the a 2D `XY` plane I need to create a frustum and which is then used to find it's projection P'=(x', y', z') using congruent triangles relationship. Arpan's video and the final matrix makes sense but I do not see how it relates to the perspective function above? Here is my attempt.
*
* Following the above I switched the frustum in opposite direction to visualise how it would apply in OpenGL using the perspective function above with `zFar` and `zNear` parameters but it's no way close to the perspective matrix in the code.
*

# Answer
Your `h` at the bottom is missing the left/right and top/bottom parameters; cf. to the code at the top where they are expressed as angle `fov` and aspect ratio.

Thanks to the `1` in the w-row of the matrix you get the `z` value as 4th coordinate, because this is the other parameter for the new `x` and `y` values. A high `x` (same for `y`) value at large distance/depth shall be displayed near the center.

The idea of the perspective projection is to choose a frustum and turn it into a cube ranging from -1 to 1 in all 3 dimensions - the NDC coordinates.

So for `x` and `y` the relation is:

Xndc = h * X / Z

This divide by `Z` cannot be expressed in a matrix and is done separately. `h` stands for the width and heigth of the near plane.

The depth `Zndc` is normalized between the near and far plane. If it is done linearly you get `A*z + B = 0`, with `A*near + B = -1` and `A*far + B = 1`.

But depth wants to be stored non-linearly, with more precision at the near side. So the general equation is `(A*z+B)/z`, or `A + B/z`. And again you can define the two planes:

```
-1 = A + B/near
 1 = A + B/far

```

Now A and B have to be expressed in terms of near and far.

`A = 1 - B/f` into first equation --\>

```
-1 = 1 - B/f + B/n           minus one

-2 = -B/f + B/n              multiply by f*n

-2fn = -Bn + Bf              factor out B

B(f-n) = -2fn                divide by f-n

B = -2fn / (f-n)

```

And this `B` is exactly your `c23`, with signs and subtraction reversed. `A` is even easier to calculate.

For the matrix, `A + B/z` is not possible, so we have to switch to the `(A*z+B)/z` form with extra divide by z as for x and y.

Putting it together gives

```
Zndc = ( Z*(f+n)/(f-n) - 2fn/(f-n) )  /  Z

```

where the linear part `Z*A + B` is done by the matrix and `W` is assumed to be one so `B` is really a constant.

This brings me back to the lone "1", or rather "-1" ??, on the bottom row of the matrix. But here is my Frustum matrix, in glsl column-major (sigh) layout:

```
/* Frustum with aspect ratio */
double fside = 1 / u.frhtan);
double pldiff = u.frf - u.frn;
mat4 F = {
    vec4(fside, 0,        0, 0),
    vec4(0, fside*u.aspr, 0, 0),
    vec4(0, 0,           (u.frf + u.frn) / pldiff, 1),
    vec4(0, 0,           -2*u.frf*u.frn  / pldiff, 0)
};

```

What I changed is 1) diff is positive ie. far - near 2) "-1" is "1" 3) "2fn" is "-2fn".

This avoids the ominous Z-flip and seems to work without needing `glDepthRange` or `glDepthFunc`. It uses directly A and B as derived above (B at least I showed).

So the "lone 1" is the matrix field that stores the original z as w-value, because x, y and z all need that division to become NDC.

Where you have "0 0 -1 0" for z it should be "0 0 A B" in terms of near and far plane. Z needs to be scaled, just like X and Y, not flipped.
> 1 votes

---
Tags: opengl, perspective
---


title: Textures only work on vertical surfaces

text:
# Question
Title: Textures only work on vertical surfaces
I'm trying to apply a megascan texture (hardwood) to a floor but it only looks right on vertical surfaces. If I apply it to a cube and rotate the cube, the texture turns weird on the horizontal faces and looks good on the upright ones. I used worldAlignedTexture object as indicated by this tutorial https://www.youtube.com/watch?v=fUW3HHMhx1A&t=171s

This is the blueprint for the texture

What gives?

# Answer
> 0 votes
The first alignedWorldTexture object the top. I changed from xy to xyz and it worked on all sides.

---
Tags: unreal-4, unreal, unreal-5
---


# Question
Title: How to make the jumping/ground pounding smooth in Godot?
I'm new to Godot (and C# in general, but I use that because that's the language I'm learning in school, and I don't want to confuse myself with GDscript), and I tried to code a 2D player character (nothing too big, just moving, sprinting, jumping, and ground pounding), but when I got to the jumping mechanics, instead of player jumping, it just teleported upwards, and then glided downwards. And the ground pound just teleported me to the ground.

Here's the code:

```
using Godot;
using System;

public class Player : KinematicBody2D
{
    private float speed = 600;
    private float gravity = 500;
    private float jumpForce = -5000;
    //Basic variables for stuff

    public override void _PhysicsProcess(float delta)
    {
        var move = Vector2.Zero;
        var animatedSprite = GetNode<AnimatedSprite>("AnimatedSprite");
        move.y = gravity;
        //Other variables

        if (Input.IsActionJustPressed("jump") && IsOnFloor())
        {
            move.y = jumpForce;
        }
        //Jumping

        if (Input.IsActionPressed("left"))
        {
            move.x = -speed;
            animatedSprite.Play("walk");
            animatedSprite.FlipH = true;

            if (Input.IsActionPressed("sprint"))
            {
                move.x = (-speed) + (-400);
            }
        }
        if (Input.IsActionPressed("right"))
        {
            move.x = speed;
            animatedSprite.Play("walk");
            animatedSprite.FlipH = false;

            if (Input.IsActionPressed("sprint"))
            {
                move.x = speed + 400;
            }
        }
                //Movement and sprint

        if(Input.IsActionJustPressed("pound"))
        {
            move.y = -jumpForce;
        }
        //Groundpound

        MoveAndSlide(move, Vector2.Up);
    }
}

```

The other thing with jumping is that I need a really big number to lift the player from the ground, so that jumpForce variable in the code is barely enough to lift the character.

A tried to tweak it a little bit, changed some numbers (I thought that maybe I just screwed up the variables), but that don't worked.

# Answer
I don't have a C# environment set up so I can't test my solution, but I did port your code to GDScript and I think I can point out some errors.

The reason your character teleports is because it has no implementation of velocity. To fix this, make `move` a member variable of `Player`. Then, instead of setting `move` with `=`, add to it with `+=`. Lastly, be aware `MoveAndSlide` returns a a modified velocity if you collide with something, so you should change the line to say `move = MoveAndSlide(move, Vector2.Up);`. Lastly, smaller numbers can be used for the physics values since they will accumulate over time.

I believe these modifications would look like this:

```
using Godot;
using System;

public class Player : KinematicBody2D
{
    private float speed = 10;
    private float gravity = 10;
    private float jumpForce = -300;
    private Vector2 move = Vector2.Zero;
    //Basic variables for stuff

    public override void _PhysicsProcess(float delta)
    {
        var animatedSprite = GetNode<AnimatedSprite>("AnimatedSprite");
        move.y += gravity;
        //Other variables

        if (Input.IsActionJustPressed("jump") && IsOnFloor())
        {
            move.y += jumpForce;
        }
        //Jumping

        if (Input.IsActionPressed("left"))
        {
            move.x += -speed;
            animatedSprite.Play("walk");
            animatedSprite.FlipH = true;

            if (Input.IsActionPressed("sprint"))
            {
                move.x += (-speed) + (-400);
            }
        }
        if (Input.IsActionPressed("right"))
        {
            move.x += speed;
            animatedSprite.Play("walk");
            animatedSprite.FlipH = false;

            if (Input.IsActionPressed("sprint"))
            {
                move.x += speed + 400;
            }
        }
                //Movement and sprint

        if(Input.IsActionJustPressed("pound"))
        {
            move.y += -jumpForce;
        }
        //Groundpound

        move = MoveAndSlide(move, Vector2.Up);
    }
}

```

If this works, keep in mind your character will slide after moving because there is no code to slow down when you let go of the movement keys.
> 2 votes

---
Tags: c#, godot
---


# Question
Title: How to make texture appear only once, in the center of a cube's top face?
I'm making a platformer game and I need a texture to be only on the top face of a cube and in the centre. Can I do this without scripts or do I need scripts? Also, my texture is transparent and I need it to have a white background, like this:

# Answer
Do this with a decal. Make the cube white, then create a quad with your top face texture on it and place it on top like a sticker. (Leave a tiny gap to ensure they're rendered in the right order with limited depth buffer precision).

You can parent the quad to the cube, and make a prefab of the pair, so that they're easy to place and move around as a single unit.

If you want to avoid having two objects / draw calls, you'll need to make your own cube mesh with a custom UV unwrap. You'd set the texture coordinates of your custom cube so that the top face samples from the middle of your texture where the design is, and the other faces sample from the edges of the texture so they don't touch the design.
> 0 votes

---
Tags: unity, textures, transparency
---


# Question
Title: Why are quads not rendering with OpenTK 4.7.5 when similar code works with OpenTk 3.3.3?
The following code will not render the quads with .Net 6 and OpenTK 4.7.5, but (nearly) identical code works with .Net 4.8 and OpenTK 3.3.3.

(Triangles will render fine, but I would rather use quads, because they are just more easy to handle for my use case.)

.Net 6 with OpenTK 4.7.5

```
using OpenTK.Windowing.Common;
using OpenTK.Windowing.Desktop;
using OpenTK.Graphics.ES30;
using OpenTK.Mathematics;

using Game game = new(new GameWindowSettings(), NativeWindowSettings.Default);

game.Run();

public class Game : GameWindow
{
    public Game(GameWindowSettings gameWindowSettings, NativeWindowSettings nativeWindowSettings) : base(gameWindowSettings, nativeWindowSettings)
    { }

    private readonly Vector2[] _circleVertices =
    {
        new(-0.1f, -0.1f),
        new(-0.1f, 0.1f),
        new(0.1f, 0.1f),
        new(0.1f, -0.1f),

        new(0.2f, 0.2f),
        new(0.7f, 0.2f),
        new(0.7f, 0.7f),
        new(0.2f, 0.7f),
    };

    private int _vertexArrayObject;

    private Shader _shader;

    protected override unsafe void OnLoad()
    {
        base.OnLoad();

        GL.ClearColor(0, 0, 0, 1);

        GL.BindBuffer(BufferTarget.ArrayBuffer, GL.GenBuffer());

        GL.BufferData(BufferTarget.ArrayBuffer, _circleVertices.Length * sizeof(Vector2), _circleVertices, BufferUsageHint.DynamicDraw);

        GL.BindVertexArray(_vertexArrayObject = GL.GenVertexArray());

        GL.VertexAttribPointer(0, 2, VertexAttribPointerType.Float, false, sizeof(Vector2), 0);

        GL.EnableVertexAttribArray(0);

        string vertexShader = @"
#version 450 core

layout (location = 0) in vec2 position;

uniform mat4 projection;

void main()
{
    gl_Position = vec4(position, 0, 1.0);
}";

        string fragmentShader = @"
#version 450 core

out vec4 fragColor;

void main()
{
    fragColor = vec4(1);
}";

        _shader = new Shader(vertexShader, fragmentShader);
    }

    protected override void OnRenderFrame(FrameEventArgs e)
    {
        base.OnRenderFrame(e);

        GL.Clear(ClearBufferMask.ColorBufferBit);

        GL.UseProgram(_shader.Handle);

        GL.BindVertexArray(_vertexArrayObject);

        GL.DrawArrays(PrimitiveType.Quads, 0, _circleVertices.Length);

        GL.DrawArrays(PrimitiveType.LineStrip, 0, _circleVertices.Length);

        Context.SwapBuffers();
    }
}

public class Shader
{
    public readonly int Handle;

    public Shader(string vertexShader, string fragmentPath)
    {
        Handle = GL.CreateProgram();

        GL.AttachShader(Handle, Create(vertexShader, ShaderType.VertexShader));
        GL.AttachShader(Handle, Create(fragmentPath, ShaderType.FragmentShader));

        GL.LinkProgram(Handle);

        GL.GetProgram(Handle, GetProgramParameterName.LinkStatus, out int success);
        if (success == 0)
            Console.WriteLine(GL.GetProgramInfoLog(Handle));
    }

    private int Create(string shader, ShaderType type)
    {
        int reference = GL.CreateShader(type);
        GL.ShaderSource(reference, shader);
        GL.CompileShader(reference);

        GL.GetShader(reference, ShaderParameter.CompileStatus, out int success);
        if (success == 0)
            Console.WriteLine(GL.GetShaderInfoLog(reference));
        return reference;
    }
}

```

.Net 4.8 with OpenTK 3.3.3

```
using System;
using OpenTK;
using OpenTK.Graphics.OpenGL4;

namespace MVP_Error_net4
{
    internal class Program
    {
        static void Main(string[] args)
        {
            using Game game = new(640, 360);
            game.Run(60);
        }
    }
}

public class Game : GameWindow
{
    public Game(int width, int height) : base(width, height) { }

    private readonly Vector2[] _circleVertices =
    {
        new(-0.1f, -0.1f),
        new(-0.1f, 0.1f),
        new(0.1f, 0.1f),
        new(0.1f, -0.1f),

        new(0.2f, 0.2f),
        new(0.7f, 0.2f),
        new(0.7f, 0.7f),
        new(0.2f, 0.7f),
    };

    private int _vertexArrayObject;

    private Shader _shader;

    protected override unsafe void OnLoad(EventArgs e)
    {
        base.OnLoad(e);

        GL.ClearColor(0, 0, 0, 1);

        GL.BindBuffer(BufferTarget.ArrayBuffer, GL.GenBuffer());

        GL.BufferData(BufferTarget.ArrayBuffer, _circleVertices.Length * sizeof(Vector2), _circleVertices, BufferUsageHint.DynamicDraw);

        GL.BindVertexArray(_vertexArrayObject = GL.GenVertexArray());

        GL.VertexAttribPointer(0, 2, VertexAttribPointerType.Float, false, sizeof(Vector2), 0);

        GL.EnableVertexAttribArray(0);

        string vertexShader = @"
#version 450 core

layout (location = 0) in vec2 position;

uniform mat4 projection;

void main()
{
    gl_Position = vec4(position, 0, 1.0);
}";

        string fragmentShader = @"
#version 450 core

out vec4 fragColor;

void main()
{
    fragColor = vec4(1);
}";

        _shader = new Shader(vertexShader, fragmentShader);
    }

    protected override void OnRenderFrame(FrameEventArgs e)
    {
        base.OnRenderFrame(e);

        GL.Clear(ClearBufferMask.ColorBufferBit);

        GL.UseProgram(_shader.Handle);

        GL.BindVertexArray(_vertexArrayObject);

        GL.DrawArrays(PrimitiveType.Quads, 0, _circleVertices.Length);

        GL.DrawArrays(PrimitiveType.LineStrip, 0, _circleVertices.Length);

        Context.SwapBuffers();
    }
}

public class Shader
{
    public readonly int Handle;

    public Shader(string vertexShader, string fragmentPath)
    {
        Handle = GL.CreateProgram();

        GL.AttachShader(Handle, Create(vertexShader, ShaderType.VertexShader));
        GL.AttachShader(Handle, Create(fragmentPath, ShaderType.FragmentShader));

        GL.LinkProgram(Handle);

        GL.GetProgram(Handle, GetProgramParameterName.LinkStatus, out int success);
        if (success == 0)
            Console.WriteLine(GL.GetProgramInfoLog(Handle));
    }

    private int Create(string shader, ShaderType type)
    {
        int reference = GL.CreateShader(type);
        GL.ShaderSource(reference, shader);
        GL.CompileShader(reference);

        GL.GetShader(reference, ShaderParameter.CompileStatus, out int success);
        if (success == 0)
            Console.WriteLine(GL.GetShaderInfoLog(reference));
        return reference;
    }
}

```

# Answer
The issue with the code is that `PrimitiveType.Quads` is not supported in OpenGL 3.0 and above, which is used by OpenTK 4.7.5. Instead, use `PrimitiveType.Triangles` and specify the indices of the vertices that make up each quad. Another option would be to use a geometry shader to convert the input triangles into quads.
> 4 votes

---
Tags: c#, .net, opentk
---


# Question
Title: How to safely store opengl vertices in a c++ struct
Instead of using a vector of floats, i want to use a struct, so that it can store different types and is easier.

```
struct QuadVertex
{
    glm::vec3 Position;
    glm::vec4 Color;
    glm::vec2 TexCoord;
    int TexIndex;
};

```

But if i use this structure in a vertex buffer, c++ could use padding or alignment in the structure and openl wouldnt get the expected data. How can i safely use this structure to store vertices, and how should i modify the vertex attributes correctly?

# Answer
**Use sizeof and offsetof**.

Specifically, when setting up your vertex format and pointers in code, using sizeof for the stride in your glVertexAttribPointer calls will cause OpenGL to correctly set things up such that each vertex properly begins at the start of each new struct in your array.

Similarly, using offsetof for the position of each attribute will cause OpenGL to correctly retrieve each attribute from it's correct location in the struct.

This will work irrespective of padding or alignment, and will be portable across different architectures and compilers where these might differ. (Loading the data correctly into the structs is another issue, of course.)
> 2 votes

---
Tags: opengl, c++
---


# Question
Title: Why is C# method not showing up for button's On Click()
I have a C# script called MainMenu.cs

Here it is in its entirety

```
using UnityEngine;
using UnityEngine.UI;

public class MainMenu : MonoBehaviour
{
    public Button btnPlay;

    // Use this for initialization
    void Start ()
    {
        btnPlay = btnPlay.GetComponent<Button>();
    }

    public void PlayLevel()
    {
        Application.LoadLevel(1);
    }
}

```

In my hierarchy, i have a Main Camera, a Canvas and EventSystem. Under Canvas i have a Button. I add the MainMenu script to the Canvas and associate the button with Button i have in canvas. When i go to the button and associate the MainMenu with its OnClick I am expecting to be able to chose PlayLevel() but it is not there.

Am i missing something obvious here? (Using Unity 5.0)

# Answer
Because the copy of "MainMenu" you selected is not the MainMenu component in your scene. Its the one in your assets folder. Be sure to find the one in your scene. Then you will see the method.
> 8 votes

# Answer
Newbie, just figured out how to do it:

1. create an empty gameobject under your scene.
2. drag the C# script to the empty gameobject's inspector, rename the gameobject to something easy to understand, e.g. "MyScript".
3. under button onclick event, click + to create a new entry.
4. in the new entry's gameobject field, drag the "MyScript" object to this field.
5. open the functions menu, your functions will show up.

Other things to consider: 1. make sure your script does not have any build errors. 2. make sure your script's functions are public. 3. make sure your function's has only 0 or 1 basic type parameter.

This will do the trick. Unity UI system is really weird BTW. Good Luck!
> 5 votes

# Answer
Make sure the name of your script matches in your code and the game object with the script in the components is in the `OnClick()`. From there use the drop down box and your method should appear under than script name as an option. Here is a picture for anyone who stumbles across this later.
> 2 votes

# Answer
To build off of BuildThatGame's answer, I had the Game Object and I had the script already in my current scene, but the functions weren't showing up.

The reason was because I was dragging the script onto the button's OnClick event, not the game object I made. If you follow BuildThatGame's answer and still can't figure out why the functions aren't showing up, check that you added the game object.
> 0 votes

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


title: Mysterious light source

text:
# Question
Title: Mysterious light source
In 5.0.3, I removed all light objects from the project, including the skylight and any/all lightbulbs. Yet, there are two spots of light in my model, one on the floor and one on a wall. What might be up with that?

# Answer
> 1 votes
The same thing can occur with shadows.

Rebuild the lighting to rebuild the lightmaps and shadow maps in lightmass.

If you are running lumen, this is a bug if it occurs when running the game. If it happens in editor after running PIE, moving the viewport "camera" will recalculate the lighting.

---
Tags: unreal-4, unreal, unreal-5
---


# Question
Title: Translate position from 3D camera to 2D camera
Currently I have 2 cameras, one for viewing the 3D objects (Perspective), and the other camera to view 2D objects (Orthographic).
(Also, the view of the camera never intercepts each other.)

I am trying to display a 2D object based on the position of a 3D object, like so:

What I have is the respective 2D and 3D `Camera`, as well as the `Vector3` position of the 3D `GameObject`.

*What I have tried:*

```
public Vector2 Convert3DPositionTo2DPosition(Camera camera3D, Vector3 position3D, Camera camera2D) {
    var tempPos = camera3D.WorldToViewportPoint(position3D);

    return camera2D.ViewportToWorldPoint(tempPos);
}

```

The only problem is that the returned position is not completely aligned with the 3D position.
Which results in this kind of results:

Also, I have made sure that both the 3D and 2D object have their pivot point are set correctly in the center, but it still does not work as intended.

(I am currently using `Unity 2019.1.14f1`)

# Answer
> 1 votes
First use the WorldToScreenPoint method of the 3d camera to convert the position of the 3d object to screen coordinates:

```
Vector3 screenPosition = camera3D.WorldToScreenPoint(3dPosition);

```

Then use the corresponding method ScreenToWorldPoint of the 2d camera to find the point in the 2d world that corresponds to this screen position:

```
Vector3 2dPositon = camera2D.ScreenToWorldPoint(screenPosition);

```

When you still experience an offset, keep in mind that the `transform.position` of a gameObject does not necessarily correspond to what looks like the center of its visual representation. There are several circumstances which can lead to an object appearing at a different location than its transform. So if you still encounter problems like that, try reproducing them with simple primitives first to ensure that it's not a problem like misaligned 3d models, sprite pivots, child-objects with local position, etc.

Relevant documentation:

https://docs.unity3d.com/ScriptReference/Camera.ScreenToWorldPoint.html https://docs.unity3d.com/ScriptReference/Camera.WorldToScreenPoint.html

# Answer
> 0 votes
Instead of `ViewportToWorldPoint` use `WorldToScreenPoint`

https://docs.unity3d.com/ScriptReference/Camera.WorldToScreenPoint.html

Oh yeah, and call the function on your 2D camera :D

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


# Question
Title: How fast or scalable is wave function collapse?
Specifically the generation part, if I wanted to use it at high resolutions.

High level descriptions make me suspect O(n²) or worse, and demos are always low res, but fast-wfc describes itself as *"Wave Function Collapse with a focus on performance. It was called fast-wfc because at the time it introduced optimizations improving the execution time by an order of magnitude."*, so do optimized implementations scale well? What sort of sizes are realistic?

# Answer
First, let's define \\$N\\$ to be the number of *cells* and \\$T\\$ to be the number of *tiles*. For example, Pac-Man has about 36 unique tiles (\\$T = 36\\$) and has about \\$28 \times 31\\$ cells (\\$N = 868\\$).

In general, the upper bound is \\$O(T^2 \cdot N^2)\\$. In practice this probably can be reduced down to \\$O(T^2 \cdot N)\\$.

We can't really do better than \\$O(T \cdot N)\\$ because just to traverse all cells and remove all non-chosen tiles, we're already at \\$T \cdot N\\$. To see why it might be \\$O(T^2 \cdot N^2)\\$, we might be required to traverse the whole grid after a single tile removal to see if any tiles need to be removed from the given constraints.

In practice, we only have pairwise neighbor tile/cell constraints and so the "impact" of a single tile removal can be localized to only cells around impacted site.

The algorithm for this approach flags neighboring cells as needing to be inspected if a tile was removed near them. After inspection, remove them from consideration, marking any neighbors as needing inspection if any further updates (tile removals) have occured.

Here's some rough pseudo-code:

```
function propagateConstraints(grid, accessed) {
  while (still culling) {
    removeFlaggedCells()
    foreach cell in accessed {
      foreach neighbor_cell in cell {
        if tiles can be removed from neighbor_cell {
          add neighbor_cell to accessed
          flag neighbor_cell
        }
      }
      remove cell from accessed and unflag cell
    }
  }
}

```

In general, this only updates a kind of "wave-front" or boundary of where a tile has been removed. In the worst case this can cycle through the whole grid but this only happens if it needs to, whereas a naive version touches many cells whether it needs to or not.

I'm kind of waiving my hands here and only considering the naive way of testing whether tiles need to be updated by doing a complete pairwise comparison. In theory, if one were sufficiently motivated, there might be speedups there to try and reduce the \\$O(T^2 \cdot N)\\$ down to something closer to \\$O(T \cdot N)\\$.

I've further ignored the dimension of the grid and taken for granted that the number of neighbors is constant. There is another factor of \\$D\\$, the dimension that comes into the runtime. For fixed dimension, this obviously doesn't impact the "big-oh" but is still a relevant factor when practically considering run time.

I wrote a small article about my implementation of Wave-Function-Collapse which can be found here. The source code is also available here (though it might be a little hard to follow) and is libre/free, so feel free to inspect or use it as a reference implementation.
> 2 votes

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


# Question
Title: My GLTF models made in Blender are transparent from certain directions
When I rotate the camera some of my blender models become transparent from different angles. They are gltf models

Here is the Python to save the gltfs

```
def export_selected_objects():
basedir = "C:\\Users\\Zack\\PycharmProjects\\CourseWork\\static\\assets\\gltf"

if not basedir:
    raise Exception("Blend file is not saved")

view_layer = bpy.context.view_layer

obj_active = view_layer.objects.active
selection = bpy.context.selected_objects

bpy.ops.object.select_all(action='DESELECT')

for obj in selection:
    obj.select_set(True)

    # some exporters only use the active object
    view_layer.objects.active = obj

    name = bpy.path.clean_name(obj.name)
    fn = os.path.join(basedir, name)

    bpy.ops.export_scene.gltf(filepath=fn, use_selection=True)

    # Can be used for multiple formats
    # bpy.ops.export_scene.x3d(filepath=fn + ".x3d", use_selection=True)

    obj.select_set(False)

    print("written:", fn)

view_layer.objects.active = obj_active

for obj in selection:
    obj.select_set(True)

```

Here is the JS to load the gltf

```
const loader = new THREE.GLTFLoader();
    loader.load( baseFilePath + baseID + ".glb", function (gltf) {
            gltf.scene.position.set(x - offset[0], 2, z - offset[2]);
            scene.add(gltf.scene);
        },
        (error) => {
            console.log(error);
        }
    )

```

The gltf files I am using: https://drive.google.com/drive/folders/1iEfGVyZ9nklFlTusTMoh5cjdhdUpRI2w?usp=sharing

To recreate:

1. Create a plane in blender and select it
2. Use the first Python function to export it as glb (change the basedir)
3. Use the second JS function to import it to a THREEJS scene

The plane should be visible from one side but not from the other

# Answer
Check the mesh normals and set double-sided rendering to true

1. Mesh normals: You'd usually check them in a 3d editing program. In Blender: At the top-right of the viewport window, click on the little arrow beside the Overlays icon, and activate the tickbox beside Face Orientation. Then switch to Edit Mode, and you'l see all faces colored depending on their orientation - blue colored faces show outwards, which is the standard, and red colored faces show inwards. If double-sided rendering is off, then these won't be drawn when looking at them from the outwards direction. To change a face's orientation, select it, go to Mesh\>Normals\>Flip(Alt+N,F)
2. Double-sided rendering: In order to save resources, faces are usually only drawn when looking at them from the outwards direction of a mesh. If you want to enable the user to look inside of a model and get the mesh shown from the inside, you have to activate double-sided rendering (also known as backface culling). This is a material setting and can be done like so:

```
var material = new THREE.MeshBasicMaterial({
  color: 0xff0000,
  side: THREE.DoubleSide
});

```

This code sets the side property of the material to THREE.DoubleSide, which makes it render both sides of the mesh.

EDIT: Since these meshes seem to be non-manifold anyway (for an explanation of non-manifold meshes see here: https://sinestesia.co/blog/tutorials/non-manifold-meshes-and-how-to-fix-them/), you can omit step one and simply set THREE.DoubleSide

Another EDIT: I just realized that Op was asking about Blender anyway, and not about Three.js, which I somehow falsely assumed. Just leaving part 2 here in case anyone has this problem when coding Three.js apps.

Last EDIT: Backface culling can be found in the Render Properties\>Workbench Render Engine\>Options in Blender.
> 0 votes

---
Tags: blender, three.js
---


# Question
Title: What is the "Built-in Texture2D"? How to reduce its size or remove it?
I am building an APK in Unity. The build log says this:

```
Used Assets and files from the Resources folder, sorted by uncompressed size:

 9.3 mb  3.7% Built-in Texture2D:

```

My 2 questions are:

1. What and where is the **Built-in Texture2D** ?
2. How do I remove or reduce the size of this **Built-in Texture2D** ?

I want to reduce the size of those texture2D files if I know where they are.

---

There is some answer on the web saying that one form of this **Built-in Texture2D** could be the splash screen.

But, I don't have any customized splash screen, and only use the default Unity splash screen, which is not too big.

---

I have tried to enable the option **Deployment Build** when building the APK. But, that does not remove or reduce the size the **Built-in Texture2D** at all.

# Answer
> 1 votes
In Unity3D, a Built-in Texture2D is a pre-defined texture included with the Unity engine and can be used in various ways, such as for creating materials, GUI elements, and particle systems. These textures include checkerboards, gradients, and noise patterns that can be used as a starting point for creating custom textures. They can be accessed and used in the Unity editor by selecting "Import Package \> Built-in Shaders" and then choosing the texture from the "Standard" or "Legacy" shader menu.

To reduce the size of an APK, the first thing that comes to mind is Unity's built-in asset bundle system. Unfortunately, I don't have a step-by-step guide for it, but in the past, that's how I reduced large APK files. Here are a couple of links that could be useful:

docs.unity3d.com/Manual/AssetBundles-Building.html

docs.unity3d.com/Manual/ReducingFilesize.html

---
Tags: unity, android, build-process, build
---


# Question
Title: Lots of objects with OnMouseDown VS Raycasting: Is one better than the other?
I have a grid of gameobjects with colliders. Currently they all have unity's inbuilt **void OnMouseDown** function which gets called when the mouse clicks on a collider. This then executes some game logic on the gameobject.

I realise that I could instead use a seperate script to send a raycast when the player clicks and if it intersects with one of the afformentioned gameobjects I can execute the code that way.

Is one approach better than the other? Or behind the scenes is unity using the raycast method for **void OnMouseDown** anyway? (Or is there perhaps a non-performance reason why you'd use one approach rather than the other)

Thank you.

# Answer
Behind `OnMouseDown`, Unity is transforming your mouse position from window coordinates to view coordinates, projecting into the world using the view-projection transform and testing this ray against `Collider`s that have the right "layer mask" for `OnMouseDown` receivers.

You should be able to see what it actually calls to do this in the profiler. It's probably just exactly would want to do if you are using `Collider`s or Unity's physics module more generally. IIRC it uses `RayCast`.

A motivation for doing it yourself would be that you can specify a layer mask when calling `RayCast`, so that fewer `Collider`s are tested, which could benefit performance.

Another motivation could be that you want to take control of when exactly the ray tests happen, rather than supply a callback to an opaque system, whether for performance or just preference.
> 1 votes

---
Tags: unity, raycasting
---


# Question
Title: Unity type safe CompareTag without using strings
When comparing tags sometimes I can do a typo. For example I might miss type `Enmy` instead of `Enemy` and loose some time when trying to find the bug. Is there a way to access all tags before the compiling. So intellisense can auto complete the tag. I am looking for something like this:

```
 if (ParentObject.tag == "Enemy")
 {
     Debug.Log("String comparison");
 }

 if (ParentObject.tag == UnityAllTags.Enemy)
 {
      Debug.Log("Safe comparison");
 }

```

# Answer
> 3 votes
Ok I found a editor script that creates a new static class with all the tags when project is saved. Here is the link to script: https://gist.github.com/gpelletier0/c6989bf5bf25dfb8b8051204baa65865

Generates a type safe representation of the tags and layers you can set up in the project settings.

**How To Install:**

Put this file somewhere in an 'Editor' folder.

**How To Use:**

When you make changes to the tags and layers in the project settings the tool will generate two scripts in the project folder which contain two static classes for Tags and Layers.

You can change the path where the scripts are created in the Preferences window(Edit/Preferences).

```
private void OnTriggerEnter(Collider other)
    {
        if (other.tag == Statics.Tags.MyCustomTag)
        {
            Debug.Log("awfa");
        }
    }

```

I want to thank Cristian Geambasu `@daemon3000` for creating this script and also Guillaume Pelletier `@gpelletier0` for updating it.

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