# Question
Title: What are the advantages and challenges of using Haxe over ActionScript 3?
I read this, and I also see that using FlashDevelop you can make an Adobe Air project with Haxe and compile to exe.

I begun to wonder from a game making perspective:

Are there any additional advantages in performance when using Haxe instead of AS3 for games development (for the web)?

# Answer
At our studio we are working with Haxe and NME, and the advantages are great. Performance and cross-platform are the more important points (at least for us).

## Pros

* Even with only a few people in the forums, you can receive a lot of help. It's a very active community. Check at haxenme.org, haxe.org, and haxe group in Google groups.
* Numerous people helped port the many APIs. They can also help you to do your own.
* If you make a simple game, without many "social" features, then cross-platform is like doing ctrl-enter in Flash. You can target the following platforms with Haxe and NME: iOS, Android, BB PLaybook, WebOS, HTML5 (with some limitations), Windows, Mac, Linux and Flash.
* The very best of the best: In FlashDevelop for Windows, you can do Haxe projects targeting C++, Java, and NME (a framework that brings flash methods to Haxe). Also, you can use MonoDevelop 3 with a Haxe add-in. It's not as good as FlashDevelop, but it does the work. Another option can be FDT, though it's not free.
* If you have experience with ActionScript, then Haxe won't be a problem for you. Of course, there are some language differences, like how they handle for loops and iterators.
* Haxe is great if you want to be able to transition from one platform to another, like from web games to mobile games.
* The performance is really, really great. However, we didn't test it against stage3D. You will need to work with different methods according to the final target, but it is not a big deal.

## Cons

* There is not much documentation, and existing documentation is not very detailed. There are only a few books on Haxe, many of which are outdated.
* If you are a flash game developer looking for sponsors, then you'll face some troubles when you need to add their APIs. The same applies for mobile development (iOS GameCenter, iAds, Google, etc)
* There are times that you'll need to know how to code in native Obj-C, Java, or C++. BB Playbook also requires a device (I don't know if this has changed).
* There are not many cross platform IDEs
* We've only worked with single-player games, so I can't recommend Haxe for multi-player. I guess it won't be a problem, but I don't have the experience to confirm that.

I hope you find this answer useful, and don't hesitate in trying Haxe. It is not hard to port code from Actionscript 3.0 to Haxe and NME.
> 11 votes

# Answer
I don't think so until now our developers still now facing with VERY LOW performance of HAXE compare to (native on android , iOS, flash) .
> 1 votes

---
Tags: actionscript-3, haxe
---


# Question
Title: Geometry Shader only creates one primitive
I am currently trying to use the geometry shader.

My input is a set of points, for which multiple triangle should be created

This is the geometry shader

```
#version 330
layout(points) in;
layout(triangle_strip, max_vertices = 3) out;

in vec3[] vPos;
out vec3 oPos;

void main() {
    for(int i = -1; i <= 1; i++)
        for(int j = -1; j <= 1; j++)
        {
            for(int k = -1; k <= 1; k++)
            {
                oPos = vPos[0] + vec3(i,j,k);
                EmitVertex();
            }
        EndPrimitive();
        }

}

```

And this the corresponding C++ code

```
mMeshGenerator->use();

GLuint query;
glGenQueries(1, &query);
glEnable(GL_RASTERIZER_DISCARD);
glBindBufferBase(GL_TRANSFORM_FEEDBACK_BUFFER, 0, mMeshVBO->buffer());
glBeginQuery(GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN, query);
    glBeginTransformFeedback(GL_TRIANGLES);
        mPointsVAO->draw();
    glEndTransformFeedback();
glEndQuery(GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN);
glFlush();
GLuint primitives;
glGetQueryObjectuiv(query, GL_QUERY_RESULT, &primitives);

std::cout << "-----" << primitives << "-----" << std::endl;
GLfloat feedback[primitives*3*3];
glGetBufferSubData(GL_TRANSFORM_FEEDBACK_BUFFER, 0, sizeof(feedback), feedback);

for (int i = 0; i < primitives*3*3; i++) {
    printf("%f\n", feedback[i]);
}
glDisable(GL_RASTERIZER_DISCARD);

```

According to the query only one primitive is written.

Output for input point (10,20,30):

```
-----1-----
9.000000
19.000000
29.000000
9.000000
19.000000
30.000000
9.000000
19.000000
31.000000

```

Whats wrong with my code that there is only 1 triangle instead of 27?

# Answer
Your code looks like it wants to output 9 triangles each consisting of a discreet three vertex triangle strip, not 27 triangles.

However you have set max\_vertices to 3 in the layout statement at the top of the shader so it only emits one triangle before it hits that limit. (The limit is for the whole shader, not per-primitive, otherwise 3 would have been fine).
> 3 votes

---
Tags: opengl, c++, geometry-shader
---


# Question
Title: City/Nation Builder - Unlocking game elements over time
Current Git (Needs more documentation)

Current working prototype to play with (Git code is after a BIG refactor)

**Background:** I'm making a javascript text city/nation builder along the lines of A Dark Room or Candy Box. This is going to be the player managing a city but be able to vassalise other cities (Ala Europa Universalis), giving you a tribute of their income but no specific control over it like your own one.

Each city has a tree of things in it, including buildings, resources, tools/machines and intermediate crafting items. These types each have their own object constructors and can easily have a complex object of about 5-50 keys depending on the item just from a few lines of code. Each tree starts at the top, a category for sorting on the UI/namespace, and then inside that is the actual object itself. So whenever referencing an item in a crafting recipe or production chain there's a `"resource.material.wood"` or `"buildingHouse.tent.small"` or such.

The player or "empire" can own multiple cities, but only directly control one in the city view screen (You can tell your city exactly how to be managed, but all other cities you've taken over live their own life, but you can send them requests and investments to boost specific things). Because the item trees are so expansive (170 items in the prototype on my website) I need an easy way to hide things away that aren't unlocked yet. Decided to go with the Civ 5 tech tree route.

**Current problem:** In the prototype I had the tech tree and items bound to the window instead of to the city. This meant there was only ever a single instance of everything and to unlock something in the UI I could just go (simplified) `foreach (unlockedItem) {item.unlocked = true}`. I can't do this as easily in the multiple city model because the tech system is player specific, not city specific, and so if you take over a new city they should retroactively build the city's tech level from that player's tech level. I'm not sure how I want to handle inheriting resources/buildings from a more advanced civ yet either.

Relevant code pulled from the Git as an example: pastebin.com/DbbUXbaL

As far as I can tell, there's a not so easy way I can work around this.

Flip the way I unlock things. The item is then bound to a tech that unlocks it instead of a tech being bound to multiple items. In my head I prefer the latter way because it means I can group like items together (The resource with the building that produces it) and it's easier to list the items that the tech unlocks when you're in the research menu. It's also much easier in the code to see what a tech unlocks at a glance, instead of going from class to class. The problem with the latter way though is that it's hard to retroactively unlock things in a newly unlocked city.

**The question to Gamedev:** Those of you with more experience than I, how would you go about designing a technology system for an entity heavy game like the Anno series or Civ if each tech unlocked 5+ things? Do I have the right idea binding the item to the tech or is there a much simpler way of doing it I'm just not seeing?

# Answer
Here is my suggestions

**Dealing with Trees** You can do any tree by using tables. It can serve as dependency counter for what ever tree you are doing. Already tested by me some time ago were skill tree, knowledge tree and my favorite, item tree.

For this example we are going to use "Item" tree.

Each item will be a record for the table name ItemTree. They will be composed of the following fields:

```
id
itemName
Status
itemCaller
itemDependencyCounter
itemDependencyTotal
etc...

```

*Status* field indicates if item is locked or unlocked. It can have 0 or 1 value. 0 for locked and 1 for unlocked.

*itemCaller* are string typed field consisting of other item "id"s with separator (a comma) in which the content can be like so...

```
id, id, id, id...

```

*itemDependencyCounter* indicates how much times a dependency of that item has been unlocked.

*itemDependencyTotal* indicates the total dependency of that item before that item is unlocked.

How to use: Whenever an item is unlocked your program should read *itemCaller* and update the rest of the items indicated on it to increment their *itemDependencyCounter*. Then another loop on the table should check if there are new items where *itemDependencyCounter* is equal to their *itemDependencyTotal*. if there is, it will unlock that item and do the loop again until there are no more items needed to be unlocked.

Note that the number of items are dependent on certain amount of item plus numbers of scenarios/events (which again can be tabled in the same way).

Example item1 has 5 *itemDependencyTotal* but there are only 2 item calling(unlocking) it. This is possible because certain scenarios/events might hold the other 3 triggers missing in order to unlock that item.

All together it create this kind of logic example:

```
item=pike
dependencies=array(item=wood,item=Ore,knowledge=bronze,time>2000BC,etc...)
unlocks=array(unit=phalanx,item=spear,etc...)

```

You see the benefit here is prominent because you do NOT have to declare the actual dependencies. Only the unlocks are stated on the table. No Redundancy.

Again as I've mentioned scenarios/events even skills, knowledge and other game parameters for your cities or your character can be tabularized the same way.

This behaves like a tree but is much simplified in some way.

**2 Dimensional Array** You can also use 2 dimensional array that acts the same logic as table above. Problem here is you have to memorize the sequence which parameter gives status, itemDependencyCount and itemDependencyTotal. Another problem might be memory size but everything can be managed upto a certain degree.

**Dealing with Multiple Cities.** Using the solution above all you need is another field named "City". You can add a whole batch of item specific for that city that is currently locked and few unlocked items to begin.

Next you need to create an AI that randomly unlocks per item or per scenario/events. Then when your program does the checking for unlock, it should be included since they are one table.

Random Events and/or AI Randomly choosing things to do can have parameters that increase over time.

Example: Initially the AI (because of limited resources,items,knowledge,etc) can only do 5 things at one time but eventually increases as more parameters are unlocked. Therefore you can assign it like so...

```
 AITodo = Random(n)

```

where n is the number of things the AI can do.

**How many tables should I put?.** It depends on your games. Essentially if the table listed applies to your game tree, you can put it.

```
1.)Item  runned
2.)Skills
3.)Knowledge(like in Civ)
4.)Milestone/prizes
5.)Map Areas
6.)Resources
7.)Enemies

```

**Example of Game Logic:**

```
SetInitialScenario >> UserInteraction >> CoreLogic >> TerminatorChecks >>
Render >> BackToUserInteraction

```

**Inside Core Logic:**

```
AIInput >> UserAIValidation >> TableProcess >> OtherLogicYouLike >>
EnemyAIInput >> TableProcess >> OtherLogicYouLike >> ExitCoreLogic

```

where TableProcess is the "How to Use" as indicated above.

**Task/Timer Organization** You can put a single time-counter that checks the time based tasked. Again every time a task is expected to happen (after user interaction), tasked should be inserted to the table. The records of this task are index in time the task is suppose to finish.

Next is on your program logic you can add a TaskMonitor function that whenever a task is expired (current time \>= timeToExpire) it will be deleted on the table and the desired changes are applied to the game. This function can be run Asynchronously or dependent on User activity.

**Data Structures** I could explain this to you or I can do this instead.

```
City1
City2
|_____Resources
|        |______Wood
|        |______Gold
|        |______etc...
|
|_____Production(Rates)
|        |______Wood
|        |______Gold
|        |______etc
|
|_____Building
|        |______Factories
|        |         |_______Smerlters
|        |         |_______ etc...
|        |______Homes
|        |______etc
|
|_____Tools
|_____Machines
|_____Item
|_____Research
City3
etc...

```

Do not confuse your data structures with game logic and functions. You need a way to associate the dependencies of your structure as tree... that is different. You need a function that monitors task... again that is different. You need an AI for the other Cities management... again different. You need an Enemy-AI that will randomly attack or give a challenge to your game... again it is a different function.

Try separating the logic for your user interaction versus the logic that happens behind the scene with or without user interaction.

**Will it create an Overload** the beauty of databases/tables is you do not need to store them on memory therefore your game will not be a resource hog. Overload may also be prevented by choosing a proper PL.

**Programming Language** Although it can be done in JavaScript there are better PLs out there that gives best results. Some favorites are C++, Java, even C#.net can be used to make games for XBOX. Note Rendering and actual game logic programming may use different applications.

**Finally** Do not overshoot your design. Make one and move on. Research some stuff then apply it to your next project.
> 3 votes

---
Tags: architecture, javascript, design-patterns
---


title: diagonals on a tiled map

text:
# Question
Title: diagonals on a tiled map
I have a map of tiles that is drawn using two triangles. I draw my map using a height map to generate vertices and make a Cell(tile) out of 4 vertices like so:

```
cells[x][z] = new Cell(corner1, corner2, corner3, corner4, colour1, colour2, colour3, colour4);

```

Now I want it so that if 3 corners match in colour, let's say blue, and the other 4th is green then I should have one triangle will be that blue and the other that is green.

Now my logic for this is as follows:

```
// triangle 1
VertexInfo v1 = new VertexInfo();
VertexInfo v2 = new VertexInfo();
VertexInfo v3 = new VertexInfo();

// triangle 2
VertexInfo v4 = new VertexInfo();
VertexInfo v5 = new VertexInfo();
VertexInfo v6 = new VertexInfo();

for (Cell[] cellrow : chunks[c].cells) {
for (Cell cell : cellrow) {
    if (cell.getColor1().equals(cell.getColor4())
            && cell.getColor1().equals(cell.getColor2())
            && cell.getColor2().equals(cell.getColor4())
                    && !cell.getColor1().equals(cell.getColor3())) {
/* 4\
*  | \
*  1--\2
*/
        v1.setPos(cell.getCorner3()).setNor(cell.getLeftNormal()).setCol(cell.getColor3()).setUV(cell.getTexturePos());
        v2.setPos(cell.getCorner2()).setNor(cell.getLeftNormal()).setCol(cell.getColor3()).setUV(cell.getTexturePos());
        v3.setPos(cell.getCorner4()).setNor(cell.getLeftNormal()).setCol(cell.getColor3()).setUV(cell.getTexturePos());

        v4.setPos(cell.getCorner1()).setNor(cell.getRightNormal()).setCol(cell.getColor1()).setUV(cell.getTexturePos());
        v5.setPos(cell.getCorner4()).setNor(cell.getRightNormal()).setCol(cell.getColor1()).setUV(cell.getTexturePos());
        v6.setPos(cell.getCorner2()).setNor(cell.getRightNormal()).setCol(cell.getColor1()).setUV(cell.getTexturePos());

        meshBuilder.triangle(v1, v2, v3);
        meshBuilder.triangle(v4, v5, v6);

    } else if (cell.getColor2().equals(cell.getColor1())
            && cell.getColor2().equals(cell.getColor3())
            && cell.getColor3().equals(cell.getColor1())
                    && !cell.getColor2().equals(cell.getColor4())) {
/*    /3
*    / |
*  1/--2
*/
        v1.setPos(cell.getCorner1()).setNor(cell.getLeftNormal()).setCol(cell.getColor2()).setUV(cell.getTexturePos());
        v2.setPos(cell.getCorner3()).setNor(cell.getLeftNormal()).setCol(cell.getColor2()).setUV(cell.getTexturePos());
        v3.setPos(cell.getCorner2()).setNor(cell.getLeftNormal()).setCol(cell.getColor2()).setUV(cell.getTexturePos());

        v4.setPos(cell.getCorner3()).setNor(cell.getRightNormal()).setCol(cell.getColor4()).setUV(cell.getTexturePos());
        v5.setPos(cell.getCorner1()).setNor(cell.getRightNormal()).setCol(cell.getColor4()).setUV(cell.getTexturePos());
        v6.setPos(cell.getCorner4()).setNor(cell.getRightNormal()).setCol(cell.getColor4()).setUV(cell.getTexturePos());

        meshBuilder.triangle(v1, v2, v3);
        meshBuilder.triangle(v4, v5, v6);

    } else if (cell.getColor3().equals(cell.getColor4())
            && cell.getColor3().equals(cell.getColor2())
            && cell.getColor2().equals(cell.getColor4())
            && !cell.getColor3().equals(cell.getColor1())) {
/* 4\--3
*    \ |
*     \2
*/
        v1.setPos(cell.getCorner3()).setNor(cell.getLeftNormal()).setCol(cell.getColor3()).setUV(cell.getTexturePos());
        v2.setPos(cell.getCorner2()).setNor(cell.getLeftNormal()).setCol(cell.getColor3()).setUV(cell.getTexturePos());
        v3.setPos(cell.getCorner4()).setNor(cell.getLeftNormal()).setCol(cell.getColor3()).setUV(cell.getTexturePos());

        v4.setPos(cell.getCorner1()).setNor(cell.getRightNormal()).setCol(cell.getColor1()).setUV(cell.getTexturePos());
        v5.setPos(cell.getCorner4()).setNor(cell.getRightNormal()).setCol(cell.getColor1()).setUV(cell.getTexturePos());
        v6.setPos(cell.getCorner2()).setNor(cell.getRightNormal()).setCol(cell.getColor1()).setUV(cell.getTexturePos());

        meshBuilder.triangle(v1, v2, v3);
        meshBuilder.triangle(v4, v5, v6);

    }else if (cell.getColor4().equals(cell.getColor1())
            && cell.getColor4().equals(cell.getColor3())
            && cell.getColor3().equals(cell.getColor1())
                    && !cell.getColor4().equals(cell.getColor2())) {
/* 4--/3
*  | /
*  1/
*/

        v1.setPos(cell.getCorner1()).setNor(cell.getLeftNormal()).setCol(cell.getColor2()).setUV(cell.getTexturePos());
        v2.setPos(cell.getCorner3()).setNor(cell.getLeftNormal()).setCol(cell.getColor2()).setUV(cell.getTexturePos());
        v3.setPos(cell.getCorner2()).setNor(cell.getLeftNormal()).setCol(cell.getColor2()).setUV(cell.getTexturePos());

        v4.setPos(cell.getCorner4()).setNor(cell.getRightNormal()).setCol(cell.getColor4()).setUV(cell.getTexturePos());
        v5.setPos(cell.getCorner3()).setNor(cell.getRightNormal()).setCol(cell.getColor4()).setUV(cell.getTexturePos());
        v6.setPos(cell.getCorner1()).setNor(cell.getRightNormal()).setCol(cell.getColor4()).setUV(cell.getTexturePos());

        meshBuilder.triangle(v1, v2, v3);
        meshBuilder.triangle(v4, v5, v6);
    } else {

/* 4---3
*  |   |
*  1---2
* (both same colour)
*/
        v1.setPos(cell.getCorner1()).setNor(cell.getLeftNormal()).setCol(cell.getColor1()).setUV(cell.getTexturePos());
        v2.setPos(cell.getCorner3()).setNor(cell.getLeftNormal()).setCol(cell.getColor1()).setUV(cell.getTexturePos());
        v3.setPos(cell.getCorner2()).setNor(cell.getLeftNormal()).setCol(cell.getColor1()).setUV(cell.getTexturePos());

        v4.setPos(cell.getCorner4()).setNor(cell.getRightNormal()).setCol(cell.getColor1()).setUV(cell.getTexturePos());
        v5.setPos(cell.getCorner3()).setNor(cell.getRightNormal()).setCol(cell.getColor1()).setUV(cell.getTexturePos());
        v6.setPos(cell.getCorner1()).setNor(cell.getRightNormal()).setCol(cell.getColor1()).setUV(cell.getTexturePos());

        meshBuilder.triangle(v1, v2, v3);
        meshBuilder.triangle(v4, v5, v6);

    }
}

```

But with the above logic I get this:

I don't see why this isn't working. Does anyone have a solution? or has anyone already done this?

# Answer
I decided to use the surrounding tiles rather than the corners of a single cell. It's not exactly what I was looking for but here is the resulting map and the code (Still have some fine tuning to do):

```
for (int cx = 0; cx < chunks[c].cells.length; cx++) {
for (int cz = 0; cz < chunks[c].cells[0].length; cz++) {

    colorC = chunks[c].cells[cx][cz].getColor1();
    if (cx != 0
            && cz != 0
            && cx != chunks[c].cells.length - 1
            && cz != chunks[c].cells[0].length - 1) {

        colorN = chunks[c].cells[cx][cz + 1].getColor1();
        colorE = chunks[c].cells[cx - 1][cz].getColor1();
        colorW = chunks[c].cells[cx + 1][cz].getColor1();
        colorS = chunks[c].cells[cx][cz - 1].getColor1();
        colorNW = chunks[c].cells[cx + 1][cz + 1].getColor1();
        colorNE = chunks[c].cells[cx - 1][cz + 1].getColor1();
        colorSW = chunks[c].cells[cx + 1][cz - 1].getColor1();
        colorSE = chunks[c].cells[cx - 1][cz - 1].getColor1();

        /* Check for South East */
        if (colorC.equals(colorS)
                && colorC.equals(colorE)
                && colorC.equals(colorSE)
                && !colorC.equals(colorN)
                && !colorC.equals(colorNW)
                && !colorC.equals(colorW)
                ) {

            chunks[c].cells[cx][cz].setColor1(colorN);

            v1.setPos(chunks[c].cells[cx][cz].getCorner3()).setNor(chunks[c].cells[cx][cz].getLeftNormal()).setCol(colorN).setUV(chunks[c].cells[cx][cz].getTexturePos());
            v2.setPos(chunks[c].cells[cx][cz].getCorner2()).setNor(chunks[c].cells[cx][cz].getLeftNormal()).setCol(colorN).setUV(chunks[c].cells[cx][cz].getTexturePos());
            v3.setPos(chunks[c].cells[cx][cz].getCorner4()).setNor(chunks[c].cells[cx][cz].getLeftNormal()).setCol(colorN).setUV(chunks[c].cells[cx][cz].getTexturePos());

            v4.setPos(chunks[c].cells[cx][cz].getCorner1()).setNor(chunks[c].cells[cx][cz].getRightNormal()).setCol(colorS).setUV(chunks[c].cells[cx][cz].getTexturePos());
            v5.setPos(chunks[c].cells[cx][cz].getCorner4()).setNor(chunks[c].cells[cx][cz].getRightNormal()).setCol(colorS).setUV(chunks[c].cells[cx][cz].getTexturePos());
            v6.setPos(chunks[c].cells[cx][cz].getCorner2()).setNor(chunks[c].cells[cx][cz].getRightNormal()).setCol(colorS).setUV(chunks[c].cells[cx][cz].getTexturePos());

            meshBuilder.triangle(v1, v2, v3);
            meshBuilder.triangle(v4, v5, v6);

            /* Check for South West */
        } else if (colorC.equals(colorS)
                && colorC.equals(colorW)
                && colorC.equals(colorSW)
                && !colorC.equals(colorN)
                && !colorC.equals(colorNE)
                && !colorC.equals(colorE)
                ) {

            chunks[c].cells[cx][cz].setColor1(colorS);

            v1.setPos(chunks[c].cells[cx][cz].getCorner1()).setNor(chunks[c].cells[cx][cz].getLeftNormal()).setCol(colorS).setUV(chunks[c].cells[cx][cz].getTexturePos());
            v2.setPos(chunks[c].cells[cx][cz].getCorner3()).setNor(chunks[c].cells[cx][cz].getLeftNormal()).setCol(colorS).setUV(chunks[c].cells[cx][cz].getTexturePos());
            v3.setPos(chunks[c].cells[cx][cz].getCorner2()).setNor(chunks[c].cells[cx][cz].getLeftNormal()).setCol(colorS).setUV(chunks[c].cells[cx][cz].getTexturePos());

            v4.setPos(chunks[c].cells[cx][cz].getCorner3()).setNor(chunks[c].cells[cx][cz].getRightNormal()).setCol(colorN).setUV(chunks[c].cells[cx][cz].getTexturePos());
            v5.setPos(chunks[c].cells[cx][cz].getCorner1()).setNor(chunks[c].cells[cx][cz].getRightNormal()).setCol(colorN).setUV(chunks[c].cells[cx][cz].getTexturePos());
            v6.setPos(chunks[c].cells[cx][cz].getCorner4()).setNor(chunks[c].cells[cx][cz].getRightNormal()).setCol(colorN).setUV(chunks[c].cells[cx][cz].getTexturePos());

            meshBuilder.triangle(v1, v2, v3);
            meshBuilder.triangle(v4, v5, v6);

            /* Check for North West */
        } else if (colorC.equals(colorN)
                && colorC.equals(colorW)
                && colorC.equals(colorNW)
                && !colorC.equals(colorS)
                && !colorC.equals(colorSE)
                && !colorC.equals(colorE)
                ) {

            chunks[c].cells[cx][cz].setColor1(colorN);

            v1.setPos(chunks[c].cells[cx][cz].getCorner3()).setNor(chunks[c].cells[cx][cz].getLeftNormal()).setCol(colorN).setUV(chunks[c].cells[cx][cz].getTexturePos());
            v2.setPos(chunks[c].cells[cx][cz].getCorner2()).setNor(chunks[c].cells[cx][cz].getLeftNormal()).setCol(colorN).setUV(chunks[c].cells[cx][cz].getTexturePos());
            v3.setPos(chunks[c].cells[cx][cz].getCorner4()).setNor(chunks[c].cells[cx][cz].getLeftNormal()).setCol(colorN).setUV(chunks[c].cells[cx][cz].getTexturePos());

            v4.setPos(chunks[c].cells[cx][cz].getCorner1()).setNor(chunks[c].cells[cx][cz].getRightNormal()).setCol(colorS).setUV(chunks[c].cells[cx][cz].getTexturePos());
            v5.setPos(chunks[c].cells[cx][cz].getCorner4()).setNor(chunks[c].cells[cx][cz].getRightNormal()).setCol(colorS).setUV(chunks[c].cells[cx][cz].getTexturePos());
            v6.setPos(chunks[c].cells[cx][cz].getCorner2()).setNor(chunks[c].cells[cx][cz].getRightNormal()).setCol(colorS).setUV(chunks[c].cells[cx][cz].getTexturePos());

            meshBuilder.triangle(v1, v2, v3);
            meshBuilder.triangle(v4, v5, v6);

            /* Check for North East */
        } else if (colorC.equals(colorN)
                && colorC.equals(colorE)
                && colorC.equals(colorNE)
                && !colorC.equals(colorN)
                && !colorC.equals(colorSW)
                && !colorC.equals(colorW)
                ) {

            chunks[c].cells[cx][cz].setColor1(colorN);

            v1.setPos(chunks[c].cells[cx][cz].getCorner1()).setNor(chunks[c].cells[cx][cz].getLeftNormal()).setCol(colorS).setUV(chunks[c].cells[cx][cz].getTexturePos());
            v2.setPos(chunks[c].cells[cx][cz].getCorner3()).setNor(chunks[c].cells[cx][cz].getLeftNormal()).setCol(colorS).setUV(chunks[c].cells[cx][cz].getTexturePos());
            v3.setPos(chunks[c].cells[cx][cz].getCorner2()).setNor(chunks[c].cells[cx][cz].getLeftNormal()).setCol(colorS).setUV(chunks[c].cells[cx][cz].getTexturePos());

            v4.setPos(chunks[c].cells[cx][cz].getCorner4()).setNor(chunks[c].cells[cx][cz].getRightNormal()).setCol(colorN).setUV(chunks[c].cells[cx][cz].getTexturePos());
            v5.setPos(chunks[c].cells[cx][cz].getCorner3()).setNor(chunks[c].cells[cx][cz].getRightNormal()).setCol(colorN).setUV(chunks[c].cells[cx][cz].getTexturePos());
            v6.setPos(chunks[c].cells[cx][cz].getCorner1()).setNor(chunks[c].cells[cx][cz].getRightNormal()).setCol(colorN).setUV(chunks[c].cells[cx][cz].getTexturePos());

            meshBuilder.triangle(v1, v2, v3);
            meshBuilder.triangle(v4, v5, v6);

            /* Full Square*/
        } else {
            v1.setPos(chunks[c].cells[cx][cz].getCorner1()).setNor(chunks[c].cells[cx][cz].getLeftNormal()).setCol(colorC).setUV(chunks[c].cells[cx][cz].getTexturePos());
            v2.setPos(chunks[c].cells[cx][cz].getCorner3()).setNor(chunks[c].cells[cx][cz].getLeftNormal()).setCol(colorC).setUV(chunks[c].cells[cx][cz].getTexturePos());
            v3.setPos(chunks[c].cells[cx][cz].getCorner2()).setNor(chunks[c].cells[cx][cz].getLeftNormal()).setCol(colorC).setUV(chunks[c].cells[cx][cz].getTexturePos());

            v4.setPos(chunks[c].cells[cx][cz].getCorner4()).setNor(chunks[c].cells[cx][cz].getRightNormal()).setCol(colorC).setUV(chunks[c].cells[cx][cz].getTexturePos());
            v5.setPos(chunks[c].cells[cx][cz].getCorner3()).setNor(chunks[c].cells[cx][cz].getRightNormal()).setCol(colorC).setUV(chunks[c].cells[cx][cz].getTexturePos());
            v6.setPos(chunks[c].cells[cx][cz].getCorner1()).setNor(chunks[c].cells[cx][cz].getRightNormal()).setCol(colorC).setUV(chunks[c].cells[cx][cz].getTexturePos());

            meshBuilder.triangle(v1, v2, v3);
            meshBuilder.triangle(v4, v5, v6);
        }

        /* Edge of chunk*/
    } else {
        v1.setPos(chunks[c].cells[cx][cz].getCorner1()).setNor(chunks[c].cells[cx][cz].getLeftNormal()).setCol(colorC).setUV(chunks[c].cells[cx][cz].getTexturePos());
        v2.setPos(chunks[c].cells[cx][cz].getCorner3()).setNor(chunks[c].cells[cx][cz].getLeftNormal()).setCol(colorC).setUV(chunks[c].cells[cx][cz].getTexturePos());
        v3.setPos(chunks[c].cells[cx][cz].getCorner2()).setNor(chunks[c].cells[cx][cz].getLeftNormal()).setCol(colorC).setUV(chunks[c].cells[cx][cz].getTexturePos());

        v4.setPos(chunks[c].cells[cx][cz].getCorner4()).setNor(chunks[c].cells[cx][cz].getRightNormal()).setCol(colorC).setUV(chunks[c].cells[cx][cz].getTexturePos());
        v5.setPos(chunks[c].cells[cx][cz].getCorner3()).setNor(chunks[c].cells[cx][cz].getRightNormal()).setCol(colorC).setUV(chunks[c].cells[cx][cz].getTexturePos());
        v6.setPos(chunks[c].cells[cx][cz].getCorner1()).setNor(chunks[c].cells[cx][cz].getRightNormal()).setCol(colorC).setUV(chunks[c].cells[cx][cz].getTexturePos());

        meshBuilder.triangle(v1, v2, v3);
        meshBuilder.triangle(v4, v5, v6);
    }

```
> 0 votes

---
Tags: tiles
---


# Question
Title: If object is bellow another object... do something
I have 2 objects in scene. When pillar is bellow target, pillar object needs to animate. I get this error: "NullReferenceException: Object reference not set to an instance of an object".

```
var pillar : GameObject;
var target : GameObject;

public var triggered : boolean = false;

function OnTriggerEnter() { triggered= true; }
function OnTriggerExit()  { triggered= false;}

function Update(){
    if (triggered && Input.GetKeyDown(KeyCode.JoystickButton1)){
        if(target.transform.position.y > pillar.transform.position.y){
            pillar = GameObject.Find("Pillars");
            pillar.animation.Play();
        }
    }
}

```

# Answer
> 1 votes
In your second *if* you access the pillar and you set it to an object.

When you try to access the pillar-Object, it never has been set and as such is initialized with null. This is your error.

```
//first if
{
    tempPillar = GameObject.FindGameobjectWithTag ("Pillars");
    //second if with tempPillar!
    {
        pillar =tempPillar;
        //play Animation
    }
}

```

---
Tags: unity, javascript, animation, transformation
---


# Question
Title: How do I save a screenshot and load it as a texture for use in game?
I have a Unity level that takes a screenshot taken in the previous level and applies it as a material to a Plane, the problem is that it will get stuck and not apply the most recent version of the screenshot.

I figure that the best way would be to handle it with a C# script instead of just simply dragging and dropping the image file from the assets folder like I have been doing.

# Answer
> 1 votes
Depending on what you want to do in your game, you could store the screenshot to disk and later load it or you could hold the reference to the Texture2D in a persistent object (not advised if you want to keep many screenshots).

Either way, to load it assign it to a plane, simply do:

```
target.renderer.material.mainTexture = image;

```

Where `target` is the reference to the GameObject where the texture will be applied and `image` is the Texture2D.

Now, from what I understand you are capturing already the screenshots; but, what I do (as a Unity Free developer) is to capture and save it to disk, like this:

```
private IEnumerator TakeScreenshot()
{
    Camera cam = Camera.main;
    Texture2D image = new Texture2D(photoWidth, photoHeight);

    RenderTexture currentRT = RenderTexture.active;

    RenderTexture.active = cam.targetTexture;
    cam.Render();

    yield return new WaitForEndOfFrame();

    photoRect = new Rect(0, 0, Screen.width, Screen.height);
    image.ReadPixels(photoRect, 0, 0);

    //Resize the image. Useful if you don't need a 1:1 screenshot.
    //4 is just used as an example. You could use 10 to resize it
    //to a tenth of the original scale or whatever floats your boat.
    if (resizePhotos)
        TextureScale.Bilinear(image, image.width / 4, image.height / 4);

    image.Apply();
    RenderTexture.active = currentRT;

    target.renderer.material.mainTexture = image;

    //Save it as PNG, but it could easily be changed to JPG
    byte[] bytes = screenshot.EncodeToPNG();

    string filename = "MyScreenshot";

    System.IO.File.WriteAllBytes(filename, bytes);
    Debug.Log(string.Format("Took screenshot to: {0}", filename));
}

```

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


# Question
Title: Concerns about Google Play Games security
I want to develop a Android game using LibGDX. Let's take a classic example ; some player can battle another one in turn based matches. The outcome of match defines the reward in some ingame currency. There will be premium currency with in-app purchases, and both can be used to purchase some upgrades.

I am discovering both Android and GPG at this point. GPG allows some P2P turn battles, matchmaking and cloud saves, making it looks like quite the thing I need.

However, I have concerns regarding its security. The currencies needs, for obvious reasons here, to be fully secure, non corruptable by altering saves on the device. In the same way, it is my understanding that the turn based (and real time) matches are P2P, between devices.

My question is, what GPGS does to enforce security on both (cloud) saves and P2P matches ? Will I need to use some backend server for this case ? And if yes, how can I authenticate a player logged in GPG on this backend server ?

Thanks for any clues about that.

# Answer
According to this Google Saved Games documentation :

> Read/Write isolation
>
> All Saved Games are stored in your players' Google Drive Application Data Folder. This folder can only be read and written by your game - it cannot be viewed or modified by other developers’ games, so there is additional protection against data corruption. In addition, Saved Games are insulated from direct tampering by players so they cannot modify individual Saved Games.

It then looks like the saves data are protected.
> 1 votes

---
Tags: android, google-play, google-play-services
---


title: Deal Damage to Player

text:
# Question
Title: Deal Damage to Player
I have to make a simple "avalanche" game to show I know how to use the physics and creating terrain. But I actually wanted to go a little above and beyond and actually give the player health so there is a actual purpose to dodging the sphere objects. I found a very useful guide on how to set up player health, the only thing is I don't know how to set up the player taking damage when he collides with a sphere. Here is the code I have for the players health

```
#pragma strict

public var health : float = 100f;                           // How much health the player has left.
public var resetAfterDeathTime : float = 5f;                // How much time from the player dying to the level reseting.
public var deathClip : AudioClip;                           // The sound effect of the player dying.

private var anim : Animator;                                // Reference to the animator component.
private var playerMovement : PlayerMovement;            // Reference to the player movement script.
private var hash : HashIDs;                             // Reference to the HashIDs.
private var sceneFadeInOut : SceneFadeInOut;            // Reference to the SceneFadeInOut script.
private var lastPlayerSighting : LastPlayerSighting;    // Reference to the LastPlayerSighting script.
private var timer : float;                                  // A timer for counting to the reset of the level once the player is dead.
private var playerDead : boolean;                           // A bool to show if the player is dead or not.

function Awake ()
{
    // Setting up the references.
    anim = GetComponent(Animator);
    playerMovement = GetComponent(PlayerMovement);
    hash = GameObject.FindGameObjectWithTag(Tags.gameController).GetComponent(HashIDs);
    sceneFadeInOut = GameObject.FindGameObjectWithTag(Tags.fader).GetComponent(SceneFadeInOut);
    lastPlayerSighting = GameObject.FindGameObjectWithTag(Tags.gameController).GetComponent(LastPlayerSighting);
}

function Update ()
{
    // If health is less than or equal to 0...
    if(health <= 0f)
    {
        // ... and if the player is not yet dead...
        if(!playerDead)
            // ... call the PlayerDying function.
            PlayerDying();
        else
        {
            // Otherwise, if the player is dead, call the PlayerDead and LevelReset functions.
            PlayerDead();
            LevelReset();
        }
    }
}

function PlayerDying ()
{
    // The player is now dead.
    playerDead = true;

    // Set the animator's dead parameter to true also.
    anim.SetBool(hash.deadBool, playerDead);

    // Play the dying sound effect at the player's location.
    AudioSource.PlayClipAtPoint(deathClip, transform.position);
}

function PlayerDead ()
{
    // If the player is in the dying state then reset the dead parameter.
    if(anim.GetCurrentAnimatorStateInfo(0).nameHash == hash.dyingState)
        anim.SetBool(hash.deadBool, false);

    // Disable the movement.
    anim.SetFloat(hash.speedFloat, 0f);
    playerMovement.enabled = false;

    // Reset the player sighting to turn off the alarms.
    lastPlayerSighting.position = lastPlayerSighting.resetPosition;

    // Stop the footsteps playing.
    audio.Stop();
}

function LevelReset ()
{
    // Increment the timer.
    timer += Time.deltaTime;

    //If the timer is greater than or equal to the time before the level resets...
    if(timer >= resetAfterDeathTime)
        // ... reset the level.
        sceneFadeInOut.EndScene();
}

public function TakeDamage (amount : float)
{
    // Decrement the player's health by amount.
    health -= amount;
}

```

Thanks for the help guys, and helping me to learn unity.

# Answer
First off, if you are that new to Unity, maybe you would benefit a lot from going through tutorials. Unity website has some pretty handy tutorials, plus some nice step-by-step complete projects.

Nevertheless I´m going to give you a general answer to guide you with your question. For my answer I assume you are familiar with some basic Unity3D concepts, as you point out, in order to avoid overexplaining every little detail.

I guess the balls you mention have a `Rigidbody` in order to be affected by physics. These `Rigidbody` have a function called `OnCollisionEnter`, that is called when the `Rigidbody` hits another `Rigidbody`/`Collider`. If your players doesn´t have one of those, you will need to add a `Collider` in order to allow it to interact with the balls. `CapsuleCollider` is used usually for players.

Once you have both objects with a `Rigidbody`/`Collider`, you can write the `OnCollisionEnter` function on the ball. Notice that `OnCollisionEnter` takes as a parameter a `Collision`, which has a parameter that is the gameObject the ball has collided with. Then you will need to make sure that it is the player, and then call the `TakeDamage` function.

I hope that helps.
> 3 votes

# Answer
Check out colliders. You'd likely want to implement `OnCollisionEnter` in your character class. When something collides with the player, this method will be activated. Inside this method is where you'll deduct from the player's health.

If the player can only collide with one thing (the sphere objects), you can make it pretty simple:

```
function OnCollisionEnter(collision : Collision) {
    TakeDamage(5);
}

```

Read up on what's required for the `OnCollisionEnter` method to be called, to ensure you have your scene set up correctly (i.e. colliders attached and rigid bodies where needed).
> 2 votes

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


title: Projectile motion based off angle

text:
# Question
Title: Projectile motion based off angle
I was using this code to hit an object that is moving horizontally(from right to left) and player on the left is throwing bullets to hit the object.But, what I am finding difficult is projectile motion based off angle(since the object that is to be hit is moving and I can not just keep throwing projectile at the same angle).

Here is what I was using that does not seem to work since the angle is fixed.

How to modify this code so that the angle is changed and not the velocity

```
IEnumerator project()
    {    yield return new WaitForSeconds(0.25f);
        float target_Distance = Vector3.Distance(mytransform.position, target.position);
        // Calculate the velocity needed to throw the object to the target at specified angle.
        float projectile_Velocity = target_Distance / (Mathf.Sin(2 * firingAngle * Mathf.Deg2Rad) / gravity);

        // Extract the X  Y componenent of the velocity
        float Vx = Mathf.Sqrt(projectile_Velocity) * Mathf.Cos(firingAngle * Mathf.Deg2Rad);
        float Vy = Mathf.Sqrt(projectile_Velocity) * Mathf.Sin(firingAngle * Mathf.Deg2Rad);

        // Calculate flight time.
        float flightDuration = target_Distance / Vx;

        // Rotate projectile to face the target.
        mytransform.rotation = Quaternion.LookRotation(target.position - mytransform.position);

        float elapse_time = 0;

        while (elapse_time < flightDuration)
        {
            mytransform.Translate(0, (Vy - (gravity * elapse_time)) * Time.deltaTime, Vx * Time.deltaTime);

            elapse_time += Time.deltaTime;

            yield return null;
        }

```

# Answer
> 0 votes
Okay, I understood. I needed to initialize the prefab at the time of shooting. So, I found it appropriate to do it in the source script rather than the bulletprefab itself. Here is the code:

Projectile motion In unity 3D

Hope that helps!

---
Tags: c#, projectile-physics
---


# Question
Title: How can I have 2 different images seamlessly tile with each other?
If I Google for "seamless tile" I can find many great answers to create a single image that will seamlessly tile with itself. GIMP even has a filter that will automatically make an image seamless in 1 click, and it works surprisingly well.

But for my game, I would like not only 1 image to tile with itself. But I would like to have different variations of that tile, so the whole texture looks less boring. I want, for example, 10 different grass textures, 10 different dirt textures. Not only should grass01 tile seamlessly with grass01. But grass01 should tile seamlessly with grass02 and dirt08.

One great example of a game that does this is Starcraft. Even the original Starcraft from 1998 has this system where they have multiple grass textures that all seamlessly tile with each other. How do they do that?

# Answer
> 6 votes
Basically, I think what you do is first of all create a tile for each of your terrain types that seamlessly tiles with itself. As you said there are many tutorials available on how to do this.

Once you have those tiles, you can draw variants as well as transitions between different types of terrain by modifying copies of them. The only thing you need to make sure to avoid is changing the borders of the image, since you need those to seamlessly connect to neighbouring tiles.

Of course, when you're drawing transition tiles, you may start with a tile that has half of it filled with each type of terrain and then you need to make it look good. In this process you'll often end up modifying the edges a bit anyway where the terrains meet up. However, transition tiles are quite specific cases so you only need to make sure these sides still connect seamlessly to only a handful of other tiles.

---
Tags: 2d, textures, tiles
---


title: Love2d: Failed to load tileset map

text:
# Question
Title: Love2d: Failed to load tileset map
I'm reading the Love2D Development book, which i think i will stop reading because is outdated and very instable, sometimes i got a lot of troubles. Backing to the question, i made a tileset map with Tiled and saved in .tmx with Base64 ( uncompressed ) then i used Advanced-Tiled-Loader and used the code from the book:

```
-- This is the main.lua file --

local loader = require ("Advanced-Tiled-Loader-master/Loader")

---the path to our .tmx files and sprites

loader.path = "map/"

local map = loader.load("tilemap.tmx")

function love.load()

    love.graphics.setBackgroundColor(255, 153, 0)

    --- load the level and bind the variable map

    loader.path = "map/"

    local map = loader.load("tilemap.tmx")
end

function love.draw()

    map:draw()

end

```

When i tested the game, the result was this:

https://i.stack.imgur.com/bVRpl.png

The result was suposted to be like this:

https://i.stack.imgur.com/0dcUS.png

So what it could be?

# Answer
> 0 votes
```
-- This is the main.lua file --

local loader = require ("AdvTiledLoader/Loader")

---the path to our .tmx files and sprites
local map = nil;

function love.load()

    love.graphics.setBackgroundColor(255, 153, 0)

    --- load the level and bind the variable map

    loader.path = "maps/"

    map = loader.load("test.tmx")
end

function love.draw()

    map:draw()

end

```

So using my copy of ATL, and just making a quick test tiled map, this code worked fine. Using base64. Should look like; https://i.stack.imgur.com/do7XH.png

Result; https://i.stack.imgur.com/iqCPk.png

Map: http://pastebin.com/k05iHYhs & my test sheet; https://i.stack.imgur.com/zDAdv.png

For clarity & any future reference ATL is a bit outdated, doesn't support polygons/polylines that are available in Tiled. It does however support older versions of LOVE. Whereas the atlernative; STI requires LOVE 0.9.1 but does provide updated support (Link)

---
Tags: lua, love2d
---


# Question
Title: How to represent a map in a top-down perspective game with low algorithm complexity?
This is the first time I develop a video-game, and I am kind of lost.

I would like to know about ways on representing 2D maps on a top-down perspective game...

(Like this one: vengadoravg.github.io/1/game.html btw, this is the first game I develop)

So far, I've found one way to represent a 2D map in a top-down perspective game:

Using a matrix. Where a normal floor place is represented by some number (or character), the obstacles are represented by a different number, and the enemies by another different number. This matrix would allow me to run graph theory algorithms and crazy things, but i think it would be, algorithmically, very complex, because the graph would be really populated and dense. Thus, all the sprites should be the same size, otherwise, the matrix would be really, really big.

Are there any other (better) ways?

In terms of algorithm complexity, which of them are the best to run graph theory algorithms?

I apologize if the question sounds subjective... but i think the superiority of an approach can be determined by its algorithmic complexity :)

# Answer
I'll refer to map nodes as tiles for the purpose of explanation, but the principles are the same. If you have more than one node in an area, then your "tile" would contain an array or list of nodes. For all of these, graph theoretic applications can be applied, though the method of application becomes more or less complex depending on what specific algorithm you're using.

Now, if by matrix you mean a two dimensional array, that is probably the least algorithmically complex method, besides a one dimensional array where tile\[x+y\*width\] = tile\[x, y\]. Structured this way you always know the distance of one tile to another, and can always access its neighbors without traversing memory in steps.

Next is a sparse matrix, where the information is structured like so (as a pseudo-structure):

```
Row : {
    PreviousRow,
    NextRow,
    ArrayOfTiles : {
        ColumnIndex,
        TileImage
    }
}

```

Or, as an associative array, such as the .NET Dictionary where the keys encode the XY location and the values are objects containing tile information.

Finally, you can use trees such as Quadtrees for arbitrary tile sizes and/or densities. If your map is totally unordered, then a simple graph where each tile has references to its neighbors will suffice.

Mostly this depends on what your API provides. If you expect to have a lot of empty space then the **associative array** is going to be the most straightforward to use, since it can be made to act like a regular 2d matrix, without allocating space for unused elements, as well as having an insert, delete, and remove complexity of O(1). Otherwise a plain 2d array is fine.

In general, always pick the least complex data structure for your needs.
> 2 votes

---
Tags: 2d, algorithm, maps
---


# Question
Title: How do I get a SphereCollider's global origin in Unity?
I've been following this tutorial: Understanding Steering Behaviors: Collision Avoidance

but I'm having trouble implementing one of the functions correctly in Unity, here's the code:

```
private function lineIntersectsSphere(ahd:Vector3, ahd2:Vector3, sphCol:SphereCollider) : boolean
{
    return distance(sphCol.center, ahd) <= sphCol.radius || distance(sphCol.center, ahd2) <= sphCol.radius;
}

```

The `SphereCollider` variable contains the `Center` variable, however, it always returns a vector containing `0, 0, 0` values. I imagine it's the spheres local origin.. is there a way to get the center? Perhaps it could be through the transform.position that the sphere is attached to?

# Answer
> 1 votes
By default, colliders in Unity will be centered on the object's pivot point (given by `transform.position`). It's possible to configure a collider such that it's *not* centered -- in this case, that offset is given by the sphere's `center` property, which is why you're seeing an offset of zero.

In *mooooost* cases, `transform.position` will be fine. If your sphere is offset from the pivot, though, you'll have to account for that:

```
Vector3 sphereCenter = transform.TransformPoint(sphCol.center);

```

---
Tags: unity, transformation, bounding-spheres
---


# Question
Title: How do I make an XML-specified animation show completely?
I want to add animation to my game board when updating tile positions. I can start an animation at the right point, but there's a catch: When the translate animation starts, it seems like the animation is confined within the tile (button) or is just hidden behind another button. Instead, I want it to look like it is moving.

This is what happens:

This is what I want to happen:

Here's how I start the animations:

```
    Animation tile_up = AnimationUtils.loadAnimation(this, R.anim.tile_up);
    // This was a valid move. Add to moves and enable undo for this
    for(int i = 0; i < 5; i++)
    {
        buttons[x][i].startAnimation(tile_up);
    }

```

Here's the animation spec (in `res/anim/tile_up.xml`):

```
    <?xml version="1.0" encoding="utf-8"?>
    <translate
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:shareInterpolator="true"
        android:fromYDelta="100%p"
        android:toYDelta="0%p"
        android:duration="100"/>

```

How can I fix this?

# Answer
Okay, finally after 6-7 hours of searching through the internet i finally found the answer i was looking for. Since my layout is made up of nested LinearLayouts, I had to add a `android:clipChildren="false"` attribute to all my LinearLayouts(button parents).

Seems like the issue was the linear layouts didn't want to let it's childs outside to play. Which is understandable, and they're great parents none the less. But i had to make them let go. (Joking here)
> 0 votes

---
Tags: android, animation, xml, puzzle
---


title: Detect mouse collision over an object

text:
# Question
Title: Detect mouse collision over an object
Suppose there are 4 areas namely A1,A2,A3,A4 and each object is given a number(1,2,3,4). When I drag and drop the object(1) on A1, it should print a message "where the object is being dropped". (no need of mouse over... any mouse collision concept)

first set i=1 -----\> o1

ie;logic

```
if(mousecollision == "L1" && i=1)
{
  mouseup
  score++;
}
else
{
  score--;
}

```

# Answer
> 2 votes
This a several-step answer and this is just a way of doing things, but certainly not the only one.

1. Both objects and areas must have a collider component attached.
2. Create the proper tags for each set to combine. In this case they're "Green" and "Purple".
3. Create a layer for the areas. In this case it's "DDArea".
4. Use the following script, attached to the D&D objects, as an example to your own. In this case I used spheres.

The train of thought goes as follows:

* Take advantage of the MonoBehaviour functions for handling mouse collision (OnMouseDrag and OnMouseUp) for moving the objects and detecting release, respectively.
* Move the object according to the position of the mouse.
* Cast a ray on release in order to know whether the mouse's position (thus, the object's position) is inside an area.
* If that's the case, then compare the area's and the object's tags (sets), so a decision can be made accordingly; reset the object to its initial position or increase the score.

Finally, here's my example running on Unity web player: https://dl.dropboxusercontent.com/u/4568142/unity/dragdrop/dragdrop.html

**Inspector for the objects representing the areas**

**Inspector for the objects representing the objects (balls/spheres)**

DragDropBall.cs:

```
using UnityEngine;
using System.Collections;
public class DragDropBall : MonoBehaviour
{
    public Camera mainCam;
    int layerMask;
    Vector3 initPosition;

    void Start()
    {
        if (mainCam == null)
            Debug.LogError("No camera attached");
        layerMask = 1 << LayerMask.NameToLayer("DDArea");
        initPosition = gameObject.transform.position;
    }

    void OnMouseDrag()
    {
        Vector3 newPosition = mainCam.ScreenToWorldPoint(Input.mousePosition);
        newPosition.z = transform.position.z;
        transform.position = newPosition;
    }

    void OnMouseUp()
    {
        Vector3 origin = mainCam.ScreenToWorldPoint(Input.mousePosition);
        Ray ray = new Ray(mainCam.ScreenToWorldPoint(Input.mousePosition), Vector3.forward);
        RaycastHit[] hits = Physics.RaycastAll(ray, Mathf.Infinity, layerMask);
        foreach (RaycastHit h in hits)
        {
            string nameSphere = gameObject.name;
            string nameArea = h.collider.gameObject.name;
            string tagSphere = gameObject.tag;
            string tagArea = h.collider.gameObject.tag;
            Debug.Log(nameSphere + " dropped on " + nameArea);
            if (tagSphere.Equals(tagArea))
            {
                Debug.Log("Increment points");
                // further logic for your game here
            }
            else
            {
                // return the object to its inital position
                gameObject.transform.position = initPosition;
            }
        }
    }
}

```

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


# Question
Title: Avoidance Steering Behavior acting inappropriately
I've been trying to implement this steering behavior in Unity: Understanding Steering Behaviors: Collision Avoidance

However, I'm getting strange results. Here's the code for the script, feel free to suggest better ways to code some things..

```
#pragma strict
#pragma downcast

public var test: boolean;

private var stop:boolean;

private var vel: Vector3; //Velocity
private var qa: Vector3;
private var ahead: Vector3; //Ahead vector - A point in front of this unit
private var ahead2: Vector3; // Shorter Ahead Vector - Used for detecting closer objects

private var spwnScript    : EnemySpawner_2; //Reference to script of Spawner
private var otherColliderLst: List.<SphereCollider>; //Should holds reference to variable of other script's (spawner) collider list.
private var otherCollider   : SphereCollider; // Used to store individual colliders from list
private var ownCollider   : SphereCollider;
private var closestCollider  : SphereCollider;
private var spwnObj : GameObject;

//Steering Behavior Variables
private var steering : Vector3; //Variable used to add to the velocity, and to have other behaviors assigned to it.
private var avoidance_frc : Vector3; //Avoidance Force
private var isCollision : boolean;

//CONSTANTS
private var MAX_QUEUE_ahead: float;
private var MAX_AVOID_FRC: float;

private var speed:float = 70;
private var damage:int = 25;

function Awake()
{
    //Destroy(gameObject, 3);
    MAX_AVOID_FRC = 2f;
    MAX_QUEUE_ahead = 30f;
    stop = false;
    steering = Vector3(0f,0f,0f);
    otherCollider = null;
    ownCollider = gameObject.GetComponent("SphereCollider") as SphereCollider;

    spwnObj        = GameObject.Find("EnemySpawn_2").gameObject;
    spwnScript     = spwnObj.GetComponent(EnemySpawner_2);
    otherColliderLst = spwnScript.colliderList;
}

function Start ()
{
    //GameObject.Find("EnemySpawner_2").transform.GetComponent("EnemySpawner_2");

    yield WaitForSeconds(Random.Range(1f, 1.3f));
    stop = true;
}

function Update () {

    if(!stop){
        vel = Vector3(0,0,-speed * Time.deltaTime);
        steering += collisionAvoidance();

        Debug.Log(steering);
        vel += steering;

        transform.Translate(vel);
    }
}

function OnCollisionEnter(col:Collision)
{
    if(col.gameObject.tag == "Player")
    {
        yield WaitForSeconds(.1); //So that bullets seems to have an effect when they touch a part of the ship, instead of an invisible box
        NotificationCenter.DefaultCenter().PostNotification(this, "PlayerHit",damage);
        //playerScript.ReceiveDamage(damage);
        Destroy(gameObject);
    }
}

// Functions used by Steering Behaviors //
/////////////////////////////////////////

private function collisionAvoidance() : Vector3 {

    qa = vel.normalized * MAX_QUEUE_ahead;
    ahead = qa + transform.position;
    ahead2 = qa * 0.5f + transform.position;

    otherCollider = findNextClosestSphere() ;

    avoidance_frc = Vector3(0f,0f,0f);

    if(otherCollider != null) {
        avoidance_frc.x = ahead.x - otherCollider.transform.position.x;
        avoidance_frc.y = ahead.y - otherCollider.transform.position.y;
        avoidance_frc.z = ahead.z - otherCollider.transform.position.z;

        Debug.Log("AVOID"+avoidance_frc);
        avoidance_frc.Normalize();
        avoidance_frc.Scale(Vector3(MAX_AVOID_FRC, MAX_AVOID_FRC, MAX_AVOID_FRC));
    }
    else{
        avoidance_frc.Scale(Vector3(0f, 0f, 0f)); // nullifty the avoidance force
    }
    return avoidance_frc;
}

private function findNextClosestSphere() : SphereCollider {

    closestCollider = null;

    for(var i:int = 0; i < otherColliderLst.Count; i++)
    {
        if(otherColliderLst[i].transform.position != ownCollider.transform.position)
        {
            otherCollider = otherColliderLst[i];
            isCollision = lineIntersectsSphere(ahead, ahead2, otherCollider);

            if(isCollision && (closestCollider == null || distance(gameObject.transform.position, otherCollider.transform.position) < distance(gameObject.transform.position, closestCollider.transform.position))) {
                closestCollider = otherCollider;
            }
        }
    }

    //Set Sphere Collider

    //For readability purposes, the function returns back a vector.
    //An alternative, would be for the function to simply set the value of the otherCollider variable
    //and not return anything.
    //The variable sits outside any function, and can be used anywhere in the script.

    return closestCollider;
}

private function distance(a:Vector3, b:Vector3){
    return Mathf.Sqrt((a.x - b.x) * (a.x - b.x) + (a.y - b.y)*(a.y - b.y) + (a.z - b.z) * (a.z - b.z));
}

private function lineIntersectsSphere(ahd:Vector3, ahd2:Vector3, sphCol:SphereCollider) : boolean
{
    return distance(sphCol.transform.position, ahd) <= sphCol.radius || distance(sphCol.transform.position, ahd2) <= sphCol.radius;
}

```

I have another script titled EnemySpawner\_2, which is attached to a gameobject in the scene, and is responsible for spawning and saving spheres to a list, which can be accessed by the above script with the `otherColliderLst` variable.

Now the issue is that the enemies that spawn, do NOT actually do any collision avoidance at all. Rather, they spawn one by one, from the same area, and they rush in the same direction (on one axis) towards the nearest enemy that is detected. I'm trying to understand why this behavior is happening. I realized that part of the problem is that not all axes have values in the `avoidance_frc` variable at the end `collisionAvoidance()` so the force is only applied to one axis, when it should be done in two, which is the z AND the x axis (The axis that currently contains no value).

But I don't understand how the code does not run into these issues in the other tutorial. I've basically done a Unity copy of the code and have been debugging for this for hours.. what have I done wrong?

# Answer
> 0 votes
How do you assign the enemy "Find Target" behavior? Maybe I missed it, haven't had my coffee yet, but I only see the collision avoidance behavior added. Steering behaviors relies on forces and take advantage of the properties of vector operations. If you, for example, give a (1,0,0) steering force towards a target ad a (0,0.5,0) force to avoid an obstacle, the entity will have a total velocity of (-, 0.5, 0).

On the other hand, if you assign the velocity elsewhere to make the entity walk towards a target, make sure it doesn't override the steering forces.

Also, have you tried to Gizmo.DrawLine on the steering forces to check that the avoidance force isn't just too weak? You should weight and truncate the forces for a proper behavior.

---
Tags: unity, steering-behaviors, collision-avoidance
---


title: Gradually reduce speed

text:
# Question
Title: Gradually reduce speed
Basically I am working on following application of android version Party Games: Drinking Wheel

For this I want to rotate wheel and want to stop wheel at specific point. But I want this with gradually decreasing speed. For example at start I have speed of 10 then at stop time it at 0. So wheel stop smoothly.

At presently I have working code but it stop suddenly.

```
registerEntityModifier(new RotationModifier(desireTime, 359f,
            desireRotation, new IEntityModifierListener() {

                @Override
                public void onModifierStarted(IModifier<IEntity> pModifier,
                        IEntity pItem) {
                }

                @Override
                public void onModifierFinished(
                        IModifier<IEntity> pModifier, IEntity pItem) {

                    mPointer.stopRotation();
                    showWindowAfterSomeTime(randomSegment);
                }
            }, EaseLinear.getInstance()));

```

I want some help in this. Thanks for your time.

# Answer
> 1 votes
Instead of mPointer.stopRotation() you need to gradually apply negative acceleration (torque) to get to your desired point.

So, you have currentPoint, targetPoint and currentSpeed (I will measure all of them in grades as I guess that's also how you do it - for currentSpeed grades/second).

The distance in grades that the wheel must travel from currentPoint to targetPoint is

```
distance = targetPoint - currentPoint + r * 360f

```

Notice that if you don't want the wheel to do any spins before it reaches targetPoint, then r = 0;

And the deceleration needed in order to stop it at targetPoint is

```
deceleration = -( currentSpeed * currentVelocity / distance ) / 2.f

```

or

```
deceleration = -( currentSpeed * currentVelocity  /
                ( targetPoint - currentPoint + r * 360f ) ) / 2.f

```

and the time along which the wheel stops is

```
time = currentSpeed / ( -deceleration )

```

If you don't want the wheel to do a complete spin, then r = 0 and that's all you need to know, just apply the deceleration and it will stop until reaching the point, but at a high currentSpeed it will stop really fast. So, you might want to have a non-null r. Even if you choose to have r = 0, read further below to the Update part.

In order to choose a good r, we need to consider which range should `time` fall into. I think a good pick is the biggest value lower than 10. So now, we do the following:

```
float_type time = 0;
float_type r = -1;

LOOP ( as long as time < 10  )
{
    r = r + 1;
    deceleration = -( currentSpeed * currentVelocity  /
                    ( targetPoint - currentPoint + r * 360f ) ) / 2.f
    time = currentSpeed / ( -deceleration );
}

// at very low speeds it will take more than 10 seconds to get to
// targetPoint so r = 0, but we have to wait more than 10 seconds
if ( r > 0 )
    r = r - 1;
deceleration = -( currentSpeed * currentVelocity  /
                ( targetPoint - currentPoint + r * 360f ) ) / 2.f
time = currentSpeed / ( -deceleration );

```

Now when updating the wheel, make sure you do it like that:

```
// suppose after last update call diff seconds have passed
float_type t = currentSpeed / ( -deceleration );
if ( t < diff ) // in this timestep we reach our target and stop right on it
{
    currentPos = currentPos + t * currentSpeed / 2;
    currentSpeed = 0;
}
else
{
    currentSpeed = currentSpeed + deceleration * diff; // deceleration is negative and (+) * (-) = (-)
    currentPos = currentPos + ( currentSpeed + currentSpeed - deceleration * diff ) * diff / 2.f;
}

```

Sorry for not posting in your coding language, but I hope you can understand it.

---
Tags: android, rotation, movement, andengine
---


# Question
Title: Timing in fighting game using animations time?
I am developing a 2D fighting game in C++. I have made the basic components such as moving, guarding and even a combo system that works perfectly well.

My main concern now is that I want the game to be as balanced as possible, and thus I am entering a testing phase. I am even requesting the help of my father to play against as no AI has been implemented (yet).

In the game you can chain attacks using a punch/kick (PK) button. But you can also charge the attack by pressing the PK button longer, which basically pauses the animation, resuming it when the attack is fully charged or the player releases the button. One thing that I have noticed is that if your opponent is simply pressing the PK button when being hit, it can counter attack pretty easily if you end up charging your attack. This behaviour basically makes charging useless, because it can never go through if your opponent knows that.

So my point is that I need to add a delay so that the counter cannot occur (I do not want it to, because the game is based on an actual PS2 game where you cannot counter that way - for the record, there is a way to escape, either by pressing the guard button, or by hitting a button at the right timing to teleport behind and counter).

To add this delay, I can either modify the actual duration of the "damage" animation so that it does what I want or I can internally add a timer where the character enters a state where he cannot do anything.

I would want to go for the first one, since that way you SEE that you cannot counter using a punch since you are still in the damage animation. But the thing is that each character has its own set of animations and thus in theory, the developer or the designer (which is me in both cases) can modify the duration of one character while the others still have an old value.

My question is thus more on the design level. Is it a good idea to let the timing be decided via animation duration? Is it what is actually done ? If I have fifty characters when I discover another timing issue, it would mean to modify the animation of each and every one of them... But adding a timer internally seems more like a patch that actual fine tuning...

# Answer
> 1 votes
Personally I am not a fan of tying up animations and states or events. I rather keep both of them separate and, if anything, sending events between them (think MVC).

You say that a timer seems like a hack, but actually I think the opposite is true. Doesn't stretching your animation length just to prevent your character from performing a counter seems even more hackish?

Since you give no details about your implementation, I will suggest some general tips. First, I guess your characters have some kind of state machine to control their behavior/animation. If this is not the case, you should give it a try. Then, the character would transit through the following states:

`IDLE --(gets hit)--> HIT [play hit animation] --(after delay)--> HELPLESS --(after delay)--> IDLE`

I think this implementation has several advantages, such as more faithfully represent the character state, being more flexible, and decoupling state from animation.

If you are concerned that much about players getting a visual clue of the HELPLESS state, you can add some kind of animation such as blinking, so that it becomes more explicit.

---
Tags: game-design, animation, balance, timing, fighting-game
---


# Question
Title: Orthographic Camera and Raycasting in Three.js
I'm working on a test project porting a simple game from iOS to Javascript. I've got the orthographic camera working and it can view the objects in the scene and move up and down the tower of meshes in the scene. Now I am trying to select the meshes with raycasting and I'm having trouble getting any of the objects to register. I have done a lot of research, spent some time in the debugger, and tried configuring things a number of different ways without success. I have checked my code numerous times and I think I am doing everything correctly as per the Three.js examples I can find, but maybe I am missing something obvious.

First I set up the global variables:

```
var container;
var camera;
var scene;
var renderer;
var projector;

var mouseX = 0;
var mouseY = 0;

//implemented a fixed game size here
var windowWidth = 800;
var windowHeight = 600;
var windowHalfX = windowWidth / 2;
var windowHalfY = windowHeight / 2;

var intersects = [];
var entities = [];

//this is the game model object
var worldSize = new WorldSize(windowHalfX, windowHalfY);
var tower = new Tower(worldSize);

```

Then I initialize the camera, renderer and projector:

```
var zoom = 1.0;
camera =  new THREE.OrthographicCamera(windowWidth * zoom / -2, windowWidth * zoom / 2, windowHeight * zoom / 2, windowHeight * zoom / -2, 0, 1000);
//z value of position can be zero or positive but negative does not work
camera.position = new THREE.Vector3(0,0,0);
camera.lookAt(new THREE.Vector3(0,0,0));
camera.updateProjectionMatrix();

projector = new THREE.Projector();

renderer = new THREE.WebGLRenderer({clearColor: 0xff0000, clearAlpha: 1});
renderer.setClearColor(0xC0C0C0, 1);     //this is light grey
renderer.setSize(windowWidth, windowHeight);
container.appendChild(renderer.domElement);

```

Then I iterate through my game model and add the objects to the scene:

```
var floorShape = THREE.SceneUtils.createMultiMaterialObject(
    new THREE.BoxGeometry(500, tower.towerFloors[obj].floorSize * 10, 1),
    multiMaterial);

//negative values work for the Z for this, 0 looks strange, positive not in view
floorShape.position.set(0, tower.towerFloors[obj].yposition * 10, -20);

scene.add(floorShape);
entities.push(floorShape);

```

And finally on a mouse click I call this function:

```
function onDocumentMouseDown(event) {
    event.preventDefault();

    var vectorx = (event.clientX / windowWidth) * 2 - 1;
    var vectory = -(event.clintY / windowHeight) * 2 + 1;
    var vectorz = camera.position.z;
    var vector = new THREE.Vector3(vectorx, vectory, vectorz);

    //quick hack to make sure the x is not the problem
    vector.x = camera.position.x;

    projector.unprojectVector(vector, camera);

    var raycaster = new THREE.Raycaster(camera.position, vector.sub(camera.position), 0, -100);
    // use picking ray since it's an orthographic camera
    raycaster = projector.pickingRay(vector, camera);

    intersects = raycaster.intersectObjects(entities);

    alert(vector.x + ' , ' + vector.y + ',' + vector.z);

    if ( intersects.length > 0 ) {
        console.log( intersects[ 0 ] );
        alert('did it');
    }
}

```

When I click the screen, the value that shows up in the alert is `(0, theCorrectValueForY, 0)`. When I check the objects in the `scene.children` or in the entities array, they are at the proper xyz positions.

When debugging I noticed that when I first call `var raycaster = ...`, the near is set to `0` and the far is set to `-100` like I told it to be. But after the call to `raycaster = projector.pickingRay`, the far value is set to null value. I've tried all different values for the near and far for the raycaster, and none of them have worked. The origin of the ray is correctly at the clicked position, and the direction it is moving is always `(0, 0, -1)` after `raycaster = projector.pickingRay`.

I can think of a couple possible problems, such as possibly I am somehow not moving the actual mesh of the objects to match their positions? Or maybe I am sending the ray in the wrong direction? But I cannot figure it out. I don't know if I am doing something wrong, or if some combination of correct values for the camera position, object positions, and raycasting values would work as expected. I would very much appreciate any help!

Edit: Here is the complete code in case anyone wants to try it. index.html

```
<!DOCTYPE html>
<html>
<head lang="en">
    <style>

        body {
        background-color: #ffffff;
        margin: 50px;
        overflow: hidden;
        font-family:Monospace;
        font-size:13px;
        text-align:center;
        font-weight: bold;
        text-align:center;
    }

    div{
        background: #ffffff;
    }
    </style>

    <meta charset="UTF-8">
    <title></title>
</head>

<body>
<script src="js/jquery.min.js"></script>
<script src="js/three.min.js"></script>
<script src = "js/three2dtest.js"></script>
</body>
</html>

```

three2dtest.js

```
var container;
var camera;
var scene;
var renderer;
var projector;

var mouseX = 0;
var mouseY = 0;

//implemented a fixed game size here
var windowWidth = 800;
var windowHeight = 600;
var windowHalfX = windowWidth / 2;
var windowHalfY = windowHeight / 2;

var particleMaterial;
var intersects = [];
var entities = [];

//this is the game model object
var worldSize = new WorldSize(windowHalfX, windowHalfY);
var tower = new Tower(worldSize);

init();

function init() {
    container = document.createElement( 'div' );
    document.body.appendChild( container );

    //test text on screen
    var info = document.createElement('div');
    info.style.position = 'absolute';
    info.style.top = '2px';
    info.style.width = '100%';
    info.style.textAlign = 'center';
    info.innerHTML = '<p>clickable tower floors</p>';
    container.appendChild(info);

    var zoom = 1.0;
    camera =  new THREE.OrthographicCamera(windowWidth * zoom / -2, windowWidth * zoom / 2, windowHeight * zoom / 2, windowHeight * zoom / -2, 0, 1000);
    //z value of position can be zero or positive but negative does not work
    camera.position = new THREE.Vector3(0,0,0);
    camera.lookAt(new THREE.Vector3(0,0,0));
    camera.updateProjectionMatrix();

    scene = new THREE.Scene();
    //scene.fog = new THREE.FogExp2( 0x000000, 0.0025 );
    console.log(scene);

    projector = new THREE.Projector();

    //particle material
    var PI2 = Math.PI * 2;
    particleMaterial = new THREE.SpriteCanvasMaterial( {
        color:0x000000,
        program: function(context) {
            context.beginPath();
            context.arc(0,0,0.5,0,PI2,true);
            context.fill();
        }
    });

    for (obj in tower.towerFloors) {
        console.log(tower.towerFloors[obj].yposition);

        // Using wireframe materials to illustrate shape details.
        var darkMaterial = new THREE.MeshBasicMaterial({color: 0xffffcc});
        var lightMaterial = new THREE.MeshBasicMaterial({color: 0xffffff});
        var wireframeMaterial = new THREE.MeshBasicMaterial({color: 0x000000, wireframe: true, transparent: true});

        var localFloor = tower.towerFloors[obj];
        if (localFloor.hasBeenClicked === true) {
            var multiMaterial = [lightMaterial, wireframeMaterial];
        } else {
            var multiMaterial = [darkMaterial, wireframeMaterial];
        }

        // create a cube for each of the floors on the tower
        var floorShape = THREE.SceneUtils.createMultiMaterialObject(
        new THREE.BoxGeometry(500, tower.towerFloors[obj].floorSize * 10, 1),
    multiMaterial);

        //negative values work for the Z for this, 0 looks strange, positive not in view
        floorShape.position.set(0, tower.towerFloors[obj].yposition * 10, -20);
        scene.add(floorShape);

        entities.push(floorShape);
    }

    renderer = new THREE.WebGLRenderer({clearColor: 0xff0000, clearAlpha: 1});
    //renderer = new THREE.CanvasRenderer();
    renderer.setClearColor(0xC0C0C0, 1);     //this is light grey
    renderer.setSize(windowWidth, windowHeight);
    container.appendChild(renderer.domElement);

    document.addEventListener( 'mousemove', onDocumentMouseMove, false );
    window.addEventListener( 'resize', onWindowResize, false );

    document.addEventListener('mousedown', onDocumentMouseDown, false);

    //should be better to start animate inside here rather than outside
    animate();
}

//new function from documentation but not the raycasting is not working
function onDocumentMouseDown(event) {
    event.preventDefault();

    var vectorx = (event.clientX / windowWidth) * 2 - 1;
    var vectory = (event.clintY / windowHeight) * 2 + 1;
    var vectorz = camera.position.z;
    var vector = new THREE.Vector3(vectorx, vectory, vectorz);

    //quick hack to make sure the x is not the problem
    vector.x = camera.position.x;

    projector.unprojectVector(vector, camera);

    var raycaster = new THREE.Raycaster(camera.position, vector.sub(camera.position).normalize(), 0, -10000);
    // use picking ray since it's an orthographic camera
    raycaster = projector.pickingRay(vector, camera);

    intersects = raycaster.intersectObjects(entities);

   alert(vector.x + ' , ' + vector.y + ',' + vector.z);

    if ( intersects.length > 0 ) {

        console.log( intersects[ 0 ] );
        alert('did it');
    }
}

function onDocumentMouseMove( event ) {
    mouseX = event.clientX - windowHalfX;
    mouseY = event.clientY - windowHalfY;
}
function onWindowResize() {
    windowHalfX = windowWidth/ 2;
    windowHalfY = windowHeight / 2;

    camera.aspect = windowWidth / windowHeight;
    camera.updateProjectionMatrix();

    renderer.setSize(windowWidth, windowHeight);
}

function animate() {
    requestAnimationFrame( animate );
    render();
}

function render() {
    //move only up and down
    //camera.position.x += ( mouseX - camera.position.x ) * 0.05;
   camera.position.y += ( - mouseY - camera.position.y / 10 ) * 0.15;

    //the camera wont move above the top floor so no bounds check needed
    if (camera.position.y < 0) {
        camera.position.y = 0;
    }

    camera.updateProjectionMatrix();

    renderer.render(scene, camera);
}

///////////////////////////////////////////////
/*           Tower Objects                   */
///////////////////////////////////////////////
function Tower (worldSize) {
    this.towerFloors = {};

    var floorNumber = 0;
    for (floorNumber = 0; floorNumber < 50; floorNumber++) {

        var floor = new Floor(floorNumber, worldSize);

        this.towerFloors[floorNumber] = floor;
    }

    for (obj in this.towerFloors) {
       //var thing = this.towerFloors[obj];
        console.log(this.towerFloors[obj].floorNumber);
    }
}
function Floor (floorNumber, worldSize) {
    this.floorNumber = floorNumber;
    this.floorSize = worldSize.ysize / 50;
    this.yposition = this.floorSize * floorNumber;
    this.hasBeenClicked = false;
}
function WorldSize (xsize, ysize) {
    this.xsize = xsize;
    this.ysize = ysize;
}

```

# Answer
Not sure what's going on here. The whole point of `vector` is to convert the mouse location into a 3d point in front of the camera. Setting Z to `camera.position.z` when the frame of reference is currently focused on the camera (camera is 0,0,0) and then unprojecting that value into world space in particular makes no sense.

```
var vectorx = (event.clientX / windowWidth) * 2 - 1;
var vectory = (event.clientY / windowHeight) * 2 + 1;
var vectorz = camera.position.z;
var vector = new THREE.Vector3(vectorx, vectory, vectorz);

```

Try the code below. It simply creates point in front of the camera based on the click coordinates, unprojects that point so that it is in the appropriate position in the world space, and then creates a ray from those two points.

```
var vector = new THREE.Vector3(event.clientX, event.clientY, 1);
projector.unprojectVector(vector, camera);
raycaster.set(camera.position, vector.sub(camera.position).normalize());

```
> 1 votes

---
Tags: camera, vector, webgl, raycasting, three.js
---


title: How to simulate random scope movement?

text:
# Question
Title: How to simulate random scope movement?
I want to simulate that random and soft movement that lot of games got (like BF3) when you use the scope of a sniper gun, so the question is how to achieve that.

# Answer
> 1 votes
You could randomly take a new looking direction or a point to look at for the camera, then just lerp or smooth damp towards it. Here is a simple example made with Unity that might get you started, feel free to modify it. You might also want to add player's camera movement to that so the player can actually control aiming.

```
private float t;
private Vector2 randomPoint;
private Vector3 lookAtPoint;
private Vector3 lookFromPoint;
private const float RADIUS = 0.1f;
private const float MOVEMENT_TIME = 1.0f;

void Start () {
    t = MOVEMENT_TIME;
    lookFromPoint = transform.forward;
}

void Update () {
    if (t >= MOVEMENT_TIME) {
        randomPoint = Random.insideUnitCircle * RADIUS;
        lookFromPoint = lookAtPoint;
        lookAtPoint = new Vector3(transform.forward.x + randomPoint.x, transform.forward.y + randomPoint.y, transform.forward.z);
        t = 0.0f;
    }
    else {
        t += Time.deltaTime;
        transform.LookAt(Vector3.Slerp(lookFromPoint, lookAtPoint, t));
    }
}

```

---
Tags: movement, random
---


# Question
Title: How to rotate a sprite on circle in android using Libgdx
Dear Fellow Game Developers
i am newbie to Android Game Development,i like to know how we can develop a sprite rotate in circle on android,with help of libgdx, i do have a image in assets folder,cant load it in emulator,following code is using to load image in texture

> texture = new Texture(Gdx.files.internal("1325603701\_wordpress.png"));

# Answer
> 4 votes
Create your sprite as following

```
Texture glowBlock = new Texture(Gdx.files.internal("data/glow-block.png"));
Sprite  glowSprite = new com.badlogic.gdx.graphics.g2d.Sprite(glowBlock);

```

Then in your render method do this

```
@Override
public void render () {
    Gdx.graphics.getGL10().glClear(GL10.GL_COLOR_BUFFER_BIT);
    spriteBatch.begin();
    spriteBatch.setColor(Color.WHITE);
    glowSprite.rotate((float) 45.0);
    glowSprite.draw(spriteBatch, 100);
    spriteBatch.end();
}

```

That should give you sprite rotated for 45 degrees

# Answer
> 1 votes
Here is the simple way how can you rotate a sprite in libGDX. First you need to set the origin:

```
sprite.setOrigin(sprite.getWidth/2,sprite.getHeight/2);

```

Then you can rotate clockwise and anticlockwise according to your need:

```
sprite.rotate(2f); or sprite.rotate(-2f);

```

# Answer
> 1 votes
If by rotating in a circle you mean WALKING on top of the circumference of a circle, then I guess any of the answers correctly answered your question. So here is my add:

You can continue loading you texture with

```
texture = new Texture(Gdx.files.internal("1325603701_wordpress.png"));

```

but it is extremely recommended that you use the AssetManager. About it not loading in the emulator, check if your texture size is power of two. (Like 64x64)

Then create your sprite:

```
sprite = new Sprite(texture);

```

you'll possibly want to pass more arguments to cut the sprite, in case you're using a power of two texture for a non power of two sprite.

Create a helper variable on the class body, to keep track of the time, and one to say where will be the sprite center:

```
private float elapsedTime = 0.0f;
private Vector2 center = new Vector2(10, 10);

```

on render:

```
public void render () {
    final float speed = 30.0f; // in degrees per second
    final float radius = 10.0f; // the radius of the circle you'll be rotating
    float angle = elapsedTime * speed;
    Gdx.graphics.getGL10().glClear(GL10.GL_COLOR_BUFFER_BIT);
    spriteBatch.setProjectionMatrix(camera.combined);
    spriteBatch.begin();
    sprite.setRotation(angle - 90);
    sprite.setPosition(center.x + radius * (float)Math.cos(angle * MathUtils.degrad), center.y + radius * (float)Math.sin(angle * MathUtils.degrad));
    sprite.draw(spriteBatch);
    spriteBatch.end();
}

```

This should work just fine.

# Answer
> -1 votes
Do it like this 1. Load your image into AssestLoader class and store it in sprite

```
sprite=new Sprite(AssestLoader.1325603701_wordpress);

```

2.Then set its size , position and color like this

```
sprite.setColor(1, 1, 1, 1);
sprite.setSize(sprite.getWidth(),sprite.getHeight());
sprite.setPosition((w / 2) - (sprite.getWidth() / 2), (h / 2)
                - (sprite.getHeight() / 2));

```

3- In your render method use the below code

```
batch.begin();
sprite.draw(batch);
batch.end();

```

4.Call the rotate method where u want to rotate

```
batch.begin();
this.rotate(deltatime);
deltatime=deltatime+0.5f;
batch.end();

```

and

```
public void rotate(float angle)
{
    sprite.setRotation(angle);

}

```

where deltatime is float value=1

Hope this Helps You.

---
Tags: android, textures, libgdx
---


# Question
Title: Loading source controlled MonoDevelop project leaves out some folders
I have recently started using version control in MonoDevelop and have discovered that if I include a folder containing for example Scenes that they will be included when I push changes to master.

My structure is:

Scripts

--\> Armour.cs

--\> Inventory.cs

Scenes

--\> Scene01.unity

However when I reopen the unity project and look at the code solution only the Script directory and the files within it appear and the Scenes folder is absent.

Strangely enough Scene01.unity is still getting picked up if I make a change and go to commit changes.

This is what I want my project to look like

Does anyone know why this is happens and if there is any way to resolve this?

NOTE: As a basic work around I can manually include the file when it disappears however when I have a large amount of assets this could become a painful task. Also if I load the project using MonoDevelop it loads fine, but opening from Unity itself seems to overwrite the solution files.

# Answer
> 2 votes
As far as I can tell, there is no problem with your tools.

Git is saving the changes and your repository is working as expected, according to what you're saying. On the other hand, MonoDevelop is a tool for code editing, and the Unity editor is the tool for managing assets and the whole project.

This is an example project and, as you can see, in both MonoDevelop and Visual Studio, the solution loads the scripts only; because that's the idea.

**Unity Project window**

**MonoDevelop Solution panel**

**Visual Studio Solution panel**

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


# Question
Title: How to stop a object with progress bar so it can start instantly in unity
I have created a gameobject(cube) and written code to move,mean while the processbar get loading.when the processbar is loaded fully then the object should stop moving.Can anybody please help me coding out.

code used for doing progress bar

```
var progress : float = 100;
var pos : Vector2 = new Vector2(20,40);
var size : Vector2 = new Vector2(60,20);
var progressBarEmpty : Texture2D;
var progressBarFull : Texture2D;

function OnGUI()
{
    GUI.DrawTexture(Rect(pos.x, pos.y, size.x, size.y), progressBarEmpty);
    GUI.DrawTexture(Rect(pos.x, pos.y, size.x * Mathf.Clamp01(progress), size.y), progressBarFull);
}

function Update()
{
    progress = Time.time * 0.05;
}

function OnMouseEnter()
{
    progressBarFull=progressBarEmpty ;
}

```

Suppose If I place a button,when I click the button the bar should get loading.For that I have written the code

progress = Time.time * 0.05;

to if(button)

but the progress bar is not getting loaded.What will be the problem

code changed is

```
#pragma strict

var progress : float = 100;
var pos : Vector2 = new Vector2(20,40);
var size : Vector2 = new Vector2(60,20);
var progressBarEmpty : Texture2D;
var progressBarFull : Texture2D;

function OnGUI()
{
GUI.DrawTexture(Rect(pos.x, pos.y, size.x, size.y), progressBarEmpty);
GUI.DrawTexture(Rect(pos.x, pos.y, size.x * Mathf.Clamp01(progress), size.y), progressBarFull);
if(GUI.Button(new Rect(300,300,60,30),"Start "))
{
progress = Time.time * 0.05;
}
}

    function OnMouseEnter()
    {
      progressBarEmpty=progressBarFull ;
    }

This code is working like,the progress bar is getting incremented on each click of the button.I need to display it at a single click.What will be the solution,can anybody help me out

```

# Answer
Well I'd like to comment on the question but I don't have 50 rep. Anyways: If we knew why you were doing this (*specifically*) then we might be able to help.

To know when to stop moving the object, you'll need a *condition* as such:

```
int maxProgress = 100; //the value at which the progress is full
if (progress > maxProgress) //if it is full
{
     var cube = GameObject.Find("cube"); //find the cube on the scene (or whatever you have named it in the heirarchy
     cube.transform.velocity = Vector3.zero; // set the velocity to 0
}

```

I hope this basic code can get you started using conditions in your code to check for happenings in your game.

(PS. If you want the cube's position to match the bar position, I'll leave that to you to figure out. Hint: it involves math, using the following pieces of information: the bars position and size, and the progress and maxProgress. Think percentages, and set the cube's position with your result.)
> 2 votes

# Answer
There are several possibilities.

If your cube is user-controlled, it probably has something along the line of

```
if(input.getKeyDown(...))
{
    //move
}

```

written either in your Update or your FixedUpdate.

Simply test the progress and the userinput like this:

```
if(!ProgressBar.isFull() && input.getKeyDown(...))
{
    //move
}

```

This also works with a little bit of work for automated movement.

You can also deactivate the Movementscript from the ProgressBar-Script or any other script monitoring the ProgressBar-Script.

---

**Bonus Code Review:**
I seriously have no real idea what your doing in your OnMouseEnter().
It looks like you set your "BarFull"-Texture to the "BarEmpty"-Texture, which would result in the progressBar never again filling up visually, simply because the "BarFull"-Texture is gone. I can only assume that this is not what you want.

You will also have some kind of flickereffect at the beginning, because your progress is 100 at the beginning, but gets set to 0 (or maybe 0.05) in the first update. Depending of the execution order of Update() and OnGUI(), this can cause problems.

You use Clamp01() in OnGUI() to keep the value from getting to big, but your progress will get too big. If you pull the Clamp01() in the Update()-Function, it is better visable what you expect from the variable, allowing better understanding (also from **your** side) in the future.

You also have a definite time your ProgressBar will need to fill up, which is 20 Seconds. This can be of course the intended effect, but I would think a ProgressBar measures the progress of something like Fileloading, Items gathered or such. Maybe consider renaming it to TimeBar.
> 0 votes

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


# Question
Title: Cancel a SpriteBatch I've started drawing
**Background:**

I'm working on a control library for XNA to use in a couple game clients I've written. The way I've implemented Dialogs is to have them derive from the base `XNAControl` class.

`XNAControl` objects follow the Game Component model and are all derived from `DrawableGameComponent`. They are added to the Game.Components list as soon as the base class `XNAControl` constructor is called.

**Problem:**

Dialogs are popped up in game by instantiating an `XNADialog` object, unlike `MessageBox.Show()` which uses a static method. The constructor of XNADialog, in turn, instantiates a couple controls that are 'children' of the parent dialog control. Children are tracked by the dialog, and removed from the `Game.Components` list automatically when the Dialog is closed.

The problem with the model that I've created is that the child controls are added to the Game's components when they're constructed, so they start updating and drawing and thus show on the screen before the dialog is fully constructed. The case I'm trying to debug is where the labels for a dialog box will appear in the top left, and then move to the center of the screen a split second later once the Dialog is constructed.

**What I've tried:**

* Separate constructor for base class XNAControl that **doesn't** add the control to the components when it's constructed. Instead, it relies on the child control (in this case dialog) to add itself to the `Game.Components` collection. This is what I have in place so far and it isn't working, which makes sense, because the labels are being added to the components collection prematurely anyway.
* `Initialized` property of XNAControl. This property is set in the `XNAControl.Initialize()` method, and the base class `XNAControl.Update` and `XNAControl.Draw` return automatically if it is false. However, this isn't working either (also in place) because child controls have to call the base methods of update and draw before after they do their own drawing logic because otherwise some things would be drawn in the wrong order. I also don't want to have to check the `Initialized` property in every single child class I make because there are a lot of them and I'm looking for something more elegant
* Moving the addition of the control to the components collection to the `Initialize` method. This didn't work because the control's initialize method didn't get called automatically because the control wasn't in the components collection yet.

**Question:**

What is the best way to keep the child controls from being updated and drawn prior to their parent control's construction? My only other ideas are:

* Using a theading sync object, but this seems like overkill/unnecessary (or maybe it's exactly what I need?). I can't think of an elegant way to do it.
* Finding a way to cancel any drawing that's been done by the SpriteBatch in the child classes, in `XNAControl.Draw`. I don't think this is possible though, and I can't find anything searching.

# Answer
So, first of all, for anyone coming here from search reading your title, I'll answer how to "**Cancel a SpriteBatch I've started drawing**":

Basically: You can't. A `SpriteBatch` acts like a list of sprites, and that gets send out to the GPU when you call `End` (or immediately with `SpriteSortMode.Immediate`). But, unlike a `List`, there's no `Clear` method or similar to erase that list without sending its contents to the GPU.

So, one terrible option is to `Dispose` of your `SpriteBatch` and then recreate it. This is pretty horrible, structurally. It's also going to perform terribly.

A more correct alternative would be to re-implement your own version of `SpriteBatch`, or simply create a wrapper around it that does what you need. Keep in mind that there's nothing "special" about `SpriteBatch` \- it's built on top of other parts of XNA and it's possible (although non-trivial) to create your own version.

---

But, really your question is "**How do I sort out my wacky use of `DrawableGameComponent`?**"

And the answer is: "**Don't do that!**"

When you get to the point where you're trying to do crazy things like "cancel" a sprite batch, or looking into threading synchronization mechanisms (note: they're not applicable here), consider, perhaps, that you've taken the wrong approach in the first place.

Again, much like `SpriteBatch`, the `GameComponent` system in XNA is entirely optional. XNA is designed so you can replace it with your own system. And, unlike with `SpriteBatch`, making your own replacement for the component system is trivial (as it basically boils down to a list of objects with `Update` and `Draw` methods).

In my experience, it's almost always the case that you'll want something slightly different to what XNA's component system does. And, in *your* case in particular, you want something *very* different - possibly a tree structure (instead of a list), where each parent control is directly responsible for drawing its children.

**OR:** Keep doing what you're doing and see if the `Enabled` and `Visible` properties on `DrawableGameComponent` do what you need (it's still not great, but this might be a quick band-aid solution to your problem).
> 2 votes

---
Tags: xna, c#, spritebatch
---