# Question
Title: Getting error when I Send a message to the RaycastHit object
I have created a shooting game, here when I am shooting I have a c# script for damage for enemies.I have Used Raycast to Shoot enemies.if the RaycastHit becomes an enemy, it will be deducted it's health.It works properly.But the thing is, If I shoot objects except enemies it causes an error. I have provided some details about that.this is the script,

```
public class DamageSMG : MonoBehaviour
{
    public int DamageAmount = 5;
    public float TargetDistance;
    public float AllowedRange = 50;
    public RaycastHit Shot;
    public int Firing;
    void Update()
    {
        if(Input.GetButton("Fire1")){
            if (Physics.Raycast(transform.position, transform.TransformDirection(Vector3.forward),out Shot))
            {
                TargetDistance = Shot.distance;
                if (TargetDistance < AllowedRange)
                {
                    if (Firing == 0)
                    {
                        Deduct();
                    }
                }
            }
        }
    }
    public void Deduct()
    {
        Firing = 1;
        Shot.transform.SendMessage("DeductPoints", DamageAmount);
        StartCoroutine(Wait());

    }
    IEnumerator Wait()
    {
        yield return new WaitForSeconds(0.1f);
        Firing = 0;
    }
}

```

I am using an machine gun.therefore I have created Script to fire coutinously with 0.1sec break.When I press **Fire1** button, The RayCastHit Object is received a message where the method called **DeductPoints** with the **DamageAmount**.As this Script my enemies are deduct point 5 by 5 every hit.Then Destroy the object.The Enemy script is this.

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

public class EnemyScript : MonoBehaviour
{
    public int EnemyHealth = 20;
    void DeductPoints(int DamageAmount)
    {
        EnemyHealth -= DamageAmount;
    }

    // Update is called once per frame
    void Update()
    {
        if (EnemyHealth <= 0)
        {
            Destroy(gameObject);
            GlobalScore.GlobalScorecount += 1;
        }

    }

}

```

But my problem is when I shoot objects except Enemies(Ex: walls),The console gives an error.The error is like this *SendMessage DeductPoints has no receiver* How can I solve this error or is there any other way of Deducting enemy health with raycast? I can play the game with this error in UnityEngine.but it is not possible to Build the game.Please help me to Solve this..

# Answer
> 1 votes
Have you considered making `DeductPoints` `public`, then calling it directly like so:

```
public void Deduct()
{
    Firing = 1;
    var enemy = Shot.transform.GetComponent<EnemyScript>();
    if(enemy == null)
        return; // Not an enemy! Abort!

    enemy.DeductPoints(DamageAmount);
    StartCoroutine(Wait());
}

```

This has a number of advantages: calling the method directly saves you the reflection cost of searching for a method called "DeductPoints" on every component of the hit object. It allows you to send more than one argument if you need (like a damage type, or damage-dealer reference), and receive a return value about the result. And it's visible to the IDE and compiler so they can do things like compile-time type checking, or refactoring to rename the method and all references to it automatically.

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


# Question
Title: What is the most efficient way to load all the textures?
I am developing a game (in Java) that is going to have a lot of textures and images in it.

What is the most efficient way to load all the textures? I was thinking on pre-loading all the images instead of loading them during runtime (because during runtime they will be loaded over and over again).

I'll be happy to hear your opinion on those strategies, and also, if you have a better strategy I would like to hear that.

# Answer
The question you have to ask yourself is, how often will the textures be used? Based on the answer you have a few options:

* If multiple textures are expected to be visible on the screen at the same time, they all *have* to be pre-loaded, and remain in memory until they are drawn.
* If multiple textures are part of different areas of your game (like on different levels) then you can pre-load all textures on the current level, and once the user moves to the next level, unload previous assets and load the ones on the new level.
* In the case of an open-world game, where the line between the two choices above are slightly blurred, divine the map into "chunks", and when moving to a new chunk, un-load all assets on the previous one, and load the ones on the new chunk.

For most machines out there, the best you can do is pre-load as much as possible. If you are worried that a machine might run out of memory, maybe you'd have to ask yourself if using less textures, or smaller textures is preferred.
> 1 votes

---
Tags: java, textures, loading
---


# Question
Title: What is online presence? (Is it the same as gameplay?)
I was reading the Fortnite 2018 outage postmortem, and it mentions it uses XMPP for **online presence**. Im not sure if this means gameplay or more generally, the presence of Fortnite online, like its websites and social media tools.

The article also mentions it uses XMPP for `presences, commands and various aux data`. Is this 'player presence' and their 'key commands' in the game world?

It also mentions 'presence flow between players'. I have no idea what this could mean.

# Answer
> 2 votes
XMPP is an instant messaging protocol. "Presence" in this context means an indicator that another user is offline, afk, available or busy. I never played Fortnite, so I have no first-hand knowledge about what social features this game provides. But the article says:

> We leverage XMPP for the following features: Online presence, Push notifications, Whispers, Group chat - for parties, for team chat and global rooms.

It seems like they are using XMPP to handle a couple social features in the game like showing you which of your friends are online or allowing you to send them text-messages. "Presence flow between players" in this context means receiving real-time notifications when your friends go online or offline.

So as the article says, if the XMPP server has a problem, then the first thing players notice about this is that all their friends appear as offline even though they are not:

> As a result, though people did actually connect to XMPP, the UI showed everyone as offline due to missing presence flow.

---
Tags: networking
---


# Question
Title: Categorize contact & overlap cases for 2D & 3D axis-aligned bounding boxes
My question is similar to this one. I want to determine whether two axis-aligned boxes are not only intersecting, but if they are intersecting and just touching on one edge or face, or if they are overlapping in some way.

Below is an example of these two options.

# Answer
> 2 votes
For each axis, compute whether the intervals spanned by the two boxes are...

* -1: overlapped (minA \< maxB & maxA \> minB)
* 0: adjacent (minA == maxB or minB == maxA)
* +1: separated (minA \> maxB or minB \> maxA)

Return the greatest result you found on any axis.

(ie. The boxes are "overlapping" only if their intervals overlap on every axis. Being "adjacent" on any axis trumps overlapped, and "separated" trumps all)

The numbers I used to label the cases are arbitrary - I picked -1,0,1 to represent the sign of the distance between the boxes: positive if separated, negative if overlapped, and exactly zero if just in contact.

---
Tags: collision-detection, mathematics, aabb, bounding-boxes
---


# Question
Title: How do I create and animate simple polygons directly from code in Unity?
I'm a beginner with Unity, but I know how to code. I'm open to tutorials, of course.

Ideally, I would like to code spacial vertices and connect them into a simple polygon. The polygon would then be animated by changing the vertices over time.

# Answer
As a Unity programmer, you usually do not work with polygons directly.

The usual way to create and animate 3d objects in Unity is not to do that with code. You usually do that by creating them in a 3d modeling program like Maya or Blender. These programs also allow you to define animations for the model. When you import the model into Unity, you can also import its animations. You can then trigger these animations through the Unity Animation System. This approach is both more design-friendly (3d modeling programs offer you WYSIWYG editing instead of just typing numbers and hoping they look good) and more performance-friendly (the deformation logic can be processed on the GPU).

But if you really want to create and manipulate 3d geometry in code (there are some edge-cases where this is indeed useful, like procedural generation for example), check out the class Mesh. It represents the geometry used by a MeshFilter component.

You can either create an entirely new mesh:

```
    Mesh mesh = new Mesh();
    GetComponent<MeshFilter>().mesh = mesh;

```

Or you can obtain the reference to an existing mesh

```
    Mesh mesh =  GetComponent<MeshFilter>().mesh;

```

You can then manipulate that mesh:

```
    mesh.vertices = /* Vector3[] of polygon corners */;
    mesh.uv = /* Vector2[] of the UV texture coordinates for the polygon corners */;
    mesh.triangles = /* int[] of indexes in the vertices array. Every 3 entries define one polygon */

```

When you are finished manipulating the mesh, you might need to update a couple precomputed values. Depending on what you changed and what kind of material you use, not all three of these might be necessary:

```
    mesh.RecalculateBounds(); /* important for culling calculation */
    mesh.RecalculateNormals(); /* required by some shaders */
    mesh.RecalculateTangents(); /* required by some shaders */

```
> 0 votes

---
Tags: unity, animation, vertex, low-poly
---


title: Calculating unit wheeling

text:
# Question
Title: Calculating unit wheeling
The user clicks a unit to select it for a move. Its going to move to wherever they click next.

It's centre c is point cf They then click a point it is to move to. This is to be where the unit centre moves to ct.

It is simple to work out the bearing between f and t and I know how to work out the delta. What I would like to simulate is a unit wheeling. Think in terms of a napoleonic battalion of a thousand men in 2 or 3 lines. They don't just spin to face the new place they will move to. Turning is handled by wheeling. The unit rotates around the nearest corner until it faces in the direction of ct giving a rotated point rcf and then moves in a straight line finishing with a facing based on the bearing between rcf and ct.

I need to somehow calculate that wheel to get rcf.

My question is: how do I do that?

My first thought was calculate the delta offset from the unit facing and then rotate cf in relation to the nearest corner.

That cannot be right though.

If the unit starts facing directly north and you click west then that delta would be 90 degrees. If you rotate the unit by the left corner by 90 degrees the facing would be out though. The left corner would end up where I want the centre to be.

This is rather like the user is dragging a rectangle projected from the front of the unit around. It rotates around either corner of the unit ending up with it's centre wherever the user clicks.

I'm not using any gaming engine so I'll be writing any c# to do the trig.

**Edit.**

I don't think my drawing skills are really up to this but I'll see what I can come up with.

The unit must rotate around one corner such that it would move directly forward and end up with it's centre where the user clicks.

One way to work this out would be to calculate the rotated point degree by degree of rotation. Then project out at 90 degrees and see if that hits the required point.

If you imagine opening a door.

There's a stick attached to the centre.

A spot on the floor represents where the unit moves to.

As you open the door the stick moves and will eventually come to that point.

Here's an attempt at a drawing.

Bear in mind units can ( could ) only move straight forward but they can also wheel.

The unit starts off in blue position.

The user clicks at a point where the red arrow head is.

This is not on that blue line which projects at 90 degrees to it's centre which is it's original facing (or bearing).

That means it must wheel.

The delta is to the left so it's going to wheel (hinge) around the left corner.

Those guys on the left of the unit stay where they are. Those on the far end do the most movement.

When a line projected from it's centre crosses that point it needs to go to then it's got the right rotation.

This is represented by the red line.

So the unit starts it's move by wheeling from blue to red state.

That point it wants to get to is now straight ahead of it's centre.

So it can then move straight forward to it.

The dotted line is to exaggerate the fact I'm looking to somehow calculate where that central point has to be after it's wheeled and is ready to move directly forward.

Any ideas?

# Answer
You've almost got it in the diagram you added. Here, let's take the dotted arrow you drew, and extend it into the full circle traced out by the center of the leading edge as it swings around the pivot:

You can see the line from our destination, through the center of our formation after it's completed the wheeling maneuver, is one of two such lines that exactly kiss this circle.

Put another way, our pivot, our destination point, and the center of our leading edge at the end of the wheel form a right-angled triangle. So now we can find all the angles we need with a little trigonometry.

Easiest is the angle \\$\alpha\\$, which is the bearing to the destination:

```
Vector2 pivotToDestination = destination - pivot;
float bearingRadians = Mathf.Atan2(pivotToDestination.y, pivotToDestination.x);

```

Next is the angle \\$\beta\\$, the difference in angle between this bearing, and the rotation we want to perform:

```
float halfWidth = formation.width / 2f;
float hypotenuse = Vector2.Length(pivotToDestination);
float differenceRadians = Mathf.Acos(halfWidth / hypotenuse);

```

Leaving us with the angle we need to wheel, \\$\theta\\$:

```
float wheelingRadians = bearingRadians - differenceRadians;

```

There are likely some additional sign considerations to attend to if we're rotating clockwise instead of counter-clockwise, or wheeling more than 180 degrees, but since I'm at the end of my lunch hour, those will be left as an exercise for the reader for the time being. ;)

Hopefully that gives you the inroad you need to tackle this problem.
> 1 votes

---
Tags: c#, mathematics, rotation
---


# Question
Title: Scaling a rotated child with parent-child transforms
In unity, if you parent something to another object, then give the child some rotation, and scale the parent, the scale applies to some arbitrary axis to the child, here's some pictures to demonstrate:

Now I scale the Z axis of the parent object and this happens:

My from scratch game does not do this. Rather it applies the parent scale along the same local axis on the child, so you get this:

I don't know how to achieve Unity's scaling behaviour though. Right now transformations are combinations of standard transform matrices that are just applied child to parent. Like this:

```
Matrixf child = Matrixf::Translate(childTrans) * Matrixf::Rotate(childRotation) * Matrixf::Scale(childScale);
Matrixf parent = Matrixf::Translate(parentTrans) * Matrixf::Rotate(parentRotation) * Matrixf::Scale(parentScale);

Matrixf worldChildTransform = parent * child;

```

Transform matrices defined as such:

```
inline static Matrix Translate(Vec3<T> translate)
{
    Matrix mat;
    mat.m[0][0] = T(1.0); mat.m[0][1] = T(0.0); mat.m[0][2] = T(0.0); mat.m[0][3] = translate.x;
    mat.m[1][0] = T(0.0); mat.m[1][1] = T(1.0); mat.m[1][2] = T(0.0); mat.m[1][3] = translate.y;
    mat.m[2][0] = T(0.0); mat.m[2][1] = T(0.0); mat.m[2][2] = T(1.0); mat.m[2][3] = translate.z;
    mat.m[3][0] = T(0.0); mat.m[3][1] = T(0.0); mat.m[3][2] = T(0.0); mat.m[3][3] = T(1.0);
    return mat;
}

```

```
inline static Matrix Rotate(Vec3<T> rotation)
{
    // This is a body 3-2-1 (z, then y, then x) rotation
    const T cx = cos(rotation.x);
    const T sx = sin(rotation.x);
    const T cy = cos(rotation.y);
    const T sy = sin(rotation.y);
    const T cz = cos(rotation.z);
    const T sz = sin(rotation.z);

    Matrix res;
    res.m[0][0] = cy*cz;    res.m[0][1] = -cx*sz + sx*sy*cz;    res.m[0][2] =  sx*sz + cx*sy*cz;    res.m[0][3] = T(0.0);
    res.m[1][0] = cy*sz;    res.m[1][1] =  cx*cz + sx*sy*sz;    res.m[1][2] = -sx*cz + cx*sy*sz;    res.m[1][3] = T(0.0);
    res.m[2][0] = -sy;      res.m[2][1] = sx*cy;                res.m[2][2] = cx*cy;                res.m[2][3] = T(0.0);
    res.m[3][0] = T(0.0);   res.m[3][1] = T(0.0);               res.m[3][2] = T(0.0);               res.m[3][3] = T(1.0);
    return res;
}

```

```
inline static Matrix Scale(Vec3<T> scale)
{
    Matrix mat;
    mat.m[0][0] = scale.x;  mat.m[0][1] = T(0.0);   mat.m[0][2] = T(0.0);   mat.m[0][3] = T(0.0);
    mat.m[1][0] = T(0.0);   mat.m[1][1] = scale.y;  mat.m[1][2] = T(0.0);   mat.m[1][3] = T(0.0);
    mat.m[2][0] = T(0.0);   mat.m[2][1] = T(0.0);   mat.m[2][2] = scale.z;  mat.m[2][3] = T(0.0);
    mat.m[3][0] = T(0.0);   mat.m[3][1] = T(0.0);   mat.m[3][2] = T(0.0);   mat.m[3][3] = T(1.0);
    return mat;
}

```

EDIT: Some more information about the matrices in this specific case:

Given this configuration

```
Parent position = (0, 0, 3)
Parent scale = (0.5, 0.5, 0.2)
Parent rotation = (0, 0, 0) (euler angles, radians)

Child local position = (0, 0, 4.2)
Child local scale = (1, 1, 1)
Child local rotation = (0, 0.9, 0) (euler angles, radians)

```

Then we have the following matrices

Child (combined translation, rotation and scale)

```
{0.621609986, 0.000000000, 0.783326924, 0.000000000}
{0.000000000, 1.00000000, 0.000000000, 0.000000000}
{-0.783326924, 0.000000000, 0.621609986, 4.19999981}
{0.000000000, 0.000000000, 0.000000000, 1.00000000}

```

Parent (combined again)

```
{0.500000000, 0.000000000, 0.000000000, 0.000000000}
{0.000000000, 0.500000000, 0.000000000, 0.000000000}
{0.000000000, 0.000000000, 0.200000003, 3.00000000}
{0.000000000, 0.000000000, 0.000000000, 1.00000000}

```

Then parent * child gives this:

```
{0.310804993, 0.000000000, 0.391663462, 0.000000000}
{0.000000000, 0.500000000, 0.000000000, 0.000000000}
{-0.156665385, 0.000000000, 0.124321997, 3.83999991}
{0.000000000, 0.000000000, 0.000000000, 1.00000000}

```

# Answer
After some experiments, I figured this out, and as was noticed in the comments to my question it was not to do with my matrix multiplication order, but rather something else entirely.

After calculating the world transform of my object, I decomposed it into a vec3 translation, vec3 scale and quat rotation. This operation stripped out what is effectively a shear operation on the child cube. Now I just save the world matrix for use in rendering later, and the problem is solved!
> 2 votes

---
Tags: rotation, matrix, transformation, coordinates, scale
---


# Question
Title: How to add multiple floors to a map in a text-based game?
I decided to learn how to make games during this quarantine. I am reading Mission Python, a book that teaches how to make games using python and pygame. I'm halfway through it, but the game only has one map.

I'm trying to challenge myself by adding a basement and an upstairs room, but the book doesn't have anything on making multiple floors.

Current code for my map:

```
###############
##    MAP    ##
###############

MAP_WIDTH = 5
MAP_HEIGHT = 10
MAP_SIZE = MAP_WIDTH * MAP_HEIGHT

GAME_MAP = [ ["Room 0 - where unused objects are kept", 0, 0, False, False] ]

outdoor_rooms = range(1, 26)
for planetsectors in range(1, 26): #rooms 1 to 25 are generated here
    GAME_MAP.append( ["The dusty planet surface", 13, 13, True, True] )

GAME_MAP  += [
        #["Room name", height, width, Top exit?, Right exit?]
        ["The airlock", 13, 5, True, False], # room 26
        ["The engineering lab", 13, 13, False, False], # room 27
        ["Poodle Mission Control", 9, 13, False, True], # room 28
        ["The viewing gallery", 9, 15, False, False], # room 29
        ["The crew's bathroom", 5, 5, False, False], # room 30
        ["The airlock entry bay", 7, 11, True, True], # room 31
        ["Left elbow room", 9, 7, True, False], # room 32
        ["Right elbow room", 7, 13, True, True], # room 33
        ["The science lab", 13, 13, False, True], # room 34
        ["The greenhouse", 13, 13, True, False], # room 35
        [PLAYER_NAME + "'s sleeping quarters", 9, 11, False, False], # room 36
        ["West corridor", 15, 5, True, True], # room 37
        ["The briefing room", 7, 13, False, True], # room 38
        ["The crew's community room", 11, 13, True, False], # room 39
        ["Main Mission Control", 14, 14, False, False], # room 40
        ["The sick bay", 12, 7, True, False], # room 41
        ["West corridor", 9, 7, True, False], # room 42
        ["Utilities control room", 9, 9, False, True], # room 43
        ["Systems engineering bay", 9, 11, False, False], # room 44
        ["Security portal to Mission Control", 7, 7, True, False], # room 45
        [FRIEND1_NAME + "'s sleeping quarters", 9, 11, True, True], # room 46
        [FRIEND2_NAME + "'s sleeping quarters", 9, 11, True, True], # room 47
        ["The pipeworks", 13, 11, True, False], # room 48
        ["The chief scientist's office", 9, 7, True, True], # room 49
        ["The robot workshop", 9, 11, True, False] # room 50
        ]

#simple sanity check on map above to check data entry
assert len(GAME_MAP)-1 == MAP_SIZE, "Map size and GAME_MAP don't match"

```

# Answer
Not quite sure if you're asking to add a new room or a new floor but if you want to add a new room you can simply write in another entry to that large `array` you have there

```
...
["The pipeworks", 13, 11, True, False], # room 48
["The chief scientist's office", 9, 7, True, True], # room 49
["The robot workshop", 9, 11, True, False] # room 50

["basement", 9, 11, True, False] # your first new room
["upstairs", 15, 8, True, False] # your second new room
]

```

If your looking for a whole new floor, if have some sort of structure you're using to store your current game map, you can make an array of them to have multiple floors, so something like:

```
GAME_MAP_FLOOR_ONE = [ ["Room 0 - where unused objects are kept", 0, 0, False, False] ]
GAME_MAP_FLOOR_TWO = [ ["Room 0 - where unused objects are kept", 0, 0, False, False] ]
GAME_MAP_ARRAY_OF_FLOORS = [GAME_MAP_FLOOR_ONE,GAME_MAP_FLOOR_TWO]

```

Hope this helps point you in the right direction
> 0 votes

---
Tags: python, maps, pygame, text-based
---


# Question
Title: How to enable the option "edit physics shape" in the Sprite Editor?
I can successfully import `.png` files, create tilesets, and use them in my tilemaps in Unity. Thanks to DMGregory, I just learned that there exists an option to customize the `Tilemap Collider 2D` in the `Sprite Editor`, which allows me to set a custom collider for every tile instead of going through them one by one.

The steps I follow while creating a tileset in Unity is as follows.

1. Import the `.png` file.
2. Open the Sprite Editor.
3. Select the option `Multiple` for `Sprite Mode`.
4. Select `Slice` from the Sprite Editor.

Then, I create a `Tile Palette` in a folder, drop and drag my created tiles, and start creating my level.

I have never encountered the option to modify the colliders tile by tile. What am I doing wrong?

# Answer
That particular guide is a few years old. In recent Unity versions, this button has been renamed, but it's still in the same place:

1. Select your spritesheet texture
2. Open the Sprite Editor
3. Click the drop-down labelled "Sprite Editor" in the top-left of the window
4. Choose "Custom Physics Shape" from the drop-down menu

You can read more about how to use this feature in the Unity documentation.
> 1 votes

---
Tags: unity, tilemap, collider
---


title: Scaling Uma Character Unity 3d

text:
# Question
Title: Scaling Uma Character Unity 3d
My room is bigger than my UMA character so on spawn my character looks tiny. I have found this link: http://answers.unity3d.com/questions/988134/uma-how-to-increase-npc-avatar-scale.html

but everywhere I put my code, it does not change my avatars features. Here is my code:

```
using UnityEngine;
using System.Collections;
using UMA;

public class UMACreator1 : MonoBehaviour {
    public UMAGeneratorBase generator;
    public SlotLibrary slotLibrary;
    public OverlayLibrary overlayLibrary;
    public RaceLibrary raceLibrary;
    public RuntimeAnimatorController animator;

    [Range(0.0f, 1.0f)]
    public float bodyMass = 0.5f;

    private UMADynamicAvatar umaDynamicAvatar;
    private UMAData umaData;
    private UMADnaHumanoid umaDnaHuman;
    private UMADnaTutorial umaDnaTutor;

    private int numberOfSlots = 20;

    void GenerateUMA()
    {

        GameObject go = new GameObject("MyUMA");
        umaDynamicAvatar = go.AddComponent<UMADynamicAvatar>();

        umaDynamicAvatar.Initialize();
        umaData = umaDynamicAvatar.umaData;

        umaDynamicAvatar.umaGenerator = generator;
        umaData.umaGenerator = generator;

        umaData.umaRecipe.slotDataList = new SlotData[numberOfSlots];

        umaDnaHuman = new UMADnaHumanoid();
        umaDnaTutor = new UMADnaTutorial();
        umaData.umaRecipe.AddDna(umaDnaHuman);
        umaData.umaRecipe.AddDna(umaDnaTutor);

        CreateMale();

        umaDynamicAvatar.animationController = animator;

        umaDynamicAvatar.UpdateNewRace();

        go.transform.parent = this.gameObject.transform;

        go.transform.localPosition = Vector3.zero;
        go.transform.localRotation = Quaternion.identity;

     }

     void CreateMale()
     {
        var umaRecipe = umaDynamicAvatar.umaData.umaRecipe;
        umaRecipe.SetRace(raceLibrary.GetRace("HumanMale"));

        umaData.umaRecipe.slotDataList[0] = slotLibrary.InstantiateSlot("MaleFace");
        umaData.umaRecipe.slotDataList[0].AddOverlay(overlayLibrary.InstantiateOverlay("MaleHead02"));

    umaData.umaRecipe.slotDataList[1] = slotLibrary.InstantiateSlot("MaleEyes");
    umaData.umaRecipe.slotDataList[1].AddOverlay(overlayLibrary.InstantiateOverlay("EyeOverlay"));

    umaData.umaRecipe.slotDataList[2] = slotLibrary.InstantiateSlot("MaleInnerMouth");
    umaData.umaRecipe.slotDataList[2].AddOverlay(overlayLibrary.InstantiateOverlay("InnerMouth"));

    umaData.umaRecipe.slotDataList[3] = slotLibrary.InstantiateSlot("MaleTorso");
    umaData.umaRecipe.slotDataList[3].AddOverlay(overlayLibrary.InstantiateOverlay("MaleBody02"));

    umaData.umaRecipe.slotDataList[4] = slotLibrary.InstantiateSlot("MaleHands");
    umaData.umaRecipe.slotDataList[4].SetOverlayList(umaData.umaRecipe.slotDataList[3].GetOverlayList());

    umaData.umaRecipe.slotDataList[5] = slotLibrary.InstantiateSlot("MaleLegs");
    umaData.umaRecipe.slotDataList[5].SetOverlayList(umaData.umaRecipe.slotDataList[3].GetOverlayList());

    umaData.umaRecipe.slotDataList[6] = slotLibrary.InstantiateSlot("MaleFeet");
    umaData.umaRecipe.slotDataList[6].SetOverlayList(umaData.umaRecipe.slotDataList[3].GetOverlayList());

    umaData.umaRecipe.slotDataList[3].AddOverlay(overlayLibrary.InstantiateOverlay("MaleUnderwear01"));
    umaData.umaRecipe.slotDataList[5].AddOverlay(overlayLibrary.InstantiateOverlay("MaleUnderwear01"));

    umaData.umaRecipe.slotDataList[0].AddOverlay(overlayLibrary.InstantiateOverlay("MaleEyebrow01",Color.black));

}

// Use this for initialization
void Start () {
    GenerateUMA();
}

// Update is called once per frame
void Update () {
    if(bodyMass!=umaDnaHuman.upperMuscle)
    {
        SetBodyMass(bodyMass);
        umaData.isShapeDirty = true;
        umaData.Dirty();
    }
}

void SetBodyMass(float mass)
{
    umaDnaHuman.upperMuscle = mass;
    umaDnaHuman.upperWeight = mass;
    umaDnaHuman.lowerMuscle = mass;
    umaDnaHuman.lowerWeight = mass;
    umaDnaHuman.armWidth = mass;
    umaDnaHuman.forearmWidth = mass;
}
}

```

And here's the image. I want him to be as big as the chair

# Answer
> 1 votes
I had my UMA as a child to a game object. I wrote a script attached to the game object that changed the transform size to a set Vector3 in the update function (I think you have to change the transform value after the UMA is generated).

```
 private Vector3 usualSize = new Vector3(3, 3, 3);
 private bool isFirstUpdate=true;

// Use this for initialization
void Start () {

}

// Update is called once per frame
void Update () {
    if(isFirstUpdate)
    {
      this.gameObject.transform.localScale = usualSize;
      isFirstUpdate=false;
    }
}

```

# Answer
> 1 votes
I had the same problem with **Unity3D 2019** and **Uma 2**

I finally found the solution in this video : UMA FAQ #3: How do I make Males & Females the same size?

Go to the asset: `UMA > Content > UMA_Core > HumanMale > DNA > HumanMaleDNAConverterController.asset`

In the `OVERALL MODIFIERS` modify the `Scale` in `Adjust Scale`

---
Tags: unity, scale
---


# Question
Title: How to make a paradox-style grand strategy map with selectable provinces using bitmap?
I'm in the process of designing a paradox-style grand-strategy game with a large map containing thousands of provinces. I plan on creating the map in a similar style to Paradox; by having a .bmp color file showing all of the games provinces, each with a unique RGB color and code that the game will reference when clicking on the map for the player to interact with the subsequent province.

This should give you an idea of what I'm talking about

Each of these provinces (particularly those on land) will have their own script/text file attached to each of them that displays their current stats (such as development/population/buildings ect.) in addition, whenever the player clicks on the map, the game will check the area he clicked on and what RGB code the province he clicked on had. This will be used for a variety of the games interactions, such as moving armies and building upgrades among many other things.

Unfortunately, I'm not particularly sure how I should go about this. I have around a year of experience working in unity, but most of that is with scene/world creation and basic scripting. I've been trying to find info on how people suggest creating this sort of system, but much of it is outdated or confusing.

Can anyone here walk me through step-by-step what I'll need to do to create such a province system in Unity using C#? What else will I need to know in order to get this working?

# Answer
I'd absolutely look into getting the screenspace coords of a mouse click and using a shader to get the pixel value at that location.

Also using scriptable objects to store information about each province is how I would do it.

Hope this helps point you in the right direction.
> 0 votes

# Answer
You can describe a convex polygon shape (collection of points like Vector2) for each province. Then all you need to do is just to check whether the point where the player clicked located inside of one of that polygons.

But first, you better to calculate AABB (axis aligned bounding box) for each of your polygons. It's easy. Then initialize two arrays with your provinces (one for x coordinate, and one for y) and sort by begin, then by the end position of corresponding axis. When user clicks on map, do binary search of the each object's AABB which overlaps with click position, then check whether this point lies inside of each of corresponding convex shape (just google it, that's easy, hint: cross product for each pair of vertices of your convex shape and vector between first vertex and the click point).
> 0 votes

# Answer
1. Import your colour-coded map into Unity as a 2D texture.
2. Inside its import settings, tick the "Read/Write Enabled" checkbox under the "Advanced" fold-out. (This makes its pixel data accessible to CPU-side scripts)
3. Set the import format to something uncompressed - you don't want the compressor to make small changes to your colour values that might make them map to the wrong territory! Also ensure the max size setting is large enough that your texture won't be down-sampled when building the game (which can also muddy the colours)
4. Place a Quad in your scene where you want your map to appear, and scale it to the right size for your needs. By default it will have a MeshCollider on it - we'll use that to test where our mouse picking ray hits the map.
5. Create an unlit material that uses your map texture, and assign it to the quad so you can see the map features on it. This is purely for player visibility, and isn't used for the picking logic, so you can use a different image here if you want - say one with more naturalistic colours and texture detail.

Now we can pick our territory colours from this map using a simple script:

```
public class MapPicker : MonoBehaviour
{
    // Assign your quad's collider here.
    public MeshCollider mapShape;

    // Assign your colour-coded territory map here.
    public Texture2D colourMap;

    // We'll use this to quickly find a territory by its colour.
    Dictionary<Color32, Territory> _territoryLookup;

    private void Start() {
        // Fetch the pixel data of the texture as a big block we can iterate through quickly.
        var pixels = colourMap.GetPixels32();

        // Prep our lookup table. For efficiency, tell it how many territories you expect.
        _territoryLookup = new Dictionary<Color32, Territory>(2000);

        // Quick & dirty: we'll generate a new territory for each unique colour we find.
        // Later, you can instead populate your lookup table from ScriptableObjects if needed.
        foreach(var pixel in pixels) {
            if (_territoryLookup.ContainsKey(pixel))
                continue;

            _territoryLookup.Add(pixel, new Territory());
        }
    }

    void Update() {
        // If no click this frame, abort. Nothing to do.
        if (!Input.GetMouseButtonDown(0))
            return;

        // Cast a ray against the map to see if/where it hits.
        var ray = Camera.main.ScreenPointToRay(Input.mousePosition);

        if (!mapShape.Raycast(ray, out RaycastHit hit, float.PositiveInfinity))
            return;  // If we missed the map entirely, abort.

        // Map the hit point on the quad to a pixel coordinate in our texture.
        var mapSize = new Vector2(colourMap.width, colourMap.height);
        var hitPoint = Vector2Int.RoundToInt(Vector2.Scale(hit.textureCoord, mapSize));

        // Fetch the colour of the pixel we hit.
        var colour = (Color32)colourMap.GetPixel(hitPoint.x, hitPoint.y);

        // Now we can look up our territory using that colour.
        var territory = _territoryLookup[colour];

        /* TODO: do something with the territory we have clicked */
    }
}

```
> 0 votes

---
Tags: unity
---


# Question
Title: How can I mod a game to render only certain pixels during pixel shader stage?
I am a gamer and hobbyist programmer in game dev and deep learning algorithms.

I want to train a deep learning algorithm like DLSS from NVIDIA, which can render a complete frame by taking certain pixels of the frame. The logic is that since all the pixels are not rendered, it gives higher frame rate.

But first, I want to know how I can mod an already created game to force it to render only certain pixels.

# Answer
> 1 votes
You could potentially use DLL injection/detouring to intercept drawing commands from the game on their way to the graphics driver.

You'd detect the calls for the start of each frame, and add a your own command that draws a dithered pattern to the stencil buffer to seed it. Then you'd modify the game's drawing commands to draw only to the stencilled pixels when you pass them along to the real graphics driver.

This would get very complicated on big modern games, which might render to many off-screen targets for things like shadow maps, virtual texturing, and reflections, might be using the stencil buffer for their own purposes that would get stomped by your intervention, or might try to use results from adjacent pixels mid-frame (say for ambient occlusion, screenspace reflections, or antialiasing), before your ML solution has done its work to fill them in.

So, it's conceivable, but likely to be quite difficult to do well or achieve good performance.

If you want to test your ML techniques, I'd argue a much better solution is to get a free game engine like Unity or Unreal, and set up one of the sample game scenes available for those engines. That will give you a representative test case, with the advantage that you have access to the game's internals and the engine API, so you can add your selectively sampled rendering at the source, rather than trying to splice it into a set of rendering commands that were issued with no awareness of it.

---
Tags: fragment-shader, modding
---


# Question
Title: Algoritm for scaling an 3D model with fixed edges
I am looking for an algorithm that allows me to scale a 3D model with certain fixed edges. For example scaling up a window should have the frame remain a fixed width while the length of the frame pieces increases or a kitchen sink should have the tap remain at a fixed size while the rest increases.

Note that in the example it's a 2D model while in reality it's a 3D model, scaling can also happen along certain axis (so only scaling over the Z-axis, rather than over all axis at the same time).

Performance is of minor concern(it's a small part of the loading sequence to which I can allocate an extra thread) so a c#/pseudocode solution is acceptable, it doesn't have to be implementable as a shader.

So far I was thinking about some kind of energy formulation/graph based system but I cannot get that to work with possible with death ends in the model. I looked for scientific papers on the issue but couldn't find the right paper (I vaguely remember there being one I learned about in university).

edit: it should also be able to handle situations like this:  where the parts that shouldn't scale are intermixed with the geometry of the object, this could also (in you don't want all of this to focus on architecture) be something like the eyes of an animal.

Lastly there is also the possibility of some edges being fixed and others (in the same face) not being fixed, I was hoping to solve this like so:

# Answer
> 1 votes
Here's a rough sketch of an approach you can use:

Add an extra texture coordinate to each vertex of your mesh. This will serve as an index, identifying which scaling behaviour that vertex should use.

* 0 : default scaling behaviour
* 1 : rigid part #1
* 2 : rigid part #2
* ... etc.

When you prepare to draw the mesh, compute a separate transformation matrix for each of these scaling behaviours. The 0th/default behaviour is just your normal model-to-world matrix. You can compute the others as...

```
float3 offset = (modelToWorld * rigidPartRootPoint).xyz;
float4x4 rigidPartMatrix = Translate(offset) * Rotate(objectRotation) * Scale(1, 1, 1);

```

Here "root point" is the place where this rigid part is "attached" to the underlying stretchable object. This point will track with the stretching applied to the rest of the object, while the rest of the points in the rigid part will maintain their exact offset relative to the root.

Upload each of these matrices to your shader as an array of uniform variables. (Optionally, you can pre-multiply each one with your view projection matrix to save an extra matrix multiply in the shader)

Finally, in your vertex shader, use your extra texture coordinate to select which matrix to use when transforming the vertex.

This will require your model's topology to be set up such that each vertex follow wholly one scaling behaviour or the other. If you need a blend, then you're getting into bone weight territory: each vertex will need multiple model matrix indices and an interpolation weight between them.

---
Tags: c#, 3d, geometry, 3d-meshes, scale
---


# Question
Title: Box2d: crash on createBody in beginContact callback
I am getting this error on creating body in contactListener

```
com.patchnhack.gdx A/libc: Fatal signal 11 (SIGSEGV), code 1, fault addr 0x58 in tid 4628 (GLThread 15500), pid 4583

```

I am creating a body in beginContact callback like this:

```
    ......
    public void beginContact(Contact contact) {
        .....
        Fixture fixA = contact.getFixtureA();
        Fixture fixB = contact.getFixtureB();

        If( fixA.getUserData()== "ground" || fixB.getUserData()== "ground")
            createBody(0,0);
        ....
        ....
    }

// createbody method in screen class
    public void createBody(float x, float y, float radius) {
        BodyDef def = new BodyDef();
        def.type = BodyDef.BodyType.DynamicBody;
        def.position.set(x ,y);
        def.fixedRotation = true;
        body = world.createBody(def);
        CircleShape shape = new CircleShape();
        shape.setRadius(radius);
        FixtureDef fdef = new FixtureDef();
        fdef.restitution = 0.5f;
        fdef.shape = shape;
        fdef.density = 2;
        body.createFixture(fdef).setUserData("chip");
    }

```

I know this is something due to async with render thread. Please tell me how can I resolve this or some better way to do this.

edit: I have even tried

```
Gdx.app.PostRunnble(new Runnable(){
..
})

```

But that works strangely and bodies keep populating and ultimately crashing the app.

# Answer
It was my silly mistake that ContactListener was invoked again and again because the body was responsible for making contact under gravity and creating infinite loop ;P

I enclosed the createBody() code inside `Gdx.app.postRunnable(new Runnable(){ .... }` And check if contact has already been made by a flag.
> 0 votes

---
Tags: java, libgdx, android, box2d, multithreading
---


title: Java - set resolution of game

text:
# Question
Title: Java - set resolution of game
Hi everybody I am making small game using  ~~pure Java 8 and rednering it by Java AWT `Graphics2D` method~~ . My question is how to make that user can change the quality of game. For example: 720p, 1080p, 1440p. Something similar that is when playing YouTube video.

The steps I will make?

* Make 3 pictures of each, each with different quality.
* Then load them.

**Is this the right way?**

But Java is default only 72dpi so each of them will be the same quality. So how to render it in different resolution?

Thanks in advance, Maratonec

Edit:

I will be using LibGDX for rendering. So I will be using OpenGL. ~~But still don’t know how to make in LibGDX.~~

**Edit:**

So I now understand that using LibGDX mipmap I will make my scaling nicer. So I will have 1440p image and scale it up down? **Or** I will have to have each image for each resolution (720p, 1080p,1440p) and they will change to user selected resolution and only scaling to the window size?

The second method I have in mind how to do, but for second I need code example.

Thanks one more time for spending time with beginner!

# Answer
This can be done via scaling, see here.

However...

**Q:** Why do render quality levels like you are proposing to implement, exist in games & video? That is, lowering texture quality while keeping the window / viewport size the same?

**A:** To improve performance on lower spec machines.

But... windowed Java AWT can't (?) be assumed to work that way. Instead, it uses the native resolution of the desktop and the size of the window within that desktop, to define the number of pixels / texels to be rendered, in x & y. AWT is not really designed for games or videos, but for simple desktop UI, graphing and diagrams. (Whether AWT's scaling and rendering mentioned above is GPU-accelerated, is up for debate.)

So if you keep things at the same size, but lower the quality, then you are possibly not changing the number of pixels that must be rendered - but rather just having to double or quadruple those texels into the final render's pixels. This makes the game look worse, potentially with no performance improvement.

So if you want a quality setting *that will definitely decrease the rendering load* (and thus isn't a complete waste of time!), you need to use a render technology like OpenGL for Java, in the form of e.g. LibGDX renderer, LWJGL, or JOGL. This is because GPU-based rendering actually will do *less* work when you render fewer texels, so that lowering quality *actually does something useful*.

So to have any assured benefits to what you're doing, I would suggest switching to a renderer that is intended for games. Else you may be wasting your time. **EDIT:** Google "libgdx mipmap" for more.
> 1 votes

---
Tags: java, textures, rendering, graphics, resolution
---


# Question
Title: How to make the character dash forward in Roblox?
In my game, I want to make a skill in a tool to dash forward for a specific range and if the character came in contact with a humanoid during the dash, it stops right on contact and stops the other humanoid from moving temporarily too and deal damage.

I don't know what functions should I do and where to look for them... I figured how to use onActivate and getting the mouse through Equipped. Appreciate any help and guidance.

# Answer
> 1 votes
It sounds like you're looking for `BodyForce`.

A good place to start on how it works might be the code in this video showing a simple script for a jump pad. The jump pad object responds when touched by parenting a `BodyForce` instance to the object that touched it for a short time.

# Answer
> 1 votes
To answer your question would require a tutorial-length post. So many things come into play including Filtering Enabled settings. However, I can answer "How to make the character dash forward in Roblox" for you.

The first thing you will need to do is capture the player object. There are a few ways to do this, but the easiest way to capture the player object is when they first spawn into your server world. If you create a regular 'Script' and put it somewhere in your 'Workspace', all you have to do is add:

```
game.Players.PlayerAdded:Connect(function(PlayerObject)

workspace.Data.Player.Value = PlayerObject

end)

```

Now when a player spawns into your world, the first line of code captures the player object and stores it in the variable named PlayerObject. The second line of code that I used, takes the player object and stores it into an 'ObjectValue' container that I added and named 'Player', and then stored in a folder which I called 'Data'. Now I can get the player object from any server-sided script by using:

```
variablename = workspace.Data.Player.Value

```

This can be modified any way you please, as long as you capture and store the player object somehow. Once you have the player object, you can adjust the player's speed by using:

```
variablename.Character.Humanoid.Walkspeed = 50 -- or whatever number you want

```

Hope this helps. Good Luck.

---
Tags: lua, roblox
---


# Question
Title: How can I prevent picking up health items when I'm already at max health?
This is what I have so far..

```
public class Per10HealthCollect :MonoBehavior

    void OnTriggerEnter(Collider other)
    {
        if (GlobalHealth.healthValue >= 91)
        {
            GlobalHealth.healthValue = 100;
        }
        else
        {
            GlobalHealth.healthValue += 10;
        }
        GetComponent< CapsuleCollider>().Enabled = false;
        this.gameObject.SetActive(false);
    }
}

```

# Answer
First, I'd add a constant to your GlobalHealth class to avoid spreading magic numbers all over your code. Now you can update it in just one place:

```
public class GlobalHealth {

    public const int MAX_HEALTH = 100;

    // ...

```

Now we can simplify your trigger method:

```
public class HealthPickup : MonoBehavior

    public int healthToAdd = 10;

    void OnTriggerEnter(Collider other)
    {
        // If we're already at max health, abort.
        // Don't change the health, don't consume the pickup.
        if (GlobalHealth.healthValue >= GlobalHealth.MAX_HEALTH)
            return;

        // We can use the Min function to choose the smaller of two values,
        // without doing the if-else ourselves. Less repetition, less chance of error! ;)
        GlobalHealth.healthValue = Mathf.Min(GlobalHealth.healthValue + healthToAdd,
                                             GlobalHealth.MAX_HEALTH);

        // Setting our game object to inactive will *also* disable the collider,
        // so we don't need to disable the collider separately.
        gameObject.SetActive(false);
    }
}

```

If you modify the global health in multiple places, you might want to consider moving the clamping logic into that class, and just calling something like `GlobalHealth.Gain(healthToAdd)` \- let GlobalHealth worry about enforcing its own limits.
> 2 votes

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


# Question
Title: How Can I Separate a Mesh Into Two Separate Objects Without Corrupting UV Data?
I'm working in Blender and Unity.

I downloaded my character from DeviantArt here, used Blender along with this addon to import the character's .mmd file to Blender, and saved her as a .blend file in my Unity project's folder. For some reason, when Unity imported her, her textures weren't appearing, so I created new materials and assigned them to the proper slots on the mesh renderer and she looks the way she should:

Now I'm trying to get my character's clothing physics working. I read online that Unity's Skinned Mesh Renderer and Cloth components are the best solutions, but it recommends that the cloth objects be child objects of the main body mesh. However, the character's clothing that I wish to add physics to (her skirt) is a part of the overall mesh.

So, in Blender I selected all of the vertices that make up the skirt and separated them from the main mesh, then saved a skirt.blend file containing just the skirt, then saved another blend file containing everything but her skirt:

After this process, the textures for the main mesh look just fine in Blender, and the UV data looks exactly the same except for the missing vertices that made up the skirt:

However, when Unity imports these files, it looks like the UV data is corrupted:

What's going on here? How can I fix the UV data for the main mesh?

# Answer
> 1 votes
I feel like a bit of a goof for not realizing that in removing vertices, I had changed the ordering of the UVs.

If I had to explain it to someone else with the same issue:

Imagine a drive-thru line (mesh) where 10 customers (vertices) place an order (UVs).

Now imagine that customers 6, 7, and 8 leave the line.

When customer (vertex) 9 comes along to the hand-out window (renderer), they're going to get customer (vertex) 6's order (UV) because no one removed the orders (UVs) that belonged to the now-departed customers (vertices).

All I had to do was go back into the inspector and reassign my materials manually with respect to the now-missing vertices and things are looking just fine.

---
Tags: unity, textures, blender, materials, uv-mapping
---


# Question
Title: How can I resolve this error I'm getting in my movement script?
For my player controlling script, I have attempted to do it so the player can only jump two times, I've not had any errors in the script itself but when I save it and go back on Unity, the error I keep getting is this:

> error CS0120: An object reference is required for the non-static field, method, or property `Collision.gameObject`

This is my code:

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

public class playerController : MonoBehaviour
{
    public float speed;
    public float power;
    private Rigidbody2D rb;
    int numberofJumps = 0;
    public int doubleJump = 2;

    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
        numberofJumps = doubleJump;
    }

    void Update()
    {
        if (Input.GetKey(KeyCode.D))
        {
            rb.AddForce(Vector3.right * speed);
        }

        if (Input.GetKey(KeyCode.A))
        {
            rb.AddForce(Vector3.left * speed);
        }

        if (Input.GetKeyDown(KeyCode.W))
        {
            if (numberofJumps > 0)
            {
                Jump();
            }
        }
    }

    public void Jump()
    {
        rb.AddForce(Vector3.up * power, ForceMode2D.Impulse);
        numberofJumps -= 1;
    }

    void OnCollisionEnter2D(Collision2D col)
    {
        if (Collision.gameObject.tag == "ground")
        {
            numberofJumps = doubleJump;
        }

    }
}

```

The error seems to be specifically regarding this line:

```
if (Collision.gameObject.tag == "ground")

```

# Answer
You're attempting to make a static call on the `Collision` class. Try replacing this line

```
Collision.gameObject.tag == "ground"

```

With the reference to the object `col` passed in

```
col.gameObject.tag == "ground"

```
> 0 votes

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


title: See through sprite?

text:
# Question
Title: See through sprite?
I used gimp to make a newspaper front page. When i import it into unity3D as a png and then rotate it you can see the print on the front reversed as if the newspaper was see-through. I had the same problem when I made a hanging sign for my dungeon. I you walked past the sign and looked back you could see the front of the sign reversed. Whats the trick to prevent this? Thanks for any help.

# Answer
> 1 votes
I would look into using a `plane` instead of a sprite for something like this and changing it's `texture` to be your image. Planes will not draw their backface. `Sprites` aren't really intended to be used in 3d in this way.

---
Tags: unity, sprites, gimp
---


# Question
Title: Call a BlueprintImplementableEvent from c++ in unreal editor?
I created a custom actor:

BPTest.h:

```
#include "GameFramework/Actor.h"
#include "BPTest.generated.h"

UCLASS(Blueprintable, BlueprintType)
class ABPTest : public AActor
{
    GENERATED_BODY()

public:
    ABPTest();

    virtual void BeginPlay() override;

    UFUNCTION(BlueprintImplementableEvent, meta = (DisplayName = "Custom event"))
    void CustomEvent(float Value);
    void CustomEvent_Implementation(float Value);
};

```

BPTest.cpp:

```
#include "ProBuilderPrivatePCH.h"
#include "BPTest.h"

ABPTest::ABPTest()
{
    PrimaryActorTick.bCanEverTick = true;
}

void ABPTest::BeginPlay()
{
    Super::BeginPlay();
    CustomEvent(0.f);
}

void ABPTest::CustomEvent_Implementation(float Value)
{
    UE_LOG(LogTemp, Warning, TEXT("CustomEvent_Implementation: %f"), Value);
}

```

I then created a blueprint from this actor class.

I added an instance of this blueprint actor in my level.

I would like to call this custom event from c++ in the editor, not when the game is started.

I tried this in a custom editor mode (extending FEdMode):

```
bool FProBuilderEdMode::InputKey(FEditorViewportClient *ViewportClient, FViewport *Viewport, FKey Key, EInputEvent Event)
{
    for (TActorIterator<ABPTest> ActorIterator(GWorld); ActorIterator; ++ActorIterator)
    {
        ActorIterator->CustomEvent(1.f);
    }
    return FEdMode::InputKey(ViewportClient, Viewport, Key, Event);
}

```

but it does not work. I assume the game has to be started (hit play) in order for the blueprint event to be taken into account. Is my assumption correct?

How can I call a blueprint function from c++ when the game is not started (Is it even possible)? I have seen `UObject::CallFunctionByNameWithArguments` but it seems dirty.

# Answer
> Nako Sung answer:
>
> Without game, UE4 prevents script functions to be executed accidently. (I don't know the clear reason)
>
> In C++ you can use FEditorScriptExecutionGuard:
>
> ```
> FEditorScriptExecutionGuard ScriptGuard;
> {
>        // your code to execute scripts in editor while the game is not started goes here, for example:
>        for (TActorIterator<ABPTest> ActorIterator(GWorld); ActorIterator; ++ActorIterator)
>        {
>             ActorIterator->CustomEvent(1.f);
>        }
> }
>
> ```
>
> answered Apr 27 '16 at 8:57
>
> arthur.sw

Hey all,

I know this post is pretty old. While reading through arthur.sw's answer and some research, figured out some Engine code that uses FEditorScriptExecutionGuard.

```
EditorTutorial.cpp
void UEditorTutorial::HandleTutorialClosed()
{
    FEditorScriptExecutionGuard ScriptGuard;
    OnTutorialClosed();
}

```

So in short, as long as the ScriptGuard is in scope, you can just call the BlueprintImplementableEvent / NativeEvent function.

Hope this helps someone.
> 3 votes

# Answer
Nako Sung answer:

Without game, UE4 prevents script functions to be executed accidently. (I don't know the clear reason)

In C++ you can use FEditorScriptExecutionGuard:

```
FEditorScriptExecutionGuard ScriptGuard;
{
       // your code to execute scripts in editor while the game is not started goes here, for example:
       for (TActorIterator<ABPTest> ActorIterator(GWorld); ActorIterator; ++ActorIterator)
       {
            ActorIterator->CustomEvent(1.f);
       }
}

```
> 1 votes

---
Tags: scripting, unreal
---


title: Blinking object

text:
# Question
Title: Blinking object
I'm trying to make an element (3D object or UI element) blink in such way:

1. There is a timer which counts down 10.0f seconds to 0.0f.
2. In 10.0f to 9.9f range the object should fade out from opacity 1 to 0.
3. In 9.9f to 9.8f range the object should fade back in from 0 to 1.
4. Then wait 300ms.
5. Then repeat and finally fade out and disappear completely on last 1.0f to 0.0f.

I created a function in Unity:

```
void Update(){
    if ( myTimeVariable < 10.0f && myTimeVariable > 9.9f ) {
        gameObject.GetComponent<Renderer>().material.color.a = (10.0f - myTimeVariable);
    } else if() {
        // The logic continues and makes a long set of
        // else if statements to cover all times.
    }
}

```

(It's originally a coroutine that executes after each `Update()` but here it's shown otherwise for simplicity reasons.)

The problem I'm facing is that at 60 FPS I have these frames available:

```
0ms 16ms 33ms 50ms 66ms 83ms 100ms

```

And on 30 FPS I may have only these:

```
0ms 33ms 66ms 100ms

```

On 30 FPS opacity is changing this way: First I get fully opaque object on 0ms frame. Then on 33ms frame I get 0.67 opaque object. Then on 66ms frame I get 0.34 opaque object and frame 100ms doesn't belong to "fade out" if statement but fading in starts. **Object starts to fade in from 0.34 to 1 over the next 100ms even if it never had 0 opacity state.**

It seems that my method of making blinking object is flawed. It never reaches 0 opacity and **it's very visible in the game that the last state was 0.34 opacity and not 0. Is there a way to make that blinking be certain to go to 0 opacity regardless of frame rate?**

Edit: For "fade in" I only call Unity's `CrossFadeAlpha()` once. That's why it starts from 0.34 and goes to 1 but even if I changed that to the other method still my frames may be available at 80ms and then 120ms and opacity 0.2 -\> 0.2 is the result (never desired 0).

# Answer
> 1 votes
Update is called once a frame, this means that the time between calls depends directly on the frame-rate. This problem can be solved by defining the alpha, a, as a function of t, where 0 \leq t \leq 10. At t = 10, a = 1, and at t = 0, a = 0, so we can define our function as f(t) = 0.1 * t. Psuedo code could appear as follows.

```
// initialize t=0
Update:
  t += Time.deltaTime
  if ( inRange(t, 0, 10) )
    setAlpha(0.1 * t)
  else
    setAlpha(0)

```

In Unity, Time.deltaTime expresses how much time in seconds has elapsed since the last frame.

# Answer
> 0 votes
For stylish control:

**Define this 50-length array A of numbers**:

```
1,0.9,0.8,0.7,0.6,0.5,0.4,0.3,0.2,0.1,0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1

```

These are alpha values for 1/2 second, which is the repeat sequence for the 9 s blinking part of your question (0.1 + 0.1 + 0.3 s). These 9 seconds hold 18 repetitions of 0.5 seconds each. You only specify the 0.5 seconds with this array. As you can see, the values begin with 1, 10 slots later (= 0.1 s later) you have 0, then back to 1, where it stays for 30 numbers (0.3 s). After this, it can repeat.

Whenever you visit your function, you have a time T handy (as you stated).

**Change your T value to start from 0 and end at 10**. Ie. you have values of T like:

0, 0.33, 0.66, ... 5.99, 6.32, ... \[any\]

**Use the value of T to index into the array A of 50 elements, and pick your alpha there**. Index using this statement (pseudo code):

```
IND = 1 + modulo(floor(100 * T), 50)

```

This will produce a number between 1 and 50, no matter what T is. If for example T=0, IND will be 1. If T=0.05, IND will be 6. If T=7.142857, IND will be 15. If T=9, IND will be 1. Etc. Remove the "1 +" if your language uses zero-origin.

Your functions would look like this (sorry, i don't know the expressions for modulo and floor, ie. round down, in your language):

```
A = (array of) 1,0.9,0.8,0.7,0.6,0.5,0.4,0.3,0.2,0.1,0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1
B = (array of) 0.9,0.8,0.7,0.6,0.5,0.4,0.3,0.2,0.1,0 // For the last fade out (length 1 second)

```

and in the loop:

```
:If (T > 10)
    [exit this thingy, do housekeeping]
:else
    :If (T < 9)
        IND = 1 + modulo(floor(100 * T), 50) // modulo(dividend, divisor)
        alpha = A[IND]
    :Else
        IND = 1 + modulo(floor(10 * T), 10) // could simplify into alpha = 10 - T
        alpha = B[IND]
    :End
    [set alpha to your object]
:end

```

Of course, you can now make different sequences, change the lenght of them, make other effects, etc.

# Answer
> -1 votes
You could try calling it inside FixedUpdate() function

---
Tags: unity
---


# Question
Title: Player with Character Controller and children colliders won't collide properly
I have a player that consists on a root object with the Character Controller attached and some children with its components. Those have box colliders attached.

When moving the player I want to be able to collide with other objects using the box colliders, but it won't, instead it will only collide with the Character Controller.

As you can see in the image, the red object didn't stop when the collider crashed with the framed cube, but it did when it did with the Character Controller.

There is any way to use the player colliders instead of the Character Controller for collision detection?

# Answer
> 0 votes
I solved it by using a non kinematic rigidbody on the root player object instead of a Character Controller. I've also changed the cube rigidbody to a kinematic one, since that shouldn't move.

Now I'm using RigidBody.velocity to move the player instead of characterController.Move. Perhaps I should use AddForce instead.

Also, in order to prevent unwanted movements I've put constraints on the x,y,z rigidbody rotantion and y translation (I only want to move the character in 2D). I don't know if this is necessary or could be done different.

Now the collision is done properly, but, as I said, some things I'm not sure if they could be done better.

---
Tags: unity, physics
---


# Question
Title: In Unity, how do I add a MeshFilter to an empty GameObject to generate a procedural model?
My code below is modeled after Unity's documentation. When I put the script into an empty GameObject, the error I get is:

MissingComponentException: There is no 'MeshFilter' attached to the "myMesh" game object, but a script is trying to access it.

How do I add a MeshFilter (and the other necessary Components) to the empty GameObject in order to generate the model procedurally?

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

public class myMesh : MonoBehaviour  {
    public Mesh mesh;

    void Start(){
        mesh= new Mesh();
        GetComponent<MeshFilter>().mesh = mesh;
    }

}

```

# Answer
You can use the AddComponent method to add a new component of your choosing:

```
var filter = AddComponent<MeshFilter>();
filter.mesh = mesh;

var renderer = AddComponent<MeshRenderer>();

```
> 0 votes

---
Tags: unity, c#, gameobject, mesh, exceptions
---


title: UnityYAMLMerge via git command line

text:
# Question
Title: UnityYAMLMerge via git command line
I'm having issues getting the UnityYAMLMerge tool to work, in order to fix conflicts merging a scene in 2 different branches (`myBranch` into `dev`). Here's what I've done:

1. **Set Asset Serialization to Force Text**: In Edit \> Project Settings \> Editor menu, I set Force Text under Asset Serialization Mode. This has been set for the entire lifetime of the project so all applicable git-tracked files should have this setting.
2. **Treat the Files as Binary to Avoid Git Merging Them Automatically**: created `.gitattributes` in project root dir with the following then pushed:

```
*.unity binary
*.prefab binary
*.asset binary

```
3. **Set up UnityYAMLMerge with Git**: copypasted the following into `.git/config`:

```
[merge]
tool = unityyamlmerge

[mergetool "unityyamlmerge"]
trustExitCode = false
cmd = 'C:/Program Files/Unity/Hub/Editor/2019.2.17f1/Editor/Data/Tools/UnityYAMLMerge.exe' merge -p "$BASE" "$REMOTE" "$LOCAL" "$MERGED"

```

Note: the Unity docs state that the UnityYAMLMerge.exe should exist at:

```
C:\Program Files\Unity\Editor\Data\Tools\UnityYAMLMerge.exe

or

C:\Program Files (x86)\Unity\Editor\Data\Tools\UnityYAMLMerge.exe

```

However I do not have an `Editor/` directory at either of these locations, and instead I found the executable at `C:/Program Files/Unity/Hub/Editor/2019.2.17f1/Editor/Data/Tools/UnityYAMLMerge.exe` (2019.2.17f1 does match the version of Unity I'm building this project in).

---

However after all this, when I am in my branch `dev` and try to merge my branch `myBranch` into `dev`, I still receive conflict warnings and am asked to manually fix them:

```
$ git merge myBranch
warning: Cannot merge binary files: Assets/Scenes/ManagerScene.unity (HEAD vs. myBranch)
warning: Cannot merge binary files: Assets/Scenes/2-Paint.unity (HEAD vs. myBranch)
warning: Cannot merge binary files: Assets/Resources/Prefabs/UI/Heatmap.prefab (HEAD vs. myBranch)
Auto-merging Assets/Scenes/ManagerScene.unity
CONFLICT (content): Merge conflict in Assets/Scenes/ManagerScene.unity
Auto-merging Assets/Scenes/2-Paint.unity
CONFLICT (content): Merge conflict in Assets/Scenes/2-Paint.unity
Auto-merging Assets/Resources/Prefabs/UI/Heatmap.prefab
CONFLICT (content): Merge conflict in Assets/Resources/Prefabs/UI/Heatmap.prefab
Automatic merge failed; fix conflicts and then commit the result.

```

From what I understand, the UnityYAMLMerge tool should automatically resolve these conflicts without causing git to prompt me to fix them. Is this correct? Otherwise, what else must I do to use this tool properly?

Thanks for any help!

# Answer
I was able to use the UnityYAMLMerge tool successfully by downloading a git GUI, specifically Sourcetree, and following along with this video. This gave me a clue as to how it may be successfully used via the command line: in Sourcetree, when you merge and get shown the conflicted files, you must launch the UnityYAMLMerge tool for each individual file in order to fix it; I imagine the same must be done via the command line but I do not know how just yet. If I ever find out later I will update this answer.
> 0 votes

---
Tags: unity, git
---


# Question
Title: Which is better practice in Unity? GetComponent<>() or making the variable public?
There are two main ways I am aware of to modify an attached component. Say, the component attached to an object is of type `Animator` and the name is `animator`.

So, in the script, I can write

```
private Animator animator;

```

and then call the function

```
animator = GetComponent<Animator>();

```

Or, I can define the variable as public

```
public Animator animator

```

and then, drag&drop in the Unity UI. Which one is the better practice?

# Answer
> 7 votes
There's a third option I sometimes like to use:

```
[RequireComponent(typeof(Animator))]
public class MyScript : MonoBehaviour {

    [SerializeField, HideInInspector]
    private Animator _animator;

    void OnValidate() {
        _animator = GetComponent<Animator>();
    }
}

```

Breaking this down...

* `RequireComponent` ensures the object actually has the component I need, and Unity will add it at edit time if I forget it, or complain at me if I try to remove it.
* Using both `SerializeField` and `HideInInspector` ensures we can save a value to the variable at edit time and have it save with the scene / carry through into game, without cluttering the Inspector with something we don't need to set manually.
* `OnValidate()` gets called when we add or modify this component, only in the editor, so it can automatically wire up the reference for us without any search cost at runtime.

I wouldn't say this is "the best practice" — a public or serialized private variable is a lot more concise and does basically the same job, this just insulates you against forgetting to assign it. It's a little cheaper than finding the component on startup, but that cost isn't huge, so you can weigh whether the alternatives are worth the extra typing or hook-up. ;)

---

Another alternative you might like: Alex Hetherington has created a handy editor script that simplifies linking up component references. Now you can just add a `[Resolve]` attribute above the serialized component field you want to populate, and it will add a one-click button to populate the field (even populating an array of references), without you having to write your own initialization in `OnValidate()` or elsewhere. Here's a link to the GitHub repository with this and other utilities you can add to your project.

# Answer
> 2 votes
First of all when you type

```
public Animator animator

```

what you're talking about is a SerializedField. You can do the same with private variables by doing

```
[SerializeField] private Animator animator

```

But as for your question the second one is better because it is faster. Using one or two `GetComponent<>()` calls generally isn't too bad, but if you use many in a single frame it could be a problem.

---
Tags: unity, performance
---


# Question
Title: Exporting models from Crocotile3D to Unreal Engine 4 (.obj). Texures are always blurry. I want crisp, clean textures
Can anyone help me? I am exporting models with textures (.obj) from Crocotile3D to Unreal Engine 4. I want them to be crisp and clear, as in the left image (Crocotile editor), but only get blurry, as in the right image (Unreal editor). Whether I export the model at scale x 1 or greater doesn't make any difference. My textures are 16x16 pixels.

I have watched endless videos and tinkered with settings but been stuck for two days. Any help or advice will be much appreciated!

# Answer
> 3 votes
Thanks to DMGregory I solved the problem. I will leave the answer here for others to see.

In Unreal Editor, double click your texture to open the texture editor. Then, look at the 'details' section on the right. Find the 'Level Of Detail' section and open the 'Texture Group' menu. Choose '2D Pixels (unfiltered)', and you should have nice crispy clean textures even when resizing objects.

---
Tags: textures, unreal-4, import, export
---


# Question
Title: Issue with Sorting Layers with an NPC and Tilemap
I have a weird thing happening, that I can't quite explain. I have two scenes, my starting town, and an Arcanist's shop. When I go into the Arcanist's Shop, the Arcanist NPC stays on the same sorting layer (background layer 0) as my checkered tiles, and the table is background layer 1. When I start the game, the NPC will switch between being "behind" the table, or on top of it whenever I reenter the Arcanist's Shop scene. It seems to switch between background layer 0 and 1 with no cause.

I've double checked my sorting layers, they're all where they should be. I've checked the camera's culling mask, it's fine. I've checked to see if there are any weird components on anything in my shop scene, and there aren't

See the image attached, this is the same instance of the game, just different times when I enter the Arcanist's Shop.

Screenshot of my tilemap setup:

# Answer
> 1 votes
I see you're using the default "Chunk" draw mode for your tilemaps. As noted in the documentation for Tilemap sorting:

> When set to Chunk Mode, the Tilemap Renderer handles Sprites on a Tilemap in batches and renders them together. They are treated as a single sort item when sorted in the 2D Transparent Queue. This reduces the number of draw calls to improve overall performance, however **other Renderers cannot be rendered in between any portion of the Tilemap which prevents other rendered Sprites being able to interweave with the Tilemap Sprites**.

So this could account for the behaviour you're seeing. Depending on an arbitrary decision made by the chunking logic when your scene is loaded, the table might get built into a chunk that's wholly in front of, or wholly behind your NPC, with no ability for the NPC to get wedged in-between these elements.

So, you can instead set your objects tilemap layer to "Individual" draw mode - at the cost of more draw calls, but more fine-grained sorting behaviour.

Then be sure to set your sorting behaviour: `Edit > Project Settings > Graphics > Transparency Sort Axis`

Set it to Custom Axis, with a positive y, so that sprites higher up on your screen render behind objects lower down. (Here I also left the z-component set, so I can also fudge the sorting order by moving objects on the z-axis where needed)

With the individual draw mode and custom sort axis set, your NPC will be drawn behind tiles that are lower than them, and in front of tiles that are higher than them on the screen (you can choose in the sprite settings whether to sort based on center point or the sprite pivot for even more control)

---
Tags: unity, 2d, rpg, sorting
---


# Question
Title: Unity Application Crashes when Video player have non-video URL
I wanna make an Online video player that player can set link. application crashes on exit when link is non-video. it happened even in editor and editor crashes when I want to exit editor.!!!

I use 2018.4.21f what happened and how can I fixed? is it a bug???

```
//---------------simple code
public void Start(){
        //init
        vplayer = GetComponent<VideoPlayer>();
        vplayer.url = "http://www.google.com"; //this is a valid format sample link that is non-video
        vplayer.errorReceived += OnError;
        vplayer.prepareCompleted += OnPreComplete;
}

public void PlayButton(){
        vplayer.Prepare();
}
//--------
void OnPreComplete(VideoPlayer videoPlayer){
        vplayer.Play();
}
void OnError(VideoPlayer videoPlayer,string msg){
        print("error: " + msg);
}

```

I got this error : windowsVideoMedia error 0x00d0035 while reading http://www.google.com

# Answer
> 0 votes
I Test this Problem on Unity 2019.3.2 make a Video player with url that filled http://google.com that's ok and did not freeze when I closed unity ... but try this test on 2018.4.21 and unity freezes when I click on close button!!!

This is a BUG on 2018!

---
Tags: unity
---


# Question
Title: How to achieve this additive blending effect in Unity shader?
I want to achieve something like this using blending

I thought that it might be a simple additive shader but after using Blend One One or Blendop Add I get something like this

# Answer
I used Blend SrcColor One and it works fine for me
> 0 votes

# Answer
I know that this topic is old and you finally found a solution but I encountered the same issue and find another solution that also works fine, so I think that it may help other people reading this page.

I'm writing a shader for Godot Engine and I get the same visual artifact as you while merging two distance maps with additive blending (by adding RGB components and applying a clamp in 0-1):

I'm using a basic addition with threshold to avoid values greater than 1:

```
//min to avoid overflow
float final_value=min(value1+value2,1);

```

When I export my two distance maps in GIMP and I apply a additive blending I get expected result:

In fact I discover that GIMP and probably photoshop don't just add RGB components when doing additive blending, I investigate by picking pixels before and after blending and result is surprisingly not linear.

After experimentations, I finally found how to get the same result, **the key is to do the square root of the sum of squared components:**

```
float final_value=min(sqrt(value1*value1+value2*value2),1);

```
> 1 votes

# Answer
This isn't something wrong with your blend mode. It's an optical illusion called Mach Bands.

When there's a sudden change in brightness, the change in *perceived* brightness is exaggerated in the immediate vicinity, making it look like there's a dark line or shadow in the image even if it's not really there.

We can fix this by smoothing out our gradients so they don't have these sharp discontinuities.

Both the top and bottom orbs in the image below use the same additive blending calculation:

The orbs at the top show the same dark ridges as in your example, but the ones at the bottom don't. The reason is I reshaped the gradient slightly in Photoshop, to give it a little "ease out" at the dark end. Like this...

That's enough to smooth out the sharp change in brightness where the gradient bottoms-out to black, so we don't perceive a sharp ridge/dark trough there.
> 0 votes

---
Tags: unity, shaders, alpha-blending
---


# Question
Title: How can I change the camera to work from an Y up system to a Z up
I am following the tutorial from learnopengl.com but it uses a Y-up system, but I would like to change it for a Z up system because I'm more used to it.

I tried changing the up vector to be 1.0 on the last coordinate but and inverting the pitch And the Yaw, but when having the camera face the positive y-axis the mouse movement breaks and starts to move slower and opposite to the way I move the mouse.

The Axis system I'm trying to achieve:

That is the same as the Blender one.

This is the function of the camera class which handles the Pitch and Yaw: (offset is the mouse movement on the x axis and y axis):

```
void Camera::updateCameraVectors()
{
    // Calculate the new Front vector
    glm::vec3 front;

    front.x = cos(glm::radians(Yaw)) * cos(glm::radians(Pitch));
    front.y = sin(glm::radians(Pitch));
    front.z = sin(glm::radians(Yaw)) * cos(glm::radians(Pitch));

    Front = glm::normalize(front);
    // Also re-calculate the Right and Up vector
    Right = glm::normalize(glm::cross(Front, WorldUp));  // Normalize the vectors, because their length gets closer to 0 the more you look up or down which results in slower movement.
    Up = glm::normalize(glm::cross(Right, Front));
}

```

Up is the vector that I initialized as (0.0f, 0.0f 1.0f)

Are there any resources available online that explain how to make the switch from a Y-up to Z-up system?

# Answer
OpenGL uses a coordinate system, where the positive z-axis points "out of the screen", it's y-axis points up and it's x-axis to the right. In the end, you need to transform every data to this target coordinate system. Let us call this the "OpenGL" coordinate system.

So there is a transformation between your camera coordinate system, which we will call the "camera coordinate" system, that transforms into the "OpenGL" system. Since both coordinate systems are right-handed, a simple rotation should do the trick. In your case, the difference between the "OpenGL" coordinate system and the "camera coordinate" system is just a rotation around the x-axis by 90 degrees:

$$O\_{oc} = R\_x(\frac{\pi}{2})$$

Here O means orientation, the index oc means "**O**penGL in **C**amera" and R\_x is the rotation matrix that represents a rotation around the x-axis. Note that our orientation is a matrix!

Now you need to know, how your camera coordinate system is oriented in the "world space" system. If you define that both systems have the same orientation if yaw=0 and pitch=0, your camera systems orientation in world space can be described by the 2 following rotations in matrix notation:

$$O\_{cw} = R\_z(yaw) \cdot R\_x(pitch)$$

Keep in mind, that you read matrix multiplication from right to left. So you apply the pitch first by rotating around the x-axis. Afterward, you apply the yaw. Order matters, so don't exchange them.

Now you have all information together, but there is still one problem. The system dependencies are wrong. You want to transform your data from world space to "OpenGL" space. This means you need the matrix:

$$O\_{wo} = O\_{co} \cdot O\_{wc}$$

Note that the indices are swapped! So you need to find the transformations in the opposite direction, which means you need to find the inverse matrix. Luckily, that is rather easy for the orientations. Since orientation (rotation) matrices are so-called orthogonal matrices, the inverse is just the transposed. So you could do:

$$O\_{co} = O\_{oc}^T$$ $$O\_{wc} = O\_{cw}^T$$

Another way, that might be a little bit easier to understand is, that if you have applied some rotations to an object (transformed from A to B) and you want to undo the rotations (transform back to A from B), you can do this by simply applying the rotations in the opposite direction in the opposite order. For our matrices that means:

$$\begin{matrix} O\_{oc} &=& R\_x(\frac{\pi}{2})\\ O\_{co} &=& R\_x(-\frac{\pi}{2}) \end{matrix}$$ and $$\begin{matrix} O\_{cw} = R\_z(yaw) \cdot R\_x(pitch)\\ O\_{wc} = R\_x(-pitch) \cdot R\_z(-yaw) \end{matrix}$$

So you get:

$$O\_{wo} = R\_x(-\frac{\pi}{2}) \cdot R\_x(-pitch) \cdot R\_z(-yaw)$$

This is the matrix, that transforms the orientations from world space to "OpenGL" space. Its rows are your `Front`, `Right` and `Up` vectors. I am not sure about the ordering since I didn't check it explicitly, but I think the second row is the `Front` vector, the first is `Right` and the last is `Up`. You can try to extract them, but since you need to bundle them into the same matrix later, I would say, don't do it. Keep using the matrix instead.

However, there are still some things to consider: translations. To get to the actual camera position, you need to translate your data. A quick look into the tutorial (the one you linked) just revealed that this is already explained there, so I won't repeat the derivation again. Your full transformation matrix from world to "OpenGL" space is then:

$$M\_{wo} = O\_{wo}\cdot\begin{bmatrix} 1&0&0&-x\_{cam}\\ 0&1&0&-y\_{cam}\\ 0&0&1&-z\_{cam}\\ 0&0&0&1\\ \end{bmatrix}$$

I am actually using this approach myself. Therefore I know that it works ;). You can still optimize it a little by performing the matrix multiplications by hand, but since you are doing it once per frame, it isn't too important for performance.
> 2 votes

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


title: Random enemy generation algorithm help

text:
# Question
Title: Random enemy generation algorithm help
I've been working on a program for my friends to use for a homebrewed roleplay system that we all use for our campaigns that can generate random enemy statlines with certain constraints.

The program accepts a list of the statlines of the players, and then the user inputs a number that denotes a percentage of the player characters that this unit can beat on average in a 1v1. The issue I'm struggling with here is that combat involves different formulas for determining hit rate, critical hit rate, and damage

The formulas I have to deal with are:

Physical damage: strength - enemy defense = damage (multiplied by 2 if user's speed is 5 greater than enemy's)

Magical damage: magic - enemy resistance = damage (multiplied by 2 if user's speed is 5 greater than enemy's)

Hit rate: base hit + floor(user dex/3) + floor(user luck/5) - enemy dodge rate = hit rate (will always have a minimum of 5%)

Dodge rate: base dodge + floor(user speed/4) * 2 + floor(user luck/5) = dodge

Critical hit rate: 5% + floor((user dex - enemy luck)/5) + crit bonus = critical hit rate

(hit system is based on singular d20 with critical hit rate equivalent to number range on d20 that's considered a critical hit, meaning a 5% hit chance with a 5% or greater critical hit rate will result in every hit being a critical hit)

I've been struggling to think of an algorithm that can generate enemy statlines based on these formulas as well as the percentage constraint but I have no idea how to go about it in a way that isn't just bruteforcing it until I get a desirable outcome. I've toyed around with ideas such as ranking the inputting players based on their damage, survivability, dodge/hit, and determining upper/lower bounds on stats to work with but the issue I have is trying to establish a relationship formula between each stat to make sure that when I tweak one stat, I can change the others accordingly while staying within the user-defined constraints.

EDIT: After some thinking, I did come up with one possible solution, that being first determining the upper and lower bounds for the statline based on player stats, generating a random statline in between those bounds, and then generating tables that determine what effect on player and enemy DPS incrementing/decrementing a stat will have, and using that to precisely tweak enemies. The only issue with this solution is that for very high/diverse player stat values, this can take a long time, as well as figuring out a way to determine which stat to increment/decrement in the algorithm.

# Answer
> 0 votes
Here is the *expected* number of turns needed to be taken in order to defeat an enemy (assuming the enemy isn't fighting back, of course):

U\_turns = E\_hp / {max(U\_strength - E\_defense, U\_magic - E\_resistance) * (U\_speed ≥ E\_speed + 5 ? 2 : 1) *

max\[0.05, U\_accuracy + floor(U\_luck / 5) + floor(U\_dexterity / 3) - E\_evasiveness - floor(E\_luck / 5) - 2 * floor(E\_speed / 4)\] *

\[1 + (0.05 + floor{\[U\_dexterity - E\_luck\] / 5\]} + U\_crititalBonus)

/ (max\[0.05, U\_accuracy + floor(U\_luck / 5) + floor(U\_dexterity / 3) - E\_evasiveness - floor(E\_luck / 5) - 2 * floor(E\_speed / 4)\] )\]}

You'll probably want the players to on average defeat enemies (on average) fast enough to always have some spare medical supplies (on average, based on however healing works.) The average percentage of HP a player will have after a battle is 1 - U\_turns / E\_turns.

---
Tags: algorithm, random, balance
---


title: Multithreaded design for a game server

text:
# Question
Title: Multithreaded design for a game server
I would like to start developing my own game. Basically, the game has a "world" that players can travel around and modify. Think of it as a much more realistic version of Minecraft or an open world MMO.

I have thought of two possible ways of designing the server, both with problems.

The first is a single threaded design where one thread handles all the game mechanics and player interactions. The problem with this is that it cannot fully utilize a processor, and if one player does actions that cause lag, all players will experience that lag.

My next idea was that there is a separate thread for each player that renders the terrain around the player, handles physics, NPC interaction, etc. With this approach the CPU could be fully utilized and one player causing lag wouldn't affect others. However, the problem is keeping the different threads in sync. The entire server must be on the same "clock," (same day/night cycle, certain things take a certain amount of time, etc.), i.e., the different threads must be synchronized. However, this raises the problem that if one player's thread is lagging behind, the only way to synchronize the other threads would be to also cause them to lag, and this would eliminate one of the big advantages of a multithreaded game server, not to mention that keeping everything in sync can become extremely complicated.

So my question is, what would be the best way to design the game server using a multithreaded design where the server is kept in sync and one player causing lag won't affect others? Or is this even possible without dropping a significant amount of game ticks?

# Answer
> 3 votes
The greatest problem when it comes to parallelization is sharing data between threads. When multiple threads read and write the same data structure simultaneously, then you will have a myriad of problems. Either you get very difficult to reproduce bugs due to race conditions (bugs which only happen when one thread writes something while another thread reads that information) or your threads end up wasting a lot of CPU time with waiting at thread synchronization points.

So when you are designing multithreaded architectures, then what you should look for are units of data processing which require little to no communication with each other.

"One thread per player" is usually a bad choice as a unit of parallelization. All the players interact with the world and with each others all the time. There is not much you can parallelize here in good conscience.

## Dividing the world into cells

A common approach in an MMO is to spatially divide the game world into cells and process each cell of the world in a separate thread. This works well in games where locations can be cleanly divided, for example if you have a concept of separated "maps" or "instances". Each player only needs to know what happens in their current cell, so there is little communication between cells anyway. When a player does something that causes a spike in server load, then it will only affect players in the same cell. That also makes it easier for players and developers alike to realize the cause-effect relationship between another player doing something unusual and the game lagging in response to it.

However, this gets tricky when there *is* interaction between cells. When you want a *seamless* open world, then you will have situations where an entity in cell A interacts with an entity in cell B across a cell boundary. Now this architecture doesn't work so well anymore.

Further, players in MMOs often have a tendency to cluster in certain locations. Parallelizing by cell does nothing when the situations which really push your server to its limits are events where all players gather in the same cell.

## Entity - Component - System

Another approach is to use the Entity - Component - System architecture. This style of game programming has the benefit that it is pretty easy to find units of data processing which can be parallelized. You know which system operates on which components, so you can easily spot systems which have no communication with each other and thus can be run in parallel. You also recognize pretty easily when a system processes each entity in isolation, so the system itself can be parallelized (each thread processes a subset of entities).

Some of the more advanced ECS architectures make the decision what to process on which core at runtime. They usually have a concept of "jobs" which have dependencies with other jobs. An automatic job scheduler assigns jobs to threads at runtime.

---
Tags: architecture, multiplayer, mmo, server, multithreading
---


title: how to increase the volume by trigger

text:
# Question
Title: how to increase the volume by trigger
I need to know how to do this in a 2d game when my 2d character approaches a sounding spirit. the sound should increase as you approach it and decrease as you move away from it. for example, it is a radio sprite and makes sounds, and when you approach the radio the sound becomes louder and vice versa.
please help me

# Answer
The easiest way to get this behavior is using an Audio listener component attached to your player and an Audio source component attached to whatever you want to be making noise. You may want to remove the Audio listener component attached to the camera when you put one on your player.
> 0 votes

---
Tags: android
---


# Question
Title: Raycast2D hits acting (seemingly) inconsistently
I'm using Unity to make a 2D game, and I'm trying to put together a vision cone/flashlight system that's a lot less of a headache than the systems that are currently out there.

Despite this, I'm still slamming my head into a wall when it comes to these raycasts. See this video.

Here's the vision cone script:

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

public class VisionCone : MonoBehaviour
{
    public List<GameObject> targetsInView = new List<GameObject>();
    public Collider2D[] collidersInRange;
    public float viewDistance;
    [Range (0, 360)]
    public float viewAngle;
    public GameObject forwardAnchor;

    private int targetMask;
    private int wallMask;
    private Vector3 origin;
    private Vector3 lightDir;

    void Start()
    {
        targetMask = 1 << 9;
        wallMask = 1 << 8;
    }

    void Update()
    {
        origin = transform.position;
        Vector3 heading = forwardAnchor.transform.position - origin;
        float anchorDistance = heading.magnitude;
        lightDir = heading / anchorDistance;

        collidersInRange = Physics2D.OverlapCircleAll(origin, viewDistance, targetMask);

        foreach (Collider2D collider in collidersInRange)
        {
            Vector3 colliderPos = new Vector3(collider.transform.position.x, collider.transform.position.y, 0);
            Vector3 targetDir = colliderPos - origin;

            Debug.DrawLine(origin, colliderPos, Color.white);

            if (Vector3.Angle(targetDir, lightDir) < viewAngle / 2)
            {
                List<Transform> vertices = new List<Transform>();
                Transform[] allChildren = collider.gameObject.GetComponentsInChildren<Transform>();

                foreach (Transform child in allChildren)
                {
                    if (child.gameObject.tag == "Vertex")
                    {
                        vertices.Add(child);
                    }
                }

                foreach (Transform vertex in vertices)
                {
                    float vertDistance = Vector3.Distance(origin, vertex.position);
                    RaycastHit2D hit = Physics2D.Raycast(origin, vertex.position, vertDistance, wallMask);

                    if (!hit)
                    {
                        Debug.DrawLine(origin, vertex.position, Color.green);
                        if (!targetsInView.Contains(collider.gameObject))
                        {
                            targetsInView.Add(collider.gameObject);
                        }
                    }
                    else
                    {
                        Debug.DrawLine(origin, vertex.position, Color.yellow);
                        if (targetsInView.Contains(collider.gameObject))
                        {
                            targetsInView.Remove(collider.gameObject);
                        }
                    }
                }
            }
            else
            {
                Debug.DrawLine(origin, colliderPos, Color.red);
                if (targetsInView.Contains(collider.gameObject))
                {
                    targetsInView.Remove(collider.gameObject);
                }
            }

        }
    }

    void LateUpdate()
    {
        foreach (GameObject target in targetsInView)
        {
            float targetDistance = Vector3.Distance(target.transform.position, origin);
            if (targetDistance > viewDistance + 0.5)
            {
                targetsInView.Remove(target);
            }
        }
    }
}

```

As you can see, the wall is inconsistent in blocking the raycast - sometimes every single ray should collide with the wall and therefore turn yellow, but they're all green. Sometimes they're yellow even when they don't collide with a wall. Sometimes it's a mix, and so on.

I'm at my wit's end with these - I tried the same method using the vertices of a box collider 2D which I found using a foreach collider loop, to the same effect.

I have absolutely no idea why the hit detection is so inconsistent. Any help would be greatly appreciated.

# Answer
> 0 votes
Here's your problem:

```
float vertDistance = Vector3.Distance(origin, vertex.position);
RaycastHit2D hit = Physics2D.Raycast(origin, vertex.position, vertDistance, wallMask);

```

If we read the documentation for Physics2D.Raycast, we see the signature described like this:

```
public static RaycastHit2D Raycast(Vector2 origin, Vector2 direction, float distance = Mathf.Infinity, int layerMask = DefaultRaycastLayers, float minDepth = -Mathf.Infinity, float maxDepth = Mathf.Infinity);

```

Notice the second parameter is a *direction*:

> **direction** A vector representing the direction of the ray.

But here you've passed the *position* of the vertex you want to shoot toward. This matches the direction only if our origin is on the line between this point and (0, 0, 0). If our origin is anywhere else in the world, then we end up firing the ray in a direction that has nothing to do with where we're trying to aim.

You could convert your position to a direction by subtracting your starting point:

```
Vector2 offset = (Vector2)(vertex.position - origin);

```

...but it looks like what you want here is a LineCast, which is a point-to-point raycast, and will let you skip calculating your `vertDistance` at all:

```
RaycastHit2D hit = Physics2D.LineCast(origin, vertex.position, wallMask);

```

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