# Question
Title: Strange behavior with transformation matrix
I'm fairly new to transformation matrices. I'm using them to translate and rotate nodes and their child nodes. The following code works when applied once, but shows strange behavior when applied many times in a row:

```
void Node::update() {
    Mat4 parentTrans = (haveParent ? parent->getTransform() : Mat4::Identity());
    Mat4 thisTrans = this->getTransform();

    Mat4 translate = Mat4::Translation(this->getPosition());
    Mat4 rotate(this->getRotation());
    Mat4 result = parentTrans * thisTrans * translate * rotate;

    this->setPosition(result.getTranslation());
    this->setRotation(result.getRotation());
}

```

This works for a somewhat complex test case: a parent node w/ one child node, the child node is offset from the parent node, the parent node is rotated, and the child node is has its own local rotation. In this case, the drawing looks correct.

I'm running into problems when applying the above multiple times. For example, when I'm animating a rotating node (changing the rotation just a bit on each frame). Here, the position of the node becomes huge and it just zooms back to some very large position.

Any help or advice on how to address this is greatly appreciated.

# Answer
You seem to be stacking matrix calculations. The "node original transform sources" should be kept pristine while calculating "node in the graph stuff".

Assuming your original code looks a bit like this:

```
bool haveParent;
Node* parent;

Mat4 rotation;  // or Quat
Mat4& getRotation() const { return rotation; }

Vec3 position;
Vec3& getPosition() const { return position; }

Mat4 Node::getTransform() {
  return getTranslation() * getRotation();
}

const Vec3&

void Node::update() {
  Mat4 parentTrans = (this->haveParent ? this->parent->getTransform() : Mat4::Identity());
  Mat4 thisTrans = this->getTransform();

  Mat4 translate = Mat4::Translation(this->getPosition());
  Mat4 rotate(this->getRotation());
  Mat4 result = parentTrans * thisTrans * translate * rotate;

  this->setPosition(result.getTranslation());
  this->setRotation(result.getRotation());
}

```

You would probably need something like this:

```
// Assume the attributes are private and the methods are public.
Node* mParent; // nullptr on initialization

Mat4 mThisNodeRotation;  // or Quat
Mat4& getThisNodeRotation() const { return mThisNodeRotation; }

Vec3 mThisNodePosition;
Vec3& getThisNodePosition() const { return mThisNodePosition; }

Mat4 mWorldRotation;    // Rotation computed with the parent's ancestries
Mat4 mWorldPosition; // Translation computed with the parent's ancestries

const Mat4& getWorldRotation()    const { return mWorldRotation; }
      void  setWorldRotation( const Mat4& aValue ) { mWorldRotation = aValue; }

const Vec3& getWorldPosition() const { return mWorldPosition; }
      void  setWorldPosition( const Vec3& aValue ) { mWorldPosition = aValue; }

const Mat4& getWorldTransform()   const { return mWorldPosition * mWorldRotation; }

Mat4 Node::getThisNodeTransform() {
  return getTranslation() * getThisNodeRotation();
}

void Node::update() {
  Mat4 parentTrans = (this->parent ? this->parent->getWorldTransform() : Mat4::Identity());

  Mat4 worldResult = parentTrans * getThisNodePosition() * getThisNodeRotation();

  this->setWorldPosition(result.getTranslation());
  this->setWorldRotation(result.getRotation());
}

```

I have not tested the code, but it's been done with nearly the best of my knowledge.

When computing the final position of a node, you really have to keep a wall between the node's data, and what's being applied to the scene graph: when computing the position in the scene graph, it must not change the node's original settings (of course, it's the position w.r.t. the parent, but this does not need to be modified during the update and the calculation of the final location).

*My coding standards have been applied, please disregard as I'm becoming an old monkey.*
> 2 votes

# Answer
Looks like including `thisTrans` in the calculation of `result` was incorrect. Updated code is:

```
Mat4 result = parentTrans * translate * rotate;

```

Thanks to everyone asking/answering other transformation matrix related questions as they were very helpful.
> 1 votes

---
Tags: 3d, rotation, matrix, transformation
---


title: How do you prepare for feature creep?

text:
# Question
Title: How do you prepare for feature creep?
How can I prepare for feature creep during preproduction?

Feature creep is when you are in the production phase and decide "It would be cool if this were a feature!" That adds n hours to the development time which were not accounted for, and unless you are Blizzard, do not have the time for. You cannot anticipate it being a cool feature during preproduction, because the feature is only discovered during production.

What can I do during preproduction to account for or prevent or prepare for feature creep?

Should I allow feature creep and cut less desired features? Or will this create a problems since the architecture is not designed for the new features? Should I say no features unless they fit into the existing architecture?

I know this is a broad question, but I hope it doesn't get closed as such. This is a major issue in game development, and should be considered.

# Answer
While of course there are no hard rules when it comes to pre-production, there are a variety of heuristics to help. Some feature creep is natural and necessary - no plan survives first contact with reality, and you may not know what would be "cool" until you see it.

First, stage your development. Draw up your outline into a feature map, and then look for ways to group your features into *testable iterations*, each with a deadline. Once you begin an iteration, resist adding new features to it. Any unforeseen *technical needs* should of course go into the current iteration, but *new ideas* for features should go into a list for future consideration. You can then consider whether or not to add it to an iteration once the current one is complete.

This follows from the MoSCoW method, whereby you categorize features like so:

* **Must haves** \- features that are *vital* for the current iteration to be *stable*, which is to say *testable*. If the iteration won't work without it, it's a must have.
* **Should haves** \- features which will have to get done at some point, but if the iteration goes over time can be pushed into the *very next iteration*. Things required by a publisher, for example, could go here.
* **Could have** \- features which you think may be important to the current iteration but could be dropped from the project. These are the all important polish features.
* **Won't have** \- items that potentially feed **the backlog**, features identified in this iteration to be considered for later iterations.

Ideally you want development to be a progressive refinement, not all-or-nothing. Working within a final deadline the least important features ought to be pushed to the end, so whatever you don't get to will be stuff that's okay to cut. Make sure to estimate how long each feature will take to develop and refine those estimates as you go. Never compress the schedule to make room for more features. Resist pushing deadlines (iteration or final) into the future - move or cut features instead, if possible. If you're coming up to your deadline and the game is still an unsaleable mess, then you know it's time to seriously reevaluate your decisions and consider cannibalizing the project before it turns into a time/money pit.
> 10 votes

# Answer
* Plan to use a fraction of your available pre-production time for base feature set.
* Base featureset should be low-risk, high-reward features, so you don't have creep on *those*
* Base featureset is minimal and non-negotiable - they must be present - otherwise no solid basis to work from and you will be riddled with self-doubt / "should I replace this" syndrome
* Make sure the earliest iterations of your game are attractive enough that you can *afford* feature creep. A fundamentally unimpressive game isn't going to make it far, let alone with creep.
* Know beforehand what margin of creep you can afford, so you can use that margin wisely.
* Use pre-built, highly-generalised technology like Unity, and use it canonically to improve flexibility so that feature creep doesn't impact too heavily on existing architecture
* Don't build complex subsystems - an eXtreme Programming approach is suitable here
* Have others(designers & coders) whose brains you can tap periodically to help you prioritise which features you will allow to creep, have someone experienced reviewing your code as primary go-to point for these questions.
* You will still have to limit feature creep, so constantly prioritise and know where to draw the line

Ultimately, it's not something I would suggest to beginners, because you need to be able to make the right decision at every stage and that is not easy even for the most experienced. If you're not sure about what the right decisions are, then have a strict "no creep beyond this point" policy.

You can also see how the first point and the one about using a technology you know *well* means you need substantial experience both in rapid prototyping (game jams) and your chosen toolset.
> 3 votes

---
Tags: development-speed, time-management, pre-production
---


title: Unity object stuck where it shouldn't

text:
# Question
Title: Unity object stuck where it shouldn't
Here's the thing. I am making a 3D top-down game about cars on the road. Right now I have different-colored cuboids representing cars. They are position-locked in Y and rotation-locked on all three axis (axises? Sorry, English isn't my first language). The cuboid in question is controlled with the following code:

```
using UnityEngine;
using System.Collections;

[System.Serializable]
public class Boundary
{
    public float xMin, xMax, zMin, zMax;
}

public class PlayerController : MonoBehaviour

public float speed;

public Boundary boundary;

void FixedUpdate ()
{
    float moveHorizontal = Input.GetAxis("Horizontal");
    float moveVertical = Input.GetAxis("Vertical");

    Vector3 movement = new Vector3 (moveHorizontal, 0.0f, moveVertical);
    GetComponent<Rigidbody>().velocity = movement * speed;

    GetComponent<Rigidbody>().position = new Vector3
        (
            Mathf.Clamp (GetComponent<Rigidbody>().position.x, boundary.xMin, boundary.xMax),
            0.0f,
            Mathf.Clamp (GetComponent<Rigidbody>().position.z, boundary.zMin, boundary.zMax)
        );
    }

}

```

It's pretty simple, almost unchanged code from the Unity tutorial. Boundaries are set as -8, 8 on X and -13, 13 on Z. The cuboid spawns at 0, 0.55 (It's 1 height, I gave it some clearance), -13. I move it forward with the WASD and it just gets stuck at 0.15 Z. Just dies there and can't move anywhere.

I'm very new to Unity, so I expect it to be some rookie mistake. Can someone help me out? Thank you.

# Answer
> 0 votes
Looks like it's fixed now. I moved the plane of my road from 0 Y to -5 Y. Knew it would be something like that.

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


title: Libgdx - Viewport for Tetris-style game

text:
# Question
Title: Libgdx - Viewport for Tetris-style game
I'm a beginner in libgdx, and I'm trying to create my first game. It's pretty simple, circles are falling from the top and sides of the screen, and the user needs to "blow" them before they touch the ground. It is a single screen game, where the world isn't moving, like Tetris.

My problem is that I'm having bad time understanding what viewports should I use, and when.

So, what viewport should I use for this type of game, without generating black bars or stretching the graphics? Will it be possible to check the screen width and height, and act accordingly? let's say the screen is 400x800, can I save it in the code and just spawn the circles out of the screen?

Again, I don't want my graphics to be stretched, since the circles will look weird.

Thanks.

# Answer
You might want to use a `ScreenViewport` or `ExtendedViewport`. See the libgdx wiki.

You can access the screen size with `Gdx.graphics.getXXX()` where `XXX` is either width or height, so you can use this information to spawn your circles outside the current view.

Note that on different screen sizes, your game will feel different, because a bigger screen might make it easier.

---

Since your question was so general, play around with these viewports and if you have additional questions you can ask a new question.
> 1 votes

---
Tags: libgdx
---


# Question
Title: The type or namespace name `OpenCVForUnity' could not be found
I am working on face traching in unity3D

I have downloaded and imported the sample project on "FaceTracker Sample using OpenCV for Unity".

But when I tried to runned the project,its showing me the error.Below is the screen shot of the error

What will be the issue?can anybody help out please?

I am using unity(5.0.0f4(64 bit))

# Answer
If in case the script is in plugin folder , try shifting it to some other location. Most of the plugins start giving such errors while porting form unity 4 to 5. Also try the "using" statement at the top of the class. For example for facebook i had to do "using Facebook.Unity"
> 0 votes

---
Tags: unity
---


title: Unity apple/google ID access?

text:
# Question
Title: Unity apple/google ID access?
After extensive Googleing I have not come up with a way to access Apple ID's or Google ID's from unity running in respective devices. Either ID's or something else unique to the accounts logged in.

I dunno if this is possible with unity or maybe a plugin exists. If not how would you go about getting this.

# Answer
> 1 votes
You need to implement the Google play games and Apple Game Center plugins to allow player login to their accounts. Once they do you get their unique id which can be used to store the game progress.

Integrating such plugins have been always a big pain for me, I always prefer Prime 31 but its not free . Link:- https://prime31.com/plugins \- Play Game Services Combo - 140$

Currently you have free options , for apple game center. There are unity's inbuilt apis which can be used. Link :- http://docs.unity3d.com/Manual/net-SocialAPI.html

And google has already launched an open source plugin for unity. Link :- https://github.com/playgameservices/play-games-plugin-for-unity

You also have plenty of other options on the asset store.

---
Tags: unity, android, ios
---


# Question
Title: How do I render a 2D overlay with DirectX 9?
I'm working in C++ with DirectX 9 on a 3D game, but I want a 2D overlay for rendering a HUD.

I've heard that I could use `D3DXMatrixOrthoLH`, but I'm very confused on how to use it. I'm more familiar with OpenGL, where I could simply switch between 3D and 2D by initiating the view.

How can I do this in DirectX 9?

**EDIT:**

I was able to achieve this like (partial psudocode):

But I have a good feeling this is not the right way to do it.

```
void render()
{
    beginscene();

    D3DXMATRIX matrix;
    D3DXMatrixIdentity(&matrix);

    D3DXMatrixTranslation(&matrix, 0, 0, 0);
    device->SetTransform(D3DTS_WORLD, &matrix);

    // Render 3D.

    D3DXMatrixIdentity(&matrix);

    device->SetTransform(D3DTS_WORLD, &matrix);
    device->SetTransform(D3DTS_VIEW, &matrix);

    D3DXMatrixOrthoOffCenterRH();
    device->SetTransform(D3DTS_PROJECTION, &matrix);

    // Render 2D.

    endscene();
}

```

# Answer
> 1 votes
The simplest way to achieve this, is probably the ID3DXSprite interface.

> The `ID3DXSprite` interface provides a set of methods that simplify the process of drawing sprites using Microsoft Direct3D.
>
> The `ID3DXSprite` interface is obtained by calling the `D3DXCreateSprite(...)` function

This call requires a valid pointer to an `IDirect3DDevice9` object.

To use this interface, simply call `Draw` for each texture you want to be rendered, between a call to `Begin` and `End`. Since `Begin` will alter the device state, you should make sure your other rendering happens before `Begin`, or after `End`, which restores the previous state.

To rotate or scale a texture, you can create a matrix and pass it to `SetMatrix` before your `Draw` call.

---
Tags: c++, 2d, directx, hud
---


# Question
Title: How to check/read multiple elements of the same arrayList at the same time in Java?
Im making an rpg game and right now I'm working on crafting. I've made a crafting slot class, and an arrayList of that class. I've got 10 of those slots in total, 9 placed in a 3x3 'order' and 1 below (like the minecraft inventory). I want to check if the 9 slots contain some items in a particular way, and if they do to put a item in the 10th slot. I can figure out how to craft stuff, but I don't know how to read all those 9 slots at the same time (btw Im using an enhanced for loop to update and render all of 'em). I figured I would check if the slots contain items in this order

> 4 4 4
>
> 0 3 0
>
> 0 3 0

(4 being stone and 3 being the stick item)

Each slot has its own item variable. So how can I access all of them at the same time? Or even if there is a simpler way to do this. Thank you

# Answer
> 1 votes
You don't need to access them all at once, use a for-loop going from 0 to 8 (1-9 in human counting) to check them against an array of your recipe.

---
Tags: java
---


# Question
Title: How I can count how many time gameOver scene is loaded?
I'm building a game using unity 3d and I want to add an interstitial ads to it, but I want it to appear after the player lost every 3 times. So when the player loses for the first time the ads will appear, and when he loses for the second and third time, nothing appears until he lost for fourth time.

# Answer
A static integer should do the work. You can simply increase it's value every time you load the scene.
> 3 votes

# Answer
You could make a global variable:

```
Public int GameOverCount = 0

```

Then add 1 every time you call game over:

```
GameOverCount = GamoOverCount  + 1

```

And finally; when you start over for the 3rd, 6th, 9th..etc. time, you can use modulo(%) to check if GameOverCount is a multiple of three:

```
if ( (GameOverCount % 3) == 0)
{
    ShowAds()
}

```
> 0 votes

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


# Question
Title: Is It Possible To Reset UI To Initial State At Runtime Without Any Direct Assignments?
Is it possible to reset UI to it's initial state (the state when game started) without directly reseting elements one by one?

Thanks in advance.

**Edit:** I'm asking for runtime. (ResetToPrefabState doesn't work at runtime.)

# Answer
> 3 votes
As far as I know, the only way to revert something to its initial state without manually resetting each property via script is with a scene reload. If your UI is decoupled enough, you could use Application.LoadLevelAdditive and its Unload counterpart to reload the UI as its own scene.

---
Tags: unity
---


# Question
Title: How can I find a free or cheap redistributable font supporting runic characters?
I've been looking around for a font to include in my game which supports rune characters, specifically this Unicode block.

All the sites I go to don't demonstrate what Unicode characters that font contains, so I cannot gauge their usefulness for me.

I've been using the *Segoe UI Symbol* font, but it is only available on Win 7 & 8, and as far as I can tell, costs far too much to redistribute as part of a game.

Anyone know where I can go to find a font with my requirements?

# Answer
> 4 votes
The fileformat.info page you linked to contains a link “Fonts that support this block”. The ones listed there with 100% support are—

---
Tags: fonts, distribution
---


title: Structure for online game server

text:
# Question
Title: Structure for online game server
i'm trying to write a server for my little game and i'm wondering about server structure.

Let me explain that. Let's say i will create game in which you could edit skill stats, character basic stats and now i'm wondering how i should implement that.

I don't want to share this game as open source and i don't want changing those stats lets say in txt file because for me it's ugly.

Do you guys have any other ideas how i could implement feature in which i could edit some basic stuff of server but not in txt and not as open source ?

# Answer
> 1 votes
You can use several Flatbuffers. Depending on how you want to organize the structure, can be a single master blob on the server or however you want to update it. And smaller buffers on the client that would be sent to the server for update.

An example would be the server having several buckets, one for each player account or the like. Each bucket of data will contain user profile, customization, level, etc. Then you will have code that will allow the client to update what you want them to update on the server and the ability to store in their own PC just what is needed to be stored. You sync all of that when you deem necessary.

This is all just an hypothetical example, you will need to adjust it to your needs.

# Answer
> 1 votes
If you want to learn basic networking I sugest you watch this tutorial series , (episodes 38 - 59 are about networking). He explains how servers work and such. You can then bend the code towards your needs.

# Answer
> 1 votes
Do something like this:

```
struct client
{
    int health:
    int armor;
}

```

The client with have an instance of this class; the server will have an instance for each client connected. (You could store them in a map.) Then whenever data changes, have the client send data to the server saying it changed, and the server will update accordingly. Say you only wanted the server to be able to change a player's health. So just handle damage on the server and send the data to the client when the player's health changes.

# Answer
> 1 votes
Your server configuration needs to be stored somewhere, so you will need either configuration files or store them in the game database.

When you don't want the end-users to have to edit your configuration files with a text editor or even worse have to use an SQL shell, you will need to provide a graphical user interface to edit them.

Such a GUI could be a standalone application which is accessed remotely (like a web interface), or is run on the server directly.

You could also integrate the admin interface in your normal game client but only make it be visible for admin users (make sure the server also checks the user permissions before applying any configuration changes. You don't want players to be able to change the server configuration by hacking the game client).

Another option to get a GUI is to use XML for your configuration files and create XSD definitions which clearly define how the configuration files are structured. There are XML editors available which provide a quite foolproof GUI when provided with a detailed enough schema definition.

---
Tags: server, architecture
---


# Question
Title: GL_INVALID_OPERATION in glGenerateMipmap(incomplete cube map)
I'm trying to learn OpenGL and i'm using SOIL to load images.

I have the following piece of code:

```
GLuint texID = 0;

bool loadCubeMap(const char * baseFileName) {

    glActiveTexture(GL_TEXTURE0);

    glGenTextures(1, &texID);
    glBindTexture(GL_TEXTURE_CUBE_MAP, texID);

    const char * suffixes[] = { "posx", "negx", "posy", "negy", "posz", "negz" };
    GLuint targets[] = {
        GL_TEXTURE_CUBE_MAP_POSITIVE_X, GL_TEXTURE_CUBE_MAP_NEGATIVE_X,
        GL_TEXTURE_CUBE_MAP_POSITIVE_Y, GL_TEXTURE_CUBE_MAP_NEGATIVE_Y,
        GL_TEXTURE_CUBE_MAP_POSITIVE_Z, GL_TEXTURE_CUBE_MAP_NEGATIVE_Z
    };

    for (int i = 0; i < 6; i++) {
        int width, height;
        std::string fileName = std::string(baseFileName) + "_" + suffixes[i] + ".png";
        std::cout << "Loading: " << fileName << std::endl;
        unsigned char * image = SOIL_load_image(fileName.c_str(), &width, &height, 0, SOIL_LOAD_RGB);
        if (!image) {
            std::cerr << __FUNCTION__ << " cannot load image " << fileName << " (" << SOIL_last_result() << ")" << std::endl;
            return false;
        }
        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, image);
        SOIL_free_image_data(image);
    }

    glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
    glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
    glGenerateMipmap(GL_TEXTURE_CUBE_MAP);

    glBindTexture(GL_TEXTURE_CUBE_MAP, 0);
    return true;

}

```

When i call this, the images load successfully, but then i get an error in console:

```
---- OGL DEBUG ----
message <1>: 'API' reported 'Error' with 'High' severity:
GL_INVALID_OPERATION in glGenerateMipmap(incomplete cube map)
---- BACKTRACE ----

```

and no cubemap is displaying at all. Do you see any mistake in this code?

# Answer
Your line of:

```
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, image);

```

You should have the GL\_TEXTURE\_2D replaced with your variable **"targets\[\]"** so that as you iterate through your for loop you specify GL\_TEXTURE\_CUBE\_MAP\_POSITIVE\_X, etc.

The changed line would be:

```
glTexImage2D(targets[i], 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, image);

```

Even though you are technically creating a 2D texture, OpenGL needs to know what part of the cubemap the incoming texture needs to become.
> 0 votes

---
Tags: opengl, textures, cubemap, mipmaps
---


# Question
Title: How do I stop off-screen tiles of a 2D tilemap from being rendered?
I am seeing lag because I render all tiles in my map at once. How can I exclude off-screen tiles from being rendered?

My tiles are 32×32 and my player is always in the centre of the screen.

Here is my render method:

```
JSONParser parser = new JSONParser();
Object obj = parser.parse(new FileReader("assets/maps/"+map+".json"));
JSONObject jsonObject = (JSONObject) obj;

for(int x = 0; x < worldWidth; x++) {
    for (int y = 0; y < blocksHeight; y++) {
        Object out = jsonObject.get("x"+x+"y"+y);
        String f = out.toString();
        int i = Integer.parseInt(f);
        g.drawImage(GetImage.ReturnImage(i), x*Size.Tile, y*Size.Tile);
    }
}

```

# Answer
One way you could do it is by testing to see if the tile is outside the screen

```
int screenWidth = [GET_THE_SCREEN_WIDTH];
int screenHeight = [GET_THE_SCREEN_HEIGHT];
for(int x = 0; x < worldWidth; x++) {
    for (int y = 0; y < blocksHeight; y++) {
        Object out = jsonObject.get("x"+x+"y"+y);
        String f = out.toString();
        int i = Integer.parseInt(f);
        if(!x*Size.Tile>screenWidth && !(x-1)*Size.Tile < 0){
            if(!y*Size.Tile>screenHeight && !(y-1)*Size.Tile < 0){
                g.drawImage(GetImage.ReturnImage(i), x*Size.Tile, y*Size.Tile);
            }
        }
    }
}

```

That is how I would do it. And, yes, I have tested it. It works perfectly. You will need to replace '\[GET\_THE\_SCREEN\_WIDTH\]' and '\[GET\_THE\_SCREEN\_HEIGHT\]' with a real variable, obviously.

Hope this has helped you
> 1 votes

---
Tags: java, rendering, tilemap, optimization, slick
---


# Question
Title: How can I develop in MonoGame without relying on .xnb files?
I'm new to game development, and MonoGame seems like a beginner-friendly framework, so thought I'd start with that. However, as I started reading tutorials on it, I noticed a common theme: That at its current state, MonoGame needs XNA's content compiler since it doesn't have one of its own. The only problem I have with this is because I'm unable to install XNA (followed instructions on the web, even installed the Game Marketplace). I'm on Windows 8.1, by the way.

Long story short, I gave up on trying to install XNA. However, I have played around a bit with MonoGame and found that you can use raw images (`.png` in my case) instead of those converted to `.xnb`. I haven't tried sound, so I don't know if it'll work. Or any other assets for the matter.

My question is, is it possible to develop in MonoGame without using `.xnb` files? Or, is it possible to develop without XNA's content compiler? If yes, then how?

# Answer
> 4 votes
Yes, you can develop with MonoGame without relying on XNB files. I've been doing it for over a year now and for the most part it's fairly straightforward.

The main thing you are likely to have trouble with is `SpriteFont`'s. What I do is pre-render my fonts onto a texture and render them like normal sprites. I've got a little tutorial over here: http://www.craftworkgames.com/blog/tutorial-bmfont-rendering-with-monogame/

I've never had any trouble with `.png` files and `.wav` files work okay too but you have to make sure they are in the correct format. I haven't tried using shader's or anything else really, but I have created a couple of complete games.

# Answer
> 4 votes
You can use XNB Builder. The program still requires XNA `.dll`s, but you can just download them and put in a folder with the program.

# Answer
> 1 votes
It's worth nothing now that Monogame now has it's own Content Pipeline Builder Tool that removes any dependencies on the old XNA framework DLLs.

It includes a command line (linked above) as well as a GUI Tool that can be used to generate your XNB files from textures etc and then copied into your game project.

If you are working in Visual Studio then the .mgcb file has it's own Build Action (MonogameContentReference) and your XNB files will be generated as a part of your Visual Studio build process, thus making a pretty seamless workflow, or at least a similar one to what XNA provided with its Visual Studio project templates.

Personally, I typically keep my assets in a separate folder beside my Game Project folder and put the .mgcb file there. I then include the .mgcb file in the game project as a linked item reference.

Old topic but I found it so maybe someone else will too :)

# Answer
> 0 votes
As mentioned by craftworkgames, you can develop without XNB ( well, at least with textures and some audio formats ) .

You can load a png file using a Stream object ( must be a seekable stream, so you may need to copy from a StreamReader into a Memory Stream , then pass the memory stream itself to the texture2d constructor ).

The same should be possible with Wav files.

However, if you want to load FBX models or .X models, I am not sure if the Model / Mesh objects can be initialized directly from a seekable file stream.

Note:

* I have also initialized textures by loading them from a HTTP streams ( read from http stream - copy into seekable memory stream - pass stream to texture2d constructor ) - which allowed my game to download textures from a website via HTTP protocal instead of disk.

Shaders can be generated at runtime - initialized from byte array, *and I think also* from a string containing code. It "should" be possible to generate shaders in real time or even load them from remote sources, or from disk without requiring XNB files.

I am not sure if the DirectX version of the MonoGame supports this yet ( in the repo ) , but I think it shouldn't be hard using the current OPENGL based builds.

If you want to avoid having to use XNB, it might be a good idea to create your own content manager to replace the XNA/Monogame versions from scratch - thus undermining the entire content pipeline - but could also imply supporting your own formats that wont require XNA specific features.

# Answer
> -1 votes
I would say you're approaching the issue in the wrong way.

Firstly try and tackle the XNA issue, because it is likely that as the MonoGame project is all about doing XNA as an open source implementation that it will use similar or the same file types in the same manner. Although MonoGame is not dependant on XNA installing correctly (see edit - Thanks Josh) here are some things to check for XNA issues:

* Does your machine meet the minimum specs for development?
* Have you installed all the prerequisites? What sort of errors are you getting?
* Sometimes previous versions of .net framework and XNA studio can interfere, make sure you un-install these before installing XNA to ensure you are starting from scratch on the installation.
* Could you work completely in the XNA studio without worrying about MonoGame and then easily port it to MonoGame later on? *As this was the original intention to MonoGame, to allow existing developers to port over to it easily, this would be a viable path to take.*

If your machine is unable to work with XNA currently there may be related issues down the line with MonoGame. It is always worth ironing out development environment installation issues first before starting on a project.

**Edit:** As Josh mentioned in the comments - XNA has been abandoned. I had not actually realised myself, so although the example from XNA installer affecting MonoGame is not an issue in this case I still believe it is worth noting that install issues are something to clear up before project development commences.

---
Tags: xna, monogame
---


title: Making a gameObject push the player

text:
# Question
Title: Making a gameObject push the player
I am working on a Unity 3D game for Oculus and I have problems with making my objects to apply physics on a player. So getting rid of a `CharacterController` and using something like a rag doll is not an option.

I am using `OVRPlayerController`, that has a Rigidbody with mass 1 and a box collider on it. My gameObject has a Rigidbody of mass 100, and a box collider. But when the object hits the player it just goes through it, whereas I want it to push the player in x direction.

I tried using `onColliderHit` but it doesn't even recognize the collision between the player and the object, so I checked box collider on the object to be a trigger and I use `OnTriggerEnter()` to recognize the collision.

I tried to translate the player's position on collision, but player gets positioned to weird places out of my map for some reason. Here is what I use:

```
 info.transform.Translate(new Vector3( -0.5f, 0.0f, 0.0f));
 info.transform.rotation = Quaternion.identity;

```

I also tried to manually set the x position of the player but this doesn't work, and I know I am not supposed to do it.

I searched for answers for a long long time, so please don't answer to this with something like "oh, have you tried googling it, there are a lot of similar questions" etc.

# Answer
> 1 votes
Have you tried using ControllerColliderHit.transform

```
void OnControllerColliderHit(ControllerColliderHit hit)
{
    Debug.Log("I'm colliding with: " + hit.transform.name);
}

```

# Answer
> 1 votes
Objects shouldn't pass through each other if both have colliders. You could disable isKinematic on the rigidbody and then use AddForce to push. You could use also transform.translate() to move the player.

# Answer
> 1 votes
> I tried using onColliderHit but it doesn't even recognize the collision between the player and the object

There's no such method. There are following methods for collision detection:

1. Void OnCollisionEnter(Collision otherCollider)
2. OnCollisionStay(Collision otherCollider)
3. OnCollisionExit(Collision otherCollider)
4. OnTriggerEnter(Collider otherCollider)
5. OnTriggerStay(Collider otherCollider)
6. OnTriggerExit(Collider otherCollider)

Note that parameters are completely optional unless you want to do something with that info.

# Answer
> 0 votes
> My gameObject has a Rigidbody of mass 100

That could very well be the source of your problem. From Unity documentation :

> You should strive to keep mass close to 0.1 and never more than 10. Large masses make physics simulation unstable

Even if this doesn't solve your current problem,it's good to follow advice from Unity themselves.

---
Tags: unity, physics, virtual-reality
---


title: Quest and NPC System Design

text:
# Question
Title: Quest and NPC System Design
I am developing a quest system for a game and am looking for the most abstract way to go about connecting the system to the NPC conversation system. This isn't much of a question about the code to do it, but more looking for input on designs for it.

Structuring of the quest system and NPC conversation system has already been completed. What I'm trying to figure out is with my current NPC system, what is the best way to integrate the conversations and quests for the NPC.

Assume that, given my conversation system, the Conversation object holds a tree of all conversation nodes that the user will go through. I assume that each NPC will be given a Conversation object to go through in some way (whether this is directly or through a quest object is what I'm trying to decide). Some NPCs may have a standard conversation they have with a user and other NPCs might have a quest which contains conversations within it that the NPC should step through dependent on their current step in the quest. But then some NPCs might have a standard conversation **and** a quest or even an NPC with multiple quests and a standard conversation.

What I'm trying to figure out is what is the best way to "connect" these systems so that is abstract, dynamic, and clean. Any suggestions to help me think it out would be great.

# Answer
Your class structure depends on the features that *your* game's quest system has.

This is my, rather complicated but very abstract setup. The information in these classes that I describe here isn't everything but gives you the idea.

The `Character` class holds textures, the `Quest` that it is involved with and a `HashMap` of `questStage`:`Interaction` objects. They also hold `InteractionStageTalk` objects for when the player talks to them at the wrong time etc.

The `Quest` class holds the `name` of the quest, the `level` required and `experience` rewarded. The `Interaction` class holds an array of `InteractionStage` objects, as well as requirements to enter that stage. The `InteractionStage` class is abstract. The `InteractionStageTalk` class holds a `String` that is said to the player by that `Character` as well as a `delay`. The `InteractionStageGrant` class holds an array of items to grant to the player. The player has a `HashMap` of their quests and the stages that they're at.

Now, if you're only giving items at the end of your quest and have a constant chat delay time, the `InteractionStage` business may be completely useless and replaceable with a string array.

It's very easy to add new features if you lay your classes out like this.
> 2 votes

# Answer
I suggest looking at the "free" tools Bethesda offers for their games, or particularly the Obsidian variant for Fallout:NV, as they are built around making very large numbers of dynamic conversion trees for NPCs and quests.

A dialog in most current RPGs consists of sequences of scripted conversion interspersed with dialog options. Selecting an option plays another sequence. A sequence could include: text spoken, audio, cutscenes, or game actions.

The actual dialog points are just a list of options. The options may have requirements: you might only be able to threaten an NPC if you have a high Strength, or only be able to say "I know who you are, let us talk" if you've reached a certain dialog point with another NPC. Each option will then direct the user to another sequence or another dialog.

The whole conversion is a graph. Yes, a graph, not a tree - there are likely multiple dialog choices that can lead into the same direction eventually, so a tree is a poor choice. The "enter" node is often an initial "hello, good day" sequence that then leads into the opening dialog options, while other times it jumps right into dialog options.

The structure of a Conversion then is a graph of nodes, where each node is either an Action (play cutscene, run Lua script, etc.) or a Dialog (a list of options).

If you were writing this in a Java-esque OOP style, you'd probably have a Conversation containing a dictionary of node names to INode objects and derived ActionNode and DialogNode classes. The ActionNode would contain a List of IAction objects like a CutsceneAction, SetQuestStateAction, ScriptAction, or GotoNodeAction. The DialogNode would contain a List of Option objects, where an Option has a script or somesuch for calculating requirements and then the name of the conversion node to enter when the option is chosen. This is probably the easiest way to think of things as a human, though it's a rather poor way to structure code.

A procedural approach would probably just use a Lua script to represent the whole thing. Such a script would have a function for each node and available procedures to perform actions, build dialog option lists, queue up animations and speech, etc.

An approach I'd prefer is a hybrid of the two. You want custom data structures and conversion code that innately understands as much about what a conversion is, how the graph works, how you can move between nodes, and so on, because you want to build nice tools for designers to create and test conversations. A raw script makes that difficult. However, you don't want to build a bloated over-engineered Java-style class hierarchy for every simple problem. A smaller flat DSL-like VM to execute conversations directly while still having enough metadata for editing and tool-supported verification works nicely. This is a relatively difficult option to engineer, though.

The tools support item is one of the trickier ones. If you build much logic into scripts, tools will not be able to reason about what the script will do. If you don't use scripts, you have to re-engineer a lot of the features you can pull off with scripts. A good balance is likely to add the ability to do all your most common actions without script but still allow script for complicated rare cases. That way, you tools and verification code can at least handle most of the conversations, and you only need technically-savvy designers and extensive manual testing for a small subset of conversations.
> 2 votes

---
Tags: game-design, quests
---


title: RTS: Unit sight in fog of war

text:
# Question
Title: RTS: Unit sight in fog of war
I am making an RTS game, and like most RTSs, you can see what's going on in a part of a map only if you have a unit over there.

I have few ideas how to accomplish this, but there are problems with them.

Problems are:

* Algorithm must be efficient.
* I need to notify players (over network), when an enemy comes into sight.
* How do I account for obstacles obstructing sight (such as cliffs).

---

Naïve approach would be like this:

```
// pseudocode
func calculate_visibility:
   vector<Bitfield> visible;

   for all units on map:
        let unit = enumerated unit

        for all human players:
             let player = enumerated player

             for all units of player:
                  let player_unit = enumerated unit

                  if player_unit sees unit
                       visible[unit.id][player.id] = true
                       process next player

```

And then run this calculation each frame, compare results with previous frame and send out events, like “enemy unit detected”.

I did some benchmarking, and using approach like this may take up to 2/3 of a frame, which is unacceptable.

---

I figured out a better way to calculate which units are visible. This approach is to use a visibility map.

* Subdivide the map into N×M cells.
* Each cell is marked by IDs of players that can see the cell.
* To determine which players can see an unit, I need only to check cells that contain given unit.

However, I don't know how to fill the map in the first place. I could iterate through all units and use a circle-drawing algorithm.

But I'll have to redraw the visibility map every frame, so this doesn't look much more efficient than the first approach. Unless I update it at a lower rate, but then there's a problem with fast-moving units.

And how do I detect when unit comes in player's sight, except than iterating through every unit and comparing with previous frame?

---

How is this done in modern RTS, such as StarCraft 2?

# Answer
You should have a visibility map with at least one bit per cell per team.

Don't brute force a full map update each frame. Only when a unit's location and/or sight range changes. Before and after movement, check his visibility against each teams bit. If he was not visible to a team and becomes visible. Send an event.
> 2 votes

# Answer
Well the way I was taught in university was to first store your **units** in memory based on their cell location. So you have a square-grid of cells (you might need to play around with the cell size to find which is most efficient), and whenever a unit moves, you update its cell (if it changes, remove it from its old cell and add it to the new one). Note, you're only moving pointers to units, not the objects themselves, so this is very efficient.

I normally use a TreeMap structure, whose key is a Point (x, y) and the value is a list of units within that point. Note that you want to store your units as a straight array as well for when it comes to iterating through their update steps (or rendering). You could further segment this structure by 'team'. You don't need to check your own units against each other when it comes to visibility, only the units on other teams.

Using this method, when it comes to the actual checking, you take each unit's viewing radius and work out all possible cells that they might be able to see based on which cell they're in (rounded up). You then look at the other teams' units in those cells and check if the distance between them is within the viewing radius. Once an enemy is spotted, you store it in a list so that you don't need to check it again. (The list could also be segmented by cell in the same fashion to shorten the list and the number of checks required to find the unit in there).

I used this method to detect collisions between firework particles in a little firework simulator I made. It shrunk the number of checks I needed to perform from 500,000 to 500 on average.

Pros: Extremely efficient.

Cons: Small increase in RAM, due to secondary pointers storage.
Bugs in the code can cause units to be invincible/invisible.

If you need an example project with this all working, I can fix something up for you. It's a lot easier than you think.
> 1 votes

---
Tags: algorithm, optimization, rts
---


# Question
Title: Path following with Asteroids-like movement. Time to complete path
I'm currently learning about how to do this, but it's best to post the problem beforehand. (posting on Physics and GameDev, as you guys know your math)

It's quite difficult to explain. This specific problem revolves around a problem of creating a guidance system for rocket powered craft.
Think: 'I want the ship from game "Asteroids" to follow a specific path and compute, how much time will the whole trip take beforehand"

A craft has it's own properties like mass, linear and angular acceleration. It is only able to accelerate in its forwards direction. Also, quite a pain in the... it's maximum traverse velocity is limited.

Hopefully the picture clears some things out:

The problem lays in the very first step. The program is initiated while the craft is already moving with random velocity and faces random direction. In order to move fully toward the target point, first the craft has to turn to face "U" vector. But while doing so, it still moves, so the vector "U" will change. From the picture you can see that the direction of turn can change, don't worry, it's not a problem.

So, the problem. I tried using only vector math, but with no success as the variable I'm trying to compute relies on equations involving this variable. I'm too dumb to get only the variable I'm interested in on one side of equation. I think the solution would involve a function of distance from craft to object over time.

\[Edit 1\]

For your interest. Here is the part where I get stuck.

From the beginning. We have the craft on initial position "A", travelling with velocity "V1" and the target on initial position "B", with velocity "V2" (better include it just in case)

From that we can compute the burn vector "U", that we need to align ourselves to in order to travel towards the target at the speed of "Vmax"

The bigger the angle between craft's heading "Cf" and vector "U", the longer it will take the craft to turn. Which means, the craft will cover more distance while turning (uppermost picture). Which means the angle will change during turning etc. etc.

On second picture, in red box. at the top we compute dot product, at the bottom we multiply magnitudes of vectors. As the Cf vector is of length 1 all the time, we can spare it.

The primary thing I'm looking for is variable "t", currently I'm out of ideas.

# Answer
> 1 votes
I've done this before. The easiest method is to simulate the projectile, record points along its trajectory and note the closest point to the target. What I then do is get the target's location + (target velocity * time taken to reach closest point\*) to get the location it would be by the time the projectile reached it. All you need to do then is Math.atan2 the new coordinate with your ship's coordinate to get the angle you need to be at to hit it (or you could draw a marker on the HUD at the new location if you prefer).

For my purposes, this is efficient enough, and can deal with multiple targets at once without any performance hits. If you want it to be more efficient, simply multiply the projectile's velocity and put less points along its trajectory.

\*note that the time taken to reach the closest point is that point's index in the array.

**Edit:** As requested, below is a rough pseudo-code for what I did, note that the way I simulate my projectile will probably be different to how you have to simulate yours.

Also note that the functions below belong to the ship and 'this' is a reference to the ship instance. Also, this is some kind of modified java :P

```
list<Point> targetPoints = new list<Point>();
list<Double> targetRotations = new list<Double>();

//the function you call in your update step:
public void doTargetting(list<Asteroid> targets, int targettingRange) {
    targetPoints.clear(); //reset the list of targets
    targetRotations.clear();

    if(targets.size() == 0)
        return;
    int maxPoints = 50, stepsPerPoint = 3;

    list<Point> mypoints = simulateCurve(maxPoints, stepsPerPoint, myProjectile);
    for(Asteroid a in targets)
    {
        if(distance(a, this) < targettingRange) {
            list<Point> apoints = simulateCurve(maxPoints, stepsPerPoint, a);
            doTargettingFor(a, this, mypoints, apoints);
        }
    }
}

//physics stuff:
public list<Point> simulateCurve(int maxPoints, int stepsPerPoint, GameObject obj) {
    list<Point> points = new list<Point>();
    double velx = obj.velx, vely = obj.vely;
    double accellx = obj.accellx, accelly = obj.accelly;
    double maxSpeed = obj.maxSpeed; //if you want a max speed
    double burnout = obj.burnout; //a point at which the projectile runs out of thruster juice
    double loss = 1 - obj.friction; //velocity loss in each step, because space dust or something?
    double x = 0, y = 0;

    points.add({x, y});

    int spl = 0; //counter for steps per line
    for(int i=0; i<maxPoints*stepsPerPoint; i++) {
        if(burnout != 0 && i < burnout) {
            velx += accellx;
            vely += accelly;
        }

        velx *= loss;
        vely *= loss;

        double mag = Math.hypot(velx, vely);
        if(maxSpeed != 0 && mag > maxSpeed) {
            double mul = maxSpeed/mag;
            velx *= mul;
            vely *= mul;
        }

        x += velx;
        y += vely;

        spl++;
        if(spl > stepsPerLine) {
            spl = 0;
            points.add({x, y});
        }
    }

    return points;
}

//targetting stuff:
public void doTargettingFor(GameObject a, Ship me, list<Point> mypoints, list<Point> apoints) {
    int closestIndex = 0;
    double closest = MAX_VALUE; //a really really big number
    for(int i=0; i<points.size(); i++) {
        double distance = Math.hypot((apoints[i].x+a.x) - (mypoints[i].x+me.x), (apoints[i].y+a.y) - (mypoints[i].y+me.y));
        if(distance < closest) {
            closest = distance;
            closestIndex = i;
        }
    }

    if(closest < a.radius) //note that this handy little statement checks if you're on target and will hit ;). I used this to change the colour of the marker on the HUD to help you 'lock on' as it were.
    {
    }

    //this bit looks complicated but it really isn't. I'm taking the simulated points of the asteroid and adding it to the asteroid's current coordinates, then doing the same for the projectile
    targetPoints.add({apoints[closestIndex].x + a.x, apoints[closestIndex].y + a.y});
    targetRotations.add(Math.atan2((apoints[closestIndex].y + a.y) - (mypoints[closestIndex].y + me.y), (apoints[closestIndex].x + a.x) - (mypoints[closestIndex].x + me.x)));

}

```

---
Tags: physics, mathematics, vector, path, kinematic
---


# Question
Title: How should I manage the update grouping of shader constants in D3D11?
I've been learning the "dragon book" written by Frank D. Luna and trying to implement the part of the demo on my own. As some of you can see, the demo of the book uses effects interfaces to update the shader constant, but I'm not gonna do that. Because the effects may be deprecated in the future. So I try to find a convenient way to handle this shader constant stuff.

For example, I defined two shader constant structures in my C++ application:

```
struct PerObjConst : register(b0)
{
    XMMATRIX world;
    XMMATRIX worldViewProj;
    //...other vars
};

struct PerFrameConst : register(b1)
{
    float3 EyePos;
    //...other vars
};

```

Should I encapsulate every element's updating method for each? like:

```
SetShaderParameters(ID3D11DeviceContext *deviceContext, XMMATRIX &worldViewProj);
SetShaderParameters(ID3D11DeviceContext *deviceContext, XMMATRIX &world);
//...and so on

```

That seems to be cumbersome, isn't it? Instead, how about passing a whole structure's reference into the function? But I think that would be unnecessary to update whole structure when actually there is only a few of the elements are updated.

# Answer
> 1 votes
You should group your shader constants in buffers based on how often you are updating them, so it won't be inefficient to update the whole buffer.
For instance if you want to update the view matrix which is often done once per frame, you are most likely also updating the eye position of the camera, so they should be in the same buffer, so when you update it, you can update the whole thing.

---
Tags: shaders, directx11
---


# Question
Title: Use Accelerometer for Roll-a-ball Movement
I'm working on maze game for Android in Unity 5.1.1f1 and I have troubles with controlling my ball with accelerometer. At start I tried:

```
public class PlayerController : MonoBehaviour {

    public GameObject sphere;
    public Camera camera;
    public float speed=200;

    private Rigidbody myRigidBody;

    void Start()
    {
        myRigidBody = gameObject.GetComponent<Rigidbody> ();
    }

    void FixedUpdate()
    {
        float moveH = Input.acceleration.x;
        float moveV = -Input.acceleration.z;

        Vector3 move = new Vector3 (moveH, 0.0f, moveV);
        myRigidBody.AddForce (move * speed*Time.deltaTime);
    }
}

```

But the ball is not moving as it should. Then I tried another solution. But my ball still doesn't move right. It seems like it's sometimes hard to move left/right/forward/backward, also it's possible my ball will rotate in the opposite direction.

```
public class PlayerController : MonoBehaviour {

    public float speedAc = 10;

    //accelerometer
    private Vector3 zeroAc;
    private Vector3 curAc;
    private float sensH = 10;
    private float sensV = 10;
    private float smooth = 0.5f;
    private float GetAxisH = 0;
    private float GetAxisV = 0;

    // Use this for initialization
    void Start () {

        ResetAxes();
    }

    //accelerometer
    void ResetAxes(){
        zeroAc = Input.acceleration;
        curAc = Vector3.zero;
    }

    void FixedUpdate () {

        curAc = Vector3.Lerp(curAc, Input.acceleration-zeroAc, Time.deltaTime/smooth);

        GetAxisH = Mathf.Clamp(curAc.x * sensH, -1, 1);
        GetAxisV = Mathf.Clamp(-curAc.z * sensV, -1, 1);

        Vector3 movement = new Vector3 (GetAxisH, 0.0f, GetAxisV);
        GetComponent<Rigidbody>().AddForce(movement * speedAc);
    }
}

```

Can someone help me, please?

# Answer
> 1 votes
The third parameter of *Vector3.Lerp*, which named *"t"*, does **not** stand for *"time"*. It should be between 0 and 1, and gives results as below:

```
curAc = Vector3.Lerp(curAc, Input.acceleration-zeroAc, 0);    //curAc = curAc
curAc = Vector3.Lerp(curAc, Input.acceleration-zeroAc, 1);    //curAc = Input.acceleration-zeroAc
curAc = Vector3.Lerp(curAc, Input.acceleration-zeroAc, 0.5f); //curAc = (Input.acceleration-zeroAc + curAc)/2

```

Here is a good explanation of Lerp: http://answers.unity3d.com/answers/998744/view.html

---
Tags: unity, accelerometer
---


# Question
Title: Error with Quaternion.FromToRotation in Unity?
I get multiple errors whenever I run this code:

```
transform.rotation = Quaternion.FromToRotation (Vector3(0, 0, 0), Vector3(0, 0, 270));

```

Can you suggest a fix for this code?

Errors:

* Expression denotes a `type', where a`variable', `value' or`method group' was expected
* The best overloaded method match for \`UnityEngine.Quaternion.FromToRotation(UnityEngine.Vector3, UnityEngine.Vector3)' has some invalid arguments
* Argument `#1' cannot convert`object' expression to type \`UnityEngine.Vector3'

# Answer
You must use the `new` keyword when defining vectors.

Like so...

```
transform.rotation = Quaternion.FromToRotation (new Vector3(0, 0, 0), new Vector3(0, 0, 270));

```

So you know, there is a predefined Vector3.zero which is equivalent to new Vector3(0,0,0), so you could also write your code like the following...

```
transform.rotation = Quaternion.FromToRotation (Vector3.zero, new Vector3(0, 0, 270));

```

Note that there is no `new` keyword for Vector3.zero because you are not defining it, just using it.
> 1 votes

# Answer
When using C# you need to use the *new* keyword in front of all constructors that you call (It's not the case with Javascript).

the correct syntax is

```
transform.rotation = Quaternion.FromToRotation (new Vector3(0, 0, 0), new Vector3(0, 0, 270));

```
> 0 votes

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


# Question
Title: Game loops using Hard realtime systems vs Soft realtime systems
I have read the article here about realtime systems and am looking for examples specific to game loops.

Am I correct in saying:

Hard realtime systems will lag and slow down gameplay causing **slow motion** if processing of AI, collision detection, or user input is delayed past the rendering deadline set by the realtime system. Example, must render every 1/30 sec but processing caused delay to 1/20 sec.

Soft realtime systems will render at 30 FPS regardless of the other subsystems processing but if there is a delay in AI, collision detection, or user inputs, the game will be presented in ***stop motion*** instead of slow motion every 1/30 sec.

# Answer
> 2 votes
There is hardly any practical relation between soft and hard realtimes in industry(what the wiki page is about) and gaming. It is usually *hardware* or *OS* designed to meet deadlines where it is *absolutely a must* e.g. navigation systems in airplanes. Unless you ship (own) RT OS with your game you don't have to worry about anything like this simply because the OS you are running the game on was not designed to do such thing.
Also there is no slow motion in hard realtimes it is not designed to ever not meet deadline(actually, when designing one you have to *prove* first there is no possibility at all of not-meeting deadline) - not meeting deadline in hard RT would usually means death, or billion dollar assembly line blowing up. For soft RT it is more relaxed - it can be simplified as "if you did not managed to finish computing physics, I don't care about (this frame's) physics anymore". You should probably understand the first sentence by now.

---
Tags: game-loop, realtime
---


title: gameObject rotation in Unity issue?

text:
# Question
Title: gameObject rotation in Unity issue?
Can someone provide me with a script that makes a gamebject calculate its rotation speed based on the next collision, in a way that when it collides, it collides with its original rotation.

I do not want the cube to abruptly return to its original rotation once it has collided with something. Like in the video, the cube's rotation is just right when it collides (when it hits the ground, it feels natural). I have tried many times fine tuning the rotation, but I always fail to get it just right (+predicting future collisions is unknown to me). I do not have the experience to accomplish such a task and searching the Web did not help either. I would appreciate any lines of code, guidance or help from the community. Thank you for your answers.

# Answer
Although it looks like rotation issue, it's actually animation issue. You'd typically have a jump animation where the character is jumping and you'd add sprites for frames in the cycle. Since in such scenarios, the jump height,distance and duration is fixed, the rotation will always be the same.
> 2 votes

---
Tags: unity
---


# Question
Title: My player sprite get stuck to walls while moving along
Hello,

My player sprite is moving along the wall (not even diagonal, just straight down) and get randomly blocked in the corner of some walls. By blocked, I mean that the Y movement is stopped. If I move him away from the wall, he might not be blocked again by the same wall and get blocked at some other walls, always at a corner.

The walls are all the same sprite and are of the same size.

I use 2D Box Colliders for the walls. The player sprite has a Box Collider 2D and a RigidBody 2D. I am not using any physics codes, I would just like to make it work with the built-in Unity physics.

I move the player by adjusting the velocity of the rigidbody according to Input:

```
RigidBody2D rb = GetComponent<Rigidbody2D>();
float horizontal = Input.GetAxisRaw ("Horizontal");
float vertical = Input.GetAxisRaw("Vertical");
Vector2 movement = new Vector2(horizontal, vertical).normalized *speed * Time.deltaTime;
this.rb.velocity = movement;

```

The player is set like this:

Do you have any idea why it behaves like this and how I could fix it?

Thanks for your help.

# Answer
This is a common issue when dealing with tiled ground/walls/terrain and `BoxCollider2D`. Often player collider's corner get stuck with wall's corner even if everything is perfectly lined up. I may suppose that the reason of it - floating point precision problem.

To solve this, you can try a different ways:

* Change player's collider to `EdgeCollider2D` and tweak it to satisfy your needs.
* Change player's collider to circle/capsule. Sometimes it work fine for platformer-style games, but in top-down game like yours it will cause another problem like weird diagonaly moving around a corners.
* Apply `PhysicsMaterial2D` to walls or player and set it to zero Friction. It may help, if you are using built-in physics or gravity.
* Generate one big collider for connected walls at runtime. If there is no seams between colliders, player will not stuck.
* Detect collisions by yourself using `Raycast`.

Also you may read this two articles: this and this.
> 2 votes

---
Tags: unity, 2d, collision-detection
---


# Question
Title: Is There a Way to See Code Inside DnD Actions in Gamemaker Studio?
I'd like to see the script inside the Drag & Drop actions in Gamemaker Studio. I figure it would be one of the easiest ways to learn GML, and generally a great reference, but I haven't come across any mentions of how to do that; is there a way?

# Answer
You can use this service.

Open your object, press `Show Information` and copy all text to the clipboard. Then paste the data into the first text area (`Paste 'Object Information' code here`) and press `GML` button.
> 0 votes

---
Tags: game-maker
---


# Question
Title: Should I make game engines to be a good "game programmer", or is it more important to build games with Unity/Unreal?
Do I need to make game engines to be a good "game programmer" in general, or is it more important to build games with Unity/Unreal and learn coding along the way or both?

I am going into a Computer Science program and want to be a software developer, preferably in the Game Industry.

I was thinking I should learn C++ first as it is the most used in Game Development and then try to make my own Game.

# Answer
> 0 votes
If you want to spend a lot of time with a big team, go make your own. But if you are an indie developer with a little time, Unreal Engine would be a better choice because light building and rendering and core classes are done by the engine. After all, if you really spend your time on making your own and it turns out great, it will pottentialy have a better performance because only the things for your game are made and not other classes for other games. A good thing to know is that Unreal engine is multiplatform.

---
Tags: unity, unreal
---


# Question
Title: Make Camera Look at point using a World transformation matrix?
Variants of this question might have been asked on this site, but none of the answers I found worked in my case.

I am trying to make a Camera look at a point. The camera has a world transformation matrix, which is used to calculate the front vector, the eye position when making the view matrix finally. My camera is treated like any other object in the scene and thus has a world transform. I want to be able to modify this world transform, and that should automatically affect the camera.I want to actually modify the world transform of this camera so that it will "LookAt" a point.

For this, I modify the Rotation term of the world transform (**R** in **T** * **S** * **R**) like this:

```
WorldTransform::SetLookAt( float x, float y, float z ) {

    vec3 lookPoint = vec3 ( x, y, z );

    vec3 lookDir = normalize( lookPoint - m_position  );

    float lookLengthOnXZ = sqrtf( lookDir.z*lookDir.z + lookDir.x*lookDir.x );
    m_rotationX = degrees(atan2f( lookDir.y, lookLengthOnXZ ));
    m_rotationY = degrees(atan2f( lookDir.x, lookDir.z ));

    RotateAbs( m_rotationX, m_rotationY, m_rotationZ );

    UpdateMatLocal( );
}

```

Basically, I already have a function that can set the rotation (`RotateAbs()`), so I calculate the pitch, yaw and roll angles and pass them to there.

While calculating the view matrix, I just do:

```
void Camera::Update( ) {
    if (m_pTransform.m_pointer == nullptr) return;

    vec3& position = m_pTransform->GetPosition( );
    m_look         = m_pTransform->GetForward( );
    m_lookAt       = position + m_look;

    //Calculate the new matrix
    m_view = glm::lookAt( position, m_lookAt, glm::vec3( 0.0f, 1.f, 0.0f ));

}

```

This sort of works, the camera starts deviating from where it should be looking at after a while. What am I doing wrong?

# Answer
Found what was wrong. The overall system works perfectly, its just that

* The `m_rotationX` angle was being calculated incorrectly. instead of

`m_rotationX = degrees(atan2f( lookDir.y, lookLengthOnXZ ));`

it should have been

`m_rotationX = -degrees(atan2f( lookDir.y, lookLengthOnXZ )); //(missed the minus sign.)`

and

* The order in which the rotations should be applied must be **Rz** * **Ry** * **Rx**, where **Rx** is the Rotation matrix along x-axis, and so on. I was doing it the other way round. Remember, matrix multiplication is not commutative...

Hope that helps somebody out there like me.
> 0 votes

---
Tags: opengl, mathematics, camera, transformation, glm
---


# Question
Title: Animation conversion failed: transform for bone not found?
I'm trying to animate my first humanoid, and the animations in the Standard Assets pack (HumanoidIdle etc) work really well right out of the box. However, when I try to use other fbx files, like those in Unity's "Raw MoCap Data" pack, I get errors.

I import the animations, select one, go to "Edit…" and go to "Rig", select "Humanoid", copy the avatar definition from the character I'm trying to animate (e.g. Robot Kyle), and under "Animations" I will get an error like "Imported file RunBackward conversion failed: Transform 'Left\_Thigh\_Joint\_01' for human bone 'LeftUpperLeg' not found". When I compare the avatar of the character I'm trying to animate with the avatar that comes with the animations, they have the same bones defined, just with different names (which shouldn't matter, right?), so it's not that bones are missing. Using the animation with the default avatar also doesn't work, I get no error but my character goes into the first frame of the animation but then freezes. I've tried this with the standard models Ethan and Robot Kyle to the same effect.

Does anyone know how to handle this import error?

# Answer
The bones in the animation you're importing need to have the exact same name as in the skeleton you're using.
> 1 votes

---
Tags: unity, animation
---


# Question
Title: UnrealEngine how to create pirate boat tutorial
I fount an Unity tutorial how to crate pirate boat, but I still can't find any sources (links, videos) how to create it using UE.

Kind of this. So when you use character controller it can jump, run and etc, but with a boat you should smoothly running trough the waves with some bouncing effects. So I try to find tutorial that describe how to create this pirate boat. So the question not about model, so I can even use a cube that I can move through waves.

# Answer
> 2 votes
To do the same as the Unity tutorial you mention, you need to use a Pawn (not a Character!) with your boat mesh.
Then, use the `SetupPlayerInputComponent` function to get your inputs (or just your input node if you're using Bluprints).
You can now `AddMovementInput` to your Pawn, and it should perfectly move.
Your can use `AddControllerYawInput` to make your Boat turn right or left.

---
Tags: udk, unreal, unreal-4
---


# Question
Title: 2D AABB vs AABB side of collision and collision depth
I realize there have been a multitude of questions involving 2D AABB vs AABB collision, but the questions and responses always avoid the simple questions that make it difficult.

To keep things simple, we are going to assuming that AABB1 is a moving(vector velocity and direction known) rectangle that is much taller than it is wide, and AABB2 cannot move and is a smaller square. If AABB1 were to move towards AABB2 from any angle how would you figure out which side of AABB2 it collided with?

Further, when calculating collision depth, I mean the distance it travels into the object on the x-axis and the y-axis. When finding those distances, how would you find what point would you use as reference? From what I can tell, you couldn't just use one point for every collision because with AABB1 (it is much taller than wide), the top left point would be irrelevant when finding the penetration depth on a collision with the bottom right corner.

Another but less important question than the other two, how can you handle an object with a velocity vector with a high enough magnitude to move through an entire wall in one frame. Say a wall is 50 pixels wide and a player is moving 100 pixels per frame, it could jump through the wall without triggering a collision.

If further information is needed to help solve my problems or understand the problem, please ask. I haven't found any post that helps and I don't have enough reputation to post pictures to elaborate in more detail.

# Answer
I think in this situation you should add the extents of the moving AABB1 to that of the static AABB2 and then perform a Segment\<\>AABB test. In this case the segment starts at the position of the moving AABB1 and ends at position of AABB1 plus its velocity.

The result of the Segment\<\>AABB test will give you normal, thus the side. Assuming the segment intersects the AABB, you can then calculate the penetration, if needed, or just the actual 'just touching' position of AABB1.

This test works for any aspect ratio AABB, at any velocity.

I think the best example I saw of this was here: http://noonat.github.io/intersect/
> 2 votes

---
Tags: c++, 2d, collision-detection, collision-resolution, aabb
---


# Question
Title: Movement Issues: jumping to another GameObject
My code can make a `GameObject` jump while simulating gravity. Now I want my `GameObject` to jump. The purpose of this is to always have a nice "touchdown".

Instead of the parabola, I want to use my jump script but I want it to jump using this relation with the other `GameObject`. I also need it to work while the target point is moving.

Could anyone solve this problem? An answer would be greatly appreciated. If you've got any questions, do not hesitate to reply (I understand that it's hard to understand...).

# Answer
> 8 votes
This ended up being simpler than I expected. Here is the process I followed so you can follow a similar process in the future:

I started writing the basic physics 101 equations with some values in 2d space because it's easier to think about:

```
a = (0, -9.8) // this is just gravity down
v = v0 + a*t  // velocity is starting velocity + acceleration times time
p = p0 + v0*t + (1/2)*a*t^2 // the position

```

and then, I assumed the target position would be relative to the start position, so p0 drops out. Rearraging to find v0, I got:

```
v0 = p - .5*a*t^2 / t

```

At this point, there are two things to solve for, v0, and t. This makes sense, you can throw a baseball right at your friend or way up high and still have it land at your friends location, even though it will take longer.

So, I took this and created the following two classes that have the desired effect.

```
public class Jumper : MonoBehaviour
{
    private Vector3 _velocity = Vector3.zero;
    public Vector3 _gravity = 9.8f * Vector3.down;

    public void Update()
    {
        _velocity += Time.deltaTime * _gravity;
        transform.position += Time.deltaTime * _velocity;
    }

    public void SetVelocityToJump(GameObject goToJumpTo, float timeToJump)
    {
        var toTarget = goToJumpTo.transform.position - this.transform.position;
        _velocity = (toTarget - (Mathf.Pow(timeToJump, 2) * 0.5f * _gravity)) / timeToJump;
    }
}

public class JumpTarget : MonoBehaviour
{
    public Jumper Jumper;
    public float TimeToJump;

    public void Start()
    {
        if (Jumper != null) Jumper.SetVelocityToJump(gameObject, TimeToJump);
    }
}

```

**Edit to address comment** If you want to keep the same position in the jump as the target moves, then you are no longer talking about a step-wise physics solution, at least not while the jump is happening. It is easily achieved, however, with a coroutine to handle the jump.

```
using UnityEngine;
using System.Collections;

public class Jumper : MonoBehaviour
{
    public Vector3 _gravity = 9.8f * Vector3.down;

    public void SetVelocityToJump(GameObject goToJumpTo, float timeToJump)
    {
        StartCoroutine(jumpAndFollow(goToJumpTo, timeToJump));
    }

    private IEnumerator jumpAndFollow(GameObject goToJumpTo, float timeToJump)
    {
        var startPosition = transform.position;
        var targetTransform = goToJumpTo.transform;
        var lastTargetPosition = targetTransform.position;
        var initialVelocity = getInitialVelocity(lastTargetPosition - startPosition, timeToJump);

        var progress = 0f;
        while (progress < timeToJump)
        {
            progress += Time.deltaTime;
            if (targetTransform.position != lastTargetPosition)
            {
                lastTargetPosition = targetTransform.position;
                initialVelocity = getInitialVelocity(lastTargetPosition - startPosition, timeToJump);
            }

            transform.position = startPosition + (progress * initialVelocity) + (0.5f * Mathf.Pow(progress, 2) * _gravity);
            yield return null;
        }
    }

    private Vector3 getInitialVelocity(Vector3 toTarget, float timeToJump)
    {
        return (toTarget - (0.5f * Mathf.Pow(timeToJump, 2) * _gravity)) / timeToJump;
    }
}

```

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


# Question
Title: Getting an object to shoot directly towards click libgdx java
I am trying to get my player to shoot a spell and it travels to where ever the player clicked. I can easily accomplish this by doing the following.

```
    if(position.x >= destination.x - 1 && position.x <= destination.x + 1)
        reachedX = true;
    if(position.y >= destination.y - 1 && position.y <= destination.y + 1)
        reachedY = true;

```

However if the players origin is at, for example, 0,0 and I click at 10,300 then it travels right and up but when the spell reaches an x of 10 it travels directly upwards. I want the spell to travel at an angle that it will reach the x coordinate at the same time as the y coordinate. Here is an image showing what happens and what I want to happen.

# Answer
> 2 votes
The behavior you're currently having is caused by adding to the y and x position step by step until either or both have reached the same x and/or y position of the target. You add one unit to x and y causing a sloped movement not aimed at the target until you hit either the y or x axis the target lies on.

Subtract position from destination to get a vector from initial position to target position. Normalize the resulting vector since we don't care about the length of the vector, just the direction it's pointing towards. We can add the x and y of this normalized vector to current position to reach our target. (To normalize we divide the vector by its length)

```
direction.x = destination.x - position.x;
direction.y = destination.y - position.y;
direction_length = sqrt(direction.x ^ 2 + direction.y ^2);
direction.x = direction.x / direction_length;
direction.y = direction.y / direction_length;

//for each frame until we reach target
current_position.x += direction.x;
current_position.y += direction.y;

```

---
Tags: java, libgdx
---


title: Creating a delay by using Invoke

text:
# Question
Title: Creating a delay by using Invoke
Is it possible to delay the effects of a script that is attached to a game object?

I have 2 characters in a scene, both receiving live motion capture data, so they are both animated identically. I have rotated one by 180 degrees and placed it in front of the other one, to create the impression that they are copying/mirroring each other.

Each has several scripts attached to them, of course...

Now, I would like to be able to delay one character a bit (e.g. 1 sec) to make it look more realistic, as if one character is observing the other character and then copying its exact movements.

Is it possible to do this by somehow using the `Invoke` method on the other character's `Update` perhaps? Or any other possibilities to achieve what I described?

**EDIT** :: I used a *buffering* mechanism, as suggested by all the helpful comments and answers, instead of delaying, because delaying would have resulted in the same network data being used, except after a delay, but I needed the same old data being used to animate a second character to create the impression of a delayed copying...

```
private Queue<Vector3[]> posQueue;
private Queue<Quaternion[]> rotQueue;
int delayedFrames = 30;

void Start()
{
    posQueue = new Queue<Vector3[]>();
    rotQueue = new Queue<Quaternion[]>();
}

void Update()
{
    Vector3[] latestPositions;
    Quaternion[] latestOrientations;

    if (mvnActors.getLatestPose(actorID-1, out latestPositions, out latestOrientations))
    {
        posQueue.Enqueue(latestPositions);
        rotQueue.Enqueue(latestOrientations);

        if ((posQueue.Count > delayedFrames) && (rotQueue.Count > delayedFrames))
        {
            Vector3[] delayedPos = posQueue.Dequeue();
            Quaternion[] delayedRot = rotQueue.Dequeue();

            updateMvnActor(currentPose, delayedPos, delayedRot);
            updateModel(currentPose, targetModel);
        }
    }
}

```

# Answer
This seems like it would be straightforward to implement with some sort of event-queue-style thing.

I'm assuming that you have a method on your characters that gets called frequently by your data source, and that you immediately interpret that data into animation. This could be trivially flipped to work with polling, etc.

So, starting with something like...

```
public void setMoCap(MoCapObject newData){
  animateImmediately(newData);
}

```

It would be pretty easy to give each animated character a `Queue<MoCapObject> moCapQueue` to track that data, and a `float animationDelay` to determine how long they wait to respond.

```
public void setMoCap(MoCapObject newData){
  moCapQueue.Enqueue(newData);
}

```

Then, in your update method, respond if the delay has passed.

```
public void Update(){
  if(moCapQueue.Count > 0)
  {
    MoCapObject nextData = moCapQueue.Peek();

    if(nextData .timestamp <= (Time.time + animationDelay))
    {
      nextData = moCapQueue.Dequeue();
      animateImmediately(nextData );
    }
  }
}

```

This approach assumes that your data, however it comes in (`MoCapObject`, here) has a timestamp. If not, you'll have to do that manually (perhaps with two parallel Queues or a new wrapper object to enqueue).

It also doesn't take into account animation conflicts or any of the other myriad issues this kind of project has, but it shouldn't be any different from an existing solution on that front. Just delays response.

Also you may want to enable your "consume queued data" check to process more than one data point per frame.
> 2 votes

# Answer
Since `Invoke()` is mentioned, I'm assuming you're looking for a simple solution to just introduce some delay.The way to introduce delay in unity is Coroutines. Here's the Pseudocode :

```
IEnumerator AnimateCharacters()
{
    Animate first character.
    // Introduce delay using yield return
     yield return new waitforSeconds(number of seconds to delay);
   Animate second character

}

```

This will animate first character, delays executing next step by specified number of seconds, and then, executes the next step which is animation. You'd call this from a method you've set up to handle input like this:

```
void OnInput()
{
   startCoRoutine("AnimateCharacters");
}

```
> 1 votes

---
Tags: unity
---


# Question
Title: Changing the direction of a particle in libgdx java
I have a particle the explodes upwards. This would work the way I want if the particle always hit the ground. However I want the particle to explode at a -90 degree angle if it hits a wall from the left to look like you just exploded the wall. Is there a way to rotate the particle emitter in any way? Any help is extremely appreciated.

# Answer
You can change the emitter angle by modifying the `ScaledNumericValue` that represents the angle of the `ParticleEmitter`.

Given some target angle, you can read the angle information from the `ParticleEmitter` and adjust its high and low boundries accordingly.

A quick solution might look something like this;

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

ScaledNumericValue angle = emitter.getAngle();

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

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

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

```
> 1 votes

---
Tags: java, libgdx
---


# Question
Title: Returning a List of coords for a sphere in order of inside to outside
I'm looking for any algorithm that can return a list of Vector3 coordinates that form a sphere. If you read the list from the beginning it would appear the sphere was expanding.

The only algorithms I've found are for circles, the algorithm doesn't have to make a sphere of a particular radius, just a number of coordinates would be fine.

If anyone could point me in the right direction for such an algorithm that would be great. Any language or even just sudo code for a basic algorithm would be appreciated.

# Answer
If I understood what you're asking , you can start from Spherical coordinate system

Very pseudo code to "list" a sphere from top to bottom:

Let r be radius.

Let PI = 3.14...

Let's use degrees.

```
For theta =0..180
   For phi =0..360
     List.add(PolarToCartesian(r,theta,phi))

```

Where PolarToCartesian:

```
x=r * sin(toRad(theta)) * cos(toRad(phi))

y=r * sin(toRad(theta)) * sin(toRad(phi))

z=r * cos(toRad(theta))

```

and toRad converts degrees into radians
> 2 votes

---
Tags: mathematics, algorithm, sphere
---


# Question
Title: Play Audio After Countdown In JavaScript
Is there a way I can have an audio sample play after a certain amount of time, like 3 seconds in JavaScript? I've looked everywhere and can't seem to find what I'm looking for! I'm very new to this type of stuff, so apologies for the kind of daft question...

Thanks

# Answer
Use Invoke function to call play sound , pass the time delay which you want. You can do it like this.

```
function Start()
{
   audio = GetComponent.<AudioSource>();
   Invoke("PlaySound", 3);
}

function PlaySound()
{
    audio.PlayOneShot(impact, 0.7F);
}

```
> 2 votes

---
Tags: javascript, unity
---


# Question
Title: What is the standard way to render each mesh at their respective locations?
I have a single mesh, and I give the vertex-shader a matrix which holds the objects position, scale and rotation. It seems to work.

```
in vec3 position;
uniform mat4 object;
uniform mat4 view;
uniform mat4 proj;

void main() {
   gl_Position = proj * view * object * vec4(position, 1.0);
}

```

What if I have multiple meshes? What is the standard way to approach this? Feed in a different `mat4` for every mesh rendered, or have separate vertex shaders for each mesh?

# Answer
> 4 votes
Each mesh gets a different object matrix (world transformation matrix).

A common sequence of rendering multiple meshes is :

* Use shader program
* Set the uniforms for Mesh1
* Bind VAO/VBO's for Mesh1
* Draw
* Set uniform for world matrix for Mesh2
* Bind VBO/VAO for Mesh2
* Draw

....

---
Tags: opengl
---


# Question
Title: Level design for puzzle game with a single mechanic
I'm developing a simple puzzle game where gameplay has a single mechanic where there is a limited amount of variation. I'm struggling to design levels that keep the game challenging/fun. I've added a bit of variation using time limits but overall it feels very repetitive.

On the other hand, there are games such as Flow which similarly has a which have 1000+ levels and somehow they are unique/challenging enough for people to continue playing.

Are there any resources that cover level design for such a game?

# Answer
I can't submit u some links, but I have some general design ideas u can counter check ur actual implementation to see if it does fit or u need to do some changes.

First of, you need to find/define aspects in your puzzle that you can make harder. I will use sudoko here as example. It get's harder as you remove more numbers in the prefilled puzzle. So you now have a way to generate different difficulties by removing more numbers.

The next step would be, to build a generator, that creates scenarios that fit your settings. In the example of Sudoko, a generator would run for levels that have as example 8 numbers prefilled.

I know that sudoko is a very easy example, but that is always the hard point in a game - define the difficulty steps.

If you explain your game a bit more, we may be able to assist you in this process.

After defining the difficulty steps and have a basic generator for this, the next step would be to add additional things, that can keep the user busy. Like your mentioned timer, side objectives, effects to interrupt, ... This will on the other hand, make the generator for this, way more complex or maybe kill the generator so you will have to design the levels on ur own.

It will always be a balance act of difficulty and still the ability to create an algorithm for it.

Another very important fact is, that people are always way more interested in success then failure. So don't make your puzzles to hard. Just create a bit easier ones, and for the prize of loosing difficulty, add variation or pure mass.

Also another way to push people, would be a point system or ladder system (sr don't know the correct spelling in English). Highlight who has most puzzles solved in what time.

But always keep in mind that u need to show, even if the people only solve a puzzle in 1000% more time, that this is still over or at least the average. Because otherwise, people that had problems solving a puzzle, will get demotivated, because ur game tells them they are stupid.

Always think about what you would await of a game. A side tip, study games of well payed game studios and copy some of their aspects for ur game.
> 1 votes

---
Tags: level-design
---


# Question
Title: Java - Loading background music into memory
I am currently developing a game with Java, with a soundtrack consisting of ten tracks in .ogg format, 1-2 MB in size each. To be able to switch between these tracks quickly and easily in the game, before the game starts, I load all of them into memory by creating ten `Clip` classes. Unfortunately, but understandably, pre-loading these tracks increases the application's CPU usage from about 61 MB to 340 MB.

Since I'm only ever playing one track at a time, I could make it so that only one `Clip` is ever in memory, and is destroyed when the track needs to change. This means, though, that I'll have to hang the game up on loading the `Clip` when this happens, or do this on a different thread during a few seconds of undesirable silence.

Is there a smarter, more conventional way to handle large BGM files, or do I just have to pick my poison?

# Answer
The easiest method is to only keep *2 tracks* in memory; one playing and one ready to be played.

When one track is done you start the next one and also start loading the track (in a background thread) to be played after that one and `close()` the Clip that just finished.
> 1 votes

---
Tags: java, music, memory-efficiency, memory
---


# Question
Title: Filling a polygon with a texture (or a color) C# Visual Studio
I'm trying to figure how to put a texture or fill a "DrawPolygon" with a simple color in C# Visual Studio (using right now 2015).

```
 //Left Wall 1
 Point lw1a = new Point(18, 7);
 Point lw1b = new Point(99, 61);
 Point lw1c = new Point(99, 259);
 Point lw1d = new Point(18, 313);

 Point[] lw1 = { lw1a, lw1b, lw1c, lw1d };

 gr.DrawPolygon(pen, lw1);`

```

This is a example code for one of the things I'm drawing on screen. Any idea on how I can achieve that? Thanks!

# Answer
try using Graphics.FillPolygon

Example :

```
            // Create solid brush.
            SolidBrush blueBrush = new SolidBrush(Color.Blue);

            // Create points that define polygon.
            Point lw1a = new Point(18, 7);
            Point lw1b = new Point(99, 61);
            Point lw1c = new Point(99, 259);
            Point lw1d = new Point(18, 313);
            Point[] lw1 = { lw1a, lw1b, lw1c, lw1d };

            // Define fill mode.
            FillMode newFillMode = FillMode.Winding;

            // assuming gr a graphic object
            gr.FillPolygon(blueBrush, lw1 , newFillMode);

```

For using a texture you can try TextureBrush instead of SolidBrush

Follow example filling ellipse with texture :

```
 try
    {
        Bitmap image1 = (Bitmap) Image.FromFile(@"C:\Documents and Settings\" +
            @"All Users\Documents\My Music\music.bmp", true);

        TextureBrush texture = new TextureBrush(image1);
        texture.WrapMode = System.Drawing.Drawing2D.WrapMode.Tile;
        Graphics formGraphics = this.CreateGraphics();
        formGraphics.FillEllipse(texture,
            new RectangleF(90.0F, 110.0F, 100, 100));
        formGraphics.Dispose();

    }
    catch(System.IO.FileNotFoundException)
    {
        MessageBox.Show("There was an error opening the bitmap." +
            "Please check the path.");
    }

```
> 2 votes

---
Tags: c#, visual-studio
---


# Question
Title: How to prune an AI game tree for a game like Magic?
I've got a game tree structure for my AI that I need to trim in order to gain some depth.

It is a single-player game of perfect information. A good analogy would be a single-player game of Magic the gathering with an oponnenet that plays no card but automaticaly deals you some damage per turn.

Since I don't have an opponent I don't need either minimax (I can do a pure MAX) or a/b pruning.

I got an evaluation function I can use on nodes if necessary. I'm trying to plan ahead and find good combo's of cards to play.

I dont want to hard-code these combos.

I'm finding hard to prune any branch at all since even a branch with bad-scoring node can potentially lead to a good combo that will completely change the game (you know, like : play 5 shitty cards and be almost dead but the 6th card will grant you a win).

Any idea on how to approach pruning in a game tree like that?

# Answer
> 1 votes
I suppose it's just the usual trade off. You'll have to decide, based on desired effectiveness of the selected strategy and performance in terms of how long your tree search takes, what you want. You have to decide how many moves into the future you want to take into account, and then you prune on the resulting tree as usual.

Your example of playing 5 bad cards and winning with the 6th one just depends on how far the AI digs into the tree. If your AI plans 5 moves or less, you just won't be able to get that combo because the moves before that will be considered bad. If it plans 6 or more moves ahead, it'll arrive at the solution using normal decision and pruning tactics. You'll have to figure out if looking 6 moves into the future takes too long or not (I don't know the branching factor of your tree).

Also, you could use this as difficulty settings. For example, an easy AI would only consider the next move, a hard one considers the next 5 moves, an expert one considers 10 moves and so on.

---
Tags: game-design, ai, tree, single-player
---


# Question
Title: Texture tearing with UV texture atlas mapping
The following code maps the texture from a texture atlas to a UV. The problem is I'm having texture tearing issues.

Does anyone know how to overcome this problem and have any suggestions? Here is the code I have, all images are point filtered and **no mipmapping** is used.

```
    for (int i = 0; i < mesh.uv.Length; i++)
    {
        UVs.Add(GetUVTextureFromAtlas(mesh.uv[i].x, mesh.uv[i].y, voxel, 0));
    }

    [...]

    Vector2 GetUVTextureFromAtlas(float x, float y, ushort voxel, Facing side)
    {
        Rect rect = GetVoxelTextureRect(voxel, side);
        float xout = UVLerp(rect.x, rect.x + rect.width, x);
        float yout = UVLerp(rect.y, rect.y + rect.height, y);
        return new Vector2(xout, yout);
    }
    float UVLerp(float from, float to, float t)
    {
        float difference = to - from;
        return from + (difference * t);
    }

```

# Answer
If you want to avoid bleeding issues with texture atlases, you'll have to leave gaps of at least 1 pixel between the elements in your atlas. Best practice is to use 2 pixel wide gaps and repeat the colors of the neighboring element pixels in those gaps.

But be careful with compression algorithms on your textures (e.g. when building to iOS, the compression is really agressive). They might require wider gaps to avoid compression artefacts bleeding over between sprites.
> 1 votes

---
Tags: unity, c#, 3d-meshes, uv-mapping, texture-atlas
---


# Question
Title: Which game consoles can I target as an indie with C++ and OpenGL
I am an indie game developer and I wish to build games using C++ and OpenGL for game consoles. I've read that there are strict requirements for developing games for some consoles. So does anybody know which consoles readily allow indie developers to build games for them using C++ and OpenGL?

# Answer
When developing for consoles, I strongly recomment using an engine that already supports multiple platforms natively.

Unreal Engine supports multiple consoles, as well as Android, iOS and PC, so you are very flexible when choosing the target console, and it uses C++.

Another option would be Microsoft's XNA, which uses a C++ variant for use with the .NET runtime, but it has a limited set of supported platforms, consisting of the Microsoft platforms Windows, Xbox 360, Xbox One and Windows Phone.
> 0 votes

---
Tags: opengl, c++, console
---