title: Rotating an object while moving

text:
# Question
Title: Rotating an object while moving
I have an object the is a perfect circle. The object is moving left, right and jumping with collision detection. What I am trying to do now is rotate the object while it is moving, so it looks like rolling.

This is the code that I have so far:

```
key_left = keyboard_check(vk_left);
key_right = keyboard_check(vk_right);
key_jump = keyboard_check_pressed(vk_space);

//1  right, -1 left
var move = key_right - key_left;
hsp = move * walkspd;
vsp = vsp + grv;

if(place_meeting(x, y + 1, oWall)) && (key_jump)
{
    vsp = -7;
}

//horizontal collisions
if (place_meeting(x + hsp, y, oWall))
{
    while (!place_meeting(x + sign(hsp), y, oWall))
    {
        x = x + sign(hsp);
    }
    hsp = 0;
}
x = x + hsp;

//vertical collisions
if (place_meeting(x , y + vsp, oWall))
{
    while (!place_meeting(x, y+ sign(vsp), oWall))
    {
        y = y + sign(vsp);
    }
    vsp = 0;
}

```

# Answer
For an exact roll of the circle object based on his displacement use this exact line at the end of your code:

```
image_angle -= hsp*pi;

```

The reason of a minus sign is because the roll is clockwise when you go to the right but angles in Game Maker are increasing counter clockwise.
> 1 votes

# Answer
I think all you need is this in the Step Event:

```
image_angle += hsp;

```

`image_angle` is a variable that decides the rotation position of the sprite. In a number between 0 and 360. You can let it move by adding value to it.

And in case you didn't knew, `x += hsp` does the same thing as `x = x + hsp`. But the former makes them more readable.
> 0 votes

---
Tags: game-maker
---


title: Pre-calculate physics in unity

text:
# Question
Title: Pre-calculate physics in unity
I have a self contained physics simulation (eg fragments of a building crumbling) which is known to be the same, excepting floating point precision errors, every time it is run.

Is there a way to improve performance by pre-calculating/recording the simulation?

It would seem that the build in physics engine does not support this, but are there other engines that do?

Or alternatively, would recording the transformation of each Rigidbody in the simulation, and then playing back those transforms, be a sensible approach to increase performance? It would remove a lot of Rigidbodies, joints and enable flattening the hierarchy.

# Answer
> 3 votes
Use GameObjectRecorder:

> Records the changing properties of a GameObject as the Scene runs and saves the information into an AnimationClip.
>
> This class binds GameObject properties, records their values as they change in the running Scene, and saves the result in an AnimationClip. The recorded GameObject is called root in the class, and you can also bind the properties of any child of root.

Here's the thread on the Unity forums explaining its use when it was originally being designed

https://forum.unity.com/threads/feedbacks-for-experimental-feature-gameobjectrecorder-2017-1.467852/

Alternatively, you could try the Unity Recorder asset, which is built on top of GameObjectRecorder, and provides a GUI interface, but is quite a bit more complex.

> The Unity Recorder is an Editor-only tool that captures video and animation data during gameplay. It records to various media formats. It is compatible with Unity 2018.1 and up.

It can be used to record to video clips, image sequences, or to an animation clip, the last one being the one you'd want to use. I don't have experience with this asset though, so I don't know whether it will actually do what you are looking for.

# Answer
> 1 votes
Since you state that all runs are the same, I think the ideal solution here would be to treat the whole thing as a single object and animation.

To my knowledge, Unity does not have a built-in animation-baking feature, unlike it's main competitor Unreal and several other engines. However, nothing prevents you from baking the animation in an external program like Blender and importing and using it in Unity.

---

If you need the objects to be able to become dynamic, however, it might then be better to have a script that records the positions and rotations of rigidbodies into a file, in order to have a persistent baked copy of the animations, and then use another script on each fragment to play back that fragment's animation when needed. This allows for each object to be separate and contain a rigidbody that can be switched to it's dynamic behaviour when an external interaction like a collision is detected.

---
Tags: unity, physics
---


# Question
Title: How can I rumble/vibrate my controller with libGDX?
The `com.badlogic.gdx.controllers.Controllers` API only supports getting the input data (which works fine).

Is there a way to make my controller rumble/vibrate, possibly using some other classes?

I tried using the `org.lwjgl.input.Controllers` class, which supports this, but the controllers don't get indexed there and I can not access them.

# Answer
> Is there a way to make my controller rumble/vibrate, possibly using some other classes?

It's not a feature libGDX itself supports, and it seems unlikely (based on the discussion on the issue linked in the comments) to happen any time soon. You'll have to use third-party libraries.

Unfortunately most of those third-party libraries (like JXInput) map to the native XInput API to provide vibration (for 360 controllers), which means they don't function on non-Windows system. Regular JInput seems like it may be hampered by the same issue, and doesn't seem to expose vibration anyhow. There are native libraries like libstem\_gamepad you could wrap, but *they* don't support vibration either.

With the caveat that I haven't really tried it, your best bet might be to use the Java binding for SDL, possibly only for the controller APIs, and try to leverage the haptic feedback API therein.
> 1 votes

# Answer
For using SDL with libGDX desktop, you can use Jamepad. It supports rumbling. There are wrappers for Jamepad to use it as a drop-in replacement for the libGDX controller implementation, for example gdx-controllerutils.

Now, a problem is that you can't trigger rumbling with the existing implementations: libGDX' controller interface just don't have a method for doing so. The task still to do is:

* make an own Controller interface extending libGDX' interface with methods for rumbling
* implement this interface in JamepadController
* check with `instanceof` in your core code if you have an Controller implementing your interface and then rumble

Best was if the libGDX' controller interface would be extended. There are other methods lacking as well, for example requesting how many buttons and axis are present. Apparently, there is not much interest in the controller extension by the maintainers, so you are better off with an own solution described above.
> 1 votes

---
Tags: libgdx, mobile, controllers
---


# Question
Title: How do I make an object not appear grey regardless of distance?
My moon texture is on a plane 500m away and I would like to know if there is a way to keep displaying the texture:  As opposed to it turning grey as pictured here: regardless of the distance it is from the camera. Any help is greatly appreciated,
Thanks.

# Answer
Try turning off "Fade out Mip Map" in the texture's settings (Under Advanced)
> 1 votes

---
Tags: unity, shaders, textures, graphics, rendering
---


# Question
Title: Should I develop the game first or get NDA?
So I have been working on my game for a while now. And I now I have other people contributing to the project. I fear that someone will tell their friends and/or family then my 'great' idea is lost.

So my question is should I wait and get a NDA ( Non Disclosure Agreement) or some other form of legal document that tells everyone one the project or who has ever worked on the project to be quite until its release?

# Answer
> 7 votes
An idea itself rarely worths anything, unless you have at least a design plan that covers most aspects of the game. Your idea will leak anyways - and as long as only family and friends hear about it, you have nothing to fear. I mean, how many game development team leaders do you have in your family?

**What you should have though, is some license to protect your source code and other assets.** Look up GPL, and the various open source licenses, see how they work, how they're written. You can copy and modify these licenses, just make sure to consult a lawyer if you want a customized license.

As for an NDA, I think you can write (copy) your own from an job contract, or similar example which can be found online. Just make sure it covers everything you want to protect, and that two witnesses also sign it.

# Answer
> 4 votes
The harsh truth is that ideas are worthless. I am not trying to be condescending, as I myself was once protective of my ideas. If they were worth something, there would be a market for them. Have you ever heard of someone purchasing an idea before?\* No matter how great you think your idea is, the human race is very large and very creative, and your idea has probably already been thought up 10 times, and if it is any good there are probably implementations of it in the works that you don't even know about yet. The best thing you can do is spread your idea as far as possible - this will test for traction, give you valuable feedback, and potentially gain you some support. Its very unlikely that anyone will try to steal your idea, because every person is more interested in their own "great" ideas.

\*(Note, intellectual property is an entirely different thing. IP is worth something because it has a mindshare, and previous implementations that have built up this mindshare).

# Answer
> 0 votes
New to collaboration, I do think ideas are worth protecting. According to this article however, it might be too late for you to implement an NDA.

Section 5 is titled: "Information already known by receiving party or in public domain". Since there was no NDA in place, your contributors have probably already shared some information about your game. While this information might not be in the "public domain", the data has already run away from you a bit.

---
Tags: legal
---


# Question
Title: Rotating game object without using localEulerAngles
I'm building a player controller.

While aiming, the player can rotate the chest bone. This looks as if the character aims in different directions.

The chest bone should only be allowed to rotate within a certain range. If this range is exceeded (either to the left or to the right), the chest bone should stay at its current rotation, and the player should be rotated instead.

I'm having problems applying the desired rotation to the parent game object instead.

I'm trying to work with the localEulerAngles in order to applying an additional Y rotation to the gameobject, but the Y rotation value tells me for example "359.9" while I expected to work with a value of ~0.

```
private void pHandle_LateUpdate_Aim()
{
    Quaternion oldNeckRotation = Neck.transform.rotation;

    // Fade old input before capturing new, so we don't dull the freshest data.
    float yawBlend = Mathf.Pow(1.0f - Aim_yawInputFalloff, referenceFramerate * Time.deltaTime);
    // A Lerp toward zero is just the same as a multiplication by the blend factor.
    Chest_yawRate *= yawBlend;
    // Accelerate by mouse movement over the past frame.
    // (May need adjustment for display resolution).
    Chest_yawRate += Input.GetAxis("Mouse X");

    float yawDelta = Chest_yawSpeed * Chest_yawRate * Time.deltaTime;
    float offCenterYaw = Chest_currentYaw - Chest_yawCenter;

    float fDesiredChestYaw = Chest_currentYaw + yawDelta;
    float fHeroRotation = 0f;

    if (fDesiredChestYaw > Chest_rotateRange) // the allowed chest rotate range would be exceeded. Instead, move the gameobject / the parent.
    {
        fHeroRotation = (fDesiredChestYaw - Chest_rotateRange);
        fHeroRotation += this.transform.localEulerAngles.y;
        this.transform.Rotate(0, fHeroRotation, 0);
        return;
    }
    else if (fDesiredChestYaw < -Chest_rotateRange)
    {
        fHeroRotation = (Chest_rotateRange + fDesiredChestYaw);
        fHeroRotation += this.transform.localEulerAngles.y;
        this.transform.Rotate(0, fHeroRotation, 0);
        return;
    }
    else
    {
        // If we're moving away from the center, slow down as we approach the edge.
        if (yawDelta * offCenterYaw > 0)
        {
            float extremityYaw = offCenterYaw / Aim_yawMaxRange;
            yawDelta *= 1.0f - extremityYaw * extremityYaw;
            fHeroRotation = yawDelta;
        }
    }

    // Ensure we never overshoot the allowed range.
    Chest_currentYaw = Mathf.Clamp(Chest_currentYaw + yawDelta,
                              Chest_yawCenter - Aim_yawMaxRange,
                              Chest_yawCenter + Aim_yawMaxRange);

    Vector3 nNewChestRotation = new Vector3(Chest.localEulerAngles.x, Chest_currentYaw, Chest.localEulerAngles.z);
    Chest.localRotation = Quaternion.Euler(nNewChestRotation);

    Quaternion newNeckRotation = Neck.transform.rotation;

    //the neck should not rotate with the chest. So I first counter-rotate it against the new chest rotation, then rotate it a little towards the chest rotation
    Neck.transform.rotation = Quaternion.Lerp(oldNeckRotation, newNeckRotation, neckFollowChest);
}

```

# Answer
Damn, I was stupid.

All the time I didn't realize I could simply add a rotation Y like this:

```
    if (fDesiredChestYaw > Chest_rotateRange) // the allowed chest rotate range would be exceeded. Instead, move the gameobject / the parent.
    {
        fHeroRotation = yawDelta;
        this.transform.Rotate(0, fHeroRotation, 0);
        return;
    }

```
> 2 votes

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


# Question
Title: Having two points (line) how can I substract a specific amount to each point?
I have two points that make a line. And I need to subtract a specific amount to each point keeping the direction of the line. I know the radius which is the amount to subtract.

The red dots of the first line is what I have, and the dots of the second line is an example of what I would like to calc.

# Answer
This should work:

For each point of the line:

`point = point + ((otherPoint - point).normalise() * radiusToSubtract)`

### Explanation:

First we get the direction from the point we're moving to the other point

`(otherPoint - point).normalise()`

Then we multiply that unit vector by the amount you want to budge the point toward the other point

`* radiusToSubtract)`

Lastly we add that to the point we're moving

`point + ((otherPoint - point).normalise() * radiusToSubtract)`
> 1 votes

# Answer
Imperial's answer works fine if you are in a game engine that has the normalise() function, but if you are doing something a bit more homebrew, the actual math works like this:

Since both points are an object with a known X, Y, and radius value, you can use your basic slope formula tells us Slope=(Y2-Y1)/(X2-X1)

We also know that both objects will follow this slope over the distance of their radius at which point you are left with something like this to find your X: https://math.stackexchange.com/questions/566029/in-a-right-triangle-given-slope-and-length-of-hypotenuse-find-length-of-legs

With two known legs on a right triangle, the Y is just a simple pythagorean function equation.

Lastly, you need to check the directions of your rise and run because all that Squaring only produces positive values.

So what this would look like in a language agnostic since is something like this:

```
getCloser(target){
    rise = target.y-this.y;
    run = target.x-this.x;
    slope = rise/run;
    movX = this.radius/sqrt(slope^2+1);
    movY = sqrt(this.radius^2-movX^2);

    if (run > 0){
        this.x += movX;
    } else {
        this.x -= movX;
    }

    if (rise > 0){
        this.y += movY;
    }else{
        this.y -= movY;
    }
}

```

then

```
point1.getCloser(point2);
point2.getCloser(point1);

```
> 1 votes

---
Tags: mathematics, vector
---


title: How can I make the text flash?

text:
# Question
Title: How can I make the text flash?
I want to have text that flashes from green to white and back to green over and over until the window is closed? Below is what I have tried but i cant seem to get it to work, please help me.

```
int main()
{
    sf::RenderWindow window(sf::VideoMode(LAYOUT_WINDOW_WIDTH, LAYOUT_WINDOW_HEIGHT),
        "Tetris 2019 - A New Beginning");

    sf::Font myFont;
    if (!myFont.loadFromFile("cartoon relief.ttf")) {

    }

    window.setFramerateLimit(30);

    sf::Text gameOver;
    gameOver.setFont(myFont);
    gameOver.setFillColor(sf::Color::Green);
    gameOver.setStyle(sf::Text::Regular);
    gameOver.setString("GAME OVER!");
    gameOver.setCharacterSize(65);
    gameOver.setPosition(30, 60);

    //everything below gets copied into the "processSplash" function
    while (window.isOpen())
    {
        sf::Time elapsed_time;
        sf::Clock r;

        sf::Time delta_time = sf::seconds(1);

        sf::Text playAgian;
        playAgian.setFont(myFont);
        playAgian.setFillColor(sf::Color::Green);
        while (window.isOpen && elapsed_time >= delta_time)
        {
            if (elapsed_time == delta_time)
            {
                playAgian.setFillColor(sf::Color::Green);
                elapsed_time == r.restart();
            }
            else
                playAgian.setFillColor(sf::Color::White);
                elapsed_time += r.restart();
        }
        playAgian.setStyle(sf::Text::Regular);
        playAgian.setString("Press ENTER to play agian!");
        playAgian.setCharacterSize(25);
        playAgian.setPosition(80, 235);

        sf::Event event;

        while (window.pollEvent(event))
        {
            if (event.type == sf::Event::Closed)
                window.close();

            if (event.type == sf::Event::KeyPressed
                && event.key.code == sf::Keyboard::Space)

                //close splash screen and start game
            {
                /*processSplash();*/
            }
        }

        window.draw(gameOver);
        window.draw(playAgian);

        window.display();
    }

    return 0;
}

```

# Answer
there were a bunch of bugs in your code. This is a working example, there are many way of getting this implemented. In principle you use the same method as for animating a sprite.

For animations you need to capture the time. Or you will not be able to calculate the duration per frame. And you need to store the current frame in a variable. I put some comment in the example code below.

Btw, if you are not used to game loops, have a look on https://gafferongames.com/post/fix\_your\_timestep/

```
#include <SFML/Graphics.hpp>

int main(){
    int LAYOUT_WINDOW_WIDTH = 800;
    int LAYOUT_WINDOW_HEIGHT = 600;

    sf::RenderWindow window(sf::VideoMode(LAYOUT_WINDOW_WIDTH, LAYOUT_WINDOW_HEIGHT),
        "Tetris 2019 - A New Beginning");

    sf::Font myFont;
    if (!myFont.loadFromFile("cartoon relief.ttf")) {

    }

    window.setFramerateLimit(30);

    sf::Text gameOver;
    gameOver.setFont(myFont);
    gameOver.setFillColor(sf::Color::Green);
    gameOver.setStyle(sf::Text::Regular);
    gameOver.setString("GAME OVER!");
    gameOver.setCharacterSize(65);
    gameOver.setPosition(30, 60);

    sf::Text playAgain;
    playAgain.setFont(myFont);
    playAgain.setFillColor(sf::Color::Green);
    playAgain.setStyle(sf::Text::Regular);
    playAgain.setString("Press ENTER to play Again!");
    playAgain.setCharacterSize(25);
    playAgain.setPosition(80, 235);

    // Clock object to measure overall timing
    sf::Clock clock;
    sf::Event event;

    // Duration to control animation speed
    int currentColor = 1;
    float duration = float();

    //everything below gets copied into the "processSplash" function
    while (window.isOpen()){

        // How much time since last loop?
        sf::Time dt = clock.restart();
        duration += dt.asSeconds();

        while (window.pollEvent(event)){
            if (event.type == sf::Event::Closed)
                window.close();

            if (event.type == sf::Event::KeyPressed
                && event.key.code == sf::Keyboard::Space){
                //close splash screen and start game
                /*processSplash();*/
            }
        }

        // Animation duration per frame (0.1f) reached
        if (duration > 0.01f){
          // Restart calculation of the duration
          duration = 0;

          // Loop through the animation colors
          if (currentColor < 255){
            currentColor += 5;
          } else {
            // Start from first frame if last frame reached
            currentColor = 0;
          }
          playAgain.setFillColor(sf::Color(0, currentColor, 0));
        }

        window.draw(gameOver);
        window.draw(playAgain);

        window.display();
    }

    return 0;
}

```
> 0 votes

---
Tags: sfml
---


# Question
Title: How to rotate CharacterController on slope
I'm trying to rotate my characterController player on a slope on the 'x' and 'z' axises, however things aren't going so well.

The player does rotate, but if I move and look in another direction, the characterController will still be on the same axis, and won't look down an up slope, and instead will be looking up a down slope.

```
void Update ()
{
   Vector3 rotateDirection = (camera.forward * Input.GetAxis("Vertical"))
                           + (camera.right * Input.GetAxis("Horizontal"));

   Quaternion newRotation = Quaternion.LookRotation(
                               new Vector3(rotateDirection.x, 0f, rotateDirection.z));
   transform.rotation = Quaternion.Slerp(
                               transform.rotation, newRotation, rotSpeed * Time.deltaTime);
 }

private void OnControllerColliderHit(ControllerColliderHit hit)
{
      transform.rotation = Quaternion.Euler(hit.transform.rotation.eulerAngles.x,
                   transform.rotation.eulerAngles.y, hit.transform.rotation.eulerAngles.z);
}

```

Also, it doesn't work at all with spheres and terrain since their rotation is zero. Anyone know how to achieve what I am talking about? Also, the goal is to allow for the 'y' axis to be free and do what it needs to in `void Update()`.

# Answer
To orient ourselves to our ground surface, we'll need to establish what direction is "out" from the ground we're standing on. So let's set aside a member variable to track that.

```
Vector3 groundNormal;

```

The safest way to populate this is likely with a raycast down toward your feet each frame. If you want to continue using `OnControllerColliderHit` then you should include some test first to distinguish hits from the ground vs hits from walls or other obstacles that should not change your ground normal. You can use physics layers or tags, for example.

Once you have a contact point that you're confident represents ground (either a `RaycastHit` or a `ControllerColliderHit`), you can capture its normal as your current `groundNormal`:

```
groundNormal = hit.normal;

```

Now, we can compute a local coordinate space relative to this surface and our camera perspective, using the TurretLookRotation method shown in this answer:

```
Quaternion inputFrame = TurretLookRotation(camera.forward, groundNormal);

```

We can use this to transform our input into world space:

```
Vector3 localInput = new Vector3(
                           Input.GetAxis("Horizontal"),
                           0f,
                           Input.GetAxis("Vertical")
                         );

Vector3 worldInput = inputFrame * localInput;

```

Then construct our new rotation using this direction in the plane of our surface, and an "up" vector pointing out of our surface:

```
Quaternion newRotation = Quaternion.LookRotation(worldInput, groundNormal);

```

Note here we've never tried to break apart an Euler angle triplet into separate angles to mix and match. This will almost never have your desired effect. It's much more reliable to describe and compute your rotations in terms of quaternions or basis vectors as illustrated above.
> 1 votes

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


title: Handling damage taken by enemy

text:
# Question
Title: Handling damage taken by enemy
I'm learning the basics of combat system by doing it myself, but there is a logical problem I can't figure out. It's on Unity2D, using C#.

```
Collider2D[] enemiesToDamage = Physics2D.OverlapCircleAll(attackPosition.position, attackRange, attackableLayer);
            for (int i = 0; i < enemiesToDamage.Length; i++)
            {
                enemiesToDamage[i].GetComponent<DamageEnemy>().TakeDamage(damage);
            }

```

This is what my attack function looks like, this script is assigned to every enemy in my game and functions properly. But the problem is I want to assign every enemy a unique function whenever they take damage, like jumping back or flying away, and I can't do it in one script. What do I do?

# Answer
As another tool in your toolbox, in addition to the polymorphism Alex Myers recommends in the comments, you can try setting this up in an event-driven manner:

```
public class DamageTaker : MonoBehaviour {

    public UnityEvent onDamage;
    public float health;

    public void TakeDamage(float damage) {
        onDamage.Invoke();
        health -= damage;

        if(health <= 0f) {
            // TODO: Handle death.
        }
    }
}

```

This will give you a widget in the Inspector (or an access point in code) where you can wire up no, one, or multiple methods to call when this object takes damage. These methods can be on the same script or different scripts, or even on different objects in your scene. You can even configure the event to pass the amount/type of damage taken, or a reference to the damage source, so your characters can react accordingly.

With a strategy like this, you can have just one simple damage-handling script that does just that one job (single-responsibility principle), rather than entangling AI behaviour logic in your damage taking code.

Your AI behaviour script(s) remain separate, and can be freely mixed-and-matched with this damage taking behaviour with zero code changes. In data, you can configure which AI behaviour(s) each enemy prefab should use, and which reaction method(s) should be called when it takes damage.

This is an example of the principle of composition over inheritance, allowing you to combine small modular components of code in remixable ways to produce lots of variety without hard-coding each combination, and without deep & inflexible inheritance trees. It's especially useful if you have non-programmers on your team, like game designers and level designers, because it empowers them to make and tune their own combinations without dependencies on code changes.
> 3 votes

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


# Question
Title: Camera view matrix from position/yaw/pitch/worldUp
I'm trying to make a basic FPS camera view matrix, using position, pitch/yaw, and worldUp. Currently, my camera's view matrix is just a plain rotation matrix (made with yaw/pitch/roll) and the result is the view appears to be looking down the negative Z-axis, which in my case is my floor. Most tutorials I can find recommend making a view matrix by passing in an "eye" and "target" vector. But this isn't a desirable setup for an FPS camera where I only know the position and angles (pitch/yaw/roll) of the camera -- I don't have a specific point in mind that I want the camera to be focused on!

I'm using OpenGL as a renderer, but I don't want to use GLM as I'd wish/hope to understand how to implement this without helper libs. Also, my meshes and world matrices are made so that Z is my worldUp, X as forward, and Y as right/left. That might seem odd, but old Unreal engine games used this setup and I'm just accustomed to it for mapping/modding.

As mentioned my view matrix is currently looking down at the floor, but I'm not surprised that it's wrong because I've never incorporated or multiplied my worldUp vector into the matrix, and I don't understand how to.

So that's my question: How exactly do I incorporate my worldUp vector into my rotation matrix, to turn it into a proper view matrix -- or better yet, what is the proper method for constructing a view matrix when you have exactly these variables: 1.) Camera Position (XYZ) 2.) World Up vector ("0,0,1" for me) 3.) Camera Pitch/Yaw/Roll (Really only need Pitch/Yaw!)

I've been going through loads of tutorials and I can't find what I'm looking for. This is how I've started, but all it is is a normal rotation matrix, so honestly a full methodology would be really appreciated as I've been pulling my hair out over this for a week now. Thank you for any guidance on this.

```
MAT4X4F mrol;
MAT4X4F mpit;
MAT4X4F myaw;
float cr, cp, cy;
float sr, sp, sy;

cr = cos(_cam_roll);    cp = cos(_cam_pitch);   cy = cos(_cam_yaw);
sr = sin(_cam_roll);    sp = sin(_cam_pitch);   sy = sin(_cam_yaw);

// Yaw (about Z-axis)
myaw.m[0] = cy;     myaw.m[1] = -sy;    myaw.m[2] = 0.0f;   myaw.m[3] = 0.0f;
myaw.m[4] = sy;     myaw.m[5] = cy;     myaw.m[6] = 0.0f;   myaw.m[7] = 0.0f;
myaw.m[8] = 0.0f;   myaw.m[9] = 0.0f;   myaw.m[10] = 1.0f;  myaw.m[11] = 0.0f;
myaw.m[12] = 0.0f;  myaw.m[13] = 0.0f;  myaw.m[14] = 0.0f;  myaw.m[15] = 1.0f;

// Pitch (about Y-axis)
mpit.m[0] = cp;     mpit.m[1] = 0.0f;   mpit.m[2] = sp;     mpit.m[3] = 0.0f;
mpit.m[4] = 0.0f;   mpit.m[5] = 1.0f;   mpit.m[6] = 0.0f;   mpit.m[7] = 0.0f;
mpit.m[8] = -sp;    mpit.m[9] = 0.0f;   mpit.m[10] = cp;    mpit.m[11] = 0.0f;
mpit.m[12] = 0.0f;  mpit.m[13] = 0.0f;  mpit.m[14] = 0.0f;  mpit.m[15] = 1.0f;

// Roll (about X-axis)
mrol.m[0] = 1.0f;   mrol.m[1] = 0.0f;   mrol.m[2] = 0.0f;   mrol.m[3] = 0.0f;
mrol.m[4] = 0.0f;   mrol.m[5] = cr;     mrol.m[6] = -sr;    mrol.m[7] = 0.0f;
mrol.m[8] = 0.0f;   mrol.m[9] = sr;     mrol.m[10] = cr;    mrol.m[11] = 0.0f;
mrol.m[12] = 0.0f;  mrol.m[13] = 0.0f;  mrol.m[14] = 0.0f;  mrol.m[15] = 1.0f;

_cam_matrix = myaw * mpit * mrol;

```

# Answer
If you're transforming a vector \\$\vec v\\$ like this:

$$\vec v ' = M \cdot \vec v\\ \begin{bmatrix}v\_x'\\v\_y'\\v\_z'\\1\end{bmatrix}= \begin{bmatrix}X\_x & Y\_x & Z\_x &T\_x\\ X\_y & Y\_y & Z\_y & T\_y\\ X\_z & Y\_z & Z\_z & T\_z \\ 0 & 0& 0 & 1 \end{bmatrix} \cdot \begin{bmatrix} v\_x\\v\_y\\v\_z\\1 \end{bmatrix}$$

Then we can usefully think of each column of the matrix as a vector:

* \\$\vec X\\$ is the direction into which the x-axis basis vector (1, 0, 0, 0) gets transformed
* \\$\vec Y\\$ is the direction into which the y-axis basis vector (0, 1, 0, 0) gets transformed
* \\$\vec Z\\$ is the direction into which the z-axis basis vector (0, 0, 1, 0) gets transformed
* \\$\vec T\\$ is the position to which the local origin (0, 0, 0, 1) gets translated

If your multiplication convention is the opposite (\\$\vec v \cdot M\\$ \- I can't remember what order OpenGL functions assume), then take the transpose of everything above - the columns become rows instead, but the same logic applies.

So, that makes it easy to compute a matrix with any orientation and any translation we want.

If we want the local x axis "forward" to point along a given yaw & pitch angle, we can compute the column vector \\$\vec X\\$ with spherical coordinates:

$$\vec X = \begin{bmatrix}\cos(pitch) \cdot \cos(yaw)\\ \cos(pitch) \cdot \sin(yaw)\\ \sin(pitch) \end{bmatrix}$$

(Negate the \\$\sin\\$ terms if you want the rotation direction to be opposite what's shown here)

If the local y axis points "right," then that depends only on yaw, no pitch needed:

$$\vec Y = \begin{bmatrix}-\sin(yaw)\\\cos(yaw)\\0\end{bmatrix}$$

And then the local z axis is just the cross product of the two:

$$\vec Z = \begin{bmatrix}- \sin (pitch) \cdot \cos (yaw) \\ - \sin (pitch) \cdot \sin (yaw) \\ \cos (pitch) \end{bmatrix}$$

And of course, \\$ \vec T \\$ is just the position of your camera.

To ultimately use this to render, you'll want to invert it (to transform world coordinates into camera-local coordinates), and swizzle the axes by swapping the rows around (since for drawing we typically want depth along the negative z axis, and height along the y axis)

So your view matrix would ultimately look something like this:

$$\begin{bmatrix} -\sin(y) & \cos(y) & 0 & T\_x \sin(y) - T\_y \cos(y)\\ -\sin(p) \cos(y) & -\sin(p) \sin(y) & \cos(p) & \sin(p)\left(T\_x \cos(y) + T\_y \sin(y)\right) - T\_z \cos(p)\\ -\cos(p) \cos(y) & -\cos(p) \sin(y) & -\sin(p) & cos(p)\left(T\_x \cos(y) + T\_y \sin(y)\right) + T\_z \sin(p) \\ 0 & 0 & 0 & 1 \end{bmatrix}$$
> 5 votes

---
Tags: opengl, camera, first-person-shooter, view
---


# Question
Title: How to manage complex mesh importing in to a game engine
A bit of context: I'm developing a 3D rendering engine and can't really make much more progress until I get some more interesting and complex meshes loaded in to the scene. So far I have been using built-in simple meshes like cubes and planes. I have written a `Mesh` class to take a `MeshData` struct which contains `Position`, `Normal`, `Tangent`, `Bitangent`, `Colour`, `Texture Coordinate`, and optional `Face` data. The `Mesh` class takes this data and depending on a few things it will generate a VBO with all of the available data interleaved, an EBO, and a VAO which has both the VBO and EBO (if one exists) bound to it. I've been pretty happy with this so far and it works fine with a simple .OBJ which contains a relatively straight-forward mesh.

Currently I have an asset management system which allows me to load in assets like this:

```
Mesh * teapot = AssetManager::loadGlobalAsset<Mesh>("res/meshes/teapot.obj");

```

If the returned pointer == `nullptr` then the assets doesn't exist. If it isn't `nullptr` then one of three things just happened: (1) the asset was just newly created and successfully loaded in to the asset manager's pool of assets, (2) the asset was found to already exist in the pool of assets and its pointer returned, (3) the asset was found to already exist in the pool of assets, but was unloaded, so it was loaded and its pointer returned.

As I said this works great for simple meshes but **I'm a bit stuck on what to do and what changes I now need to make to load meshes which have multiple sub-meshes which might have individual materials.**

For example the Sponza mesh has many sub-meshes which make use of a set of materials.

I could just load the mesh right in to my scene and have the mesh spread across multiple scene nodes all with a common ancestor node, but then this would defeat the purpose of an asset manager and I would have to worry about cleaning up and unloading the mesh outside of the asset manager. I could also just load the mesh as one big combined mesh, but of course then I can't assign individual materials to the sub-meshes without a lot of trouble.

I currently can't load the mesh using my asset manager as assets are identified by the hash of their filepaths, and here we have a situation where many individual meshes technically have the same filepath. If I just create new assets and give them to the asset manager with an ID to later fetch the asset (which isn't necessarily a bad idea for built in assets (I think)), then I feel I have the following issues:

* Easy to add multiple assets with same ID
* Breaks the connection between the meshes contained in a single mesh file
* No way of actually knowing the ID of a mesh which was loaded in via a mesh file
* Would have to manually recreate the whole mesh from its loaded sub meshes if I wanted to simply display the mesh as-is.

There is also the issue of where to store the materials that are included in the material library that a mesh file might reference. Do I create new material assets from this library, add them to the manager, and then have the mesh somehow reference these materials? But then how would I reference these materials manually? It's a similar issue to last point from the above list. Also, meshes don't currently have any knowledge of its material, that's the scene node's job.

Thanks for any thoughts or comments on this issue. I'd be very interested to hear what you guys think.

# Answer
One common way to handle this is to introduce a new category of asset that we might call a "prefab."

A prefab is a self-contained branch of a scene graph, with its own root node, and optionally additional child nodes.

When you instantiate a prefab inside your scene, you spawn a copy of the prefab's root node as a child of the scene root or an existing scene node, and recursively spawn copies of each of its children as children of this new prefab instance.

Now, when you're importing a model file that may contain multiple meshes, count the meshes. If there's exactly one mesh, you can import it as a mesh asset using your existing logic.

If there's more than one mesh, import it as a prefab asset. Give it an empty root node, then create a mesh node as a child of the prefab root for each mesh in the source file.

This lets you preserve the internal structure and spatial/hierarchy relationships between the various meshes (or other node types) in the file. The root level asset can still refer back to the file it was imported from, so any functions that need to access the file from which an asset was loaded just need to remember to navigate to the root node of the asset first (which is just a no-op on plain mesh assets that are their own root).

For placing the meshes in your scene, you'll typically want to place the whole coordinated prefab block as a single piece, so this should still be compatible with your strategy of using a hash of the file path to look up / load the asset. The root node of the prefab still has a unique path and thus (barring collisions) a unique hash to associate with it.

If you ever need a specific mesh from within the prefab, you'll need a second layer of addressing to select sub-assets. You could for instance assign them a sub-asset ID within the prefab at import time, based on their IDs or order inside the source file.
> 1 votes

---
Tags: architecture, software-engineering, asset-management
---


# Question
Title: Combine flat and smooth shading with a single model geometry
I need to be able to switch between smooth and flat shading interactively. Is there a way to do this efficiently with a single geometry?

For example, smooth shading does not require duplicate vertices, whereas flat shading does. If I load an arbitrary model, would I need to rebuild the geometry such that each triangle has it's own set of 3 vertices, or is there a better way to accomplish this?

# Answer
> 3 votes
You need two different models, because flat-shaded and smooth-shaded models normals are different.

One of the ways is to generate 2 separate models and replace them with one another on demand.

Another way is to make a single model prepared for flat shaded render (all vertices unique) and replace only normals when switching to flat/smooth shading. For smooth-shaded normals that would mean unnecessary vertices duplication, but you will save memory on overall by keeping vertices/indices single.

Further unification is to store both normals per each vertex (x,y,z,nx1,ny1,nz1,nx2,ny2,nz2) and use required ones using a switch in the shader.

P.S. Smooth-shaded models might still need duplicate vertices along the sharp edges if there are smooth groups and/or smoothing degree threshold and/or discontinuous UVs.

# Answer
> 2 votes
One way of doing this is to when you are loading the model and creating the vertex layout. you could calculate a second set of normals. which would be the flat normals. Do so by taking the connecting triangles. and then put it into all the vertices. if there is more than one connecting pollygon, you could insert some indexing to make it easier to handle this. after that you can just switch shader paths.

# Answer
> 1 votes
This is an old question. However, in the interest of others seeking help with a similar problem, I believe I have a plausible solution:

You could have a model prepared for smooth shading (without the duplicate vertices) and present an option of emulating flat shading through your pixel shader. It is possible to calculate the normal at a given pixel by comparing it's position to that of others in its vicinity.

Precisely, a unit vector perpendicular to the surface containing the pixel is the normalized cross product of the partial derivatives of the position with respect to the screen-space x and y coordinates.

In HLSL, the derivatives are represented by the ddx() and ddy() functions:

```
normal = normalize(cross(ddy(position), ddx(position)));

```

The GLSL parallels to those should be dFdx() and dFdy().

# Answer
> 0 votes
You can also use "flat" interpolation and adjust your normals so that the first vertex normal of each triangle is appropriate for that particular face. That will likely require rotating your triangles so that each triangle can get a decent normal, and possibly splitting some verts if the only verts available are taken by faces with normals that are too far off.

---
Tags: opengl, shaders, glsl, lighting
---


title: If online games use permalinks

text:
# Question
Title: If online games use permalinks
I'm trying to figure out how to accurately capture the state of the web app by a URL, similar to something like https://jsfiddle.net/, where they create `https://jsfiddle.net/foobar123` a custom ID for the code you load, and you can share that with anyone and they can run the code. However, it's not a live, interactive thing, so it makes sense to do it that way.

But I'm wondering what games do. I don't really play games so I am not aware how browser-based games use the URL. I'm interested to know if, when you want to start back your game (I'm imagining WoW, though I've never played it), you just go to wow.com and click "start" or "join", and there is no URL involved at all. Or perhaps instead of that, you go to wow.com/123foobar to go to your last saved state, and it loads up the environment as it last was.

I'm not wondering for WoW specifically, just generally any game, if they use the URL to persist state, and if so, how (roughly speaking). Some simpler games like agar.io don't seem to use the URL; if you refresh, you lose your spot and have to start over.

I'm not really sure how a game could save the dynamically evolving state in a URL, which is why I'm interested to see if any of them do.

Another related example is a Collaborative Markdown Editor. I don't know if they dynamically change the URL though to reflect the state, I doubt it.

# Answer
> 1 votes
There are generally two ways to refer through the URL to a specific state

1. The state itself is stored in the URL. The State will be serialized and then encoded to a string of valid URL-Characters. Either Hexadecimal, or base 64 or something else
2. The state is stored in a database and only the unique `state-id` is appended to a url.

Note though, that not many games use those approaches, for multiple reasons:

* There is no reason to "share" state in games
* They don't allow you to save and restore, usually. If you die, or loose some item, or whatever, its gone for good. No way to "load a save" to get it back
* Games like WoW don't run in a browser.
* State can be bound to your account, which means providing your login data to the game allows the server to find your state
* Other data, configuration state for example, might be stored beside your game state in the providers databases or in cookies in your browser, no url-parameters required.
* Some games don't need state at all. Think of Counter-Strike for example. You join a server, play a few rounds and then leave. There is no "health" or "items" to save.

Above points generally apply to multiplayer games. Browser-based Singleplayer games might be different if they want to provide some sort of "checkpoint" or "save" without actually storing the values in your browser. Non-browser-based Singleplayer games store their state in files on your computer.

Text-Sharing websites and similar sites *do* store either the full text or the ID to a row in their database in the URL to allow you to share the text, image, blog-entry, ... easily, since this is usually the purpose of the website. (Most) Games don't need or want you to share the state.

---
Tags: browser-based-games, state, game-state
---


# Question
Title: Missing colors in Collada export from Blender
I've noticed something strange in a Collada DAE export from Blender. I've assigned Diffuse BDSF colors to 4 faces of a cube as shown here:

http://www.4shared.com/photo/\_hM04zywba/blendcube.html

It renders fine in Blender but after exporting to the following DAE file the diffuse and ambient color's RGB values stay the same for all materials. Shouldn't each material block in DAE have different values? Do I need to do something more in Blender to save the material info?

http://www.4shared.com/file/KdzuIwWGce/matcube.html

# Answer
Assuming your setup code remains unchanged, and after checking the source code for Assimp .NET, try this:

```
private void SetUpVertices()
{
    int count = oScene.MeshCount;
    vertexBuffers = new VertexBuffer[count]
    indexBuffers = new IndexBuffer[count]

    Mesh mMesh;
    // define objects for the meshes material and the color we are sampling
    Matrial mMaterial;
    Color4D color;
    for (int m = 0; m < count;m++)
    {
        mMesh = oScene.Meshes[m];
        vertices = new VertexPositionColor[mMesh.VertexCount];
        indices = new  short[mMesh.FaceCount*3];

        // load the material
        mMaterial = oScene.Material[mMesh.MaterialIndex];
        // get the diffuse color for this material
        color = mMaterial.ColorDiffuse;

        int i=0;
        foreach (Vector3D mVec in mMesh.Vertices)
        {
            // convert the Assimp Color4D data into an XNA Color
            vertices[i] = new VertexPositionColor(new Vector3(mVec.X, mVec.Y, mVec.Z), new Color(color.R, color.G, color.B, color.A));
            i++;
        }

        int f = 0;
        Face mFace;
        for (i = 0 ; i < mMesh.FaceCount*3 ; i=i+3)
        {
            mFace = mMesh.Faces[f];
            f++;
            indices[i] = (short)mFace.Indices[0];
            indices[i + 1] = (short)mFace.Indices[1];
            indices[i + 2] = (short)mFace.Indices[2];
        }

        vertexBuffer = new VertexBuffer(device, VertexPositionColor.VertexDeclaration, vertices.Length, BufferUsage.WriteOnly);
        vertexBuffer.SetData(vertices);

        indexBuffer = new IndexBuffer(device, typeof(short), indices.Length, BufferUsage.None);
        indexBuffer.SetData(indices);

        vertexBuffers[m] = vertexBuffer;
        indexBuffers[m] = indexBuffer;
    }
}

```

I've added comments so you can see the changes I've made, so hopefully you can understand how the added/changed code works, but basically I've loaded each meshes Material, grabbed the diffuse color from it, and instead of setting a default color, I've converted the Assimp Color4D to XNA Color inline when creating each vertex. Again, untested, so it may or may not work.
> 0 votes

# Answer
I Tried exporting from blender to MS word/Powerpoint, and I found that exporting using the option wavefront(.obj) helps because it crease an obj file and a an mtl file (texture file). Now in order to insure that when you open the obj file in MS word make sure the obj file and the mtl file are in the same folder.
> 0 votes

---
Tags: blender, collada, materials
---


# Question
Title: Why models that are far from camera not rendered correct in unity?
I am making a roguelike in unity and i came across a problem where models are far from the center of camera rendered weird like upper right enemy. I have added screnshot there are also camera settings. I tried changing field of view but it did not work. Does anyone know which option causes that distortion?

# Answer
As DMGregory mentioned above, Distortion happened because my free Aspect screen is so wide and unity uses the vertical field of view. That's why horizontal fov is more than 100 in my case. I have also found a simple GitHub page to calculate horizontal fov:

http://themetalmuncher.github.io/fov-calc/
> 2 votes

---
Tags: unity
---


title: Isometric coords to cartesian coords

text:
# Question
Title: Isometric coords to cartesian coords
I'm new to the tilemap feature of Unity, and I'm having a hard time with all those coords.

I created a new project, added an isometric tilemap and left all values to their default. In the Unity Editor (and in-game at runtime as well), the coordinates of the cells are like this:

This is pretty disturbing to me and it will be to most players (not programmers) too I guess.

I would like something like this:

However, I can't figure out how to do the transformation.

I tried this:

```
Vector3 currentWorldPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Vector3Int currentCellPos = _grid.WorldToCell(currentWorldPos); // This gives the coordinates as in the Unity Editor except for z
currentCellPos.z = 0; // Set z to 0 so the coordinates of the cell are exactly as in the Unity Editor
Vector3 cartesianCellPos = new Vector3((2 * currentCellPos.y + currentCellPos.x) / 2, (2 * currentCellPos.y - currentCellPos.x) / 2, 0); // Try to transform the Unity coordinates into cartesian coordinates: WRONG RESULT

```

But this calculation gives weird results, not what I expect at all.

Do you know how I could transform the Unity coordinates shown in the first screenshot into the coordinates shown in the second screenshot?

# Answer
The coordinate system you've chosen is not a Cartesian plane. The axis x=0 forms a zig-zag instead of a straight vertical line, because you've shifted the start point of alternating rows.

```
Vector2Int ToJaggedRow(Vector3Int isometric) {
    int row = isometric.x + isometric.y;
    int column = isometric.x - isometric.y;

    // Shift alternating rows by one.
    if((Mathf.Abs(row) & 1) == 1)
        column++;

    // All column numbers are now even numbers.
    // Divide by 2 to get them into consecutive integers.
    column /= 2;

    return new Vector2Int(column, row);
}

```
> 1 votes

---
Tags: unity, 2d, tilemap, isometric
---


# Question
Title: Redundant checks from spatial partitioning
A simple 2D grid partition system for collision detection divides space into equal-sized tiles. Colliders then map themselves to tiles with their bounding box in O(1) time. Collision detection only has to be performed between objects that occupy the same tile(s).

Collision detection is expensive so the more culled, the better. With a grid partitioning system, how are collisions culled when colliders share multiple tiles?

For example, Circle\_A and Circle\_B both sit on the edge between Tile\_1 and Tile\_2. Iterating both tiles would make collision detection between Circle\_A & Circle\_B run twice.

A global pair hashtable seems performance expensive since it has to be cleared every frame. Tracking pairs inside colliders takes a lot of memory. How do you mitigate redundant pairs when iterating through partition grid tiles?

# Answer
> how are collisions culled when colliders share multiple tiles?

Pairwise, as you suggest. You can do this in one of two ways: as a global dictionary which you suggested, or as a dictionary per unique neighbourhood.

**Global Approach**

You need to clear the entire map because you need the boolean "has this pair been checked against one another already" to be reset for each pair, each frame; yet it is likely that iterative, keywise `Dictionary` clearing would be slow. To solve this, you need:

* a backing array of values of that you *can* clear quickly, using fast approaches such as `Array.Clear()` or `Buffer.BlockCopy()` (see more here and further research elsewhere), pre-sized / pre-allocated to accomodate all unique pairs.
* a map implementation using that backing array, primarily by acting as an indirection table into it.
* a way to key into this map efficiently.

Pairwise keys are assembled in some deterministic manner using unsigned integer-type IDs that you'd have assigned to every body, e.g. lowest then highest. To assemble **key**, take e.g. two `ushort` IDs and order as:

`uint key = (uint)((highID << 16) | lowID); //2x 16-bit ushorts into a 32-bit uint.`

(`ushort` means you can support up to 65536 unique bodies. If you need more, use `uint` and make your key a `ulong`... but see caveat about capacity below.)

As for the map's **values**, those are just indices into the backing array on which you can perform fast clears. This is called *indirection* and, provided your data structures are well-allocated, should be very fast. If jumping between the backing array and the key set is slow, then I'd strongly suggest implementing your own interleaved or at least contiguously allocated map of keys and values, which has the possibility to be ultra-fast in terms of cache memory access. However, note for now that your cache ways should handle jumping between the map and the array, admirably, provided they are small enough (test, test, test).

If you could help it, you wouldn't want to do *any* management on the array except C#'s `memset`-style clears mentioned above. The backing array's order *does not change*; *no compaction occurs*; some entries are simply no longer referenced by the map (as its values, which are indices into the array) if the associated bodies are destroyed or invalidated.

You may rightly ask, "But that still leaves me clearing the map/dictionary?". Not quite: this map will remain unchanged most of the time, except where individual bodies are destroyed or invalidated, in which case you manage *only* the entries which pertain to them, at that point in time, rather than clearing the whole map constantly. In other words, the map is set up once, at the start, and then modified incrementally as the scene runs.

Caveat: even using (unsigned) `byte` keys (which support only 256 unique bodies) means you will need (using sigma function) 32k elements in your array to store all possible pairwise combinations; 10k unique bodies would require 50M entries, that is a 50mb array if you use 1 byte entries, or about 6 megabytes if using 1 bit to indicate your usual `bool`. So this approach is only useful for a relatively small numbers of bodies. As you said:

> A global pair hashtable seems performance expensive

More: it's now costly in terms of *space*, which from a cache-performance perspective is not ideal.

**Partitioned Approach**

But we're assuming above that we have to lump everything together, when in fact, the entire point of such partitioning schemes is to reduce which bodies can relate to which.

Let's now consider a world where there are 16x16 cells total. What matters to your solution is not every body relating to every other body *in the world*, but rather relating to every other body *in the local cell neighbourhood* (2x2). In an `n=16` wide cell neighbourhood, you'll note there are exactly `n-1=15` unique neighbourhoods (they overlap) per axis. This leads to `15x15=225` neighbourhoods.

Note that in spite of this number, we'd ideally still want a single, contiguously-allocated array for fastest possible access; but sadly we'd then be bound to doing considerable management of the array, since the contents of each cell is utterly dynamic, unlike the combined contents of all cells i.e. the world. This can certainly be automated, but off the top of my head, I'd think the management cost would be quite high.

So in this case, assuming you don't have an exorbitant number of neighbourhoods, I would suggest pre-allocating an individual `Dictionary` instance for every unique 2x2 neighbourhood in your world, and go from there. If, much later down the line, you feel their non-contiguity is costing you performance, you can look again at the above idea of multiple collections sharing a single contiguous backing array.

Caveat: Managing the multiple dictionaries may be costly; each frame you will need to update them from the changes just made to their constituent cells. Use a delta-based approach to minimise cost.

**Coarser Partitioning**

There is another option: to reduce the number of `Dictionary`s, don't use your usual 2x2 for the neighbourhoods but perhaps something larger like 4x4 or 8x8 roughly around the body's centroid; it seems worth a try at least to check performance at different body densities. Fewer, larger allocations this way *may* lead to better performance.

**Implementing your own map**

This is not trivial, but it is doable for an intermediate to advanced coder. You can go with regular hashing or perfect hashing if possible, which is fast but more complicated to implement and with certain limitations. Basically, perfect hashing eliminates the worst case cost of regular hashing, where there is a hash collision. With a single global backing array, this could be the fastest of all possible options, but also by far more time-consuming to implement.

**Final notes on such optimisations**

There are times when it is better to accept worst case performance as average case, and move ahead in other areas. It may be that none of the overheads that these optimisations (or any others) produce is justifiable in cases where bodies number less than the hundreds of thousands. And if you never reach that sort of body count, you may never see the gains. In other words, it is sometimes better to take the hit. Just be aware of this before you begin deep and complex implementations.

A pattern I've seen over and over in performing algorithmic optimisations and researching the optimisations of others: Sometimes a broad and sweeping optimisation introduces smaller inefficiencies, but the *overall* gain is so overwhelming that you are satisfied. You are then free to try to tackle those smaller inefficiencies if you like, but at each step this becomes more and more costly in terms of dev-time, for smaller and smaller gains. This is the point at which things stagnate for a period of time, and then whole new approaches are thought up, since we are otherwise stuck in a sort of black-hole of ever-decreasing gains.

Applied to your concrete case: When checking `n` bodies in a non-partitioned space, you have to do the pairwise check against your `Dictionary` every time, such that for all n^2 checks, you will do sigma-n actual collisions (I can explain why, if you like). But after the partitioning optimisation, you've *greatly* reduced that cost. However, partitioning *creates* the problem of cross-border, redundant checks in that neighbourhood. Having reduced the number of checks by orders of magnitude already, do those few surplus checks within each neighbourhood really make a difference? If so, is it worth reducing the cell/neighbourhood size to be even finer? If not - is it worth optimising a whole lot more for what may be vanishingly small gains? This is up to your own research and testing.
> 1 votes

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


title: How can I benefit when I don't use gpu?

text:
# Question
Title: How can I benefit when I don't use gpu?
I am trying to make a 3D game with C++, SDL, and OpenGL.

My program roughly looks like this:

control function has only CPU operations.

draw function has CPU and OpenGL functions operations.

I just randomly pick numbers.

How can I use GPU when program at control function?

Or I need to use? Do game engines use at every time? For example Unity, or Unreal Engine.

# Answer
> 2 votes
There are some games which actually use at least two threads - one for rendering and one for gameplay. While the rendering thread renders the current gamestate, the gameplay thread calculates the next.

But this software architecture is a lot more complex than it seems at first glance. If implemented poorly it can actually hurt performance.

One problem is that it is important to synchronize these two threads properly. You don't want the renderer to render half of the previous and half of the next state. Badly implemented thread synchronization can have worse performance than doing the same things in a single thread.

Another is that you need two copies of the gamestate (or at least of those components which are relevant for rendering). One copy for rendering and one copy the gameplay thread builds . And those two copies better don't get out of sync. A naive approach to this is to just create a whole new copy of the gamestate, but that means that you might copy a lot more data each update frame than you need to.

# Answer
> 2 votes
The classic standard answer for single-threaded games is to render first, then update game logic, and only then call your `SwapBuffers`.

```
while (running) {
  draw();
  update_game_logic();
  GL_SwapBuffers();
}

```

If you render first and then update game logic, the GPU can continue processing the submitted rendering commands while the game logic is updated on the CPU.

It's worth noting that really the important part there is to keep your `draw` and `SwapBuffers` calls far apart from each other. For example, if you really want/need to do your game logic in the beginning of the loop, you can actually `SwapBuffers` *before* `draw` (so you're syncing the *previous frame* before rendering the next frame).

```
while (running) {
  update_game_logic();
  GL_SwapBuffers();
  draw();
}

```

---
Tags: opengl, c++, sdl, game-loop
---


# Question
Title: MouseLook Script "Pops" back to the last value when the script is enabled after being disabled or destroyed
I am trying to get a problem with a MouseLook script that controls my camera and a LookatGameObject script that also controls my camera when I want to force the player to look in a certain direction under control, but still no luck. I have identified where the issue is - `Line 43, transform.localEulerAngles = new Vector3(-rotationY, rotationX, 0);` is the the method that sets the X Axis, makes it "POP" back to the last value when the script is enabled (I have even destroyed the component and then added the component when needed but the same result) can anyone see a solution for this?

The MouseLook Script:

```
 using UnityEngine;
 using System.Collections;

 [AddComponentMenu("Camera-Control/Mouse Look")]
 public class MouseLook : MonoBehaviour
 {

     public enum RotationAxes { MouseXAndY = 0, MouseX = 1, MouseY = 2 }
     public RotationAxes axes = RotationAxes.MouseXAndY;
     public float sensitivityX = 15F;
     public float sensitivityY = 15F;

     public float minimumX = -360F;
     public float maximumX = 360F;

     public float minimumY = -60F;
     public float maximumY = 60F;

     float rotationY = 0F;

     void Update()
     {
         if (axes == RotationAxes.MouseXAndY)
         {
             float rotationX = transform.localEulerAngles.y + Input.GetAxis("Mouse X") * sensitivityX;

             rotationY += Input.GetAxis("Mouse Y") * sensitivityY;
             rotationY = Mathf.Clamp(rotationY, minimumY, maximumY);

             transform.localEulerAngles = new Vector3(-rotationY, rotationX, 0);
         }
         else if (axes == RotationAxes.MouseX)
         {
             transform.Rotate(0, Input.GetAxis("Mouse X") * sensitivityX, 0);
         }
         else
         {
             rotationY += Input.GetAxis("Mouse Y") * sensitivityY;
             rotationY = Mathf.Clamp(rotationY, minimumY, maximumY);

             transform.localEulerAngles = new Vector3(-rotationY, transform.localEulerAngles.y, 0);
         }
     }
  }

```

Here is my LookAtGameObjectScript:

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

 public class LookAtGameObject : MonoBehaviour
 {
     public Transform target;
     public float speed = 5f;

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

         Vector3 direction = target.position - transform.position;
         Quaternion rotation = Quaternion.LookRotation(direction);
         transform.rotation = Quaternion.Lerp(transform.rotation, rotation, speed * Time.deltaTime);
     }
     }

```

And And my method for turning off MouseLook and Turning on LookAtGameObject:

```
private IEnumerator LookAtGameObject()
     {

         GameObject.FindWithTag("MainCamera").GetComponent<MouseLook>().enabled = false;
         GameObject.FindWithTag("MainCamera").GetComponent<LookAtGameObject>().enabled = true;

         yield return new WaitForSeconds(8f);

         GameObject.FindWithTag("MainCamera").GetComponent<LookAtGameObject>().enabled = false;
         GameObject.FindWithTag("MainCamera").GetComponent<MouseLook>().enabled = true;

         yield return null;
     }

```

# Answer
It looks like all you need is an OnEnable method to update the internal state when the script is switched back on:

```
float lastEnabledTime = float.negativeInfinity;
float limitEaseSeconds = 3f;

void OnEnable() {
    rotationY = transform.localEulerAngles.y;
    lastEnabledTime = Time.time;
}

```

Saving the last enabled time lets us gradually re-introduce our rotation limits inside Update, by first calculating our current limits for this frame:

```
float limitBlend = Mathf.Clamp01((Time.time - lastEnabledTime)/limitEaseSeconds);

float currentMin = Mathf.Lerp(-180, minimumY, limitBlend);
float currentMax = Mathf.Lerp(180, maximumY, limitBlend);

...

rotationY = Mathf.Clamp(rotationY, currentMin, currentMax);

```
> 0 votes

---
Tags: unity, camera
---


# Question
Title: Calculate required position to keep object centered when camera is rotated
I always want to keep an object in the center of view of a camera. When the camera's rotation X value is -45, the object should still be centered.

Therefore I need to calculate the new position of the camera.

How could the "required camera position Y value" be calculated?

Thank you.

# Answer
```
// Track the object we want to keep centered.
public transform centeredObject;

void LateUpdate() {
    // Cache how far we are from the object before we do anything to the camera.
    // (This could instead be a constant distance you've set via an Inspector variable)
    float cameraDistance = Vector3.Distance(transform.position, centeredObject.position);

    // Apply whatever change you want to make to the camera's orientation.
    transform.rotation = ComputeNewCameraRotation();

    // Calculate its new position by "backing up" the desired distance
    // from your centered object, along the camera's new look direction.
    transform.position = centeredObject.position - cameraDistance * transform.forward;
}

```
> 1 votes

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


# Question
Title: Python/java framework for developing artificial intelligence for board games like Diplomacy/Risk
I am trying to pick a python/java framework for developing artificial intelligence for board games like Diplomacy/Risk for research purpose. I am specifically looking for multiplayer, multiple-round games without any dominant strategies that require players to cooperate as well as non-cooperate at certain times.

The idea of the research is to not build the game itself or the AI bot, but to discover novel methods for game theory, specifically to deceive other players- bots or humans.

This research is specifically based on Deceptive Artificial Intelligence. Please share any frameworks(game code with stubs for decision making) that you may know about. It would be a lot of help for my work.

If you have any ideas about some other game that I can pick, please mention that as well.

I have tried a few frameworks but the lack of documentation is extremely annoying and I haven't been able to move forward in the process.

Thanks and Regards!

# Answer
After trying out a few frameworks, I decided to go with PyRisk. The code can be found here: https://github.com/chronitis/pyrisk

Thanks and Regards Uttakarsh Tikku
> -1 votes

---
Tags: ai, game-theory
---


# Question
Title: Should I make a FPS game on Fixed Function Pipeline or Programmable Pipeline OpenGL?
I have a “FPS” game I have programmed in Fixed Function Pipleline and one made in Programmable pipeline OpenGL. While the programmable pipeline has lots of weird things that you can edit, it does not have glLoadIdentity that I need for the gun to be attached to the camera. There is little to no information on this subject and most of the information that I can find is in the fixed function pipeline rather than the programmable one. Keep in mind that with the fixed function pipeline, I can just use the glloadidentity function and attach it then move on to another thing. On the programmable one, I don’t know how to do this, so I have spent a whole week looking up how I can do it.

Should I just use the fixed function pipeline one and abandon the programmable pipeline?

What shall I do?

Thanks!

# Answer
> 1 votes
In OpenGL terms, "programmable pipeline" can actually mean a lot of things. For example, it might mean one of:

* OpenGL 1.5 with the GL\_ARB\_vertex\_program and GL\_ARB\_fragment\_program extensions.
* OpenGL 2.0 or 2.1 with the earliest versions of GLSL.
* Modern OpenGL (3.x or higher) with a compatibility context.
* Modern OpenGL (3.x or higher) with a core context.
* Some other GL version with vendor-specific extensions.

On the other hand, glLoadIdentity is actually *nothing whatsoever to do with the programmable pipeline*. Instead, it's part of the OpenGL matrix stack, and absolutely **is** available in many cases when using the programmable pipeline.

In fact, the only case where the matrix stack is not available is in modern OpenGL with a core context. *In every other case, so long as you access the built-in matrix uniforms in your shaders, you absolutely can combine the matrix stack with the programmable pipeline*.

---
Tags: opengl
---


# Question
Title: Issue with script recognizing particular z-axis rotation angles in Unity
I'm trying to make a simple flowing pipe-style rotation puzzle, but having issues getting Unity to properly recognize certain angles of rotation. My rotation script for the pieces:

`private void OnMouseDown()
 {
 if (!GameControl.winState)
 transform.Rotate(0f, 0f, 90f);
 }`

If the value of the z rotation is set to 90 or -90, the game works fine. However, if I try a different value such as 60 or 30 (and have corresponding 60 or 30 shifts to the puzzle hexes' z rotations to scramble the puzzle), the game fails to note a win state. Here is the game control script:

```
public Transform[] hex;
public GameObject successLight;

public static bool winState;

void Start () {
    successLight.SetActive(false);
    winState = false;
}

void Update ()
{
    if (hex[0].rotation.z == 0
        && hex[1].rotation.z == 0
        && hex[2].rotation.z == 0
        && hex[3].rotation.z == 0
        && hex[4].rotation.z == 0)
    {
        Debug.Log("PuzzleSolved!");
        winState = true;
        successLight.SetActive(true);
    }
}

```

I've also tried making the rotation using Euler angles, but still experienced the same problem. Is this an issue with the rotation not being exact and therefore unable to meet the conditions? Checking the inspector as the game runs, it looks as if even when the hexes all get to the proper z rotation of 0, the win state still isn't triggering when the rotation moves at a degree other than 90. Any help would be appreciated, feeling very confused at the moment.

# Answer
`hex[0].rotation.z == 0`

Here you're looking for `z` to be a rotation angle, but it's not. A `Transform`'s `.rotation` property is a quaternion, not an Euler angle triplet. Picking out one of the four components of a quaternion individually is rarely meaningful.

You could query the `eulerAngles` or `localEulerAngles` properties instead to get angle triplets, but I'd recommend getting out of the habit of picking out individual angles for game calculations - it leads many devs to avoidable errors, because our expectations of how the angles should behave are not well-calibrated to how they actually do.

Instead a safer method might be this:

```
// Expose the solution angle values as an Inspector-editable array.
public float[] solutionAngles = new float[]{0,0,0,0,0};
Quaternion[] solutionRotations;

void Start() {
    // Cache our solutions as quaternion rotations.
    solutionRotations = new Quaternion[solutionAngles.Length];
    for(int i = 0; i < solutionAngles.Length; i++)
        solutionRotations = Quaternion.Euler(0, 0, solutionAngles[i]);

    successLight.SetActive(false);
    winState = false;
}

void Update() {
    // If any hex doesn't match its solution rotation, early-out.
    for(int i = 0; i < solutionRotations.Length; i++) {
        if(hex[i].rotation != solutionRotations[i])
            return;
    }

    // If we get here, then all solution rotations match.
    Debug.Log("PuzzleSolved!");
    winState = true;
    successLight.SetActive(true);
}

```

Doing it this way, our code is insensitive to differences in angular notation - like wither to call an angle -90 or +270 - and also has a little wiggle room for floating point rounding, since the quaternion `==` looks for an approximate match.
> 0 votes

---
Tags: unity, rotation
---


# Question
Title: Changing text occurs error: move initialization code to the Awake or Start function
I have GameManager class that has Log method:

```
using UnityEngine;
using UnityEngine.UI;

public class GameManager: MonoBehaviour {
    public static GameManager Instance;
    [SerializeField] private ScrollRect m_GUIConsoleContainer;
    [SerializeField] private UnityEngine.UI.Text m_GUIConsole;
    ...

    void Awake() {
        Instance = this;
    }

    ...

    public void Log(string message) {
        m_GUIConsole.text = m_GUIConsole.text + message + "\n";
    }
}

```

GameManager class has static instance, so I can invoke Log method in anywhere like this:

```
GameManager.Instance.Log("Helloworld");

```

However it works only first time. After invoke Log again, Unity gives me this error message:

> get\_isActiveAndEnabled can only be called from the main thread. Constructors and field initializers will be executed from the loading thread when loading a scene. Don't use this function in the constructor or field initializers, instead move initialization code to the Awake or Start function. UnityEngine.UI.Text:set\_text(String)

I assigned reference of m\_GUIConsoleContainer and m\_GUIConsole in inspector, but I don't get it what this means and why it happens. Just using Debug.Log() or print() works without any error.

How should I avoid this error message? Using Unity 2018.2.1f1.

p.s. Error coming from here, another class called NetworkManager:

```
void OnReceivedBytes(IAsyncResult result) {
    try {
        if(m_Socket == null) {
            return;
        }

        int resultLength = m_Socket.EndReceive(result);

        if(resultLength == 0) {
            Shutdown();
            return;
        }

        Log("Received: " + m_RecvBuffer[0]);  <<- Error coming from here
        ...
    }
    ...
}

```

And this is where it call OnReceivedBytes:

```
using UnityEngine;
using UnityEngine.UI;
using System;
using System.Collections;
using System.Net;
using System.Net.Sockets;

public class NetworkManager: MonoBehaviour {
    private Socket m_Socket;

    void Start() {
        m_Socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        m_Socket.Connect("localhost", 1337);

        if(m_Socket.Connected) {
            Log("Connected.");

            m_Socket.BeginReceive(
                m_RecvBuffer,
                0,
                m_RecvBuffer.Length,
                SocketFlags.None,
                new System.AsyncCallback(OnReceivedBytes),
                null
            );
        }
        else {
            Log("Failed to Connect.");
        }
    }

    ...
}

```

# Answer
> get\_isActiveAndEnabled can only be called from the main thread.

This tells us somehow we've tried to call the logging method from a thread that isn't the main thread. This could lead to nasty race conditions if the UI layout on the main thread is busy building the vertices for our text string, and another thread modifies the string out from under it, so this error catches the cross-thread access before it can lead to subtle and hard to reproduce bugs.

To fix this, we'll need a way for code on other threads to log messages without grabbing hold of the text object directly. For instance, we could have them write to a queue of messages that the `GameManager` can safely pump into the text field on its next update. To make sure we don't have contention on this queue, we could add our own mutex locking code, or we can use the standard `ConcurrentQueue` which handles thread-safety internally:

```
using System.Collections.Concurrent;

...

ConcurrentQueue<string> m_queuedLogs = new ConcurrentQueue<string>();

void ThreadsafeLog(string message) {
    m_queuedLogs.Enqueue(message);
}

void Update() {
    string message;
    while(m_queuedLogs.TryDequeue(out message)) {
        m_GUIConsole.text = m_GUIConsole.text + message + "\n";
    }
}

```

Now code that's executing on other threads - like in AsyncCallback methods - can log its messages via `ThreadsafeLog` and they'll be added to the GUI console's text next frame.
> 1 votes

---
Tags: unity, gui
---


# Question
Title: How can I make natural rain drops on screen?
I'm trying to make rain effect drop with metaballs and trail on screen.I find a clue in shadertoy but I didn't understand how implemented:

https://www.shadertoy.com/view/ltffzl

unfortunately it have many math calculations and i can't use it in unity because it produces a lag.obviously I should use textures but how can I have trail effect?!

my idea is using a texture and trail renderer for droping but how can I have metaballs effect?

---

# Update

I could Implement Metaballs by This Article

https://github.com/smkplus/RainFX/tree/master

but I haven't Idea about trail

# Answer
you can make this effect by following the steps below:

# Particle

# RenderTextuer

you can store result by using RenderTexture. this is example of multipass in shadertoy:

https://www.shadertoy.com/view/ltccRl

> iñigo quilez: Shadertoy uses multiple passes, one per "Buffer". As the name indicates, this passes store the results in a buffer. A buffer is just a texture. Unity will let you render to textures too.

I created a camera to Rendering particles to RenderTexture:

# GrabPassing

you can grab pass for applying Distortion

I explained it in this post:

How can I replicate Quantum Break's distortion particle effect?

# Blur

by using alpha in color over Lifetime we have simple blur

to get better result it's better to use simple blur , but how we achive blur?

**Convolution matrix**

In image processing, a kernel, convolution matrix, or mask is a small matrix. It is used for blurring, sharpening, embossing, edge detection, and more. This is accomplished by doing a convolution between a kernel and an image.

for more details, please follow this link

```
 Shader "Smkgames/Convolution"
    {
        Properties
        {
            _MainTex ("Texture", 2D) = "white" {}
            [Enum(kerEdgeDetectionA,1,kerEdgeDetectionB,2,kerEdgeDetectionC,3,kerSharpen,4,kerBoxBlur,5)]
            _Kernel("Kernel", Float) = 1
        }
        SubShader
        {
            // No culling or depth
            Cull Off ZWrite Off ZTest Always

            Pass
            {
                CGPROGRAM

                #pragma vertex vert
                #pragma fragment frag

                #include "UnityCG.cginc"

                struct appdata
                {
                    float4 vertex : POSITION;
                    float2 uv : TEXCOORD0;
                };

                struct v2f
                {
                    float2 uv : TEXCOORD0;
                    float4 vertex : SV_POSITION;
                };

                v2f vert (appdata v)
                {
                    v2f o;
                    o.vertex = UnityObjectToClipPos(v.vertex);
                    o.uv = v.uv;
                    return o;
                }

                sampler2D _MainTex;
                float4 _MainTex_TexelSize;

                float3x3 GetData(int channel, sampler2D tex, float2 uv, float4 size)
                {
                    float3x3 mat;
                    for (int y=-1; y<2; y++)
                    {
                        for(int x=-1; x<2; x++)
                        {
                            mat[x+1][y+1]=tex2D(tex, uv + float2(x*size.x, y*size.y))[channel];
                        }
                    }
                    return mat;
                }
                float3x3 GetMean(float3x3 matr, float3x3 matg, float3x3 matb)
                {
                    float3x3 mat;
                    for (int y=0; y<3; y++)
                    {
                        for(int x=0; x<3; x++)
                        {
                            mat[x][y] = (matr[x][y] + matg[x][y] + matb[x][y]) / 3.0;
                        }
                    }
                    return mat;
                }

                float Convolve(float3x3 kernel, float3x3 pixels, float denom, float offset)
                {
                    float res = 0.0;
                    for (int y=0; y<3; y++)
                    {
                        for(int x=0; x<3; x++)
                        {
                            res += kernel[2-x][2-y]*pixels[x][y];
                        }
                    }

                    return  res;
                }

                float _Kernel;

                fixed4 frag (v2f i) : SV_Target
                {

                    float3x3 kerEdgeDetectionA = float3x3 (    0.0,  0,  -1.0,
                                                        1.0,  0,  -1.0,
                                                        0.0,  1.0,  0.0);

                   float3x3 kerEdgeDetectionB = float3x3 (0.0,  1.0,  0.0,
                                                 1.0, -4.0,  1.0,
                                                 0.0,  1.0, 0.0);

                   float3x3 kerEdgeDetectionC = float3x3 (-1.0, -1.0, -1.0,
                                                    -1.0,  8.0, -1.0,
                                                    -1.0, -1.0, -1.0);

                   float3x3 kerSharpen = float3x3 (0.0, -1.0, 0.0,
                                                    -1.0, 5.0, -1.0,
                                                    0.0, -1.0, 0.0);

                    float3x3 kerBoxBlur = (1.0/9.0)*float3x3 (    1.0,  1.0,  1.0,
                                                        1.0,  1.0,  1.0,
                                                        1.0,  1.0,  1.0);

                    float3x3 kernelSelection;
                if(_Kernel == 1){
                kernelSelection = kerEdgeDetectionA;
                }else if(_Kernel == 2){
                kernelSelection = kerEdgeDetectionB;
                }else if(_Kernel == 3){
                kernelSelection = kerEdgeDetectionC;
                }else if(_Kernel == 4){
                kernelSelection = kerSharpen;
                }else if(_Kernel == 5){
                kernelSelection = kerBoxBlur;
                }

                float3x3 matr = GetData(0, _MainTex, i.uv, _MainTex_TexelSize);
                float3x3 matg = GetData(1, _MainTex, i.uv, _MainTex_TexelSize);
                float3x3 matb = GetData(2, _MainTex, i.uv, _MainTex_TexelSize);
                float3x3 mata = GetMean(matr, matg, matb);

                // kernel
               float4 gl_FragColor = float4(Convolve(kernelSelection,matr,1.0,0.0),
                                            Convolve(kernelSelection,matg,1.0,0.0),
                                            Convolve(kernelSelection,matb,1.0,0.0),
                                            1.0);

                return gl_FragColor;
            }
            ENDCG
        }
    }
}

```

**Boxblur**

> A box blur (also known as a box linear filter) is a spatial domain linear filter in which each pixel in the resulting image has a value equal to the average value of its neighboring pixels in the input image. It is a form of low-pass ("blurring") filter. A 3 by 3 box blur can be written as matrix
>
> https://en.wikipedia.org/wiki/Box\_blur

```
Shader "Smkgames/Simple Box Blur"
{
    Properties
    {
        _MainTex ("Texture", 2D) = "white" {}
    }
    SubShader
    {
        Blend SrcAlpha OneMinusSrcAlpha

        Pass
        {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag

            #include "UnityCG.cginc"

            struct appdata
            {
                float4 vertex : POSITION;
                float2 uv : TEXCOORD0;
            };

            struct v2f
            {
                float2 uv : TEXCOORD0;
                float4 vertex : SV_POSITION;
            };

            v2f vert (appdata v)
            {
                v2f o;
                o.vertex = UnityObjectToClipPos(v.vertex);
                o.uv = v.uv;
                return o;
            }

            sampler2D _MainTex;
            float4 _MainTex_TexelSize;

            float4 box(sampler2D tex, float2 uv, float4 size)
            {
                float4 c = tex2D(tex, uv + float2(-size.x, size.y)) + tex2D(tex, uv + float2(0, size.y)) + tex2D(tex, uv + float2(size.x, size.y)) +
                            tex2D(tex, uv + float2(-size.x, 0)) + tex2D(tex, uv + float2(0, 0)) + tex2D(tex, uv + float2(size.x, 0)) +
                            tex2D(tex, uv + float2(-size.x, -size.y)) + tex2D(tex, uv + float2(0, -size.y)) + tex2D(tex, uv + float2(size.x, -size.y));

                return c / 9;
            }

            float4 frag (v2f i) : SV_Target
            {
                float4 col = box(_MainTex, i.uv, _MainTex_TexelSize);
                return col;
            }
            ENDCG
        }
    }
}

```

# Repetition

you can use Rendertexture to store previous frame.so you can grab previous frame then blur. by repeating this you achieve blur.

# Normal

```
float4 distortion = tex2D(_MainTex,i.uv);
float3 distortionNormal = UnpackNormal(distortion);

```

# Conclusion

Final shader:

```
Shader "Smkgames/BrokenGlass3D"
{
    Properties{
        _MainTex("MainTex",2D) = "white"{}
        _NormalIntensity("NormalIntensity",Float) = 1
        _Alpha("Alpha",Float) = 1
    }
    SubShader
    {
Tags {"Queue"="Transparent" "RenderType"="Transparent"}
Blend SrcAlpha OneMinusSrcAlpha

        GrabPass
        {
            "_GrabTexture"
        }

        Pass
        {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag

            #include "UnityCG.cginc"

            struct appdata
            {
                float4 vertex : POSITION;
                float2 uv : TEXCOORD0;
                float2 grabPos : TEXCOORD1;
                float3 normal :NORMAL;
            };

            struct v2f
            {
                float2 uv : TEXCOORD0;
                float4 grabPos : TEXCOORD1;
                half3 worldNormal :TEXCOORD2;
                float4 vertex : SV_POSITION;

            };
            sampler2D _MainTex;
            float _Intensity,_Alpha;

            v2f vert (appdata v)
            {
                v2f o;
                o.uv = v.uv;
                o.vertex = UnityObjectToClipPos(v.vertex);
                o.grabPos = ComputeGrabScreenPos(o.vertex);
                o.worldNormal = UnityObjectToWorldNormal(v.normal);
                return o;
            }

            sampler2D _GrabTexture;
            float _NormalIntensity;

            fixed4 frag (v2f i) : SV_Target
            {
                float4 distortion = tex2D(_MainTex,i.uv);
                float3 distortionNormal = UnpackNormal(distortion);
                distortionNormal.xy *= _NormalIntensity;
                normalize(distortionNormal);
                fixed4 col = tex2Dproj(_GrabTexture, i.grabPos+float4(distortionNormal.rgb,0));
                return col;
            }
            ENDCG
        }
    }
}

```

without using alpha in color over Lifetime:

by using alpha in color over Lifetime:

**Source is available:**

https://github.com/smkplus/RainDrop

# There's more!

also you can make Ripples

**Useful Links**

https://80.lv/articles/breakdown-animated-raindrop-material-in-ue4/

https://seblagarde.wordpress.com/2013/01/03/water-drop-2b-dynamic-rain-and-its-effects/
> 9 votes

# Answer
I think you should think about the effect as "calculate a map of where the water is" + "generate a normal vector from that map and use it to offset a background texture lookup".

Breaking down what your example shadertoy does, it just calculates a "trail" to show where the defogging happens:

Calculates the normals of the circular raindrops,

and uses that normal map to offset a texture lookup to fake refraction.

If you want the trails done via post-processing in a shader, you should just create the "trail" shape in the shader using some algebra. For example, in the following function, I've overlaid a "wobbly path" and a taper at the head and tail to get

```
float trailDrop(vec2 uv, vec2 id, float t) {
    // wobbly path
    float wobble = 0.5 + 0.5
        * cos(120.0 * uv.y)
        * sin(50.0 * uv.y);
    float v = 1.0 - 10.0 * abs(uv.x - 0.5 + 0.2 * wobble);
    // head
    v *= clamp(30.0 * uv.y, 0.0, 1.0);
    v *= clamp( uv.y + 7.0 * t - 0.6, 0.0, 1.0);
    // tail
    v *= clamp(1.0 - uv.y - pow(t, 2.0), 0.0, 1.0);
    return clamp(v * 10.0, 0.0, 1.0);
}

```

Here's a rough POC in shadertoy -- https://www.shadertoy.com/view/XlBfz1 demonstrating creating a set of raindrop trails. It looks grainy at small resolutions due to the derivatives resolution but should look better if you fullscreen it.

Edit: Added an example with overlaid raindrops

Left as an exercise to the reader:

1) Add the small round drops. for inspiration, look at the `StaticDrops` function in your original shadertoy example.

2) Add in high-quality normal calculations. As the `#define CHEAP_NORMALS` option in your original shadertoy example implies, the builtin dFdx is a low-fidelity approximation and you can get better results by manually calculating the derivatives (at the cost of calculating the function 3 times).

3) Randomizing the spacing between the columns. You can widen the columns and then modify the `uv.x - 0.5 + 0.2 * wobble` bit to add a random offset on the x axis. You'll also probably want to take a page out of the original example once again and layer a couple different sized layers of streams on top of each other to get a less uniform look.
> 13 votes

# Answer
There was actually a question about this years ago, but it doesn't pertain to Unity at all (unfortunately). If you look at slide 57 of the linked presentation, they mention a grid-based approach.

There's a somewhat related question on Physics SE that you might find interesting. The link to droplet.pdf in the linked question is broken, but it's still on the Wayback Machine. It goes into some of the mathematics of water running off a few types of surfaces. Droplets prefer to travel in paths previously used by earlier raindrops, for instance (see p926).

You could probably just model the heads and tails of each "raindrop" and allowing it to zig and zag a bit. When two elongated raindrops collide, I suppose you could have them combine into a larger and faster-moving raindrop. The volume of water stays the same. It's just being moved and shaped by the forces of gravity, adhesion to the glass, and cohesion.
> 1 votes

---
Tags: unity, shaders, shaderlab
---


# Question
Title: How can I add array of components to a new gameobject?
I use Getcomponents to get all components from existing gameobject:

```
Component[] components = go.GetComponents(typeof(MonoBehaviour));

```

And I want to add them now to another gameobject:

```
for (int i = 0; i < components.Length; i++)
                {
                    var comp = components[i];
                    newObject.AddComponent<comp>();
                }

```

components is type Component\[\]

But when I try to type components inside the AddComponent\<\> the variable components not exist. Tried then to make the comp variable but can't type it inside the \<\> either.

# Answer
Solution: newObject.AddComponent(components\[i\].GetType());
> 1 votes

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


# Question
Title: How do I make a gun alignment to camera matrix in OpenGL GLSL?
I am trying to program a FPS game with OpenGL.

I am using 3D eight the OpenGL 3.3 programmable pipeline.

I have a gun and a camera that I loaded.

When I load all of the assets for the game, I put everything int a 4x4 matrix, as it is compatible with the view matrix.

I set the corresponding matrix for the model equal to all the needed variables, then I use another variable that I defined in a header file to draw the actual model...

I did some searching because I do not have the code with me, and the closest I could find is learnopengl’s model loading tutorial as that is the most similar.

What I have tried; I have tried multiplying the matrix for the gun’s world info, which I will call the model view matrix (such as position and scale) times the view matrix. I have also tried doing the same but multiplying the model view times the inverse of the normal view matrix.

I already set the guns position equal to the camera’a position, but when I run the application and try to move around, the gun still moves away from the camera.

I knew a way of how to fix this in OpenGL 1.1 by using glLoadIdentity, which is now deprecated with the core version of OpenGL 3.\*.

When i try to set the two matrices equal, I get different results because the gun doesn’t move at all.

When I move the camera with the inverse of view times gun, it moves away from the camera...

I learned about the inverse matrix thing from here: https://forums.khronos.org/showthread.php/81932

My matrixes are also set up the same. The gun model view * inverse(view matrix) has worked the best... this link is where I found it.

# Answer
> 2 votes
You need to transform the vertices of the gun with the **Model • View • Projection** matrix.

The thing to know is, that the View matrix, is just the inverse of the Camera transformation matrix.

So if you have a matrix that positions and orients your camera in the world, its inverse will be your view matrix.

You also have a matrix that positions and orients your gun.

In your FPS game, you will want these matrices to be quite similar: looking into the same direction, and maybe the camera slightly above and behind the gun.

Once you have multiplied the gun matrix, with the inverse of the camera matrix and then with the projection matrix, you have the resulting matrix that you want to feed into your shader using the glUniformMatrix4fv() call.

In pseudo code:

```
Mat44 viewmat = cammat.invert();
Mat44 mvp = projmat * viewmat * gunmat;
glUniformMatrix4fv( mvpUniform, 1, false, mvp );
draw_gun();

```

NOTE: Depending on your math library, you may have to post-multiply or pre-multiply your matrices. In my code I have multiply them as proj * view * model. If it doesn't work for you, reverse the order.

Then, in your vertex shader, you multiply the vertex position with this matrix.

```
#version 150
in mediump vec4 position;
...
uniform highp mat4 modelviewprojmat;
...
void main()
{
    gl_Position = modelviewprojmat * position;
    ...

```

Lastly, if you need to know how to build a projection matrix, look at the gluPerspective() call.

---
Tags: opengl, game-design, game-mechanics
---


# Question
Title: How to store Unity Component after destroying a GameObject
I have a collectible item, which I can put into the inventory. Its GameObject has a InventoryItem script attached in which I want to set all parameters needed for correct display in the inventory. Here is the C# code:

**InventoryItem.cs**

```
public class InventoryItem : MonoBehaviour {
    public bool collectible = true;
    public string name;
    public Sprite sprite;
}

```

Part of **ItemCollectingController.cs** responsible of passing data to InventoryController

```
if (Input.GetButtonDown("Use")) {
    InventoryController inventory = GameObject.FindGameObjectWithTag("Inventory").GetComponent<InventoryController>();
    inventory.AddItem(target.GetComponent<InventoryItem>());
    Destroy(target);
    Debug.Log("Added to inventory");
}

```

And the important part of **InventoryController.cs**

```
public List<InventoryItem> items;
public void AddItem(InventoryItem item) {
    items.Add(item);
}

```

When collecting the item, the GameObject is destroyed and so is the reference in the InventoryController. The `items` List keeps a missing component. What can I do about that?

# Answer
> 1 votes
A `Component` must be attached to a `GameObject`. If you have data that needs to outlive its `GameObject`, then it should not be built into a `Component`.

Consider instead creating your inventory items as `ScriptableObject`s - these are persistent data objects that live in your assets folder. You can still edit them in the inspector, but they have an identity of their own not dependent on any particular `GameObject` or `Scene`.

eg.

```
// This line lets you create items via the right-click / Asset -> Create menu
[CreateAssetMenu(filename = "NewItem", menuName="Inventory Item")]
public class InventoryItem : ScriptableObject {
    public bool collectible = true;
    public string name;
    public Sprite sprite;
}

```

Then to attach this to an in-world collectible, make a distinct component for the `GameObject` that houses it:

```
public class CollectibleItem : MonoBehaviour {
    public InventoryItem item;
}

```

Now when you collect the item, you can ask the `CollectibleItem` component to tell you which item archetype to add to your inventory. Once it's done that, you can destroy the `CollectibleItem` along with its `GameObject` safely - it just held a reference to the `InventoryItem`, but that item can keep living on after the collectible is gone.

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


# Question
Title: D3D12CreateDevice(pAdapter, D3D_FEATURE_LEVEL_12_0) ISSUE
I'm getting this error when I compile this code.

D3D12CreateDevice(pAdapter, D3D\_FEATURE\_LEVEL\_12\_0, IID\_PPV\_ARGS(&pDevice)). Error! No such Interface supported

I've got a rtx 2060 GPU installed in my computer. All my GPU drivers are up to date. I've got the windows 10 version 1803(OS Build 17134.590) I've got visual studio 2017 installed and used to compile my code.

Here is the code I'm trying to compile. https://github.com/acmarrs/IntroToDXR

What, in the hell is this error man its so stupid. I've been stuck for over 6 damn hours man. Any help, much appreciated.

# Answer
Your card & driver may support DirectX 12 (the API) but may not support the Direct3D Hardware Feature Level 12.0 feature level. Most of the sample code for DirectX 12 uses `D3D_FEATURE_LEVEL_11_0` as the minimum required hardware because that's the one that's most often supported.

See Anatomy of Direct3D 12 Create Device and Microsoft Docs
> 0 votes

---
Tags: directx12
---