# Question
Title: How can I loop over waypoints to move all the objects between them?
```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Waypoints : MonoBehaviour
{
    public enum RotationMode
    {
        Normal, Curved
    }

    public GameObject objectToDuplicate;
    public Transform[] waypoints;
    public float movingSpeed;
    public bool randomSpeed = false;

    private GameObject[] prefabsToMove;

    private void Start()
    {
        prefabsToMove = GameObject.FindGameObjectsWithTag("FrameLine");
        DuplicatePrefabEffects(prefabsToMove.Length);
    }

    private void DuplicatePrefabEffects(int duplicationNumber)
    {
        for (int i = 0; i < duplicationNumber; i++)
        {
            var go = Instantiate(objectToDuplicate);
            go.tag = "Duplicated Prefab";
            go.name = "Duplicated Prefab";
        }
    }

    private void WaypointsAI()
    {
        for (int i = 0; i < waypoints.Length; i++)
        {
            if (randomSpeed)
            {
                movingSpeed = Random.Range(1, 20);
            }
            prefabsToMove[i].transform.position = Vector3.MoveTowards(
                         prefabsToMove[i].transform.position,
                         waypoints[i].position,
                         movingSpeed * Time.deltaTime
                     );
        }
    }

    void Update()
    {
        WaypointsAI();
    }
}

```

The problem is inside the loop there might be less or more prefabsToMove then waypoints so it will throw exception.

Then doing prefabsToMove\[i\] is wrong.

# Answer
> 2 votes
Like I mentioned in the last answer, you can solve this by keeping a parallel array of data about how each instance should move. There, it was the object's speed. Here, we add the index of the waypoint it's supposed to drive toward. That way we can simulate object 1 on its way to waypoint 4 while object 5 is still working to reach waypoint 3, and they don't interfere with each other.

```
// Adding selectable behaviour at the end of the path,
// as requested from the comments.
public enum PathCompleteBehaviour {
    Stop,
    Loop,
    Reverse
}
public PathCompleteBehaviour completeBehaviour;

// Store parallel arrays for our movement parameters.
private float[] movementSpeeds;    // Randomized speed per object.
private int[] nextWaypointIndices; // Destination per object.

private void Start()
{
    // Changing terminology to be more standard.
    // - a "prefab" is a source asset you want to copy
    // - an "instance" is a copy of it that's been spawned in the scene
    instancesToMove = GameObject.FindGameObjectsWithTag("FrameLine");

    movementSpeeds = new float[instancesToMove.Length];
    nextWaypointIndices = new int[instancesToMove.Length];

    for(int i = 0; i < instancesToMove.Length; i++)
         movementSpeeds[i] = Random.Range(minSpeed, maxSpeed);
}

private void WaypointsAI()
{
    // We want to iterate over the instances, not over the waypoints.
    for (int i = 0; i < instancesToMove.Length; i++)
    {
        // Check to see if we reached the last waypoint.
        // If so, stop / loop / turn around as needed.
        int waypointIndex = nextWaypointIndices[i];
        if(waypointIndex < 0 || waypointIndex >= waypoints.Length) {
           switch(completeBehaviour) {
               case PathCompleteBehaviour.Stop:
                   // Leave it where it is and skip to the next instance.
                   continue;
               case PathCompleteBehaviour.Loop:
                   // Wrap front to back / back to front.
                   waypointIndex = (waypointIndex + waypoints.Length) % waypoints.Length;
                   break;
               case PathCompleteBehaviour.Reverse:
                   // Bounce back to the point before last.
                   waypointIndex += (movementSpeeds[i] > 0f) ? -2 : 2;
                   // Reverse direction.
                   movementSpeeds[i] *= -1f;
                   break;
           }
           nextWaypointIndices[i] = waypointIndex;
        }

        // Look up the waypoint we want to move toward next.
        Vector3 waypoint = waypoints[waypointIndex].position;

        // Read this instance's speed,
        // to compute how far it should move in this frame.
        float travel = Mathf.Abs(movementSpeeds[i]) * Time.deltaTime;

        // Apply the motion.
        Vector3 position = instancesToMove[i].transform.position;
        position = Vector3.MoveTowards(position, waypoint, travel);
        instancesToMove[i].transform.position = position;

        // If we're within a configurable tolerance of the
        // destination waypoint, set our destination
        // to the next waypoint after it.
        if((position - waypoint).sqrMagnitude < 0.1f) {
            nextWaypointIndices[i] += (movementSpeeds[i] > 0f) ? 1 : -1;
        }
    }
}

```

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


# Question
Title: How can I set only the players X rotation to 0 in Quaternion.Slerp in Unity?
I want to set the players X axis to zero while he is turning to the target Object but I dont get it to work.

Code:

---

public float rotationSpeed;

```
void OnMouseDown()
{
        //PLAYER ROTATION TO ORE OBJECT
        var rotation = Quaternion.LookRotation(transform.position - player.transform.position);
        player.transform.rotation = Quaternion.Slerp (player.transform.rotation, rotation, rotationSpeed * Time.deltaTime);
    }

```

# Answer
`Quaternion.LookRotation` looks along the vector you pass it. So if you want that rotation to twist only in the horizontal plane, lock the input vector into that plane:

```
var offset = transform.position - player.transform.position;

// Remove any uphill / downhill component,
// so the rotation we get is a pure yaw rotation.
offset.y = 0;

var rotation = Quaternion.LookRotation(offset);

```
> 1 votes

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


# Question
Title: How do I change the name of map shown in Warcraft 3 list of available maps?
I used an MPQ editor to change some things in one of my maps. Among those changes was the map name defined as a text string in the **war3map.wts** inside the map.
Now, however, I see that the name of the map, as shown in the list of maps, was unchanged and — of course — differs from the name of the map shown everywhere else: above the preview, e.g.

How do I change the list name?
Do I actually need to resave it in a map editor, e.g. Blizzard's “World Editor”?

# Answer
> 0 votes
No, you do not need to open the map in “World Editor” or any other Warcraft 3 map editor.
Changing the listname of your map can be done if you are willing or able to grab a hexeditor, or the like, and follow some very simple constraints.

The name of the map is stored in a header prepended to the actual MoPaQ stuff. Here I show you an excerpt from the hexadecimal representation of an example map:

```
? xxd  -autoskip_00_lines  -columns 8  -g 1  -length_read 520  -uppercase  ./'(2)Amazonia.w3x'
0000000: 48 4D 33 57 00 00 00 00  HM3W....
0000008: 41 6D 61 7A 6F 6E 69 61  Amazonia
0000010: 00 14 DC 01 00 02 00 00  ........
0000018: 00 00 00 00 00 00 00 00  ........
*
0000200: 4D 50 51 1A 20 00 00 00  MPQ. ...

```

The asterisk there represents several lines that are nothing more than null octets.
Anyways: You can see the name of the map there: that is the ‘listname’ which Warcraft 3 shows in the list of multiplayer or custom game maps. The name is succeeded by a 00, and then a sequence of some other octets.

I mentioned some constraints that you would need to abide if you wished to change the listname of any map. Here they are:

* Do not change the offset of the ‘MPQ’ sequence or anything succeeding it. I.e. it needs to begin at 0x200.
* Do not edit anything later than the offset mentioned above. None of that matters for what you need to do.
* Do not change the offset where the name of the map begins. I.e. it needs to begin at 0x8.
* Do not edit anything prior to the offset where the name begins. Doing so could invalidate your map and prevent it from being recognized as one.
* The name is simply terminated by a 00 octet. This is actually rather convenient because it allows us to change the length of the name and not be concerned with updating any pointers designating where the name terminates.
* The sequence succeeding the name — in this example, ‘14 DC 01 00 02’, — needs to be unaltered. It also needs to immediately succeed the single 00 octet which terminates the name.
These are various other parameters and information which Warcraft 3 reads when it displays the map. Tooling with them is beyond the scope of this answer.

Therefore, it follows that you can change the length of the name, so long as you compensate by deleting or adding, in the margin, however many 00 octets are necessary. It is also possible for you to give the map two different names: one which is shown in the list of available maps, and one which is shown anywhere the ‘true’ name is referenced.

Here, I show you a map for which I already changed the listname:

```
? xxd  -autoskip_00_lines  -columns 8  -g 1  -length_read 520  -uppercase  ./test/changing-length-of-listname.w3x
0000000: 48 4D 33 57 00 00 00 00  HM3W....
0000008: 69 66 20 69 20 73 65 65  if i see
0000010: 20 74 68 69 73 20 61 6E   this an
0000018: 64 20 63 61 6E 20 70 6C  d can pl
0000020: 61 79 20 69 74 2C 20 74  ay it, t
0000028: 68 65 6E 20 74 68 65 20  hen the
0000030: 6E 61 6D 65 20 63 68 61  name cha
0000038: 6E 67 65 20 77 6F 72 6B  nge work
0000040: 65 64 21 00 14 DC 01 00  ed!.....
0000048: 02 00 00 00 00 00 00 00  ........
0000050: 00 00 00 00 00 00 00 00  ........
*
0000200: 4D 50 51 1A 20 00 00 00  MPQ. ...

```

*I.e.*

> if i see this and can play it, then the name change worked!

Of course, that new name is far too long to show all of it in the list of maps, but my changes resulted in a map which Warcraft 3 could use and which exhibited evidence of the changes made.

The examples I gave were done using `xxd` in a Linux commandline environment. However, you could do something similar with any decent hexeditor or binary stream editor on any platform. Your choice of tool depends on what you have available and on your level of skill or proficiency with such a tool.

I'll repeat the example above, but this time sans the `-autoskip` switch so that you have a fuller representation of what I did.
I shall also omit the `-columns` switch so that each line width defaults to 16 octets.

```
? xxd  -g 1  -length_read 528  -uppercase  ./'(2)Amazonia.w3x'
0000000: 48 4D 33 57 00 00 00 00 41 6D 61 7A 6F 6E 69 61  HM3W....Amazonia
0000010: 00 14 DC 01 00 02 00 00 00 00 00 00 00 00 00 00  ................
0000020: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ................
0000030: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ................
0000040: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ................
0000050: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ................
0000060: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ................
0000070: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ................
0000080: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ................
0000090: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ................
00000a0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ................
00000b0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ................
00000c0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ................
00000d0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ................
00000e0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ................
00000f0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ................
0000100: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ................
0000110: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ................
0000120: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ................
0000130: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ................
0000140: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ................
0000150: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ................
0000160: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ................
0000170: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ................
0000180: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ................
0000190: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ................
00001a0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ................
00001b0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ................
00001c0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ................
00001d0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ................
00001e0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ................
00001f0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ................
0000200: 4D 50 51 1A 20 00 00 00 A0 C9 01 00 00 00 03 00  MPQ. ...........

? xxd  -g 1  -length_read 528  -uppercase  ./test/changing-length-of-listname.w3x
0000000: 48 4D 33 57 00 00 00 00 69 66 20 69 20 73 65 65  HM3W....if i see
0000010: 20 74 68 69 73 20 61 6E 64 20 63 61 6E 20 70 6C   this and can pl
0000020: 61 79 20 69 74 2C 20 74 68 65 6E 20 74 68 65 20  ay it, then the
0000030: 6E 61 6D 65 20 63 68 61 6E 67 65 20 77 6F 72 6B  name change work
0000040: 65 64 21 00 14 DC 01 00 02 00 00 00 00 00 00 00  ed!.............
0000050: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ................
0000060: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ................
0000070: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ................
0000080: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ................
0000090: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ................
00000a0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ................
00000b0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ................
00000c0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ................
00000d0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ................
00000e0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ................
00000f0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ................
0000100: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ................
0000110: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ................
0000120: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ................
0000130: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ................
0000140: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ................
0000150: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ................
0000160: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ................
0000170: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ................
0000180: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ................
0000190: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ................
00001a0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ................
00001b0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ................
00001c0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ................
00001d0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ................
00001e0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ................
00001f0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ................
0000200: 4D 50 51 1A 20 00 00 00 A0 C9 01 00 00 00 03 00  MPQ. ...........

```

---
Tags: modding
---


# Question
Title: After setting fixedDeltaTime to timeScale * 0.02f physics is behaving weirdly
I'm just facing a problem that when I slow time and set fixedDeltaTime to timeScale * 0.02f the physics starts behaving really weirdly. I have a chain of hinge joints and it makes kinda wave when I slow the time down. I tried slowing the time without changing fixedDeltaTime and it worked normally (it was only laggy, which is normal), but when I change it, it makes the physics weird. Here is video showing my problem: https://youtu.be/wEakZ03bWso Notice the wave on the chain in the first test.

# Answer
> 1 votes
One of the reasons we use a fixed timestep is to make physics behaviour more consistent.

It follows from this that changing the fixed timestep mid-run makes the physics behaviour less consistent.

And long chains of interactions are one of the first places inconsistencies in iteration frequency will appear. The timestep imparts a kind of inertia to these long chains, limiting how far down the chain an influence can travel in a given window of time (based on how many iterations fit). At higher update frequencies, the same chain can behave in a more flexible/snappy/responsive way, while at a lower frequencies it can behave stiffer / more damped.

So, the most surefire solution would be to not change your timestep dynamically. Choose a compromise timestep that's small enough to give good responsiveness at slowed time, but large enough to not bog your game down in physics computations at regular speed, and use that at all times. You can enable interpolation on rigidbodies where the timestep causes a noticeable stutter to keep it looking smooth & fluid.

The other thing you can try is to compensate your physics sim when you change timesteps - say, changing the number of bodies in your chain, their friction and damping parameters - so that of the high-timestep and low-timestep versions come out similar. This sounds like a parameter-tuning nightmare though, with no guarantee that any perfect match exists.

---
Tags: unity, physics
---


# Question
Title: How do you make a ShapeRenderer always full screen on resize?
I have:

```
shapeRenderer.setProjectionMatrix(stage.getViewport().getCamera().combined);

```

And I tried to do the following in `render()`:

```
shapeRenderer.rect(0, 0, stage.getViewport().getScreenWidth(), stage.getViewport.getScreenHeight());

```

Which full-screens the `ShapeRenderer` when I first run my project, but as soon as I resize the window, the rectangle starts to change size and go off-screen. I'm using a `FitViewport` on my `Stage`, is there any way to make the `ShapeRenderer` always be full screen?

# Answer
You should use the methods `getWorldWidth` and `getWorldHeight` instead of the `screen` counterparts. "World" is the emulated size of the viewport while "screen" is your actual screen size.
> 0 votes

---
Tags: libgdx
---


title: Why do I need offset on my camera?

text:
# Question
Title: Why do I need offset on my camera?
So I've been away from Unity and game development in general for a bit, so I'm working through Unity's UFO Tutorial and had a question about the camera set up. I don't understand why you need the offset for it? It follows the Player object directly it seems, and they use a Vector3? But it's a 2D game, so why not just use a Vector2? I was experimenting with the code just to see if I could figure it out, so I removed the offset variable completely but then when I ran the game it just showed a blank space in the game view. Any body who can help me understand this?

```
public class CompleteCameraController : MonoBehaviour
{
    public GameObject player; //Public variable to store a reference to the player game object
    private Vector3 offset; //Private variable to store the offset distance between the player and camera

    // Use this for initialization
    void Start ()
    {
        //Calculate and store the offset value by getting the distance between
        // the player's position and camera's position.
        offset = transform.position - player.transform.position;
    }

    // LateUpdate is called after Update each frame
    void LateUpdate ()
    {
        // Set the position of the camera's transform to be the same as
        // the player's, but offset by the calculated offset distance.
        transform.position = player.transform.position + offset;
    }
}

```

# Answer
> 3 votes
**First:** *What is offset and why do we need it?*

As comment goes in your script, offset is just a variable which will store a starting distance between player and camera. (We subtract player position from camera position, so we get the difference. basic vector algebra).

you can try making this variable public: `public Vector3 offset;` Remove it from start method completely (but don't remove from lateupdate). And launch the game.

You will see that it first, your camera will be inside player. This is because offset variable was 0,0,0 at first, so you are adding 0 to player position:

`transform.position = player.transform.position + offset;`

that obviously == player position.

You will be able to edit this variable in inspector, play around, you will see that camera starts moving, relative to player.

**Second:** *Why Vector3 and not Vector2?*

Yes, it is 2D game, and you can try using Vector2, but if you do, you will be able to move camera only, up, down and left, right, but not forwards and backwards.

Hope it helps.

# Answer
> -1 votes
You need an offset because otherwise the camera would be in the exact position as the player.

---
Tags: unity, camera
---


title: Skeletal animation with Assimp and glm

text:
# Question
Title: Skeletal animation with Assimp and glm
I'm trying to implement skeletal animation using assimp and glm. Everything seems to work, except for rotations.

This is the code I use when packing assimp data into my own engine's format. I THINK it should be correct, but since I've already run into problems with matrices (assimp uses row major, glm - column major), I'd rather post this, too:

```
for(uint32_t l = 0; l < tempChannel.numRotationKeys; ++l){
    quatKey tempKey;
    tempKey.values =  glm::quat(scene->mAnimations[i]->mChannels[j]->mRotationKeys[l].mValue.w,
                                scene->mAnimations[i]->mChannels[j]->mRotationKeys[l].mValue.x,
                                scene->mAnimations[i]->mChannels[j]->mRotationKeys[l].mValue.y,
                                scene->mAnimations[i]->mChannels[j]->mRotationKeys[l].mValue.z);

```

And this is the code that performs the actual transformations (quite a bit of it is based on http://ogldev.atspace.co.uk/www/tutorial38/tutorial38.html), but modifications (e.g. storing a list, where each child element is placed after a parent and keeps a parent's id, as was suggested here: http://blog.tojicode.com/2011/10/building-game-part-3-skinning-animation.html) have been made. Scaling and location transforms seem to be working fine, but rotations don't:

```
for(unsigned int i = 0; i < skeleton.size(); ++i){
    finalTransforms[i] = calcFinalTransform(time, i);
}

glm::mat4 SkeletalMeshObject::calcFinalTransform(double animationTime, unsigned int currentNode){
    // Find the node where the keyframes for the current bone are stored
    // Return -1, if not found
    int nodeId = findNodeAnimation(currentAnimation, skeleton[currentNode].name);

    glm::mat4 nodeTransform(skeleton[currentNode].offset);
    // If this node isn't animated, pass the default offset to it
    if(nodeId >= 0){
        unsigned int index;
        unsigned int nextIndex;
        // Interpolate scaling
        glm::vec3 scl;
        if(animations[currentAnimation].channels[nodeId].scalingKeys.size() == 1){
            scl = animations[currentAnimation].channels[nodeId].scalingKeys[0].values;
        } else {
            index = findKey(animationTime, KeyType::Scaling, nodeId);
            nextIndex = index + 1;
            double delta = animations[currentAnimation].channels[nodeId].scalingKeys[nextIndex].time -
            animations[currentAnimation].channels[nodeId].scalingKeys[index].time;
            double factor = (animationTime - animations[currentAnimation].channels[nodeId].scalingKeys[index].time) / delta;
            scl =     glm::mix(animations[currentAnimation].channels[nodeId].scalingKeys[index].values,
                            animations[currentAnimation].channels[nodeId].scalingKeys[nextIndex].values,
                            (float)factor);
        }
        // Interpolate rotation
        glm::quat rot;
        if(animations[currentAnimation].channels[nodeId].rotationKeys.size() == 1){
            rot = animations[currentAnimation].channels[nodeId].rotationKeys[0].values;
        } else {
            index = findKey(animationTime, KeyType::Rotation, nodeId);
            nextIndex = index + 1;
            double delta =     animations[currentAnimation].channels[nodeId].rotationKeys[nextIndex].time -
            animations[currentAnimation].channels[nodeId].rotationKeys[index].time;
            double factor = (animationTime -     animations[currentAnimation].channels[nodeId].rotationKeys[index].time) / delta;
            rot =     glm::mix(animations[currentAnimation].channels[nodeId].rotationKeys[index].values,
                           animations[currentAnimation].channels[nodeId].rotationKeys[nextIndex].values,
                           (float)factor);
        }
        // Interpolate location
        glm::vec3 loc;
        if(animations[currentAnimation].channels[nodeId].locationKeys.size() == 1){
            loc = animations[currentAnimation].channels[nodeId].locationKeys[0].values;
        } else {
            index = findKey(animationTime, KeyType::Location, nodeId);
            nextIndex = index + 1;
            double delta =     animations[currentAnimation].channels[nodeId].locationKeys[nextIndex].time -
            animations[currentAnimation].channels[nodeId].locationKeys[index].time;
            double factor = (animationTime -     animations[currentAnimation].channels[nodeId].locationKeys[index].time) / delta;
            loc =     glm::mix(animations[currentAnimation].channels[nodeId].locationKeys[index].values,
                            animations[currentAnimation].channels[nodeId].locationKeys[nextIndex].values,
                            (float)factor);
        }

        // Get final transform
        nodeTransform = glm::translate(loc) * glm::toMat4(rot) * glm::scale(scl);
    }

    // Store the node's transform
    locRotScaleTransforms[currentNode] = nodeTransform;

    // Get the id of the parent
    int parentId = skeleton[currentNode].parent;
    // Hierarchial transform
    glm::mat4 hierarchyTransform = nodeTransform;
    while(parentId >= 0){
        hierarchyTransform = locRotScaleTransforms[parentId] * hierarchyTransform;
        parentId = skeleton[parentId].parent;
    }

    // Apply inverse bind position matrix
    hierarchyTransform *= skeleton[currentNode].ibp;

    return hierarchyTransform;
}

```

Here's how the animation looks in blender:  And here's in my engine. Couldn't capture a gif from my window, so I'll describe it. First, it rotates along multiple axes (bones in the original animation were constrained to z axis), and as you can also see, it distorts. The frame seen below is almost at an end of animation, when distortions are most visible:

What can I do to make it look right?

# Answer
~~First thing I see is that you shouldn't read the quaternion in reverse order.~~

Also you shouldn't use `glm::mix`, use `glm::slerp` instead.

And here is how I construct the bone transform:

```
mat = glm::mat4_cast( currentrotation );
mat[0][0] *= currentscale.x; mat[1][0] *= currentscale.x; mat[2][0] *= currentscale.x;
mat[0][1] *= currentscale.y; mat[1][1] *= currentscale.y; mat[2][1] *= currentscale.y;
mat[0][2] *= currentscale.z; mat[1][2] *= currentscale.z; mat[2][2] *= currentscale.z;
mat[0][3] = currentposition.x; mat[1][3] = currentposition.y; mat[2][3] = currentposition.z;

```

Also I would check all my matrix multiplication, it should be in reverse order to how would you do it with Assimp matrices.

---

I base all this on personal experience from implementing an animated mesh with assimp and glm myself.(which now works) But it might not be the *correct* way of doing things.
> 2 votes

# Answer
I think the missing piece is parents starting transform. Meaning the bone was not at the origin to start with, so it should not be animated as it is. I saw you are using parents "animation" transform in the end withing while, but where is the starting point of the bone?

I am saving the transforms while loading the mesh like this:

```
void ModelAsset::createMeshes(const aiScene *scene, aiNode *aiNode, glm::mat4 parentTransform) {
    parentTransform = parentTransform * GLMConverter::AssimpToGLM(aiNode->mTransformation);

    for (unsigned int i = 0; i < aiNode->mNumMeshes; ++i) {
            aiMesh *currentMesh;
            currentMesh = scene->mMeshes[aiNode->mMeshes[i]];
            for (unsigned int j = 0; j < currentMesh->mNumBones; ++j) {
                meshOffsetmap[currentMesh->mBones[j]->mName.C_Str()] = GLMConverter::AssimpToGLM(
                        currentMesh->mBones[j]->mOffsetMatrix);
                std::string boneName =  currentMesh->mBones[j]->mName.C_Str();
                boneName += "_parent";
                meshOffsetmap[boneName] = parentTransform;
            }

//some other code

    for (unsigned int i = 0; i < aiNode->mNumChildren; ++i) {
        createMeshes(scene, aiNode->mChildren[i], parentTransform);
    }
}

```

and when I am calculating the animation:

```
    transforms[boneNode->boneID] =
            globalInverseTransform * meshOffsetmap.at(boneNode->name + "_parent") * nodeTransform * meshOffsetmap.at(boneNode->name)

```

If you would like to check out t Full source code can be found at https://github.com/enginmanap/limonEngine/blob/master/src/Assets/ModelAsset.cpp
> 0 votes

---
Tags: opengl, 3d, skeletal-animation, glm, assimp
---


title: How do I make mask work

text:
# Question
Title: How do I make mask work
I have been trying to make a game, but mask collision doesn't seem to work. Here is my code:

```
    class Player(pg.sprite.Sprite):
            def ___init__(self, game, x, y, lvl):
                    self.group = game.all_sprites
                    pg.sprite.Sprite.__init__(self.groups)
                    #nothing else important

            def update(self):
                    self.mask = pg.mask.from_surface(self.image)
                    #check if hits
                    hits = pg.sprite.spritecollide(self, self.game.kill, False, pg.sprite.collide_mask)
                    if hits:
                            #stops game
                            self.game.playing = False

    class Kill(pg.sprite.Sprite):
            def ___init__(self, game, x, y, lvl):
                    self.group = game.kill
                    pg.sprite.Sprite.__init__(self.groups)
            def update(self):
                    self.mask = pg.mask.from_surface(self.image)

```

The problem is that the game sets self.game.playing to False even before the pixels collide.

# Answer
> 1 votes
You might want to try *directly* using the `collide_mask()` method of the Sprite class. Like you, I have had issues trying to use it as an argument in the `spritecollide()` method.

Also, as a rule, you should do regular rectangle collision testing before you test for mask collisions, and only test mask collisions in the event of a rectangular collision. This is because mask collision testing is expensive, but rectangle collision testing is cheap.

I might do something like this:

```
for sprite in self.game.kill:

    # regular collision check before mask collision check for efficiency
    if self.bounding_rect.colliderect(sprite.bounding_rect):

        # mask collision check
        if pg.sprite.collide_mask(self, sprite):
            self.game.playing = False

```

---
Tags: collision-detection, python, pygame, masking
---


# Question
Title: How can I create a custom MeshCollider for my object, or fix my collision problem?
I have a problem with collisions in Unity and I am unsure how to fix it.

I have an octree with a depth of 2, and each node in the tree has a `Bounds` object attached to it for collisions. I am trying to see which nodes have been intersected by a specific object however it is giving me unexpected results.

The colliding object is a flat triangle that I have constructed myself which is acting as a cutting plane and I have attached a MeshCollider component to the GameObject.

When there is an intersection with a leaf node in the octree, the node is outlined in yellow and if there is no intersection, it is outlined in purple.

**Before rotation**

**After rotation** In this image I rotated the triangle a small amount on the Y axis and apparently Unity found a collision even though the objects are not even touching at all.

I am drawing the octree nodes using Gizmos.DrawWireCube, providing the center and size of the cube which are used to create the Bounds object of the node. Due to this it seems that the Bounds object for the nodes are correct, however the collider for the triangle may be incorrect.

When I test this with another 3D object such as a cube, it works perfectly, however not with the object I need it to work with. How can I fix this issue?

---

Collision checking code:

```
       public bool intersects(Bounds otherBounds)
        {
//bounds refers to the node's Bounds object
//otherBounds is the one I'm checking against, in this case the triangle's bounds from the MeshCollider
            if (otherBounds.Intersects(bounds))
            {
                return true;
            }
            return false;
        }

```

Octree traversal:

```
 if (node.intersects(triangleCollider.bounds))
        {

            if (node.isLeaf())
            {
                node.colour = Color.yellow;
            }

            if (node.hasChildren)
            {
                for (int i = 0; i < node.children.Length; i++)
                {
                    findIntersections(node.children[i]);
                }
            }
        }

```

---

It seems that perhaps a quad is being wrapped around the triangle as can be seen in the image below. This image has a triangle which is intersecting the top half of the octree, however the top left octant should have no collision.

How can I create a custom MeshCollider which I can specify the vertices manually?

---

See accepted answer for solution

```
int cutterMask = 1 << 9;
Collider[] intersectedColliders = Physics.OverlapBox(node.bounds.center, node.bounds.extents, Quaternion.identity, cutterMask, QueryTriggerInteraction.UseGlobal);

```

# Answer
> "It seems that perhaps a quad is being wrapped around the triangle"

You're not far off. All of your intersection methods are checking for intersections between `Bounds` structs. These represent axis-aligned bounding boxes, a set of min & max extents along each axis: precisely a box drawn around the object. They don't have the fidelity of an arbitrarily oriented plane or shaped polygon.

So it's not that your collider is being formed incorrectly. I'd be willing to bet it's correct as-is. You just need to make sure you're testing against that `MeshCollider` and not only its bounds.

To test a given box against the actual colliders in your scene, you can use Physics.OverlapBox or its non-allocating version.

I haven't found a simple built-in way to check for a box intersection with a single provided collider, but if you only need this for planes or triangles (or other primitives) we can do this analytically for each case with a few math formulas.
> 0 votes

---
Tags: unity, collision-detection
---


# Question
Title: Box2D simulation running slower on lower FPS(even when the desired FPS is lower than the actual)
I´m playing around and trying to make myself an easy platformer using the Box2D physics, before that I was not using it and was using my own physics implementation(just simple movements with timestep). My gameloop architecture now works like this:

```
while (_isRunning) {

    //Processing input events
    processInput();

    update();

    //Rendering stuff
    startFPSCap();

    render();

    delayFPS();
}

```

The update function is consisting of updating a game world (normal update function without deltatime) - inside this I´m calling a Box2D step function, with desired timestep at 1/60(wanted to have simulation at 60 fps) and then I call my own timestep function to update entity components(so they can be updated also with timestep not just the physics).

```
void update()
{
    _physics->Step(1.0f / 60.0f, 6, 2);

    updateEntitiesWithOwnTimestep();
}

```

However when I tried to run it on slower FPS, the simulation slow downs (even when I capped the FPS to like 200 at the start, so running it at 100 fps is like a slowmotion). I thought that when I set the desired physics simulation for **60** fps it will be no problem when reducing the FPS, but it seems like I´m missing something. Or is there something wrong? I mean, maybe the fact I´m running also my own timestep function.. Thanks for help.

**Edit1 - according to Timos answer**

Do you mean I should put the delta value I pass to my update function during each step in my own timestep? Like this:

```
void TimestepManager::update() {

int i = 0;

while ((_totalDeltaTime>0.0f) && (i<MAX_PHYSICS_STEPS)) {

    _deltaTime = std::min(_totalDeltaTime, MAX_DELTA_TIME);

    //This is std::function - i can define my own behavior via this
    _f.exec(_deltaTime);

    _physics.Step(_deltaTime, 6, 2);

    _totalDeltaTime -= _deltaTime;

    i++;
}

```

}

Or should I pass the total deltaTime? Because I thought that I should keep this unchanged because I don´t want to tie the simulation with the FPS.

# Answer
The first argument of the step method is the frame delta, the time between the last and the current frame. In your example it is the time between the last and the current iteration of the update method.

You should calculate it and supply that to the step method instead of the hardcoded `1.0f / 60.0f` value.
> 0 votes

---
Tags: c++, physics, architecture, box2d, game-loop
---


# Question
Title: How can I make the objects to move at the same speed as the lines?
```
void Update()
    {
        if (animateLines)
        {
            counter++;
            for (int i = 0; i < allLines.Length; i++)
            {
                Vector3 endPos = allLines[i].GetComponent<EndHolder>().EndVector;
                Vector3 startPos = allLines[i].GetComponent<LineRenderer>().GetPosition(0);
                Vector3 tempPos = Vector3.Lerp(startPos, endPos, counter / 500f * speed);

                allLines[i].GetComponent<LineRenderer>().SetPosition(1, tempPos);

                instancesToMove[i].transform.position =
                    Vector3.MoveTowards(endPos, startPos, counter / 500f * speed);
            }
        }
        else
        {
            counter = 0;
            foreach (GameObject thisline in allLines)
            {
                thisline.GetComponent<LineRenderer>().SetPosition(1, thisline.GetComponent<LineRenderer>().GetPosition(0));
            }
        }
    }

```

The lines are LineRenderer.

```
void SpawnLineGenerator(Vector3 start, Vector3 end, Color color)
    {
        GameObject myLine = new GameObject();

        myLine.tag = "FrameLine";
        myLine.name = "FrameLine";

        myLine.AddComponent<LineRenderer>();
        myLine.AddComponent<EndHolder>();
        myLine.GetComponent<EndHolder>().EndVector = end;
        LineRenderer lr = myLine.GetComponent<LineRenderer>();
        lr.material = new Material(Shader.Find("Particles/Alpha Blended Premultiply"));
        lr.startColor = color;
        lr.useWorldSpace = false;
        lr.endColor = color;
        lr.startWidth = 0.1f;//0.03f;
        lr.endWidth = 0.1f;//0.03f;
        lr.SetPosition(0, start);
        lr.SetPosition(1, start);
    }

```

So I have lines each new gameobject have a LineRenderer component and inside Update I'm animating the lines with some speed.

Now I want to move the instancesToMove (GameObject\[\] ) with the same speed as the lines but the instancesToMove are moving much slower then the lines.

I tried:

```
instancesToMove[i].transform.position =
                        Vector3.MoveTowards(endPos, startPos, speed);

```

Then

```
instancesToMove[i].transform.position =
                        Vector3.MoveTowards(endPos, startPos, speed * Time.deltaTime);

```

But it's never moving with the same lines speed.

# Answer
I think what you probably want to do is move your object first, then move the line to meet it:

```
// Move the object toward endPos at speed over the duration of the frame.
Vector3 objectPosition = instancesToMove[i].transform.position;
objectPosition = Vector3.MoveTowards(
                     objectPosition,        // Where we are so far.
                     endPos,                // Where we want to go.
                     speed * Time.deltaTime // How far to move this frame.
                 );
instancesToMove[i].transform.position = objectPosition;

// Snap the line to meet it there.
allLines[i].GetComponent<LineRenderer>().SetPosition(1, objectPosition);

```

This will work best if your lines are set to draw in worldspace, but we can convert this to their local space too if you need.

If you just need transforms from your array `instancesToMove`, I'd make that an array of `Transform[]` to save you a `.transform` every time. Similarly, it's better to type your `allLines` as an array of `LineRenderer[]` so you don't need to search for components with `.GetComponent<>()` many times every frame. That's just needless overhead. ;)
> 2 votes

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


title: D3D11 SkyDome with texture

text:
# Question
Title: D3D11 SkyDome with texture
Has anyone some code about a skydome mesh with a texture and a shader? Or even know how can I create a skydome mesh in Direct3D11? I wanted give an idea from https://ifun01.com/R8CTFZQ.html but it needs the md3 skydome mesh and without a sky texture. So I still think.

# Answer
> 0 votes
This is a file containing vertices for a triangulated sphere. You can include it in a shader, and if you call Draw() with a vertex count of 240, and have SV\_VERTEXID semantic as an input to the vertex shader, you can index into the ICOSPHERE variable in the shader. This will get you a 3D coordinate which you can use as your skydome mesh vertex positions and cubemap sampling coordinates as well. Like this vertex shader for example:

```
#include "icosphere.hlsli"

struct VSOut {
    float4 pos : SV_POSITION;
    float3 tex : TEXCOORD0;
};

VSOut main(uint vid : SV_VERTEXID)
{
    VSOut Out;
    Out.pos = mul(float4(ICOSPHERE[vid].xyz, 0), g_xCamera_ViewProjection);
    Out.tex = ICOSPHERE[vid].xyz;
    return Out;
}

```

I also like to use this method to draw any simple geometry like light geometries, boxes, etc. This way you don't have to bind a vertex buffer to the shader, the mesh gets compiled into the shader binary as an immediate constant buffer.

# Answer
> 0 votes
CPP alluded to it, but you can do it through a few simple things.

1 - Create a ball or box mesh in a 3d program. Most offer Wavefront export, there are a few wavefront to direct 3d mesh converters, but you challenge will be to find one. I found there are more wavefront import libraries around. If you use a box, you could easily hand craft it in your code (not nice but fairly straightforward, lots of render tutorials around). Box is definitely the easiest sky mesh to do first.

2 - It's a background, so just turn Z test/write off in Direct X so it will be written over by everything after.

---
Tags: 3d, directx11
---


# Question
Title: How can I make a shader that will make a cube or any object invisible?
I'm trying to create a shader that will make the object invisible and then with a script a fade in/out effect between invisible and visible.

What I tried:

```
Shader "InsideVisible" {
    Properties {
        _MainTex ("Base (RGB)", 2D) = "white" {}
        _Color ("Color (RGBA)", Color) = (1, 1, 1, 1) // add _Color property
    }

    SubShader {
        Tags {"Queue"="Transparent" "IgnoreProjector"="True" "RenderType"="Transparent"}
        ZWrite Off
        Blend SrcAlpha OneMinusSrcAlpha
        Cull front    // ADDED BY BERNIE, TO FLIP THE SURFACES
        LOD 100

        Pass {
            CGPROGRAM

                #pragma vertex vert alpha
                #pragma fragment frag alpha

                #include "UnityCG.cginc"

                struct appdata_t {
                    float4 vertex : POSITION;
                    float2 texcoord : TEXCOORD0;
                };

                struct v2f {
                    float4 vertex : SV_POSITION;
                    half2 texcoord : TEXCOORD0;
                };

                sampler2D _MainTex;
                float4 _MainTex_ST;
                float4 _Color;

                v2f vert (appdata_t v)
                {
                    v2f o;
                    o.vertex = mul(UNITY_MATRIX_MVP, v.vertex);
                    // ADDED BY BERNIE:
                    v.texcoord.x = 1 - v.texcoord.x;
                    o.texcoord = TRANSFORM_TEX(v.texcoord, _MainTex);
                    return o;
                }

                fixed4 frag (v2f i) : SV_Target
                {
                    fixed4 col = tex2D(_MainTex, i.texcoord) * _Color; // multiply by _Color
                    return col;
                }
            ENDCG
        }
    }
}

```

I added this shader to my cube's material But it's not invisible at all not even close.

Sorry for the confusion.

The shader that I need is not to be based on distance from the camera but to be based on fade in/out effect so it will change between visible/invisible slowly depending on speed value.

Update:

This script seems to be working on Standard shader but for some reason it's not fading smooth it's fading a bit each time but not smooth flow. Why is that ?

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

public class InsideVisible : MonoBehaviour
{
    private void Start()
    {
        Coroutine _currentFade = StartCoroutine(FadeTo(0f, 10.0f));
    }

    IEnumerator FadeTo(float aValue, float aTime)
    {
        float alpha = transform.GetComponent<Renderer>().material.color.a;
        for (float t = 0.0f; t < 1.0f; t += Time.deltaTime / aTime)
        {
            Color newColor = new Color(1, 1, 1, Mathf.Lerp(alpha, aValue, t));
            transform.GetComponent<Renderer>().material.color = newColor;
            yield return null;
        }
    }
}

```

# Answer
I've verified that the shader in the question works just fine for creating transparency.

For the fade script, it looks like you want something more like this:

```
// Local storage for the material instance we're modifying.
Material _materialCopy;

IEnumerator FadeTo(float endAlpha, float durationSeconds)
{
    // Cache the material so we don't need to re-get it all the time,
    // and can clean it up when we're done with it.
    if(_materialCopy == null)
        _materialCopy = GetComponent<Renderer>().material;

    // Record the starting colour so we can preserve it.
    Color color = _materialCopy.color;
    // Record the starting alpha so we know where we're fading from.
    float startAlpha = color.a;

    for (float t = 0.0f; t < 1.0f; t += Time.deltaTime / durationSeconds)
    {
        // Lerp between start and end, not between current and end.
        color.a = Mathf.Lerp(startAlpha, endAlpha, t);
        _materialCopy.color = color;
        yield return null;
    }

    // Ensure we end exactly where we want, not off by any fraction.
    color.a = endAlpha;
    _materialCopy.color = color;
}

// Add a method to clean up our local material copy when we're done with it,
// so it doesn't clutter up memory until the next scene change.
void OnDestroy()
{
    if(_materialCopy != null)
        Destroy(_materialCopy);
}

```
> 2 votes

# Answer
To Invisible the object you can use alpha value in your shader.

so instead of `return col;` try this `return 0;`

# Fading Effect

To fading your object you can use linear interpolation and clamping time by absolution function. try this `abs(clamp(x,0,50))` on graphtoy.

try this shader and play the game.you can see fading effect :)

```
Shader "Smkgames/Fading"
{
    Properties
    {
        _MainTex ("Texture", 2D) = "white" {}
        _EndAlpha("EndAlpha",Float) = 0
        _Duration("Duration",Float) = 1
        [MaterialToggle]_Fade("Start Fading",Int) = 1
    }
    SubShader
    {
    Tags {"Queue"="Transparent" "IgnoreProjector"="true" "RenderType"="Transparent"}
    Blend SrcAlpha OneMinusSrcAlpha Cull Off

        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;
            float _EndAlpha,_Duration;
            int _Fade;

            fixed4 frag (v2f i) : SV_Target
            {
                fixed4 col = tex2D(_MainTex, i.uv);

                float duration = abs(clamp(_Time.y,0,_Duration));//Clamp Time
                duration = duration/_Duration;// convert Time to number between 0 and 1
                float Alpha = lerp(col.a,_EndAlpha,duration);//linear interpolation between values
                float4 colFade = float4(col.rgb,Alpha);//linear interpolation Alpha
                float4 result = lerp(col,colFade,_Fade);//Check Condition
                return result;
            }
            ENDCG
        }
    }
}

```

here is C# code:

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

[ExecuteInEditMode]
public class FadeEffect : MonoBehaviour {
    private Material mat;
    public Texture2D image;
    public float _EndAlpha,_Duration;
    public bool Fade = true;
    public Color color = Color.white;

    void Awake()
    {
        mat = GetComponent<MeshRenderer>().material;
        int fade = Fade ? 1 : 0;
        mat.SetInt("_Fade",fade);
        mat.SetFloat("_EndAlpha",_EndAlpha);
        mat.SetFloat("_Duration",_Duration);
        mat.SetTexture("_MainTex",image);
    }
}

```

---

# Fading based on distance from the camera

I wrote a shader that you can determine range of fading effect and manage visibility:

```
Shader "Smkgames/InsideVisible"
    {
      Properties
      {
        _MainTex ("Texture", 2D) = "white" {}
        [MaterialToggle]_Fade("Fade",int) = 1
        [MaterialToggle]_Visible("Visibility",int) = 1
        _MinVisDistance("MinDistance",Float) = 0
        _MaxVisDistance("MaxDistance",Float) = 20
        _Color("Color",Color) = (0,0,0,1)
      }
      SubShader
      {
          ZWrite Off
          Blend SrcAlpha OneMinusSrcAlpha
          Tags {"Queue"="Transparent" "IgnoreProjector"="true" "RenderType"="Transparent"}
          LOD 100

        Pass
        {
          CGPROGRAM
          #pragma vertex vert
          #pragma fragment frag
          // make fog work
          #pragma multi_compile_fog

          #include "UnityCG.cginc"

        struct v2f
      {
        half4 pos       : POSITION;
        fixed4 color : COLOR0;
        half2 uv        : TEXCOORD0;
      };

      sampler2D  _MainTex;
      half   _MinVisDistance,_MaxVisDistance;
      float4 _Color;
      int _Fade,_Visible;

      v2f vert(appdata_full v)
      {
        v2f o;

        o.pos = UnityObjectToClipPos(v.vertex);
        o.uv = v.texcoord.xy;
        o.color = v.color*_Color;

        half3 viewDirW = _WorldSpaceCameraPos - mul((half4x4)unity_ObjectToWorld, v.vertex);
        half viewDist = length(viewDirW);
        half falloff = saturate((viewDist - _MinVisDistance) / (_MaxVisDistance - _MinVisDistance));
        o.color.a *= (1.0f - falloff);
        return o;
      }

      fixed4 frag(v2f i) : COLOR
      {
        //I could declare condition here but in shader it's better to prevent if else statement so I use lerp
        //if (_Fade == 1){ color = tex2D(_MainTex, i.uv) * i.color }
        //else{color = tex2D(_MainTex, i.uv); }
        fixed4 color = tex2D(_MainTex, i.uv) * lerp(i.color,1,(1-_Fade))*_Visible;
      return color;
      }
          ENDCG
        }
      }
    }

```

also you can change these variables through code:

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

[ExecuteInEditMode]
public class InsideVisible : MonoBehaviour {
    private Material mat;
    public Texture2D image;
    public bool _Fade = false,_Visible = true;
    public float MinVisDistance = 0,MaxVisDistance = 5;
    public Color color = Color.white;

    void Awake()
    {
        mat = GetComponent<MeshRenderer>().material;
    }
    void Update () {
        int fade = _Fade ? 1 : 0;
        int visible = _Visible ? 1 : 0;
        mat.SetInt("_Fade",fade);
        mat.SetInt("_Visible",visible);
        mat.SetFloat("_MinVisDistance",MinVisDistance);
        mat.SetFloat("_MaxVisDistance",MaxVisDistance);
        mat.SetTexture("_MainTex",image);
    }
}

```
> 2 votes

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


# Question
Title: How can I wait for all lines and instances to finish moving and then to destroy them?
```
void Update()
    {
        if (animateLines)
        {
            counter++;
            for (int i = 0; i < allLines.Length; i++)
            {
                endPos = allLines[i].GetComponent<EndHolder>().EndVector;
                Vector3 startPos = allLines[i].GetComponent<LineRenderer>().GetPosition(0);
                Vector3 tempPos = Vector3.Lerp(startPos, endPos, counter / 500f * speed);

                allLines[i].GetComponent<LineRenderer>().SetPosition(1, tempPos);

                instancesToMove[i].transform.position =
                    Vector3.MoveTowards(startPos, endPos, counter / 25f * speed);
            }

            for (int i = 0; i < allLines.Length; i++)
            {
                if (instancesToMove[i].transform.position == endPos)
                {
                    DestroyImmediate(instancesToMove[i]);
                    DestroyImmediate(allLines[i]);
                }
            }
        }
        else
        {
            counter = 0;
            foreach (GameObject thisline in allLines)
            {
                thisline.GetComponent<LineRenderer>().SetPosition(1, thisline.GetComponent<LineRenderer>().GetPosition(0));
            }
        }
    }

```

When doing:

```
for (int i = 0; i < allLines.Length; i++)
                {
                    if (instancesToMove[i].transform.position == endPos)
                    {
                        DestroyImmediate(instancesToMove[i]);
                        DestroyImmediate(allLines[i]);
                    }
                }

```

It's destroying only some of the lines and instancestomove and then give the exception:

MissingReferenceException: The object of type 'GameObject' has been destroyed but you are still trying to access it. Your script should either check if it is null or you should not destroy the object.

# Answer
The code is still keeping a reference to the destroyed object in the instancesToMove list, even though it is "destroyed". As such, it hasn't been garbage collected yet.

Unity overrides the GameObject == comparison to return true when compared to null if the object has been destroyed. So the following should stop the error you are getting.

```
for (int i = 0; i < allLines.Length; i++)
{
    if (instancesToMove[i] != null && instancesToMove[i].transform.position == endPos)
    {
        DestroyImmediate(instancesToMove[i]);
        DestroyImmediate(allLines[i]);
    }
}

```

You can also use something like the following once each update to remove all destroyed objects from the list;

```
instancesToMove.RemoveAll(x => x == null);

```

Alternatively, you can wait until all lines have moved before destroying them (like you are asking about) with something like;

```
bool finished = true;
for (int i = 0; i < allLines.Length; i++)
{
    if (instancesToMove[i].transform.position != endPos)
    {
        finished = false;
        break;
    }
}
if (finished)
{
    //insert destruction code here.
}

```
> 1 votes

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


# Question
Title: What do I need to develop for the Playstation 3?
I made a game, and I want to port it to the Playstation 3. What do I need in terms of hardware, money, licenses and such?

# Answer
> 9 votes
Are you interested in developing for PSN, or as a retail game that people buy in stores?

To develop for PSN, you'll need to start by contacting Sony and becoming a licensed developer. To develop a retail game, you'll most likely need to contact a publisher who will distribute the game.

In either case, be prepared to demo the game and your company to either Sony or a publisher for approval.

Once you've made this first step, Sony or the publisher will be able to help answer all of your questions regarding getting development hardware, costs, etc.

Good luck.

# Answer
> 0 votes
Although this is an old thread, I wanna mention an alternative option that has been available for both PlayStation 3 (and later) and Xbox One (and later) from the very beginning: Blu-ray Disc Java, abbreviated BD-J.

These consoles feature a Blu-ray Player, and all Blu-ray players can run JavaME as part of the Blu-ray specification. This means you can actually code games and apps with JavaME, and run it on these game consoles from the very same disc.

So if you're just looking to create some homebrew games for fun, then BD-J is a very attractive option. Because:

* you can run your homebrew games on many gaming consoles from the very same disc
* there's no expensive SDK to buy, you simply code JavaME in whatever IDE you want
* there's no approval process, you just create your own disc and make the ISO downloadable

---

Here's a few YouTube example videos of various BD-J Xlets running on PS3, showing that the platform is quite capable of running homebrew stuff:

https://www.youtube.com/watch?v=M\_E9VaXywG0

https://www.youtube.com/watch?v=NxMpLB\_ZsDs

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

https://www.youtube.com/watch?v=1bC5FV-2AY4

And a few useful links:

http://www.oracle.com/technetwork/articles/javame/bluray-142687.html

http://www.tvwithoutborders.com/

http://www.java-gaming.org/index.php?topic=38044.0

---
Tags: porting, playstation3, console
---


# Question
Title: Calculate the amout that should be added or subtracted to x and y axis with rotation?
Say I have this figure:

How would I calculate the amount I must add or subtract to x and y axis to get the cube to move in the direction its facing? The rotation is a float 0 - 360 and 0 is straight up.

# Answer
> 0 votes
In a coordinate system with:

* `y+` pointing up
* `x+` pointing right
* `angle` measured clockwise from straight up

Then a unit vector pointing in the direction given by a particular `angle` has:

```
u.x = sin(angle)
u.y = cos(angle)

```

Assuming you're careful to convert between degrees & radians or other units as needed for the particular trig library you're using (most work in radians, some work in degrees, some work in fractions of a full circle, etc.)

To move more or less than one unit in this direction, just apply a scalar multiple to both axes:

```
v.x = distance * sin(angle)
v.y = distance * cos(angle)

```

---
Tags: vector, coordinates
---


title: Calling Functions from Other Scripts

text:
# Question
Title: Calling Functions from Other Scripts
Say I have three different `gameObjevcts`, each representing rock, paper or scissors. These objects all have a `Player` script attached to them. The `Player` script has two functions i want to use, `MoveSelected()`, `MoveNotSeleccted()`. When the function `CPUMove()` is called, I want the program to randomly choose one of the three moves. My question is, how do I call a either of the functions fro another script `RPS_Game`? I thought of using Invoke() somehow but after trying couple of things with it, I got no where. Can someone please help me out?

```
public class RPS_Game {
    public void CPUMove() {
        int rand = Random.Range(1, 3);

        if(rand == 1) {
          //call MoveSelected() for one of the three Player objects and
            MoveNotSelected() for the other two
        }
        else if(rand == 2) {
          //call MoveSelected() for one of the three Player objects and
            MoveNotSelected() for the other two
        }
        else if(rand == 3) {
          //call MoveSelected() for one of the three Player objects and
            MoveNotSelected() for the other two
        }
    }
}

```

# Answer
You can just store a public reference to each of the scripts you want, and wire them up in the inspector:

```
public Player rockMove;
public Player paperMove;
public Player scissorsMove;

```

Then your script can say

```
rockMove.MoveSelected();
paperMove.MoveNotSelected();
scissorsMove.MoveNotSelected();

```

Though how I'd do it would be more like this:

```
public class PlayerMove : MonoBehaviour {

     public enum MoveType : int {
         Rock,
         Paper,
         Scissors
     }

     // This gives us a dropdown in the inspector
     // to select a move type on each object.
     public MoveType moveType;

     // No need for two methods for on and off,
     // just pass a boolean representing true = selected
     // false = unselected (similar to Unity's SetActive method)
     public void SetMoveSelected(bool selected) {
        // ...
     }
}

```

Then your script can get an array of `PlayerMove` components (or even search for them itself using `FindObjectsOfType`), and your `CPUMove` method can be very simple:

```
// Expose the array to populate or validate in the Inspector.
public PlayerMove[] moves;

public void CPUMove() {
    // Generate a random move 0, 1, or 2
    // (Random.Range on ints never selects the last item)
    // and cast it to a MoveType to get Rock, Paper, or Scissors.
    var selectedMoveType = (PlayerMove.MoveType)Random.Range(0, 3);

    // Iterate over the move objects and toggle them on/off
    // based on whether they match the randomly-selected move type.
    foreach(var move in playerMoves)
        move.SetMoveSelected(move.moveType == selectedMoveType);
}

```
> 1 votes

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


title: LibGDX particle emitter rotation

text:
# Question
Title: LibGDX particle emitter rotation
I have a libGDX game, in which I'd like to make some ice breath like effect using particles. So far we made a cone like effect. I can obtain and render it on the screen with this.

```
ParticleEffectPool.PooledEffect effect = breathPool.obtain();
effect.setPosition(x,y);
ps.add(effect);

```

But I don't really see any way to **rotate** the entire particle system in a given direction. Is there any way to achieve this?

# Answer
> 1 votes
You could try picking out the `angle` property of your emitter (or emitters if you have many) and manually adjust the values to center around some angle.

```
ParticleEffect effect = /* your effect */
ParticleEmitter emitter = effect.findEmitter("some_name"); // find the emitter you want to     rotate here
float targetAngle = /* your target angle */

ScaledNumericValue angle = emitter.getAngle();

/* find angle property and adjust that by letting the min, max of low and high span their current size around your angle */

float angleHighMin = angle.getHighMin();
float angleHighMax = angle.getHighMax();
float spanHigh = angleHighMax - angleHighMin;
angle.setHigh(angle - spanHigh / 2.0f, angle + spanHigh / 2.0f);

float angleLowMin = angle.getLowhMin();
float angleLowMax = angle.getLowMax();
float spanLow = angleLowMax - angleLowMin;
angle.setLow(angle - spanLow / 2.0f, angle + spanLow / 2.0f);

```

Note that the above would just adjust what the *high* and *low* are, and you'll most likely need to do something about it wrapping around.

# Answer
> 1 votes
Here's my own solution for 90° rotations:

```
/**
 * Created on 2018-02-09.
 *
 * @author Alexander Winter
 */
public class RotatableParticleEffect extends ParticleEffect {
    public RotatableParticleEffect() {}

    public RotatableParticleEffect(ParticleEffect effect) {
        super(effect);
    }

    public void rotateBy(int turnQuarter) {
        while(turnQuarter < 0)
            turnQuarter += 4;

        turnQuarter %= 4;

        for(ParticleEmitter emitter : getEmitters()) {
            ScaledNumericValue angle = emitter.getAngle();

            angle.setHighMax(angle.getHighMax() + turnQuarter * -90f);
            angle.setHighMin(angle.getHighMin() + turnQuarter * -90f);

            angle.setLowMax(angle.getLowMax() + turnQuarter * -90f);
            angle.setLowMin(angle.getLowMin() + turnQuarter * -90f);

            ScaledNumericValue rot = emitter.getRotation();

            rot.setHighMax(rot.getHighMax() + turnQuarter * -90f);
            rot.setHighMin(rot.getHighMin() + turnQuarter * -90f);

            rot.setLowMax(rot.getLowMax() + turnQuarter * -90f);
            rot.setLowMin(rot.getLowMin() + turnQuarter * -90f);

            for(int i = 0; i < turnQuarter; i++) {
                swapFields(emitter.getXOffsetValue(), emitter.getYOffsetValue());

                emitter.getYOffsetValue().setLowMin(-emitter.getYOffsetValue().getLowMin());
                emitter.getYOffsetValue().setLowMax(-emitter.getYOffsetValue().getLowMax());
            }
        }
    }

    private static void swapFields(Object o1, Object o2) {
        if(o1 == null || o2 == null)
            throw new IllegalArgumentException("Objects must not be null");

        if(!o1.getClass().equals(o2.getClass()))
            throw new IllegalArgumentException("Objects are not the same type");

        Class<?> type = o1.getClass();

        while(type != null) {
            for(Field field : type.getDeclaredFields()) {
                if(!field.isAccessible())
                    field.setAccessible(true);

                try {
                    Object tmp = field.get(o1);
                    field.set(o1, field.get(o2));
                    field.set(o2, tmp);
                } catch(IllegalAccessException ex) {
                    throw new RuntimeException(ex);
                }
            }

            type = type.getSuperclass();
        }
    }
}

```

With this solution, you can't rotate with any angle. If you'd need to, you will need to adjust the X and Y offsets with a rotation. `offsetY = originalOffsetY * sin(angle)` and same for X with `cos()`. I didn't implement the full solution for any angle because I didn't need it. However, I can confirm this simpler solution works for me.

# Answer
> 0 votes
Add the particle effect to a group with transformation enabled (default).

---
Tags: libgdx, particles
---


# Question
Title: Love2D STI library not drawing map at all (black screen)
I'm trying to use a pretty standard map with the Simple Tiled Implementation module for Love2D, but no matter what I try, I can't get it to display anything but a black screen. Here's my current code (keybindings in an effort to see if the map has just been placed offscreen):

```
local sti = require "sti"
local mapPos = { x = 0, y = 0 }

function love.load()
   map = sti("maps/map1.lua")
end

function love.update(dt)
   if love.keyboard.isDown("w") or love.keyboard.isDown("up") then
      mapPos.y = mapPos.y - 5
   end

   -- Move player down
   if love.keyboard.isDown("s") or love.keyboard.isDown("down") then
      mapPos.y = mapPos.y + 5
   end

   -- Move player left
   if love.keyboard.isDown("a") or love.keyboard.isDown("left") then
      mapPos.x = mapPos.x - 5
   end

   -- Move player right
   if love.keyboard.isDown("d") or love.keyboard.isDown("right") then
      mapPos.x = mapPos.x + 5
   end
   map:update(dt)
end

function love.draw()
   -- Transform world
   love.graphics.translate(-mapPos.x, -mapPos.y)

   -- Draw world
   map:draw()
end

```

However, even a more basic attempt (copied from the STI tutorial linked from the README on the Github page) doesn't work, again giving a black screen:

```
-- Include Simple Tiled Implementation into project
local sti = require "sti"

function love.load()
    -- Load map file
    map = sti("map.lua")
end

function love.update(dt)
    -- Update world
    map:update(dt)
end

function love.draw()
    -- Draw world
    map:draw()
end

```

My directory structure is basically just `main.lua`, an assets folder, and a maps folder. The maps folder contains the Tiled tile set and the Tiled .tmx maps and the lua exported maps.

I'm on Mac OSX, using Love2D version 0.10.2.

Am I missing something? Thanks.

# Answer
I realized you need to be careful exporting lua maps from Tiled, because they are automatically named like "\[your map name\]..lua". I'm not sure why this is, but when I did Export As instead and named the file manually, it worked.
> 1 votes

---
Tags: tilemap, lua, tiled, love2d
---


# Question
Title: How does an ECS work for a world subdivided into chunks (example)?
I am trying to use an ECS for my 2d game at the moment. Up until now I had my world subdivided into chunks (as minecraft does) of size 64x64. They are loaded and drawn when they come onto screen. I did this to reduce the drawing calls.

How would something like this work in an ECS? I would say my Chunks have the following properties at the moment: `tile_is_water[64,64], humidity[64,64], sprite_batch` (the thing that is drawn)

At some intervals I will need to call some kind of updatefunction which uses tile\_is\_water and humidity to generate a new sprite\_batch (but not very often, these change rarely). On every frame I need to draw the sprite\_batch. On every (or maybe every few) frame I need to check which areas are visible and set some kind of flag s.t. I only draw the visible ones.

It would help me a lot of someone could explain to me what the components, the entities and systems would be in this case.

Edit: To clarify. I don't have this modelled as an ECS yet and I have problems modelling this particular issue. What I have until now is just seperated everything into components: **Components**: Is\_Water\_Area, HumidityArea, SpriteBatch Is\_Water\_Area and HumidityArea just contain the corresponding 64x64 arrays and sprite\_batch contains the drawable spritebatch. I also have a BatchDrawer system that draws everything that has a SpriteBatch. But where do I do the updating of the SpriteBatch for example? Where do I check which areas are drawn?

For example I could just check this every frame or I could keep a list of drawable Areas and update that. But where would I keep such a list of the drawable areas?

# Answer
This answer is focused on how I would approach solving the problem instead of a prebaked specific answer.

For google reference, the basic ideas are based on broad phase and narrow phase collision detection.

First, list out the facts and invariants that you can depend on. E.g.

* Size of Chunk.
* Player movement
* Calculate (d) the time required for a player to cross one Chunk of map.
* Calculate (d\_2) the time required to traverse 1/2 of one Chunk.

Create a Component for tracking Player\_Loaded\_Chunks

Create a System which runs every (d\_2) intervals of time. (d\_2 because you need to load the world BEFORE it comes into view)

```
foreach available chunk:
    Is the player within (d) travel time of a chunk which is not loaded/generated/rendered yet?
        yup
            Load the chunk the player just moved into range of.
            (Other Systems should use this as a trigger to create your various Terrain/Object/Map entities in that chunk)
        nope
            chunk out of range, ignore
foreach loaded chunk:
    Is the player OUT OF RANGE of this already loaded chunk?
        yup
            Unload the chunk
        nope
            keep it loaded

```

This approach allows you to run far less than every frame, potentially only every few seconds.

Obviously you'll need to tune many factors for your specific case.

* Are you allowing teleports? Better have a teleport delay to allow loading the other end of the map
* Speed boosting items? Same deal.
* If your chunks are huge, you can't hold as many in memory, but you run the algorithm less often
* If your chunks are tiny compared to player speed, you need to run the load/unload more often

Highly advanced drawing to add flavor to this answer:
> 1 votes

---
Tags: game-design, architecture, entity-system, design-patterns, entity-component
---


# Question
Title: Freetype: create Signed Distance Field based font
I am trying to implement Font Rendering in my OpenGL C++ game.

I read many articles on the subject and got to know different methods, but I am still learning.

Valve has published a paper for Signed Distance Fields and how you can use them with Shaders to generate sharp edges for you text. This has turned out to be the preferred method.

In my project I create all of my characters with Freetype in a loop, bind them to a texture object and reuse them whenever I need a specific character.

I perfectly know that it is not very efficient. Unfortunately, I haven't found a good way to load a bitmap with all the letters and use only single sections. That's why I'm going to use this way for now.

I got everything working (creating the letters, binding the textures and use them for text), but without Signed Distance Fields.

So my Question is how to generate all of my character textures as a Signed Distance Field with the help of Freetype?

This is what my procedure looks like so far:

```
struct Character {
    GLuint textureID, advance;
    glm::ivec2 size, bearing;
};

```

.

```
FT_Library ft;
if( FT_Init_FreeType( &ft ) )
{
    throw std::string( "Could not initialize Freetype Library. Abort" );
}

FT_Face t_face;
if( FT_New_Face( ft, t_fontname.c_str(), 0, &t_face ) )
{
    throw std::string( "Could not load " + t_fontname + ". Abort" );
}

// set font size
FT_Set_Pixel_Sizes( t_face, 0, 48 );

// Disable byte-alignment restriction
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);

std::map< GLchar, Character > characters;

for( GLubyte c = 0; c < 128; c++ )
{
    // Load character glyph
    if ( FT_Load_Char( t_face, c, FT_LOAD_RENDER ) )
    {
        throw std::string( "Could not load glyph from font. Abort" );
    }

    // Generate texture
    GLuint tex;
    glGenTextures(1, &tex);
    glBindTexture(GL_TEXTURE_2D, tex);
    glTexImage2D
    (
        GL_TEXTURE_2D,
        0,
        GL_RED,
        t_face->glyph->bitmap.width,
        t_face->glyph->bitmap.rows,
        0,
        GL_RED,
        GL_UNSIGNED_BYTE,
        t_face->glyph->bitmap.buffer
    );

    // Set texture options
    glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE );
    glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE );
    glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
    glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );

    // Now store character for later use
    Character character =
    {
        tex,
        t_face->glyph->advance.x,
        glm::ivec2( t_face->glyph->bitmap.width, t_face->glyph->bitmap.rows ),
        glm::ivec2( t_face->glyph->bitmap_left, t_face->glyph->bitmap_top )
    };

    characters.insert( std::pair< GLchar, Character >( c, character ) );
}

glPixelStorei(GL_UNPACK_ALIGNMENT, 4);

```

I already fount this project on github which seems to be a solution. It also depends on Freetype, but to be honest I don't quite understand how the Signed Distance Fields are generated. It might also be too overkill for my intentions.

There are many websites that unfortunately use the old fixed pipeline or are not intended for C++.

# Answer
> 2 votes
Unfortunately, freetype does not seem to render directly to a distance field as of version 2.9 (check the render modes listed here)

You could calculate the distance from the alpha value of the freetype generated bitmaps using something like the techniques described in the paper "Anti-aliased Euclidean distance transform"

---
Tags: opengl, c++, fonts, signed-distance-field
---


# Question
Title: When creating a game, what are some architectural desgin concepts I can use to be able to port my game from single to multiplayer?
I am a software developer but, I mostly develop games in Unity. I have experience creating single player games as well as multiplayer games. I am at a crossroads where I am in the middle of development of a proof of concept or small demo and all of a sudden I am asked to turn it into a multiplayer game without prior knowledge of this I turn around and say it would add 50% to development time because I basically have to start over from scratch because I didn't necessarily take into account that later down the road they might want to change the experience from single to multiplayer.

So with all of that out of the way, are there any different methodologies out there that would make it easier on the developer to port a game from single player to multiplayer?

I have thought of a possible way of doing this by just setting the game up as single player, however, making my functions where they are easily able to wrap them using Commands and RPCs. But I find this may or may not help me and is only dependent on what the requirements are.

My biggest time killer when it comes to porting these PoC's is typically the UI. Most of the time my requirements are so that the UI will be the same shared UI for all clients and having to update it for each action performed on it and dealing with handling ClientAuthority. (Any tips for dealing with this would be greatly appreciated too) Think of this as something like, making something with Legos in multiplayer and having shared instructions based on the step the user is on.

**Summary**

What are different ways that I can design a small demo/concept where I can easily port it to multiplayer later on, or make my game where it is "multiplayer friendly" ? Or should I try to stay away from this type of thinking altogether and just develop a single player aspect and just develop a multiplayer aspect, arguments for and against this concept are sought after.

# Answer
Depends on the size of the project.

For small projects like the ones described in the question, it's not worth the effort. Constantly worrying about large but possibly non-existent problems can slow down development speed considerably, so for a multi-day or even multi-week project the best you can do is **communication**. Tell the Customer/Employer/Coworker before you start what your time/price estimate is, clarify if they want single or multiplayer, and inform them that as long as they are willing to pay extra you're happy to switch it should they later change their mind - but it will be more expensive than just picking the right thing from the start.

For larger projects that take multiple months, I recommend taking half a day to figure out how you'd run multiplayer, writing it down. Then base the software design of the game on that multiplayer draft, but implement only the parts you need for single player.

In a now removed comment a specific issue was mentioned regarding who to send what from the server, and when to use local position versus remote position. In another comment P2P was mentioned. For both of these, Drafts and PoCs can be considerably simplified by always going through an authoritative hypothetical zero latency server - during the demo all players are on the same LAN to avoid latency, and you always use server position for everyone. If you only implement the single player parts you don't even need to go through sockets and messages - you simply have method calls which call your server interface directly and process an asynchronous response. For drafts in P2P settings, still use a server, unless what you want to prove isn't the gameplay but the underlying P2P technology.
> 1 votes

---
Tags: unity, multiplayer, unity-networking
---


# Question
Title: Black screen when try to capture Vive gameplay using VRCapture
I'm using Unity, the first recording in VR Mode was fine. Then the rest were just black screen. No errors were detected and my gameplay was just playing fine. Also the red dot recording signal on Vive HMD was not there anymore. Any advice ?

Setting :

========VRCapture Diagnosis========

Software Checksum: 37CD Version: 1.0.278.128
Processor: Intel(R) Core(TM) i7-7700HQ CPU @ 2.80GHz
Display Card: GeForce GTX 950M/PCIe/SSE2
Operating System: Microsoft Windows 10 64 Bit
VR Headset: HTC Vive MV
Microphone: Microphone (2- USB Audio Device)

# Answer
apologies for adding to the question yesterday.

I have found a solution to make sample videos. It is not as cool as VRCapture, but it works for both video and audio.

I downloaded http://camstudio.org/ for free and changed the video settings options -\> video options -\> compressor to IYUV
> 1 votes

---
Tags: unity, htc-vive, game-recording, gameplay3d-engine
---


title: How to make a noise gradient?

text:
# Question
Title: How to make a noise gradient?
**Introduction:**

I am working on a heat map made by Perlin Noise with the next result:

*(Figure 1)*

```
                  *(Red means really hot and light blue is colder)*

```

The algorithm identifies that mountains are colder at their top and plains vary between warm and hot(randomly, there is no physics behind).

**QUESTION:**

**How can i do so that heat map i generated with Perlin Noise looks like this example:**

*(Figure 2)*

where the temperature variations follows something like Earths equator.

**My Ideas:**

I thought about divide the map manually (from height to height2 is hot and so on...) but i do not like that idea as i want **something more dynamic** (temperatures may vary so does the heat map)

**What i am asking?**

Is there any **better solution** to this idea i had?

Thanks for your interest in this question.

**EDIT:**

With the code below i made possible the next thing:

```
public static Texture2D GetAirTemperature(int width, int height, Tiles[,] tiles)
{
    var texture = new Texture2D(width, height);
    var pixels = new Color[width * height];

    for (var x = 0; x < width; x++)
    {
        for (var y = 0; y < height; y++)
        {
            if (y <= 5 || y >= 95)
            {
                pixels[x + y * width] = Coldest;
            }
            else if (y <= 15 || y >= 85)
            {
                pixels[x + y * width] = Colder;
            }
            else if (y <= 30 || y >= 70)
            {
                pixels[x + y * width] = Warm;
            }
            else if (y <= 45 || y >= 55)
            {
                pixels[x + y * width] = Warmer;
            }
            else { pixels[x + y * width] = Warmest; }
        }
    }

    texture.SetPixels(pixels);
    texture.wrapMode = TextureWrapMode.Clamp;
    texture.Apply();
    return texture;
}

```

and obtaining the next result:

*(Figure 3)*

**How i could multiply/modulate/something it by my Perlin noise so i get something irregular but looks a like Earths Equator?**

Because you cannot do like Texture2D * Texture2D (multiply textures)

**EDIT2:**

What if, instead of using noise, i create my own 2D air temperature map as a starting point? I mean, my own matrix \[width\*height\].

Temperature will have the input given at the center of matrix *(equator)* and then, when update the temperature map *(a cycle)*.

*A cycle will go once in a while (periodically) to simulate temperature changes.*

The input from the sun at the equator \[(width/2)x(height/2)\] will move outwards from the center into "north and south the matrix" *(North is x, y \< 50 && south is x,y \> 50)*

That means i have to check each row and number above and under the equator while maintaining energy conservation and other factors.

It is nice on paper but a hell in coding. **Do you have any other idea to accomplish something similar to figure 3?**

# Answer
> 4 votes
Here are two different ways I might approach this problem, showing how they change as the effect intensity is cranked up & down.

The outermost column on each side is just my gradient, computed as a function of the vertical position y, from 0 to 1:

```
gradient(y) = 1 - 2 * abs(y - 0.5);

```

The next column inward is my noise sample, varying with intensity from a medium grey at 0.5 to 0/1 at the darkest/brightest extremes. Here I'm using a scrolling texture as my noise source, but you can sample one or more octaves of procedural noise for a similar effect.

The innermost grey columns show the gradient & noise combined, using two different strategies.

* On the left: **Weighted Average** `output = lerp(gradient(y), noise, intensity)`

Nothing fancy here. We have two signals in the range 0..1, so we add them together and multiply the result so it has the same range, equivalent to a linear interpolation between the two.
* On the right: **Domain Warping** `output = gradient(y + intensity * (noise - 0.5))`

Here we're using the noise to change the input to the gradient function, making it behave as though it were running for a point higher or lower on the image.

The innermost columns are the same two strategies, visualized in colour by sampling from a texture ramp. A series of `if` bands as in your example would work too for hard-edged contours.

One thing to notice is that, because the left strategy uses averaging, it tends to weaken the effect of each input, softening them toward mid-greys. In the colour map, you can see the effect of this as the green mid-temperature band expanding as the intensity ramps up, and we have fewer high reds or low blues.

The domain warping strategy, on the other hand, keeps the sharpness of the features and the average positions of each colour band roughly the same. But it does have the ability to fall off the edges of the domain at the top & bottom, sampling gradient values for inputs below 0 and above 1, which is why the deep blues & reds get more prominent there.

An effect that's a bit tougher to see in this gif is that the gradient function I used has a sharp fold in the middle where it changes from brightening to darkening, which our eyes tend to exaggerate and perceive as a faint line. In the weighted average case, this fold line is preserved, just made a little shallower. When the red is pushed in toward the middle, you briefly see sort of a "burned in" line across the middle on the left. On the right, the domain warping tends to bend and distort this fold line so it's less visible.

# Answer
> 1 votes
Just because you use noise as your data, doesn't mean you can "modulate" the result.

To get a gradient overlay on top of noise, just multiply it with a factor that ranges from 0.8 at north pole, to 1.2 at equator, to 0.8 at south pole.

This code would do the trick:

```
// x and y range from -1 to 1
v = noise( x, y );
s = 1.2 - 0.4 * abs(y);
result = s * v;

```

That would result in a noise field, that is skewed to hot at equator. The equator still has streams of hot and cold running through it, but on a whole, is hotter than the poles.

Reminder: Not shown in my example code, but: don't forget to mix multiple octaves to make the noise look good. You do this like so.

# Answer
> 1 votes
You could take a linear gradient between equator and poles ranging from `min` at the poles (y = 0 and y = 100) to `max` at the equator (y=50). The factor then becomes

```
f =  Math.Abs(y / 50 - 1) * (min - max) + max;

```

multiply the noise with this factor

```
pixels[x + y * width] = GetColorFromTemperature(GetTemperatureFromNoise(x, y) * f);

```

As an example with min = 0.2 and max = 1.2:

Plot made with: www.wolframalpha.com (with x-axis as your latitude (y) and y-axis as the factor.

You could also make a flat top at the equator with `Math.Min(top, f)`.

---
Tags: c#, algorithm, tilemap, simulations, heightmap
---


# Question
Title: Using StartCoroutine() and WaitForSeconds()
I am trying to perform two operations. First I want to increase the size of a GameObject and then delay for 0.1s before returning it back to its original size. However, when I try using StartCoroutine(), it keeps giving me the error :

```
An object reference is required to access not-static members

```

even though I made my Delay() function static. Can somebody please tell me what I'm doing wrong?

```
public static void MoveSelected(int choice)
{
    GameObject rock1 = GameObject.Find("Rock1");
    GameObject paper1 = GameObject.Find("Paper1");
    GameObject scissors1 = GameObject.Find("Scissors1");

    Vector3 scl;

    if (choice == 1)
    {
        scl = rock1.transform.localScale;
        scl.x *= 1.1f;
        scl.y *= 1.1f;
        rock1.transform.localScale = scl;

        StartCoroutine(Delay());

        scl.x /= 1.1f;
        scl.y /= 1.1f;
        rock1.transform.localScale = scl;
    }
    else if (choice == 2)
    {
        scl = paper1.transform.localScale;
        scl.x *= 1.1f;
        scl.y *= 1.1f;
        paper1.transform.localScale = scl;

        StartCoroutine(Delay());

        scl.x /= 1.1f;
        scl.y /= 1.1f;
        rock1.transform.localScale = scl;
    }
    else if (choice == 3)
    {
        scl = scissors1.transform.localScale;
        scl.x *= 1.1f;
        scl.y *= 1.1f;
        scissors1.transform.localScale = scl;

        StartCoroutine(Delay());

        scl.x /= 1.1f;
        scl.y /= 1.1f;
        rock1.transform.localScale = scl;
    }

}

static IEnumerator Delay()
{
    yield return new WaitForSeconds(0.1f);
}

```

# Answer
This is not how coroutines work.

StartCoroutine returns immediately after starting the coroutine, and the function you called it from keeps executing. It does not wait for that coroutine to finish.

So you can't use StartCoroutine to put a delay into a non-coroutine method. (If that method is itself a coroutine, you can yield to a newly-started coroutine until it completes)

Also, StartCoroutine itself is not a static method, so you need to have a Monobehaviour instance to call it. That instance is important for tracking the state of the coroutine from frame to frame.

So we could rework your method as an instance method like so:

```
public void MoveSelected(int choice) {
    Transform option;
    switch(choice) {
        case 1: option = rock1.transform; break;
        case 2: option = paper1.transform; break;
        case 3: option = scissors1.transform; break;
    }

    StartCoroutine(PulseChosenOption(option));
}

IEnumerator PulseChosenOption(Transform option, float delay = 0.1f, float pulseAmount = 1.1f) {
    var originalScale = option.localScale;
    option.localScale = originalScale * pulseAmount;

    yield return new WaitForSeconds(delay);

    option.localScale = originalScale;
}

```
> 3 votes

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


# Question
Title: Attach the UIButton to Component Via Script (C# Unity)
I want to attach the UI to the MC\_Streaming Option Script via Code .

What i wanted here is that this `live_onOff` will go to the Livestream(MC\_Streaming Option) without dragging it . And i don't know where to start.

PS: The MC\_Streaming Option script is being attached only when the program run

```
MC_StreamingOption mcStreamingOption = gameObject.AddComponent<MC_StreamingOption>();

```

# Answer
> 1 votes
If the MC\_StreamingOption doesn't exist at edit time, you can assign the button to another script to hold onto the button on its behalf until it's been spawned and is ready to accept it.

```
// 1) Member variable you can use to store a reference to the button in the Inspector.
public UIButton livestreamButton;

...

// 2) later, when you spawn the StreamingOption:
var mcStreamingOption = gameObject.AddComponent<MC_StreamingOption>();

// ...you assign the button you had set aside for it.
mcStreamingOption.livestream = livestreamButton;

```

---
Tags: unity, c#, gameobject, ngui
---