# Question
Title: How to add undulation to a constraint-based chain?
I have a constraint-based chain composed of segments where each of the terminal segments has a fixed position.

My constraints are set up as follows:

```
var segments = [segment0, segment1, segment2, segment3, segment4, segment5, segment6]

# terminal segments follow head and anchor
segments[0].global_position = head.global_position
segments[segments.size() - 1].global_position = anchor.global_position

for x in range(4): # iterate 4 times

    for i in segments.size() - 1:
        var desired_distance = 8

        var current_segment = segments[i]
        var prev_segment_position = current_segment.global_position if i == 0 or i == segments.size() - 1 else segments[i - 1].global_position
        var next_segment_position = current_segment.global_position if i == 0 or i == segments.size() - 1 else segments[i + 1].global_position

        # get vector from previous to next and find midpoint
        var prev_to_next = next_segment_position - prev_segment_position
        var midpoint = prev_segment_position + prev_to_next.normalized() * prev_to_next.length() * 1/2

        # move current segment to midpoint
        var vec_to_midpoint = midpoint - current_segment.global_position
        current_segment.global_position += vec_to_midpoint

```

My question is: **How can I implement random undulation in this chain?**

In other words, I want the intermediate segments to move smoothly in a random wave pattern, while the terminal segments remain fixed to their positions.

Ideally, I'd set it up with some parameters than I could adjust to control the speed and volatility of the undulation.

I am working in Godot 3.1, but would like an engine-neutral explanation of the technique.

# Answer
Take a look at this function, it produces waves and maintains edges at zero:

https://www.desmos.com/calculator/aloi3ydowg

I guess you can position your elements by evaluating it accordingly.
> 2 votes

---
Tags: physics, movement, godot, rope-physics
---


title: Normal Matrix in plain English

text:
# Question
Title: Normal Matrix in plain English
I'm into shader language with Webgl and GLSL. I've seen some tutorial about normal matrix and I don't really understand it. I mean, I think I'm ok with the math such as:

```
modelViewMatrix = mat4.multiply(camera.view, modelMatrix);
inverseModelViewMatrix = mat4.invert(this.modelViewMatrix);
normalMatrix = mat3.fromMat4(inverseModelViewMatrix);
normalMatrix = mat3.transpose(this.normalMatrix);

```

But why do I need it? Where can I find a case where I can see the difference between using it and not using it? Ot when do I don't need it?

# Answer
> 4 votes
You need to use a different matrix to transform your normal vectors when your model's transformation might include non-uniform scale.

When we stretch a shape along, say, just the y axis, the y coordinate of all of the vertices gets exaggerated, making the object taller.

This doesn't just elongate the model - it also changes the orientation of the faces. Faces that run diagonal to the stretched axis end up tilting further away from that axis. As the model gets taller vertically, its normals start to point out more horizontally.

(Diagram from this article explaining how the inverse transpose matrix is used for transforming normals. Notice how as the model gets taller, the normal gets flatter.)

So this gives us a conundrum: the y coordinate of the vertices needs to get bigger, but the y coordinate of the *normals* needs to get *smaller*.

If we neglect this detail and just use the same model matrix for transforming both the vertices and the normals, the shading we get will be subtly wrong. Things like specular highlights will bunch up on the skinny poles of the object, instead of spreading across its elongated sides.

The inverse transpose of the model view matrix - what you've called the Normal matrix here - computes exactly the transformation we need to adjust the normals correctly. By inverting it, we "undo" the scaling factors and the rotation. By transposing it, we "undo" the undone rotation (the inverse of a rotation matrix is its transpose), getting us back to the rotation we started with, but still with the scaling factors inverted as desired.

---
Tags: shaders, glsl, matrix, normals
---


# Question
Title: Help with Google Sign In services with Libgdx
Im looking for some help on implementing Google Play sign in. Ive got the interface part figured out, but the last time I did this, google had a gamehelper utility and now it doesnt and having trouble figuring out how to implement the sign in, so after they sign in the first time it auto signs in when the app starts. Also cant seem to think of how ot send the info back to update the display with their new info...Heres what I got:

Main Game uses an interface and calls the sign in function on button click:

```
TextButton profile = new TextButton("Login",skin, "default");
        profile.addListener(new ClickListener(){
            @Override
            public void clicked(InputEvent event, float x, float y) {
                game.playServices.signIn();
            }
        });

```

Then taking the code from one of the examples from the google source this is my android launcher:

```
//Client used to sign in with Google APIs
   private GoogleSignInClient mGoogleSignInClient;

   //request codes we use when invoking an external activity
   private static final int RC_SIGN_IN = 9001;

   //Client variables
   private PlayersClient mPlayersClient;

@Override
   protected void onResume() {
      super.onResume();
      Log.d(TAG, "onResume()");

      // Since the state of the signed in user can change when the activity is not active
      // it is recommended to try and sign in silently from when the app resumes.
      signInSilently();
   }

   @Override
   public void signIn() {
      startSignInIntent();
   }

   @Override
   public void signOut() {
      Log.d(TAG, "signOut()");

      if (!isSignedIn()) {
         Log.w(TAG, "signOut() called, but was not signed in!");
         return;
      }

      mGoogleSignInClient.signOut().addOnCompleteListener(this,
            new OnCompleteListener<Void>() {
               @Override
               public void onComplete(@NonNull Task<Void> task) {
                  boolean successful = task.isSuccessful();
                  Log.d(TAG, "signOut(): " + (successful ? "success" : "failed"));

                  onDisconnected();
               }
            });
   }

@Override
   public boolean isSignedIn() {
      return GoogleSignIn.getLastSignedInAccount(this) != null;
   }

private void signInSilently(){
      Log.d(TAG, "signInSilently()");

      mGoogleSignInClient.silentSignIn().addOnCompleteListener(this,
            new OnCompleteListener<GoogleSignInAccount>() {
               @Override
               public void onComplete(@NonNull Task<GoogleSignInAccount> task) {
                  if (task.isSuccessful()) {
                     Log.d(TAG, "signInSilently(): success");

                     onConnected(task.getResult());
                  } else {
                     Log.d(TAG, "signInSilently(): failure", task.getException());
                     onDisconnected();
                  }
               }
            });
   }

   private void startSignInIntent() {
      startActivityForResult(mGoogleSignInClient.getSignInIntent(), RC_SIGN_IN);
   }

   @Override
   protected void onActivityResult(int requestCode, int resultCode, Intent data) {
      super.onActivityResult(requestCode, resultCode, data);
      if (requestCode == RC_SIGN_IN) {
         Task<GoogleSignInAccount> task =
               GoogleSignIn.getSignedInAccountFromIntent(data);

         try {
            GoogleSignInAccount account = task.getResult(ApiException.class);
            onConnected(account);
         } catch (ApiException apiException) {
            String message = apiException.getMessage();
            if (message == null || message.isEmpty()) {
               message = getString(R.string.signin_other_error);
            }

            onDisconnected();

            new AlertDialog.Builder(this)
                  .setMessage(message)
                  .setNeutralButton(android.R.string.ok, null)
                  .show();
         }
      }
   }

   private void onDisconnected() {
      Log.d(TAG, "onDisconnected()");

      mPlayersClient = null;
      // Show sign-in button on main menu

   }

   private void onConnected(GoogleSignInAccount googleSignInAccount) {
      Log.d(TAG, "onConnected(): connected to Google APIs");

      GamesClient gamesClient = Games.getGamesClient(AndroidLauncher.this, googleSignInAccount);
      gamesClient.setGravityForPopups(Gravity.TOP | Gravity.CENTER_HORIZONTAL);
      gamesClient.setViewForPopups(((AndroidGraphics) Gdx.graphics).getView());

      mPlayersClient = Games.getPlayersClient(this, googleSignInAccount);

      // Show sign-out button on main menu

      // Set the greeting appropriately on main menu
      mPlayersClient.getCurrentPlayer()
            .addOnCompleteListener(new OnCompleteListener<Player>() {
               @Override
               public void onComplete(@NonNull Task<Player> task) {
                  String displayName;
                  if (task.isSuccessful()) {
                     displayName = task.getResult().getDisplayName();
                  } else {
                     Exception e = task.getException();
                     handleException(e, getString(R.string.players_exception));
                     displayName = "???";
                  }
                  //mMainMenuFragment.setGreeting("Hello, " + displayName);
               }
            });

      // if we have accomplishments to push, push them
      //if (!mOutbox.isEmpty()) {
      //   pushAccomplishments();
      //   Toast.makeText(this, getString(R.string.your_progress_will_be_uploaded),
      //         Toast.LENGTH_LONG).show();
      //}

      //loadAndPrintEvents();

   }

   private void handleException(Exception e, String details) {
      int status = 0;

      if (e instanceof ApiException) {
         ApiException apiException = (ApiException) e;
         status = apiException.getStatusCode();
      }

      String message = getString(R.string.status_exception_error, details, status, e);

      new AlertDialog.Builder(AndroidLauncher.this)
            .setMessage(message)
            .setNeutralButton(android.R.string.ok, null)
            .show();
   }

```

I think it logs in as I get the log output of success

> D/RoboSmash: signInSilently(): success D/RoboSmash: onConnected(): connected to Google APIs

But it just flashes like it is going to another activity real quick and then comes back. Doesnt show the login or the little alert at the top like other games

# Answer
After the player successfully logs in, you can use the account to get the Games client and then set the view the popups appear on.

```
gamesClient = Games.getGamesClient(this, signedInAccount);
gamesClient.setViewForPopups(findViewById(android.R.id.content));
gamesClient.setGravityForPopups(Gravity.TOP | Gravity.CENTER_HORIZONTAL);

```
> 0 votes

---
Tags: libgdx, google-play-services
---


title: Questions about texture compression

text:
# Question
Title: Questions about texture compression
So when I choose the texture in the Inspector window I see three tabs: Default, Standalones & Android. I can choose some variants of how to compress this texture, but:

* My texture is a png (so it's RGBA). When I click the Default-\>Format I can see stuff like **Alpha 8, R 8, RGB 24** bit. So if I choose **R8**, for example, does that mean that my **GBA** channels will be thrown away?
* What is the **Max Size**? My texture is **600x375.** If I choose **512** will it clip my texture to **512x375** or what? And why it is called ***Max*** Size if I am working with a single texture right now?
* If I choose Default-\>Format to **Automatic** and **does not do any override on any specific platform** will Unity choose default texture compression formats for a specific platform using this table?

# Answer
This info can all be found in the manual
> 2 votes

---
Tags: unity
---


# Question
Title: Ideal 3D platformer controls for Keyboard + Mouse
I am developing a 3D platformer, and I know that controller is optimal for the precise movement, but I don't feel players should have to buy a controller just to experience a 3D platformer that is available for PC.

I get that WASD to move and SPACEBAR to jump is all good(and SHIFT to crouch), but I'm a little lost for the rest. I was thinking JKL could do some stuff, but then that ruins the point of a mouse, so maybe one set of controls for Keyboard + Mouse, and another for keyboard alone?

Here are my current controls for controller:

**Potential Ideas:**

Left Stick/WASD - move(obviously)

Right Stick/arrow keys/mouse(maybe + right click?) - camera

A(gamepad)/SPACE(maybe 'j' as well?) - Jump

Triggers/SHIFT - crouch

(No need to worry about start + select)

**Ones I'm stuck on(all of these are gamepad)**

Right Stick down - first person view

B - Attack

X - Dive

Y - Use power-up

Bumpers - Snap Camera behind

D-Pad Up/Down - zoom camera

D-Pad Left-Right - snap camera 45 degrees to left/right

I tried looking at other examples(e.g. A hat in time), but those games have a much different move set than mine, and wouldn't quite work.

# Answer
> 1 votes
As the comments suggest, taking an American keyboard mapping for granted is a problem;so, you ideally want to have a configurable keyset, but American mappings are domanate enough to make since for default settings.

First things first: FPS almost always map to the mouse in place of the right analogue. This actually makes the game more user friendly than a controller for most PC gamers. Most of these controls you are unsure about normally map to the mouse:

left-click - attack

right-click - use power-up (special attack)

Scroll-wheel - zoom

Scroll-wheel-click - Snap Camera behind (I'm assuming this is to reset your view)

Dive, look left, and look right are less conventional. But, there are some general guidelines that can help mapping less conventional buttons intuitively:

Q,E,Z,X,C,shift,ctrl,alt: These are buttons you may use a lot, especially while moving. So theses are often used for things like strafing, crouching, sprinting, swapping weapons, etc.

R,T,F,G,V,B: These are your tier 2 buttons, things you may need to hit here and there in the midst of battle, but don't need to focus on like reload, pick-up weapons, etc.

Other keys are often used for out-of-battle stuff like M for mini-map, I for inventory, etc.

---
Tags: game-mechanics, platformer, mouse, keyboard, controllers
---


title: Online database

text:
# Question
Title: Online database
In a unity MOBILE game where a player needs to see all online other players added by each other. and once one gets offline, or their scores changed, their status gets updated, do I need a real time database? Can this be done with php & Api ?? How to check if there is any update in any player's status?? Thanks

# Answer
> 1 votes
*Can* this be done with php? Yes, it certainly can. You can perform arbitrary web requests from a Unity game with the class UnityWebRequest.

Will it fulfill your requirements? Maybe, maybe not. We don't know your requirements, so we can only guess.

In general, the communication model of a webservice is pull-only. The client (in your case the Unity game) makes a request, and the server answers. The server can not do push notificaitions. If the server wants to tell the client(s) something it wasn't asked for, like the fact that a new client connected, then there are two workarounds:

* Long-Polling: Have the client create a request and delay the answer until there is something to report.
* Hammering: Have the client request status updates from the server at regular intervals.

Neither option is ideal, because they take up considerable resources on the server. So if you want to support a large number of users on a small server and give them near-realtime updates, then you might want to implement your own network protocol using the transport layer API.

---

Do you need a "realtime database"? If you want to have highscores and user accounts, then using *some kind of* database is certainly a good idea. But "realtime" is a meaningless marketing buzzword when it comes to databases, which translates to "fast at certain kinds of queries". Again, we don't know your requirements. So we don't know if you need some obscure special product here or if a run-off-the-mill SQL database like mySQL or PostgreSQL will do. But my educated guess is that you will be fine with a regular database.

---
Tags: unity, databases
---


# Question
Title: Unity3D: Replicating SM64 turning movement into Unity
**Brief Summary:** I want to recreate Super Mario 64 turning movement into unity without the clunky movement I currently have. And I would also love how to implement the camera rotation system mentioned below.

**Troubles:** I get lost when thinking into movement algorithms for unity. Like my character won't respond to camera relative movement appropriately. I'll provide a link to a video I made comparing my current basic unity controls to Super Mario 64 if you wish to see the full comparison between the two. And in this video I also mention stuff I think I can do to replicate the things I want. Youtube Link to my comparison video

**In-Depth Explanation of the problems with my current movement:**

\[*TurnSpeed ~* **My Character** turn speed is actually decent. I can increase the value of it to mimic the instant snap turning Mario does when he has a input value of 0. Now when movement is being made, the characters simulate the smooth turning Mario does when given a value of 1 on horizontal input and 1 on vertical input (I usually clamp these values to make it more smooth for people on controllers). **Mario:** Also as a bonus, when Mario does make a instant snap turn; the camera slowly rotates itself behind the player again to give them the view of the direction they are heading. **Estimate Solution:** I would love to learn to how exactly make this but so far my guess is getting the direction the player is heading and use that information to rotate the camera using lerp to get it in the right position.\]

**My Code:** I will provide my code for my progress so far in two different fashions: A clean basic movement version on here and a separate code link to see it all.

**Full Code Links:** CharacterController BasicMovement, and Basic Camera Controls

```
public Transform T_Player;
private CharacterController CC_PlayerCC;
public float F_CamTurnSpeed;
public float F_CamDistance;
public float F_CamTilt;
public float F_CamTiltLowest;
public float F_CamTiltHighest;
public float F_DirectionItsHeading;
public float F_PlayerHeight;

void start()
{
  CC_PlayersCC = GetComponent<CharacterController>();
}

void update()
{
    Input();
    CalculateCamera();
    CalculateGround();
    Move();
    Gravity();
    Jump();

    CC_PlayersCC.Move(V3_Velocity * Time.deltaTime);
}

void Input()
{
  V2_Input = new Vector2(Input.GetAxis("Horizontal_Keyboard"), Input.GetAxis("Vertical_Keyboard"));

  V2_Input = Vector2.ClampMagnitude(V2_Input, 1);
}

void CalculateCamera()
{
    V3_CamForwardDirection = T_CameraObj.forward;
    V3_CamRightDirection = T_CameraObj.right;
    V3_CamForwardDirection.y = 0;
    V3_CamRightDirection.y = 0;
    V3_CamForwardDirection = V3_CamForwardDirection.normalized;
    V3_CamRightDirection = V3_CamRightDirection.normalized;
}

void CalculateGround()
{
    if (CC_PlayersCC.isGrounded)
    {
        B_PlayerIsGrounded = true;
    }
    else
    {
        B_PlayerIsGrounded = false;
    }
}

void Move()
{
    V3_IntendedDirection = V3_CamForwardDirection * V2_Input.y + V3_CamRightDirection * V2_Input.x;
    F_CurrentTurnSpeed = V3_Velocity.magnitude / 5;
    F_PlayerTurnSpeed = Mathf.Lerp(F_PlayerHighestTurnSpeed, F_PlayerLowestTurnSpeed, F_CurrentTurnSpeed);
    if (V2_Input.magnitude > 0)
    {
        Q_PlayerRotation = Quaternion.LookRotation(V3_IntendedDirection);

        transform.rotation = Quaternion.Lerp(transform.rotation, Q_PlayerRotation, F_PlayerTurnSpeed * Time.deltaTime);
    }

    V3_VelocityXZ = V3_Velocity;
    V3_VelocityXZ.y = 0;
    V3_VelocityXZ = Vector3.Lerp(V3_VelocityXZ, transform.forward * V2_Input.magnitude * F_PlayerSpeed, F_Accerlation * Time.deltaTime);
    V3_Velocity = new Vector3(V3_VelocityXZ.x, V3_Velocity.y, V3_VelocityXZ.z);
}

void Gravity()
{
    if (B_PlayerIsGrounded)
    {
        V3_Velocity.y = F_OnGroundGravity; //OnGround Gravity
    }
    else
    {
        V3_Velocity.y -= F_PlayerGravity * Time.deltaTime;
        V3_Velocity.y = Mathf.Clamp(V3_Velocity.y, -10, 10);
    }
}

void Jump()
{
    if (B_PlayerIsGrounded == true)
    {
        if (Input.GetButtonDown("Jump"))
        {
            V3_Velocity.y = F_PlayerJumpHeight;
        }
    }
}

void OnControllerColliderHit(ControllerColliderHit hit)
{
    F_CurrentAngle = Vector3.Angle(Vector3.up, hit.normal);
}

```

# Answer
> 1 votes
I'm working on a 3D platformer as well, and have studied SM64 a lot in the process of making, however, I'm not exactly replicating it, so I don't have the code on hand. However, I can tell you several things:

A: Mario moves forward based on the direction he is facing, and if you turn left on the movement stick while going forward, he will quickly, but noticeably, be in a rotation state, resulting in a curve to start fully moving left and not forward. You're going to use `transform.forward` a lot in this case, especially for diving and long jumps. A little something like this:

`marioVelocity += transform.forward * acceleration;`

Note that `transform.forward` and `transform.right` are both Vector3s, not floats. Another thing to note is that when when you slam the stick in the opposite direction you are moving, Mario will enter a short slide animation to change direction, and if the player presses 'A' as this happens, it does a side ward somersault. To make this happen, you should check if the absolute value of the rotation that needs to happen is greater than 160 degrees(give or take).

Also, when Mario is completely standing still and you start moving, he will instantly snap into the rotation you want to go in with no transition. A few `if` statements can help with that. Here is a little code on how to do that:

```
Vector3 rotateDirection = (camera.forward * Input.GetAxis("Vertical")) + (camera.right * Input.GetAxis("Horizontal"));
if (marioVelocity.magnitude == 0f) {
Quaternion newRotation = Quaternion.LookRotation(new Vector3(rotateDirection.x, 0f, rotateDirection.z));
transform.rotation = Quaternion.Slerp(transform.rotation, newRotation, rotationSpeed * Time.deltaTime);//You're going to make rotationSpeed super low, like 0.0001(not sure if 0 works) or super high. I forget which
}

```

When Mario is in the air he doesn't rotate, but rather faces the direction that he was on the ground last. You're going to want something like this at the begging of your code `public Transform camera` so that you can get the rotation of your camera(or what the camera is pivoting off of) so that you can use `camera.right` and `camera.forward` in the air, and for getting rotation reference on the ground.

For wall jumps however, that is a little more complex. I recommend this video for more reference.

Diving, long jumping, and triple jumps are pretty simple, as diving you jump test `marioVelocity.magnitude` to see if he is fast enough to perform a dive when the player presses 'B' otherwise kick or punch, long jumps if the player is crouching, has some velocity, and presses 'A', and triple jumps you just have a float that goes down, and when Mario lands again he has a short time to press 'A' to perforom a double or triple jump.

---
Tags: unity, c#, rotation, movement, lerp
---


# Question
Title: Computing the UV coordinates of a 3D point that lies within a 3D triangle
From a triangular mesh I have a 3D triangle T represented by 3D vertexes ***v0, v1 and v2***. Each vertex has an associated UV coordinate into a common texture image, represented as ***uv0, uv1, uv2***.

Furthermore there is 3D point P, that is guaranteed to be within the triangle T *(coplanar to and within boundary of T)*.

My question is given point P, and triangle T, how does one go about calculating the ***UV coordinates of P***?

# Answer
Here is some C++ code from javidx9 from his olc3DEngine library. Hope this helps.

```
void TexturedTriangle(  int x1, int y1, float u1, float v1, float w1,
                            int x2, int y2, float u2, float v2, float w2,
                            int x3, int y3, float u3, float v3, float w3,
        olcSprite *tex)
    {
        if (y2 < y1)
        {
            swap(y1, y2);
            swap(x1, x2);
            swap(u1, u2);
            swap(v1, v2);
            swap(w1, w2);
        }

        if (y3 < y1)
        {
            swap(y1, y3);
            swap(x1, x3);
            swap(u1, u3);
            swap(v1, v3);
            swap(w1, w3);
        }

        if (y3 < y2)
        {
            swap(y2, y3);
            swap(x2, x3);
            swap(u2, u3);
            swap(v2, v3);
            swap(w2, w3);
        }

        int dy1 = y2 - y1;
        int dx1 = x2 - x1;
        float dv1 = v2 - v1;
        float du1 = u2 - u1;
        float dw1 = w2 - w1;

        int dy2 = y3 - y1;
        int dx2 = x3 - x1;
        float dv2 = v3 - v1;
        float du2 = u3 - u1;
        float dw2 = w3 - w1;

        float tex_u, tex_v, tex_w;

        float dax_step = 0, dbx_step = 0,
            du1_step = 0, dv1_step = 0,
            du2_step = 0, dv2_step = 0,
            dw1_step=0, dw2_step=0;

        if (dy1) dax_step = dx1 / (float)abs(dy1);
        if (dy2) dbx_step = dx2 / (float)abs(dy2);

        if (dy1) du1_step = du1 / (float)abs(dy1);
        if (dy1) dv1_step = dv1 / (float)abs(dy1);
        if (dy1) dw1_step = dw1 / (float)abs(dy1);

        if (dy2) du2_step = du2 / (float)abs(dy2);
        if (dy2) dv2_step = dv2 / (float)abs(dy2);
        if (dy2) dw2_step = dw2 / (float)abs(dy2);

        if (dy1)
        {
            for (int i = y1; i <= y2; i++)
            {
                int ax = x1 + (float)(i - y1) * dax_step;
                int bx = x1 + (float)(i - y1) * dbx_step;

                float tex_su = u1 + (float)(i - y1) * du1_step;
                float tex_sv = v1 + (float)(i - y1) * dv1_step;
                float tex_sw = w1 + (float)(i - y1) * dw1_step;

                float tex_eu = u1 + (float)(i - y1) * du2_step;
                float tex_ev = v1 + (float)(i - y1) * dv2_step;
                float tex_ew = w1 + (float)(i - y1) * dw2_step;

                if (ax > bx)
                {
                    swap(ax, bx);
                    swap(tex_su, tex_eu);
                    swap(tex_sv, tex_ev);
                    swap(tex_sw, tex_ew);
                }

                tex_u = tex_su;
                tex_v = tex_sv;
                tex_w = tex_sw;

                float tstep = 1.0f / ((float)(bx - ax));
                float t = 0.0f;

                for (int j = ax; j < bx; j++)
                {
                    tex_u = (1.0f - t) * tex_su + t * tex_eu;
                    tex_v = (1.0f - t) * tex_sv + t * tex_ev;
                    tex_w = (1.0f - t) * tex_sw + t * tex_ew;
                    if (tex_w > pDepthBuffer[i*ScreenWidth() + j])
                    {
                        Draw(j, i, tex->SampleGlyph(tex_u / tex_w, tex_v / tex_w), tex->SampleColour(tex_u / tex_w, tex_v / tex_w));
                        pDepthBuffer[i*ScreenWidth() + j] = tex_w;
                    }
                    t += tstep;
                }

            }
        }

        dy1 = y3 - y2;
        dx1 = x3 - x2;
        dv1 = v3 - v2;
        du1 = u3 - u2;
        dw1 = w3 - w2;

        if (dy1) dax_step = dx1 / (float)abs(dy1);
        if (dy2) dbx_step = dx2 / (float)abs(dy2);

        du1_step = 0, dv1_step = 0;
        if (dy1) du1_step = du1 / (float)abs(dy1);
        if (dy1) dv1_step = dv1 / (float)abs(dy1);
        if (dy1) dw1_step = dw1 / (float)abs(dy1);

        if (dy1)
        {
            for (int i = y2; i <= y3; i++)
            {
                int ax = x2 + (float)(i - y2) * dax_step;
                int bx = x1 + (float)(i - y1) * dbx_step;

                float tex_su = u2 + (float)(i - y2) * du1_step;
                float tex_sv = v2 + (float)(i - y2) * dv1_step;
                float tex_sw = w2 + (float)(i - y2) * dw1_step;

                float tex_eu = u1 + (float)(i - y1) * du2_step;
                float tex_ev = v1 + (float)(i - y1) * dv2_step;
                float tex_ew = w1 + (float)(i - y1) * dw2_step;

                if (ax > bx)
                {
                    swap(ax, bx);
                    swap(tex_su, tex_eu);
                    swap(tex_sv, tex_ev);
                    swap(tex_sw, tex_ew);
                }

                tex_u = tex_su;
                tex_v = tex_sv;
                tex_w = tex_sw;

                float tstep = 1.0f / ((float)(bx - ax));
                float t = 0.0f;

                for (int j = ax; j < bx; j++)
                {
                    tex_u = (1.0f - t) * tex_su + t * tex_eu;
                    tex_v = (1.0f - t) * tex_sv + t * tex_ev;
                    tex_w = (1.0f - t) * tex_sw + t * tex_ew;

                    if (tex_w > pDepthBuffer[i*ScreenWidth() + j])
                    {
                        Draw(j, i, tex->SampleGlyph(tex_u / tex_w, tex_v / tex_w), tex->SampleColour(tex_u / tex_w, tex_v / tex_w));
                        pDepthBuffer[i*ScreenWidth() + j] = tex_w;
                    }
                    t += tstep;
                }
            }
        }
    }

```
> -2 votes

---
Tags: 3d, mathematics, textures, uv-mapping
---


# Question
Title: how to get if a rotation/position has been completed?
I've done an if / else with the final position / rotation plus they never complete, how can I check this? stays like this

https://i.stack.imgur.com/3ADqz.gif

```
    if(head == false)
        cam.transform.position = Vector3.Lerp(cam.transform.position, PosicMin, Time.deltaTime * Speed);
    else {
        cam.transform.position = Vector3.Lerp(cam.transform.position, PosicMax, Time.deltaTime * Speed);
    }
    if(head == false)
        cam.transform.eulerAngles = Vector3.Lerp(cam.transform.rotation.eulerAngles, RotationMin, Time.deltaTime*Speed);
    else {
        cam.transform.eulerAngles = Vector3.Lerp(cam.transform.rotation.eulerAngles, RotationMax, Time.deltaTime*Speed);
    }

```

# Answer
You're using an exponential ease-out Lerp, which in real numbers never actually reaches completion. Each iteration, it moves a fraction of the remaining distance - always leaving a nonzero fraction left to go. Even in finite-precision floating point, it might not reach the destination value: at a certain point, the incremental displacement can round to less than the precision of the current value, resulting in no further change.

Fortunately, Unity's `==` comparison operator on `Vector3s` and `Quaternions` includes a tolerance range so it will return `true` when they're *almost* the same.

The other issue that's going to throw you off is you're trying to interpolate Euler angles. This is almost always a bad idea. The game engine does not store or use Euler angles internally - it computes them on demand from the quaternion internals. That means the output you save in one frame might not match the input you get in the next frame, due to inevitable discontinuities in computing an Euler angle triplet from an orientation. That can be the source of the perpetual jitter in your implementation. And even without that complication, Euler angles do not interpolate well in general:

* On the left: interpolating rotations with quaternions, we get smooth rotation along the shortest arc to the destination
* On the right: interpolating rotations with Euler angles results in excessive spinning/tumbling

(See this UnityAnswers post for more details \- unfortunately the original source of this animation is no longer available online nor in the Wayback machine, but you can play with an interactive app)

So, we can fix your code like so:

```
// Adjust for deltaTime correctly, given the non-linear nature of this use of Lerp.
float blend = 1.0f - Mathf.Pow(1.0f - Speed/30f, Time.deltaTime * 30f);

// Select destinations. This way we don't need to repeat our blend / check logic.
Vector3 destinationPosition = head ? PosicMax : PosicMin;
Quaternion destinationRotation = Quaternion.Euler(head ? RotationMax : RotationMin);

// Ease toward the selected destinations.
cam.transform.position = Vector3.Lerp(cam.transform.position, destinationPosition, blend);
cam.transform.rotation = Quaternion.Lerp(cam.transform.rotation, destinationRotation, blend);

// Check whether we're "close enough".
if(cam.transform.position == destinationPosition && cam.transform.rotation == destinationRotation) {
    // Arrived!
}

```

If you want to more precisely control the threshold of what gets to count as "close enough," you can use `Vector3.Distance` and `Quaternion.Angle` to compute how far we are from our destinations, and compare those against custom thresholds.
> 1 votes

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


# Question
Title: Procedural terrain generation is very slow
I've been trying to create procedural generated 2d terrain (similar to a game like Terraria) using Simplex noise. I was able to get the noise function working, and I set up a grid of 16 by 16 tiles that uses the noise to generate the height of the terrain. The problem is that the grid generation is rather slow. I often need to wait 5 - 10 seconds for a somewhat small grid to generate.

My code looks like this:

```
var level; // height of the terrain
generate_simplex_octaves2D(__largestfeature, __persistance, seed); // generate octaves using __largestfeature

for (var gy = 0 ; gy < global.__gridheight ; gy++)
{
    for (var gx = 0 ; gx < global.__gridwidth ; gx++)
    {
        level = (global.__gridheight div 2) + (100*get_noise2D(gx/100, gy/100, __octaves, __frequencys, __amplitudes)); // get noise value at point (gx/100, gy/100)
        if (gy > level) // if below level
        {
            global.__testgrid[# gx,gy] = TILE_FULL; // set grid position to a full tile
        } else global.__testgrid[# gx,gy] = VOID; // set grid position to an empty tile

        if (global.__testgrid[# gx,gy] == TILE_FULL) tilemap_set(global.testmap, 1, gx, gy);
    }
}

```

This creates terrain that looks fine, it's just too slow. I want to be able to generate terrain in real-time to create an infinite landscape. After doing some research, I found that I could maybe use a compute shader to have the GPU help speed up the generation, but I am not sure how to implement a compute shader in my case. Would I calculate the noise in a shader, or generate a noise map using one? Or do something else to generate the terrain faster?

# Answer
> 2 votes
I can see 2 possible reasons of bad performance:

1. You have very big numbers in X and Y. Like 2000\*1000. In this way you must lower that. You can make bigger areas to generate (like 10\*10 squares instead of 1\*1). Or you can regenerate many possibilities for squares of 50\*50 and randomly select them.
2. Or it can be very hard function: `get_noise2D(gx/100, gy/100, __octaves, __frequencys, __amplitudes)`. You can use lighter version of this or just random generator.

# Answer
> 1 votes
I'm seeing `get_noise2D()` and `tilemap_set()` as potential problems here. You didn't write them (?), so you don't know what's happening inside them. The high likelihood is there are heap memory allocations (`new` operator) going in inside there and it's causing your system to really chug as the CPU pipeline stalls while it waits for those allocations to return from main memory.

What you really need to do here is write dummy versions of each of these functions (or replace them basically) without any logic inside, and see which of these causes the gen-time to shoot up. So try dummying one, then the other, and see which impacts duration. Hopefully, gutting the first function doesn't cause the remaining logic to crash, else you'll have to supply dummy outputs therefrom.

Your nested loop and conditionals therein are, in my experience, not enough to cause serious slowdowns, even though nesting loops and conditionals is generally something you want to keep to a bare minimum.

---
Tags: procedural-generation, game-maker, terrain, terrain-rendering
---


# Question
Title: How can I reward dungeon masters that take risks?
I am working on a MORPG project featuring essentially two major roles: adventurers and dungeon masters. **My concern is about balancing the two roles.**

For those who have heard of it, the principle is inspired from the French comics Dungeon. The business model of a dungeon, as stated in the comics, is the following: dungeon masters place treasures in heavily guarded dungeons, to lure in adventurers seeking fame and fortune. While some of them succeed, most die in the process, dropping valuable items which joins the pile of treasures of the dungeon, further attracting more adventurers. Dungeon master make a living by collecting the right amount from these drops to create new rooms, pay mercenaries, fetch new creatures, breed dragons and whatnot.

Adventurers are quite classic: they are combat oriented characters that can attack monsters or fellow players and earn XP, items and money in the process, gradually making them stronger.

Dungeon masters are trade oriented. Their difficulty is balancing budgets: treasures and dragons are expensive. Now, I already expect a sort of equilibrium among dungeon masters because dungeons that are either too hard or too easy are naturally penalized (low attempt rate or low kill rate, respectively). **DM vs DM balancing: check.**

Since PvP combat is enabled in dungeons, there is also a competition among adventurers pushing weak players to stick to easy dungeons that offer little reward to more advanced players. **Adventurers vs advanturers balancing: check.**

However there is one specific imbalance between the two roles that I am trying to solve: adventurers have a bias toward attempting dungeons above their league, because even if they die (dropping some items and respawning outside the dungeon), they will have gained some XP in the process. This is good because it rewards risk-takers. On the other hand, dungeon masters do not have any advantage of this kind: if an adventurer completes the dungeon and escapes with their share of the treasure, nothing is gained. This would be a pity if it lead dungeon master to be too cautious about their defenses, killing the probability of ever completing the dungeon. **Adventurer vs DM balancing: problem.**

Hence my question: what reward mechanism could I introduce that incitates dungeon masters to maintain a small but non-zero winning probability?

# Answer
This system might be more auto-balancing than you think.

Players in MMORPGs will always go to the dungeon which gives them the most reward per hour of playtime. So if a dungeon master creates a dungeon which has a very low completion rate, then players will avoid that dungeon and rather go to an easier one. Dungeon Masters will have to compete with each other to create the dungeon with the largest reward for the smallest risk in order to attract the most players. But on the other hand, they must not be too generous, or they will start to lose money because nobody dies in their dungeon.

This is quite similar to how the casino industry operates. If you would own a casino, then you would want players to lose as often as possible so you make more money. So do you only offer games which are almost impossible to win? No, because if your games are too difficult, then the players will go to a different casino where the house edge is smaller. So you have to find a compromise. The result is an equilibrium where all casinos in a city will offer games with about the same house edge.

All you need to do for this system to work is create transparency: Players need to be able to tell what rewards a dungeon offers, how many players attempted that dungeon, how many were successful and how long they took.

On the other hand, you also want to encourage DMs to create dungeons which are rewarding, not frustrating. So if you notice that DMs need to build killer-dungeons in order to make a profit, then you should abandon the idea that dungeon raiding is a zero-sum game between player and DM. Consider ways to also reward the DM for successful completions. Not as much as an unsuccessful one, but it should be possible to run at least a meager income from running an easy-mode dungeon. For example, you could reward the DM with a special resource for every monster slain in their dungeon. Or you could allow DMs to collect an entrance fee for their dungeon which is to be paid regardless of whether the run is successful or not.

I'm looking forward to building the most profitable dungeon ever in your game.
> 9 votes

# Answer
Philipp definitely brought several great insights that are worth considering.

One possible direct answer to your concern would be to disperse rewards at intervals according to a curve.

For example, if you collected the rewards from all of the failed attempts of the day, you could give the DM \\$\frac{1}{A(p-P)^2+B}\\$ of the reward and divide the remainder amongst the successful adventurers (where \\$p\\$ is the real proportion of successful runs, \\$P\\$ is some target proportion of successful runs, \\$A\\$ is a steepness factor, and \\$\frac{1}{B}\\$ is the maximal proportion of the total earnings the DM can claim.)

This makes a dungeon most profitable near the P success rate. I personally like the curve \\$\frac{1}{1000(p-.05)^2+2.5}\\$, forcing DMs to aim for 95% failure rate with a steep penalty for pushing it up to 100% and reserving a 60% of the total income for the adventurers while giving 40% to the DM.

One note: Any zero-sum system will cause macro problems with the economy of the game. If there isn't money being generated but it's being spent (DMs on dungeon maintenance and improvement and adventurers on gear), then the money will just run out. With that in mind, you could simply add a factor to the disbursement to produce slightly more money on each run.

All that said, there will likely be a lot of autobalancing as DMs compete with each other to attract adventurers.
> 5 votes

# Answer
I agree with transparency, but success rate is not a good metric. If you have a hard dungeon that the high level guys like to farm, then a mid-level might see a 60% success rate and go in only to get stomped.

Instead they should be shown based on challenge rating (CR). If a dungeon kills a lvl6, a lvl10, & a lvl11, but a lvl9 and a lvl17 beat it, then you average the levels of adventures who succeed/fail and the find the average of those two numbers. (6+10+11/3=9 average failed adventurer, 9+17/2=13 average successful adventurer, 9+13/2=11) So, the dungeon would receive a challenge rating of 11. This way adventures would always know about what they are getting into.

The problem with transparency is if you know what you are getting into, losing a raid will be rare; so, to balance this your CR (and loot quality) is not fixed.

To keep things interesting a dungeon can have whatever sum value of loot they want to invest into it, but perhaps they have to push their CR up higher to unlock better rare drops. This will create a push pull between wanting to get farmed and wanting to be hard. The more you get farmed, the more the CR drops. This means you'll lose access to rare drops that attract high level characters, but if you CR does go down from being farmed, that means that dungeon will look easier than it is, luring in some ambitious noobs that you loot when they die... which pushes your CR back up, and the cycle continues.
> 1 votes

# Answer
I agree with Phillip on the most points he brought up, except that i dont see it that simple to balance. Just like in the casino, there will be some people who try a game again and again, but as every one knows, in the end, the bank wins.

In a game, that does not work. Why would a player attempt to do a dungeon over and over, if he realises shortly after, that he lost more than he could ever get out of it. Especcially with other players, who can just take their most desired objects. Only if you can get items, that really boost your stats immensly, players will stick to a dungeon. Expensive Unique Items, that a dm should only have in his hardest dungeon.

One thing is, if a dungeon gets played often, but not defeated nearly as often, than that could mean, that you get slightly better equipment out of that dungeon. A dungeon with a lower completion rate would drop slightly less, even using the exacte same enemies, traps, rooms etc.

On the other hand, if a dm also had something else to gain from players except of money and petty equipment, that they drop on death, then DMs could have another reason to have easier dungeons adventures can grind for simple stuff. For example, if players slays enemies, these enemies have a chance to come back stronger like Elite Monster. The more Monsters die, the higher the chance to get one of those. That may DMs might want "weaker" dungeons with weaker Monster, to get those Elite Monsters.

That way, even by making a net gold loss with that dungeon, he gains a value out of it.

A third thing is, you should see it a bit more like Super Mario Maker, where you build cool levels to show off. These Levels can be hard or easy, but the more stylish a level, the more play it will see. A poorly designed dungeon will see less play than a good designed dungeon at an equivalent difficult level.
> 0 votes

# Answer
Here is one possible solution I am not entirely satisfied with.

Creatures found in dungeons could have their own XP system, gradually getting stronger as they defeat more adventurers. The XP system for both creatures and adventurers would need to reward risky combats.That is: the stronger your opponent relative to you, the higher the XP gain.

In that case, having a dragon in the treasure room is useless if no adventurer climb up there: the dragon is costly and if it has never levelled up, it will be defeated easily the one time a strong player shows up.

In that sense, the best interest of a dungeon master would that all rooms be explored by players as close as possible to the level of their creatures, which are also the most likely to defeat them.

As stated earlier, I am not entirely satisfied. I am afraid this would incitate DMs to place very strong creatures at the very beginning of the dungeon so that they XP quickly. Perhaps this can be healed by ramping the XP reward steeply enough.
> 0 votes

---
Tags: game-design, mmo, rpg, balance
---


# Question
Title: OpenGL Texture Zig-Zag Artifacts Over Time
I'm working on a deferred shading renderer in OpenGL, where I write all geometry output to Colour, Normal and Depth textures and then apply lighting effects later.

Everything seems fine except once every few weeks, constant zigzag-like patterns appear past a certain depth (below the player's knees in the screenshot below). These zigzag patterns are at the same screen coordinates regardless of my pitch and yaw in the game:

I'm not sure what information to provide to resolve this issue, as it seems to me like a GPU error. Each zigzag square is 16x16 pixels, which could be the warp size on my NVIDIA GTX 960. Restarting the program resolves the problem and it doesn't happen again for a few weeks.

My guess is that sections of the fragment shader are failing to write to multiple render targets as I see the same pattern on the Colour, Normal and Depth textures.

The blue colour you can see on the left side of the zigzag pattern is the water at the bottom of the map, which is rendered after the post-processing stage and does not have these artifacts.

Any help with this would be greatly appreciated.

# Answer
To me it actually looks and sounds like bad video memory or core issue. Sometimes video cards can start to corrupt their outputs as the silicon degrades. If other cards do not show this artifact, then consider a new video card.
> 2 votes

---
Tags: c#, opengl, shaders, fragment-shader, gpu
---


# Question
Title: (Unity) Proper way to save ScriptableObjects changed during play mode?
I was wondering what the "correct" way to save scriptable objects in Unity that are changed during Play mode. So far I have something that works:

```
    // changes
    PartyMember Lalala = PartyMemberDictionary.Find("Lalala");
    Lalala.HP += 17;
    print("Lalala's HP: " + Lalala.HP);
    // then saves
    AssetDatabase.Refresh();
    EditorUtility.SetDirty(Lalala);
    AssetDatabase.SaveAssets();

```

Note: Lalala is a direct reference to a PartyMember scriptable object in my Assets/Resources folder.

I'm still a little shaky on this approach, however. I got this directly from reading this question:

https://forum.unity3d.com/threads/scriptableobject-asset-problem-the-changes-wont-saved-to-disk.229664/

But the commentator did not explain what each of these three lines of code mean.

```
    AssetDatabase.Refresh();
    EditorUtility.SetDirty(Lalala);
    AssetDatabase.SaveAssets();

```

Can someone explain these to me? I'm not sure I understand them fully. I assume "dirty" indicates that data changed; please correct me if I'm wrong.

In this link

https://docs.unity3d.com/ScriptReference/AssetDatabase.SaveAssets.html

it asserts that SaveAssets() saves all unchanged asset changes to disk, so why do I need the other Refresh and SetDirty Functions?

In this link

http://answers.unity3d.com/questions/11531/why-doesnt-my-scriptableobject-save-using-a-custom.html

The OP says "as I found out after some trial and error AssetDatabase.SaveAssets doesn't actually save the asset as expected." ... so confused at this point. That leaves me hesitant to continue until I understand what's going on. Perhaps the Refresh and SetDirty cement the job?

Also, in this link

https://docs.unity3d.com/ScriptReference/EditorUtility.SetDirty.html

it mentioned that Undo.RecordObject is preferred. Based on your experiences, is this true? Is EditorUtility.SetDirty(); obsolete in this day and age already? I don't want to use it if I have to change my code in the future.

At the end of the day I simply want something that works.

# Answer
Actually, it's a known thing they warn you about in the Unity docs (somewhere) that if you drag a prefab or Asset file to a script and then at edit OR runtime you change the contents of that prefab/script without first instantiating it the changes are permanent.

Example: You create a prefab for "Boss" and give him a Health value of 500. If your code looks like this:

```
public MyEnemyClass BossPrefab;
void OnDamage(int value) {
    BossPrefab.Health -= value;
    if (BossPrefab.Health <= 0)
    { BossPrefab.Health = 0; Die(); }
}

```

The first time you fight the boss he will have 500 health. If he beats you and has only 23 health left then the next time you start the game and get to the boss he will start with 23 health. So if you ever beat the boss then every single time you get to him he will die immediately.

Basically what you are doing is changing the value that you set on the PREFAB itself and that persists forever. If you want the code to behave as intended you need to first Instantiate the prefab and then make changes to that instance.

With ScriptableObjects, on the other hand, since they are not intended to be instanced but were designed to just store data for you to use in game, you are not supposed to change their values at runtime at all. That is not what they were designed for. That is what prefabs were designed for.

So to answer your question of "How do you save the values set during runtime" the answer is simply: "You don't. As soon as you change the value in the game the values are already permanently saved". If you don't see this because you have the asset visible in the inspector while running, just click on anything else then click on the asset again and notice how the value in the inspector is now no longer what you set it to manually but what it ended up being while playing.

EDIT: For the longest time I didn't understand what the difference was between a ScriptableObject and a prefab since I used both just to store data for use in the game and never actually instantiated it. the answer I got whenever I asked was that prefabs appear in the hierarchy and have a Transform which it simply doesn't need... but none of that is true if you don't actually instantiate the prefab into your scene.

So, again, what is the difference between a ScriptableObject and a run of the mill prefab? Simply this:

1. You don't instantiate ScriptableObjects at runtime, you just use them directly (Same as you CAN do with prefabs)
2. By adding a property before the class name you can create a ScriptableObject from the Unity menu (with a prefab you would just select the prefab and hit Ctrl+D to duplicate it)

...and that is IT. So all and all ScriptableObjects are nothing really special and you can just use a prefab to do the same thing only prefabs can be instantiated (or not) and thus offer you more you can do with it.
> 1 votes

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


# Question
Title: What aspect of performance should I be optimizing my code towards? (asynchronous chunk modification)
***Preface*** I realized that the root of my question is a little simpler than all of the details below make it out to be. All other things being equal, what is the most important system aspect to optimize for in order to prevent performance impacts from showing up later? Should I be reducing the main thread load, reducing the overall CPU load across all threads, or reducing the game's memory footprint? It seems like a simple question, but I haven't seen it addressed anywhere.

**All the glorious specifics:**

I am creating a 2D top-down game with custom mesh tilemaps. I have a fixed size map, but I'm chunking anyways. I have an asynchronous worker thread that will generate a mesh data object that will be imported into the chunk:

```
public class MeshData
{
    public List<Vector3> verticies = new List<Vector3>();
    public List<int> triangles = new List<int>();
    public List<Vector2> uv = new List<Vector2>();
}

```

I can run my noise sampling and triangle creation in the worker thread and then import the mesh data via the main thread when the data is ready. This works for world generation, but I'm not sure what to do for on-the-fly updates.

Specifically, I need to change the Z coordinate of any mesh point at any time when the player raises/lowers the terrain. My first thought was to directly edit the `MeshFilter` from the worker thread, but Unity doesn't allow secondary threads to modify gameobjects. So, that leaves me with a few other options:

1. Save a copy of `MeshData` in each chunk and modify that in the worker thread. Re-import in the main thread when the work is done. (This consumes 208Mb overall if my map size doesn't change)
2. Re-generate the mesh triangles from the saved coordinate array. (burns unnecessary CPU cycles on secondary thread, but no additional memory usage).
3. Edit the mesh directly from the game thread. (Puts all the work on the main thread, probably a bad idea)
4. Implement coroutines (Still puts the work on the main thread, but more "gracefully" (source))
5. I need to re-write my chunk generation entirely, I obviously failed to learn elementary idea "X".

Since I am an embedded developer by day, I often find myself worrying about clock cycles and memory allocations, perhaps more than I need to. To be clear, I don't have a lag problem yet, I'm just doing my best to avoid creating one. From what I can see, lag is a common problem around here. (ex. 1, ex. 2, ex. 3) I am capable of doing any of the above (or something else I missed), I just don't know which is the most viable solution. Any expert opinions would be gladly appreciated.

**Excerpt from my chunk generator**

```
public class ChunkGenerator : MonoBehaviour
{
    private MeshFilter filter;

    // Can be called in async thread.
    public void GenerateHeightMap(Vector2Int chunkPos, Vector2Int chunkSize, Vector2Int worldSize, WorldPoint[,] grid)
    {
        // Set the real coordinates for this grid point and calculate the height
    }

    // Can be called in async thread.
    public void CreateChunk(Vector2Int chunkPos, Vector2Int chunkSize, WorldPoint[,] grid)
    {
        MeshData mesh = new MeshData();
        // Some for loops here to iterate over the cells.
                MeshUtilities.CreateCell(mesh, cellPoints);
        this.meshData = mesh;
    }

    // Called by main thread, interacts with a filter.
    public void LoadMeshData()
    {
        filter = GetComponent<MeshFilter>();
        Mesh mesh = new Mesh()
        {
            vertices = this.meshData.verticies.ToArray(),
            uv = this.meshData.uv.ToArray(),
            triangles = this.meshData.triangles.ToArray()
        };
        filter.mesh = mesh;
        filter.mesh.RecalculateNormals(); // Enables shadows.
    }

```

**Excerpt from my world generator thread**

```
private void ChunkManagementThread()
{
    // While loop allows us to bail if the main thread dies (game exit).
    while (chunkGenerationThreadRunning)
    {
        for (int x = 0; x < chunkArraySize; x++) for (int y = 0; y < chunkArraySize; y++)
        {
            ChunkGenerator chunk = this.chunks[x,y];

            lock(chunk)
            {
                switch (chunk.state)
                {
                    case ChunkState.GenerateHeightmap:
                        // Pass 1: Set the height for all points.
                        this.chunks[x, y].GenerateHeightMap(new Vector2Int(x,y),this.realChunkSize,this.realWorldSize,this.grid);
                    break;
                    case ChunkState.CreateChunk:
                        this.chunks[x, y].CreateChunk(new Vector2Int(x, y), this.realChunkSize, this.grid);
                        // Pass 3: Create triangles.
                    break;
                    case ChunkState.ActivateMesh:
                        // Finally, render the image. (Actually from main thread, not shown)
                        this.chunks[x, y].LoadMeshData(this.chunks[x, y].GetMesh());
                    break;
                    case ChunkState.UpdatesPending:
                        // Need to process updates here.
                    break;
                        // Etc...

```

(Note: I did cut my code down a lot since my problem isn't with syntax. It probably won't run as shown; I can post the full version if needed)

# Answer
> 2 votes
As your initial question is based on just one factor - "Where does my bottleneck lie?" - only you can get at the answers, by profiling your code (now and later as features develop and bottlenecks change). Sounds to me as if you want us to project against future changes, which we cannot possibly do, given how your requirements set may change in future.

Even if we said right now that "reducing the overall CPU load across all threads" was the answer, some other subsystem may be implemented by you later that changes the dynamic and actually requires more main thread time, in which case you'd have been better off with "reducing the main thread load". That is how these things inevitably work. You cannot be certain until you get to point B. You can *project*; and if that's hard for you to do, it's impossible for us, knowing nothing about where your spec is at or is headed, especially (given your questions) your desired threading model.

Heavy optimisation makes code brittle and difficult to change; simpler, earlier "root" solutions to the problem (what we often call the naive solutions) are a better place to start (re)factoring from.

Either stick with simpler, more refactorable optimisations for now, or provide multiple optimisation approaches and maintain unit tests for these, by developing them against a single interface, thus requiring only one set of tests for all variations. By testing them against one another, you can find answers to your questions, but it will take work, and time.

One problem here is that method calls themselves have overheads, so interfaces may cost you; but this is the price you'd have to pay for higher flexibility.

---
Tags: unity, c#, procedural-generation, resource-management, lag
---


# Question
Title: Rigidbody & Ray alternative or optimization
I am creating an **AI** that moves around to certain points, but should interact with ais or objects seen.

### The **ai** should find other **ai** to comunicate or look for **objects** on the ground.

It works with all those solutions with a low number. But when I have +300 ais the fps drops a lot, caused by Physics2D.FixedUpdate or something related with physics.

### How would you deal with this?

I have tried those solutions:

---

## **Solution 1**

**AI:**

* Rigidbody2D Kinematic
* SphereCollider2D Trigger
* OnTriggerEnter & Exit Script.

**Objects**

* Rigidbody2D Kinematic
* SphereCollider2D Trigger

---

## **Solution 2**

**AI:**

* Rigidbody2D Kinematic
* SphereCollider2D Trigger
* OnTriggerStay Script executed each 120 frames & a Coroutine to simulate OnTriggerExit.

**Objects**

* Rigidbody2D Kinematic
* SphereCollider2D Trigger

---

## **Solution 3**

**AI:**

* No RigidBody
* SphereCollider2D Trigger
* Cone of Rays executed each 2 second to detect colliders at certain layers.

**Objects**

* No RigidBody
* SphereCollider2D Trigger

---

**EDIT**

In solution 1 and 2, all AI have an "eyes" children GameObject with a TriggerCircleCollider2D and no RigidBody2D, to detect near AIs and GroundObjects.

# Answer
> 0 votes
**The best solution was solution 3.**

With the solutions 1 & 2 with RigidBodies, Physics2D Update Profiler **was around 80%** usage, **now it is at 12%**. I need to remove more RigidBodies from the scene.

**I created a RayCasting & Layer system with Coroutines with the best practices, for example using Arrays instead of Lists.**

Now I can have 1000 agents at 50fps.

Related to **@ThePumkinMelon** recomendation, **ECS**, those links helped me:

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


# Question
Title: How to render animated models via instanced rendering?
I have an animated model with a maximum of 60 bones. That means i have an array of 60 matrices when i want to render the model. Previously i would just create a uniform with the fixed size (mat4\[60\]), but now i want to render the model via instanced rendering, which means i need to write 60 matrices per instance into the VAO of the model.

This would mean i have to create 240 vertex attributes each containing 4 floats because thats the maximum number of floats an attribute can have. This is obviously a ridiculous solution, besides the fact that i think it exceeds the maximum number of attributes a VAO can have.

So how do i render animated models via instance rendering?

# Answer
**The solution is to not use a vertex attribute to store this data**.

As you've correctly observed, this is going to overflow the maximum number of attributes, and is indeed ridiculous.

Instead you should use some other form of object - e.g. a UBO or SSBO - to store it, and then use the value of gl\_InstanceID to index into that storage in your shader.

So for example you might use something like:

```
mat4 bones[600];

```

Which would give you sifficient storage for 10 instances. Then using `gl_InstanceID * 60 + bonenumber` to retrieve the correct bone matrix for each instance.

This of course is going to put an upper limit on the number of instances you can draw, but that's OK.
> 2 votes

---
Tags: opengl, glsl
---


# Question
Title: How can I implement the traffic(+drawing) functionality in the game?
I am a beginner game developer. Games such as "Cities: Skyline", "Simcity", "Citybounds", and "Traffic lanes 3" directly build roads and show simulations of cars moving over them. I have no knowledge to make these things. I can use Unity, construct2. How can I express things like roads, lanes, intersections, snapping, traffic simulations, path finding, driver AI, traffic lights, even wheels on the road?

Road drawing

Traffic simulating

# Answer
The navigation part is probably the easieast. Every point where two or more roads connect should become a node in a graph, the roads connecting them are the edges. A simple pathfinding algorithm can navigate a car from one point to another.

Lanes are just a modification on this. Make the same road represent multiple edges, one per lane. If the car needs to be in a certain lane to e.g. turn left, it will use the corresponding edge.

Drawing these roads is very complicated, especially when they start intersecting. The roads can be done using bezier curves if they need to bend, but the intersections have to be procedurally generated somehow.

If you're just starting game developement, especially if you have no programming knowledge, I'd start with something smaller. There's a reason these games aren't produced by indies too often.
> 1 votes

---
Tags: unity
---


# Question
Title: Raymarching signed distance function resulting in holes on surface - step size required?
I've been learning about raymarching and signed distance functions, and I implemented a raymarching fragment shader in Unity. It works fine for geometric shapes such as cubes and spheres, but when I started trying to build terrains with it I started running into issues.

I think I've narrowed down the problem to my signed distance function and not the raymarching implementation. To simplify things I've reproduced the problem using a sin wave, which seems to have the same result I'm seeing with noise functions.

The first issue is I'm getting strange holes in the surface - at least I think they are holes. At many points it's rendering inside the volume instead of the surface:

Here is a modified color output where I color each pixel based on the signed distance value.

`color = 0 - signedDistance`

* Red: surface not hit
* Black: At or very near surface
* White: Inside the volume

I would expect to not see any white at all in this image. The results should be either black (surface found) or red (surface not found, ray marching loop stopped).

The other problem, which I believe is closely related to the first, is I'm getting inaccurate surface normal values at relatively large distances resulting in a wavy appearance. However, I'm fairly certain this is caused by the normal calculation using the same signed distance function which is returning inside the volume (which would provide incorrect, probably inverted, distance results), so I'm focusing on that issue first.

I've reproduced the issue I'm having on Shadertoy. While it's not exactly the same code, the basic algorithm is the same on both the GLSL Shadertoy sample and my Unity HLSL shader.

First, here is the most basic signed distance function I've used successfully. It just renders a flat plane at y=0:

```
float map(float3 position) {
    float sdist = position.y;
    return sdist;
}

```

Now I add a sine wave on top of this flat plane:

```
float map(float3 position) {
    float sdist = position.y + sin(x);
    return sdist;
}

```

What I expect is to see the plane move up and down as a sine wave along the x axis. I do see that, but I also see those odd holes (in the images above) through the surface. It's as if the ray marching portion goes right through past the surface and then stops inside of the volume.

I can somewhat mitigate this by stepping in much smaller steps than the calculated signed distance. Here is an example with the step size at 0.05:

But this decreases performance since each raycast / marching step now traverses much smaller distances.

Is stepping shorter distance than the calculated distance function result the way to fix this?

Just for completeness, here is a stripped down version of the ray marching function:

```
// March forward multiplier
float stepSize = 1.0;
// maximum number of times to march forward
float maxRayCasts = 128;
// The minimum distance considered to be the surface
float precis = 0.01;

vec3 castRay( in vec3 ro, in vec3 rd ) {
    float tmin = 0.01;
    float tmax = 600.0;

    vec2 res;

    float t = tmin;
    float m = -1.0;
    for( int i=0; i<maxRayCasts; i++ ) {
        res = map( ro+rd*t );
        if( res.x<precis || t>tmax ) break;
        t += res.x*stepSize;
        m = res.y;
    }

    if( t>tmax ) m=-1.0;
    return vec3( t, m, res.x );
}

```

# Answer
> 2 votes
After messing with the Shadertoy link (thank you for that, by the way), I have discovered that most of your problem comes from the line `if( res.x<precis || t>tmax ) break;`. You need to replace `res.x` with `abs(res.x)`. This way, if the ray overshoots, when the signed distance function returns a negative value, the ray extends negatively, or to put it another way, retracts.

# Answer
> 0 votes
Alex F's solution is correct; I'd like to just explain why it's necessary in this case.

The way you're raymarching assumes that `map` is a true distance function, or at least a conservative one: because you try to step forward by the distance returned by `map` in each iteration, that return value must always be less than or equal to the true distance to your surface.

But your addition of sine breaks that rule.

Let's look at the curve `map(p) == 1.0` (in blue), the level set of points your map function claims are 1.0 units from the surface (the level set `map(p) == 0.0` in black):

Because `map(p)` increases straight vertically, not perpendicular to the surface, it gives the correct distance at the peaks, but massively over-estimates the distance inside the troughs.

This means that a ray heading close to perpendicularly into the side of a trough will be given an estimate larger than its true distance to the surface, and on the next step it will tunnel through.

I'm not aware of an analytical function for computing the distance to a sine wave, so correcting the estimate itself may not be viable here.

Instead, you can modify your raymarcher to understand that it might sometimes get a bad estimate and overshoot. It can detect this if it lands in a region where `map(p)` returns a negative value, corresponding to a distance "inside" the shape. You can then backtrack based on this estimate. Your ray will then do something similar to a binary search in regions with inaccurate estimates, hopping between points on the near and far side of the surface, a little closer each time, until it zeroes-in on something close enough.

This is what Alex F's proposed modification accomplishes.

Note that for this to work, your step size needs to be small enough that you don't tunnel through the surface and out the other side in one step - otherwise your raymarcher won't see the negative value and detect the overshoot. When it does overshoot, it needs to move back again by less than its last step distance - otherwise it could oscillate endlessly or diverge away from the true intersection point.

Tuning your step size multiplier can help achieve this in trouble spots, though it does make your raymarching slower overall since even areas with well-behaved estimates will start taking more iterations.

---
Tags: glsl, hlsl, fragment-shader, signed-distance-field, raymarching
---


# Question
Title: How to disable MenuItem in play mode in Unity?
I created a function which snaps an object to pivot with a hotkey of **Shift + S**. When I play the game in which I run using **Shift** and move backwards using **S** I accidentally call the function. How can I have this MenuItem enabled only in Editor?

Here is the code in C#:

```
[MenuItem("GameObject/Snap/To pivot #s")] // snap to pivot
private static void SnapToPivot() {
    var selectedObjects = Selection.gameObjects;
    foreach (var obj in selectedObjects)
    {
        Undo.RecordObject(obj.transform, "Snap to pivot");
        obj.transform.position = SceneView.lastActiveSceneView.pivot;
    }
}

```

# Answer
Have you tried adding a guard clause to the top of your method?

```
if (Application.isPlaying)
    return;

```

This will halt execution of the shortcut command if the editor is in play mode.

A better solution might be to also check if the game window has focus, so you can still use the shortcut in the scene view while playing.
> 1 votes

---
Tags: unity, menu
---


title: OpenTK OpenGL wierd camera look

text:
# Question
Title: OpenTK OpenGL wierd camera look
I am trying to implement a simple camera mouse look.

```
if (Input.GetInstance().GetMouseKey(MouseButton.Middle))
{
    Vector2 d = Input.GetInstance().getMouseDelta() * 0.001f;
    camera.transform.AddRotation(new Vector3(-d.Y, d.X, 0));
}

```

Here is the camera matrix:

```
cameraMatrix = Matrix4.LookAt(myEntity.transform.Position, myEntity.transform.Position + myEntity.transform.GetForward(), myEntity.transform.GetUp());

```

I also tried to create camera matrix like this, but the results were the same:

```
Matrix4 t = Matrix4.CreateTranslation(myEntity.transform.Position);
Matrix4 r = myEntity.transform.RotationMatrix;
cameraMatrix = t * r;

```

Here is the rotation matrix of transform:

```
var x = Matrix4.CreateRotationX(rotation.X);
var y = Matrix4.CreateRotationY(rotation.Y);
var z = Matrix4.CreateRotationZ(rotation.Z);
rotationMatrix = x * y * z;

```

Add rotation of transform:

```
public void AddRotation(Vector3 rotation)
{
    if (rotation == Vector3.Zero) return;
    this.rotation += rotation;
    myEntity.ObserverOnRotationChanged();
}

```

Get forward method of transform:

```
public Vector3 GetForward()
{
    return new Vector3(RotationMatrix * new Vector4(0.0f,0.0f,1.0f,0.0f));
    //or just extract third column from matrix
}

```

Vertex shader:

```
#version 330

uniform mat4 transformMat;
uniform mat4 cameraMat;
uniform mat4 projectionMat;

layout (location = 0) in vec3 position;
layout (location = 1) in vec3 normal;
layout (location = 2) in vec2 uv;

void main(){
    gl_Position = projectionMat * cameraMat * transformMat * vec4(position, 1.0);
}

```

It rotates the camera around global x axis instead of local x when i look at triangle from the side. Thanks.

# Answer
> 0 votes
When creating rotation matrix of transform it should be z*y*x and not x*y*z.

```
var x = Matrix4.CreateRotationX(rotation.X);
var y = Matrix4.CreateRotationY(rotation.Y);
var z = Matrix4.CreateRotationZ(rotation.Z);
rotationMatrix = z * y * x;

```

---
Tags: c#, opengl, mathematics, opentk
---


# Question
Title: How can I prioritize the call order of decoupled scripts?
I have a player with many individual components that each handle a behavior such as jump, block, attack, duck, etc.. None of the scripts know about one another. Each listens for a specific input to fire. Some behaviors share the same input depending on the characters state such as ok the ground, in the air.

I'm running into issue where the wrong behavior will fire that has shared input (down+attack instead of down+attack being held down for x seconds).

I'm looking for advice on how to manage these behaviors and have more control over what can happen when.

I've tried resolving this issue by creating a method that will disable other behaviors temporarily while completing the action and I've changed the script execution order.

I thought about adding a discrete player state and restricting what behaviors are able to be performed at any given time but this increases the complexity quiet a bit.

# Answer
As Aybe suggests in the comments above, I'd recommend separating the concept of Input from the concept of Actions. You can do this in your own scripts, even if you're not ready to jump into the new input system.

To do this, you'd have one script that manages reading the player's input devices and determining what actions have been performed. This has several benefits:

* If one action should affect whether another can be performed (eg. taps & holds coexisting on the same button), you can coordinate the two in one place and ensure the correct one fires.
* Your input logic is centralized. If you add control mapping, or need to swap out a whole new input handler (eg. for a new platform with completely different input hardware), you have one well-defined place to make these changes, rather than sprinkling them through every script that uses input.

Then your individual behaviour scripts can subscribe to this input controller for the actions they care about. A side benefit you get with this is that your in-game effects are now decoupled from their triggers: you can re-use those same behaviour scripts for non-player initiated actions, like NPC abilities, or events in cutscenes - substituting an AI controller or cutscene script as the action provider.

It's up to you how much knowledge your input controller script has about the player's various abilities. It could explicitly know all the action types it needs to support and their relationships, and expose getters / events / handler slots to fire off the corresponding behaviours. Then you control which action blocks which with explicit logic inside this script. Or it could be a completely generic input-checker that accepts subscription requests asking it to watch a particular input, and maybe a priority level or spillover setting to control which subscriptions should fire first / block other subscribers. Then it's delegated to the subscribers to describe the input they want and its conditions.
> 1 votes

---
Tags: unity
---


title: LineRenderer on Mesh surface

text:
# Question
Title: LineRenderer on Mesh surface
**Goal:** Render distance lines between two points on the surface of a mesh-based primitive (i.e. sphere, cube, etc).

**Current Solution:** Iteratively traverse distance line between two end points and "reverse" raycast through this point somehow. *Since the distance line directly connects both vertices through the mesh, the according points on the mesh surface are required.*

```
Ray ray = new Ray();
RaycastHit raycastHit;
ray.origin = posOnDistanceLine;
ray.direction = raycastNormal.normalized;
// Reverse ray since we can't raycast from inside the mesh
ray.origin = ray.GetPoint(1);
ray.direction = -ray.direction;

```

Lines are then drawn using Unity's `LineRenderer` which is being populated with positions of vertices whenever a change in normals (to previous raycast) is identified.

**Issues:**

* Horrible performance (as 100 rays are cast whenever the end points move).
* Solution doesn't always work and produces unexpected, jagged lines / points.

**Question:** Is there a better approach to implement this?

# Answer
This is effectively a navmesh pathing problem.

First, you'll iterate over your mesh data (vertex positions and triangle indices) and build a set of adjacency information - so you can associate each triangle with its adjacent edges, and from there to its neighbouring triangles. I describe a version of this process in another answer.

Next, you can use a pathfinding algorithm like A\* to determine a path across the adjacency graph you've created, joining your initial triangle to your destination triangle. You can use a funnel algorithm to pull this path "taut," finding the crossing point along each edge that minimizes the length of the resulting path.

Lastly, you can walk over each segment of the resulting path, adding a point to your line renderer wherever it crosses a triangle edge, and summing the length of the segments you've built to determine the total measurement.
> 0 votes

---
Tags: unity, 3d, 3d-meshes, mesh
---


title: Handedness of 2D coordinate systems

text:
# Question
Title: Handedness of 2D coordinate systems
I know that there's always a big debate on the handedness of 3D coordinate systems, but I can't seem to find any information about the handedness of 2D coordinate systems.

Usually, the X axis points to the right, but the Y axis can point up (in the case of many game engines) or down (in the case of screen coordinates and in Godot). What are the standards for these?

* Which one of those is "left-handed" and which one is "right-handed"?
* Are rotations always clockwise? Counter-clockwise? From X to Y? From Y to X?

# Answer
> 5 votes
It entirely depends on what you want to do with it and both have reasons why they exist.

The one where the top left corner is the origin and the positive xes point away from them are based on the way the pixels are stored, while the oke where y points at the sky uses a more mathematical approach. 2D systems thus generally use the former, 3d (or at least rasterization based ones) use the latter.

As mentioned by DMGregory, there's no handedness to these, because that system depends on the three axes. This is because a 2d plane divides the space into two parts and there's no way to tell by default, which should "contain" the normal vector.

Since rotation relies on trigonometric functions, it's also coordinate system dependent whether it's a CW or CCW system. When the angle is 0°, the vector you get is \\$\vec v(cos(0°),sin(0°))=\vec v(1,0)\\$, and at 90° it's \\$\vec v(0,1)\\$. In the "top-left origin" system this is clockwise, while it's counter-clockwise in the more traditional coordinate system.

One thing I must add is that even though I use the term "traditional" when describing the coordinate system where y points up, there's nothing stopping you, even in vanilla mathematics, from using other conventions. This is why you need to draw the arrows at the end of the axes.

---
Tags: 2d, rotation, coordinates
---


# Question
Title: How can i set OnClick equal to UnityEvent
## The Problem

I'm making a dialogue system for a small 2d rpg. I Have a Dialogue class with two lists for pages and responses. The response class has a UnityEvent so i can use the ui in the inspector to set methods like a button. Then in a DialogueManager class i have a `Show()` method which makes a button for every response in the list from Dialogue. The problem is when i try to set the created button's `OnClick()` event to the UnityEvent in the response.

## The Question

So the question is how can i set the button's `OnClick()` to the methods in the UnityEvent from the response?

# Answer
Just make a method that invokes your event:

```
public class DialogueItem : MonoBehaviour {

   public UnityEvent response;

   public void FireResponses() {
       response.Invoke();
   }

   public void WireUpResponses(Button button) {
       button.onClick.AddListener(FireResponses);
   }
}

```
> 0 votes

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


# Question
Title: System.Net.Http.dll and Unity 2018.2.1, 2.2, 2.3 are conflicting, assembly reference keeps being deleted in VS 2017, any suggestions?
I'm looking for some suggestions on how to fix a strange bug i've been getting with System.net.http.dll.

For the record, builds work fine as i have the mcs.rsp file in the /Assets/ folder with "-r:System.Net.Http.dll" inside. The problem lies with Visual Studio and it's relation to Unity. I can add the reference to the dll by selecting "Analyzers" then hitting "Project" and Adding the dll found in:

C:\Program Files\Unity\Hub\Editor\2018.2.2f1\Editor\Data\MonoBleedingEdge\lib\mono\4.7.1-api\System.Net.Http.dll

But VS changes the reference instantly to:

C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework.NETFramework\v4.7.1\System.Net.Http.dll

Then after a short amount of time, the reference i made just gets automatically deleted.

I've tried clearing the VS Cache inside of AppData/Local/ as well as clearing everything but the Asset Folder in my unity project (including obj, library, .CSPROJ, .sln files etc.) But to no success.

Im using .NET 4.x in the project and it builds fine, its just that the VS reference keeps being deleted. so when it comes to "Attaching to Unity" i can't execute until i re-assign the "temporary" assembly reference.

I've tried updating VS, Reinstalling it as well as unity 2018.2.1 and Unity2018.2.2 to no success.

I'm all ears.

**UPDATE: Problem has been fixed in 2018.3**

# Answer
> 1 votes
Unity will override the .csproj files every time it recompiles the scripts. To fix this, you must include a script that will listen for the generation of the project files event and add the reference manually. This is just a quick and dirty example, you can add a proper XML parser to do the job. Add this script in an Editor folder.

```
using SyntaxTree.VisualStudio.Unity.Bridge;
using System;
using UnityEditor;

[InitializeOnLoad]
public class ReferenceRemovalProjectHook
{
    static ReferenceRemovalProjectHook()
    {
        const string itemGroup = "<ItemGroup>";
        const string systemNet = "<Reference Include=\"System.Net.Http\" />";

        ProjectFilesGenerator.ProjectFileGeneration += (name, content) =>
        {
            if (!content.Contains(systemNet) && content.Contains(itemGroup))
            {
                int a = content.IndexOf(itemGroup, StringComparison.OrdinalIgnoreCase);

                content = content.Insert(a + itemGroup.Length, "\n    " + systemNet);
            }

            return content;
        };
    }
}

```

---
Tags: unity, visual-studio, .net, dll, http
---


# Question
Title: Cant write/read to/from external storage with LibGDX
My `create` method looks like this:

```
@Override
public void create () {
    batch = new SpriteBatch();

    FileHandle file = Gdx.files.external("file.txt");
    file.writeString("My god, it's full of stars", false);
}

```

I allso included:

```
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

```

The Exception i get is this:

```
02-13 14:45:51.858 12439-12466/com.snowdevs.tweetiebirds E/AndroidRuntime: FATAL EXCEPTION: GLThread 1120
Process: com.snowdevs.tweetiebirds, PID: 12439
com.badlogic.gdx.utils.GdxRuntimeException: Error writing file: file.txt (External)
   at com.badlogic.gdx.files.FileHandle.writeString(FileHandle.java:353)
   at com.badlogic.gdx.files.FileHandle.writeString(FileHandle.java:339)
   at com.snowdevs.tweetiebirds.TweetieBirdsGame.create(TweetieBirdsGame.java:22)
   at com.badlogic.gdx.backends.android.AndroidGraphics.onSurfaceChanged(AndroidGraphics.java:254)
   at android.opengl.GLSurfaceView$GLThread.guardedRun(GLSurfaceView.java:1519)
   at android.opengl.GLSurfaceView$GLThread.run(GLSurfaceView.java:1240)
Caused by: com.badlogic.gdx.utils.GdxRuntimeException: Error writing file: file.txt (External)
   at com.badlogic.gdx.files.FileHandle.writer(FileHandle.java:330)
   at com.badlogic.gdx.files.FileHandle.writeString(FileHandle.java:350)
   at com.badlogic.gdx.files.FileHandle.writeString(FileHandle.java:339)
   at com.snowdevs.tweetiebirds.TweetieBirdsGame.create(TweetieBirdsGame.java:22)
   at com.badlogic.gdx.backends.android.AndroidGraphics.onSurfaceChanged(AndroidGraphics.java:254)
   at android.opengl.GLSurfaceView$GLThread.guardedRun(GLSurfaceView.java:1519)
   at android.opengl.GLSurfaceView$GLThread.run(GLSurfaceView.java:1240)
Caused by: java.io.FileNotFoundException: /storage/emulated/0/file.txt: open failed: EACCES (Permission denied)
   at libcore.io.IoBridge.open(IoBridge.java:452)
   at java.io.FileOutputStream.<init>(FileOutputStream.java:87)
   at com.badlogic.gdx.files.FileHandle.writer(FileHandle.java:322)
   at com.badlogic.gdx.files.FileHandle.writeString(FileHandle.java:350)
   at com.badlogic.gdx.files.FileHandle.writeString(FileHandle.java:339)
   at com.snowdevs.tweetiebirds.TweetieBirdsGame.create(TweetieBirdsGame.java:22)
   at com.badlogic.gdx.backends.android.AndroidGraphics.onSurfaceChanged(AndroidGraphics.java:254)
   at android.opengl.GLSurfaceView$GLThread.guardedRun(GLSurfaceView.java:1519)
   at android.opengl.GLSurfaceView$GLThread.run(GLSurfaceView.java:1240)
Caused by: android.system.ErrnoException: open failed: EACCES (Permission denied)
   at libcore.io.Posix.open(Native Method)
   at libcore.io.BlockGuardOs.open(BlockGuardOs.java:186)
   at libcore.io.IoBridge.open(IoBridge.java:438)
   at java.io.FileOutputStream.<init>(FileOutputStream.java:87)
   at com.badlogic.gdx.files.FileHandle.writer(FileHandle.java:322)
   at com.badlogic.gdx.files.FileHandle.writeString(FileHandle.java:350)
   at com.badlogic.gdx.files.FileHandle.writeString(FileHandle.java:339)
   at com.snowdevs.tweetiebirds.TweetieBirdsGame.create(TweetieBirdsGame.java:22)
   at com.badlogic.gdx.backends.android.AndroidGraphics.onSurfaceChanged(AndroidGraphics.java:254)
   at android.opengl.GLSurfaceView$GLThread.guardedRun(GLSurfaceView.java:1519)
   at android.opengl.GLSurfaceView$GLThread.run(GLSurfaceView.java:1240)

```

I use a Nexus 5 with Android 6 Marshmallow for testing. I searched and found that Android 6 uses runtime permissions but the LibGDX guys says that it works even on Android 6... Is there a fix With or Without runtime permissions?

# Answer
> 0 votes
This question is now answered in here, and it goes like this:

I check if the user has granted permission of external storage and request permission if not granted by using:

```
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
    if (this.checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
         this.requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, WRITE_REQUEST_CODE);
}

```

All of this is android-specific code and thus resides in the `AndroidLauncher` class.

# Answer
> 1 votes
If you're writing to the local area (Where the app is stored) then don't use the external file type. The correct type to use is `local` as the `local` type will store it in the same folder as the app. The problem with `external` is that `external` reads from the root directory onward. So on Windows the `external` path would need to specify the drive and other such specialized locations on the hard drive such as `C:/Windows/system32.sys` or `F:/Videos/Other/NotAdultVideo.mp4` whereas using the `local` format allows you to store it in the local area near to your app run-time and such.

---
Tags: android, libgdx, filesystem
---


# Question
Title: Attaching objects on collision in Unity?
I'm trying to make a game where the player can connect objects Lego style with objects becoming children of any object they come into contact with, so if the parent object is moved the child is moved too, but the child object can be dragged away to disconnect it.

What is the best way to go about doing this?

# Answer
> 1 votes
OnCollisionEnter will probably work out better in the long run, because it means you don't have to go through every "lego" in your scene.

Without more information, I can't be sure, but I think the problem is both objects are trying to be each other's parent. You need to set a defined order for which object will be the parent object (maybe the one that's lower down in the world, or maybe you have a test to see if the object is the one being dragged) and exit the OnCollisionEnter script immediately in the child object.

---
Tags: unity
---


title: Distance function on a pacman plane

text:
# Question
Title: Distance function on a pacman plane
I am making a game, where if you go through the right wall, you pop up on the left. I want to have a function that calculates the distance between two objects, where we can have a line that goes through the wall. For example, if the screen width is 100 and one object was at (0, 90) and another at (0, 10), the distance between them would be 20.

# Answer
Basically, you need to check if the absolute distance on either plane is larger than half that screen dimension - if so, wrapping across the screen is faster than the standard distance on that axis:

```
dx = abs(x1 - x2);
if (dx > width/2)
   dx = width - dx;
dy = abs(y1 - y2);
if (dy > height/2)
   dy = height - dy;
dist = sqrt(dx*dx + dy*dy);

```
> 2 votes

---
Tags: mathematics
---


title: How can i check when Lerp has finished?

text:
# Question
Title: How can i check when Lerp has finished?
```
private bool hitted = false;
private Vector3 hitPosition;

private void Test()
    {
        RaycastHit hit;

        if (Physics.Raycast(start.position, Vector3.left, out hit, 1.5f)
             || Physics.Raycast(start.position, Vector3.right, out hit, 1.5f)
             || Physics.Raycast(start.position, Vector3.forward, out hit, 1.5f))
        {
            if (hit.transform.tag == "Test")
            {
                hitted = true;
                hitPosition = hit.transform.localPosition;
            }
        }
    }

    private void Update()
    {
        if (hitted == true)
        {
            player.localRotation = Quaternion.Lerp(player.localRotation, Quaternion.LookRotation(hitPosition), 1 * Time.deltaTime);
        }
    }

```

What i want to detect is when the player finished rotating and then set back hitted to false.

# Answer
You can check when your rotation has gotten "close enough" using a quaternion dot product, like so:

```
private void Update()
{
    if (hitted == true)
    {
        Quaternion targetRotation = Quaternion.LookRotation(hitDirection);

        // Ensure we're correctly compensating for variable framerate
        float sharpness = 0.1f;
        float blend = 1f - Mathf.Pow(1f - sharpness, 30f * Time.deltaTime);

        player.localRotation = Quaternion.Lerp(player.localRotation, targetRotation, blend);

        // A Quaternion dot product gives you the cosine of the angle
        // between the rotations. Closer to 1 = more similar.
        if(Quaternion.Dot(transform.rotation, targetRotation) > 0.9999f) {
            // Now we're within 1 degree of the target rotation.
            // Put your "arrived" code here.
        }
    }
}

```

Or, if you don't need to precisely control the exact threshold you want to use, Unity's default `==` operator on quaternions includes a little wiggle room, so in many cases you can even just test:

```
if (player.localRotatiin == targetRotation)

```
> 6 votes

# Answer
You can just use the t Time. Instead of writing 1 * Time.deltaTime just make 4 fields, LerpTime, CurrentLerpingTime, Speed, T;

Then check whether the T is more than or equal to 1, if it is then the lerp has finished!.

```
private float LerpTime = 1.0f;
private float CurrentLerpingTime;
private float Speed = 25f;

private void Update(){

   ......

   if(hitted == true){

      CurrentLerpingTime = Mathf.Clamp01(CurrentLerpingTime + (speed * Time.deltaTime));

      t = CurrentLerpingTime / LerpTime;

      player.localRotation = Quaternion.Lerp(player.localRotation, Quaternion.LookRotation(hitPosition), t);

      if(t >= 1){
        Debug.Log("Lerping Has Finished!");
      }
   }
}

```
> 0 votes

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


# Question
Title: What are the differences between all RPG Maker products?
I can't find a complete chart of differences between the many versions of RPG Maker. There's only a partial list of features here.

On the official site there are:

* RPG Maker MV
* RPG Maker VX Ace
* RPG Maker VX
* RPG Maker XP
* RPG Maker 2003
* GG Maker
* IG Maker

I might have missed some versions because there are so many and their names are pretty similar.

# Answer
> 5 votes
First of all, IG maker and GG maker are not part of the RPGMaker product line. While RPGMaker focuses solely on JRPGs, IG Maker and GG Maker are less genre-focused game engines. I don't know why they list them on rpgmakerweb.com. Maybe because they can *also* make RPGs. (they also present MangaMaker on the website which isn't even a game development tool). The same company also currently develops VN Maker which is an engine especially for visual novels.

RPGMaker is a product which exists for quite a long time and went through several versions:

1. RPG Maker 95
2. RPG Maker 2000
3. RPG Maker 2003
4. RPG Maker XP (2005)
5. RPG Maker VX (2008)
6. RPG Maker VX Ace (2011)
7. RPG Maker MV (2015)

The versions are only partially compatible with each other, which means a game developed on an older version can often not easily be ported to a more recent one. That means older versions still stay relevant for maintaining the older titles, for people who simply dislike some feature-changes of the newer versions or for people who want to benefit of the more mature ecosystem of previous versions (3rd party plugins and assets).

A complete list of all differences between all these versions would be too broad to list here. But when you are starting a greenfield project you should use the most recent version (RPG Maker MV).

GG Maker or IG Maker might be interesting when you plan a project which is sort of JRPG*ish* but defies many common UI conventions of the genre. But then you should also consider all the other game engines out there and also the option of not using any game engine and just a bunch of helpful libraries for your programming language of choice.

# Answer
> 0 votes
My guess would be that the compatibility of Windows operating systems.

My guess is based around older software would tend to name there releases based around compatibility of the latest operating system software. An example of this "Microsoft office".

My guess on this might be entirely wrong: it's just a guess.

* RPG Maker 95 (Windows 95)
* RPG Maker 2000 (Windows 2000)
* RPG Maker 2003 (Windows Server 2003)
* RPG Maker XP (2005) (Windows XP)
* RPG Maker VX (2008) (Windows Vista and xp)
* RPG Maker VX Ace (2011) (Windows Vista and XP) "don't have a guess on why it says ace"
* RPG Maker MV (2015) (Macintosh, Windows Vista and anything else like Windows 10 and below)

---
Tags: rpg-maker
---


# Question
Title: How do I stop a monster from dropping a quest item once the related quest is finished?
I'm trying to make a quest. When the quest is activated (switch is on), monsters should drop a certain quest item. After the quest is finished (switch is off), those monsters should stop dropping the quest item. How can I do this?

# Answer
> 1 votes
I think this is what your looking for. Go to "Troops" Tab in "database" and pick the troop you want to use and look in the conditions window and select "conditional branch".From the selections click "switch" type or choose a desired switch and click ok, in this case we are naming our switch "quest item potions". Then click inside the conditional branch and select "change items" and choose a potion. Make sure increase is checked and not decrease or else it will take away a potion. so now if you choose to turn on (switch)"quest item potions" it'll give you a potion. BUT WE ARE FORGETTING SOMETHING STILL! Make sure to change the conditions window to the desired one in this case I picked "turn end".

# Answer
> 0 votes
If you have something like a loot table system where you can change the chance of the item appearing, you could set it to 0% to make sure it doesn't show up. Other options are

* The quest adding the item to the loot table while the quest is active and removing it when it's inactive.
* Having a locked state on your item, so it means that it cannot spawn.

And there are probably a lot more ways to go about this problem. Look at your architecture and see what's the best for your game. I would go for the second option, but it all depends on what kind of architecture you have for your game.

---
Tags: rpg-maker-mv
---