# Question
Title: Issues with OpenGL rotation matricies and shaders
I am having an issue with my rotations in my opengl shaders. My program works fine before I add in my rotation matrices. Here is an example, at YouTube. After I add rotations to my shaders, there are issues. Here is an example.

---

Here is my vertex shader:

```
    #version 130

in vec3 position;
in vec4 color;
in vec2 texcoord;
uniform mat4 view_array;
uniform mat4 end_array;
uniform mat4 projection_matrix;
uniform mat4 trans_matrix;
uniform mat4 x_rotation_matrix;
uniform mat4 y_rotation_matrix;
uniform mat4 z_rotation_matrix;

out vec4 pos;
out vec2 texture_coordinate;
//out vec4 color_value;
void main()
{
     mat4 vw_matrix = mat4(1.0);
     mat4 rotation_matrix = x_rotation_matrix * y_rotation_matrix;
     mat4 model_matrix =  trans_matrix * rotation_matrix;//
     pos = projection_matrix * vw_matrix * model_matrix *  vec4(position, 1.0);
     gl_Position = pos;
     texture_coordinate = texcoord;
     //color_value = color
}

```

Here are the values for my matrices:

```
// rotation matrices

x_rotation_matrix[0] = 1;
x_rotation_matrix[1] = 0;
x_rotation_matrix[2] = 0;
x_rotation_matrix[3] = 0;
x_rotation_matrix[4] = (float) cos(-yaw * (PI / 180));
x_rotation_matrix[5] = (float) -sin(-yaw * (PI / 180));
x_rotation_matrix[6] = 0;
x_rotation_matrix[7] = (float) sin(-yaw * (PI / 180));
x_rotation_matrix[8] = (float) cos(-yaw * (PI / 180));
x_rotation_matrix[9] = 0;
x_rotation_matrix[10] = 1;
x_rotation_matrix[11] = 0;
x_rotation_matrix[12] = 0;
x_rotation_matrix[13] = 0;
x_rotation_matrix[14] = 0;
x_rotation_matrix[15] = 1;

y_rotation_matrix[0] = (float) cos(-pitch * (PI / 180));
y_rotation_matrix[1] = 0;
y_rotation_matrix[2] = (float) sin(-pitch * (PI / 180));
y_rotation_matrix[3] = 0;
y_rotation_matrix[4] = 0;
y_rotation_matrix[5] = 1;
y_rotation_matrix[6] = (float) -sin(-pitch * (PI / 180));
y_rotation_matrix[7] = 0;
y_rotation_matrix[8] = (float) cos(-pitch * (PI / 180));
y_rotation_matrix[9] = 0;
y_rotation_matrix[10] = 1;
y_rotation_matrix[11] = 0;
y_rotation_matrix[12] = 0;
y_rotation_matrix[13] = 0;
y_rotation_matrix[14] = 0;
y_rotation_matrix[15] = 1;

z_rotation_matrix[0] = (float) cos(-pitch * (PI / 180));
z_rotation_matrix[1] = (float) -sin(-pitch * (PI / 180));
z_rotation_matrix[2] = 0;
z_rotation_matrix[3] = (float) sin(-pitch * (PI / 180));
z_rotation_matrix[4] = (float) cos(-pitch * (PI / 180));
z_rotation_matrix[5] = 1;
z_rotation_matrix[6] = 0;
z_rotation_matrix[7] = 0;
z_rotation_matrix[8] = 0;
z_rotation_matrix[9] = 0;
z_rotation_matrix[10] = 1;
z_rotation_matrix[11] = 0;
z_rotation_matrix[12] = 0;
z_rotation_matrix[13] = 0;
z_rotation_matrix[14] = 0;
z_rotation_matrix[15] = 1;

GL20.glUniformMatrix4fv(
    GL20.glGetUniformLocation(programID, "x_rotation_matrix"), true, x_rotation_matrix);
GL20.glUniformMatrix4fv(
    GL20.glGetUniformLocation(programID, "y_rotation_matrix"), true, y_rotation_matrix);
GL20.glUniformMatrix4fv(
    GL20.glGetUniformLocation(programID, "z_rotation_matrix"), true, z_rotation_matrix);

```

Here is my transformation matrix:

```
trans_matrix[0] = 1;
trans_matrix[5] = 1;
trans_matrix[10] = 1;
trans_matrix[12] = x;
trans_matrix[13] = y;
trans_matrix[14] = z;
trans_matrix[15] = 1;

```

---

What am I doing wrong?

# Answer
> 4 votes
You're off by 1 in your matrix initialization. The matrix rows are 4 entries wide (4x4 matrix) but you're initializing them like they're 3 entries wide.

```
z_rotation_matrix[0] = (float) cos(-pitch * (PI / 180));// * (PI / 180));
z_rotation_matrix[1] = (float) -sin(-pitch * (PI / 180));// * (PI / 180));
z_rotation_matrix[2] = 0;
z_rotation_matrix[3] = (float) sin(-pitch * (PI / 180));// * (PI / 180));
z_rotation_matrix[4] = (float) cos(-pitch * (PI / 180));// * (PI / 180));
z_rotation_matrix[5] = 1;
z_rotation_matrix[6] = 0;

```

Should be

```
z_rotation_matrix[0] = (float) cos(-pitch * (PI / 180));// * (PI / 180));
z_rotation_matrix[1] = (float) -sin(-pitch * (PI / 180));// * (PI / 180));
z_rotation_matrix[2] = 0;
z_rotation_matrix[3] = 0;
z_rotation_matrix[4] = (float) sin(-pitch * (PI / 180));// * (PI / 180));
z_rotation_matrix[5] = (float) cos(-pitch * (PI / 180));// * (PI / 180));
z_rotation_matrix[6] = 0;

```

And so on.

```
x_rotation_matrix[4] = (float) cos(-yaw * (PI / 180));//);// * (PI / 180)
x_rotation_matrix[5] = (float) -sin(-yaw * (PI / 180));// * (PI / 180));
x_rotation_matrix[6] = 0;
x_rotation_matrix[7] = (float) sin(-yaw * (PI / 180));// * (PI / 180));
x_rotation_matrix[8] = (float) cos(-yaw * (PI / 180));// * (PI / 180));
x_rotation_matrix[9] = 0;
x_rotation_matrix[10] = 1;

```

Should be

```
x_rotation_matrix[4] = 0;
x_rotation_matrix[5] = (float) cos(-yaw * (PI / 180));//);// * (PI / 180)
x_rotation_matrix[6] = (float) -sin(-yaw * (PI / 180));// * (PI / 180));
x_rotation_matrix[7] = 0;
x_rotation_matrix[8] = 0;
x_rotation_matrix[9] = (float) sin(-yaw * (PI / 180));// * (PI / 180));
x_rotation_matrix[10] = (float) cos(-yaw * (PI / 180));// * (PI / 180));
x_rotation_matrix[11] = 0;
x_rotation_matrix[12] = 0;

```

Same issue with `y_rotation_matrix`.

---
Tags: opengl, java, mathematics, matrix
---


# Question
Title: Missing textures after making a build in Unity
I am working with a 2D game, in Unity. I am able to see the texture, in the Unity editor, but after taking the desktop build the texture is not visible to the scene.

What could be the problem?

# Answer
You say 'I am able to see the texture in the editor' - you *do not* say 'in the editor, I can see the texture *when I run the game*'.

While it is difficult to diagnose the *exact* problem, based off your provided description, it is important to remember that in a build, we will only see our game as it appears in the *game* view. In contrast, there are many situations where an element would be visible to the *editor view*, but not visible to the *game view*.

---

Ensuring the texture *is* visible to the game view ensures that the texture *should* be visible in a build. If you *can not* see it in the game build, this could help further diagnose the problem. This seems to be confirmed, through comments.

> Its a the problem with my camera view – `user1509674` Oct 7 '16 at 10:40

---

There are a couple of ways in which a camera may be set up to limit the display of the texture.

### Position

If an object is not within your camera's field of view, it will not be rendered to the screen. It should be obvious that the texture needs to be *in front* of the camera, but there are other variables that effect whether the texture will be rendered, based off it's position relative to the camera.

* **Clipping plane**: The camera's *clipping plane* determines both the closest and furthest distances to which the camera will render. Anything *before* the local `Near` distance or *after* the local `Far` distance does not get rendered by the camera. The camera has a gizmo to let you drag these distances in and out, via the inspector. It should be noted that a negative `Near` distance will allow you to include objects *behind* the camera, if this should ever be useful.

* **Size / Field of View**: An *orthographic* camera will have a *size*, while a *perspective* camera will have a *field of view*. These values effectively do the same thing; they determine the size of the camera's view. In the case of *perspective* cameras, the camera's view becomes an angle; the further away you get, the wider the view. As such, the closer an object gets to the camera, the closer it needs to be to the cameras center view for it to be rendered.

### Texture Rotation

It is important to note the rotation of the object containing your texture. Ideally, you want your texture to be *facing* the camera. Since a texture is 2D, it does not have a Z depth; if you face it away from the camera, at a 90 degree angle, it simply will not be visible.

### Culling Mask

Lastly, it is possible that the camera is being told to cull the layer containing the texture. There are many reasons you may want to actually do this, but it is important to remember that a culled layer will not be rendered to that camera. Under the `SpriteRenderer` attached to your texture object, you will find a `Sorting Layer`. Ensure that this value is checked, on the camera, under `CullingMask`. Alternatively, ensure that the camera has it's `CullingMask` set to `Everything`.
> 1 votes

# Answer
As Gnemlock points out in a comment above, even though in this specific case the problem seems to have been due to the camera being misaligned for viewing the texture, this question may attract hits from people with other problems leading to these symptoms:

* The textures appear normal when viewing scenes in the editor.
* Textures are missing or show black/magenta default appearance when running a compiled build of the game.

So, here are a couple of things you can try to troubleshoot these types of problems:

1. Close Unity, delete your Library folder, then re-open Unity.

Unity keeps a cache of pre-processed assets in this folder, and occasionally they can become corrupted, leading to strange behaviour. All of your source assets are in your Assets folder, so deleting Library won't lose any of your work - it just forces Unity to do a full re-import on its next run, giving you a clean asset cache to work from.
2. Close Unity, reset file permissions on all files in your project, then re-open Unity.

As mentioned in my comment above:

> I had something similar happen recently on a project where multiple user accounts were editing assets in a shared folder. The OS file system decided to give one user exclusive permissions to some files. They still displayed fine in the Unity editor (presumably it was using the Library's cached assets generated by the owner user), but when a build was generated by the second user the assets would be missing. Resetting permissions on all files in the project fixed it. Can you check the problem textures/materials to see if their permissions look odd?
> 1 votes

# Answer
If you drew something which contains transparency, the transparency might be the problem.

---

I had a similar issue, using Tiled. The scene was fine with transparent tiles on upper layers. However, my app did not manage the transparency correctly, and the lower layers was invisible on screen.
> 0 votes

---
Tags: unity, textures
---


title: Need help reducing my build's size

text:
# Question
Title: Need help reducing my build's size
I developed an Android game using Unity3D and successfully published it in Play Store. But the apk size almost 30MB which is pretty big for my game. When I checked the Editor Log after the build, this is what I found:

```
Textures      2.5 mb     20.1%
Meshes        433.8 kb   3.4%
Animations    2.2 kb     0.0%
Sounds        3.9 mb     31.3%
Shaders       191.3 kb   1.5%
Other Assets  157.9 kb   1.2%
Levels        166.9 kb   1.3%
Scripts       1.2 mb     9.4%
Included DLLs 3.9 mb     31.5%
File headers  44.5 kb    0.3%
Complete size 12.5 mb    100.0%
```

I just don't understand how could the final build will weigh more than twice the size stated in the log

# Answer
> -2 votes
In your case, most of the space is occupied by sound and texture.

* For sound, compress big sound into mono, and compression formats should be streaming.
* For texture, compress big textures. You can find thee textures that occupy more size via the editor log and compress them while they do not become blurred.

In Unity, go to *"Player Settings"* -\> "*Device Filter*" -\> "*Choose Armv7*'; it may help you.

# Answer
> -1 votes
Unity runtime is taking up a lot of space. You could try reducing the build size by stripping the assemblies. Refer to the documentation about stripping byte code on android under "Other settings" in build settings window. You can also try downloading the assets from the web on first run. There is not much else to do than that.

---
Tags: unity, android
---


# Question
Title: Handheld video playback pauses when going to the home screen
Put an MP4 movie in your StreamingAssets folder and play it with

```
Handheld.PlayFullScreenMovie("MyMovie.mp4", Color.black, FullScreenMovieControlMode.CancelOnInput);

```

Then, in the middle of the movie, go to the home screen and then go back to the game. The video is paused.

You can't resume it because upon tapping the screen the video will disappear because of the `CancelOnInput` parameter (which I want to keep).

So - how can I make it so when the player returns to the game, the video resumes? I don't want to show video controls.

I am using Unity Pro 5.4.2, running on an iPhone 7 with iOS 10.1.

# Answer
All I can offer is a workaround.

Use `Object.DontDestroyOnLoad` to make the object persistent. Pause the video, and after detecting which screen I am in, if it is the main menu:

```
if (SceneManager.GetActiveScene().buildIndex == 0) //main menu
{
   GetComponent(MeshRenderer).enabled = false; //hide the video.
}
if (SceneManager.GetActiveScene().buildIndex == 1) //game screen
{
   GetComponent(MeshRenderer).enabled = true; //also play the movie
}

```

You can also keep some Player Preferences and pull it in to other scenes to destroy the persistent video, when you don't need it.
> 1 votes

---
Tags: unity, ios, iphone, video
---


title: Unity 5 Animator will not disable

text:
# Question
Title: Unity 5 Animator will not disable
I am making a small FPS in unity 5. I made a cursor animation that I want to play only for a brief moment. I tried to do this using some code:

```
using System.Collections;

```

using System.Collections.Generic; using UnityEngine; using UnityEngine.UI;

public class CrossAnimate : MonoBehaviour {

```
public GameObject UpCurs;
public GameObject DownCurs;
public GameObject LeftCurs;
public GameObject RightCurs;

// Use this for initialization
void Start () {

}

// Update is called once per frame
void Update () {
    if (Input.GetMouseButtonDown(0))
    {
        UpCurs.GetComponent<Animator>().enabled = true;
        DownCurs.GetComponent<Animator>().enabled = true;
        LeftCurs.GetComponent<Animator>().enabled = true;
        RightCurs.GetComponent<Animator>().enabled = true;
        WaitingAnim();
    }
}

IEnumerator WaitingAnim()
{
    yield return new WaitForSeconds(0.1f);

    UpCurs.GetComponent<Animator>().enabled = false;
    DownCurs.GetComponent<Animator>().enabled = false;
    LeftCurs.GetComponent<Animator>().enabled = false;
    RightCurs.GetComponent<Animator>().enabled = false;
}

```

}

All of the four animators on the four gameobjects (UpCurs, DownCurs, etc) are not enabled by default. When clicking the mousebutton they should be enabled so it plays the animation and then after a brief time, they should disable again. The problem is that they don't disable.

Any help would be appreciated!

# Answer
You call a Coroutine by using `StartCoroutine("method name")`. Calling it like this probably does not trigger the yield and thus nothing happens so your code should look like :

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

    public class CrossAnimate : MonoBehaviour {

    public GameObject UpCurs; public GameObject DownCurs; public GameObject LeftCurs; public GameObject RightCurs;

    // Use this for initialization void Start () {

    }

    // Update is called once per frame void Update () {
        if (Input.GetMouseButtonDown(0))
        {
            UpCurs.GetComponent<Animator>().enabled = true;
            DownCurs.GetComponent<Animator>().enabled = true;
            LeftCurs.GetComponent<Animator>().enabled = true;
            RightCurs.GetComponent<Animator>().enabled = true;
            StartCoroutine(WaitingAnim());
        } }

    IEnumerator WaitingAnim() {
        yield return new WaitForSeconds(0.1f);

        UpCurs.GetComponent<Animator>().enabled = false;
        DownCurs.GetComponent<Animator>().enabled = false;
        LeftCurs.GetComponent<Animator>().enabled = false;
        RightCurs.GetComponent<Animator>().enabled = false;
}
}

```
> 1 votes

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


title: Can I use Marvel characters in games?

text:
# Question
Title: Can I use Marvel characters in games?
I want to develop an android game containing Marvel or DC characters, and publish it to Google Play.

Do Marvel or DC have copyright on their characters? If so, can that affect whether I can publish my game to Google Play?

# Answer
**No, you can not include Marvel and DC characters in your game1**. Yes, Marvel and DC both copyright their characters. No, you can not copy them without *extreme risk of gross legal repercussions*, and *Yes*, this will affect how your game is received by Google via the Play Store.

---

Marvel and DC characters are both protected under copyright protection. If you use their characters in your game, they are completely within their right to sue the pants off you. I am not a lawyer, but can confidently say they will succeed.

You also have to consider the fact that they have a lot more money to work with, in regards to legal expenditure. Marvel are owned by Disney, and DC are owned by Warner Bros.

To give a clear example, Marvel sued NCSoft over their MMO franchise "City of Heroes / City of Villains". The claim was that the character customisation allowed players to make *variations* of the copyrighted heroes - to my knowledge, the developers were not even accused of straight out copying the characters. While it is said that this case worked out in favour of NCSoft, they still had to pay out. Marvel simply lost a *majority* of their claims, as NCSoft were able to proove that many of the "infringements" were in fact created by Marvel employees, themselves. At the end of the day, they still settled, and they still had to pay out.

Copyright infringement is also listed as a reportable violation on Google Play. At best, they will take your game down. At worst, they will block your account from further publishing, and may even notify the original authors to further pursue the matter.

### Is there any way to do this, legally?

If you first gain *permission* to use the characters, there should be no problem. This is still a *massive* road block - were talking intellectual property that is worth millions, if not billions, of dollars. It is *highly* unlikely that either company would even consider entering into *consideration* of signing such a contract with anyone but a AAA company. It is even more unlikely that anyone other than a AAA company could even *begin* to afford the potential licensing costs.

***I am a AAA developer! Where do I start?***

The simple fact is, if you were a AAA developer, you would not be coming here to ask a legal question. You would be asking your *legal team*. If you *really* want to entertain this idea, consult a lawyer. It *is* worth noting that Activision had an exclusive deal2 with Marvel, and that Disney terminated this deal. After announcing the discontinuation of the Disney Infinity franchise, Disney *are* now pursuing Marvel as a *licensing opportunity*, so they do entertain the idea of licensing their characters to other game developers. I can find no evidence that Warner Bros. entertain licensing their characters, but there is certainly no developer exclusive contract.

---

### Seems there is a much better option

As a final note, it is worth considering the obvious. If you want some good characters for your game, it is going to be significantly less expensive to simply pay a designer to make the characters for you. *You should still consult a lawyer*, in regards to this. Such contracts need to be watertight, to ensure both parties have the rights they interpret. For example, there is a difference between paying for an artist to make a series of characters for you to use in your game and paying an artist to make a series of characters *that you then own*, to use in *future* games and representations.

1 Technically, the answer is \*"Yes you can, if you want Marvel or DC to sue you for everything your worth, and your not worried about being banned from the Google Play Store, as a developer.

2 In an exclusive contract, the game developer may pay more; but they are buying the *only* rights to those characters. For the entire length of the contract, the original owners *may not* sell or offer license to any other developer.
> 2 votes

---
Tags: copyright, google-play
---


# Question
Title: Phaser game is not registering collisions and input - but only on my machine
I was developing a game with Phaser and the Zenva Phaser Tutorial. I did some work on it last night, checked it was working, and went to bed. This morning, it isn't working! Input (either touch or mouse click) is not working, and the player no longer collides with the floor, but rather he sinks to the bottom.

Here is my game, and here is my git source. I have given a GitHub link, because I'm not receiving an error, and I can't pinpoint the issue.

Other users have confirmed that my game works, but when I run it, it is not the case.

# Answer
> 1 votes
I was able to solve it by clearing my local cache in my browser history.

Lesson learnt: clear the cache if weird localised problems happen.

---
Tags: phaser
---


title: Layered UI architecture

text:
# Question
Title: Layered UI architecture
I'm working on GUI system and I want to implement tooltips and dialogs.

Base components hierarchy looks like this:

So every panel extend `ComponentContainer` class, and other controls like button extend `Component` class

This is my current component hierarchy:

My main idea to add layers. For example first for components, second for tooltips, third for different dialogs, but I can't realize where they should be in this structure... and if dialog will contain some fields with tooltips, how should it work?

Any ideas?

UPD: The question about layers and class structure with layers. How they should be organized considering the fact that they will be used to hold dialogs and tooltips.

Event handling already implemented and it will not be so complicated to add it for layers.

# Answer
I have all my UI nodes in a tree, I then walk the tree and add the visible nodes to there respective draw queues, as I'm adding nodes to queues I also check if the mouse is over the current node and then add that node to the mouse courser\tooltip layer.

I have a queue for each blend type, a queue for the mouse layer and then a queue for each font type.

The ui tree node walking happens in the update method, where all the click and change events happen.

Each node also has a depth value for draw order within the queue, I have the back layer set as 1.0 and the front as 0.0 then if I draw a window with other controls on it as children I have there depth set as parent.depth - 0.01 and the windows depth set to some value based on where i want it to be.

In the image the window has a depth of 0.85 and all of the controls on in the window have a depth of 0.84, the health bar container and the item slots have a depth of 0.95 while the health bars have a depth of 0.94.

The tooltip in the left corner has a depth of 1 for the back ground a depth of 0.99 for the text.

The tooltip can have a depth of 1 because its layer is drawn after everything else so it will be the front most anyway.
> 1 votes

# Answer
I have build basic GUI, its almost the same as the one in picture , my main class is GUIManager witch own everything and deals with drawing , keyboard , mouse events .

```
class GUIManager
{
public:
    GUIManager();
    ~GUIManager();
    // Add Methods
    std::shared_ptr<GUITextInput> AddTextInput(std::string name, int x, int y, int width, int height,int zindex=0, std::wstring fontfamily = L"Minion Pro");
    std::shared_ptr<GUIButton>  AddButton(std::string name, std::string title, std::string path, int x, int y, std::string value = "", int zindex=0 ,std::wstring font = L"Minion Pro", float fontsize = 15, bool textbold = true);
    std::shared_ptr<GUIPanel> AddPanel(std::string name, std::string path, int x, int y, int zindex = 0);
    std::shared_ptr<GUITextArea> AddTextArea(std::string name, int x, int y, int width, int height, std::string value = "", int zindex = 0, std::wstring fontfamily = L"Minion Pro", float fontsize = 14, bool bold = true);
    std::shared_ptr<GUITextBox> AddTextBox(std::string name, std::string text, int x, int y, int width, int height, int zindex = 0, std::wstring fontfamily = L"Minion Pro", float fontsize= 14, bool bold = true);
    std::shared_ptr<GUICheckBox> AddCheckBox(std::string name, std::string value, std::string path, int x, int y, int width = 0, int height = 0, int zindex = 0);
    std::shared_ptr<GUIList> AddList(std::string name, std::string topic, std::string dvalue, int x, int y, int width, int height, int zindex=0, std::wstring fontfamily = L"Minion Pro", bool bold=true);
    //Handling methods
    void Draw(Graphics& gfx);
    void Update(Mouse& mouse,Keyboard& kbd);
    void SortByZIndex();
    void ClearGUI();
    //Getters
    std::shared_ptr<GUIElement> GetElement(std::string name);
private:
    void MouseHandler(Mouse& mouse);
    void KeyboardHandler(Keyboard& kbd);
private:
    std::vector<std::shared_ptr<GUIElement>> Elements;
};

```

all my elements are stored inside `std::vector<std::shared_ptr<GUIElement>> Elements;` GUIElement class is parent class of all element each element have child class who overrides GUIElement some of methods depends on needs. Also GUIElement , have some futures like border , label , and ect . i can enable that for each element is part of GUIElement .GUIManager have have funtions to add element to element vector and return pointer to it so you wont need to cast them later , there is also Funtion GetElement(std::strin elementname); but this function returns GUIElements witch means only parent class funtions will by available unless they are overrided by child class , so in that case it will be called child class functions instead of parent
> 0 votes

---
Tags: architecture, gui
---


# Question
Title: Point system that is not competitive or has a clear goal
I'm making a game in which the goal is to reach as much entries as possible and I want the player to see that he is making progress somehow. However the game shouldn't be of competitive nature (it co-operative), so I feel that points might not be the right measure. I thought instead of a progress bar, so you work towards a goal of entries. However the problem with this is that there isn't a specific number of entries the user should aim for; The more, the better.

Is there a way of showing progress without assuming there is an end and without it getting competitive?

# Answer
> 2 votes
Give the players some recognized milestones.

Whenever they complete a certain number of objectives, make *something* happen to reward them. That *something* can be a new game mechanic, making more game content available, giving them more character customization options, a change to the game environment (which can just be a big "completed" over a whole section of your level select screen) or just a virtual trophy (like an achievement). None of these rewards really needs to be that big regarding the development effort you put into it. What matters here is that the game somehow acknowledges that the player fulfilled some arbitrary goal.

If you want the game to be cooperative in nature, you could make some of these rewards apply to all players equally.

Note that even if your game is designed to be "endless" in theory it won't be endless in practice. There will always be a point where the player had enough of your game mechanics and abandons your game. Ideally your final milestone should be as close as possible to that point for most players so that they have a feeling of completion. Where exactly is that point? That's something you really can only find out through lots of playtesting.

# Answer
> 1 votes
People will always find a way to compete. Either completion time, remaining HP/buildings, etc. It makes games for them more fun. You should be thinking about why is competition wrong? Competition can be detrimental, when one players' fun ruins the fun of others.

I am going to assume that the problem you want to solve is players who should be cooperating are instead competing for points. A simple solution: make the points shared, so cooperation will get them more points!

Specifically creating a system that both shows progress towards the same thing and is not comparable to the other persons is not possible. You can make it hard to compare their progress, but not impossible. A progress bar can still be compared to another progress bar.

However if you give players different objectives/side goals and a different way of showing progress, that could be a solution. This usually involves asymmetric gameplay. For example showing points to a healer based on his total healing or amount of revives, while the fighter would get a different number. There are other ways to do this too: make players focus on different aspects of gameplay, but its hard to go into details without knowing the type of game you are creating.

**TL;DR:** People will compete anyways. Give them different goals if you want their points to be incomparable.

# Answer
> 1 votes
If you like the visual aesthetic of the progress bar, you could have it fill up and then reset once full (perhaps with fireworks, or offering some other bonus)

If you prefer points, you could use points, but have it so both players share the same point total.

But as akaltar pointed out, people will find a way to compete. I know in one co-op game my friends and I were playing, we would race to see who could open each door first, even though the game did not care. God only knows what would have happened if the game actually kept track of that. Incomparable goals can help prevent that.

# Answer
> 0 votes
If there's progress determinable, you've got innate competition and cooperation.

How you motivate the players around that presentation of progress is going to determine if they focus on competing or cooperating.

So the presentation of progress itself isn't the problem, the context is.

# Answer
> 0 votes
People already provided some good answers, but I'd like to add my perspective to it.

---

**1. Team Score:**

I really don't see why people in a cooperative game should get individual scores. I'd suggest giving them a team score. You can add individual scores, as well, for "personal performance identification reasons". Just give it a less prominent position in the UI or scoreboard. You may also add some rewards for the maximum team score. Skins, or even achievements, will do. They will endorse cooperative play, and the better player will have more incentive to help the worse player.

**2. Objectives:**

As Akaltar already posted, give them different objectives. A cooperative game should be a-symmetrical in nature, or it's not worth cooperating with each other. If both players can do everything, one will steamroll ahead, while the other falls back.

**3. Severely Punish Competition:**

Just make it ridiculously hard to progress alone, and reward cooperative play in a difficulty sense. This is really genre dependent. Let's say it's an RPG. Give the "Tank" limited or no ways to heal, so they are dependant on the "Healer" or "DPS".

---

These ideas are, of course, very hard to get right. Going too far with them may be negatively perceived by the players. If one player is really good, and other really bad, it's just frustrating to the better player. You could help this a little by giving both players an individual difficulty setting. This way, people who really want to play together but are of different skill levels can still do so, and the high score hunters get rated off their lowest difficulty setting (or something of that like).

---
Tags: game-design
---


# Question
Title: What is the bare minimum I need to set up the Android SDK for Unity development?
I want to import my Unity project to Android, and I need to download the Android SDK, but I do not want to download any unnecessary components.

Do I need to download all platforms, or just the latest one? I am worried about the size of Android 7.1.1 (API Level 25); the SDK Manager reports this as the latest version, but I am not sure.

I only want to import my project for Android smartphones, with no plan of publishing it. I do not want to build to Android TV or Android Wear, for example. Do I need to download all of the contents under the specific platform? I ask because there are Android TV and Android Wear system images, and the files can get quite large.

# Answer
> 0 votes
The first thing you will need is the actual SDK Manager. You can download the command line version from the official website, but I found a link to the Windows GUI version via a helpful Stack Overflow question. The official link should provide the GUI version for both Mac OS and Linux. As of this answer, this download is 145Mb.

Note that if you intend to use Android Studio at some point, you should just download Android Studio. This will come with the SDK Manager, though it will greatly increase the size of your download. Android Studio is currently quoted at *1, 674Mb*, which is grossly oversized, in comparison to the other files and the simple fact that it is *not* a requirement.

If you do not have it, you will also need to install the Java Development Kit. The current version is about 200Mb1, and you will need to have it installed for the SDK Manager to complete it's installation.

---

From here, your actually on easy street. You should only need the *latest* SDK Platform. As of this answer, that version is API 25, also known as Android Nougat 7.1.1. This file is listed as exactly 81.5Mb.

Since you are already in the SDK Manager, it would help to *also* download the Android USB Driver. You will find this under "Extras", at a meager 8.3Mb. These drivers are often required in order to play test your games, using the Unity Remote app.

---

***Do I need to download the latest version?***

Yes and no. With each API release, Google have added more features and change to how the API works. If your project only used features up to API Level 15, for example, you would only need to install API Level 15. It is far easier to simply keep up to date than to ensure you have the API up to the level you require. According to Unity documentation, the bare minimum required is API Level 9, also known as Android Gingerbread 2.3.

***What if my players have an older version of Android?***

Older versions of android should still support *the language* of newer APIs - they just won't necessarily support the newer *features*. This *is* something you want to take into account; if only to ensure that you build your game to the correct *minimum API level*. You may also want to consider the percentage of users using each API level.

***Do I need to download the additional images?***

No. The additional images are merely *device images*. If you were to be using Android Studio, and you wanted to run your application on a particular hardware emulator, that is when you would need to have the appropriate images installed.

***I am making a game for the phone - don't I need the phone images?***

No. Assuming you *have* an android phone, you should use your *physical* phone to test your game. The image is only for running emulated Android on your computer; to my knowledge, it still requires being run from Android Studio, and it is known to be a bit unpredictable in regards to performance.

***All in all, what are the damages?***

Assuming the bare necessities, including the USB drivers, you need the following:

* Android SDK Manager: 145Mb
* Java Development Kit: 200Mb
* Latest SDK Platform: 81.5Mb
* Android USB Drivers: 8.3Mb

Assuming you have already installed the Android SDK Manager, you only have a meager 89.8Mb of download left to complete. Assuming you start from scratch, your looking at a download of 434.8Mb. *This is still less than 30% of the download required to use Android Studio*, the official Android development software.

1 Linux and Mac versions are considerably smaller.

---
Tags: unity, android
---


title: Raycast2D ray not follow object

text:
# Question
Title: Raycast2D ray not follow object
I have some Raycast2D problem. I want raycast follow the object like this:

But when I drag object somewhere the ray looklike this :

Here is my code where is my fault. Please help :(

```
using UnityEngine;
using System.Collections;
public class RayCast : MonoBehaviour {
private float uzunluk = 5.0f;

void Start ()
{
}
void Update () {
    BoxCollider2D col2 = new BoxCollider2D();
    Vector2 dirs = new Vector2 (0, -1);

    Vector2 obj = new Vector2 (transform.position.x , (transform.position.y- 0.375f));
    RaycastHit2D hit = Physics2D.Raycast (obj, dirs , uzunluk);
    Debug.DrawLine (obj, dirs , Color.cyan);
    if (hit.collider != col2)
    {
        Debug.Log("çarptı");
    }
}
}

```

# Answer
> 1 votes
your Ray should be working fine you are just using the wrong debugging function. DrawLine draws a line in between 2 points not on that direction like the ray. Use Debug.DrawRay instead. Good Luck.

---
Tags: unity, 2d, raycasting, gameobject
---


# Question
Title: What is the best collision detection method or algorithm for a 2d platformer?
I'm working of a 2d platformer. It's a preety simple game, but the ground is flat and it looks boring. I did the collision detection for it and it's all working when the boxes are axis aligned, but I want to add slopes so it's more interesting. I researched a lot and I found the separating axis theorem but I read that it is not good for platformers because it's not side specific. So, my question is: what is the best way to detect collision with curves and slopes? I use javascript if you want to provide some code. Thanks in advance!

# Answer
> 2 votes
For horizontal boxes AABB is great, for slopes, you need to add a twist to it.

The height of a slope that's positioned between x1 and x2 at a specific point can be calculated the following way (x is the point we want to get the height at, h1 is the height at x1 and h2 is the hight at x2):

```
height := (x - x1) / (x2 - x1) * (h2 - h1) + h1

```

Now, first you need to check if the player collides with the aabb of the slope (this is the broad phase), if it does, then get the height of it at the player's position.

Next, check if the player's height is less than the result, if it is and he's fallong, then set his y coordinate to the height of the slope and if he has one, set his vertical velocity to 0.

This doesn't work with the underside of the slopes, if you want that too, you need to do the same for that too.

---
Tags: 2d, collision-detection, javascript, platformer
---


# Question
Title: What is the shader format for Metal shaders shipped with iOS applications?
I am interested in analyzing existing shaders implemented using Apple's Metal framework. From my previous experience on other platforms with OpenGL, I have found that applications sometimes bundle shader code more or less in plaintext within the application binary. I have not found this to be the case with iOS.

* Is there a special final format that Metal shaders are compiled into?
* Can they be disassembled?
* Where should one normally look for shader code in iOS applications?

Please let me know if this isn't posted on the right SE before downvoting. I was torn on whether this should go on Graphics SE or GamesDev SE. I *do not* think this should go on ReverseEngineering, or Security SE, as I fear those communities have very little experience with shader formats and likely wont be much help.

# Answer
> Is there a special final format that Metal shaders are compiled into?

Yes. They're compiled into a proprietary format (LLVM-based, device-agnostic intermediate language) that is not publicly documented. This happens as part of the build process, by default; the Xcode toolchain has a build rule to take Metal source files, compile them, and shove the output `.metallib` into your application's bundle someplace. Apple's documentation covers this in more detail.

> Can they be disassembled?

You should be able to use llvm-dis to do so, although I've never actually tried. You may not be able to use it directly on the `.metallib`.

> Where should one normally look for shader code in iOS applications?

In the "Resources" directory of the application's bundle. That would be a good place to *start* at least. A developer could choose to put them elsewhere.
> 3 votes

---
Tags: ios, metal
---


# Question
Title: D3DCompileFromFile() failed, gives an error HRESULT
i'm reading the "3D game programming with directx 11 " book (Frank Luna) and i'm struggling becouse he uses the old D3DX11CompileFromFile() method, which can't be used anymore. So i searched on internet how to solve this problem and i found out i have to use D3DCompileFromFile instead, which is a little bit different, but not totally. Now this is my script

```
DWORD flags = D3DCOMPILE_ENABLE_STRICTNESS | D3DCOMPILE_DEBUG;
    ID3DBlob*compiledShader = nullptr;
    ID3DBlob*compilationMsgs = nullptr;

    HRESULT hr = D3DCompileFromFile(L"FX/effects.fx", 0, 0, 0, "fx_5_0", flags, 0,  &compiledShader, &compilationMsgs);

    if (FAILED(hr))
        MessageBox(0, L"Failed D3DCompileFromFile", 0, 0);  //THIS POPS OUT

```

I did this by myself and than i started copying things from internet to make it work. Could the problem be in entryPoint=0? What do i have to put there? This is the effect.fx file

```
cbuffer cbPerObject
{
    float4x4 gWorldViewProj;
};
struct VertexIn
{   float3 Pos : POSITION;
    float4 Color : COLOR;
};

struct VertexOut {
    float4 PosH : SV_POSITION;
    float4 Color : COLOR;
};
VertexOut VS(VertexIn vin) {
    VertexOut vout; // Transform to homogeneous clip space.
    vout.PosH = mul(float4(vin.Pos, 1.0f), gWorldViewProj); // Just pass vertex color into the pixel shader.
    vout.Color = vin.Color; return vout; }

float4 PS(VertexOut pin) : SV_Target {
    return pin.Color;
}
technique11 ColorTech {
    pass P0 {
        SetVertexShader( CompileShader( vs_5_0, VS() ) );
SetPixelShader( CompileShader( ps_5_0, PS() ) );
    }
}

float3 iPosL; // local space
float3 gEyePosW; // world space
float3 normalV; // view space
float4 posH; // homogeneous clip spac

```

Thanks

# Answer
Here's a robust replacement for `D3DX11CompileFromFile` using the D3DCompile DLL instead:

The `D3D_COMPILER_VERSION < 46` case is if you are using the legacy DirectX SDK, otherwise you should be using the Windows 8.x SDK or Windows 10 SDK version.

```
#if D3D_COMPILER_VERSION < 46
namespace
{

struct handle_closer { void operator()(HANDLE h) { if (h) CloseHandle(h); } };

typedef public std::unique_ptr<void, handle_closer> ScopedHandle;

inline HANDLE safe_handle( HANDLE h ) { return (h == INVALID_HANDLE_VALUE) ? 0 : h; }

class CIncludeHandler : public ID3DInclude
    // Not as robust as D3D_COMPILE_STANDARD_FILE_INCLUDE, but it works in most cases
{
private:
    static const unsigned int MAX_INCLUDES = 9;

    struct sInclude
    {
        HANDLE         hFile;
        HANDLE         hFileMap;
        LARGE_INTEGER  FileSize;
        void           *pMapData;
    };

    struct sInclude     m_includeFiles[MAX_INCLUDES];
    size_t              m_nIncludes;
    bool                m_reset;
    WCHAR               m_workingPath[MAX_PATH];

public:
    CIncludeHandler() : m_nIncludes(0), m_reset(false)
    {
        if ( !GetCurrentDirectoryW( MAX_PATH, m_workingPath ) )
            *m_workingPath = 0;

        for ( size_t i = 0; i < MAX_INCLUDES; ++i )
        {
            m_includeFiles[i].hFile = INVALID_HANDLE_VALUE;
            m_includeFiles[i].hFileMap = INVALID_HANDLE_VALUE;
            m_includeFiles[i].pMapData = nullptr;
        }
    }
    virtual ~CIncludeHandler()
    {
        for ( size_t i = 0; i < m_nIncludes; ++i )
        {
            UnmapViewOfFile( m_includeFiles[i].pMapData );

            if ( m_includeFiles[i].hFileMap != INVALID_HANDLE_VALUE)
                CloseHandle( m_includeFiles[i].hFileMap );

            if ( m_includeFiles[i].hFile != INVALID_HANDLE_VALUE)
                CloseHandle( m_includeFiles[i].hFile );
        }

        m_nIncludes = 0;

        if ( m_reset && *m_workingPath )
        {
            SetCurrentDirectoryW( m_workingPath );
        }
    }

    STDMETHOD(Open( D3D_INCLUDE_TYPE IncludeType, LPCSTR pFileName, LPCVOID pParentData, LPCVOID *ppData, UINT *pBytes ) )
    {
        UNREFERENCED_PARAMETER(IncludeType);
        UNREFERENCED_PARAMETER(pParentData);

        size_t incIndex = m_nIncludes+1;

        // Make sure we have enough room for this include file
        if ( incIndex >= MAX_INCLUDES )
            return E_FAIL;

        // try to open the file
        m_includeFiles[incIndex].hFile  = CreateFileA( pFileName, GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, nullptr );
        if( INVALID_HANDLE_VALUE == m_includeFiles[incIndex].hFile )
        {
            return E_FAIL;
        }

        // Get the file size
        GetFileSizeEx( m_includeFiles[incIndex].hFile, &m_includeFiles[incIndex].FileSize );

        // Use Memory Mapped File I/O for the header data
        m_includeFiles[incIndex].hFileMap = CreateFileMappingA( m_includeFiles[incIndex].hFile, nullptr, PAGE_READONLY, m_includeFiles[incIndex].FileSize.HighPart, m_includeFiles[incIndex].FileSize.LowPart, pFileName);
        if( !m_includeFiles[incIndex].hFileMap )
        {
            if (m_includeFiles[incIndex].hFile != INVALID_HANDLE_VALUE)
                CloseHandle( m_includeFiles[incIndex].hFile );
            return E_FAIL;
        }

        // Create Map view
        *ppData = MapViewOfFile( m_includeFiles[incIndex].hFileMap, FILE_MAP_READ, 0, 0, 0 );
        *pBytes = m_includeFiles[incIndex].FileSize.LowPart;

        // Success - Increment the include file count
        m_nIncludes = incIndex;

        return S_OK;
    }

    STDMETHOD(Close( LPCVOID pData ))
    {
        UNREFERENCED_PARAMETER(pData);
        // Defer Closure until the container destructor
        return S_OK;
    }

    void SetCWD( LPCWSTR pFileName )
    {
        WCHAR filePath[MAX_PATH];
        wcscpy_s( filePath, MAX_PATH, pFileName );

        WCHAR *strLastSlash = wcsrchr( filePath, L'\\' );
        if( strLastSlash )
        {
            // Chop the exe name from the exe path
            *strLastSlash = 0;
            m_reset = true;
            SetCurrentDirectoryW( filePath );
        }
    }
};

}; // namespace

#endif

HRESULT WINAPI DXUTCompileFromFile( LPCWSTR pFileName,
                                    const D3D_SHADER_MACRO* pDefines,
                                    LPCSTR pEntrypoint, LPCSTR pTarget,
                                    UINT Flags1, UINT Flags2,
                                    ID3DBlob** ppCode )
{
    HRESULT hr;
    WCHAR str[MAX_PATH];
    V_RETURN( DXUTFindDXSDKMediaFileCch( str, MAX_PATH, pFileName ) );

#if defined( DEBUG ) || defined( _DEBUG )
    // Set the D3DCOMPILE_DEBUG flag to embed debug information in the shaders.
    // Setting this flag improves the shader debugging experience, but still allows
    // the shaders to be optimized and to run exactly the way they will run in
    // the release configuration of this program.
    Flags1 |= D3DCOMPILE_DEBUG;
#endif

    ID3DBlob* pErrorBlob = nullptr;

#if D3D_COMPILER_VERSION >= 46

    hr = D3DCompileFromFile( str, pDefines, D3D_COMPILE_STANDARD_FILE_INCLUDE,
                             pEntrypoint, pTarget, Flags1, Flags2,
                             ppCode, &pErrorBlob );

#else

    ScopedHandle hFile( safe_handle( CreateFileW( str, GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr ) ) );

    if ( !hFile )
        return HRESULT_FROM_WIN32( GetLastError() );

    LARGE_INTEGER FileSize = { 0 };

#if (_WIN32_WINNT >= _WIN32_WINNT_VISTA)
    FILE_STANDARD_INFO fileInfo;
    if ( !GetFileInformationByHandleEx( hFile.get(), FileStandardInfo, &fileInfo, sizeof(fileInfo) ) )
    {
        return HRESULT_FROM_WIN32( GetLastError() );
    }
    FileSize = fileInfo.EndOfFile;
#else
    GetFileSizeEx( hFile.get(), &FileSize );
#endif

    if (!FileSize.LowPart || FileSize.HighPart > 0)
        return E_FAIL;

    std::unique_ptr<char[]> fxData;
    fxData.reset( new (std::nothrow) char[ FileSize.LowPart ] );
    if ( !fxData )
        return E_OUTOFMEMORY;

    DWORD BytesRead = 0;
    if ( !ReadFile( hFile.get(), fxData.get(), FileSize.LowPart, &BytesRead, nullptr ) )
        return HRESULT_FROM_WIN32( GetLastError() );

    if (BytesRead < FileSize.LowPart)
        return E_FAIL;

    char pSrcName[MAX_PATH];
    int result = WideCharToMultiByte( CP_ACP, WC_NO_BEST_FIT_CHARS, str, -1, pSrcName, MAX_PATH, nullptr, FALSE );
    if ( !result )
        return E_FAIL;

    const CHAR* pstrName = strrchr( pSrcName, '\\' );
    if (!pstrName)
    {
        pstrName = pSrcName;
    }
    else
    {
        pstrName++;
    }

    std::unique_ptr<CIncludeHandler> includes( new (std::nothrow) CIncludeHandler );
    if ( !includes )
        return E_OUTOFMEMORY;

    includes->SetCWD( str );

    hr = D3DCompile( fxData.get(), BytesRead, pstrName, pDefines, includes.get(),
                     pEntrypoint, pTarget, Flags1, Flags2,
                     ppCode, &pErrorBlob );

#endif

#pragma warning( suppress : 6102 )
    if ( pErrorBlob )
    {
        OutputDebugStringA( reinterpret_cast<const char*>( pErrorBlob->GetBufferPointer() ) );
        pErrorBlob->Release();
    }

    return hr;
}

```

> This code is from the GitHub open source version of DXUT for Direct3D 11.

See HLSL, FXC, and D3DCompile

**As you are using the legacy Effects for Direct3D 11 system constructs**, you should use the GitHub version of Effects11 in which case you might as well just use `D3DX11CompileEffectFromFile` that version provides:

```
HRESULT hr = D3DX11CompileEffectFromFile(
    L"FX/effects.fx",
    nullptr, nullptr,
    flags, 0, device, &effect, &compilationMsgs);

if (FAILED(hr))
    // error

```

Since it has no include handler use of `#include` in your fx file will fail. The best solution is to use the default include handler that is part of D3DCompiler #46 or later:

```
HRESULT hr = D3DX11CompileEffectFromFile(
    L"FX/effects.fx",
    nullptr,  D3D_COMPILE_STANDARD_FILE_INCLUDE,
    flags, 0, device, &effect, &compilationMsgs);

if (FAILED(hr))
    // error

```

See D3DX11CompileEffectFromFile
> 1 votes

---
Tags: directx11
---


# Question
Title: How do I prevent jitter amongst near-stationary physics objects?
I have been implementing a custom physics engine, and I'm pretty close to having it working as I would like it to. There is a gravitational force, collisions and collision response. Unfortunately, there seems to be some jitter among near-stationary objects, most likely due to unchangeable low physics ticks.

I have looked online, and tried some of the implementations I have found, including some of my own attempts. Here are the solutions I tried:

* Damping movement when speed/momentum/potential energy is below a threshold.
* Only applying gravity when speed/momentum/potential energy is above threshold.
* Implementing a sleep function. that checks the position of the object for the last 60 frames, and sleeps if it hasn't moved outside a threshold bounding box.
* Iterating through the objects from top to bottom when applying collision testing and resolution.

---

Here is my code:

```
for each (auto ball in m_Balls)
{
    ball->Update(t);
    ball->Accelerate(m_Gravity);
}

// This disgusting hack sorts the balls by height. In a more complete physics
// implementation, I guess I could change the sorting based on the direction of
// gravitational force. This hack is necessary to prevent balls being pulled downwards
// into other balls by gravity; by calculating from the bottom of the pile of
// objects, we avoid issues that occur when adjustments push the object towards gravity.
m_Balls.sort([](const CSprite* a, const CSprite* b)
    {return a->m_pos.m_y < b->m_pos.m_y; });

static float cor = 0.8f;

for each (auto ball in m_Balls)
{
    for each (auto collider in m_Walls)
    {
        if (collider->HitTest(ball, 1))
        {
            float offset = 0;
            auto n = Helper::GetNormal(ball, collider, offset);

            ball->SetPosition(ball->GetPosition() + (n * offset));

            auto r = ball->GetVelocity() - ((1 + cor) * Dot(ball->GetVelocity(), n) * n);

            ball->SetVelocity(r);

            ball->SetPosition(ball->GetPosition() + ball->GetVelocity() * DeltaTime());
        }
    }

    CVector adjustment;

    for each (auto collider in m_Balls)
    {
        if (ball == collider)
        {
            break;
        }

        auto diff = collider->GetPosition() - ball->GetPosition();

        float distance = diff.Length();

        if (distance <= (ball->GetWidth() / 2) + (collider->GetWidth() / 2))
        {
            auto midPoint = (ball->GetPosition() + collider->GetPosition()) * 0.5f;

            adjustment = diff.Normalise() * (ball->GetWidth() / 2
                - Distance(ball->GetPosition(), midPoint));
            ball->SetPosition(ball->GetPosition() - adjustment);
            diff = collider->GetPosition() - ball->GetPosition();

            if (Dot(ball->GetVelocity() - collider->GetVelocity(), diff) > 0)
            {
                auto n = diff.Normalise();
                auto u = Dot(cor * ball->GetVelocity() - collider->GetVelocity(), n) * n;
                ball->Accelerate(-u);
                collider->Accelerate(u);
            }
        }
    }

    if (ball->GetSpeed() > MAX_SPEED)
    {
        ball->SetSpeed(MAX_SPEED);
    }
}

```

---

How do I prevent jitter amongst near-stationary physics objects?

# Answer
Well, it turns out that one of my boolean checks was causing this issue.

This code here:

```
if (ball == collider)
{
    break;
}

```

Was breaking everything. I was under the impression that it would simply ignore collisions with itself but for whatever reason, it was prevent collisions happening in the correct order. Not exactly sure why, I think it's a bug in the game engine I'm using. Anyway, here is the working code, which implements a sleep state for all balls - when movement after 30 frames is confined to certain bounding area, the object is put in a sleep state, during which no forces are applied to it (gravity in this instance). It is woken after it is shifted outside of this bounding area by something - typically a adjustment or collision by another ball.

```
    // This disgusting hack sorts the balls by height
    // In a more complete physics implementation I guess I could change the sorting based on the direction of gravitational force
    // This hack is necessary to prevent balls being pulled downwards into other balls by gravity... By calculating
    // From the bottom of the pile of objects, we avoid issues that occur when adjustments push the object towards gravity.
    m_Balls.sort([](const CSprite* a, const CSprite* b) { return a->m_pos.m_y < b->m_pos.m_y; });

    static float cor = 0.5f;

    for each (auto ball in m_Balls)
    {
        ball->Update(t);

        if (jitterBoundX[ball].size() < 30)
        {
            jitterBoundX[ball].push_back(ball->GetX());
            jitterBoundY[ball].push_back(ball->GetY());
        }
        else
        {
            jitterBoundX[ball].pop_front();
            jitterBoundY[ball].pop_front();
            jitterBoundX[ball].push_back(ball->GetX());
            jitterBoundY[ball].push_back(ball->GetY());

            float minx = jitterBoundX[ball].front();
            float maxx = minx;

            for each (auto f in jitterBoundX[ball])
            {
                if (f < minx) { minx = f; }
                if (f > maxx) { maxx = f; }
            }

            float miny = jitterBoundY[ball].front();
            float maxy = miny;

            for each (auto f in jitterBoundY[ball])
            {
                if (f < miny) { miny = f; }
                if (f > maxy) { maxy = f; }
            }

            auto xdif = maxx - minx;
            auto ydif = maxy - miny;

            if (ball->GetState() == 0 && xdif < 3 && ydif < 3)
            {
                ball->SetState(1);
            }
            else if (ball->GetState() == 1 && (xdif > 3 || ydif > 3))
            {
                ball->SetState(0);
            }
        }

        if (ball->GetState() == 0)
        {
            ball->Accelerate(m_Gravity);
        }
        else
        {
            ball->SetVelocity(CVector(0, 0));
        }

        if (IsLButtonDown())
        {
            ball->Accelerate(0.3f * ((CVector)GetMouseCoords() - ball->GetPosition()));
        }

        for each (auto collider in m_Walls)
        {
            if (collider->HitTest(ball, 1))
            {
                float offset = 0;
                auto n = Helper::GetNormal(ball, collider, offset);

                ball->SetPosition(ball->GetPosition() + (n * offset));

                auto r = ball->GetVelocity() - ((1 + cor) * Dot(ball->GetVelocity(), n) * n);

                ball->SetVelocity(r);
            }
        }

        CVector adjustment;

        for each (auto collider in m_Balls)
        {
            // This breaks everything.
            //if (ball == collider)
            //{
            //  break;
            //}

            if (ball->HitTest(collider, 0))
            {
                auto diff = collider->GetPosition() - ball->GetPosition();

                float distance = diff.Length();

                if (ball->HitTest(collider, 0))
                {
                    if (distance < (ball->GetWidth() / 2) + (collider->GetWidth() / 2))
                    {
                        auto midPoint = (ball->GetPosition() + collider->GetPosition()) * 0.5f;

                        auto discrepancy = (collider->GetWidth() / 2 - Distance(collider->GetPosition(), midPoint));
                        adjustment = diff.Normalise() * discrepancy;
                        collider->SetPosition(collider->GetPosition() + adjustment);
                        diff = collider->GetPosition() - ball->GetPosition();

                        //This actually seems to contribute to the wandering issue, it seems worth calculating the opposite collision
                        //As there may be adjustments made to the position during the previous iteration...
                        //if (gridSquares[GetGridIndex(midPoint, SPHERE_RAD)] == true)
                        //{
                        //  break;
                        //}
                        //gridSquares[GetGridIndex(midPoint, SPHERE_RAD)] = true;

                        if (Dot(ball->GetVelocity() - collider->GetVelocity(), diff) > 0)
                        {
                            auto n = diff.Normalise();
                            auto u = Dot(cor * ball->GetVelocity() - collider->GetVelocity(), n) * n;
                            ball->Accelerate(-u);
                            collider->Accelerate(u);
                        }
                    }
                }
            }
        }

        if (ball->GetSpeed() > MAX_SPEED)
        {
            ball->SetSpeed(MAX_SPEED);
        }
    }

```
> 1 votes

---
Tags: physics, vector, collision-resolution
---


# Question
Title: Turning a Java single player game into a multiplayer game
I recently built a game with libgdx for my desktop. I would like now to make it a multiplayer game.

How could I do this? I was thinking about using node.js but there are some problems: I use Box2D and other Java libraries to help me making the game simulation and this would be hard to write all over again in Javascript.

The other option would be to write a Java server. Honestly I never used sockets or anything related to networks in Java (I have always been a C++ guy). So, what would you guys recommend? What would be the best option?

Also I would like to consider the performance since Box2D simulations are a bit heavy and with Java I am able to use multi-threading while node.js doesn´t allow me to do that. (I also think Java itself is a bit faster than Javascript).

Just one more note. As I said before I never done anything network related with Java, so if you think Java is the best option could you also recommend some technologies and/or java libraries and/or articles about networking or server creation in Java?

Thanks for your time!

# Answer
Java sockets are not much farther from C++ sockets. It is actually a lot similar, with some managed stuff here and there.

You should gather some info on how other people are doing it, that should help you decide:

* I recommend checking on eAthena code to check how to handle multiple users online, receiving data from a tcp channel without blocking and other techniques (check the login-server, then char-server, then map-server, this order)
* I recommend you read the specs/protocol of any multiplayer game (Minecraft for example is very detailed) if you've never seen one before. This will help you have an idea on what kind of data to send over the sockets.
* These posts from GafferOnGames are also very useful.

Your better option is to indeed just make a new java module under your already made game, share the codebase and start coding.

> Just one more note. As I said before I never done anything network related with Java, so if you think Java is the best option could you also recommend some technologies and/or java libraries and/or articles about networking or server creation in Java?

Libgdx has some networking built-in. But it's very simplistic and it assumes a lot of stuff. It could work for you, but if it doesn't then I really recommend you use pure java sockets.

Opening a connection to a server is very easy:

```
channel = SocketChannel.open();
channel.configureBlocking(false);
channel.socket().setTcpNoDelay(true);

```

and receiving data is as easy as:

```
ByteBuffer rdata = ByteBuffer.allocateDirect(1024);;
channel.read(rdata);

```

But there are some stuff you might need to keep in mind: Java's `ByteBuffer` interface is a pain in the \***, you might spend some time trying to understand the concepts on `flip`, `compact`, `drain`, when you can read/write etc.

The rest should be easy. Good luck!
> 1 votes

---
Tags: java, javascript, networking
---


title: Sphere UV mapping. Texture Streched

text:
# Question
Title: Sphere UV mapping. Texture Streched
I am trying to write a sphere mesh algorithm. Unfortunately, is the texture stretched vertically at the very end of the image. This should be near U 0.99~.

Below is the code used for the sphere creation. In the Image below that you can see a sphere created by Maya with the correct textures applied to it. Therefore, the issue is defiantly the UV map created by this code.

If I increase the number of parallels that are wrongly called meridians. Then the texture looks nearly spot on, but one thin line of garbage.

Hope someone sees the issue. I worked on it for 2 days now :(
There is a live version online for a closed examination of the object. https://upmkuhn.github.io/AGAV/AGAV/

Btw what is the correct terminology for such an issue?

```
function makeSphere(radius, numParallels, numMeridians)
{
    var index = 0;
    var grid = [];
    var vertecies = [];
    var normals = [];
    var texture = [];
    var faces = [];

    for (var p = -1; p < numParallels; p++)
    {
        var row = [];
        var parallel = Math.PI * (p +1) / numParallels
        for (var m = -1; m < numMeridians; m++) {
            var meridian = 2.0 * Math.PI * m / numMeridians
            var cartesian = sphericalToCartesian(radius, meridian, parallel);
            var vec3xyz = vec3.create(cartesian);
            vertecies.push(cartesian);

            //NORMALS
            vec3.normalize(vec3xyz, vec3xyz);
            normals.push(vec3xyz);

            x = vec3xyz[0] == 0 ? 0 : vec3xyz[0];
            y = vec3xyz[1] == 0 ? 0 : vec3xyz[1];
            z = vec3xyz[2] == 0 ? 0 : vec3xyz[2];
            //UV
            var u = (Math.atan2(x, z) / (2 * Math.PI) + 0.5);
            var v = y * 0.5 + 0.5;

            texture.push(u,v);
            row.push(index++);
        }
        grid.push(row);
    }

    for (var i = 0; i < texture.length;i+=2)
    {
        var u = texture[i];
        var v = texture[i+1];
        if (Math.abs(u-v) < 0.5)
        {
        }
    }

    for (var p = 0; p < (numParallels ); p++) {
        for (var m = 0; m < numMeridians; m++) {

            if (m < numMeridians) {
                var p1 = grid[p][m];
                var p2 = grid[p + 1][m];
                var p3 = grid[p][m + 1];
                faces.push(p1, p3, p2, grid[p + 1][m + 1]);
            }
        }
    }

    return {
        vertecies: vertecies,
        normals: normals,
        texture: texture,
        faces: faces
    }
}

function sphericalToCartesian(radius, azimuth, elevation)
{
    var x = radius * Math.sin(elevation) * Math.cos(azimuth)
    var y = radius * Math.sin(elevation) * Math.sin(azimuth)
    var z = radius * Math.cos(elevation)
    return [x , y , z];
}
```

# Answer
> 0 votes
You should set `u` to `m / numMeridian` and `v` to `p / numParalell`

---
Tags: uv-mapping
---


# Question
Title: Finding distances between sprites in an array
i'm new to java and was hoping if anyone can help me out. So my game has meteors which spawns off screen and sometimes as they spawn, they overlap each other which I don't want. I want them to spawn from a certain distance from each other.

From pseudo code I know what I want which is to find the centre point of sprite, find other meteors on screen and calculate the distance and then spawn from a certain distance from each other. I know the distance to point formula (distance = Math.sqrt(Math.pow(x2 - x1, 2) + (Math.pow(y2 - y1, 2)));), but how do I do that within an array. Here is my code so far:

Meteor Class

```
public class Meteors {
    private Texture bigMeteor;
    private Vector2 posBigMeteor;
    private Random yrand;

    //Constructor
    public Meteors(float x){
        bigMeteor = new Texture("meteor.png");
        yrand = new Random();

        //Spawn location of meteor
        posBigMeteor = new Vector2(x, yrand.nextInt(AstroDemo.HEIGHT/2 - bigMeteor.getHeight()));
    }

    public Texture getBigMeteor() {
        return bigMeteor;
    }

    public Vector2 getPosBigMeteor() {
        return posBigMeteor;
    }

    public void reposition(float x){
        posBigMeteor.set(x, yrand.nextInt(AstroDemo.HEIGHT/2 - bigMeteor.getHeight()));
    }
}

```

Playstate Class

```
public class PlayState extends State {
    //Total meteor count on screen
    private static final int METEOR_COUNT = 8;

    private Naught naught;
    private Texture bg;
    private Random xrand;
    private Array <Meteors> meteors;

    public PlayState(GameStateManager gsm) {
        super(gsm);
        //Starting co-ordinates of main character (Naught)
        naught = new Naught(50, 100);
        //Setting viewport of the camera
        cam.setToOrtho(false, AstroDemo.WIDTH/2, AstroDemo.HEIGHT/2);
        bg = new Texture("bg.png");
        xrand = new Random();

        meteors = new Array <Meteors>();

        //Spawn meteors randomly off screen
        for (int i = 1; i <= METEOR_COUNT; i++){
            meteors.add(new Meteors(AstroDemo.WIDTH/2 + (xrand.nextInt(300))));
        }
    }

    @Override
    protected void handleInput() {
        //If screen/mouse is held
        if(Gdx.input.isTouched()){
            //Main Character jumps/flys
            naught.jump();
        }
    }

    @Override
    public void update(float dt) {
        handleInput();
        naught.update(dt);
        //If meteors are left side of the screen, re-position to the right side of the screen
        for(Meteors meteor : meteors){
            if (cam.position.x - (cam.viewportWidth/2) > meteor.getPosBigMeteor().x + meteor.getBigMeteor().getWidth()){
                meteor.reposition(meteor.getPosBigMeteor().x + (AstroDemo.WIDTH/2 + 20 + (xrand.nextInt(300))));
            }
       }
        cam.position.x = naught.getPosition().x + 80;

        cam.update();
    }

    @Override
    public void render(SpriteBatch sb) {
        //Adjust the spritebatch for co-ordinate system in relation to camera
        sb.setProjectionMatrix(cam.combined);
        sb.begin();
        //Draw background where the camera is
        sb.draw(bg, cam.position.x - (cam.viewportWidth/2), 0);
        sb.draw(naught.getTexture(), naught.getPosition().x, naught.getPosition().y);
        for (Meteors meteor : meteors) {
            sb.draw(meteor.getBigMeteor(), meteor.getPosBigMeteor().x, meteor.getPosBigMeteor().y);
        }
        sb.end();
    }

    @Override
    public void dispose() {

    }
}

```

# Answer
So you want to generate meteor and you don't want them to spawn at a location where they overlap. Plus, you want them to be spaced by a minimal amount.

In my opinion, you should not compute y positions that way. I'll do the y generation at the same time of x. I'll assume you build a meteor by x AND y positions.

I usually make a function for this. This code will do those things :

1. Make meteor at 0,0 location
2. Compute random x and y
3. Compute distance between x/y and already existing meteors
4. Compute new random x and y until distance between new meteor and already existing meteors is superior or equal to the minimal distance autorized between meteors
5. Set position of the meteor
6. Return the meteor

---

```
// This will create a meteor, and compute positions until they don't overlap with other meteors
private Meteors generateMeteor(int maxX, int maxY, float minDistanceBetweenMeteors)
{
    // Make the meteor
    Meteors meteor = new Meteor(0, 0) // You don't care at the moment

    // Init positions
    float x = rand.nextInt(maxX); // Your boundaries
    float y = rand.nextInt(maxY); // Your boundaries

    // Now you want to check if the min distance is good enough
    float distance;
    boolean minDistanceRespected = true; // The first meteor is always in respect of min distance

    do
    {
        for (Meteors m : meteors)
        {
            // Compute distance between your new meteor and the existing ones
            distance = Math.sqrt(Math.pow(m.getX() - x, 2) + (Math.pow(m.getY() - y, 2));

            // Check if distance is good enough
            if (distance < minDistanceBetweenMeteors)
            {
                minDistanceRespected = false;

                // Compute positions again
                x = rand.nextInt(maxX);
                y = rand.nextInt(maxY);

                break; // Don't need to check for others
            }
            else
            {
                minDistanceRespected = true;
            }
       }
    } while (!minDistanceRespected);

    // Reach this point means you finally get good positions
    meteor.reposition(x, y); // Change your reposition method to actually take x and y as position (you compute a random y each time you set a new X, here we want to set both of them
}

```

To use :

```
 meteors.add(generateMeteor(maxX, maxY, minDistanceBetweenMeteors));

```
> 1 votes

---
Tags: java, libgdx, mathematics, vector
---


title: LIBGDX Image tearing

text:
# Question
Title: LIBGDX Image tearing
I'm making an game in libGDX and I have been noticing some image tearing when camera is moving. Note that it happens only when the game is maximized and the camera x position is less than screen width and camera y position is less than screen height. Here's a GIF showing what is the problem The color errors are not the problem here, it is the GIF fault

# Answer
> 0 votes
I figured it out. It was to do with float rounding(or something to do with floats atleast). After casting them to ints it works without problems.

# Answer
> 1 votes
Disabling CPU sync and enabling vsync could fix your issue.

```
config.useCPUSynch = false;
config.vSyncEnabled = true;

```

There is more discussion of this over on reddit if that doesn't work.

---
Tags: java, libgdx
---


title: How do I get objects using layer name?

text:
# Question
Title: How do I get objects using layer name?
I am creating an FPS game in local multiplayer. One player creates the hot-spot game, and the other one connects through WiFi network and plays the game.

I want to find all of the player objects on the network that have a specific layer name, and store them into an array when the player spawns on the network. I've been able to add the object to the array, but I can't find the layer's objects with what I found with Google searches.

```
LayerMask.NameToLayer("LayerName");

LayerMask.LayerToName(8);

```

This returns the name of layer and layer index. How can I get the objects using a specific layer name, and also store it in to an array?

# Answer
It seems there is not any built-in function to do what you want, but you can write your own function to find every object in a given layer. However, be careful, the function is quite slow, so do not use it frequently :

```
GameObject[] FindGameObjectsInLayer(int layer)
{
    var goArray = FindObjectsOfType(typeof(GameObject)) as GameObject[];
    var goList = new System.Collections.Generic.List<GameObject>();
    for (int i = 0; i < goArray.Length; i++)
    {
        if (goArray[i].layer == layer)
        {
            goList.Add(goArray[i]);
        }
    }
    if (goList.Count == 0)
    {
        return null;
    }
    return goList.ToArray();
}

```

*Source : http://answers.unity3d.com/questions/179310/how-to-find-all-objects-in-specific-layer.html*

---

If you have to frequently update the list, I advise you to update a Dictionary when a player connects / disconnect / changes layer. The following class can't be attached to a gameobject, simply instantiate it inside your players manager. I haven't tested the following code :

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

private class PlayersManagerByLayer
{
    private Dictionary<int,List<GameObject>> gameObjectsByLayer ;

    public PlayersManagerByLayer()
    {
        gameObjectsByLayer = new Dictionary<int,List<GameObject>>();
    }

    public void AddPlayer( GameObject player )
    {
        if( !gameObjectsByLayer.ContainsKey( player.layer ) )
            gameObjectsByLayer.Add( player.layer, new List<GameObject>() );

        if( !gameObjectsByLayer[player.layer].Contains(player ) )
            gameObjectsByLayer[player.layer].Add( player ) ;
    }

    public void RemovePlayer( GameObject player )
    {
        if( gameObjectsByLayer.ContainsKey( player.layer ) && gameObjectsByLayer[player.layer].Contains(player ) )
            gameObjectsByLayer[player.layer].Remove( player ) ;
    }

    public void MovePlayerToLayer( GameObject player, int newLayer )
    {
        RemovePlayer( player ) ;
        player.layer = newLayer ;
        AddPlayer( player ) ;
    }

    public List<GameObject> GetPlayersFromLayer( int layer )
    {
        if( !gameObjectsByLayer.ContainsKey( layer ) )
            return null ;
        else
            return gameObjectsByLayer[layer] ;
    }

}

```
> 6 votes

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


title: Camera type for puzzle game like tetris

text:
# Question
Title: Camera type for puzzle game like tetris
I can't find what is the name of the camera type.

Sided camera view seems logical but not correct thought

# Answer
From what I understand of your question, the '**type**' you're after is in fact called a '**projection**'.

From Wikipedia:

> 3D projection is any method of mapping three-dimensional points to a two-dimensional plane.

Since most 2D games are rendered via 3D APIs (such as OpenGL), **the projection that is used in most 2D games is the 'orthographic'**, or 'parallel', projection, as opposed to 'perspective' projections, that are used in 3D games.

As for the **side**, there is not really such a thing. If you use a 2D engine, the coordinates will be `x`, `y` and `depth`, while if you use a 3D engine, you'll be able to decide how to do it, depending on how your brain works:

* you can place the camera in z+, pointing towards 0/z-, having y+ pointing up and x+ pointing right, with the smaller z being the further away from the camera
* you can place the camera in y-, pointing towards 0/y+, having z+ pointing up and x+ pointing right, while the bigger y being the further way from the camera
* etc

---

Now the rest of the answer is just extra things that complement what has already been said.

An orthographic projection will project the 3D points directly to the screen, in a 'flat' fashion, without simulating a 'real world' point of view.

The use of the orthographic projection is required because even if everything is going to 'look flat' in the 2D game, there is still the concept of depth, or z-ordering.

As a simple example, here is a bunch of cubes rendered with a *perspective* camera projection:

And here is the same thing, but using an *orthographic* camera projection:

The cubes' top faces are 10 units above the grid. Do you notice that the cubes are well aligned with the grid with the orthographic projection, but are not with the perspective? That's what you're after when programming a 2D game.
> 1 votes

---
Tags: camera, terminology
---


title: What does a matrix represent?

text:
# Question
Title: What does a matrix represent?
I began learning OpenGL recently and am having problems visualizing what matrices are and their role in computer graphics. Given the template of a 4x4 matrix like this:

I would assume that each matrix like this are the coordinates of a vertex in world space. And several of them put together and shaded give an object?

But why is there a `Xx`, a `Xy` and an `Xz`? I read that its a different axis (up, left, forward) but still can't make heads or tails of the significance.

# Answer
> 22 votes
Matrices in computer graphics are the transformations given to each coordinate in the model. Each Matrix is a combination of multiple transformations to apply to a coordinate (a point in 3-space).

Building a transformation is based from one of three transform types: Translate, Rotate and Scale.

A translation matrix is something like:

And a scale matrix:

Rotation matrices look like:

To combine any of these matrices you just multiply them together. To apply the transformation to a vertex just multiply to the vertex (as seen in the translation diagram).

# Answer
> 11 votes
In computer graphics, we use matrices to encode *transformations*.

Matrices that contain only translation, rotation or scaling transforms have a commonly-exploited interpretation: the upper-left 3x3 of the matrix contains only rotation or scale data, the bottom row or right column contains translation data. This is *not* a generality, but holds true often enough for the subset of transformations represented in computer graphics that people make use of it.

There is, similarly, a relationship between the values of the matrix and the corresponding coordinate frame the matrix represents (which is not always "world space," I should note). The upper-left 3x3 columns (or rows) represent the X, Y and Z axes of the coordinate frame.

Whether or not the rows represent axes or the column do depends on whether you are using the convention of multiplying as `row vector * matrix` or `matrix * column vector`. When performing matrix multiplication, the inner dimensions of the two matrices must agree, and so whether you are representing vectors as row matrices or column matrices impacts that choice (OpenGL and traditional math tend to prefer column vectors).

I recommend getting a good book on linear algebra, or at least taking a look at the Matrix and Quaternion FAQ and this post on matrix layouts in DirectX and OpenGL.

# Answer
> 10 votes
## What is a matrix?

A matrix with `m` columns and `n` rows represents a function which consumes a vector* with `m` elements (or coordinates) and produces a vector with `n` elements.

From this you can observe that if and only if a matrix is square, will the dimensionality of the vector not change. Eg. you get a 3D vector from transforming a 3D vector, a 2D from a 2D, etc.

*: In physics, vectors are usually used to indicate forces or other "influences" which "move around" things such as velocity or acceleration. But there is nothing stopping you from using a vector to represent a point or any arbitrary array of numbers (some libraries and programming languages even use "vector" to mean "1D array"). For use with matrices, anything can be the elements of your vector (even strings or colors), so long as you have a way of adding, subtracting and multiplying them by whatever the elements of your matrix are. Hence the name *vector*, which means "carrier" - it *carries* or *holds* values for you.

## What does multiplying by a matrix mean?

So if a matrix is a function, *what kind of function*? What does the function do? The recipe for it is defined by the elements of the matrix. Let's call the input `u`, output `v`, the matrix `M` (the multiplication `M*u=v` is then the same as `f(u)=v`) and `u(i)` gives the `i`th element of `u` (2nd element is y coordinate, for instance). For the matrix, `M(i,j)` means row `i`, column `j`.

Construction of element `v(1)`, the first one in the result, is described by the first row of the matrix. `u(1)` times `M(1,1)`, plus `u(2)` times `M(1,2)`, ... plus `u(i)` times `M(1,i)`. A matrix is a bit like a very simple programming language, that is only good for programming functions that work by shuffling around the inputs, adding them to themselves, etc.\**

It is helpful to imagine that you are working on one element of output at a time, hence, you are using only one row of the matrix at a time. You write out `u` horizontally. You write the ith row of `M` below it. You multiply every above/below pair and write the products below, then add up the products. Repeat for every row to get every element of `v`. (Now you see why an `m` by `n` matrix must operate on an `m` vector and produce an `n` vector.)

Another way to think about this - let's say we are doing a 3D to 3D transform, so a 3x3 matrix (or *3D transform* as they are often called because you can pretend this "function" is "moving" 3D points, even though really it's just changing up the numbers). Let's say the first row is `[1 2 0]`. This means, to get x of result, get 1 of input's x, 2 of input's y, and 0 of input's z. So it's really a recipe.

\**: If a matrix is a programming language, then it is not even Turing complete.

## What does multiplying two matrices mean?

If they are both matrices of appropriate size, then `A*B` means "a function which applies first `B` then `A`". You can see why the constraints on sizes for multiplication exist, because size determines input and output size, and one matrix consume the output of the other. Why does multiplication mean combine functions? It's easier to notice that it has to be. If `A*u` is the same as `f(u)` and `B*u` is the same as `g(u)` then `f(g(u))` is the same as `f(B*u)` which is the same as `A*(B*u)`.

Likewise, repeated applications of the same function can be shown as powers, since `A*A*A` means applying the function that `A` represents thrice.

## How are matrices useful?

What good is doing a transformation like `new_x = 1*x+2*y+0*z` (if the first row is \[1 2 0\])? That's not very obvious, but let's take another 2D matrix to explain that. The matrix is:

```
[ 0 1
  1 0 ]

```

Or `[0 1; 1 0]` using the convenient Matlab notation. What does this matrix do? It transforms a 2D vector like so: For the x of result, take 1 of the y of the input. For the y of result, take 1 of the x of the input. We've just swapped the x and y coordinates of the input - this matrix *reflects* points about the x=y line. That's sort of useful! By extension, you'll see that all matrices with 1s along the SW-NE line reflect. You can also see why identity matrices give you the input back (for x of output, take x of input; for y of output, take y of input...).

Now you see why the symbols are eg. `Xx`, `Yx` \- they mean how much of input `X`, `Y`, etc. goes into output `x`.

## How else are matrices useful?

What other transformation can you do? You can resize by taking an identity matrix, but with a different number than 1 along the diagonal. For example, `[2.5 0; 0 22.5]` will multiply every coordinate of the input by 2.5, and if you apply this matrix to every point in a picture, the picture will be 2.5 as large. If you only put a 2.5 in one row (`[2.5 0; 0 1]`) then only the x coordinate will be multiplied, so you will only stretch along x.

Other matrices can give other transformations, such as "skewing", which have varying degrees of usefulness. Personally, skew is my least favorite because the matrix looks so simple but the transform itself rarely does anything except mangle a picture. A useful one is "rotation" - how do you rotate a point? Try working out the position of point `(x, y)` after rotating by `theta` degrees counterclockwise about the origin. You will find that the new x and y coordinates both come out from multiplying the old x and y by some sines and cosines of theta. You should be able to easily write a rotation matrix using sines and cosines which corresponds to this function.

With non-square matrices, you can also change the dimensionality of an input. Turning a 2D input into 3D isn't very useful, since it's hard to "manufacture" something to put into the new coordinate, but 3D into 2D is very useful. Among other things, this is how your computer knows to project\*** a 3D scene into 2D image to draw on your monitor.

Since vectors can hold different things, you could even describe a matrix which encrypts a string n-characters at a time, by shuffling them around or "multiplying" them (you would have to come up with multiplication/addition function).

\***: When you *project*, you take a 3D object like a sculpture, shine a light on it, and see what kind of 2D shadow drops on a wall.

## What are the limitations of matrices?

Can you do every function with matrices? No. Thinking graphically, it's hard to imagine something that a matrix couldn't do (but it exists: a "swirl" effect cannot be done, for instance). However, here's an easy example: Let's say function `f` is such that `f(u)` gives you back `u` *with every element squared*. You will see that you cannot write a matrix for this: With matrices there is only facility for describing recipes that multiply coordinates by a constant number, no other fancy functions like power can be expressed.

\****: This is also why it's called *linear* algebra - the power function is *non-linear*, it doesn't make a straight line when plotted.

## On the weird extra row in 4D matrices

Now, why is the matrix in your example 4 by 4? Doesn't this mean 4-dimensional space? We don't have 4D computers, so why? This is actually an interesting trick with matrices that relates to the previous point about linear operations.

Regarding which functions cannot be done with matrices: What is the matrix for moving a 2D point by 2 units to the right (which produces the point `(x+2, y)`? Again, we get stuck. There is a way to multiply the input, but no way to add a constant. For 2D work, the trick is to pretend you are actually not in 2D space, but in 3D space, except the height (z coordinate or 3rd element) of everything is always 1 (it's a bit like how a 2D universe is just a "plate" lying flat along the floor of a 3D universe - in that case the third coordinate is always 0). Then you can use this magic last coordinate as a constant, because you know it is always 1 for every input.

Likewise, for moving 3D points, you need 4D coordinates. That's also why all 3D transformation matrices you see will have `[0 0 0 1]` as the last row - you must never alter the 4th dimension, or the result will be too complicated to represent in 3D!

# Answer
> 2 votes
That is a 4x4 column-major matrix, and from the looks of it, a view matrix.

The first 3 columns define direction of your basis vectors (up, left, forward as you called them), and the last column defines translation of the eye point. Put them together and you can describe the orientation of your camera, and more importantly you can use this matrix to transform points into a coordinate space known as "eye space", "view space" or "camera space".

Those are all synonyms for the same coordinate space. Unfortunately you have to learn all of the synonyms when dealing with computer graphics because different books and people will call them by different names. Most coordinate spaces have multiple names.

By the way, the three columns in your view matrix are generally orthogonal, that is they form right angles to one another. This is not required, but it is a very common property when constructing a traditional camera.

# Answer
> 2 votes
**TL;DR version:**

The first three elements `[x y z]` in each row represent a single *basis vector* of a transformed cooordinate system. The last element `w` is a translation component.

**The Long Version**

If you wanted a matrix that, when applied to a vertex, would rotate the vertex about the origin by, say, 45 degrees, you would fill the matrix with three vectors representing the transformed axes:

* A point `i` on the `x` axis `[1 0 0]`, but rotated 45 degrees. This is simply `[i_x i_y i_z]`, where `i_x` and `i_y` are the legs of a triangle with a 45-degree interior angle relative to the X axis: `[cos(45) sin(45) 0]`.
* A point `j` on the y axis `[0 1 0]`, but rotated 45 degrees from that axis. Sketch it on a piece of paper and you'll see that, when rotating counter-clockwise, the components become `[-sin(45) cos(45) 0]`.
* A point `k` on the `z` axis. In this example, `z` is unaffected since we're rotating in the (screen-aligned) x-y plane

So, we have three new vectors: i,j, k. The easy way to visualize this is just taking the X and Y axes and rotating the whole cross arrangement.

How do we put these in a matrix?

```
i_x i_y i_z
j_x j_y j_z
k_x k_y k_z

```

Or

```
 cos(45)  sin(45)    0
-sin(45)  cos(45)    0
    0        0       1

```

If you multiply any vertex by that matrix, you'll get

```
v1_x = v_x cos(Θ)     - v_y sin(Θ) + v_z * 0
V1_y = v_x*sin(Θ)    + v_y cos(Θ) + v_Z * 0
V1_z = v_x * 0        + v_y * 0    + v_z * 1

```

for `v = [1 0 0]`, and `Θ = 90°`, this becomes `v1 = [0 1 0]`

For translation, we add a fourth row and column, and put the translation components in the last column. We add a fourth component to the vertex `w` which is usually `1`. This is so that, when we multiply the vertex by the matrix, the w component causes the last column to be added to the input vertex, so the vertex is moved or translated. We call these "homogeneous coordinates." (For our purposes, "homogeneous" just means that there is a 4th component `w` in each vector, and we use a 4x4 matrix instead of a 3x3. Frequently you'll see shaders that use 4x3 matrices to avoid sending the mostly-useless 4th row to the GPU, which consumes valuable memory and bandwidth. The 4th row is needed for perspective projection, but not much else.)

Hope this helps.

---
Tags: opengl, matrix
---


title: Unity projects and building

text:
# Question
Title: Unity projects and building
I've made my first game, in Unity, and I want to upload it to MediaFire.

I'm not sure what to upload. Should I upload the whole project, or is a certain part enough for someone to play it?

# Answer
If you wish to upload your game for others to play, you should only have to upload the *build*. This is the executable that is created when you build your project.

In contrast, you should only upload your *entire project* if you intend for users to have access to your Unity project.

---

For further direction, follow this YouTube tutorial.
> 1 votes

---
Tags: unity, build-process
---


# Question
Title: How can I hide an object for one eye for the unity oculus rift DK2 platform?
I am trying to build a game for my son for the Oculus Rift DK2 to help treat his lazy eye using Unity.

I need objects that:

* Appear only to his left eye
* Appear only to his right eye
* Appear for both eyes.
(this helps force the brain to use both eyes together to form the complete scene)

How can I pull this off?

Thanks!

# Answer
> 1 votes
Use culling mask for each camera & use corresponding layer for intended object that supposed to disguise for that specific camera.

# Answer
> 0 votes
The most direct way, unfortunately, is to group the objects that you want to hide - layer, culling mask, custom property or whatever - and enable/disable them before rendering. You'd need to add a component to the Oculus cameras that, in a pre-render event handler, enable or disable the layers.

Note that, for each frame, you'll get at least two renders per update (assuming that your game isn't dropping frames) - one for each eye. In `Update()`, set a flag indicating that the current eye is `left`. At the end of the first render, change that flag - probably just an integer - to `right`, and enable / disable whatever you need to.

---
Tags: unity, oculus
---


title: Objective C Path

text:
# Question
Title: Objective C Path
I am looking for some help on what would be the best approach to create a path from one point in a grid to the other side.

Imagine a grid of 5 x 5, where at (0,1) there is a light source pointing into the grid. In the centre of grid there are angled mirrors, angled at 45 degrees. After randomly placing the mirrors, the light source will turn on and the beam of light grows, deflects off the mirrors and reaches a point somewhere else in the grid perimeter.

e.g. start: (col 0, row 1) Light, (col 3, row 1) mirror, (col 3 row 3) mirror, (col 4, row 3) end point.

In Objective C, what would be the best way to create this beam?

The deflection mirrors will have 4 reflection possibilities, UP or DOWN, LEFT or RIGHT depending on type of mirror and beam direction.

# Answer
You can use Core Graphics for this. In your NSView's `drawRect` handler, for example:

```
- (void)drawRect:(NSRect)dirtyRect {
  CGContextRef context = [[NSGraphicsContext currentContext] CGContext];

  // Move to first point, draw a line to the second point.
  CGContextMoveToPoint(context, X0, Y0);
  CGContextAddLineToPoint(context, X1, Y1);

  // ...repeat the above as needed to draw all the lines, then:
  CGContextStrokePath(context);
}

```

Functions like `CGContextSetRGBStrokeColor` or `CGContextSetLineWidth` can be used to control the color and thickness of the line.
> 1 votes

---
Tags: objective-c, xcode, path, maze
---


# Question
Title: Draw a line trailing behind a moving object
I'm working with monogame, moving a sprite object up and down. I want to draw a trail from the sprite's position and scrolling off to the left of the screen - like the sprite was a pencil leaving marks on a long sheet of paper sliding underneath it.

Here is an animated example:

I know how to move the sprite up and down but I'm a bit lost on how to do the trailing part. If someone could point me in the right direction I would really appreciate it

# Answer
> 1 votes
A point, in the right direction?

You should have an array for points that will be drawn on the screen. And every frame, you should be capturing the position of the player and adding that to that array. Then, iterate through the array to add points to the screen. To reduce lag, you can also delete points from the array that have left the screen.

e.g.:

```
// The following code will not run properly:

public Vector2 playerPosition;

// Assume some code is here

public Vector2[] pointPositions;

public void Update()
{
    for(int i = 0; i < pointPositions.length; i++)
    {
        // Assuming your positions are in pixels
        pointPositions[i].X = pointPositions[i].X - 1;
    }
    pointPositions += playerPosition;
}

public void Draw()
{
    for(int i = 0; i < pointPositions.length; i++)
    {
        // Assuming you have a drawPoint(Vector2) function:
        drawPoint(pointPositions[i]);
    }
}

```

---
Tags: c#, monogame, trail-renderer
---


# Question
Title: How to modify a property after animating it in Unity3D?
I animate localPosition. The animation works well, but after, I can't change a value of localPosition in editor or code. I want to change a value after the animation completes, not at the same time.

I use Animator with AnimationClipPlayable. I create Animator in editor and the rest in code (AnimationClip, AnimationClipPlayable, AnimationCurve).

The animation animates a property from one position to another. It finishes, I don't do anything to stop the animation.

Let me know, if you need a code example or video presentation.

# Answer
> 1 votes
Short answer: Use `Animator.Stop()`.

It happens, because Animator still holds a property, i. e. the animation is still animating the property and hence you can't modify it. The solution is to count time and when it is right time (when the animation completes), execute `Animator.Stop()`. For example, If you animate `gameObject`, you should execute `gameObject.GetComponent<Animator>().Stop();`.

# Answer
> 0 votes
You should avoid modification of the same variable in animation and code.

However there are two workarounds for the case:

1. Wrap your object in an empty object and then change properties of an inner object in animation and change properties of outer object by code.
2. Use LateUpdate to change a property in code which is already changed in animation. LateUpdate is executed after everything included animators.

## edit

make sure no other state in animator has the `write defaults` flag on. If any has, then by entering that state **all animated properties animator-wide** will be reset to their default values.

---
Tags: unity, animation
---