# Question
Title: Trying to understand why libgdx wipes existing models when creating new ones
I'm coding a simulated brain and I'd like to make an arrow appear when one cell connects to another cell.

My output without generating an arrow looks like this:

Where each block rendered represents a cell in a 8x8x1 grid.

The cells are programmed to seek out another cell when they haven't had a pulse in a hundred ticks. When they find another cell I'd like to draw an arrow between them to visualize the link. This arrow is created in my method `onAxonConnected()`

But at my first attempt to make the arrow as the connection is established it seems to completely wipe the rendering of the existing cell blocks. I've had no issues in creating new cell blocks when a new cell was grown dynamically, so why this gives problems mystifies me.

As you can see in the below image there is one well defined arrow and what seems to be a lot of stretched out lines that may or may not be the cell blocks.

This is my very first time experimenting with libgdx and i'm eager to learn more about it, but except for LibGDX creating ModelInstance after create() has ended without an answer I haven't found anything that comes close to my scenario.

**My Question**

*What causes the cell blocks to not render when arrows are introduced?*

Below is the code I'm using for the rendering.

```
public class MyGdxGame implements ApplicationListener, IBrainEventListener {

 @Override
 public void onAxonConnected(Pos one, Pos two) {

  Model lineModel = build.createArrow(one.x, one.y, one.z, two.x, two.y, two.z, 0.15 f, 0.05 f, 5, GL20.GL_TRIANGLES, new Material(), VertexAttributes.Usage.Position | VertexAttributes.Usage.Normal);
  ModelInstance line = new ModelInstance(lineModel);
  this.addArrowModelInstanceToRender(line);
 }

 protected void addModelInstanceToRender(ModelInstance render) {
  ArrayList < ModelInstance > newlist = new ArrayList < ModelInstance > (this.modelRenders.size() + 1);
  newlist.addAll(this.modelRenders);
  newlist.add(render);
  this.modelRenders = newlist;
 }

 protected void addArrowModelInstanceToRender(ModelInstance render) {
  ArrayList < ModelInstance > newlist = new ArrayList < ModelInstance > (this.arrowmodelRenders.size() + 1);
  newlist.addAll(this.arrowmodelRenders);
  newlist.add(render);
  this.arrowmodelRenders = newlist;
 }

 @Override
 public synchronized void onCellGrown(Cell cell, Pos pos) {

  ModelInstance render = new ModelInstance(model);
  render.transform.setToTranslation(pos.x, pos.y, pos.z);
  this.addModelInstanceToRender(render);

  ArrayList < CellRender > newCellRenders = new ArrayList < CellRender > (cellRenders.size() + 1);
  newCellRenders.addAll(cellRenders);
  CellRender renderManager = new CellRender(cell, render);
  newCellRenders.add(renderManager);
  cell.setPulseListener(renderManager);

  this.cellRenders = newCellRenders;

 }

 @Override
 public synchronized void onAxonFired(Cell cell, Axon axon, Pos pos) {

 }

 PerspectiveCamera cam;
 CameraInputController camMove;
 ModelBatch batch;
 Model model;
 ModelBuilder build;
 ModelInstance renderer;
 ArrayList < ModelInstance > modelRenders;
 ArrayList < ModelInstance > arrowmodelRenders;
 Environment enviroment;
 ArrayList < CellRender > cellRenders;

 BrainBoot brainBooter;
 Brain brain;

 Texture texture;
 SpriteBatch spriteBatch;

 @Override
 public void create() {

  modelRenders = new ArrayList < ModelInstance > ();
  arrowmodelRenders = new ArrayList < ModelInstance > ();
  cellRenders = new ArrayList < CellRender > ();
  texture = new Texture(Gdx.files.internal("android.jpg"));
  spriteBatch = new SpriteBatch();
  brainBooter = new BrainBoot();
  brain = brainBooter.getBrain();

  cam = new PerspectiveCamera(50, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
  cam.position.set(16 f, 8 f, 16 f);
  cam.lookAt(8 f, 8 f, 8 f);

  cam.near = 1 f;
  cam.far = 300 f;
  cam.update();

  enviroment = new Environment();
  enviroment.set(new ColorAttribute(ColorAttribute.AmbientLight, 0.4 f, 0.4 f, 0.4 f, 1 f));
  enviroment.add(new DirectionalLight().set(0.8 f, 0.8 f, 0.8 f, -1 f, -0.8 f, -0.2 f));

  batch = new ModelBatch();
  build = new ModelBuilder();

  model = build.createBox(0.5 f, 0.5 f, 0.5 f,
   new Material(ColorAttribute.createDiffuse(Color.PURPLE)),
   VertexAttributes.Usage.Position | VertexAttributes.Usage.Normal);

  brain.addEventListener(this);

  camMove = new CameraInputController(cam);

  Gdx.input.setInputProcessor(camMove);

  brainBooter.boot();
 }

 @Override
 public void render() {
  ArrayList < CellRender > cellRenderList = this.cellRenders;
  for (CellRender r: cellRenderList) {
   if (r.dirty) {
    r.clean();
   }
  }
  Gdx.gl.glClearColor(1, 1, 1, 1);
  Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT);
  camMove.update();

  ArrayList < ModelInstance > renderers = modelRenders;
  ArrayList < ModelInstance > arenderers = arrowmodelRenders;

  batch.begin(cam);

  batch.render(arenderers, enviroment);
  batch.render(renderers, enviroment);

  batch.end();

 }

 @Override
 public void dispose() {
  batch.dispose();
  model.dispose();
 }

 @Override
 public void resize(int width, int height) {}

 @Override
 public void pause() {}

 @Override
 public void resume() {}
}

```

# Answer
> 0 votes
The problem was caused by giving the command to create the arrow from an event that was triggered from a separate running thread.

This separate running thread was the cause somehow that everything went awry when it fired off an event that instantiated the model and added it to the arraylist for the next rendering cycle.

When I put the separate thread in line with the main render thread I was able to instantiate new arrows without issue.

Lesson learned: don't use threads with Libgdx and if you do, use PostMessages.

---
Tags: java, libgdx, android
---


# Question
Title: Unity using 40% GPU for just a UI interface on ultra but 90 on low?
So I made some software using unity for my FRC team. All this application is, is just a User Interface with labels, input fields, buttons, etc... When I choose the quality to be on Ultra, I will get about 50% GPU usage but when on very low, I got 90%, close to 100%. How can I optimize my software to use much less of the GPU(Preferably less than 15%)? I am measuring with the Task Manager Performance Menu

# Answer
Unity is pretty much unfit by design if you just want a simple UI without any animated content. This isn't just about VSync, it's about Unity - by design - keeping rendering in a loop regardless of any state changes.

If you want to conserve resources properly use an event driven UI framework for such tasks. A dedicated UI framework will only render if something has changed, and if nothing is to be animated, that's actually just on user input or other explicit events.

I suppose you could just "Pause" Unity if you wanted, but that would just stop even more than you intended.
> 1 votes

---
Tags: unity, c#, graphics, optimization
---


# Question
Title: Pure ECS, How to copy all components from one entity to another
I am attempting to create component payloads using prefabs. My goal is to use

`var entity = EntityManagerExtensions.Instantiate(EntityManager, ai_steeringPipelinePrefab[i].Prefab);`

to get all the components I need copied over to another entity (including there data)

The only way i have found so far is to get the component types from the payload entity and add them to the recieving entity with

```
EntityManager.AddComponents(entity, componentTypes);

```

But this does not copy the data.

Thoughts?

# Answer
Since no exact solution was found instead I opted to add a component to the recieving entity called LinkToPipeline that simply contains the entity so I can look up the components through EntityManager. This works for me because it's only done once during initialization so the performance hit is negligable.
> 0 votes

---
Tags: unity, entity-component-system
---


# Question
Title: Should the server calculate the time of a player's input, or trust sent data?
I am curious about the details of lag compensation in games. I have read a lot of articles about it, for example:

1. Source Engine Multiplayer Networking
2. Fast-Paced Multiplayer - Gabriel Gambetta
3. How do Multiplayer Game\[s\] sync their state?

And I still have this question:

At the 1st link, the Valve developers give a formula to compute the time when the command should be executed:

```
Command Execution Time = Current Server Time - Packet Latency - Client View Interpolation

```

But on the 3rd site, the author says that the client sends the `Command Execution Time` and the server does not need to use that complicated formula to calculate something that the client can give the server for free. I mean, the player will always send the correct info about `Command Execution Time`, so the server can believe him.

Which one is correct? Or are both suitable (for different situations)?

# Answer
As Steve Smith pointed out in the comment above:

> "the player will always send the correct info about Command Execution Time" - Are you sure? Could be a mechanic for cheating if the player could say "I was actually elsewhere when the bullet supposedly hit me".

Let's say I'm a player interested in exploiting your system. If I know your server trusts the timestamp I send, and uses it to determine when to place my action in its reconstructed timeline of events, then I can use this to effectively send my inputs *back in time*!

Imagine I see an enemy zip out of cover, and I'm not quite quick enough on the draw to shoot them before they're out of sight again, so I click 3 frames / ~50 ms too late. That's fine. I have a little program running to intercept packets from the game and back-date my timestamps when I miss, so instead of telling the server I clicked after the player was out of sight, it reports that I clicked 3 frames earlier.

The server trusts this timestamp, rewinds the game state to three frames before my click, and verifies that a click at this (false) time would indeed be a killing shot, so it awards me the kill.

So I score a kill when, in a fair game, I'd have missed. I've successfully exploited the system to give myself an unfair advantage over players not using my back-dating tool.

So: if you want to close off any avenue to cheating you can find, follow the mantra "the client is in the hands of the enemy" and do not trust anything from a remote client that you could calculate yourself on a trusted device.

Or, if you choose to trust client-provided timestamps, just be aware that this is a vector for a hacker to exploit your system, and monitor accordingly to make sure this is not damaging the experience for players following the rules. If hackers start exploiting this and similar avenues en masse, you might need to push out a patch after the fact to restore your intended play experience, and deal with the player community reputation fallout that this can have.
> 1 votes

---
Tags: networking, client-server, synchronization, latency
---


# Question
Title: How to get asset folder path in android native activity?
I am trying to create a small game with android native activity. I wish to load textures using stb image. I don't know how to get the path to assets folder. Is there any API to get path to apk directory so that I can use that to get textures? Thanks.

# Answer
> 3 votes
Reading assets in C or C++ is actually very tricky in Android.

You need to go via the AssetManager, and in Java-side code, you need to do this in your NativeActivity class:

```
AssetManager mgr = this.getApplicationContext().getResources().getAssets();

```

And then pass this manager to your C code.

Actually reading assets can be tricky, as it is read from compressed archived, but there is an amazing trick available that remaps the FILE functionality.

Look at android\_fopen.h + android\_fopen.c on how to do that.

With this trick, you can then `fopen()` and `fread()` your assets, and have the assetmanager do all the work under water.

---
Tags: android, ndk
---


# Question
Title: How is the default value of ContactFilter2D.isFiltering true?
I have a static ContactFilter2D like so:

```
protected static ContactFilter2D contact_filter;
protected float self_destruct_timer;
protected Vector3 direction;
private float xward;

protected virtual void Start ()
{    phys.velocity = transform.right * speed * xward;
     self_destruct_timer = Time.time + life_time;

     if (!contact_filter.isFiltering) contact_filter.layerMask = Public_Const.Solid;
     contact_filter.useLayerMask = true;
     ...
}

```

Every isFiltering\_____ variable (i.e. isFilteringLayerMask) is set to false by default, therefore there should be no way that isFiltering should return a true value. The whole point of checking to see if isFiltering is true is to check to see if the contact filter has already been initialized, so why won't it work?

# Answer
Okay so apparently the code for IsFiltering looks like:

```
    public bool isFiltering => !useTriggers || useLayerMask || useDepth || useNormalAngle;

```

So I guess that not using triggers filters out triggers, therefore returning true. I guess I'll check to see if contact\_filter is initialized by checking useLayerMask, and then setting that to true in the conditional.
> 0 votes

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


# Question
Title: Mixing between two colours in fragment shader causes normal mapping to be ignored
I'm making a game in which the world is black and white except from the immediate area around the player. It all works, except the normal mapping breaks when I turn it on. If I set the output at just the black and white version, normal mapping appears, if I set the output as the colour version, also there, but as soon as I mix between them the shader ignores the normal mapping. I'll post the shader code here, it's very long but I thought I'd include it all just in case.

Quick explanation: splatCalcs() uses a splat map to mix between 4 different textures and their corresponding normal maps and spec maps. In this example, the splat map is completely black, in order to isolate that variable. The normal is stored as "calcedNormal" during that method, which is then used in the applyLight() method. blackAndWhiteCalcs() takes in the final colour for the fragment and then mixes between a black and white version and the original. I've used that weird calculation on the radius etc to avoid if statements. It also means once it's working I can do partial mixes.

Thanks for any help.

Edit: I have reduced the shaders to a smaller function to show the normal mapping in action and the lack thereof when I apply a mix on the two colours. In this code, I simply change the mix value in the return from hard coded 1 to hard coded 0. This produces the following results:

```
vec4 blackAndWhiteCalcs(vec4 colour)
{
    //Black and white effects for Dreameater
    vec3 lum = vec3(0.299, 0.587, 0.114);

    //the black and white version of tempFragColor
    vec3 blackAndWhite = mix(vec3(dot(colour.xyz, lum)), colour.xyz, 0.1);
    blackAndWhite *= 0.8f;

    return vec4(mix(blackAndWhite, colour.xyz, 0) , colour.a);
}

```

Result when 1 is hard coded

and result when 0 is hard coded

However using a calculation to define the 1 or 0 causes all the detail gained by normal mapping to disappear. To be clear, the base texture is all one colour, and all the detail given above is from the normal mapping. So the area that is black and white is correct, only that detail is lost.

Finally, I just to prove I wasn't going mad I replaced my eqn with a simple if set as seen below. This didn't change results.

```
vec4 blackAndWhiteCalcs(vec4 colour)
{
//Black and white effects for Dreameater
vec3 lum = vec3(0.299, 0.587, 0.114);

//the black and white version of tempFragColor
vec3 blackAndWhite = mix(vec3(dot(colour.xyz, lum)), colour.xyz, 0.1);
blackAndWhite *= 0.8f;

float bw = 0.0f;

if (circleRadius > length(inputFragment.vert - circlePos[0]) )
{
    bw = 1;
}
else
{
    bw = 0;
}

//bw = clamp(bw, 0, 1);

return vec4(mix(blackAndWhite, colour.xyz, bw) , colour.a);
}

```

I'm still including the full final code below. Below is what produced the result above. Thanks again.

```
    #version 400

#define MAX_TEXTURES 4
uniform sampler2D bases[MAX_TEXTURES];
uniform sampler2D normals[MAX_TEXTURES];
uniform sampler2D specs[MAX_TEXTURES];
uniform int inverts[MAX_TEXTURES];
uniform sampler2D splat;

//Uniforms that have to be unique to each surface

#define MAX_LIGHTS 16

uniform float materialShininess;
uniform vec3 cameraPos_World;
uniform int numLights;

uniform int invertY;

uniform struct Light {
   vec4 position;
   vec3 colors;
   float attenuation;
   float ambientCoefficient;
   float coneAngle;
   vec3 coneDirection;
   mat4 finalLightMatrix;
} allLights[MAX_LIGHTS];

in packet{

    vec2 textureCoord;
    vec2 tiledCoord;

    vec3 normal;
    vec3 vert;
    mat3 TBN;

} inputFragment;

vec3 specColour = vec3(1,0,0);
mat3 calcedTBN;
vec3 calcedNormal;
vec4 tempFragColor;

float circleRadius = 5;
#define CIRCLESMAX 60
uniform vec3 circlePos[CIRCLESMAX];

float bwMix = 1.0f;

// output packet
layout (location = 0) out vec4 fragmentColour;

vec3 applyLight(Light thisLight, vec3 baseColor, vec3 surfacePos, vec3 surfaceToCamera)
{
    float attenuation = 1.0f;
    vec3 lightPos = (thisLight.finalLightMatrix*thisLight.position).xyz;
    vec3 surfaceToLight;

    vec3 coneDir = normalize(thisLight.coneDirection);

    if (thisLight.position.w == 0.0f)
    {
        //Directional Light (all rays same angle, use position as direction)
        surfaceToLight = normalize((thisLight.position).xyz);
        attenuation = 1.0f;
    }
    else
    {
        //Point light
        surfaceToLight =  normalize(lightPos - (surfacePos));

        float distanceToLight = length(lightPos -( surfacePos));
        attenuation = 1.0 / (1.0f + thisLight.attenuation * pow(distanceToLight, 2));

        //Work out the Cone restrictions
        float lightToSurfaceAngle = degrees(acos(dot(-surfaceToLight, normalize(coneDir))));

        if (lightToSurfaceAngle > thisLight.coneAngle)
        {
            attenuation = 0.0;
        }
    }

    //Ambient light calculation
    vec3 ambient = thisLight.ambientCoefficient * baseColor.rgb * thisLight.colors;

    //Diffuse Light Calculation
    float diffuseCoefficient = max(0.0, dot(calcedNormal,normalize(surfaceToLight)));
    vec3 diffuse = diffuseCoefficient * baseColor.rgb * thisLight.colors;

    //Specular Light Calculation
    float specularCoefficient = 0.0;
    if (diffuseCoefficient > 0.0)
    {
        specularCoefficient = pow(max(0.0, dot(surfaceToCamera, reflect(-surfaceToLight,calcedNormal))), materialShininess);
    }

    vec3 specular = specularCoefficient * specColour * thisLight.colors;//

    return ambient + attenuation * (diffuse+ specular);
}

void splatCalcs()
{
    //Read in splat
    vec4 splat = (texture2D(splat, inputFragment.textureCoord));

    //read in each base colour texture
    vec4 base0 = texture2D(bases[0], inputFragment.tiledCoord);
    vec4 base1 = texture2D(bases[1], inputFragment.tiledCoord);
    vec4 base2 = texture2D(bases[2], inputFragment.tiledCoord);
    vec4 base3 = texture2D(bases[3], inputFragment.tiledCoord);

    //Use an appropriate blend from each texture. use normal and spec maps for the most prevalent map
    //Black = base 0
    //red = base 1
    //green = base 2
    //blue = base 3
    //a = 0 then base 4
    float black = 1 - (splat.r + splat.g + splat.b);

    base0 = base0 * black;
    base1 = base1 * splat.r;
    base2 = base2 * splat.g;
    base3 = base3 * splat.b;

    //frag colour combined =
    tempFragColor = base0 + base1 + base2 + base3;

    //Do everything again for normal maps
    vec3 normal0 = texture2D(normals[0], inputFragment.tiledCoord).xyz;
    vec3 normal1 = texture2D(normals[1], inputFragment.tiledCoord).xyz;
    vec3 normal2 = texture2D(normals[2], inputFragment.tiledCoord).xyz;
    vec3 normal3 = texture2D(normals[3], inputFragment.tiledCoord).xyz;

    normal0 = normal0 * black;
    normal1 = normal1 * splat.r;
    normal2 = normal2 * splat.g;
    normal3 =  normal3 * splat.b;

    vec3 inputN = normal0 + normal1 + normal2 + normal3;
    //input = (texture2D(normals[0], inputFragment.tiledCoord)).xyz;

    //Normal map specific calculations
    vec3 readIn;
    readIn.x = (2.0* inputN.r) - 1.0;
    readIn.y = invertY *((2.0* inputN.g) - 1.0);
    readIn.z = (2.0*inputN.b - 1.0);

    //calcec normal combined =
    calcedNormal = normalize(inputFragment.TBN * readIn);

    //read in spec maps
    vec3 spec0 =  texture2D(specs[0], inputFragment.tiledCoord).xyz;
    vec3 spec1 =  texture2D(specs[1], inputFragment.tiledCoord).xyz;
    vec3 spec2 =  texture2D(specs[2], inputFragment.tiledCoord).xyz;
    vec3 spec3 =  texture2D(specs[3], inputFragment.tiledCoord).xyz;

    spec0 = spec0 * black;
    spec1 = spec1 * splat.r;
    spec2 = spec2 * splat.g;
    spec3 = spec3 * splat.b;

    //Set spec colour
    specColour = spec0 + spec1 + spec2 + spec3;

}

vec4 blackAndWhiteCalcs(vec4 colour)
{
    //Black and white effects for Dreameater
    vec3 lum = vec3(0.299, 0.587, 0.114);

    //the black and white version of tempFragColor
    vec3 blackAndWhite = mix(vec3(dot(colour.xyz, lum)), colour.xyz, 0.1);

    float bw = 0.0f;
    float additive;

    //if the radius is smaller than the distance between the vert and the centre, mul = 0.
    //if the radius is bigger than the distance between the vert and the centre, mul > 0
    //the result of the following eqn is 0 if the point is outside of the circle, and (0< result < radius) radius if it is.

    for (int count2 = 0; count2 < CIRCLESMAX; count2++)
    {
        additive = circleRadius - (min(circleRadius, abs(length(inputFragment.vert - circlePos[count2]))));

        // make sure the mul value is definetly either 0, or bigger than 1
        additive += (additive * (circleRadius + 100));

        bw += additive;
    }

    bw = clamp(bw, 0, 1);

    return vec4(mix(blackAndWhite, colour.xyz, bw) , colour.a);
}

void main(void) {

    vec3 surfaceToCameraWorld = normalize((cameraPos_World)-(inputFragment.vert));

    //get the base colour from the texture
    splatCalcs();

    tempFragColor = blackAndWhiteCalcs(tempFragColor);

    vec3 tempColour = vec3(0.0, 0.0, 0.0);

    for (int count = 0; count < numLights; count++)
    {
        tempColour += applyLight(allLights[count], tempFragColor.xyz, inputFragment.vert, surfaceToCameraWorld);
    }

    vec3 gamma = vec3(1.0 / 2.2);

    vec4 final = vec4(pow(tempColour, gamma), tempFragColor.a);

    fragmentColour = final;
}

```

# Answer
> 2 votes
Branching of any kind causes uniforms to be unbound! So in this example, the tiling factor that calculated the tiledCoords for the texture sampling was set only once at the beginning of the shader's life, and not every frame. Because the shader branched, for pixels that were and weren't in the sphere of influence, the tiling factor was reset to 0, causing all tiled co-ords to equal 0.

---
Tags: opengl, shaders
---


# Question
Title: How to setup input for local multiplayer without split-screen in Unreal Engine 4
To bind actions and axes in the character blueprint class, I may have multiple such character instances for each new APlayerController. Merely 1 Action Name (e.g. avoiding `UseSkill_P1`, `UseSkill_P2`, etc) is required for each character by adding the node in the Player Controller. However, for more functionality the same is required in cpp.

### What I've tried:

When I bind actions and axes (*delegates*) in the `APlayerController`'s `SetupInputComponent` (e.g: `InputComponent->BindAction("Attack", IE_Pressed, this, &AMyController::DoSomething);`, then spawn multiple players with `UGameInstance::CreateLocalPlayer(index, err, true)`, the editor will crash on pressing Play in Editor (*Alt+P*).

The error thrown during runtime is: `Access violation - code c0000005 (first/second chance not available)` and referencing the line where the first `ActionBind` appeared, e.g: `UE4Editor_MyProject!AMyController::SetupInputComponent() [d:\path\to\project\source\private\mycontroller.cpp:66]`

---

A common solution can be found in this wiki post it seems. In short, overwrite `GameViewportClient` and set it as default, then within, overwrite `InputAxis` and `InputKey` and increment the player controller index for each input device (*gamepad*) used.

As mentioned previously, this would require the project to specify a unique Action Name for each player index e.g. `Attack_P4`.

---

There is also some confusion that needs to be cleared up.

* An `AController` will not be created for each input device connected.
* 1-viewport-multiplayer isn't supported as split-screen. (*Weird naming, but good for search engines*).
* Spawning new Local Players is generally done in your override of `AGameMode::BeginPlay`. I made it up to the deriving BPs of my Game Mode to call `CreatePlayers` to create up to the set amount of players.
* Setting `Skip Assigning Gamepad to Player 1` will allow keyboard to be used for player 1.

---

Hopefully there are some common best practices to tackle this problem. Any suggestion is very much appreciated!

PS Here is the related unreal answers hub question.

# Answer
I tried the template approach, where it overrides `SetupPlayerInputComponent(class UInputComponent* PlayerInputComponent)` in the `ACharacter` derived class, and then bind delegates by calling e.g: `PlayerInputComponent->BindAction("Jump", IE_Pressed, this, &ACharacter::Jump);`

For some reason this reminded me to include `Super::SetupInputComponent();` in my `APlayerController::SetupInputComponent` and the bindings started working. The editor wouldn't crash any longer.
> 1 votes

---
Tags: input, unreal-4, unreal
---


# Question
Title: Lock enemy's y-axis when using Vector3.MoveTowards to follow the player
I am using the following code to make a zombie move towards me, but when playing the scene the zombie seems to be moving towards me, but also off the ground and not fixed on the y-axis

```
 public GameObject ThePlayer;
public float TargetDistance;
public float AllowedRange = 10;
public GameObject TheEnemy;
public float EnemySpeed;
public int AttackTrigger;
public RaycastHit Shot;

void Update()
{
    transform.LookAt(ThePlayer.transform);
    if (Physics.Raycast(transform.position, transform.TransformDirection(Vector3.forward), out Shot))
    {
        TargetDistance = Shot.distance;
        if (TargetDistance < AllowedRange)
        {
            EnemySpeed = 0.01f;
            if (AttackTrigger == 0)
            {
                //TheEnemy.GetComponent<Animation>().Play("Walking");
                transform.position = Vector3.MoveTowards(transform.position, ThePlayer.transform.position, EnemySpeed);
            }
        }
        else
        {
            EnemySpeed = 0;
            //TheEnemy.GetComponent<Animation>().Play("Idle");
        }
    }

    if (AttackTrigger == 1)
    {
        EnemySpeed = 0;
        //TheEnemy.GetComponent<Animation>().Play("Attacking");
    }
}

void OnTriggerEnter()
{
    AttackTrigger = 1;
}

void OnTriggerExit()
{
    AttackTrigger = 0;
}

```

What can i do to ensure that it is sticking to the y axis at all times

# Answer
> 12 votes
The reason this is happening is because `Vector3.MoveTowards` will move all axes toward the target.

You can specifically exclude changes to the Y axis by creating a new target Vector3 having the Y axis set to the value it should stay at.

```
transform.position = Vector3.MoveTowards(
    transform.position,
    new Vector3(
        ThePlayer.transform.position.x,
        transform.position.y,
        ThePlayer.transform.position.z
    ),
    EnemySpeed
);

```

The above code creates a new Vector3 target where the Y axis is the same as the current position instead of the target, preventing `Vector3.MoveTowards` from changing the Y axis at all.

# Answer
> 3 votes
You can break out the `Vector3 target` parameter of `Vector3.MoveTowards` to prevent movement on the y-axis. Simply set the y value of the `target` position to the same y value as the `current` position. For example:

```
Vector3 currentPosition = transform.position;
Vector3 targetPosition = new Vector3(ThePlayer.transform.position.x, transform.position.y, ThePlayer.transform.position.z);

transform.position = Vector3.MoveTowards(currentPosition, targetPosition, EnemySpeed);

```

# Answer
> 1 votes
The other answers are great. But if you have a RigidBody attached, you can freeze the y rotation via constraints. Then no code change would be necessary.

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


# Question
Title: Large gap between the grabbed game object and controller
When i grab a gameobject, there is a gap between them. I have tried changing the scale of the colliders, tool handle position from global to pivot but nothing worked for me. Should i reset the pivot points of model in 3D modeller and reimport it again or is there another way to solve this?

I have attached few screenshot related to the problem

# Answer
In my case, i am using VRTK toolkit. So, i changed the grab attach mechanism from child of controllers to fixed joint and selected precision grab. This solved my problem.
> 1 votes

---
Tags: unity, controllers, collider
---


title: Ball always showing in Unity

text:
# Question
Title: Ball always showing in Unity
Some weird "ball" is showing when I select an element in Unity, preventing me to see the object itself:

I've tried to hide some layers, but even with all layers hidden it's still here:

Do you know how to hide this thing? Any idea is greatly welcomed :)

# Answer
> 4 votes
Thanks to @TomTsagk's comment on the question above, I've found it.

It was **light probes** that needed to be switched off, this is done in the **Gizmo menu** (in scene view):

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


# Question
Title: How can I solve niche collision cases between circles and insides/outsides of AABBs or arcs?
I am trying to create a game with some interesting geometry. Literally all the geometry that is involved are the circles that move large distances per frame, and the edge of an iPhone X display, which I am going to approximate using the following shapes:

* *It is worth noting that instead of the inside quarter eclipse one could do another "outside of AABB" and another "inside of quarter-circle"*

Here's the problem: These collision detections are very niche and I can't find anyone doing them anywhere. In fact I can't even find the algorithm to collide these fast moving circles with the outside of an AABB let alone the inside of one. And no formulas for circle collisions allow for a quarter circle collision to be calculated. Everything needs to be hyper efficient so I think using Bézier curves/complex shapes is really not an option.

How do I develop or find the algorithms to do these types of collisions?

Have I perhaps overthought everything? Would Bézier or some other spline curve be easier here? I suppose I made a bit of an assumption that that would be expensive to calculate. But maybe is that the answer?

Keep in mind whatever I do needs to work for over 1 thousand entities to collide with this shape in real time.

# Answer
> 0 votes
I'd argue you don't need anything niche here at all.

A disc colliding against any shape is equivalent to a point colliding with that same shape "inflated" by the radius of the disc.

Since your collision boundary is a closed path, this maps your input sequence of line segments and circular arcs to just another sequence of lines and circular arcs. You don't need any more exotic shapes or additional end caps.

To handle high speeds, we can use continuous collision detection, by sliding the point along a ray.

So, your situation reduces to:

* ray vs line segment
* ray vs circle

Two of the most bread and butter checks. So, I won't rehash the details of how to perform these raycasts here — you can find excellent answers & articles about high-performance implementations of these checks elsewhere.

Instead I'll focus on a few details:

* **For concave circles**: the quadratic formula used in your ray-circle intersection routine can find two roots. Conventionally, it will return the closer of the two (smaller time-to-impact `t`). To collide against a concave circle, take the farther root instead (larger `t`)
* **For quarter-circle arcs**: since your quarters are axis-aligned (and remain so after inflation), you don't need any angles or trig. Just check the signs of the x & y components of `rayIntersection - circleCenter`, discarding collisions in the other quadrants.
* **Computing the original collision info**: once you have your intersection between the ray and the inflated shape (what's called the Minkowsi sum of the original shapes), here's how that maps back to a collision between the original disc & original boundary...

```
Collision UnMinkowski(Collision minkowski, float discRadius) {
    // We can have up to two collision normals
    // if our ray struck a sharp corner exactly.
    Collision actual = new Collision(pointCount = minkowski.pointCoint);

    actual.timeOfImpact = minkowski.timeOfImpact;
    actual.discPositionAtImpact = minkowski.contactPoints[0];

    for(int i = 0; i < actual.pointCount; i++) {
        actual.normals[i] = minkowski.normals[i];
        actual.contactPoints[i] = minkowski.contactPoints[i]
                       - discRadius * minkowski.normals[i];
    }

    return actual;
}

```

# Answer
> 0 votes
You need to represent the iphone as a rectangle where the 4 corners are the centers of the 4 circles. We know a point is inside the iphone's shape when the distance from this rectangle is less than the radius of the circles. The formula for the distance based on the center of the rectangle `c`, the position of the point `p`, the side lengths of the rectangle `s` and the radius of the circles `r`:

$$\vec d(|p\_x-c\_x|, |p\_y-c\_y|)-\frac{s}{2}$$ $$dist = \sqrt {max(d\_x, 0)^2+max(d\_y, 0)^2} - r$$

Now the only thing you need to do is get the distance from the center of the circle to the iphone, if it's less than the radius of that circle, then they are colliding.

---
Tags: collision-detection, physics
---


# Question
Title: How to properly create a handle for setting moving platform's target position in Unity?
As the title suggests, I am trying to set up a handle for setting target position of a moving platform.

I have an empty GameObject(targetPos) and this is what I want to use for setting target position of the moving platform.

Here is the code I have for it so far but it does not seem to work correctly and I am not sure what is wrong.

The problem is, the empty gameobject's transform is not using correct position for moving platform to go to. Not that I put the empty gameobject as the child of the moving platform.

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

public class MovePlatform : MonoBehaviour
{
public Transform targetPos;
private Vector3 initialPosition, targetPosition, targetPosDebug;
public float speed = 3;
public bool loop;

void Start()
{
    initialPosition = transform.position;
    SetTargetPosition(targetPos.position);
}

void Update()
{
    transform.position = Vector3.MoveTowards(transform.position, targetPosition, speed * Time.deltaTime);

    if (transform.position == targetPosition)
    {
        if (loop)
        {
            SwitchDirection();
        }
    }
}

public void SwitchDirection()
{
    if (transform.position == initialPosition)
    {
        SetTargetPosition(targetPos.position);
    }
    else
    {
        targetPosition = initialPosition;
    }
}

private void SetTargetPosition(Vector3 localPosition)
{
    targetPosition = initialPosition + localPosition;
    targetPosDebug = targetPosition;
}

void OnDrawGizmos()
{
    if (Application.isPlaying)
    {
        Debug.DrawLine(initialPosition, targetPosDebug, Color.red);
    }
    else
    {
        Debug.DrawRay(transform.position, targetPos.position, Color.red);
        Gizmos.DrawSphere(targetPos.position, 1.0f);
    }

}
}

```

# Answer
You are treating the target transform’s absolute position as a local position offset. For example, if transform.position is (3,3,3) and targetPos is offset by (1,1,1) from that, as a child of this transform, its position is (4,4,4).

So when you call SetTargetPosirion, passing in (4,4,4), targetPosition is set to initialPosition + (mislabeled) localPosition, which is (3,3,3)+(4,4,4), or (7,7,7). What you really want is to either pass in targetPos.localPosition when calling SetTargetPosition, or do not call SetTargetPosition at all, instead just assign `targetPosition = targetPos.position`:

```
using UnityEngine;

public class MovePlatform : MonoBehaviour
{
public Transform targetPos;
private Vector3 initialPosition, targetPosition;
public float speed = 3;
public bool loop;

void Start()
{
    initialPosition = transform.position;
    targetPosition = targetPos.position;
}

void Update()
{
    transform.position = Vector3.MoveTowards(transform.position, targetPosition, speed * Time.deltaTime);

    if (loop && transform.position = targetPosition)
    {
        SwitchDirection();
    }
}
public void SwitchDirection()
{
    if (transform.position == initialPosition)
    {
        targetPosition = targetPos.position;
    } else {
        targetPosition = initialPosition;
    }
}
}

```
> 1 votes

---
Tags: unity, c#, moving-platforms
---


# Question
Title: How to decelerate Ship using Vector Objects in Java
I am developing an Asteroids type game in Java, using a custom Vector2D class for the Ship. I have a vector object for its position, direction and velocity. I am having an issue with the ship deceleration, currently when there is no thrust (forward key is released) then I multiply my velocity vector by the Drag constant which is 0.3. However the ships speed does not decelerate and will stop abruptly instead, upon releasing the thrust key.

Here is the update method in my Ship Class:

```
public void update() {
    velocity = new Vector2D(direction);

    if(ctrl.action().turn > 0) {
        direction.rotate(ctrl.action().turn / STEER_RATE);
    }
    else if(ctrl.action().turn < 0){
        direction.rotate(ctrl.action().turn / STEER_RATE);
    }

    //Acceleration
    if(ctrl.action().thrust == 1) {
        velocity.addScaled(direction, DT).mult(MAG_ACC);
    }
    //Deceleration
    else if(ctrl.action().thrust == 0){
        velocity.mult(DRAG);
    }
    position.addScaled(velocity, DT);
    position.wrap(FRAME_WIDTH, FRAME_HEIGHT);
}

```

Contructor:

```
public Ship (Controller ctrl) {
    centerX = FRAME_WIDTH/2.0;
    centerY = FRAME_HEIGHT/2.0;
    this.ctrl = ctrl;
    position = new Vector2D(centerX, centerY);
    direction = new Vector2D(position).normalise();
    velocity = new Vector2D(direction);
}

```

I'd like to ask how I can slow the ship velocity rather than it losing all of its speed instantly. If more code is required I am happy to show it.

# Answer
> 1 votes
You're recreating the velocity vector every frame as DMGregory pointed out already.

The newly created vector likely has a value of 0 on all axis so multiplying it with 0.3 results in a velocity of 0.

The other case "ctrl.action().thrust == 1" only works because you are always adding a value first.

Just move the velocity-vector object out of the function and into the class scope. You will have to adjust your acceleration values and add upper and lower bounds for the velocity now though, since you're not recreating it every time.

---
Tags: java, vector
---


# Question
Title: How do I test for intersection of a ray and part of a capped cone / cone frustum?
The formulas to calculate the intersection between a ray and a capped cone / cone frustum are already widely known (see http://lousodrome.net/blog/light/2017/01/03/intersection-of-a-ray-and-a-cone/ or How do I test for intersection between a ray and a cone?) However, I have to test for the intersection between a ray and part of a capped cone. That means instead of having a surface doing a full revolution, it's just one quarter of it, for example.

The aforementioned formulas can handle a capped cone, but they are not suitable to determine the "revolution intersection angle". What would be the best way to solve this problem?

My idea is to first take the standard formula to intersect with the full cone and then use the parametric representation of the cone (see https://de.wikipedia.org/wiki/Kegel\_(Geometrie)#Analytische\_Beschreibung parametric representation is only on the German page), solve a linear equation system and then applying the inverse trigonometric functions to get the t parameter... I'm also thinking about some inequality tricks or applying the tangent function, but had no luck so far...

# Answer
> 0 votes
I would solve this by using the following steps:
1. Determine the points of ray-cone intersection
2. Filter out the points that are in range of a segment

You already have the first part, so using that get a list of candidate points. For each point, calculate the vector from the axis of the cone to the point (call this D).

You should also have two vectors that represent the segment. These should be vectors in the plane described by the axis of the cone, and rotated at angles representing the part to collide with. Call these A and B.

Using the solution here https://stackoverflow.com/questions/13640931/how-to-determine-if-a-vector-is-between-two-other-vectors, you can use:

```
if (AxD * AxB >= 0 && BxD * BxA >= 0)
// D is between A and B

```

where `x` represents the cross product.

---
Tags: intersection, raytracing
---


# Question
Title: Bitmap drawn with Graphics.DrawImage flickers
I am working on a space invaders clone using bugs as aliens. Everything works ok but the bug bitmap flickers on the screen.

```
    public void Form1_Load(object sender, EventArgs e)
    {

    }
    int x = 0, y = 0;
    private void Form1_KeyDown(object sender, KeyEventArgs e)
    {
        if(e.KeyCode == Keys.Left)
        {
            x-=5;
            if(x<=-350)
            {
                x = -350;
            }
        }
        if(e.KeyCode == Keys.Right)
        {
            x+=5;
            if(x>=375)
            {
                x = 375;
            }
        }
        if (e.KeyCode == Keys.Space)
        {
            if (y <= -530)
            {
                y = 0;
            }
        }
    }
    private void timer1_Tick(object sender, EventArgs e)
    {
        y -= 5;
        Invalidate();
    }
    protected override void OnPaintBackground(PaintEventArgs e)
    {

    }
    private void Form1_Paint(object sender, PaintEventArgs e)
    {
        Bitmap bug_one = new Bitmap("bug_one.bmp", true);
        Bitmap ship = new Bitmap("ship.bmp", true);
        Bitmap bullet = new Bitmap("bullet.bmp", true);
        e.Graphics.Clear(this.BackColor);
        e.Graphics.DrawImage(ship, 350 + x, 530);
        e.Graphics.DrawImage(bullet, 375 + x, 520 + y);
        e.Graphics.DrawImage(bug_one, 350, 0);
        e.Graphics.Dispose();
    }

```

# Answer
> 1 votes
The best way here is to create your own double buffer. It won't completely fix the problem but will reduce it. That being drawing your entire scene to a hidden canvas then once drawing is complete you then copy that content to your front buffer or swap the canvas that your component is pointing too. Your flicker is most likely due to clearing the canvas that you can see and drawing over the top.

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


# Question
Title: How to write a custom WaitUntil that is reusable?
In my turn based game, I like to have a function similar to Unity's WaitForSeconds, WaitUntil that can be called within a IEnumerator that suspends the coroutine execution for the given amount of moves. I already have a public working UnityEvent (moveEvent) which I could listen to.

So I could call it from any IEnumerator like:

```
IEnumerator Example()
{
    yield return new WaitForMoves(2);
}

```

I think I'd need a separate class like:

```
class WaitForMoves {

  int moves = 0;

  void Start() {
    Game.moveEvent.AddListener(OnMoveComplete);
  }

  void OnMoveComplete() {
     moves++;
  }

  // I'm not sure how to write this in a way that it waits
  // until this.moves === movesToWait
  public WaitForMoves(int movesToWait) {

  }
}

```

# Answer
https://docs.unity3d.com/ScriptReference/CustomYieldInstruction.html

```
class WaitForMoves : CustomYieldInstruction {

  private int movesLeft;

  public WaitForMoves(int moves) {
    movesLeft = moves;
    Game.moveEvent.AddListener(OnMoveComplete);
  }

  void OnMoveComplete() {
    movesLeft—-;
    if (movesLeft <= 0)
      Game.moveEvent.RemoveListener(OnMoveComplete);
  }

  public override bool keepWaiting {
    get {
      return movesLeft > 0;
    }
  }
}

```

And to use it, just as you wanted:

```
yield return new WaitForMoves(2);

```

If you have a global move counter in Game, then you wouldn’t need to have a listener at all:

```
class WaitForMoves : CustomYieldInstruction {

  private int targetMoves;

  public WaitForMoves(int moves) {
    targetMoves = moves + Game.moveCounter;
  }

  public override bool keepWaiting {
    get {
      return Game.moveCounter < targetMoves;
    }
  }
}

```
> 5 votes

---
Tags: unity
---


title: Depth texture white in shader

text:
# Question
Title: Depth texture white in shader
I am trying to implement shadow mapping into my project and am stuck at this problem: If I'm reading the shadow map values with `glReadPixels` and linearize those values, I am getting exactly the value I was looking for: ranging from 0 to 1. But when I am doing the exact same calculation in my shader, everything, where I rendered an object, is white. Another thing I noticed(which i assume is directly linked to my problem) is that if I am changing `glClearDepth` to anything different than 1, the output of my shader is black and the output of `glReadPixels` after linearizing is not anymore the value I wanted but anything else.

Here is the code where I am creating the depth texture:

```
glBindTexture(GL_TEXTURE_2D, _textures[GBTEXTURE_DEPTH]);
glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, width, height, 0, GL_DEPTH_COMPONENT, GL_FLOAT, NULL);
glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_NONE);

glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, _textures[GBTEXTURE_DEPTH], 0);

```

And here is the fragment shader:

```
in vec2 fragUV;
uniform sampler2D tex;

float zfar = 1000.0f;
float znear = 1.0f;

float linearize(float depth)
{
    return (-zfar * znear / (depth * (zfar - znear) - zfar)) / zfar;
}

out vec4 finalColor;
void main(void){
    float depth = texture2D(tex, fragUV).r;
    depth = linearize(depth);

    finalColor = vec4(depth);
}

```

I am doing the exact same calculation on the CPU, with correct values as a result.

I hope I described my problem with enough details for you to help me.

# Answer
Make sure that you call `glEnable(GL_DEPTH_TEST)` when you are binding your depth buffer for rendering. Preferably just before you call `glBindFramebuffer(GL_FRAMEBUFFER, (GLuint)Index);`
> 1 votes

---
Tags: opengl, graphics, shadows, depth-buffer, shadow-mapping
---


# Question
Title: Which is the fastest: shaders vs animations / animated images / pixel manipulation?
I'm quite newbie to shader programming.

I use Godot engine and after I see what can be done with shaders (eg. http://glslsandbox.com/e#53172.0) I realized that I MUST learn it no matter how hard it can be to understand the harder parts of it.

Till now I've used animated sprites or just make an animation in the animation editor.

I want to know if I gain perfomance by using shaders for example when I want to make a flag dragged by wind or I want to make something like in the example I linked.

I would think shaders are the fastest...but isn't it faster when there is a finished animation and you just have to make the game engine to use it?

# Answer
> 4 votes
Just because you can do something, it doesn't mean that you should. Shaders are amazing for making almost anything, but making those objects from scratch is more of a waste of time than anything.

The demos over at shadertoy and glslsandbox use these features because they can do it and they don't really have another option there.

Even if you could for instance create a flag with them, it would eat up way too much time of your life and it wouldn't really look any better than a sprite based approach. Combine this with slow/limited interaction between the CPU and the GPU and you'll have a hard time making a good game with this technique.

Most graphical libraries either have a built-in way to display animation or it's trivial using 2d sprites/textures. These give you a comparable result in seconds.

And yes, building procedural animation in shaders is slower than these. There's a reason bigger games don't use them as often (although as pointed out by DMGregory, games like Uncharted 4 do use this style of procedural animation). GPU cores are fast at basic things. Iterations and branching can slow them down a lot.

You **should** learn how to use shaders, yes. They're amazing, but if there are easier solutions, then go with those.

Using shaders also makes sure your future artists won't have any control over the animations you did. Updating them will take away precious development time from other places.

# Answer
> 1 votes
Performance-wise, direct pixel manipulation is almost always slower than the other techniques, because you have absolutely no hardware acceleration at all. Usually all the textures of your game live solely in the GPU RAM. Drawing a sprite somewhere on the screen is a pure GPU-internal operation. But if you want to do CPU pixel manipulation, you need to load the texture from GPU RAM into regular RAM, run your algorithm and then copy it back into GPU ram. That alone takes time. And then many common image operations are very parallelizable, so even the stuff you actually want to do likely runs faster on GPU than on CPU (but your mileage may vary, depending on what you actually want to do).

When it comes to choosing between pre-baked animation frames and procedural shader effects, you are dealing with a trade-off of computation time vs. memory. Cycling through different frames of the same animation is fast, but all the animation phases consume GPU RAM. A shader will likely take longer to compute the next frame (depending on how computationally expensive your shader is), but will use next to no video memory.

---
Tags: shaders, animation, godot
---


# Question
Title: Dr.Strange's door in Unity3D, how to put a projected void on a plane?
My question is about a visual trick I would like to perform in Unity3D. I want the player to walk outside a door and see no walls of the room behind them, just the door. They should still be able to see inside the room as if it were a "projected box plane" but not the walls containing it. They won't be able to touch where the walls should be, so I'm not worried about any invisible walls.

I'm imagining it would be similar to a "projected box plane" but I couldn't find any resources on how to do that in Unity3D. Just point me in an area I could research if this problem is more complicated then I thought.

Thank you.

# Answer
If I understand correctly, I think I came across a Brackey's youtube tutorial awhile back demonstrating a similar technique. You can have two completely different environments, but see through the door as if it's a portal. Thus you could set up your skybox-like magic dr.strange room, and your normal room and use something like this demo.

https://www.youtube.com/watch?v=cuQao3hEKfs

If not, I'd imagine you can achieve something similar with render textures.

If still not, you can get more complicated with camera layers and the new physics worlds api. But i'd avoid that if something like the Brackeys video is good enough!

**Edit:**

In case the video becomes unavailable, the process is as follows:

1. Set up two identical rooms that aren't visible to each other. You can do this by putting them on different layers, and modifying which layers the player camera can see.
2. In the center of each room you put a door. The door has a render texture and a trigger in the doorway. Each room has it's own camera which renders the view from the doorway into the other room onto a render texture. In room A's door, put the render texture from the camera in room B's door, so the doorway in room A is showing a view of room B. Do the same but the other way around for room B. Move the cameras around so as the player moves relative to the door, the view also changes.
3. When you hit the trigger of the doorway, teleport the player and it's camera to the corresponding spot in the door of the other room. You probably also want to temporarily ignore the trigger so the player isn't immediately teleported back.

This whole effect gives the illusion of a magic dr strange door.
> 1 votes

---
Tags: unity, c#, 3d, rendertexture
---


# Question
Title: How would you implement a soft magic system in a games?
Most, if not all, magic systems in games are necessarily hard magic systems, often with mana limits (or cooldowns) and a limited set of spells to prevent spamming god-tier spells in early game.

Other than breaking the rules in cutscenes (which makes every player mad), how would you go about designing and implementing a balanced soft magic system?

# Answer
This is a really interesting idea, and while I haven't thought about it before I'll give my initial thoughts on the matter.

Hard Magic Systems implies strongly enforced rules within the logic of your narrative universe. Soft Magic Systems implies not having strongly enforced rules within the logic of your narrative universe. In games, you need to code systems, and code is a set of rules and instructions for a computer to follow. However game logic != narrative logic, so I believe it would be possible if you can get your game logic to give the illusion of narrative freedom. We try to do this all the time in modern open world games.

**The easy solution:** Naratively your character can do anything, gameplay wise they can only do what you've programmed explicitly. While this technically gives you what you want, I assume you really mean having a more open gameplay.

**The hard solution:** Design a system that allows you to freely combine and generate new magical abilities. This is all about the illusion of no rules. This would be incredibly hard to balance from a gameplay perspective, as players could make / do a variety of things you may never have tested. However you could see a system like that used in starcraft/dota, with data driven spells and abilities. This way players could freely mix data points and the system would output an effect. Imagine starcraft 2 editor but done naturally through a players interactions in the game world. This is pretty complex but doable. See: https://developer.valvesoftware.com/wiki/Dota\_2\_Workshop\_Tools/Scripting/Abilities\_Data\_Driven

**The AI Approach:** I'm sure some machine learning to generate spells and abilities could help, but i wouldn't recommend it. Seems like trying to assemble a shelf with a sandal.
> 3 votes

---
Tags: game-design
---


# Question
Title: Rotate an object smoothly by using Accelerometer Input in Unity
There is a simple script where the object orientation is equal to the mobile devices orientation.

it works but the object doesn't rotate smoothly.

```
void FixedUpdate()
{
    float accelx = Input.acceleration.x;

    float angle = Mathf.Asin(accelx) * Mathf.Rad2Deg;

    transform.eulerAngles = new Vector3(angle , 0, 0);
}

```

How to rotate an object smoothly by using Accelerometer Input ?

# Answer
> 1 votes
DMGregory is right in his comment. What you're looking for is a gyroscope. An Accelerometer measures the acceleration of a device (or the change in velocity). If the object is still, or moving at a constant speed, it will measure 0 (except in the direction of gravity because gravity is a constant acceleration downward). Since force = mass * acceleration, and our mass is constant, you could look at this as indirectly measuring the force applied to the device. If we shake the device we apply a force. If we move the device left, we apply a force pushing left, then another pushing right to stop it once we've reached our destination.

A Gyroscope is used to measure the rotation / orientation of a device. This is what you want. While neither sensor is perfect, you definitely want the gyroscope.

If you REALLY want to use the accelerometer you could do the following, however I would NOT recommend it as it doesn't have much use and a gyroscope will give better results as that's what it's made for:

1. Ask your user to hold the device flat, and measure the accelerometer. This is the direction of gravity as a vector since as long as the device is stationary that should be the only force applied
2. Now if your user rotates the device and the device has no forces applied to it (usually not moving as it's hard for a user to maintain constant velocity), then again the only force on the accelerometer is gravity. Take that measurement and compare it to your original measurement.

Let's say the user held it perfectly flat and the accelerometer measured \<0, -9.8, 0\> assuming the y axis is pointed towards the ceiling, z away from the player, and x towards the players left hand side. Then say your next measurement is \<0, 0, -9.8\>. This means the user pointed the controller up towards the ceiling, as the second vector is a 90deg rotation compared to the first. Again this fails as soon as the user tries to move the device, and likely while the user is rotating the device, since the accelerometer might not be located directly in the center of the device or the user is not rotating around the center. This means the accelerometer is moving in the xyz plane, thus a force was applied, thus your measurement could be invalid.

---
Tags: unity, rotation
---


# Question
Title: Unity: Is type casting every frame too expensive?
I have a state machine that controls my enemy AI. Each AI has a target which may be a Player, an obstacle, a shell, or even a Vector2 position.

I'm trying to abstract my "target" member, and my first thought was to use GameObject, then downcast to whichever type I need for different enemies. Examples below:

```
class StateController: MonoBehavior {
    GameObject target;
    FireAction action;

    Update() {
        action.Fire(this);
    }
}

class FireAction: ScriptableObject {
    public abstract void Fire(StateController c);
}

//Examples of different fire scripts:
class FireAtPlayer: FireAction {
    public override void Fire(StateController c) {
        Player p = c.target as Player;
        //--use properties of Player object--
    }
}

class FireAtPoint: FireAction {
    public override void Fire(StateController c) {
        GameObject t = c.target as Player;
        //--use properties of GameObject object--
    }
}

```

As you can see, my Fire methods would cast the target object at every call to Update. Will this negatively affect my game's performance? Note that I know for a fact what type of object the target is, so I'm not guessing when I'm casting. Thank you in advance of your help!

# Answer
> 2 votes
What other's have said is correct. It likely won't cause issue. This is partially a problem with oop in general. The non casting solutions are not easy to maintain and work with. An alternative component based approach might be better, but since you're using oop i'll go from there. There's two alternatives that come to mind

1. Duplicate your pipeline for each subtype. For example, let's say I have BaseCharacter, and Enemy and Player which inherit BaseCharacter. I can have something like this

```
public class SpawnManager : Monobehaviour {
  public event Action CharacterSpawned;
  public event Action PlayerSpawned;
  public event Action EnemySpawned;

  public void SpawnCharacter(BaseCharacter char) {
    Instantiate(char)
    if (CharacterSpawned != null) CharacterSpawned.Invoke();
  }

  public void SpawnPlayer(Player player) {
    SpawnCharacter(player);
    if (PlayerSpawned != null) PlayerSpawned.Invoke();
  }

  public void SpawnEnemy(Enemy enemy) {
    SpawnCharacter(enemy);
    if (EnemySpawned != null) EnemySpawned.Invoke();
  }
}

```
2. Another alternative to not cast is to just have a union-like struct which as long as it's holding pointer references, is only taking up sizeof(pointer) * N where N is the number of subclasses

```
public struct SpawnEvent {
  public enum Type { Player, Enemy };
  public Type Type;
  public Player player; // null if enemy
  public Enemy enemy; // null if player
}

```

Then check the enum and get the correct field as needed. Again none of these approaches are perfect, nor is casting, but if you stick with OOP you'll find this is one of the places it falls short. You can look into component based design, if you're really not satisfied, but i'm not as well versed in that to offer much advice.

# Answer
> 1 votes
If you can avoid casting frequently casting then do. However if you do not find it causes a reasonable performance hit then don't worry.

Also it is not possible to cast GameObject to Player as you cannot inherit GameObject yourself. You should be using GetComponent() to get components from GameObjects.

# Answer
> 0 votes
I wasn’t aware that you could cast a GameObject into a component type on that GameObject and it would work. In fact I don’t think it will, will it?

Even if it did, it would be akin to calling GetComponent, which is an expensive function, every frame, which is generally accepted to be a Bad Idea.

From Unity’s documentation:

> In Unity, it is common is to call GetComponent() to access components \[repeatedly. ...\] This code works, but it is inefficient due to the repeated GetComponent() call.

A more efficient solution would likely involve a bit more polymorphism, although it would require a bit of restructuring from your presented design, and even that has its own drawbacks. As DMGregory suggested, you won’t know if your solution is sufficient or requires some rework until you try it out. Just keep in mind that your solution is simple, but not particularly efficient.

---
Tags: unity, c#, performance, state
---


# Question
Title: How to limit speed while still adding external forces
I have a ship with a single thruster in space (no friction). My ship uses integration on every update, like this:

(PSEUDO CODE)

```
Update() {
  Velocity += Acceleration
  Velocity = Min(Velocity, MaxSpeed)
  Position += Velocity
  Acceleration = 0
}

```

Any force that interacts with the ship will accelerate it:

```
Accelerate(f) {
  f /= Mass
  Acceleration += f
}

```

Finally this is how I thrust the ship:

```
Thrust() {
  f = MaxThrustPower * Angle (cos/sin)
  Accelerate(f)
}

```

Like this I can accelerate my ship thrusting until MaxSpeed is reached.

The problem is that I also accelerate the ship with other forces line Gravity pulls, collisions, friction fields, etc. And all those forces, as they also add to velocity, they are also being truncated by the MaxSpeed limit.

At the other hand, once I have reached MaxSpeed, I cannot thrust any more to change my direction.

*(This is a 2D game, not an exact simulator)*

How can this be handled properly?

**Thanks**!

# Answer
Ok so I found that the solution to my problem was a new approach to the problem.

First I removed the overall velocity length limit in the update function. At this point all forces will be able to apply on my ship, from thrusting to black holes, no limits.

The thruster is a vector with a direction and the force to be applied on that direction. The thruster also has a **max power** value that will limit the amount of force it can apply until the **max speed** is reached.

Every time I fire the thrust I need to keep the applied force **proportional** to the new desired velocity and **relative** to the current velocity.

And as I am using Steering Behaviours I will calculate the new thrust vector like this (PSEUDO CODE)

```
  steer = desiredVelocity - ship.velocity
  steer.limit(maxThrustPower)

  // Thrust and direction settings
  desireStrength = steer.length;
  rotorAngleDiff = Math.abs(ship.rotorAngle - steer.angle);

  // Start rotating the ship
  ship.rotateTo(steer.angle);

  // Fire thrust: **n** and **k** are 0.01 and good for my game scale
  if (desireStrength > n && rotorAngleDiff < k) {
    ship.thrust(desireStrength);
  }

```

It is working perfect now!! Even combining different steering behaviours.

In case someone likes to have working demo in JavaScript just ask.
> 0 votes

# Answer
Just change the order of your operations, and make sure you use 2d vector values for everything (force, acceleration, velocity, position.)

Your clamping should be done at the last step, after you have accumulated all the forces, calculated the acceleration, applied the acceleration.

1. accumulate all forces
2. acceleration = force / mass
3. velocity += acceleration * dt
4. clamp the magnitude of the 2d velocity vector
5. position += velocity * dt

To do the clamping:

```
if velocity.length() > maxvel
    velocity = velocity.normalized() * maxvel

```

**UPDATE**

Yes, by clamping the velocity, you will see that further acceleration in the direction of the currently maximum velocity vector will have no effect. But that's the cost of adding that artificial clamp.

Simulations in an atmosphere (airplane instead of rocket) have the benefit of a soft velocity limit:

Because air-drag goes up with the square of the velocity, even the most powerful engine will at some point stop accelerating. Also gravity can't overcome the "terminal velocity" once the drag forces equal the gravity force.

In space there is no such limit, so acceleration continues. (If we disregard the effects at near light speed of course.) So a max speed in space makes little sense in physics terms, and is more like a game-play thing.
> 2 votes

---
Tags: 2d, javascript, vector, integration
---


# Question
Title: Make a variable go down as another goes up?
I am making a JavaScript game called "Spoop: The Clicker", and I have a variable shown by text:

```
stroke("blue");
fill("purple");
textSize(30);
text("Spoop Cash: §" + spoopCash, 130, 10);

```

This is inside the draw loop, as it is always shown.

The thing is, I need `textSize` to be set shrink as my other variable `spoopCash` increases. How could I do that? If you can, please include a way to stop it from going too small (such as size 10 being the smallest allowed.)

# Answer
There are many ways to do things like this based entirely on context. One example would be to have 2 values have the same values (say 10 to 20) and doing it like a scale where +5 on one would result in -5 on the other. This is probably the easiest case to handle since all you would have to do is say:

```
var1 = X; // if x is 12
var2 = max - (var1 - min); //var2 = 20 - 2

```

Another, slightly more complex but more useful case would be for you to define the min and max values of each variable and then check how far from max the one value is and then set the current value of the other one to the opposite, both cases using relative values...

Example:

```
var obj1_min = 10;
var obj1_max = 50;
var obj2_min = 13;
var obj2_max = 47;
var obj1_cur = 10;
var obj2_cur = 47;

function SetObj1(var to) {
    if (to < obj1_min || to > obj1_max) return;
    obj1_cur = to;
    var range1 = obj1_max - obj1_min;
    var range2 = obj2_max - obj2_min;
    var percentage = (obj1_cur - obj1_min) / range1;
    var percentage_other = 1 - percentage;
    var value_by_range = range2 * percentage_other;
    obj2_cur = obj2_min + value_by_range;
}

```

As you can see, implementation varies dramatically by how you intend the values to relate to one another but this larger function should be a decent all rounder.

Just in case it's not clear what's going on is that it is checking how much each value can change (i.e. 10 to 50 means it has a range of 40) and then it checks to see how far into that range you currently are. (i.e. at 25 you are 15 into the range). Once it knows you are 15 points into the max 40 it calculates that as a % (say 30%) and then says "In that case, make the other one 100% - that amount).

Now we repeat the process to find the range of the second object and then we ask "So, what value would be 70% of that range?" and then we add that to the min value. So if the min and max for the second object were 13 and 47 that would give us a range of 34, 70% of which would be something like 25-ish so we add that to the min value of 13 and there you go... 30% into the range of 10..20 means 70% into the range of 13..47 = object2's current value
> 3 votes

---
Tags: javascript, game-loop, text
---


# Question
Title: Does an inventory limit in an MMORPG make sense?
I am currently developing a simple 2d MMORPG. My current focus is the inventory system.

I am currently wondering if I should implement a limit on what a player character can carry. Either in form of a maximum weight, a limited number of inventory slots, or a combination of both. Almost every MMORPG I ever played limits inventory space. But plausibility aside, is this really necessary from a gameplay point of view? Maybe it would in fact improve the game experience when I just let the players carry as much stuff as they want.

**tl;dr:** What is the game development rationale behind limiting carrying capacity of player characters?

**Edit:** Thanks for all the answers so far. They all were very insightful. After your input I decided to go for a limited inventory to prevent people from carrying too many healing items and too much specialized equipment into dungeons. To avoid the problem of loot overload and having to return to the town all the time, I plan to give players the ability to send items from their inventory directly to their storage (but not the ability to retrieve them in the field). I accepted the answer by Kylotan for now, but do not let this discourage you from posting additional answers, when you feel that some interesting aspect wasn't covered yet.

# Answer
Much of game design is about resource management, because deciding how best to use limited resources is an interesting choice that games can easily implement. Limiting the inventory forces players to think about the value of each item and make decisions on whether to hoard or sell their loot, and on which items to carry out into battle with them.
> 35 votes

# Answer
Limiting inventory can make sense.

**Doesn't make sense:**

* limiting just for sake of limiting; there's no purpose, and hence, no sense.
* limiting to limit, again only for sake of limiting, without any competition meaning; as Kylotan said, you can limit players, forcing them to think what they need to take on a fight; but what if they can just teleport to base any time, like in Diablo 2 - this makes the limit only annoying to the player.
* realism - you fly on a huge dragon, that would biologically need to eat a herd of cows every month, fight with a 5-meter flaming sword without any burns on your face, appear from nowhere when logging in, but suddenly you need to limit your capacity just for the sake of realism and nothing else?

**Makes sense:**

* to save storage (database) space
* to sell more space, like backpacks in WoW, or upgrading stash in Diablo 3; most of RPG games feed on the feel of growth, your level grows, your experience grows, your wealth grows, then why not your storage capacity?
* to involve some additional fun like storing items in Diablo 2 efficiently (as they have different shapes)
* to force trading; again Diablo is a good example - at some moment you have so many set items, that you can no longer store them - it's best then to exchange some items from sets you don't need, for items from sets you want to collect.
* realism for sake of immersion as Mitchell stated in his answer.
> 18 votes

# Answer
Limiting the inventory serves two reasons:

### Immersion

It doesn't make sense to carry every item you can pick up. Limiting your inventory prevents breaking the player's immersion in the game world. This is why most modern shooters have a limited amount of weapon slots.

### Challenge

It forces the player to make choices about what equipment to pick up, and what to leave behind, as well as preventing the hoarding of items which would make the game too easy. This is the most common reason for games to limit the inventory.
> 10 votes

# Answer
I think an important point has not been covered here. If you let people have unlimited inventory space, they will soon enough (depending on your itemization model) have filled their inventory with a crazy amount of items.

Unless you've designed the most amazing inventory management system ever with search and filter capabilities matching those of Gmail and beyond, you will have players give up your game out of frustration ("Where did I put my Great Axe of Beheading again? Page 58?")

If you want the player to have unlimited space, force her to organize her items by (for example) letting her create labelled chests where she can "archive" items of interest, keeping them away from her inventory.
> 10 votes

# Answer
Realism would surely be one rationale. One thing that bugs me in games like Oblivion is that there's a threshold for weight - if you're over it, you just can't move at all. I mean, how plausible is it that you can run and jump at full speed while carrying 187kg of armour and weapons and random potions without any apparent means of them even being attached to your body, and then you pick up a flower that weights 0.1kg, and suddenly you can't move? It's a real jarring point that brings home that you're playing flawed game, and kicks you right out of your escapism trip.

Far more sensible would be to have weight affect speed - once you start carrying a lot, you start to slow down, eventually slow to a crawl. This would still have all the advantages mentioned in other answers - challenge, for instance, but would be far more realistic, and immersive.

Daggerfall also had a system where you could buy a cart, which you could drive around, and fill with crap. You couldn't take it into dungeons and shops, but you could raid a dungeon, and come back and unload into your cart a few times before heading to the shops to sell your loot. That was a very cool system, and it'd be nice to see it in other games.

You could also have a "bulk" system, where after you start carrying too much volume, it starts to affect your agility, so you have to do actions slower. Might get a bit complex though.
> 5 votes

# Answer
Skyward Sword had one of my favorite inventory management systems. You had limited "pouches" for ancillary items, and you had to store the ones you didn't need in the item check. You could buy more pouches for items increasing the amount you could carry with you. And you could also buy/find duplicates of items (mainly the ammunition bags and medals) allowing you to play how you want.

The good part is that while you had limited space for items, the main weapons you had enough space for, so you had everything you needed, but you could tailor your inventory to suit your preference. At one point I filled my pouches with just upgraded quivers so I could snipe to my hearts content.
> 2 votes

# Answer
In Lineage (2 at least) the weight limit seemed pretty much like a requirement as if you could stack an infinite number of potions and soulshots/spiritshots, you'd never need to return to town and could grind in a dungeon forever and ever... ^^
> 2 votes

# Answer
Inventory limit makes sense for every item type which isn't used as a trivially stackable currency.

This isn't so much about being realistic, or cost associated with inventory, but all about conditioning the player to keep the inventory tidy enough that they don't carry "dead weight" around with them.

The user is only able to recall a limited number of items from his inventory, everything beyond that is cluttering the UI. The more you allow the inventory to clutter, the more tedious it becomes too the user to actually weed out.

You don't only hit this phenomenon with unlimited inventories, but even already of the inventory is just slightly to big.

20 slots or so are what the user can actively recall. Most games are going way beyond that, and as a result you see bandaids such as "favorites" or "trash filters" introduced which aim to assist the user in discarding their excessive inventory.

But even then you usually end up with too many "favorites", so some games are starting to split of "collectibles" like "rare skins" into separate collections instead, in order to encourage the user to part even with their "favorites".

Usually, item management in a game with a severely limited inventory - hardly more slots than you could utilize in a quick bar - is less tedious than one with unlimited or excessive inventory.
> 1 votes

---
Tags: game-design, mmo
---


# Question
Title: Activate object that have button component?
I'm trying to activate the array object that have button component.

```
 public GameObject[] weapon_carry_pistol = new GameObject[3];
 public int p1_carry,activeObjects;

 // Update is called once per frame
 void Update()
{

  p1_carry =  weapon_carry_pistol[0].GetComponentsInChildren<Button>().Length; // 6 objects

        for (int i = 0; i < activeObjects; i++)
    {
        weapon_carry_pistol[0].GetComponentsInChildren<Button>()[i].enabled = true;
    }

}

```

This script do activate the button component but not the whole game object. If I change "Button" to "GameObject" I get error //.GetComponent requires that the requested component 'GameObject' derives from MonoBehaviour or Component or is an interface.//

# Answer
> 1 votes
There is a conceptual difference between a GameObject and a Component. One GameObject has many Components and every Component belongs to a GameObject. If you have that thing on the UI which you consider a button, then what you actually have is a GameObject which has a Button component (among other components).

Some components can be enabled and disabled with a `.enabled` property or in some other way (not all components, though. For example, you can disable a `Renderer` but you can't disable a `Transform`). A GameObject on the other hand, is activated or deactivated with the `SetActive(bool)` method.

So if you want to get all the game objects in the children of `weapon_carry_pistol[0]` which have a button and then activate those game objects, then you:

1. find all the button-components with `GetComponentsInChildren`. In this case you specifically want to include any buttons in inactive game objects, so you need to use `GetComponentsInChildren<Button>(true)`.
2. iterate those in a `foreach` loop
3. determine the GameObject of the current button by checking the `.gameObject` property every component has.
4. activate that GameObject with `.SetActive(true)`

Like this:

```
foreach (Button button in weapon_carry_pistol[0].GetComponentsInChildren<Button>(true) ) {
   button.gameObject.SetActive(true);
}

```

---
Tags: unity
---


# Question
Title: Why is the Position Handle placed at certain distance away from vector3 unit in Unity?
I have a vector3 value that I am setting in inspector and I am drawing a ray using `OnDrawGizoms` to draw that vector line.

However, the position handle I made using Handles API to set the vector3 value is placed certain distance away from the vector unit. It's not placed exactly at the end point of the vector line that is drawn and I am not sure why.

My goal is to just make a handle to position a vector3 value.

EDIT: For some reason, the handle is positioned correctly for y position alone but not for x and z positions.

Here is my code:

In this script, it is the `localTargetPosition` vector3 value that I want to make my handle for.

```
public class MovePlatform : MonoBehaviour
{
public Vector3 localTargetPosition = new Vector3(5, 0, 0);
public Vector3 m_initialPosition { get { return initialPosition; } set { initialPosition = value; } }
private Vector3 initialPosition, targetPosition, targetPosDebug;
public float speed = 3;
public bool loop;

void Start()
{
    initialPosition = transform.position;
    SetTargetPosition(localTargetPosition);
}

void Update()
{
    transform.position = Vector3.MoveTowards(transform.position, targetPosition, speed * Time.deltaTime);

    if (transform.position == targetPosition)
    {
        if (loop)
        {
            SwitchDirection();
        }
    }
}

public void SwitchDirection()
{
    if (transform.position == initialPosition)
    {
        SetTargetPosition(localTargetPosition);
    }
    else
    {
        targetPosition = initialPosition;
    }
}

private void SetTargetPosition(Vector3 localPosition)
{
    targetPosition = initialPosition + transform.TransformDirection(localPosition);
    targetPosDebug = targetPosition;
}

void OnDrawGizmos()
{
    if (Application.isPlaying)
    {
        Debug.DrawLine(initialPosition, targetPosDebug, Color.red);
    }
    else
    {
        Debug.DrawRay(transform.position, transform.TransformDirection(localTargetPosition), Color.red);
    }
}
}

```

This is the script used for making handle:

```
[CustomEditor(typeof(MovePlatform)), CanEditMultipleObjects]
public class MovePlatformEditor : Editor
{
protected virtual void OnSceneGUI()
{
    MovePlatform movePlatform = (MovePlatform)target;

    Vector3 initialPosition = movePlatform.transform.TransformPoint(movePlatform.m_initialPosition);
    Vector3 targetPosition = movePlatform.transform.TransformPoint(movePlatform.localTargetPosition);

    EditorGUI.BeginChangeCheck();
    Handles.Label(targetPosition, "Target", "button");
    targetPosition = Handles.PositionHandle(targetPosition, movePlatform.transform.rotation);

    if (EditorGUI.EndChangeCheck())
    {
        Undo.RecordObject(movePlatform, "Move Handles");

        movePlatform.localTargetPosition = movePlatform.transform.InverseTransformPoint(targetPosition);
    }

    Handles.color = Color.yellow;
    //Handles.DrawLine(initialPosition, targetPosition);
}

}

```

# Answer
I fixed my own problem. All I had to do was attach the MovePlatform script to an empty game object and make the cube that I wanted to move as the child of this game object. The problem was I originally had the script attached to the cube itself and because the cube's scale was not (1,1,1) but (4,1,4), it positioned the handle further away in x and z positions by approx 40 units.
> 0 votes

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


# Question
Title: Finding translation component of a 4x4 matrix inverse
I have 4x4 matrix (A) (maya softw):

```
|Xx Xy Xz 0| - basis of X and dummy 0
|Yx Yy Yz 0| - basis of Y and dummy 0
|Zx Zy Zz 0| - basis of Z and dummy 0
|Tx Ty Tz 1| - Position x, y, z and dummy 1

```

In this case, I know there is no scaling or sheer, so the upper-left 3x3 portion is a pure rotation matrix. That means I can invert this portion by taking the transpose.

So inverting the matrix should give me something like this:

```
|Xx Yx Zx 0|
|Xy Yy Zy 0|
|Xz Yz Zz 0|
|T? T? T? 1|

```

But I don't know how to find the `T?` values that correctly invert the translation component of the matrix. It's not just the inverted position (T-1)

---

My thinking so far:

Matrix of an untransformed object at the origin - (I - identity):

```
| 1  0  0  0 |
| 0  1  0  0 |
| 0  0  1  0 |
| 0  0  0  1 |

```

Matrix of a translated object (Tx=3, Ty=4, Tz=5) (A):

```
| 1  0  0  0 |
| 0  1  0  0 |
| 0  0  1  0 |
| 3  4  5  1 |

```

Inverse matrix of A (A'):

```
| 1  0  0  0 |
| 0  1  0  0 |
| 0  0  1  0 |
|-3 -4 -5  1 |

```

Matrix of translated and rotated(Y=90) object(B):

```
| 0  0 -1  0 |
| 0  1  0  0 |
| 1  0  0  0 |
| 3  4  5  1 |

```

inverse matrix of B (B'):

```
| 0  0  1  0 |
| 0  1  0  0 |
|-1  0  0  0 |
| 5 -4 -3  1 |

```

Strange things start to happen when you take two differently-rotated matrices with the same translation and you get different inverse translations!

It seems like some dot product is involved in the translation calculation.

# Answer
If I have a matrix \\$M\\$ with translation vector \\$\vec T\\$, that means it maps the origin to the vector \\$\vec T\\$ in homogeneous coordinates, ie:

$$\begin{bmatrix}0 & 0 & 0 & 1\end{bmatrix} \cdot M = \begin{bmatrix}T\_x & T\_y & T\_z & 1 \end{bmatrix} = \begin{bmatrix} \vec T & 1 \end{bmatrix}$$

So then the inverse of \\$M\\$, that is \\$M^{-1}\\$, should do the opposite, and map \\$ \vec T\\$ back to the origin.

We can think of the result of the matrix multiplication as a sum of the input vector multiplied by the first three rows (what the rotation / scaling / shearing part of the matrix do to the vector) plus the input vector multiplied by the final row (what the translation part of the matrix does to the vector). To get back to zero, this last part has to exactly negate what happened before.

So, if we look at just the upper 3x3 portion of your given inverse does to the vector \\$\vec T\\$...

$$\begin{bmatrix}T\_x & T\_y & T\_z\end{bmatrix} \cdot \begin{bmatrix}X\_x & Y\_x & Z\_x \\ X\_y & Y\_y & Z\_y\\X\_z & Y\_z & Z\_z \end{bmatrix} = \begin{bmatrix} \vec T \cdot \vec X & \vec T \cdot \vec Y & \vec T \cdot \vec Z\end{bmatrix}$$

This gives us what our inverse translation needs to undo. So our final translation vector, call it \\$\vec U\\$ for "Undo", is:

$$\vec U = -1 \cdot\begin{bmatrix} \vec T \cdot \vec X & \vec T \cdot \vec Y & \vec T \cdot \vec Z\end{bmatrix}$$

And your inverted 4x4 matrix is:

$$\begin{bmatrix}X\_x & Y\_x & Z\_x & 0\\ X\_y & Y\_y & Z\_y & 0 \\X\_z & Y\_z & Z\_z & 0 \\ -\vec T \cdot \vec X & -\vec T \cdot \vec Y & -\vec T \cdot \vec Z & 1\end{bmatrix}$$
> 0 votes

---
Tags: matrix, linear-algebra
---


title: Model turning 2d when it's parented

text:
# Question
Title: Model turning 2d when it's parented
I'm importing arms from blender for my first person controller but when I make the player the Arms' parent it turns 2d. I have no idea why this is happening so if anyone could help it would be very appreciated.

I'm very confused lol

# Answer
When creating my empty game object the scale along the x axis was 0. This meant that when I made the player (An empty game object) the parent, the arms inherited the 0 scale on the x factor. To fix this, change the scale on the x axis to 1 on the player gameobject :).
> 1 votes

---
Tags: unity, transformation, first-person-shooter, importing
---


# Question
Title: Unity is Creating Black Boxes when I look around
Please help me with this issue. I believe it came about after I finished tweaking post processing behavior in a minor way. If anyone has any idea please share it. I tried to rebake lighting on both scene and lightmaps tabs and it didn't make any difference.

# Answer
> 1 votes
It was Screen Space Reflections property on postprocessing behavior when turned off. Once I turned back on they went away. Hope this helps future developers. Very strange by that it was only having this issue on one scene.

---
Tags: unity, lighting, post-processing
---


# Question
Title: How to change the mesh of the character in UE4?
I made a Bellsprout mesh in Blender, exported it as an FBX file, and imported it into UE4.

I can insert it in the stage without problem, but I would like to use this Bellsprout mesh to replace the mesh of the built-in character.

Even clicking and dragging will not replace the mesh:

I've looked into importing between blender/UE4: https://wiki.unrealengine.com/Static\_Mesh\_from\_Blender

And also about mesh editing: https://docs.unrealengine.com/en-us/Engine/Content/Types/StaticMeshes/Editor

I also looked at some questions in this forum: Changing rendering in UE4 and Making only parts of a mesh destroy in UE4

To see if the question had not already been asked.

# Answer
> 0 votes
The mesh you've imported appears to be a static mesh, whereas the character expects a *skeletal* mesh (one that supports animation).

Your options are basically to

* re-export your character model as a skeletal mesh or
* modify the character Blueprint to change the type of the mesh component from SkeletalMeshComponent to StaticMeshComponent.

The first option is probably the simpler one, as changing the mesh component type will likely break functionality related to triggering and dealing with animations that you may need to fix up before the Blueprint will compile.

Here is a guide on making a skeletal mesh in Blender. I can't vouch for its utility, but it might provide a starting point for handling the export.

---
Tags: unreal-4, 3d-meshes, mesh, fbx
---


# Question
Title: Make health bar follow the player not the camera
I wrote a script to create small bars of life & mana on top of the character.

So far it's following him and everything ok, but the problem is that it has a delay, for example the player arrives first and then the bars arrive shortly afterward.

How can I keep the bars it fixed to the player?

```
using UnityEngine;
using UnityEngine.UI;

public partial class UIMiniHealthMana : MonoBehaviour
{
     public GameObject panel;
     public Slider healthSlider;
     public Slider manaSlider;

     void Update()
     {

         Player player = Utils.ClientLocalPlayer();
         panel.SetActive(player != null); // hide while not in the game world
         if (!player) return;

         healthSlider.value = player.HealthPercent();

         manaSlider.value = player.ManaPercent();

     }

}

```

Example of the error:

# Answer
Since you have not given any info about the GameObject, so i am guessing it could be one of these two.

1. Problem with your sprite animation. (As the health bar doesn't deviate too much and can be visualised within imaginary square, so it is possible that the animations are not in place, and the health bar is fine)
2. The GameObject Panel is not a child of the PlayerController.

Solution:

1. For the first case, you should look into your animations, so that they are in place.
2. For the second case, make the sure that the GameObject Panel is a child of PlayerController.

Provide more information if your problem isn't solved from these two cases.
> 0 votes

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


title: Vertices in index buffer not rendered

text:
# Question
Title: Vertices in index buffer not rendered
I'm beginning with the 3D rendering in Monogame and i'm facing not a real issue because i already find a way to bypass it but more of a question. I'm rendering a simple cube with 8 vertices like that:

```
_vertices[0] = new VertexPositionColor(new Vector3(-1, 1, -1), Color.Red);
_vertices[1] = new VertexPositionColor(new Vector3(-1, -1, -1), Color.Red);
_vertices[2] = new VertexPositionColor(new Vector3(1, -1, -1), Color.Red);
_vertices[3] = new VertexPositionColor(new Vector3(1, 1, -1), Color.Red);
_vertices[4] = new VertexPositionColor(new Vector3(-1, 1, 1), Color.Green);
_vertices[5] = new VertexPositionColor(new Vector3(-1, -1, 1), Color.Green);
_vertices[6] = new VertexPositionColor(new Vector3(1, -1, 1), Color.Green);
_vertices[7] = new VertexPositionColor(new Vector3(1, 1, 1), Color.Green);

```

But i'm also using an index buffer to draw each triangle for each faces and this is where my issue is. When i'm doing the following:

```
_indices = new int[] // 6 faces, each containing 2 triangles of 3 vertices
{
           0, 1, 2, 0, 2, 3, // front
           3, 2, 6, 3, 6, 7,
           4, 0, 3, 4, 3, 7,
           1, 5, 6, 1, 6, 2,
           4, 5, 1, 4, 1, 0,
           4, 7, 6, 4, 6, 5 // back
};

```

The render is perfect and every edge is rendered as you can see on this gif:

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

But when i changed the order inside the index buffer of the back part, like the following:

```
_indices = new int[] // 6 faces, each containing 2 triangles of 3 vertices
{
           0, 1, 2, 0, 2, 3, // front
           3, 2, 6, 3, 6, 7,
           4, 0, 3, 4, 3, 7,
           1, 5, 6, 1, 6, 2,
           4, 5, 1, 4, 1, 0,
           4, 6, 7, 4, 5, 6 // back, update is here
};

```

The only thing that was updated is the order of the last column and the result is the following:

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

Why does the render is not done on the second case when the only change made is the order of two vertices ? I know that I can do a rasterize state to render each side of a triangle but one solution is working without it, so i'd like to avoid using it.

Thanks!

# Answer
> 1 votes
When you render a closed, opaque object like your cube, from any particular viewpoint, only about half of the triangles contribute to the final image: the ones on the side facing the camera. The ones on the far side would occupy the same silhouette on-screen, but would be hidden behind the front-facing triangles.

So, we can cut our rendering workload in half by not even trying to render those "back faces" in the first place, knowing they'll end up hidden. This is an optimization called "backface culling"

To figure out if a particular triangle is a back face, the GPU uses a neat trick: when we wall thorough the projected vertices of a non-degenerate triangle in the order they were given, the path we follow will turn either clockwise or counterclockwise in the plane of the screen. This is called the "winding" of the triangle. When we look at a triangle from its "back" side, the winding order flips, from clockwise to counter-clockwise or vice versa.

By setting up our input so that all the triangles we pass in are wound clockwise when viewed from their outside face, we can tell the GPU to draw only clockwise-wound faces and skip any thar are wound counter-clockwise, since the latter must be back faces.

When you exchange the order of two vertices in a triangle, you also change its winding order. So in your example, you told the GPU that the last two triangles in your buffer should only be drawn when viewed from the other side, so it culls them as back faces when looking at them directly.

The fact that these two triangles on the green face of the cube are not being drawn lets you see into the cube and notice that the other faces are also not being drawn — and this is correct, because we really are looking at them from behind. Normally the green face would be drawn in front, hiding the back sides of the other faces from view, so it would be safe to skip drawing those faces from this angle.

---
Tags: 3d, monogame, vertex
---


# Question
Title: Can a .exe file ported from a program like NW.js or Electron be put console stores?
I'm early in development working on a game in HTML5/JavaScript canvas, and I wondering if porting the game with some HTML/JS to .EXE converter would allowed it to be posted on consoles?

I think it should be possible, since Downwell(though made with an entirely different language) is a .EXE file, and is available on Switch and Playstation.

# Answer
Probably not.

Ultimately it will depend on what the "converter" tool does, but generally they operate by either:

* translating calls from one API to another (generally the OS API). The OS API for consoles is not generally public, so there are generally very few tools that could make such a conversion
* embedding a runtime for the original language/technology into the executable along with the original version of the game as data for that runtime; this requires a runtime to be available for the target platform (the consoles), which is often not the case

Certainly it would be possible for you to port your game, but you will likely need to do more legwork than simply running it through a "converter." Unless such a path was already blazed for you, by other developers or the platform vendor, but that depends on the platform and your technology and the licensing agreements you have as a developer for the console.

The ".exe" file format in particular (Portable Executable) is fairly specific to Windows platforms.

---

The version of Downwell available on the Switch and the PlayStation platforms was likely re-built for the port to those platforms.
> 0 votes

---
Tags: javascript, html5, html-canvas, publishing, porting
---


# Question
Title: Calculating the intersection of a fast moving circle and a line
Inside of my game, I am in need of a way to test the collision between a line segment and a fast-moving circle. I would say I need a line v capsule collision however the problem is I need the collision point. None of the existing formulas I can find can do quite what I need. I have tried line x line intersection and just moving the lines by the radius of the capsule sort of work however then the collision point found around the edges is off. Additionally, I can't find a way to work back from the collision point to the point that the circle first collided at.

Above is sort of a picture of what I am hoping to achieve. The green capsule represents the circle's path.

So really the problem here is finding that collision point because a yes or no answer is trivial here. There are formulas for ray capsule or box capsule however none of them will get me this collision point.

Does anyone have any ideas on how I can figure this out?

# Answer
I assume that the black line (in the end: repeat for each line) is given as $$a+sb, \quad s \in I,$$ (where \\$a\\$ and \\$b\\$ are vectors denoting starting point and direction and \\$I\subset\mathbb{R}\\$ is an interval, probably \\$\[0,\infty)\\$ for the first of your lines and \\$(-\infty,\infty)\\$ for the second) and that the green path (more precisely: the path of the centre of the circle) is similarly given as $$c+td, \quad t\in J,$$ (with given vectors \\$c\\$,\\$d\\$ and interval \\$J=\[0,?\]\\$).

Then the point you are searching for should be described by $$|a+sb-(c+td)|^2=R^2 \qquad (\star)$$ (with \\$|.|\\$ denoting Euclidean distance and \\$R\\$ being the radius of the circle).

Up to now, this is one equation for two unknowns (\\$s\\$ and \\$t\\$). You want that \\$t\\$ is as small as possible and then want to know \\$s\\$. Consider \\$t\\$ as given and (\\$\star\\$) as quadratic equation in \\$s\\$. Then you can compute the discriminant of this quadratic equation, which will tell you how many solutions the quadratic equation has. As the discriminant is an expression depending on \\$t\\$ (and known constants), you can compute the smallest value of \\$t\\$ (\\$\in J\\$) for which (\\$\star\\$) has a solution (if such \\$t\\$ exists). With this value of \\$t\\$ solve (\\$\star\\$) for \\$s\\$. If \\$s\in I\\$, then \\$a+sb\\$ is the point you were searching for.

If \\$s\not\in I\\$, then (probably) the endpoint of \\$I\\$ is the only possible collision point, and checking the path of the circle(-midpoint, i.e. the line \\$c+td, t\in J\\$) for intersection with a circle with radius \\$R\\$ around that endpoint should tell you if a collision occurs there.
> 1 votes

# Answer
Why do you need the collision point of the circle at all? Couldn't you simply calculate a circle-circle collision with your red circle and the end point of your line?

```
if (dx * dx + dy * dy <= r1 * r1 + r2 * r2) {
  // Collision detected
}

```

Or maybe a look on this stackoverflow post will help: https://stackoverflow.com/questions/1736734/circle-circle-collision

Darth Moon
> 0 votes

---
Tags: collision-detection, physics, mathematics
---