title: Match 3 game - Check for matches

text:
# Question
Title: Match 3 game - Check for matches
I'm out of ideas and need help. So far I generate a board nicely using a flood fill algorithm and a 2d-array, I can also move tiles around the board.

Each Tile knows its own row, column and ID (images get set depending on ID, it's also what I use to check for matches).

The version I have for checking matches right now **almost** works, but it does not remove Tiles correctly if the match happens on row/col that got changed because of the recent move (tiles above that move down because of the match that was made from my move).

I have a lot of code but Ill try to explain it:

I check for matches in my game loop, so each frame I loop through the 8x8 board and check for matches. To check for matches I have these methods:

```
private void checkIfUpMatch(int row, int col){ //recursive
        Tile toCheck = array[row][col];

        toCheck.setChecked(true); //we set the tile as checked

        if(toCheck.getRow() >= 7){ //if next row doesnt exist
            return;
        }

        if(array[row + 1][col].getId() == array[row][col].getId()) {
            verticalMatches ++;
            checkIfUpMatch((toCheck.getRow() + 1), toCheck.getCol());
        }

        return;
    }

    private void checkIfDownMatch(int row, int col){ //recursive
        Tile toCheck = array[row][col];

        toCheck.setChecked(true);

        if(toCheck.getRow() <= 0){ //if next row doesnt exist
            return;
        }

        if(array[row - 1][col].getId() == array[row][col].getId()) {
            verticalMatches ++;
            checkIfDownMatch((toCheck.getRow() - 1), toCheck.getCol());
        }

        return;
    }

    private void checkIfLeftMatch(int row, int col){ //recursive
        Tile toCheck = array[row][col];

        toCheck.setChecked(true);

        if(toCheck.getCol() <= 0){ //if next col doesnt exist
            return;
        }

        if(array[row][col - 1].getId() == array[row][col].getId()) {
            horizontalMatches ++;
            checkIfLeftMatch((toCheck.getRow()), toCheck.getCol() - 1);
        }

        return;
    }

    private void checkIfRightMatch(int row, int col){ //recursive
        Tile toCheck = array[row][col];

        toCheck.setChecked(true);

        if(toCheck.getCol() >= 7){ //if next col doesnt exist
            return;
        }

        if(array[row][col + 1].getId() == array[row][col].getId()){
            horizontalMatches ++;
            checkIfRightMatch((toCheck.getRow()), toCheck.getCol() + 1);
        }

        return;
    }

```

All of these methods do the same thing, just for up/down/left/right. Basically:

* Set the tile as checked
* If the tile is on the board and the neighboring tile matches, increase verticalMatches/horizontalMatches.
* call method again for next Tile (recursive)

I call these methods inside my `checkForMatch` method that is called in the game loop:

```
private void checkIfMatch(int row, int col){
        checkIfUpMatch(row, col);
        checkIfDownMatch(row, col);
        checkIfLeftMatch(row, col);
        checkIfRightMatch(row, col);

        if(verticalMatches >= 3 || horizontalMatches >= 3){
            for(int i=0; i<ROWS;i++){
                for(int j = 0; j < COLS; j++){
                    if(array[i][j].isChecked()){
                        array[i][j].setMatched(true);
                    }
                }
            }
            reFill();
        }else{
            for(int i=0; i<ROWS;i++){
                for(int j = 0; j < COLS; j++){
                    if(array[i][j].isChecked() && !array[i][j].isMatched()){
                        array[i][j].setChecked(false);
                    }
                }
            }
        }

        verticalMatches = 1;
        horizontalMatches = 1;
    }

```
* If verticalMatches or horizontalMatches \>= 3 we set the checked tiles as `matched`
* else we set `checked` back to false for all the tiles and reset verticalMatches/horizontalMatches

As you can see I call refill after we set all the tiles needed as `matched`, which looks like this:

```
private void reFill(){ //refill the board after a match has been made
        for(int i=0; i<ROWS;i++){
            for(int j = 0; j < COLS; j++){
                if(array[i][j].isMatched()){
                    fallDown(i, j);
                    array[i][j].setMatched(false);
                    array[i][j].setChecked(false);
                }
            }
        }
    }

    private void fallDown(int row, int col){ //replaces the ID of the removed tile from above
        Tile removedTile = array[row][col];

        if(row+verticalMatches > 7){
            //we are at the top so just put in new tiles
            int random = MathUtils.random(1, TILETYPES);
            array[row][col].setId(random);
            return;
        }

        Tile changeTile = array[row + verticalMatches][col]; //use vertical matches to set the removed tile to the correct ID
        removedTile.setId(changeTile.getId());
        fallDown(changeTile.getRow(), changeTile.getCol());
        return;
    }

```
* Here we loop through all the matched tiles and call `fallDown`
* `fallDown` replaces the removed tile with the tile above recursively until we are at the top of the board, then we insert new random tiles

That is it, any advice, tips or ideas are welcome, I've spent probably a good 20 hours of coding trying to figure this out. Maybe there is some easier way to do this that I am missing, or maybe I'm just making a few mistakes.

**EDIT:**

Trying to implement Shiro's solution:

```
private void checkVertical(int row, int col){
    // The current id of the tile that we are checking for matches
    final int currentId = tiles[row][col].getId();
    // The matches of the current tile
    final List<Tile> matchedTiles = new ArrayList<Tile>();
    matchedTiles.add(tiles[row][col]);

    if(row < 7 && tiles[row + 1][col].getId() == currentId){ // 1 up
        matchedTiles.add(tiles[row + 1][col]);
        if(row < 6 && tiles[row + 2][col].getId() == currentId) // 2 up
        matchedTiles.add(tiles[row + 2][col]);
    }

    if(row > 0 && tiles[row - 1][col].getId() == currentId) { // 1 down
        matchedTiles.add(tiles[row - 1][col]);
        if(row > 1 && tiles[row - 2][col].getId() == currentId) // 2 down
            matchedTiles.add(tiles[row - 2][col]);
    }

    // If we find a match
    if(matchedTiles.size >= 3) {
        for(Tile tile : matchedTiles) {
            final int row = tile.getRow();
            final int col = tile.getCol();
            tiles[row][col].setId(8);
        }
    }
}

```

# Answer
> 1 votes
In a 3-match game I don't believe you can match more than 5 at a time, so it is in fact 2 at most from up and 2 from below. You don't have to use recursion for that, you can write this code in-line and comment what you are doing for clarity.

Here is a different approach:

We have a temp list of tiles. We start checking every tile. For every tile that we check, we fill the list with the tiles that "match" the current tile's ID in the vertical direction (just the 2 tiles above and 2 tiles below).`if list.size() >= 3`, then for every tile in that list, we call `fallDown()` and reset the list, `else` just reset the list. We do the same for the horizontal direction.

And that's all. No `reFill()` method, no extra iterations, no `matched`/`checked` variables and no recursion.

---
Tags: java, libgdx, algorithm
---


title: Can I use someone else's music/midi?

text:
# Question
Title: Can I use someone else's music/midi?
The music in question is not exactly owned by the other individual either, as it's simply an arrangement of a game's soundtrack as a midi or music sheet.

Am I allowed to use these in my videogame? Should those persons be given credit or should it go to the original composers of the track in the original video game?

Should I ask for permission for the authors of the rearrange? What if the file and site list no author? What if it lists an author but I have no means to reach and ask?

# Answer
> 0 votes
In short: Don't use it.

An arrangement or performance of a song is a derivative work, and as such the composers are owners of the Copyright, even if they didn't do the actual performance or re-arrangement. You always need permission from the rights owner. If you can't determine who that is, you can't get permission, and are thus illegally using it. (With exceptions for music that's old enough that Copyright has expired, fair use exceptions in some countries for short excerpts or scholarly purposes don't apply here)

Disclaimer: I'm not a lawyer, this is not legal advice. You should really see a lawyer about this.

---
Tags: legal, music
---


# Question
Title: Getting ray using gluUnProject or inverted MVP matrix
I've read a lot of topics here, on SO, opengl.org etc. Example how gluUnProject should work (from NeHe tutorial):

```
winX = (float)x;
winY = (float)viewport[3] - (float)y;
glReadPixels( x, int(winY), 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &winZ );
gluUnProject( winX, winY, winZ, modelview, projection, viewport, &posX, &posY, &posZ);

```

The problem is that `gluUnProject` returns mostly zeros, if not zeros then it returns Camera position in World Coords. Value `winZ` I'm getting from `glReadPixels` is always correct, if I scale it like below:

`float z_distance = ProjectionMatrix[14] / (winZ * -2.0 + 1.0 - ProjectionMatrix[10]);`

I get distance between near plane and parallel plane that contains mouse click point. Look at the sample below:

```
gluUnProject( winX, winY, -1, modelview, projection, viewport, &posX1, &posY1, &posZ1);
gluUnProject( winX, winY, 0, modelview, projection, viewport, &posX2, &posY2, &posZ2);
gluUnProject( winX, winY, 1, modelview, projection, viewport, &posX3, &posY3, &posZ3);
gluUnProject( winX, winY, winZ, modelview, projection, viewport, &posX4, &posY4, &posZ4);

```

The result is always the same `(posX1,posY1,posZ1)=(posX2,posY2,posZ2)=(posX3,posY3,posZ3)=(posX4,posY4,posZ4)` and is either `(0,0,0)` or `(Camera-Position.x,Camera-Position.y,Camera-Position.z)`

After `gluUnProject` I tried to do it manually:

```
float NDC_x = 2.0f * winX / Width - 1.0f;
float NDC_y = 1.0f - 2.0f * winY / Height;
float winZ = 0;
glReadPixels(winX, (Height - winY), 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &winZ);
vec4 point1 = inverse(ViewProjectionMatrix) * vec4(NDC_x, NDC_y, winZ, 1.0f);
vec4 point2 = inverse(ViewProjectionMatrix) * vec4(NDC_x, NDC_y, -1.0f, 1.0f);
vec4 point3 = inverse(ViewProjectionMatrix) * vec4(NDC_x, NDC_y, 0.0f, 1.0f);
vec4 point4 = inverse(ViewProjectionMatrix) * vec4(NDC_x, NDC_y, 1.0f, 1.0f);

```

Now all points coordinates are different and never zeros but some values, seems like real ones but I don't know how to handle it or I missed something.

BTW I used different approach to get ray (using angles) and it works perfectly. Check here.

Q1: Any suggestions what's wrong with `gluUnProject` ?

Q2: What is my mistake in manual implementation?

I thought that I messed with row\column-major format, but transposition of matrices had no effect. I read\write matrices as column-major format so last column is `(ViewMatrix[12], ViewMatrix[13], ViewMatrix[14], ViewMatrix[15])`

# Answer
Firstly, we should convert winX and winY values in pixels to Normalized Device Coordinates.

To get world coordinates from pixel position on screen we should multiply inverse ViewProjection matrix by clip space `vec3(NDC_x, NDC_y, some_z, 1.0f)` Actually every pixel on screen corresponds to line in world space. So the question is what `some_z` value to use. But no matter what values we will use - final points will always be laying on our ray.

Tricky part is to correctly use received values. Let's look at four possible situations I've mentioned in opening post:

```
float NDC_x = 2.0f * winX / Width - 1.0f;
float NDC_y = 1.0f - 2.0f * winY / Height;
float winZ = 0;
glReadPixels(winX, (Height - winY), 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &winZ);
vec4 point1 = inverse(ViewProjectionMatrix) * vec4(NDC_x, NDC_y, winZ, 1.0f);
vec4 point2 = inverse(ViewProjectionMatrix) * vec4(NDC_x, NDC_y, -1.0f, 1.0f);
vec4 point3 = inverse(ViewProjectionMatrix) * vec4(NDC_x, NDC_y, 0.0f, 1.0f);
vec4 point4 = inverse(ViewProjectionMatrix) * vec4(NDC_x, NDC_y, 1.0f, 1.0f);

```

Now we need to do perspective division (this part that is missing very often).

Note: code below uses 'point' with no numeration because its the same for any case.

```
point /= point.w; //perspective division for chosen point
vec3 RayDirection = vec3(point.x, point.y, point.z) - Camera->Position;
 //subtracting  camera position from 'point' coordinates gives as ray direction, length
 //depends on `z-value` used: '1.0f' gives us ray that stops on far plane, '0.0f' - ray
 //will stop at near plane, all negative values return point between camera and near plane,
 //using value from glReadPixels(from 0 to 1) returns point between near and far plane
ScaledRay = RayDirection * scale; //scale original ray in 'scale' times
NormalizedRay = normalize(ScaledRay); //normalizing ray length to 1, we can normalize first
                //and then scale to whatever length we want(for example range of shooting)
RayEndPoint = NormalizedRay + Camera->Position; //adding Camera position gives endpoint

```

Now when we know how to handle values - same goes for `gluUnProject`:

```
GLint vp[4];
glGetIntegerv(GL_VIEWPORT, vp);
GLdouble wx = 0, wy = 0, wz = 0;
gluUnProject(winX, (vp[3] - winY), 0, mvmatrix, projmatrix, vp, &wx, &wy, &wz);
vec3 RayEndpoint = vec3((float)wx, (float)wy, (float)wz);
vec3 RayDirection = RayEndpoint - Camera->Position;
vec3 ScaledRay = RayDirection * Scale;
vec3 NormalizedRay = normalize(ScaledRay);
RayEndPoint = NormalizedRay + Camera->Position;

```

Note: gluUnProject is unstable for me - mostly it returns zeros or #INF, but once per 10 launches of `exe` it works flawlessly (I meant I never change `exe` but just starting it again and again).
> 2 votes

---
Tags: opengl, c++, raycasting, perspective, raytracing
---


# Question
Title: Communicating with Collision System in ECS
I have read tons of articles and forums threads about ECS but still can't understand how anything in engine should communicate with Collision System. Let's say I have Input System that handle keyboard input and then at some point it want to move player character forward. Before doing this I should ask Collision System if there would be a collisions after that move and only if no - change position.

My current approach is to have requestTranslation function in CollisionSystem that take translation function and object like this:

```
moveForward(){
    V3.CollisionSystem.requestTranslation(this.mesh, function(object){
        object.translateZ(-this.movingSpeed);
    }.bind(this));
}

```

What do you think about this approach? How good/bad it is? What are know alternatives?

# Answer
As indicated, your `Input System` signals an intent to perform some action. How your game signals the action is really a matter of taste but the point remains the same.

A `Movement System` is then a logical step in your game logic thread. It's resposible for taking the *intent* specified by the `Input System` and determining velocity/force to be applied to movable entities. The velocity/force is determined based on existing entity state such as whether the entity is running, walking, swimming, flying or has some other speed boost aura applied to it's current state.

Your `Physics System` takes the calculated velocity/force and applies it to your physics managed entities. This system will determine either a new position for the entity because the movement was allowed or will not move the entity but instead generate a list of collision points. It's here where the magic happens.

At this point you'll need to iterate two types of entities: those *with* collisions and those *without* collisions.

For those *without*; you'll simply want to take the newly calculated position from the physics simulation step and apply that position to the entity's transform component.

For those *with* a collision; you'll likely want to communicate this collision to remaining parts of the system either via some type of event or callback solution.

To your question in your comment, you simply need to execute whatever logic that needs to know whether a collision happened or not after the physics system has executed it's step in the game loop. It's at this point where you know whether the entity is participating in a collision or not and the ideal place to execute or skip game logic based on this information.
> 2 votes

---
Tags: entity-system, component-based, entity-component
---


# Question
Title: How to load and unload objects at a certain radius from the player?
I am making a procedurally generated space exploration game in unity. I'm currently generating 5000 stars in a cube of a fixed size. Each star just gets a random 3d coordinate. What I would like to do is to dynamically load and unload stars at a certain radius from the player. This would be the maximum view distance. The algorithm that does this must be working with a seed for the universe, as the stars need to be loaded in the same spot when you revisit them.

My idea is something like in the amazing Space Engine.

I have pretty much no knowledge of algorithms that can do this, so I ask for your help.

# Answer
Have two different kinds of star game-object:

```
LoadedStar
UnloadedStar

```

While the `UnloadedStar` is nothing but the transform coordinates, a very simple collider and its basic properties, the `LoadedStar` is the full-fledged object with all its visual representation and game-mechanics functionality.

Have a `Collider` with IsTrigger=true attached to your player which represents the current active zone. Whenever a `UnloadedStar` triggers the `OnTriggerEnter` event, replace it with a corresponding `LoadedStar`. Whenever a `LoadedStar` triggers the `OnTriggerExit` event, replace it with an `UnloadedStar`.

The advantage of also having active game objects for stars out of range is that you have the option to later add a simplified representation of them. You can, for example, add a simple billboard sprite to represent far-away stars or add a navigation widget for selected stars to the GUI.

the disadvantage is that your universe can not be truely infinite and not generated on-the-fly while the player is exploring. But it can still get very large without losing too much performance because the unloaded stars won't consume many resources when they are simple enough.
> 3 votes

# Answer
You could use playerPrefs() to save the location of the stars so you could restore it later.
> 0 votes

# Answer
What you have is two separate problems. One generating/saving/loading stars. The other is finding nearest stars. It seems that you already have star generator, which means that you can save and load seed or entire list of stars via PlayerPrefs or Application.persistentDataPath. Read about serialization if you are not sure.

To find nearest stars you can use simple brute force algorithm:

```
private List<Vector3> GetNearestStars(Vector3 playerPosition, List<Vector3> stars)
{
    return stars.FindAll(star => Vector3.Distance(playerPosition, star) < 100);
}

```

Just iterate through all coordinates and filter the ones you need. For 5000 stars that might be enough. If you need more speed, you can use something like Octree or Spatial hash.
> 0 votes

# Answer
Consider a grid in your space, take the grid cross points. P1 .. Pn Consider a pseudo random generation function f(x,y,z,k). Foreach P you can call f(x,y,z,k1) to get dx coord of a star from P, f(x,y,z,k2) to get dy, f(x,y,z,k3) to get dz. Repeat this incrementing k to get all stars near P. Consider your radius. For each point P on your radius generate its stars. You can add other parameters other than dx dy dz for a star (color,size,type) so you can go full procedural generation avoiding storing data. Finaly I suggest a coroutine that checks if stars are out of scope and can be deleted.
> 0 votes

---
Tags: unity, procedural-generation, random, loading
---


title: Draw cube in glsl shader

text:
# Question
Title: Draw cube in glsl shader
I am working on a voxel engine. Currently my cubes are rendered as vbos. I thought, it may be better to load only the cooridinates of voxels to the shader and make it draw a cube itself. Can someone tell me, if thats possible, and if so, how?

# Answer
> 1 votes
I am currently working on a voxel engine as well. And I have found a few interesting conclusions:

1. Have 6 different vbo's one for each side (each vbo has contains the vertices of all the blocks which you want to render). A vbo has 4 vertices (connect them to form triangles with an index buffer) per block which contains color information and possibly also lightning information.
2. You can subdivide your world into different `chunks` and generate a vbo per chunk each time that a chunk is changed. Or you can generate your vbo per frame and just add everything which is visible to the camera.
3. Greedy mesh generation resulted (for me) into a 80% performance boost (I generate my vbo's each frame (for now)).

In a question of mine is my code for generating the meshes, this might also help you understand how I render my voxels. I´m not implying that my method is the best method, but this has worked for me (so far).

Here are a few of my sources (which I used to come to these conclusions):

PS: This is not really an answer to the question you asked, but a suggestion. It is what I think is a better alternative.

---
Tags: shaders, glsl, voxels
---


# Question
Title: How would you define this mechanic in narrative based games?
I'm a researching a certain game mechanic that seems very commonplace in modern narrative-based games. The mechanic is defined (by me) as a user action that the player can take while in a dialogue or a cutscene, which affects the course of the narrative (and sometimes has a long lasting impact on the game progression in general).

The interaction can be of several types - press a button\click a character\hit a sequence of keys\button mashing.

Here's an example from Game of Thrones

https://www.youtube.com/watch?v=ykq213pPD6Q&feature=youtu.be&t=181

In Mass Effect it is referred to as an interrupt

https://www.youtube.com/watch?v=9TgTLJXoD\_o

Here's one from King's Quest:

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

I'm looking for more info on this type of mechanic. Specifically -

1. Is there an accepted name for it?
2. What other games have this mechanic, and use it in an interesting way? (I would appreciate links to videos demonstrating it)
3. What types of interactions (such as the ones I've described) have you seen implemented in this mechanic?

Thanks :)

(BTW if you think this game-design related question is more suitable for StackExchange's Arqade do let me know and I'll ask to move it there)

# Answer
> 9 votes
The game mechanic where the player is prompted to press a certain button during an otherwise non-interactive scene is called a Quick-Time Event or QTE.

From the point of view of a game designer, it is a two-edged sword.

On the one hand, it is an effective and very simple to implement tool to keep the player engaged during cutscenes and give them something to do during an otherwise non-interactive part of the game. But on the other hand they are a quite dull game mechanic which could often be replaced with a much more exciting and interactive one and can distract from the cutscene instead of adding immersion.

Your first example (the Game of Thrones one) is not a bad use of QTEs in my opinion. By prompting the player to trigger the execution of a character action, the player is engaged in a cutscene which would otherwise be completely non-interactive. I haven't played that game and the video doesn't tell me if the player has the option to not make their character hit the NPC, but it would definitely be a better option when they could because it would give agency to the player.

The second example (Mass Effect 2) is a bit controversial. It is often not obvious for the player what their character will do when they follow the instructions presented on the screen and what will happen instead when they don't. *So the red icon flashes in the lower-left corner. What happens when I press the left mouse-button? Will my character shout at the other character? Will she punch them? Will she kill them?* The player can't know, and just has seconds to decide. And that in a game where each of the players decisions can have far-reaching consequences. The uncertainty about what decision is to be made right now combined with adding time pressure can make the player feel like they are tricked into performing some action they neither intended to do nor had to do to progress.

Finally, the third example (Kings Quest) appears to be a quite bad use of QTEs. Again, I haven't played the game, but the video gives me the impression that the player has to press the keys showed on the GUI within a very short time limit or they lose the game. Such "quickly press X to not die" quick-time events force the player to focus their attention on the GUI icons which appear on their screen instead of the animation of the cutscene. So they are rather a distraction than adding to the immersion.

Game critics often consider QTEs as a cheap cop-out for adding some action to a games narrative which would be far more fun when represented with proper game mechanics. For example, when you want the player to beat the main villain in hand-to-hand combat, you could implement a proper hand-to-hand combat mechanic where the player can perform different actions and an AI which reacts to them appropriately, but that would be quite a lot of work to polish until it is balanced and fun. Just having a fully-scripted cutscene where the player presses buttons at the right time is far easier. It's also far less fun to play, but it looks almost the same in the trailer when you play it without the GUI. And the reviewers *will* call you out on taking this obvious shortcut too often.

# Answer
> 3 votes
These type of events fall into two main categories as I see them, the first is simple RPG style dialogue options, some good examples for this would be Skyrim and Fallout, as well as classical games such as Zelda and FF, however I think what you are interested in is known as 'quick time events' (QTE's).

QTE's are commonplace in several games but they basically mean when you have to react to a button prompt in a certain amount of time (either dialogue or an action cut scene) and the perfect example of these is in the TellTale games (like the GoT's one you posted).

Another example of these can be seen in games like Gears of War or Left for Dead where an enemy attaches itself or grabs you and you have to hit certain buttons to get them off but I don't think that 'where have you seen this' is a good fit for this type of Q&A (rest of question is). Searching for QTE's should give you a good spread of examples of other cases though.

---
Tags: game-design, user-experience
---


# Question
Title: I'm making a networked game for mobile. Should I worry about cheating?
I'm in the process of making a racing game for Android/iOS. I'm thinking of implementing a server/client model, should I worry about cheating and make all players communicate with a server of mine, or will I be good by letting one of the players host the game?

I'm not sure how much memory editing or packet editing is possible in Android/iOS, and that's the main reason why I'm asking this.

# Answer
> 0 votes
Unfortuntely it's very difficult to prevent cheating when something is only done on the client side or a server hosted by a client. There are lot's of tools for memory editing&locking, package sniffing/editing and similar activities.

There are some ways to make it a bit more difficult, but as soon as one person decompiles your app and takes a look at your prevention methods, it'll be almost useless as well.

I've got a similar problem to solve in the near future and I'm about to try something based on serialized values (which I won't manipulate or even address in code) as I once heard they cannot be tracked easily in the final builds (who knows if that's true though...). This needs some further research but this information may be useful for you. **If that is true**, you could maybe use them as a calculation factor for check-values.

However, the best and most secure way is to have your own servers and handle critical/sensitive logic there.

# Answer
> 2 votes
In android its very easy to manipulate scores. You just need a rooted phone and one app. It can freeze the other app or manipulate in real time. If you let somebody edit his score to 1324891234042390 and send this to the server this won't be very useful for you. I don't know how to prevent it, but i know its easy to perform as the cheater

---
Tags: networking, mobile, anti-cheat
---


# Question
Title: Cursor position to a 3D ray using angles
I've been stuck for a month trying to get gluUnProject working. After my attempts to use gluUnProject failed (as well as attempts to implement gluUnProject functionality manually) I implemented method to get ray using angles.

```
 float RadToDeg = 180.0f / (float)M_PI; // conversion coefficient to degree
 float DegToRad = 1 / RadToDeg; // conversion coefficient to radians

 float DeltaX = tan(fovy/2 * DegToRad) * 2 * (Width / 2 - winX) * zNear / Height;
 float DeltaY = tan(fovy/2 * DegToRad) * 2 * (Height / 2 - winY) * zNear / Height;
 float AngleX = atan(DeltaX / zNear) * RadToDeg;
 float AngleY = atan(DeltaY / zNear) * RadToDeg;

 float DeltaXY = sqrt(DeltaX*DeltaX + DeltaY*DeltaY);
 float AngleXY = atan(DeltaXY / zNear) * RadToDeg;
 float AxisAngle = atan(DeltaX / DeltaY) * RadToDeg;
 vec3 RotationAxis = rotate(Camera->X, AxisAngle, Camera->Z);
 if (DeltaY < 0) { RotationAxis = -RotationAxis; }

 vec3 ray = rotate(-(Camera->Z), AngleXY, RotationAxis); //getting ray direction
 ray = vec3(ray.x * scale, ray.y * scale, ray.z * scale); //scale ray if needed

 vec3 RayEndPoint = Camera->Position + ray;

```

The main idea behind my method is to rotate ray pointing perpendicularly from the middle of the screen (like in first person shooters) to position where you clicked.

Necessary values are fovy angle (field of view in vertical direction), zNear (distance from Camera to near plane) and Camera Transformation Matrix(Camera-\>X, Camera-\>Y, Camera-\>Z, Camera-\>Position - 1st, 2nd, 3rd and 4th columns). Difference between Camera Transformation Matrix and View Matrix here.

Besides we need some method `rotate(vec3 vector,float angle,vec3 axis)` that will rotate any vector at any angle around any arbitrary axis. Explanation how it works will consume too many lines (check photo of my calculations).

Q: Is any easier or better way to do it? Any information or links welcomed.

# Answer
> 1 votes
Just multiply a clip-space coordinate (x and y are screen-coords ranging from \[-1;1\], z=0, w=1) with the **inverse of the view-projection matrix**. Then you need to divide the resulting homogenous vector with its w-component. This gives you a position on the desired ray. To get the ray direction just subtract the camera position and normalize the result.

While this is surely not the best solution in number of arithmetical operations, I find it super intuitive. Since it relies on function which are included in most 3D-math libraries, it is usually also super short in its implementation.

# Answer
> 0 votes
A month ago I came across a youtube video which explains how to do it, although this video is a tutorial for Java, you will probably be able to use it.

The video was based on this text article.

I hope this is usefull for you.

PS: This tutorial uses the LWJGL Matrix functions, this StackExchange answer has some code which you will be able to copy if you need the inverse of a matrix.

---
Tags: opengl, c++, raycasting, perspective, raytracing
---


# Question
Title: Is it possible to have FixedUpdate execute once every n frames?
I'm currently building a small game, and I've created this simple character controller using `FixedUpdate`, which executes every frame.

```
using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
    /// <summary>
    /// Check for a key press, and if that key is pressed,
    /// move in a specified direction if there are no obstacles.
    /// </summary>
    private void MovePlayerOnKey(KeyCode keyCode, Vector3 direction)
    {
        Collider[] hitColliders = Physics.OverlapSphere(this.transform.position + direction, 0.1f);
        if(Input.GetKey(keyCode) && hitColliders.Length <= 0)
        {
            this.transform.position += direction;
        }
    }

    /// <summary>
    /// FixedUpdate is used to ensure that the player is
    /// moving in sync with the step of the Physics engine,
    /// and not executing a variable amount each frame.
    /// </summary>
    public void FixedUpdate()
    {
        this.MovePlayerOnKey(KeyCode.W, new Vector3(0, 1f, 0));
        this.MovePlayerOnKey(KeyCode.A, new Vector3(-1f, 0, 0));
        this.MovePlayerOnKey(KeyCode.S, new Vector3(0, -1f, 0));
        this.MovePlayerOnKey(KeyCode.D, new Vector3(1f, 0, 0));
    }
}

```

While the code itself works, the player moves *much* too fast for my liking, and I can't change the step of the player either, it has to stay at `1` in order for other game mechanics to function properly.

The only solution I can think of is changing how `FixedUpdate` runs by running it less often. Is it possible to make `FixedUpdate` run once every *n* frames?

# Answer
> 1 votes
Well, it seems like this was an easy solution. Thanks to a suggestion by @Quill, I added this to the top of my class:

```
public int timeStepIncrement = 1;
public int timeStepDivisor = 5;
private int timeStepCounter;

```

I then changed `FixedUpdate` to look something like this:

```
public void FixedUpdate()
{
    if(this.timeStepCounter <= 50000 - this.timeStepIncrement)
    { this.timeStepCounter += this.timeStepIncrement; }
    else
    { this.timeStepCounter = 0; }

    if(this.timeStepCounter % timeStepDivisor == 0)
    {
        this.MovePlayerOnKey(KeyCode.W, new Vector3(0, 1f, 0));
        this.MovePlayerOnKey(KeyCode.A, new Vector3(-1f, 0, 0));
        this.MovePlayerOnKey(KeyCode.S, new Vector3(0, -1f, 0));
        this.MovePlayerOnKey(KeyCode.D, new Vector3(1f, 0, 0));
    }
}

```

Now it only executes once every five frames, and is very configurable.

# Answer
> 0 votes
You can change the fixed time step in the time settings of your project, but it may look a bit laggy if you turn it up too much.

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


# Question
Title: How to manipulate unity objects in a C# script?
I am new to unity and i was wanting to know how i can change a objects position and angles and stuff like that in a c# script. I exported the object from blender as .3ds. The objects name is sphere.3ds. please show and explain code.

# Answer
> 0 votes
A quick and easy way to do this would be just to pass in the object as a variable.

Creating a public GameObject variable in a script will allow an object to be handed to it from the Unity interface.

```
public GameObject testObject;

```

Then when you go back into unity you can see a new box appeared in the script module. You can then drag the object you want to manipulate into that box that says `"None (Game Object)"` and it'll be passed into your script as that variable.

To then manipulate that object's position, you can just use its transform and do as you please. It's the object's transform variable which determines its position, rotation, etc.

```
Vector3 objectPos = testObject.transform.position;
Quaternion rotation = testObject.transform.rotation;

```

Also, the transform variable already supplies you with useful functions that you can mess around with, like Translate and RotateAround.

To rotate an object around an axis, use

```
testObject.transform.RotateAround(testObject.transform.position, Vector3.up, 90)

```

The first parameter is the position of the rotation, the second is the axis you want to rotate around, say up, left, right, etc.. And the third is the amount you want to rotate it by.

---
Tags: unity
---


title: Good way to handle offscreen AI?

text:
# Question
Title: Good way to handle offscreen AI?
For example sake:

* Let's say there are 10 rooms in the world.
* And let's say the world is inhabited by 10 entities.
* And each entity has it's own "daily routine" where it performs certain actions in the room and also might navigate between the rooms as well.

Given that the player can only be in one room at a time, what is a good way to keep track of the actions the other entities are performing in other rooms offscreen?

1. The most straightforward option is to check on each of the 10 entities on every frame, check their position/state and determine whether or not the entity should be in the room where player is located in at any given time. *( This however feels really resource heavy especially as the room/entity amount is increased. )*
2. Another option is to keep track of the time that has passed since the start of the game, then each of the entities checks whether its pattern intersects with the room the player is on, and if it does it checks against the time whether or not the entity is supposed to be in the same room at this particular time, entities whose patterns do not intersect with the current room the player is located in do nothing until the player enters a room which their pattern intersects and only at that point calculate whether or not they should render. *( But if they interact with the room, then they will have to always check the state of the rooms which intersect their route in order to determine their location at that point in time, which is not that great. )*
3. The third option I came to would be to first of all only look at the routes which intersect the player location (as described previously), secondly upon entering a room, check if the player is in that room, if not then to only check the state of the room and how long will it take to proceed to the next room. For example a janitor NPC enters the room, checks the state of the room, sees that there is a spillage made by player, calculates how much time it will take to clean that up and how long the pathing will take etc. And until the mentioned time is due to enter the next room we only check if the player is in the room. The exact location of the NPC for rendering purposes would only be calculated when the player enters the room.

After brainstorming a while I came to the third option, but I was wondering if perhaps there is a known or better way to handle things like these?

# Answer
A very simple approach is to use "AI Level of Detail." Roughly, this means that you update AI more frequently the closer it is to the player/camera. You can also reduce the complexity of AI calculations that are farther out, esp. for path-finding. After all, if the player can't see the character well or at all, there's no point putting in a ton of effort into simulating the character at the highest accuracy.

In your example, the room the player is in might get the highest accuracy (AI updates every frame, full resolution). The rooms adjacent might get the next highest accuracy (updates every 10 ticks, remove path smoothing and animations). All the other rooms can get the lowest accuracy (updates every second, low-resolution path-finding, eliminate non-essential NPC-to-NPC interactions).

Bigger and more complex games can (and have) used similar approaches. They might simplify combat calculations, teleport characters rather than path-finding them when they need to move, etc.

If your game is big enough that you can't keep the whole thing in memory at all times, a good solution then is to store the last update time in the room's saved data, and replay its simulation offscreen (at its lowest resolution) when it's loaded back up.

If you expect AI to move into "live" areas from unloaded "asleep" areas on a schedule, you'll either want to create super-low-fidelity data for those regions to keep in memory at all times (e.g., just the coarsest navmesh detail level and key object/character locations) or you'll want to periodically cycle those areas in (e.g., keep X "asleep" areas in memory and simulation at low fidelity with infrequent updates and then round-robin those through all the "asleep" areas that have key active NPCs in them, unloading and loading areas as you do so).
> 12 votes

# Answer
I'd store the entities which are currently in a room in that room instance, the room object would also keep track of when which entities need to be *updated* (eg. travel to another room or change something in that room, etc.). And I'd also update one (or more) room each second (maybe in another thread).

When you update a room, the NPC positions should be updated and all the actions they have performed which interact with the room since the last update should be handled as well, lastly the time of the next needed *update* should be checked / updated.

If an entity travelles from one room to another, it's instance should be stored in the other room and the entity's next *update* should be updated as well.

This way you only have to keep updating the current room and the rooms which have a scheduled update at that moment in time, updating the other rooms is just optional (but recommended if you have an AI which updates whenever the player moves or does something).
> 1 votes

---
Tags: ai, memory-efficiency
---


# Question
Title: How to force Landscape Mode Unity3D Android Game?
I am developing a small side project on Unity that will ultimately be for Android but I cannot figure out how to force landscape on the device and when I have tried it out the game just goes all over the place! I am using Unity Canvas and have spent a long time with binding position points etc. but I cannot work it out! Could someone please tell me how to force the phone into landscape mode?

# Answer
In Unity, navigate to Edit -\> Project Settings -\> Player and choose the platform on the right. Android should be the 4th tab if you're using one of the latest versions of Unity. Open the dropdown menu Resoultion and Presentation, you can set it there.
> 6 votes

---
Tags: unity, c#, android, mobile
---


title: Unity crashes when opening a project

text:
# Question
Title: Unity crashes when opening a project
Why does this happen?

I'm new to Unity development. I have installed Unity yesterday (2015-09-06). This is the error that I get:

# Answer
> 5 votes
Read the error:

> System out of memory!

Maybe there is a lack of RAM on your system. Try closing some (if any) background applications to free up some RAM.

# Answer
> 0 votes
It's likely your system is out of RAM to be able to make the required memory allocations for opening the project. Have you tried a reboot?

If a reboot doesn't help, have a look to see what image file you have in your Unity assets folder that is around 128mb. I would guess as the crash is within Unity's **Image.cpp** source code, and the allocation is for 134217744 bytes or 128mb, that it is unable to find memory to create that large image file.

---
Tags: unity
---


# Question
Title: What's the proper way to set up a texture atlas in Unity 3D?
I am using Unity3d (free) to make a game with user-defined content (i.e., load in a map, it'll build the level for you).

Everything is working as expected, except for the rendering.

Note the artifact / seam along the edge of the two cubes.

I am not entirely sure what is causing this, other than, perhaps a rounding error?

At any rate, every mesh in my scene shares the same texture, with specific UV offsets generated at 1/8 intervals for each corresponding texture:

Playing around with the assigned UVs moves the artifacts around. For instance, the red brick texture has the issue between the top faces:

So clearly, I'm doing this in a suboptimal way. Is there something specific I'm doing wrong? Or is there a better way to build meshes with texture atlases?

# Answer
Here's how I wound up doing it. (This is probably sub-optimal)

The problem originally arose due to a combination of a shared texture and UVs being specified as a float from 0 to 1. That's a recipe for niggling rounding issues.

On the other hand, there is a way to make each texture have the "regular" UVs -- submeshes! I discovered that the "SetTriangles" method already has a "Submesh" parameter, so I split my single texture into individual "blocks", and am able to generate artifact-free objects with each submesh using the full range of UVs.
> 0 votes

# Answer
I would recommend using **Sprite Textures**.

You will need to do the following:

1. Set your texture type to **Sprite (2D and UI)**.
2. Set Sprite mode to **Multiple**.
3. Access the **Sprite editor** and use the Slice tool (sneakily hidden in the upper left corner)

From here, slice up the single image and get multiple sprites to your heart's content. Then you can use these sprites in your gameobject (might need some custom shaders).

If you want to avoid using sprites, I believe you can access this feature by selecting Advanced import setting.
> 2 votes

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


# Question
Title: Why doesn't the animtor animate in unity5?
I have a player consisting of 20 different body parts which I have animated into a walking cycle. When I play the animation in an 'animation' component it works as intended, but when I try to play it from an animator nothing happens.

The player is animated when the animation component is checked.

It does not animate when only the animator component is checked.

It is however running the animation, yet nothing happens in the scene. I have no scripts attached.

# Answer
> 2 votes
Hey can you check the animation type for the clip. Make sure it is not legacy while using it with mecanim. Make the animation clip mode to loop (helps while testing). Also click on Walking\_test and check the inspector if the anim clip is assigned properly. If you already have checked for these things then while playing with mecanim try removing the animation component instead of just disabling it. It will be great if you can provide more information about the animation clip.

---
Tags: unity, animation
---


# Question
Title: How can I simulate a "Hot Swap" betwen Audio Clips?
I have a Unity project with 3 separate looping Audio Clips and a single Audio Source. Based on certain events, I swap between which of them are playing.

This works fine, but whenever I swap between Audio Clips, the AudioSource stops playing, and must be restarted... which means it starts over from the beginning.

As the Audio Clips are the same length, how should I handle the logic to pickup where the previous Clip last left off? Neither Unity's AudioClip nor AudioSource classes seem to have either a "PlayFromTime()" or "GetPercentPlayed()" method that would facilitate using a single Audio Source.

What's the expected way to handle such a scenario? Simultaneously "play" from 3 AudioSources at once, muting 2 of them and leaving the last the only one that is actually heard?

# Answer
> 2 votes
You can use audio.time to get the current time for the music and also setting the time from where the music should start playing.

Link :- http://docs.unity3d.com/ScriptReference/AudioSource-time.html

Pseudo code (not tested)

```
AudioSource audio1;
AudioSource audio2;
AudioSource audio3;

audio1.time = audio2.time;
audio2.Stop();
audio1.Play();

```

---
Tags: unity, sound, audio
---


# Question
Title: How to make a triangle pixellated with GLFW?
How can one make a triangle look pixelated without modifying the size of the window in GLFW3?

Preferably, I'd like to accomplish this without the use of shaders. For example, by setting the size of the frame buffer to be 1/8th the size of the window.

I've created an Xcode test project for this and tried setting a small window size to create a small framebuffer, then changing the window size to be big afterwards, but the framebuffer size always changes to match the window size.

Example project output:

Desired output:

# Answer
> 3 votes
Render to a small render target texture (FBO) first and then render an orthographic quad to the screen using the render target as a texture (with nearest neighbour sampling). There are plenty of tutorials for this such as this one.

---
Tags: opengl, frame-buffer, glfw
---


title: Procedural texturing with opengl

text:
# Question
Title: Procedural texturing with opengl
I have a hexagonal grid of fields, each field has a certain terrain type. I assign every vertex of hexagon with terrain type and pass it as attribute to vertex and then fragment shader. Then I use the extrapolated value to blend terrain textures together.

For instance: 1 is grassy, 2 is desert.

Vertex shader:

```
varying vec2 vUv;
attribute float terrainType;
varying float vTerrainType;

void main()
{
   vUv = uv;
   vTerrainType = terrainType;
   vec4 mvPosition;
   mvPosition = modelViewMatrix * vec4( position, 1.0 );
   gl_Position = projectionMatrix * mvPosition;
}

```

Fragment shader:

```
uniform vec3 diffuse;
uniform float opacity;
varying vec2 vUv;
varying float vTerrainType;
uniform sampler2D map;
uniform sampler2D map1;

void main()
{
   gl_FragColor = vec4( diffuse, opacity );
   vec4 texelColor = texture2D( map, vUv ) * (2.0 - vTerrainType) + texture2D( map1, vUv ) * (vTerrainType - 1.0);
   gl_FragColor = gl_FragColor * texelColor;
}

```

Implementation is WebGL, if it makes any difference.

The result looks really unnatural, so is there any way to make it smoother and rounder?

# Answer
> 1 votes
As you can see, the artifact originates from the interpolation of your vTerrainType varying accross the triangles.

Thus, one possibility to fix the issue would be to subdivide the hexagons in such a way that they have a nicer defined border region of consistent thickness.

Another more complicated but more powerful method would be to compute the distance of each pixel to the border of its hexagon. However, for this you need a lot of information about the field itself - each pixel needs to determine to which hexagon it belongs and where its borders are. Once you have the distance, you can use it to perform blending. Applying functions like `clamp(pow(borderDistance, someExponent)*someScale, 0.0, 1.0)` to this function would allow you even smoother transitions.

---
Tags: opengl, procedural-generation
---


# Question
Title: Different game resolutions on emulator and on a real device (which has the same resolution) on Windows Phone 8
I have a big problem with game resolution, when I'm running my game on emulator (which theoretically has the same resolution as my real windows phone device: 800 x 480). I'm making the game with Monogame.

Here is how it looks, the bottom of a page when I run the game on emulator:

And, here is how it looks the bottom of a page, when I run the game on the real device:

How can I fix this problem? I noticed, that if I hold the back button till I see all the apps that I have opened, and get back to the game, the resolution will be back to normal, as it is on the emulator.

PS\> I'm targeting the Windows Phone 8 devices, and testing on a Lumia 520, with Windows 10 Mobile, Preview for developers.

Thanks.

# Answer
> 0 votes
I think the problem was caused because I was testing on the Windows 10 Mobile Preview. Today I downgraded to Windows Phone 8.1, and I do not have anymore that problem.

---
Tags: c#, xna, monogame
---


# Question
Title: For iteneration + if statement - bottleneck
in list I have objects of 1, 2, 3 type and I must every frame refresh next list where I need only type 2 and 3. - via calculating in Vector3..

This statement consume a lot of time and slow down program, is there any next possibility how make it better ?

Thank you

EDIT: type of object has changing every frame according to what is happening on screen - unpredictable.

```
for(int i = 0; i < 100000; i++)
{
   if(object[i].... != type1)
     list.add(object[i]);
}

```

# Answer
> 1 votes
If this is truly a bottleneck - Create a separate list with only `type2` and `type3` entries and update them without the `!= type1` check.

If the codition changes every frame, maybe you better of having a separate list for every type and update resulting list only from the relevant lists.

---
Tags: performance
---


# Question
Title: Screen management: How to switch between screens
How can I switch between different screens that implement `Screen`?

# Answer
> 2 votes
Something like below. Off course you need to add the Button to the stage, create a skin and the OptionScreen yourself.

```
@Override
    public void show() {
        final OptionScreen optionScreen = new OptionScreen();

        TextButton optionButton = new TextButton("Options", skin);

        optionButton.addListener(new ClickListener(){
            @Override
            public void clicked(InputEvent event, float x, float y) {
                ((Game) Gdx.app.getApplicationListener()).setScreen(optionScreen);
            }
        });
    }

```

Because we use `optionScreen` inside a listener here it has to be final since the application never knows when the button is clicked it. You can also just create a `new` instance of `OptionScreen` inline `setScreen(new OptionScreen);`.

---
Tags: java, libgdx, screen, menu
---


# Question
Title: How do I make hit damage a Gaussian distribution centered around a value?
I'd like my character's attacks to on average 10 damage, but to vary anywhere from 0 to 20.

Instead of a linear spread, I would like a normal distribution, so most of their hits are between 10-15, but they can still hit between 0-20. How can I do this?

I am using PHP.

# Answer
> 4 votes
Second (harder) aproach. I used that in c# to get a gaussian distribution (link) i think you can easly traslate in php.

```
private double  nextGaussian(double mean,double variance ) {
            // https://stackoverflow.com/questions/218060/random-gaussian-variables

            //with mean = 0.5 and variance = 0.5 we get uniform distribution over [0..1]

            double u1 = r.NextDouble(); //these are uniform(0,1) random doubles
            double u2 = r.NextDouble();
            double randStdNormal = Math.Sqrt(-2.0 * Math.Log(u1)) *
                         Math.Sin(2.0 * Math.PI * u2); //random normal(0,1)
                         //Math.Sin( Math.PI * u2); //random normal(0,1)
            double randNormal =
                         mean + variance * randStdNormal; //random normal(mean,stdDev^2)

            return randNormal;

        }

```

You can try

```
 damage = nextGaussian(0.5, 0.2) *MAXDAMAGE ;

```

and play with second parameter of nextGaussian (variance).

Here follow a test I made distributing points over x axe changing the variance :

# Answer
> 2 votes
An easy way is roll 4 dice (6 faces) add them , then subtract 4. You get 0..20 with more distribution in the middle. Or 2 * 12 FACE dice - 2.

# Answer
> 1 votes
Would personally suggest the following KISS technique to convert uniform distribution to slanted distribution:

Randomly (uniformly), draw a number `x` between 0 and 1. Now raise `x` by some const predetermined `p` value (likely) in the range between 1.1 to 7. The larger `p` is, the more slanted (and less likely to hit extreme results) it'll be. Lets call `x` by the power of `p` our `offset coefficient`. Now randomly pick a `sign` (i.e plus or minus \[negative, positive\]). OK, the `center` of your desired range is 10 == the max `offset` from the center.

```
// Essentially
// center +/- offset = min/max
// 10 - 10 = 0
// 10 + 10 = 20

//  So now, you simply do in pseudo code:
small_buffer = ~ 0.1 * range;
rand   = randomize_float_between(0, 1);
coefficient = pow(rand, p);
sign   = pick_one_of_these(-1, 1);
result = center + sign * coefficient * (offset + small_buffer);
result = max(0, min(result, 20)); // Keep it in range

```

This is the simplest way to get and tweak the effect you are looking for.

---
Tags: algorithm, random, distribution
---


# Question
Title: How do I make games that interact with desktop windows?
I want to know how games like desktop pet games like *Sheep* work, so I can make my own:

In this game, the creatures are being rendered directly to the desktop or over top other windows. How do they accomplish this task? How are they getting the window information? Do they take and process screenshots?

# Answer
Games like that are called *screenmates* or *desktop pets*. They are a type of digital pet that interacts with desktop windows.

## Positioning

Desktop pets query the host operating system's windowing system for window positions. The windowing system is typically DWM on Windows and X11 on Linux.

On Windows, you can include `Windows.h` and use `EnumWindows` to get a list of windows, then `GetWindowRect` to find its size and position.

On Linux (using X11), the equivalent calls are `XQueryTree` and `XGetWindowAttributes`.

## Rendering

Most screenmates are rendered with each little character in its own desktop window. The windowing system's API is used to give that window a transparent background and to remove its borders (like this on Windows and this on Linux), to move those windows around, to keep them on top of other windows, and to receive pointer events.

Since using windowing system APIs directly is often very complex, you might want to look into using a UI toolkit such as GTK+ or Qt, which are wrappers for the core windowing functionality. Some are even cross-platform.

## Some helpful links

For Linux, the open source Linux desktop pets XPenguins and oneko may be helpful. Xsnow demonstrates window position queries more minimally.

For Windows, here's a series of articles on replicating xsnow in C++ and C#.
> 6 votes

---
Tags: windows
---


# Question
Title: How to manipulate unity camera in a C# script?
I am new to unity and i'm trying to move the camera to follow the player, but everything i tried won't work. Please explain what each step is and show code. I want to add to its position not use translate.

# Answer
> -1 votes
"Camera Follow"\>

```
using UnityEngine;
using System.Collections;

public class CameraFollow : MonoBehaviour {

private Vector2 velocity;
public float smoothTimeX;
public float smoothTimeY;
public GameObject player;

void Start ()
{

}

void FixedUpdate ()
{
    float posX = Mathf.SmoothDamp(transform.position.x, player.transform.position.x, ref velocity.x, smoothTimeX);
    float posY = Mathf.SmoothDamp(transform.position.y, player.transform.position.y, ref velocity.y, smoothTimeY);

    transform.position = new Vector3(posX, posY , transform.position.z);
}

```

}

---
Tags: unity, movement
---


# Question
Title: Unity 4 mecanim; 'Quaternion to Matrix conversion failed, input quaternion is invalid'
I'm trying to animate a stick figure in Unity, with placeholder animations. Character is built/animated in Blender, exported to FBX. When imported to Unity, everything appears correct in the editor. All animations are imported, and i can preview them normally.

I set up the "rig" section of the model import to use generic rigging. This creates the avatar which is used in mecanim.

I set up a simple "walkForward" animation, and setup mecanim parameters to get it called when the player moved forward; all that works. The animation is called at the right times.

However, during play, as soon as any animation is started on the avatar, the model disappears, and a flood of error messages appear in the console, stating

```
Quaternion to Matrix conversion failed because input Quaternion is invalid {-1.#IND00, -1.#IND00, -1.#IND00, -1.#IND00} |=-1#IND00

```

I'm not altering the animation with any scripts of my own, it's all mecanim. Is there a setting i'm missing?

I'm using Unity 4.3.0.0f4, building/exporting my mesh with Blender (latest).

# Answer
> 1 votes
I was never able to find a proper solution to this problem - I eventually gave up on Unity 4. This year I've returned and found that Unity 5 correctly imports the exact same models/animations and everything works as expected.

So; solution is to update to unity 5.

---
Tags: unity, mecanim
---


# Question
Title: Car Game: Engine and Gearbox calculations?
I am making a racing game inside of Blender Game Engine. You can see the latest video here to get the impression of what type of game it is: https://www.youtube.com/watch?v=0i3m-xXtnhc

What I want to do is to replace current constant engine setup which has a constant Nm value(I guess that applyEngineForce() takes torque as input, but I am sure it uses Nm as unit) whith a new setup that calculates RPM, use RPM/torque curves(I've made 2 arrays for them already), aswell as use gearbox with multiple gear ratios(a custom number). This game is planned to be pretty realistic, but at the same time I must make sure that it is not too expensive(although CPU stuff is not the problem for me usually, it is more GPU and graphics).

So any type of help will be appreciated, thank you!:)

So what I have:

I have steering already. I have inputs for brakes, gas, shifting gears, e-brake and reverse.

What I need:

I need to use the inputs correctly to make engine act naturally. I need to have a gear and RPM dependent torque output as final result aswell as RPM to show in the HUDs. Finally I will put the torque into applyEngineForce() and if I am right, than the final value at 1st gear ratio should be around 3500 - 6000 Nm, but it is the case if applyEngineForce() uses torque.

I couldn't find more information about Blender Game Engine vehicle wrapper!:(

P.S. BGE uses python as it's built-in programing language so I use python for this.

My script at current state which needs improvements:

```
import bge
from bge import logic
import PhysicsConstraints
from gamesystem import gaudges

### Define ###
scene = logic.getCurrentScene()
car = scene.objects["Car"]
keyboard = logic.keyboard
JUST_ACTIVATED = bge.logic.KX_INPUT_JUST_ACTIVATED
ACTIVE = bge.logic.KX_INPUT_ACTIVE

#keyboard keys
gas = keyboard.events[bge.events.WKEY]
left = keyboard.events[bge.events.AKEY]
reverse = keyboard.events[bge.events.SKEY]
right = keyboard.events[bge.events.DKEY]
ebrake = keyboard.events[bge.events.SPACEKEY]

#stats
gasPower = car["gasPower"] * 10
brakePower = car["brakePower"]
ebrakePower = car["ebrakePower"]
reversePower = car["gasPower"] / 3 * 20
maxSteer = car["maxSteer"]
steerSpeed = car["steerSpeed"]
maxSpeed = car["maxSpeed"]

# Define tire objects
tireFL = scene.objects["TireFL"]
tireFR = scene.objects["TireFR"]
tireRL = scene.objects["TireRL"]
tireRR = scene.objects["TireRR"]

### Initialise ###

if not "ini" in car:
    pid = car.getPhysicsId()
    suspension = PhysicsConstraints.createConstraint(pid, 0, 11)
    cid = suspension.getConstraintId()
    suspension = PhysicsConstraints.getVehicleConstraint(cid)

    wheelRadius = 0.345
    suspensionRestLength = 0.5
    hasSteering = 1

    ### Tweakables ###
    damping = car["damping"]
    stiffness = car["stiffness"]
    compression = car["compression"]
    roll = car["roll"]
    grip = car["grip"]
    drift = car["drift"]

    ### Actions ###

    # Generate tires
    wheelAttachDirLocal = [0, 0, -1]
    wheelAttachPosLocal = [-0.745, 1.27, 0.59]
    wheelAxleLocal = [-1, 0, 0]
    suspension.addWheel(tireFL, wheelAttachPosLocal, wheelAttachDirLocal, wheelAxleLocal, suspensionRestLength, wheelRadius, hasSteering)
    wheelAttachDirLocal = [0, 0, -1]
    wheelAttachPosLocal = [0.745, 1.27, 0.59]
    wheelAxleLocal = [-1, 0, 0]
    suspension.addWheel(tireFR, wheelAttachPosLocal, wheelAttachDirLocal, wheelAxleLocal, suspensionRestLength, wheelRadius, hasSteering)
    wheelAttachDirLocal = [0, 0, -1]
    wheelAttachPosLocal = [-0.75, -1.18, 0.59]
    wheelAxleLocal = [-1, 0, 0]
    hasSteering = 0
    suspension.addWheel(tireRL, wheelAttachPosLocal, wheelAttachDirLocal, wheelAxleLocal, suspensionRestLength, wheelRadius, hasSteering)
    wheelAttachDirLocal = [0, 0, -1]
    wheelAttachPosLocal = [0.75, -1.18, 0.59]
    wheelAxleLocal = [-1, 0, 0]
    suspension.addWheel(tireRR, wheelAttachPosLocal, wheelAttachDirLocal, wheelAxleLocal, suspensionRestLength, wheelRadius, hasSteering)

    # Update suspension
    for tire in range(4):
        suspension.setSuspensionDamping(damping, tire)

        suspension.setSuspensionStiffness(stiffness, tire)

        suspension.setSuspensionCompression(compression, tire)

        suspension.setRollInfluence(roll, tire)

    suspension.setTyreFriction(grip, 0)
    suspension.setTyreFriction(grip, 1)
    suspension.setTyreFriction(grip / (drift * ((maxSpeed - gaudges.speed) / maxSpeed)), 2)
    suspension.setTyreFriction(grip / (drift * ((maxSpeed - gaudges.speed) / maxSpeed)), 3)

    car["ini"] = True
    car["CID"] = cid

### Car in action ###

suspension = PhysicsConstraints.getVehicleConstraint(car["CID"])

# Drift
suspension.setTyreFriction(car["grip"] / (car["drift"] * ((maxSpeed - gaudges.speed) / maxSpeed)), 2)
suspension.setTyreFriction(car["grip"] / (car["drift"] * ((maxSpeed - gaudges.speed) / maxSpeed)), 3)

# Gas
if gas == ACTIVE:
    car["gas"] = gasPower
else:
    car["gas"] = 0

# Emergency brake
if ebrake == ACTIVE:
    car["ebrake"] = ebrakePower
else:
    car["ebrake"] = 0

# Reverse
if reverse == ACTIVE:
    if car["speed"] > 0:
        car["brake"] = brakePower
        car["gas"] = -reversePower
    else:
        car["brake"] = 0
        car["gas"] = -reversePower
else:
    car["brake"] = 0

# Steering
if right == ACTIVE:
    if car["steer"] > -maxSteer:
        car["steer"] -= steerSpeed
elif left == ACTIVE:
    if car["steer"] < maxSteer:
        car["steer"] += steerSpeed
else:
    car["steer"] = 0.0

drive = car["drive"]
## drives
    # 1: rear
    # 2: front
    # 3: full
frontDrive = 0
rearDrive = 0

if drive == 1 or drive == 3:
    rearDrive = 1
else:
    rearDrive = 0.5

if drive == 2 or drive == 3:
    frontDrive = 1
else:
    frontDrive = 0.5

for tire in range(4):
    # Front tires
    if tire < 2:
        suspension.applyEngineForce(-car["gas"] * frontDrive, tire)
        suspension.applyBraking(car["brake"], tire)
    # Rear tires
    else:
        suspension.applyEngineForce(-car["gas"] * rearDrive, tire)
        suspension.applyBraking(car["ebrake"], tire)

suspension.setSteeringValue(car["steer"], 0)
suspension.setSteeringValue(car["steer"], 1)

gaudges.speed = car.getLinearVelocity(1).y * 3.6
car["speed"] = int(gaudges.speed)

if car["speed"] > maxSpeed:
    car.localLinearVelocity.y = maxSpeed / 3.6

if car["speed"] < -(maxSpeed / 2):
    car.localLinearVelocity.y = -((maxSpeed / 2) / 3.6)

```

To make sure that you see my knowledge level, here is what I know already aswell as what I need:

http://blenderartists.org/forum/showthread.php?381056-Need-to-find-resources-of-equations-in-engine-RPM-part

# Answer
First, you'll need to make a model of your engine. It should be a simple function that would resemble the green line.

Quick and dirty inquiry at wolfram alpha gives this estimation:

```
def max_engine_torque_at_rpm(rpm):
    return -0.0000138889 * rpm ** 2 + 0.0799786 * rpm - 28.2671

```

Now this is incredibly trivial and not representative at all of what you really want. You should, at least, implement linear interpolation of some dataset, either of a real engine or a made up one.

Then, calculate how fast your wheels are spinning. This will depend on how realistic you want to get. As a most trivial example, just divide movement speed by 2 pi.

Then, divide the wheel's RPM by the current gear's ratio and the result will basically be the engine's RPM (unless you do some damage modeling at the transmission part). Plug that into the function defined earlier, and you get maximum torque from the engine. Scale that by current throttle input.

When you have the torque currently produced by the engine, multiply it by current gear ratio. The result is what should be outputted towards the wheels.

Again, all of this is very simplified. You can add simulation of friction, inertia, damage, and any other influences to any step of this algorithm.
> 3 votes

---
Tags: python, racing, car, blender-game-engine
---


# Question
Title: Overlapping surfaces in deferred shader blend through one another
I've just finished implementing deferred shading into my engine, and noticed that when a large object overlaps another smaller object, it blends through it.

For example, in this scene I have a large plane floor, and on top of it rests 3 rectangle walls. When looking at these walls anywhere from above the floor, one can see that the floor blends through the walls.

Alternatively, here's a small video clip showing what I mean

I've been following a tutorial series on OGLDev, and have followed the guide very closely, with the sole exemption being that I use a component based system.

---

The general format of my rendering loop is as follows:

1. Prepare the GBuffer
2. Render Pass (render to FBO, output properties as textures)
3. Stencil Pass (render light object for stencil operations)
4. Light Pass (sample from previous textures for lighting calculations)
5. Final Pass (draw back to default FBO)

Specifically, during my rendering pass the lights are rendered using geometrical objects, such as a bounding sphere for point lights (the only light currently implemented).

---

I believe that the issue is with the function

> glBlendFunc(GL\_ONE, GL\_ONE);

I may have multiple lights in a scene, so I need to be able to blend them all together, however when I do that I seem to also get surfaces blending together. If I disable the blend function, the problem disappears but then only the last light processed will render.

The blend function occurs in the following function:

Lighting Pass:

```
void DLightPointComponent::LightPass(DCamera *cam, GBuffer *gbuffer)
{
    // Obtain required objects for lighting pass
    PointLight point = getPointLight();
    BaseLight base = point.getBaseLight();
    Attenuation atten = point.getAtten();
    DModelComponent *BSphere = getSphere();
    DSuperShader *shader = getSuperShaderProgram();
    QMatrix4x4 mat = getModelMatrix(), mat2 = BSphere->getModelMatrix();
    DMeshComponent *mesh = BSphere->getMeshComponent();

    // Scale up bounding sphere
    float BSphereScale = CalcPointLightBSphere(point)*5000000000;
    mat2.scale(BSphereScale);

    // Prepare textures for sampling
    gbuffer->BindForLightPass();

    // Upload uniforms to shader
    shader->bind();
    shader->bindCamera(*cam);
    shader->pushMatrix(mat);
    shader->pushMatrix(mat2);
    mesh->setShaderProgram(shader);
    mesh->bindToShader();

    ... (upload the many light uniforms to shader) ...

    // Specific OpenGL operations
    glStencilFunc(GL_NOTEQUAL, 0, 0xFF);
    glDisable(GL_DEPTH_TEST);
    glEnable(GL_BLEND);
    glBlendEquation(GL_FUNC_ADD);
    glBlendFunc(GL_ONE, GL_ONE);
    glEnable(GL_CULL_FACE);
    glCullFace(GL_FRONT);

    // Render the bounding sphere
    mesh->pollWholeMesh();

    //Clean up shader
    glCullFace(GL_BACK);
    glDisable(GL_BLEND);
    shader->popMatrix();
    shader->release();
}

```

My rendering pass in question:

```
void oglWidget::RenderPass(QList<DComponent*> *components, DCamera *cam, GBuffer *gbuf)
{
    // Obtain the gbuffer shader, and bind all prerequisites to the shader
    DSuperShader *shader = gbuffer->getSuperShaderProgram();
    gbuf->BindForGeomPass();
    shader->bind();
    shader->bindCamera(*cam);

    // Specific OpenGL functions
    glDisable(GL_BLEND);
    glDepthMask(GL_TRUE);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glEnable(GL_DEPTH_TEST);

    // Render geometry into GBuffer
    for (int x = 0, total = components->size(); x < total; ++x)
        components->at(x)->pollLocal(shader);

    // Shader Cleanup
    shader->release();
    shader->popMatrix();
    shader->purgeCamera();
    glDepthMask(GL_FALSE);
}

```

If any further information is wanted, I'll post it.

# Answer
> 1 votes
I don't know **why** this is happening, but somehow despite the fact that I clearly disable blending at the end of my lighting function, and don't use it anywhere else in my rendering loop, this effect seems to happen.

However, if add the following line **after** disabling blending:

> glBlendFunc(GL\_ONE, GL\_ZERO);

..then the problem disappears, for now. This is the default blending function.

---
Tags: opengl, deferred-rendering, deferred-shading
---


# Question
Title: Does Holacracy help new game development teams?
I am setting up a game development team in my university, and we have an interest in making a strategic game based on simple graphics. My question is in relation to the management of the team. It has been suggested that we use some unusual new lightweight management system. Does this Holacracy system help in managing new game development teams?

# Answer
> 2 votes
Try it - or not. There is no recipe for success. Everyone's different. Every team is different.

If it works, great! If it doesn't work, then at least you'll learn from the experience.

---
Tags: project-management, teamwork
---


title: Call function after Level loaded

text:
# Question
Title: Call function after Level loaded
I'm stuck in this situation:

I have a GameObject with a script, that persist trough Level loads.

Inside this script, when a condition is meet, i Load a Level, and also call a function. That function is a `C# Messenger` `Broadcast()` function.

The level that I am loading contain the script with the Listener for that Messenger Broadcast.

The problem is that the Broadcast occurs before the level has been loaded, and so there is no Messenger Listener that can receive the event.

> BroadcastException: Broadcasting message OnConnectionError but no listener found.

**I need to do the Broadcast only after the level has been loaded, but I don't know how, or maybe there is a better solution.**

For a simple example here is the code:

```
public class NetworkingManager : MonoBehaviour {

    void Start(){
        DontDestroyOnLoad (this);
    }

    void OnConnectionLost(BaseEvent _event ){
        if(Application.loadedLevelName != "LoginScreen"){
            Application.LoadLevel ("LoginScreen");
        }
        Debug.Log ("Disconnected. Reason: " + _event.Params["reason"]);
        Messenger<string>.Broadcast ("OnConnectionError", "Disconnected");
    }
}

```

# Answer
try using OnLevelWasLoaded :

```
public class NetworkingManager : MonoBehaviour {
    bool broad = false;
    void Start(){
        DontDestroyOnLoad (this);
    }

    void OnConnectionLost(BaseEvent _event ){
    broad = true;
        if(Application.loadedLevelName != "LoginScreen"){
            Application.LoadLevel ("LoginScreen");
        }
    }
    void OnLevelWasLoaded(){
      if (broad ){
        Debug.Log ("Disconnected. Reason: " + _event.Params["reason"]);
        Messenger<string>.Broadcast ("OnConnectionError", "Disconnected");
    broad =false;
      }
    }
}

```
> 2 votes

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


# Question
Title: How can I do something only after an animation has finished?
I'm making this 2D platform based game. Basically what I want is when the player walks into spikes (which have a "deadly" tag") it displays the animation that has the parameter of animate with the value of 3 and after that the player gets destroyed. So my question is:

* How do I build a timer or something so that the object only gets destroyed after the animation is played (with no looping)?

This is the code I'm using now:

```
void OnTriggerEnter2D(Collider2D target) {
    if (target.gameObject.tag == "Deadly") {
        Die();
    }
}

void Die() {
    animator.SetInteger ("AnimState", 3);
    Destroy (gameObject);
}

```

# Answer
> 3 votes
The propper way to trigger actions in certain frames of an animation is to use Animation Events. Basically, you edit the animation, adding an "event" in the last frame, and in that event you set the "Die" function to be called without any parameter.

Take a look here: http://docs.unity3d.com/Manual/animeditor-AnimationEvents.html

Also, using animation events you don't depend on timers or coroutines, and you can do a lot more than waiting for the end since you have full control on every frame.

# Answer
> 0 votes
> How do I build like a timer or something so that the object only gets destroyed after the animation is played

Do this with a coroutine, something like:

```
void OnTriggerEnter2D(Collider2D target) {
    if (target.gameObject.tag == "Deadly") {
      StartCoroutine(Die());
    }
}

IEnumerator Die() {
    animator.SetInteger ("AnimState", 3);
    while (animator.isPlaying) { // or whatever this property is called
        yield return null;
    }
    Destroy (gameObject);
}

```

If you're unfamiliar with coroutines, that line "yield return null" in the middle tells Unity to pause this function for a frame before picking up where it left off. So this code gets stuck in a loop until the animation stops playing.

# Answer
> 0 votes
After combining this tutorial with the answer from @DiegoSLTS I ended up with this code:

```
using UnityEngine;
using System.Collections;

public class GameOverManager : MonoBehaviour {

  private Animator animator;

  void Awake() {
    animator = GetComponent<Animator> ();
  }

  void Update () {
    if (GameManager.instance.GetHealth () <= 0) {
        Debug.Log (GameManager.instance.GetHealth ());
        animator.SetTrigger("GameOver");
    }
  }

  public void GameOverTriggered() {
    Debug.Log ("Game Over Triggered");
    Time.timeScale = 0;
  }
}

```

# Answer
> 0 votes
Maybe it's a little late, but if someone will need to know, you can add events for Unity animations http://docs.unity3d.com/Manual/animeditor-AnimationEvents.html

as well for imported Animation clips http://docs.unity3d.com/Manual/AnimationEventsOnImportedClips.html (basically the same steps, but you do them during the import/reimport of the animation/object).

---
Tags: unity, animation
---


# Question
Title: Do shader compilers typically know not to look up unused texture channels?
I have a texture that's from the color attachment of an FBO in OpenGL ES 2.0, so I have limited control over the number of channels in the image.

Suppose I only need the color from the R channel of this texture. If I immediately swizzle out the R in the fragment shader like this:

```
float brightness = texture2D(u_texture, v_texCoord).r;

```

can I expect the GPU to know not to bother looking up G, B, and A?

I figure this is something that might vary from device to device, depending on the optimizations of the shader compiler, but to me this looks like a very obvious and easy optimization.

I'd like to know if I can be reasonably confident that almost all GPUs will make the optimization. This shader is a multiple-texture shader, and I'd hate to get surprised by some percentage of devices running it much slower than what I've tested on. If I cannot, then I may want to take pains to use a different method of generating my image so I can ensure a texture with fewer channels.

# Answer
You are not going to see any difference from fetching one channel over many. There is no optimization to make.

Longer explanation:

Texure is stored, you can guess without any doubt, by pixel in memory. Which means, r,g,b,a are packed together on the same place. (i.e. channels are interleaved). Fetching stuff from memory happens in batches of whatever the DDR format banksize is, which is probably quite large, more than one pixel for sure. Luckily, because shaders fetch usually only one pixel, transferring more is not lost in overhead, it is used to fill the texture unit cache. Which works well usually because of correlation between shader unit core locality, and texture space locality.
This is ensured using Z-order curve storage in main memory. (aka Morton code).
*for the trivia this is actually also called swizzling, but has nothing to do with shader swizzled accessors.*

The swizzle operation takes no supplementary time thanks to the pipelined instruction architecture, but it does not permit optimization either.

One could think nvidia card (scalar shader units) would be advantaged over ATI cards (vector shader units) in the case where ALU works with scalars like here. But this is not related to compilation, or optimization.

Some optimizations that the compiler WILL perform:

move texture fetches as high as possible in the shader, above any computation even sometimes. This is possible if `tex2d` instructions are not dependent on variable uvs (purely varying passing verbatim). Note that this will be true even if the tex2d instruction is inside a condition !

The goal of this, is to try to act as a prefetcher. To hide bus latencies over ALU speed.
> 3 votes

---
Tags: shaders, glsl, hlsl, opengl-es2, gpu
---


title: Error when initializing Stage

text:
# Question
Title: Error when initializing Stage
I made a new class that implements Screen, what I've seen from other people's code is that they create a constructor that takes a parameter of Game game. I did not created a constructor, I think that's the reason why I get the error

```
  public class MainMenu implements Screen{
     public MainMenu(Game game){ //I dont know what are these for
            this.game = game;    //<--
        }

 public void show() {
        btnAtlas=new TextureAtlas(Gdx.files.internal("bitters.atlas"));
        skin=new Skin();
        skin.addRegions(btnAtlas);
        stage=new Stage(Gdx.graphics.getWidth(),Gdx.graphics.getHeight(),true);// I get the error here when initializing the Stage
    }
 }

```

the error is `"Cannon resolve constructor 'Stage(int,int,boolean)'"`

# Answer
The message is pretty clear. There is no constructor that takes `(int, int, boolean)`. Here are the constructors from Stage.java source code.
> 2 votes

---
Tags: java, libgdx, screen, initialization
---


# Question
Title: The import aurelienribon cannot be resolved
I've been having problems with using the Tween Engine by aurelien ribon for a Splash Screen for my 2d game. I'm using Eclipse and libgdx.

I've tried rebuilding, clean...-ing, and refreshing.

I've closely followed the import directions from here: https://github.com/libgdx/libgdx/wiki/Universal-Tween-Engine

I'd be more than happy to provide anyone with more information/code if they need it.

The import file/lines of code (Game Renderer class):

```
package com.companyname.gameWorld;

import aurelienribon.tweenengine.Tween;
import aurelienribon.tweenengine.TweenEquations;
import aurelienribon.tweenengine.TweenManager;

```

build.gradle:

```
project(":android") {
    apply plugin: "android"

    configurations { natives }

    dependencies {
        compile project(":core")
        compile "com.badlogicgames.gdx:gdx-backend-android:$gdxVersion"
        natives "com.badlogicgames.gdx:gdx-platform:$gdxVersion:natives-armeabi"
        natives "com.badlogicgames.gdx:gdx-platform:$gdxVersion:natives-armeabi-v7a"
        natives "com.badlogicgames.gdx:gdx-platform:$gdxVersion:natives-x86"
        compile "com.badlogicgames.gdx:gdx-box2d:$gdxVersion"
        natives "com.badlogicgames.gdx:gdx-box2d-platform:$gdxVersion:natives-armeabi"
        natives "com.badlogicgames.gdx:gdx-box2d-platform:$gdxVersion:natives-armeabi-v7a"
        natives "com.badlogicgames.gdx:gdx-box2d-platform:$gdxVersion:natives-x86"
        compile "com.badlogicgames.gdx:gdx-freetype:$gdxVersion"
        natives "com.badlogicgames.gdx:gdx-freetype-platform:$gdxVersion:natives-armeabi"
        natives "com.badlogicgames.gdx:gdx-freetype-platform:$gdxVersion:natives-armeabi-v7a"
        natives "com.badlogicgames.gdx:gdx-freetype-platform:$gdxVersion:natives-x86"

        compile "com.badlogicgames.gdx:gdx-bullet:$gdxVersion"
        natives "com.badlogicgames.gdx:gdx-bullet-platform:$gdxVersion:natives-armeabi"
        natives "com.badlogicgames.gdx:gdx-bullet-platform:$gdxVersion:natives-armeabi-v7a"
        natives "com.badlogicgames.gdx:gdx-bullet-platform:$gdxVersion:natives-x86"

        compile fileTree(dir: '../libs', include: '*.jar')
    }
}

```

...(other project(":...")s)...

```
project(":core") {
    apply plugin: "java"

    dependencies {
        compile "com.badlogicgames.gdx:gdx:$gdxVersion"
        compile "com.badlogicgames.gdx:gdx-box2d:$gdxVersion"
        compile "com.badlogicgames.gdx:gdx-freetype:$gdxVersion"

        compile "com.badlogicgames.gdx:gdx-bullet:$gdxVersion"

        compile fileTree(dir: '../libs', include: '*.jar')
    }
}

```

The /libs folder:

# Answer
In the /libs folder, right click the two tween-engine.jar files, Build Path \> Add to Build Path
> 1 votes

---
Tags: 2d, libgdx, eclipse, tweening
---


# Question
Title: Remove Touch LIstener from scene at a specific point
how to remove SceneTouchListner at a specific point?

I am Working on a Endless Runner Game. my player is jumping onSceneTouchListner when player is collide with a barrier i want to remove TouchListner because i attached a particle effact that burns my player.

# Answer
> -1 votes
finally I got Solution ..............I am Creating a new IOnSceneTouchListener tv= new IOnSceneTouchListener() {

```
                @Override
                public boolean onSceneTouchEvent(Scene pScene, TouchEvent pSceneTouchEvent)
                {
                    if(pSceneTouchEvent.isActionUp())
                    {
                        player.animate(new long[]{200, 200, 200},9,11, true);
                        return true;
                    }
                    return false;
                }
            };

```

and the just write scene.setonsceneTouchListner(tv);.

---
Tags: andengine
---


# Question
Title: Why does my player walk animation take so long to begin?
I'm new to Unity and after doing some tutorials and reading documentation from Unity, I've started a test project. The game is a 2.5D platformer and I wrote the PlayerController; it looks like this:

```
using UnityEngine;
using System.Collections;

public class PlayerMovement : MonoBehaviour {

    public float turnSmoothing = 15f;
    public float speedDampTime = 0.1f;

    private Animator anim;
    private Rigidbody rb;
    // Use this for initialization
    void Start () {
        anim = GetComponent<Animator>();
        anim.SetLayerWeight(1, 1f);

        rb = GetComponent<Rigidbody>();
    }

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

    }

    void FixedUpdate()
    {
        float h = Input.GetAxis("Horizontal");
        MovementManagement(h);
    }

    void MovementManagement (float horizontal)
    {
        if (horizontal != 0.0f)
        {
            anim.SetBool("Move", true);
            anim.SetFloat("Speed", 5.5f, speedDampTime, Time.deltaTime);
            Rotating(horizontal);

        }
        else
        {
            anim.SetFloat("Speed", 0.0f);
            anim.SetBool("Move", false);
        }
    }

    void Rotating (float horizontal)
    {
        Vector3 targetDirection = new Vector3(horizontal, 0.0f, 0.0f);
        Quaternion targetRotation = Quaternion.LookRotation(targetDirection, Vector3.up);
        Quaternion newRotation = Quaternion.Lerp(rb.rotation, targetRotation, turnSmoothing * Time.deltaTime);
        rb.MoveRotation(newRotation);
    }
}

```

My AnimatorController has a BlendTree called Locomotion and looks like this:

When I run the game and use the keyboard or the controller the player starts walking, but it takes a long time (I can see the Speed parameter from the blend Tree that has to reach "5" to start walking)

I think I'm not understanding something but I don't know what it is.

# Answer
> 3 votes
When you trigger the transit from one animation state to another with a parameter condition, that condition won't be checked until the exit time of the transition is reached in the current animation cycle. So when you have a very long idle animation with a long exit time, it can take a while until the conditions for changing to the walk animation is checked and the animator blends to `HumanoidWalk`. For example, when your idle animation is 2 seconds and your exit time is 0.8, it can take up to 1.6 seconds until the transition happens.

To fix this issue, reduce the exit time or remove it altogether by unchecking "Has Exit Time" in the transition.

Another problem might be a too long "transition duration".

As an alternative way to switch to a different animation state *immediately*, you can also use `anim.Play` which will skip the transition altogether.

---
Tags: unity, movement, 2.5d
---


title: Collisions between sprites in SpriteKit

text:
# Question
Title: Collisions between sprites in SpriteKit
I'm making a game in XCode using SpriteKit. The game has a player and different types of projectiles that he has to avoid. When the player collides with the projectiles, the score changes and the projectile disappears. However, when two projectiles collide, they kind of bounce away. I want to make that every time two projectiles collide, they act like nothing happened and they keep going in their original path. What should I do?

\*Note: This is not the whole code, it's just what matters.

```
    import SpriteKit

    struct Physics {
        static let player : UInt32 = 1
        static let missileOne : UInt32 = 2
        static let missileTwo : UInt32 = 3
    }

class GameScene: SKScene, SKPhysicsContactDelegate {

    var player = SKSpriteNode(imageNamed: "p1.png")

    override func didMoveToView(view: SKView) {

        physicsWorld.contactDelegate = self

        player.position = CGPointMake(self.size.width/2, self.size.height/5)
        player.physicsBody = SKPhysicsBody(rectangleOfSize: player.size)
        player.physicsBody?.affectedByGravity = false
        player.physicsBody?.dynamic = false
        player.physicsBody?.categoryBitMask = Physics.player
        player.physicsBody?.collisionBitMask = Physics.missileOne
        player.physicsBody?.collisionBitMask = Physics.missileTwo

        var missileOneTimer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("SpawnMissileOne"), userInfo: nil, repeats: true)
        var missileTwoTimer = NSTimer.scheduledTimerWithTimeInterval(1.2, target: self, selector: Selector("SpawnMissileTwo"), userInfo: nil, repeats: true)

        self.addChild(player)
    }

    //When contact happens
func didBeginContact(contact: SKPhysicsContact) {
    var firstBody : SKPhysicsBody = contact.bodyA
    var secondBody : SKPhysicsBody = contact.bodyB

    if ((firstBody.categoryBitMask == Physics.player) && (secondBody.categoryBitMask == Physics.missileOne)) {

        CollisionWithMissileOne(firstBody.node as SKSpriteNode, missileOne: secondBody.node as SKSpriteNode)

    } else if ((firstBody.categoryBitMask == Physics.player) && (secondBody.categoryBitMask == Physics.missileTwo)){

        CollisionWithMissileTwo(firstBody.node as SKSpriteNode, missileTwo: secondBody.node as SKSpriteNode)

    } else if ((firstBody.categoryBitMask == Physics.missileOne)&&(secondBody.categoryBitMask == Physics.missileTwo)) {

        CollisionBetweenMissiles(firstBody.node as SKSpriteNode, missileTwo: secondBody.node as SKSpriteNode)

        }

    }

//For Player and MissileOne
    func CollisionWithMissileOne(player: SKSpriteNode, missileOne: SKSpriteNode) {

        missileOne.removeFromParent()
    }

//For Player and MissileTwo
    func CollisionWithMissileOne(player: SKSpriteNode, missileTwo: SKSpriteNode) {

        missileTwo.removeFromParent()
    }

//For MissileOne and MissileTwo
        func CollisionBetweenMissiles(missileOne: SKSpriteNode, missileTwo: SKSpriteNode) {

        ???WHAT SHOULD I CODE HERE???

    }

}

```

# Answer
You may want to modify the `collisionBitMask` property of your SKPhysicsBodies.
You can set a bitmask to make collision rules. Objects that shares a same bit collides together. Since `collisionBitMask` is a `UInt32`, you can set up to 32 different layers of collision.

Set your projectiles in different layers depending on who launched the projectile.

Here's an answer you'll probably be interested in.
> 2 votes

---
Tags: physics, ios, spritekit, xcode, swift
---


# Question
Title: Camera will not move between given points, stuck at first given point
\[EDIT: Working code added\]

\[Original question\]

I'm putting together a "raid cam" or "overview cam" for a given map in my shooter for an observing player to use to fly down a given preset path (to prevent griefing and cheating, this may change in my final build)

Unfortunately though I can get the program to invoke the given method, iterate through each of my points, and display this to the debug console, my player camera does not move from the very first start point. I'm attempting to use the Vector3.MoveTowards function at the moment but if there is a better way to move the camera between the points I am open to that.

\[/Original question\]

The code is as follows, and heavily commented for clarity on my thought process:

```
// Invoked from external function, takes precoded path and translates player between the given points
public void FlyThroughPath(List<Vector3> path){

    // If the flightpath is not empty
    if(path.Count > 0){
        // If we haven't already enabled fly through mode
        if (!enabled){
            Debug.Log ("enabling fly through mode");
            // Enable fly mode
            enabled = true;
            // Assign our starting point
            CurrentIndex = 0;
            StartPoint = path[0];
            // Move us to the start point
            transform.position = StartPoint;
        }else if (enabled && CurrentIndex < path.Count){
            Debug.Log ("Already enabled, moving to next point");
            // If the distance between the points is too far we keep moving towards that point
            if(Vector3.Distance(transform.position, path[CurrentIndex]) > 5.5f){
                Debug.Log("Too far keep moving");
                FlyToNextPoint(transform.position, path[CurrentIndex]);
            }else if (Vector3.Distance(transform.position, path[CurrentIndex]) <= 5.5f){
                Debug.Log ("Point reached move to next one");
                CurrentIndex++;
            }else{
                Debug.Log ("Ifs were too specific, whoops");
            }
        }else if(enabled && CurrentIndex >= path.Count){ // If enabled and we don't have another point in our path
            Debug.Log ("no more points let's disable the flythrough");
            // We have arrived at our last point so let's disable the flythrough;
            enabled = false;
        }
    }
}

// Takes two points and transforms the player camera between them at a preset speed
public void FlyToNextPoint(Vector3 start, Vector3 end){
    // Grab the time for movement speed and duration
    // Snag the player's last chosen speed for consistency
    m_speed = flyMotor.m_actualSpeed;
    // put together the time we want to use between the two points
    float t = m_speed * Time.deltaTime;
    // Move the player between the given points at the given speed
    Debug.Log ("Flying to " + end.ToString() + " from position " + start.ToString());
    // Move the player camera towards the next point from the given start point
    transform.position = Vector3.MoveTowards(start,end, t);
}

```

EDIT: For clarity the function is evoked here:

```
// Update is called once per frame
void Update () {
   [...]
   else if(cInput.GetKeyUp("Fly Mode Start")){
        Debug.Log ("Flythrough initiated in FlyMotor");
        // Instantiate and start the flight path functions
        AutoFlyThrough = GetComponent<FlyThrough>();
        AutoFlyThrough.FlyThroughPath(FlightPath);
    }

    if(AutoFlyThrough != null){
        if (AutoFlyThrough.enabled){
            // Check the position and continue to move the player
            AutoFlyThrough.FlyThroughPath(FlightPath);
        }
    }
}

```

# Answer
You can't assign `transform.position = StartPoint` at the beginning of each invocation of your FlyThroughPath. I'm assuming you're calling FlyThroughPath on every frame so I'll walk through quickly what's going on in **each** frame.

1. Position gets reset to the first starting point
2. Add a little bit of the distance to each point in the path to the position

After this occurs, it *appears* to be at the first point but is really a little bit of the way to every point (which is still not what you want).

Instead your algorithm should behave more like this

1. Determine which point you're currently flying towards (keep track of this)
2. Call `transform.position = Vector3.MoveTowards(transform.position, NextPoint, t)`
3. If you reach the point, update the next point to the next in the list

Note that this probably requires keeping some state! You need to recall which index into the list you're currently flying towards. The index should be initialized to 0, and when it reaches the end of the array you know the fly through is over. You increment the index when you get very very close to the current destination point, you probably should not do floating point comparisons to see if they're equal. Instead check to see if the distance between the current position and the current destination is less than the speed at which you move.
> 0 votes

---
Tags: c#, movement, vector
---